Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion packages/auth/src/Auth.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Concrete, Hash, appKey, env, getModel } from '@arkstack/common'
import { JWTPayload, SignJWT, jwtVerify } from 'jose'
import { randomUUID } from 'node:crypto'

import { AuthContract } from './Contracts/AuthContract'
import { AuthenticationException } from './Exceptions/AuthenticationException'
Expand Down Expand Up @@ -371,14 +372,18 @@ export class Auth extends AuthContract {
}

/**
* Create a JWT token
* Create a JWT token. Each carries a random `jti`: without it, two tokens for
* the same user issued within the same second (`iat` has one-second precision)
* are identical, and the second collides with the first on the unique
* `personal_access_tokens.token` column.
*
* @param payload
* @returns
*/
private async createJWT(payload: JWTPayload, expiresIn: string = env('JWT_EXPIRES_IN', '1h')): Promise<string> {
const jwt = await new SignJWT(payload)
.setProtectedHeader({ alg: 'HS256' })
.setJti(randomUUID())
.setIssuedAt()
.setExpirationTime(expiresIn)
.sign(new TextEncoder().encode(this.getSecret()))
Expand Down
22 changes: 22 additions & 0 deletions packages/auth/tests/jwt.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { decodeJwt } from 'jose'
import { describe, expect, it } from 'vitest'

import { Auth } from '../src/Auth'
import { authSecret } from './fixtures/auth'

type WithCreateJWT = { createJWT(payload: Record<string, unknown>): Promise<string> }

describe('Auth JWT', () => {
it('issues a distinct token each time, even for the same user within one second', async () => {
const auth = new Auth(authSecret) as unknown as WithCreateJWT
const payload = { sub: '1', email: 'a@example.com' }

const first = await auth.createJWT(payload)
const second = await auth.createJWT(payload)

// Same `sub` and the same one-second `iat`: only the `jti` tells them apart.
expect(second).not.toBe(first)
expect(decodeJwt(first).jti).toBeTruthy()
expect(decodeJwt(second).jti).not.toBe(decodeJwt(first).jti)
})
})
Loading