From aa2ab1a3d2509db578b3cfa087c26744045b5684 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Oliveira?= Date: Sat, 28 Mar 2026 03:55:58 +0000 Subject: [PATCH 1/2] Patch adonis5-jwt to fix jwt errors spamming --- app/Controllers/Http/UserController.ts | 18 +++++- package.json | 5 +- patches/adonis5-jwt@1.1.7.patch | 90 ++++++++++++++++++++++++++ pnpm-lock.yaml | 10 ++- tests/functional/api/register.spec.ts | 70 ++++++++++++++++++++ 5 files changed, 187 insertions(+), 6 deletions(-) create mode 100644 patches/adonis5-jwt@1.1.7.patch diff --git a/app/Controllers/Http/UserController.ts b/app/Controllers/Http/UserController.ts index ef7cfdd3..d0eb3c2d 100644 --- a/app/Controllers/Http/UserController.ts +++ b/app/Controllers/Http/UserController.ts @@ -91,7 +91,11 @@ export default class UsersController { } // Generate new auth token - const token = await auth.use('jwt').login(user, { payload: {} }); + const token = await auth.use('jwt').login(user, { + payload: { + nonce: crypto.randomUUID(), + }, + }); return response.send({ message: 'Successfully created account', @@ -140,7 +144,11 @@ export default class UsersController { } // Generate token - const token = await auth.use('jwt').login(user, { payload: {} }); + const token = await auth.use('jwt').login(user, { + payload: { + nonce: crypto.randomUUID(), + }, + }); return response.send({ message: 'Successfully logged in', @@ -228,7 +236,11 @@ export default class UsersController { return response.send('Missing or invalid api token'); } - const token = await auth.use('jwt').generate(user, { payload: {} }); + const token = await auth.use('jwt').generate(user, { + payload: { + nonce: crypto.randomUUID(), + }, + }); return response.send({ token: token.accessToken, diff --git a/package.json b/package.json index c6d9c9b2..9d4875a2 100644 --- a/package.json +++ b/package.json @@ -110,6 +110,9 @@ "aws-sdk", "bcrypt", "sqlite3" - ] + ], + "patchedDependencies": { + "adonis5-jwt@1.1.7": "patches/adonis5-jwt@1.1.7.patch" + } } } diff --git a/patches/adonis5-jwt@1.1.7.patch b/patches/adonis5-jwt@1.1.7.patch new file mode 100644 index 00000000..a6c4de75 --- /dev/null +++ b/patches/adonis5-jwt@1.1.7.patch @@ -0,0 +1,90 @@ +diff --git a/build/lib/Guards/JwtGuard.js b/build/lib/Guards/JwtGuard.js +index e369820d726e37c4d924d18d879e847e3accf669..058180d34043122c46711f551cab0442de66d28a 100644 +--- a/build/lib/Guards/JwtGuard.js ++++ b/build/lib/Guards/JwtGuard.js +@@ -216,27 +216,37 @@ class JWTGuard extends Base_1.BaseGuard { + /** + * Generate a JWT and refresh token + */ +- const tokenInfo = await this.generateTokenForPersistance(expiresIn, refreshTokenExpiresIn, payload, rememberMe); + let providerToken; +- if (!this.config.persistJwt) { +- /** +- * Persist refresh token ONLY to the database. +- */ +- providerToken = new ProviderToken_1.ProviderToken(name, tokenInfo.refreshTokenHash, userId, this.tokenType); +- providerToken.expiresAt = tokenInfo.refreshTokenExpiresAt; +- providerToken.meta = meta; +- await this.tokenProvider.write(providerToken); +- } +- else { +- /** +- * Persist JWT token and refresh token to the database +- */ +- providerToken = new JwtProviderToken_1.JwtProviderToken(name, tokenInfo.accessTokenHash, userId, this.tokenType); +- providerToken.expiresAt = tokenInfo.expiresAt; +- providerToken.refreshToken = tokenInfo.refreshTokenHash; +- providerToken.refreshTokenExpiresAt = tokenInfo.refreshTokenExpiresAt; +- providerToken.meta = meta; +- await this.tokenProvider.write(providerToken); ++ let tokenInfo; ++ for (let attempts = 0; attempts < 3; attempts++) { ++ tokenInfo = await this.generateTokenForPersistance(expiresIn, refreshTokenExpiresIn, payload, rememberMe); ++ if (!this.config.persistJwt) { ++ /** ++ * Persist refresh token ONLY to the database. ++ */ ++ providerToken = new ProviderToken_1.ProviderToken(name, tokenInfo.refreshTokenHash, userId, this.tokenType); ++ providerToken.expiresAt = tokenInfo.refreshTokenExpiresAt; ++ providerToken.meta = meta; ++ } ++ else { ++ /** ++ * Persist JWT token and refresh token to the database ++ */ ++ providerToken = new JwtProviderToken_1.JwtProviderToken(name, tokenInfo.accessTokenHash, userId, this.tokenType); ++ providerToken.expiresAt = tokenInfo.expiresAt; ++ providerToken.refreshToken = tokenInfo.refreshTokenHash; ++ providerToken.refreshTokenExpiresAt = tokenInfo.refreshTokenExpiresAt; ++ providerToken.meta = meta; ++ } ++ try { ++ await this.tokenProvider.write(providerToken); ++ break; ++ } ++ catch (error) { ++ if (attempts === 2 || !this.isUniqueConstraintError(error)) { ++ throw error; ++ } ++ } + } + /** + * Construct a new API Token instance +@@ -337,7 +347,8 @@ class JWTGuard extends Base_1.BaseGuard { + } + let accessTokenBuilder = new jose_1.SignJWT({ data: payload, ...payload }) + .setProtectedHeader({ alg: this.config.algorithmJwt || "RS256", typ: "JWT" }) +- .setIssuedAt(); ++ .setIssuedAt() ++ .setJti((0, uuid_1.v4)()); + if (this.config.issuer) { + accessTokenBuilder = accessTokenBuilder.setIssuer(this.config.issuer); + } +@@ -377,6 +388,17 @@ class JWTGuard extends Base_1.BaseGuard { + generateHash(token) { + return (0, crypto_1.createHash)("sha256").update(token).digest("hex"); + } ++ /** ++ * Detect duplicate token persistence errors across supported databases. ++ */ ++ isUniqueConstraintError(error) { ++ const code = error?.code; ++ const message = error?.message; ++ return code === "SQLITE_CONSTRAINT" || code === "ER_DUP_ENTRY" || code === "23505" ++ || (typeof message === "string" && (message.includes("UNIQUE constraint failed") ++ || message.includes("duplicate key value violates unique constraint") ++ || message.includes("Duplicate entry"))); ++ } + /** + * Converts expiry duration to an absolute date/time value + */ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 4c12c146..464457d8 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -4,6 +4,11 @@ settings: autoInstallPeers: true excludeLinksFromLockfile: false +patchedDependencies: + adonis5-jwt@1.1.7: + hash: b1d39457aff2a7bd4496aab6a43ff0d1fb3045ba08cf3d2286641c19d2e72d24 + path: patches/adonis5-jwt@1.1.7.patch + importers: .: @@ -34,7 +39,7 @@ importers: version: 6.2.0(@adonisjs/core@5.9.0) adonis5-jwt: specifier: github:SpecialAro/adonis5-jwt#34941c10adcf89583a40767552b994ea499b92e3 - version: https://codeload.github.com/SpecialAro/adonis5-jwt/tar.gz/34941c10adcf89583a40767552b994ea499b92e3 + version: https://codeload.github.com/SpecialAro/adonis5-jwt/tar.gz/34941c10adcf89583a40767552b994ea499b92e3(patch_hash=b1d39457aff2a7bd4496aab6a43ff0d1fb3045ba08cf3d2286641c19d2e72d24) aws-sdk: specifier: 2.1672.0 version: 2.1672.0 @@ -1672,6 +1677,7 @@ packages: acorn-import-assertions@1.9.0: resolution: {integrity: sha512-cmMwop9x+8KFhxvKrKfPYmN6/pKTYYHBqLa0DfvVZcKMJWNyWLnaqND7dx/qn66R7ewM1UX5XMaDVP5wlVTaVA==} + deprecated: package has been renamed to acorn-import-attributes peerDependencies: acorn: ^8 @@ -8079,7 +8085,7 @@ snapshots: adonis-preset-ts@2.1.0: {} - adonis5-jwt@https://codeload.github.com/SpecialAro/adonis5-jwt/tar.gz/34941c10adcf89583a40767552b994ea499b92e3: + adonis5-jwt@https://codeload.github.com/SpecialAro/adonis5-jwt/tar.gz/34941c10adcf89583a40767552b994ea499b92e3(patch_hash=b1d39457aff2a7bd4496aab6a43ff0d1fb3045ba08cf3d2286641c19d2e72d24): dependencies: jose: 4.14.6 ts-morph: 16.0.0 diff --git a/tests/functional/api/register.spec.ts b/tests/functional/api/register.spec.ts index e69de29b..f9c4052f 100644 --- a/tests/functional/api/register.spec.ts +++ b/tests/functional/api/register.spec.ts @@ -0,0 +1,70 @@ +import { test } from '@japa/runner'; +import UserFactory from 'Database/factories/UserFactory'; +import crypto from 'node:crypto'; + +function createLegacyApiPassword(password: string) { + return crypto.createHash('sha256').update(password).digest('base64'); +} + +function createBasicAuthHeader(email: string, password: string) { + return `Basic ${Buffer.from(`${email}:${password}`).toString('base64')}`; +} + +test.group('API / Auth', () => { + test('returns unique persisted JWTs for repeated login requests', async ({ + client, + assert, + }) => { + const user = await UserFactory.create(); + const authorization = createBasicAuthHeader( + user.email, + createLegacyApiPassword('password'), + ); + + const [firstResponse, secondResponse] = await Promise.all([ + client.post('/v1/auth/login').header('Authorization', authorization), + client.post('/v1/auth/login').header('Authorization', authorization), + ]); + + firstResponse.assertStatus(200); + secondResponse.assertStatus(200); + + const firstBody = JSON.parse(firstResponse.text()); + const secondBody = JSON.parse(secondResponse.text()); + + assert.notEqual(firstBody.token, secondBody.token); + }); + + test('returns unique persisted JWTs for repeated new token requests', async ({ + client, + assert, + }) => { + const user = await UserFactory.create(); + const loginResponse = await client + .post('/v1/auth/login') + .header( + 'Authorization', + createBasicAuthHeader(user.email, createLegacyApiPassword('password')), + ); + + loginResponse.assertStatus(200); + const { token } = JSON.parse(loginResponse.text()); + + const [firstResponse, secondResponse] = await Promise.all([ + client + .get('/v1/me/newtoken') + .header('Authorization', `Bearer ${token}`), + client + .get('/v1/me/newtoken') + .header('Authorization', `Bearer ${token}`), + ]); + + firstResponse.assertStatus(200); + secondResponse.assertStatus(200); + + const firstBody = JSON.parse(firstResponse.text()); + const secondBody = JSON.parse(secondResponse.text()); + + assert.notEqual(firstBody.token, secondBody.token); + }); +}); From d45170b94cbbce8c8597e80b8de9744e73d95570 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Oliveira?= <37463445+SpecialAro@users.noreply.github.com> Date: Sat, 28 Mar 2026 15:48:38 +0000 Subject: [PATCH 2/2] Update tests/functional/api/register.spec.ts Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- tests/functional/api/register.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/functional/api/register.spec.ts b/tests/functional/api/register.spec.ts index f9c4052f..2717973a 100644 --- a/tests/functional/api/register.spec.ts +++ b/tests/functional/api/register.spec.ts @@ -10,7 +10,7 @@ function createBasicAuthHeader(email: string, password: string) { return `Basic ${Buffer.from(`${email}:${password}`).toString('base64')}`; } -test.group('API / Auth', () => { +test.group('API / Auth token uniqueness', () => { test('returns unique persisted JWTs for repeated login requests', async ({ client, assert,