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
18 changes: 15 additions & 3 deletions app/Controllers/Http/UserController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,11 @@
}

// 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',
Expand Down Expand Up @@ -140,7 +144,11 @@
}

// 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',
Expand Down Expand Up @@ -228,7 +236,11 @@
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,
Expand Down Expand Up @@ -298,7 +310,7 @@
return response.status(401).send(errorMessage);
}

token = content.token;

Check warning on line 313 in app/Controllers/Http/UserController.ts

View workflow job for this annotation

GitHub Actions / Ferdium Server Build

Use object destructuring
} catch (error) {
return response.status(401).send({
message: 'Cannot login to Franz',
Expand Down
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,9 @@
"aws-sdk",
"bcrypt",
"sqlite3"
]
],
"patchedDependencies": {
"adonis5-jwt@1.1.7": "patches/adonis5-jwt@1.1.7.patch"
}
}
}
90 changes: 90 additions & 0 deletions patches/adonis5-jwt@1.1.7.patch
Original file line number Diff line number Diff line change
@@ -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
*/
10 changes: 8 additions & 2 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

70 changes: 70 additions & 0 deletions tests/functional/api/register.spec.ts
Original file line number Diff line number Diff line change
@@ -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 token uniqueness', () => {
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);
});
});
Loading