Skip to content

The open alternative to Salesforce, designed for AI.

fix(auth): make login tokens single use (#26614)

Aditya Mishra1ba9d795b637
diff --git a/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.ts b/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.ts
index 7abe66cab66..416fc9f5068 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.ts
@@ -437,6 +437,8 @@ export class AuthResolver {
TwoFactorAuthenticationStrategy.TOTP,
);
+ await this.loginTokenService.consumeLoginTokenOrThrow(loginTokenPayload);
+
const authTokens = await this.authService.verify(
email,
workspace.id,
@@ -847,6 +849,8 @@ export class AuthResolver {
user.email,
);
+ await this.loginTokenService.consumeLoginTokenOrThrow(tokenPayload);
+
authTokens =
await this.authService.generateImpersonationAccessTokenAndRefreshToken({
workspaceId,
@@ -858,6 +862,8 @@ export class AuthResolver {
} else {
await this.validateRegularAuthentication(workspace, userWorkspace);
+ await this.loginTokenService.consumeLoginTokenOrThrow(tokenPayload);
+
authTokens = await this.authService.verify(
user.email,
workspace.id,
diff --git a/packages/twenty-server/src/engine/core-modules/auth/constants/consumed-login-token-cache-key-prefix.constant.ts b/packages/twenty-server/src/engine/core-modules/auth/constants/consumed-login-token-cache-key-prefix.constant.ts
new file mode 100644
index 00000000000..4aa5536c7fc
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/auth/constants/consumed-login-token-cache-key-prefix.constant.ts
@@ -0,0 +1 @@
+export const CONSUMED_LOGIN_TOKEN_CACHE_KEY_PREFIX = 'login-token:consumed';
diff --git a/packages/twenty-server/src/engine/core-modules/auth/token/services/login-token.service.ts b/packages/twenty-server/src/engine/core-modules/auth/token/services/login-token.service.ts
index 183aa6a37f2..4ddfe257736 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/token/services/login-token.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/token/services/login-token.service.ts
@@ -1,8 +1,12 @@
import { Injectable } from '@nestjs/common';
+import crypto from 'crypto';
+
import { addMilliseconds } from 'date-fns';
import ms from 'ms';
+import { isNonEmptyString } from '@sniptt/guards';
+import { CONSUMED_LOGIN_TOKEN_CACHE_KEY_PREFIX } from 'src/engine/core-modules/auth/constants/consumed-login-token-cache-key-prefix.constant';
import { type AuthToken } from 'src/engine/core-modules/auth/dto/auth-token.dto';
import {
AuthException,
@@ -10,6 +14,9 @@ import {
} from 'src/engine/core-modules/auth/auth.exception';
import { type LoginTokenJwtPayload } from 'src/engine/core-modules/auth/types/login-token-jwt-payload.type';
import { JwtTokenTypeEnum } from 'src/engine/core-modules/auth/types/jwt-token-type.enum';
+import { InjectCacheStorage } from 'src/engine/core-modules/cache-storage/decorators/cache-storage.decorator';
+import { CacheStorageService } from 'src/engine/core-modules/cache-storage/services/cache-storage.service';
+import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';
import { JwtWrapperService } from 'src/engine/core-modules/jwt/services/jwt-wrapper.service';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
import { AuthProviderEnum } from 'src/engine/core-modules/workspace/types/workspace.type';
@@ -19,6 +26,8 @@ export class LoginTokenService {
constructor(
private readonly jwtWrapperService: JwtWrapperService,
private readonly twentyConfigService: TwentyConfigService,
+ @InjectCacheStorage(CacheStorageNamespace.EngineAuthSession)
+ private readonly cacheStorage: CacheStorageService,
) {}
async generateLoginToken(
@@ -40,6 +49,7 @@ export class LoginTokenService {
workspaceId,
authProvider,
impersonatorUserWorkspaceId: options?.impersonatorUserWorkspaceId,
+ jti: crypto.randomUUID(),
};
const expiresIn = this.twentyConfigService.get('LOGIN_TOKEN_EXPIRES_IN');
@@ -78,4 +88,26 @@ export class LoginTokenService {
return decoded;
}
+
+ async consumeLoginTokenOrThrow({ jti }: LoginTokenJwtPayload): Promise<void> {
+ if (!isNonEmptyString(jti)) {
+ throw new AuthException(
+ 'Login token is missing its identifier',
+ AuthExceptionCode.UNAUTHENTICATED,
+ );
+ }
+
+ const isFirstUse = await this.cacheStorage.setIfAbsent(
+ `${CONSUMED_LOGIN_TOKEN_CACHE_KEY_PREFIX}:${jti}`,
+ true,
+ ms(this.twentyConfigService.get('LOGIN_TOKEN_EXPIRES_IN')),
+ );
+
+ if (!isFirstUse) {
+ throw new AuthException(
+ 'Login token has already been used',
+ AuthExceptionCode.UNAUTHENTICATED,
+ );
+ }
+ }
}
diff --git a/packages/twenty-server/src/engine/core-modules/auth/types/login-token-jwt-payload.type.ts b/packages/twenty-server/src/engine/core-modules/auth/types/login-token-jwt-payload.type.ts
index 3cc15f65809..3d9ba64955e 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/types/login-token-jwt-payload.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/types/login-token-jwt-payload.type.ts
@@ -7,4 +7,5 @@ export type LoginTokenJwtPayload = CommonPropertiesJwtPayload & {
workspaceId: string;
authProvider: AuthProviderEnum;
impersonatorUserWorkspaceId?: string;
+ jti?: string;
};
diff --git a/packages/twenty-server/test/integration/graphql/suites/auth.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/auth.integration-spec.ts
index 917fa5d9fdc..c154b55e6e6 100644
--- a/packages/twenty-server/test/integration/graphql/suites/auth.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/auth.integration-spec.ts
@@ -19,6 +19,25 @@ const auth = {
describe('AuthResolve (integration)', () => {
let loginToken: string;
+ const exchangeLoginToken = () =>
+ client
+ .post('/metadata')
+ .set('Host', ORIGIN.host)
+ .set('Origin', ORIGIN.origin)
+ .send({
+ query: `
+ mutation GetAuthTokensFromLoginToken {
+ getAuthTokensFromLoginToken(loginToken: "${loginToken}", origin: "${ORIGIN.toString()}") {
+ tokens {
+ accessOrWorkspaceAgnosticToken {
+ token
+ }
+ }
+ }
+ }
+ `,
+ });
+
it('should getLoginTokenFromCredentials with email and password', () => {
const queryData = {
query: `
@@ -54,25 +73,7 @@ describe('AuthResolve (integration)', () => {
});
it('should getAuthTokensFromLoginToken with login token', () => {
- const queryData = {
- query: `
- mutation GetAuthTokensFromLoginToken {
- getAuthTokensFromLoginToken(loginToken: "${loginToken}", origin: "${ORIGIN.toString()}") {
- tokens {
- accessOrWorkspaceAgnosticToken {
- token
- }
- }
- }
- }
- `,
- };
-
- return client
- .post('/metadata')
- .set('Host', ORIGIN.host)
- .set('Origin', ORIGIN.origin)
- .send(queryData)
+ return exchangeLoginToken()
.expect(200)
.expect((res) => {
expect(res.body.data).toBeDefined();
@@ -90,4 +91,13 @@ describe('AuthResolve (integration)', () => {
expect(accessToken.token).toBeDefined();
});
});
+
+ it('should reject a login token that was already exchanged', () => {
+ return exchangeLoginToken()
+ .expect(200)
+ .expect((res) => {
+ expect(res.body.data).toBeNull();
+ expect(res.body.errors?.[0]?.extensions?.code).toBe('UNAUTHENTICATED');
+ });
+ });
});
diff --git a/packages/twenty-server/test/integration/graphql/suites/auth/jwt-key-rotation/jwt-legacy-hs256-fallback.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/auth/jwt-key-rotation/jwt-legacy-hs256-fallback.integration-spec.ts
index 50c5c6bbbd4..fee3abc5525 100644
--- a/packages/twenty-server/test/integration/graphql/suites/auth/jwt-key-rotation/jwt-legacy-hs256-fallback.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/auth/jwt-key-rotation/jwt-legacy-hs256-fallback.integration-spec.ts
@@ -131,6 +131,7 @@ describe('JWT Legacy HS256 no-kid fallback (integration)', () => {
workspaceId: sharedLoginPayload.workspaceId,
authProvider:
sharedLoginPayload.authProvider ?? AuthProviderEnum.Password,
+ jti: randomUUID(),
};
const forgedToken = forgeLegacyHs256Token(