diff --git a/server/src/nest/oauth/oauth-api.controller.ts b/server/src/nest/oauth/oauth-api.controller.ts index dc42a5422..5da5d2f74 100644 --- a/server/src/nest/oauth/oauth-api.controller.ts +++ b/server/src/nest/oauth/oauth-api.controller.ts @@ -29,6 +29,12 @@ import type { Request, Response } from 'express'; const MIN = 60_000; +/** The id of the cookie session a consent comes from, null for a token from before sessions were tracked. */ +function consentingSession(req: Request): string | null { + const jti = verifiedSessionClaims((req.cookies as Record | undefined)?.trek_session)?.jti; + return typeof jti === 'string' ? jti : null; +} + /** * Authenticated OAuth management endpoints (the SPA's consent + client/session * UI) — byte-identical to the legacy oauthApiRouter (server/src/routes/oauth.ts): @@ -136,9 +142,8 @@ export class OauthApiController { resource: validation.resource ?? null, codeChallenge: body.code_challenge, codeChallengeMethod: 'S256', - // The cookie session the guard has just verified: the code is good only under its password. - passwordVersion: - verifiedSessionClaims((req.cookies as Record | undefined)?.trek_session)?.pv ?? 0, + // The cookie session the guard has just verified: the code is good only while it stands. + sessionId: consentingSession(req), }); if (!code) { throw new HttpException( diff --git a/server/src/nest/oauth/oauth-public.controller.ts b/server/src/nest/oauth/oauth-public.controller.ts index 85df9c3d3..85a4f377d 100644 --- a/server/src/nest/oauth/oauth-public.controller.ts +++ b/server/src/nest/oauth/oauth-public.controller.ts @@ -96,7 +96,7 @@ export class OauthPublicController { if (!this.oauth.verifyPKCE(code_verifier, pending.codeChallenge)) return invalidGrant('pkce_failed', pending.userId); const tokens = await this.oauth.issueTokensForCode(pending); - if (!tokens) return invalidGrant('password_changed', pending.userId); + if (!tokens) return invalidGrant('session_ended', pending.userId); await this.audit.writeAudit({ userId: pending.userId, action: 'oauth.token.issue', diff --git a/server/src/nest/oauth/oauth.module.ts b/server/src/nest/oauth/oauth.module.ts index fec127cf2..fc1758e88 100644 --- a/server/src/nest/oauth/oauth.module.ts +++ b/server/src/nest/oauth/oauth.module.ts @@ -8,6 +8,7 @@ import { createMcpAddonGate } from '../addons/mcp-addon-gate'; import { AuditModule } from '../audit/audit.module'; import { RateLimitModule } from '../common/rate-limit.module'; import { SchedulingModule } from '../scheduling/scheduling.module'; +import { SessionsModule } from '../sessions/sessions.module'; import { OauthApiController } from './oauth-api.controller'; import { CimdClientResolver } from './oauth-cimd'; import { OauthPublicController } from './oauth-public.controller'; @@ -59,14 +60,15 @@ import type { MiddlewareConsumer, NestModule } from '@nestjs/common'; * shape `McpTokensRepository`/`InviteTokensRepository` already use across * `nest/tokens`/`nest/auth`/`nest/oidc`). OA16/OA31 read `users` columns * THROUGH `OauthTokensRepository`'s own join methods, not a separate - * `Users` call (Task 1's ruling: "do not add users methods" for this join); - * `OauthService` injects `UsersRepository` only to check that the password - * an authorization code was granted under still holds. + * `Users` call (Task 1's ruling: "do not add users methods" for this join). + * Whether the session that consented to an authorization code still stands + * is the sessions domain's to answer (`SessionsService.findActive`). */ @Module({ imports: [ RateLimitModule, AuditModule, + SessionsModule, AddonsModule, SchedulingModule, MikroOrmModule.forFeature([OauthClients, OauthTokens, OauthConsents, Users]), diff --git a/server/src/nest/oauth/oauth.pending-codes.ts b/server/src/nest/oauth/oauth.pending-codes.ts index 912fd943a..a145104d7 100644 --- a/server/src/nest/oauth/oauth.pending-codes.ts +++ b/server/src/nest/oauth/oauth.pending-codes.ts @@ -28,8 +28,12 @@ export interface PendingCode { resource: string | null; codeChallenge: string; codeChallengeMethod: 'S256'; - /** The password version the consent was given under; the code mints tokens only while it holds. */ - passwordVersion: number; + /** + * The browser session that consented (`user_sessions.id`), or null for a + * token from before sessions were tracked; the code mints tokens only while + * that session is active. + */ + sessionId: string | null; expiresAt: number; } diff --git a/server/src/nest/oauth/oauth.service.ts b/server/src/nest/oauth/oauth.service.ts index 4226b496d..438330a1a 100644 --- a/server/src/nest/oauth/oauth.service.ts +++ b/server/src/nest/oauth/oauth.service.ts @@ -3,7 +3,6 @@ import { getMcpSafeUrl } from '../../app-config'; import { OauthClients } from '../../db/entities/OauthClients.entity'; import { OauthConsents } from '../../db/entities/OauthConsents.entity'; import { OauthTokens } from '../../db/entities/OauthTokens.entity'; -import { Users } from '../../db/entities/Users.entity'; import { OAUTH_CLIENT_ALLOWED_SCOPES, OAUTH_CLIENT_REDIRECT_URIS, @@ -13,7 +12,6 @@ import { import type { OauthClientRow, OauthClientsRepository } from '../../db/repositories/OauthClients.repository'; import type { OauthConsentsRepository } from '../../db/repositories/OauthConsents.repository'; import type { OauthTokenRefreshRow, OauthTokensRepository } from '../../db/repositories/OauthTokens.repository'; -import type { UsersRepository } from '../../db/repositories/Users.repository'; import { dbNow, parseDbTimestamp } from '../../db/types'; // Import from scopes/sessionManager directly, NOT the ../../mcp barrel: the // barrel pulls the whole tools fan-out (and via the domain bridges, the Nest @@ -30,6 +28,7 @@ import { AuditService } from '../audit/audit.service'; import { DomainError } from '../common/domain-error'; import { toRowId } from '../common/row-id'; import { UnitOfWork } from '../database/unit-of-work'; +import { SessionsService } from '../sessions/sessions.service'; import { CimdClientResolver, isCimdClientId, type CimdClient } from './oauth-cimd'; import { ACCESS_TOKEN_TTL_S, @@ -135,7 +134,7 @@ export class OauthService { @InjectRepository(OauthClients) private readonly clients: OauthClientsRepository, @InjectRepository(OauthTokens) private readonly tokens: OauthTokensRepository, @InjectRepository(OauthConsents) private readonly consents: OauthConsentsRepository, - @InjectRepository(Users) private readonly users: UsersRepository, + private readonly sessions: SessionsService, private readonly addons: AddonsService, private readonly audit: AuditService, private readonly uow: UnitOfWork, @@ -320,7 +319,7 @@ export class OauthService { resource: string | null; codeChallenge: string; codeChallengeMethod: 'S256'; - passwordVersion: number; + sessionId: string | null; }): Promise { const rawCode = randomBytes(32).toString('hex'); const stored = await this.pendingCodes.put(rawCode, { ...params, expiresAt: Date.now() + AUTH_CODE_TTL_MS }); @@ -393,14 +392,18 @@ export class OauthService { // ------------------------------------------------------------------------- /** - * The tokens a redeemed authorization code grants, or null when the - * password changed since the consent: a reset or a change revokes the - * user's tokens, and a code from before it must not mint new ones. Checked - * in the transaction that writes the tokens. + * The tokens a redeemed authorization code grants, or null when the session + * that consented has ended since: a password reset or change ends every + * session along with the user's tokens, and a sign-out ends this one, so a + * code from before must not mint new tokens. Checked in the transaction + * that writes them. A token from before sessions were tracked has no + * session to check and passes, as it does everywhere until it expires. */ async issueTokensForCode(pending: PendingCode): Promise> | null> { return this.uow.transactional(async () => { - if ((await this.users.getPasswordVersion(pending.userId)) !== pending.passwordVersion) return null; + if (pending.sessionId !== null && !(await this.sessions.findActive(pending.sessionId, pending.userId, dbNow()))) { + return null; + } return this.issueTokens(pending.clientId, pending.userId, pending.scopes, null, pending.resource ?? null); }); } diff --git a/server/tests/integration/oauth-authorize.test.ts b/server/tests/integration/oauth-authorize.test.ts index 06636ed87..3207f2d56 100644 --- a/server/tests/integration/oauth-authorize.test.ts +++ b/server/tests/integration/oauth-authorize.test.ts @@ -264,7 +264,7 @@ describe('GET /oauth/authorize — SDK authorizationHandler over trekOAuthProvid // SDK-side exchange see it. const code = await withRequestContext(orm, () => containerSideOauth.createAuthCode({ - passwordVersion: 0, + sessionId: null, clientId, userId: user.id, redirectUri: 'https://client.example.com/cb', diff --git a/server/tests/integration/oauth.test.ts b/server/tests/integration/oauth.test.ts index 62a006356..2becc0d30 100644 --- a/server/tests/integration/oauth.test.ts +++ b/server/tests/integration/oauth.test.ts @@ -332,7 +332,7 @@ describe('POST /oauth/token — authorization_code grant', () => { // Create code for client1 const code = await createAuthCode({ - passwordVersion: 0, + sessionId: null, clientId: r1.client!.client_id as string, userId: user.id, redirectUri: 'https://app1.example.com/cb', @@ -361,7 +361,7 @@ describe('POST /oauth/token — authorization_code grant', () => { const { verifier, challenge } = makePkce(); const code = await createAuthCode({ - passwordVersion: 0, + sessionId: null, clientId: r.client!.client_id as string, userId: user.id, redirectUri: 'https://app.example.com/cb', @@ -389,7 +389,7 @@ describe('POST /oauth/token — authorization_code grant', () => { const { verifier, challenge } = makePkce(); const code = await createAuthCode({ - passwordVersion: 0, + sessionId: null, clientId: r.client!.client_id as string, userId: user.id, redirectUri: 'https://app.example.com/cb', @@ -417,7 +417,7 @@ describe('POST /oauth/token — authorization_code grant', () => { const { challenge } = makePkce(); const code = await createAuthCode({ - passwordVersion: 0, + sessionId: null, clientId: r.client!.client_id as string, userId: user.id, redirectUri: 'https://app.example.com/cb', @@ -445,7 +445,7 @@ describe('POST /oauth/token — authorization_code grant', () => { const { verifier, challenge } = makePkce(); const code = await createAuthCode({ - passwordVersion: 0, + sessionId: null, clientId: r.client!.client_id as string, userId: user.id, redirectUri: 'https://app.example.com/cb', @@ -505,7 +505,7 @@ describe('POST /oauth/token — refresh_token grant', () => { const { verifier, challenge } = makePkce(); const code = await createAuthCode({ - passwordVersion: 0, + sessionId: null, clientId: r.client!.client_id as string, userId: user.id, redirectUri: 'https://app.example.com/cb', @@ -592,7 +592,7 @@ describe('POST /oauth/revoke', () => { const { verifier, challenge } = makePkce(); const code = await createAuthCode({ - passwordVersion: 0, + sessionId: null, clientId: r.client!.client_id as string, userId: user.id, redirectUri: 'https://app.example.com/cb', @@ -1066,7 +1066,7 @@ describe('Sessions — /api/oauth/sessions', () => { const { verifier, challenge } = makePkce(); const code = await createAuthCode({ - passwordVersion: 0, + sessionId: null, clientId: r.client!.client_id as string, userId: user.id, redirectUri: 'https://app.example.com/cb', @@ -1115,7 +1115,7 @@ describe('Sessions — /api/oauth/sessions', () => { if (!client) throw new Error('the OAuth client was not created'); const { verifier, challenge } = makePkce(); const code = await createAuthCode({ - passwordVersion: 0, + sessionId: null, clientId: client.client_id as string, userId: user.id, redirectUri: 'https://app.example.com/cb', @@ -1210,7 +1210,7 @@ describe('H1 — PKCE format validation', () => { const { challenge } = makePkce(); const code = await createAuthCode({ - passwordVersion: 0, + sessionId: null, clientId: r.client!.client_id as string, userId: user.id, redirectUri: 'https://app.example.com/cb', @@ -1265,7 +1265,7 @@ describe('H5 — All invalid_grant cases return identical response body', () => const { verifier, challenge } = makePkce(); const code = await createAuthCode({ - passwordVersion: 0, + sessionId: null, clientId: r.client!.client_id as string, userId: user.id, redirectUri: 'https://app.example.com/cb', @@ -1287,7 +1287,7 @@ describe('H5 — All invalid_grant cases return identical response body', () => // Redirect URI mismatch (need fresh code since code is single-use) const code2 = await createAuthCode({ - passwordVersion: 0, + sessionId: null, clientId: r.client!.client_id as string, userId: user.id, redirectUri: 'https://app.example.com/cb', @@ -1418,7 +1418,7 @@ describe('C3 — Refresh token replay detection', () => { const { verifier, challenge } = makePkce(); const code = await createAuthCode({ - passwordVersion: 0, + sessionId: null, clientId: r.client!.client_id as string, userId: user.id, redirectUri: 'https://app.example.com/cb', @@ -1467,7 +1467,7 @@ describe('C3 — Refresh token replay detection', () => { const { verifier, challenge } = makePkce(); const code = await createAuthCode({ - passwordVersion: 0, + sessionId: null, clientId: r.client!.client_id as string, userId: user.id, redirectUri: 'https://app.example.com/cb', @@ -1509,7 +1509,7 @@ describe('C3 — Refresh token replay detection', () => { const { verifier, challenge } = makePkce(); const code = await createAuthCode({ - passwordVersion: 0, + sessionId: null, clientId: r.client!.client_id as string, userId: user.id, redirectUri: 'https://app.example.com/cb', diff --git a/server/tests/unit/nest/oauth.controller.test.ts b/server/tests/unit/nest/oauth.controller.test.ts index 424235934..aa190fbcf 100644 --- a/server/tests/unit/nest/oauth.controller.test.ts +++ b/server/tests/unit/nest/oauth.controller.test.ts @@ -132,7 +132,7 @@ describe('OauthPublicController /token', () => { ); expect(ok.body).toEqual({ access_token: 'at', token_type: 'Bearer' }); - // The password changed since the consent: the code grants nothing, and the refusal is audited. + // The consenting session ended since: the code grants nothing, and the refusal is audited. const stale = makeRes(); const staleSvc = osvc({ consumeAuthCode: vi.fn().mockReturnValue({ @@ -157,7 +157,7 @@ describe('OauthPublicController /token', () => { expect(staleAudit.writeAudit).toHaveBeenCalledWith( expect.objectContaining({ action: 'oauth.token.grant_failed', - details: { client_id: 'c', reason: 'password_changed' }, + details: { client_id: 'c', reason: 'session_ended' }, }), ); }); @@ -627,14 +627,14 @@ describe('OauthApiController', () => { expect((ok as { redirect: string }).redirect).toContain('code=the_code'); }); - it('authorize: the code carries the password version of the cookie session that consented', async () => { + it('authorize: the code carries the cookie session that consented', async () => { const createAuthCode = vi.fn().mockReturnValue('the_code'); const svc = osvc({ validateAuthorizeRequest: vi.fn().mockReturnValue({ valid: true, scopes: ['s'], resource: null }), saveConsent: vi.fn(), createAuthCode, }); - const cookie = jwt.sign({ id: user.id, pv: 4 }, JWT_SECRET, { algorithm: 'HS256' }); + const cookie = jwt.sign({ id: user.id, jti: 'sess-4' }, JWT_SECRET, { algorithm: 'HS256' }); await new OauthApiController(svc, rl()).authorize( user, { @@ -647,7 +647,7 @@ describe('OauthApiController', () => { }, { ...req, cookies: { trek_session: cookie } } as unknown as Request, ); - expect(createAuthCode).toHaveBeenCalledWith(expect.objectContaining({ passwordVersion: 4 })); + expect(createAuthCode).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 'sess-4' })); }); it('clients/sessions: 403 when MCP off, else CRUD', async () => { diff --git a/server/tests/unit/nest/oauth.service.test.ts b/server/tests/unit/nest/oauth.service.test.ts index b576cdb9c..43a5eb8a9 100644 --- a/server/tests/unit/nest/oauth.service.test.ts +++ b/server/tests/unit/nest/oauth.service.test.ts @@ -37,6 +37,7 @@ import { sweepPendingCodes, } from '../../../src/nest/oauth/oauth.pending-codes'; import { OauthService } from '../../../src/nest/oauth/oauth.service'; +import type { SessionsService } from '../../../src/nest/sessions/sessions.service'; import { createUser } from '../../helpers/factories'; import { countRows, findRow, findRows, insertRow, updateRows } from '../../helpers/factories/rows'; import { resetTestDb } from '../../helpers/test-db'; @@ -121,6 +122,12 @@ const getConsent = (...args: Parameters) => svc.getC const isConsentSufficient = (...args: Parameters) => svc.isConsentSufficient(...args); +/** Sessions a reset or a sign-out ended; every other id reads as an active session. */ +const endedSessions = new Set(); +const sessionsStub = { + findActive: vi.fn(async (id: string) => (endedSessions.has(id) ? null : { id, last_seen_at: '2026-01-01 00:00:00' })), +} as unknown as SessionsService & { findActive: ReturnType }; + beforeAll(async () => { t = await createTestOrm(testDb); auditLogRepo = t.repo(AuditLog); @@ -132,7 +139,7 @@ beforeAll(async () => { clientsRepo, tokensRepo, consentsRepo, - usersRepo, + sessionsStub, addonsStub, new AuditService(auditLogRepo, usersRepo), new UnitOfWork(t.em, new SqliteEngine()), @@ -411,7 +418,7 @@ describe('createAuthCode + consumeAuthCode', () => { const clientId = created.client!.client_id as string; const code = await createAuthCode({ - passwordVersion: 0, + sessionId: null, clientId, userId: user.id, redirectUri: 'https://example.com/callback', @@ -437,7 +444,7 @@ describe('createAuthCode + consumeAuthCode', () => { const clientId = created.client!.client_id as string; const code = await createAuthCode({ - passwordVersion: 0, + sessionId: null, clientId, userId: user.id, redirectUri: 'https://example.com/callback', @@ -451,13 +458,13 @@ describe('createAuthCode + consumeAuthCode', () => { expect(await consumeAuthCode(code)).toBeNull(); }); - it('a code mints tokens only while the password it was granted under holds', async () => { + it('a code mints tokens only while the session that consented stands', async () => { const { user } = createUser(testDb); const created = await makeClient(user.id); const clientId = String(created.client?.client_id); - const grant = async () => { + const grant = async (sessionId: string | null) => { const code = await createAuthCode({ - passwordVersion: 0, + sessionId, clientId, userId: user.id, redirectUri: 'https://example.com/callback', @@ -471,13 +478,15 @@ describe('createAuthCode + consumeAuthCode', () => { return pending; }; - const kept = await svc.issueTokensForCode(await grant()); - expect(kept?.access_token).toEqual(expect.any(String)); + expect((await svc.issueTokensForCode(await grant('sess-live')))?.access_token).toEqual(expect.any(String)); + // A token from before sessions were tracked has no session to check. + expect((await svc.issueTokensForCode(await grant(null)))?.access_token).toEqual(expect.any(String)); - const beforeReset = await grant(); - await updateRows(t, Users, { id: user.id }, { password_version: 1 }); + const beforeReset = await grant('sess-reset'); + endedSessions.add('sess-reset'); expect(await svc.issueTokensForCode(beforeReset)).toBeNull(); - expect(await countRows(t, OauthTokens, { user: user.id })).toBe(1); + expect(await countRows(t, OauthTokens, { user: user.id })).toBe(2); + expect(sessionsStub.findActive).toHaveBeenCalledWith('sess-reset', user.id, expect.any(String)); }); }); @@ -1305,7 +1314,7 @@ describe('addon gate and MCP endpoint', () => { describe('pending-code store', () => { const codeParams = { - passwordVersion: 0, + sessionId: null, clientId: 'c', userId: 42, redirectUri: 'https://example.com/callback', @@ -1466,7 +1475,7 @@ describe('module-scoped OAuth state', () => { // scoped, so even a second hand-built instance must see it — two maps would // kill the authorization-code flow silently. const code = (await createAuthCode({ - passwordVersion: 0, + sessionId: null, clientId: 'c', userId: 42, redirectUri: 'https://example.com/callback', @@ -1480,7 +1489,7 @@ describe('module-scoped OAuth state', () => { clientsRepo, tokensRepo, consentsRepo, - usersRepo, + sessionsStub, addonsStub, new AuditService(auditLogRepo, usersRepo), new UnitOfWork(t.em, new SqliteEngine()), diff --git a/server/tests/unit/nest/process-state-ports.test.ts b/server/tests/unit/nest/process-state-ports.test.ts index 8c78b26a9..abf2bc02a 100644 --- a/server/tests/unit/nest/process-state-ports.test.ts +++ b/server/tests/unit/nest/process-state-ports.test.ts @@ -66,7 +66,7 @@ function code(over: Partial = {}): PendingCode { resource: null, codeChallenge: 'x', codeChallengeMethod: 'S256', - passwordVersion: 0, + sessionId: null, expiresAt: Date.now() + 60_000, ...over, }; @@ -135,7 +135,7 @@ describe('OAuth pending codes', () => { store, ); const issued = await service.createAuthCode({ - passwordVersion: 0, + sessionId: null, clientId: 'c', userId: 1, redirectUri: 'https://app.example/cb',