diff --git a/.github/actions/run-e2e-suite/action.yml b/.github/actions/run-e2e-suite/action.yml index b74f7dc7..8c596117 100644 --- a/.github/actions/run-e2e-suite/action.yml +++ b/.github/actions/run-e2e-suite/action.yml @@ -260,6 +260,7 @@ runs: "NEXT_PUBLIC_THUNDERID_BASE_URL=https://localhost:8090" \ "NEXT_PUBLIC_THUNDERID_CLIENT_ID=JS_SDK_E2E_NEXTJS" \ "THUNDERID_CLIENT_SECRET=e2e-nextjs-secret" \ + "THUNDERID_SESSION_SECRET=${NEXTJS_SECRET}" \ "THUNDERID_SECRET=${NEXTJS_SECRET}" \ "NODE_TLS_REJECT_UNAUTHORIZED=0" diff --git a/packages/browser/CHANGELOG.md b/packages/browser/CHANGELOG.md index 1ea654aa..944a75fb 100644 --- a/packages/browser/CHANGELOG.md +++ b/packages/browser/CHANGELOG.md @@ -7,6 +7,8 @@ No changes to this SDK since sdk/browser/v1.26.0. ## 1.26.0 ### 📝 Other Changes -* Add opt-in telemetry for page views, API calls, sign-ins and outbound links by @bhagyasakalanka in https://github.com/thunder-id/javascript-sdks/pull/188 + +- Add opt-in telemetry for page views, API calls, sign-ins and outbound links by @bhagyasakalanka in + https://github.com/thunder-id/javascript-sdks/pull/188 **Full Changelog**: https://github.com/thunder-id/javascript-sdks/compare/sdk/browser/v1.25.0...sdk/browser/v1.26.0 diff --git a/packages/express/src/ThunderIDExpressClient.ts b/packages/express/src/ThunderIDExpressClient.ts index 507873d0..950648da 100644 --- a/packages/express/src/ThunderIDExpressClient.ts +++ b/packages/express/src/ThunderIDExpressClient.ts @@ -8,10 +8,12 @@ import { FlowSessionStore, ThunderIDNodeManagementClient, ThunderIDRuntimeError, + SessionData, Storage, TokenResponse, User, CookieConfig as NodeCookieConfig, + resolveSessionCookieSameSite, } from '@thunderid/node'; import express from 'express'; import {v4 as uuidv4} from 'uuid'; @@ -49,12 +51,96 @@ class ThunderIDExpressClient { + try { + const data: SessionData | undefined = await this.getStorageManager().getSessionData(sessionId); + + return data?.access_token ? data : undefined; + } catch { + return undefined; + } + } + + /** + * Removes a session from the store and waits for it, unlike `clearSession`, which does not wait. + * + * @param sessionId - The session to remove. + */ + public async endSession(sessionId: string): Promise { + await this.clearSessionAsync(sessionId); + } + + /** + * Deletes the session cookie. The deletion repeats the cookie's attributes, without which a + * browser ignores it for a `__Host-` cookie. + */ + public clearSessionCookie(res: express.Response): void { + const {httpOnly, path, sameSite, secure} = this.getSessionCookieOptions(); + + res.clearCookie(this.getSessionCookieName(), {httpOnly, path, sameSite, secure}); + } + + /** + * The name of the cookie that carries a sign-in in progress: `thunderid-session-state`, with `__Host-` when + * `Secure`. It holds the session ID the authorization request's `state` and PKCE verifier are stored under. + */ + public getSessionStateCookieName(): string { + return NodeCookieConfig.withHostPrefix( + NodeCookieConfig.getTempSessionCookieName(this._expressConfig?.vendor), + this.getSessionCookieOptions().secure, ); } + /** + * The attributes of the sign-in cookie. It is `SameSite=Lax` whatever the session cookie is, so it comes back on + * the redirect to the callback, which a `Strict` session cookie does not. + */ + public getSessionStateCookieOptions(): express.CookieOptions & {maxAge: number; secure: boolean} { + return { + httpOnly: true, + maxAge: CookieConfig.sessionStateMaxAgeSeconds * 1000, + path: '/', + sameSite: 'lax', + secure: this.getSessionCookieOptions().secure, + }; + } + + /** + * Deletes the sign-in cookie, repeating its attributes. + */ + public clearSessionStateCookie(res: express.Response): void { + const {httpOnly, path, sameSite, secure} = this.getSessionStateCookieOptions(); + + res.clearCookie(this.getSessionStateCookieName(), {httpOnly, path, sameSite, secure}); + } + public async getUserFromRequest(req: express.Request): Promise { const cookies = req.cookies as Record | undefined; const sessionId: string | undefined = cookies?.[this.getSessionCookieName()]; @@ -108,23 +194,18 @@ class ThunderIDExpressClient; + // The callback finds its sign-in through the sign-in cookie: a Strict session cookie does not come back on the + // identity provider's redirect. Starting a sign-in keeps the session already on this browser, if any. + const userId: string = + (req.query['code'] ? (cookies[stateCookieName] ?? cookies[cookieName]) : cookies[cookieName]) ?? uuidv4(); const authRedirectCallback = (url: string): void => { if (!url) return; - res.cookie(cookieName, userId, { - httpOnly: sc?.httpOnly ?? CookieConfig.defaultHttpOnly, - maxAge: (sc?.expiryTime ?? CookieConfig.defaultExpirySeconds) * 1000, - sameSite: (sc?.sameSite ?? CookieConfig.defaultSameSite) as any, - secure: sc?.secure ?? CookieConfig.defaultSecure, - }); + res.cookie(stateCookieName, userId, this.getSessionStateCookieOptions()); // The redirect is the response, so the request ends here rather than going on to later routes. res.redirect(url); }; @@ -146,6 +227,10 @@ class ThunderIDExpressClient): string => Buffer.from(JSON.strin const ID_TOKEN = `${encode({alg: 'none'})}.${encode({sid: 'server-session-1', sub: 'user-1'})}.`; interface MockResponse { + clearCookie: ReturnType; cookie: ReturnType; end: ReturnType; redirect: ReturnType; @@ -30,7 +31,7 @@ describe('authorization details through the Express middleware', () => { let client: ThunderIDExpressClient; const newResponse = (): MockResponse => { - const res: MockResponse = {cookie: vi.fn(), end: vi.fn(), redirect: vi.fn(), status: vi.fn()}; + const res: MockResponse = {clearCookie: vi.fn(), cookie: vi.fn(), end: vi.fn(), redirect: vi.fn(), status: vi.fn()}; res.status.mockReturnValue(res); @@ -135,10 +136,51 @@ describe('authorization details through the Express middleware', () => { ); expect(onSignIn).toHaveBeenCalledTimes(1); + // Sign-in starts with the Lax sign-in cookie, and only a completed sign-in sets the Strict session cookie. + expect(cookieName).toBe('thunderid-session-state'); + expect(callback.cookie).toHaveBeenCalledWith( + 'thunderid-session', + sessionId, + expect.objectContaining({sameSite: 'strict'}), + ); + expect(callback.clearCookie).toHaveBeenCalledWith( + 'thunderid-session-state', + expect.objectContaining({sameSite: 'lax'}), + ); const tokenResponse = onSignIn.mock.calls[0][1] as TokenResponse; expect(tokenResponse.accessToken).toBe('access-1'); expect(tokenResponse.authorizationDetails).toEqual(AUTHORIZATION_DETAILS); }); + + it("answers onSignIn's redirect with a page that moves on, so the Strict session cookie is sent", async () => { + const config: Partial = {onSignIn: (r: express.Response) => r.redirect('/home')}; + const start = newResponse(); + + await signIn(config, newRequest(), start); + + const [cookieName, sessionId] = start.cookie.mock.calls[0] as [string, string]; + const state = redirectedTo(start).searchParams.get('state')!; + + fetchMock.mockResolvedValueOnce( + new Response( + JSON.stringify({access_token: 'access-1', expires_in: '3600', id_token: ID_TOKEN, token_type: 'Bearer'}), + {headers: {'Content-Type': 'application/json'}, status: 200}, + ), + ); + + const callback = Object.assign(newResponse(), {send: vi.fn(), set: vi.fn()}); + + callback.set.mockReturnValue(callback); + + await handleSignIn()( + Object.assign(newRequest({code: 'auth-code', state}, {[cookieName]: sessionId}), {thunderIDAuth: client}), + callback as unknown as express.Response, + vi.fn(), + ); + + expect(callback.status).toHaveBeenCalledWith(200); + expect(callback.send).toHaveBeenCalledWith(expect.stringContaining('content="0;url=/home"')); + }); }); diff --git a/packages/express/src/__tests__/bff.test.ts b/packages/express/src/__tests__/bff.test.ts new file mode 100644 index 00000000..92d6bb90 --- /dev/null +++ b/packages/express/src/__tests__/bff.test.ts @@ -0,0 +1,373 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import http from 'node:http'; +import {AddressInfo} from 'node:net'; +import express from 'express'; +import {afterEach, beforeEach, describe, expect, it, Mock, vi} from 'vitest'; +import thunderIDBff from '../middleware/bff'; +import ThunderIDExpressClient from '../ThunderIDExpressClient'; + +const SESSION_ID = 'session-1'; +const COOKIE = 'thunderid-session'; +const STATE_COOKIE = 'thunderid-session-state'; + +type StubClient = Record & {expressConfig: Record}; + +const createClient = (): StubClient => + ({ + endSession: vi.fn().mockResolvedValue(undefined), + clearSessionCookie: vi.fn((res: express.Response) => res.clearCookie(COOKIE, {path: '/'})), + clearSessionStateCookie: vi.fn((res: express.Response) => res.clearCookie(STATE_COOKIE, {path: '/'})), + expressConfig: { + afterSignInUrl: 'http://127.0.0.1/api/auth/callback', + afterSignOutUrl: 'http://127.0.0.1/', + baseUrl: 'https://idp.example.com', + }, + getDecodedIdToken: vi.fn().mockResolvedValue({aud: 'c', email: 'a@example.com', nonce: 'n', sub: 'u'}), + getSessionCookieName: vi.fn().mockReturnValue(COOKIE), + getSessionCookieOptions: vi + .fn() + .mockReturnValue({httpOnly: true, maxAge: 1000, path: '/', sameSite: 'strict', secure: false}), + getSessionStateCookieName: vi.fn().mockReturnValue(STATE_COOKIE), + getSessionStateCookieOptions: vi + .fn() + .mockReturnValue({httpOnly: true, maxAge: 900_000, path: '/', sameSite: 'lax', secure: false}), + getSignInUrl: vi.fn().mockResolvedValue('https://idp.example.com/oauth2/authorize?x=1'), + getSessionData: vi.fn().mockResolvedValue({ + access_token: 'secret-access-token', + created_at: 1_000_000_000_000, + expires_in: '3600', + scope: 'openid', + }), + isSignedIn: vi.fn().mockResolvedValue(true), + refreshAccessToken: vi.fn().mockResolvedValue({}), + signIn: vi.fn().mockResolvedValue({accessToken: 'at'}), + signOut: vi.fn().mockResolvedValue('https://idp.example.com/oauth2/logout'), + switchOrganizationUnitWithDeviceSecret: vi.fn().mockResolvedValue({tokenResponse: {}}), + }) as unknown as StubClient; + +describe('thunderIDBff', () => { + let server: http.Server; + let client: StubClient; + let base: string; + + const call = (path: string, init: RequestInit = {}, sdk = true): Promise => + fetch(`${base}${path}`, { + redirect: 'manual', + ...init, + headers: { + cookie: `${COOKIE}=${SESSION_ID}`, + ...(sdk ? {'x-requested-with': 'XMLHttpRequest'} : {}), + ...(init.headers as Record | undefined), + }, + }); + + beforeEach(async () => { + client = createClient(); + + const app: express.Express = express(); + + // A minimal stand-in for cookie-parser. + app.use((req: express.Request, _res: express.Response, next: express.NextFunction) => { + req.cookies = Object.fromEntries( + (req.headers.cookie ?? '') + .split(';') + .filter(Boolean) + .map((pair: string) => { + const [name, value] = pair.trim().split('=') as [string, string]; + + return [name, decodeURIComponent(value)]; + }), + ); + (req as express.Request & {thunderIDAuth?: ThunderIDExpressClient}).thunderIDAuth = + client as unknown as ThunderIDExpressClient; + next(); + }); + app.use(express.urlencoded({extended: true})); + app.use(thunderIDBff({apiBaseUrl: 'https://api.example.com'})); + app.get('/elsewhere', (_req: express.Request, res: express.Response) => { + res.send('app'); + }); + + server = http.createServer(app); + await new Promise((resolve: () => void) => { + server.listen(0, '127.0.0.1', resolve); + }); + base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; + }); + + afterEach(async () => { + vi.unstubAllGlobals(); + await new Promise((resolve: () => void) => { + server.close(() => resolve()); + }); + }); + + it('passes requests outside /api/auth on to the app', async () => { + expect(await (await call('/elsewhere')).text()).toBe('app'); + }); + + it('reports the session without the token or the protocol claims', async () => { + const response: Response = await call('/api/auth/session'); + const text: string = await response.text(); + + expect(response.headers.get('cache-control')).toBe('no-store'); + expect(JSON.parse(text)).toEqual({ + expiresAt: 1_000_003_600, + isSignedIn: true, + scope: 'openid', + user: {email: 'a@example.com', sub: 'u'}, + }); + expect(text).not.toContain('secret-access-token'); + }); + + it('refuses a call without the request header', async () => { + expect((await call('/api/auth/session', {}, false)).status).toBe(403); + }); + + it('refuses a state-changing call from another origin', async () => { + const response: Response = await call('/api/auth/signout', { + headers: {origin: 'https://evil.example'}, + method: 'POST', + }); + + expect(response.status).toBe(403); + expect(client.signOut).not.toHaveBeenCalled(); + }); + + it('starts sign-in with the Lax sign-in and return-to cookies, keeping only a local returnTo', async () => { + client.isSignedIn.mockResolvedValue(false); + const response: Response = await call('/api/auth/signin?returnTo=/orders&ouId=ou-1', {}, false); + const cookies: string[] = response.headers.getSetCookie(); + + expect(response.status).toBe(302); + expect(response.headers.get('location')).toBe('https://idp.example.com/oauth2/authorize?x=1'); + expect(client.getSignInUrl).toHaveBeenCalledWith({organizationUnitId: 'ou-1'}, SESSION_ID); + expect( + cookies.some( + (cookie: string) => cookie.startsWith(`${STATE_COOKIE}=${SESSION_ID}`) && cookie.includes('SameSite=Lax'), + ), + ).toBe(true); + // The session cookie is set only when sign-in completes. + expect(cookies.some((cookie: string) => cookie.startsWith(`${COOKIE}=`))).toBe(false); + expect(cookies.some((cookie: string) => cookie.startsWith('thunderid-return-to=%2Forders'))).toBe(true); + }); + + it('sends a signed-in user straight back to returnTo', async () => { + const response: Response = await call('/api/auth/signin?returnTo=/orders', {}, false); + + expect(response.headers.get('location')).toBe('/orders'); + expect(client.getSignInUrl).not.toHaveBeenCalled(); + }); + + it('completes sign-in on the callback and moves on from a page, so the Strict session cookie is sent', async () => { + // Only the Lax cookies come back on the identity provider's redirect. + const response: Response = await call( + '/api/auth/callback?code=c&state=s', + {headers: {cookie: `${STATE_COOKIE}=${SESSION_ID}; thunderid-return-to=%2Forders`}}, + false, + ); + + expect(client.signIn).toHaveBeenCalled(); + expect(response.status).toBe(200); + expect(response.headers.get('location')).toBeNull(); + expect(await response.text()).toContain(''); + }); + + it('redirects from the callback when the session cookie is Lax', async () => { + client.getSessionCookieOptions.mockReturnValue({ + httpOnly: true, + maxAge: 1000, + path: '/', + sameSite: 'lax', + secure: false, + }); + const response: Response = await call( + '/api/auth/callback?code=c&state=s', + {headers: {cookie: `${STATE_COOKIE}=${SESSION_ID}; thunderid-return-to=%2Forders`}}, + false, + ); + + expect(response.status).toBe(302); + expect(response.headers.get('location')).toBe('/orders'); + }); + + it('does not complete a callback without a sign-in in progress', async () => { + const response: Response = await call('/api/auth/callback?code=c&state=s', {}, false); + + expect(client.signIn).not.toHaveBeenCalled(); + expect(response.headers.get('location')).toBe('/'); + }); + + it('checks the session without refreshing it', async () => { + const response: Response = await call('/api/auth/checksession'); + + expect(await response.json()).toEqual({isSignedIn: true}); + expect(client.isSignedIn).not.toHaveBeenCalled(); + expect(client.refreshAccessToken).not.toHaveBeenCalled(); + }); + + it('refreshes, or answers 401 login_required when it cannot', async () => { + expect((await call('/api/auth/refresh', {method: 'POST'})).status).toBe(204); + + client.refreshAccessToken.mockRejectedValueOnce(new Error('invalid_grant')); + const failed: Response = await call('/api/auth/refresh', {method: 'POST'}); + + expect(failed.status).toBe(401); + expect(await failed.json()).toEqual({error: 'login_required'}); + expect(client.clearSessionCookie).toHaveBeenCalled(); + }); + + it('ends the stored session when a refresh fails, so checksession agrees with the 401', async () => { + let stored = true; + + client.getSessionData.mockImplementation(() => + Promise.resolve(stored ? {access_token: 'at', created_at: 0, expires_in: '3600', scope: 'openid'} : undefined), + ); + client.endSession.mockImplementation(() => { + stored = false; + + return Promise.resolve(); + }); + client.refreshAccessToken.mockRejectedValueOnce(new Error('invalid_grant')); + + expect((await call('/api/auth/refresh', {method: 'POST'})).status).toBe(401); + expect(await (await call('/api/auth/checksession')).json()).toEqual({isSignedIn: false}); + }); + + it('reports a failure to end the session instead of hiding it', async () => { + client.refreshAccessToken.mockRejectedValueOnce(new Error('invalid_grant')); + client.endSession.mockRejectedValueOnce(new Error('store unavailable')); + + const response: Response = await call('/api/auth/refresh', {method: 'POST'}); + + expect(response.status).toBe(500); + expect(await response.json()).toEqual({error: 'server_error'}); + }); + + it('signs out, clears the cookie and the session, and returns the end-session URL', async () => { + const response: Response = await call('/api/auth/signout', {method: 'POST'}); + + expect(await response.json()).toEqual({redirectUrl: 'https://idp.example.com/oauth2/logout'}); + expect(client.clearSessionCookie).toHaveBeenCalled(); + expect(client.endSession).toHaveBeenCalledWith(SESSION_ID); + }); + + it('switches the organization unit with the device secret', async () => { + const response: Response = await call('/api/auth/switch', { + body: JSON.stringify({ouId: 'ou-2'}), + headers: {'content-type': 'application/json'}, + method: 'POST', + }); + + expect(response.status).toBe(200); + expect(client.switchOrganizationUnitWithDeviceSecret).toHaveBeenCalledWith('ou-2', SESSION_ID); + }); + + it('asks for sign-in for the unit when the session holds no device secret', async () => { + client.switchOrganizationUnitWithDeviceSecret.mockResolvedValueOnce(undefined); + const response: Response = await call('/api/auth/switch?ouId=ou-2', {method: 'POST'}); + + expect(response.status).toBe(400); + expect(await response.json()).toEqual({error: 'interaction_required'}); + }); + + it('proxies an API call with the access token', async () => { + const realFetch: typeof fetch = fetch; + const apiFetch: Mock = vi + .fn() + .mockResolvedValue(new Response('{"id":"u"}', {headers: {'content-type': 'application/json'}})); + + vi.stubGlobal( + 'fetch', + (input: string | URL, init?: RequestInit): Promise => + String(input).startsWith('https://api.example.com') + ? (apiFetch(input, init) as Promise) + : realFetch(input, init), + ); + + const response: Response = await call('/api/auth/proxy/users/me'); + const [target, init] = apiFetch.mock.calls[0] as [string, RequestInit]; + + expect(await response.json()).toEqual({id: 'u'}); + expect(target).toBe('https://api.example.com/users/me'); + expect(new Headers(init.headers).get('authorization')).toBe('Bearer secret-access-token'); + }); + + describe('the proxy', () => { + let apiFetch: Mock; + + beforeEach(() => { + const realFetch: typeof fetch = fetch; + + apiFetch = vi.fn(); + vi.stubGlobal( + 'fetch', + (input: string | URL, init?: RequestInit): Promise => + String(input).startsWith('https://api.example.com') + ? (apiFetch(input, init) as Promise) + : realFetch(input, init), + ); + }); + + it('forwards a form a body parser already read as a form', async () => { + apiFetch.mockResolvedValue(new Response(null, {status: 204})); + + const response: Response = await call('/api/auth/proxy/forms', { + body: 'name=Alice&tag=a&tag=b', + headers: {'content-type': 'application/x-www-form-urlencoded'}, + method: 'POST', + }); + + expect(response.status).toBe(204); + + const [, init] = apiFetch.mock.calls[0] as [string, RequestInit]; + + expect(new Headers(init.headers).get('content-type')).toBe('application/x-www-form-urlencoded'); + expect(await new Response(init.body).text()).toBe('name=Alice&tag=a&tag=b'); + }); + + it('keeps nested fields the extended parser read', async () => { + apiFetch.mockResolvedValue(new Response(null, {status: 204})); + const sent = 'profile[name]=Alice&profile[tags][0]=x&profile[tags][1]=y&items[0][id]=1'; + + await call('/api/auth/proxy/forms', { + body: sent, + headers: {'content-type': 'application/x-www-form-urlencoded'}, + method: 'POST', + }); + + const [, init] = apiFetch.mock.calls[0] as [string, RequestInit]; + + expect(decodeURIComponent(await new Response(init.body).text())).toBe(sent); + }); + + it('streams the response, so events reach the browser before the API closes the stream', async () => { + let push!: (chunk: string) => void; + let close!: () => void; + + apiFetch.mockResolvedValue( + new Response( + new ReadableStream({ + start(controller: ReadableStreamDefaultController): void { + push = (chunk: string): void => controller.enqueue(new Uint8Array(Buffer.from(chunk))); + close = (): void => controller.close(); + }, + }), + {headers: {'content-type': 'text/event-stream'}}, + ), + ); + + const response: Response = await call('/api/auth/proxy/events'); + const reader: ReadableStreamDefaultReader = response.body!.getReader(); + + push('data: first\n\n'); + + expect(Buffer.from((await reader.read()).value!).toString()).toBe('data: first\n\n'); + + close(); + await reader.cancel(); + }); + }); +}); diff --git a/packages/express/src/__tests__/sessionCookie.test.ts b/packages/express/src/__tests__/sessionCookie.test.ts new file mode 100644 index 00000000..4d115e3b --- /dev/null +++ b/packages/express/src/__tests__/sessionCookie.test.ts @@ -0,0 +1,94 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import express from 'express'; +import {afterEach, describe, expect, it, vi} from 'vitest'; +import {ExpressClientConfig} from '../models/config'; +import ThunderIDExpressClient from '../ThunderIDExpressClient'; + +const clientWith = (config: Partial): ThunderIDExpressClient => { + const client = new ThunderIDExpressClient(); + + (client as unknown as {_expressConfig: Partial})._expressConfig = config; + + return client; +}; + +describe('the Express session cookie', () => { + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it('is Secure with the __Host- prefix in production, on Path=/', () => { + vi.stubEnv('NODE_ENV', 'production'); + const client: ThunderIDExpressClient = clientWith({}); + + expect(client.getSessionCookieName()).toBe('__Host-thunderid-session'); + expect(client.getSessionCookieOptions()).toMatchObject({ + httpOnly: true, + path: '/', + sameSite: 'strict', + secure: true, + }); + }); + + it('keeps the plain name when it is not Secure, such as on a plain-HTTP development server', () => { + vi.stubEnv('NODE_ENV', 'development'); + + expect(clientWith({}).getSessionCookieName()).toBe('thunderid-session'); + expect(clientWith({sessionCookie: {secure: true}}).getSessionCookieName()).toBe('__Host-thunderid-session'); + }); + + it('keeps a name the app chose as it is', () => { + vi.stubEnv('NODE_ENV', 'production'); + + expect(clientWith({sessionCookie: {name: 'my_session'}}).getSessionCookieName()).toBe('my_session'); + }); + + it('is deleted with the same attributes it was set with', () => { + vi.stubEnv('NODE_ENV', 'production'); + const clearCookie = vi.fn(); + + clientWith({}).clearSessionCookie({clearCookie} as unknown as express.Response); + + expect(clearCookie).toHaveBeenCalledWith('__Host-thunderid-session', { + httpOnly: true, + path: '/', + sameSite: 'strict', + secure: true, + }); + }); + + it('is Lax only when the app asks, with a warning', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + + expect(clientWith({sessionCookie: {sameSite: 'lax'}}).getSessionCookieOptions().sameSite).toBe('lax'); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('RFC 10017')); + }); +}); + +describe('the Express sign-in cookie', () => { + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it('is Lax, so it comes back on the redirect to the callback, and Secure with __Host- in production', () => { + vi.stubEnv('NODE_ENV', 'production'); + const client: ThunderIDExpressClient = clientWith({}); + + expect(client.getSessionStateCookieName()).toBe('__Host-thunderid-session-state'); + expect(client.getSessionStateCookieOptions()).toEqual({ + httpOnly: true, + maxAge: 900_000, + path: '/', + sameSite: 'lax', + secure: true, + }); + }); + + it('is named thunderid-session-state on a plain-HTTP development server', () => { + vi.stubEnv('NODE_ENV', 'development'); + + expect(clientWith({}).getSessionStateCookieName()).toBe('thunderid-session-state'); + }); +}); diff --git a/packages/express/src/constants/CookieConfig.ts b/packages/express/src/constants/CookieConfig.ts index 6669f1fc..2faf83b9 100644 --- a/packages/express/src/constants/CookieConfig.ts +++ b/packages/express/src/constants/CookieConfig.ts @@ -5,7 +5,13 @@ const CookieConfig = { defaultExpirySeconds: 86400, defaultHttpOnly: true, - defaultSameSite: 'lax' as const, + defaultSameSite: 'strict' as const, + /** How long a sign-in may take before the cookie that carries it expires, in seconds. */ + sessionStateMaxAgeSeconds: 900, + /** + * @deprecated No longer read. The session cookie is `Secure` by default in production; see + * `ThunderIDExpressClient.getSessionCookieOptions()`. + */ defaultSecure: false, }; diff --git a/packages/express/src/index.ts b/packages/express/src/index.ts index e5da4335..3453cfb8 100644 --- a/packages/express/src/index.ts +++ b/packages/express/src/index.ts @@ -9,6 +9,8 @@ export {thunderID, handleSignIn, handleSignOut} from './middleware/authenticatio export {default as protect} from './middleware/protect'; export {default as handleFlow} from './middleware/flow'; export {default as handleBackchannelLogout} from './middleware/backchannelLogout'; +export {default as thunderIDBff} from './middleware/bff'; +export type {ThunderIDBffOptions} from './middleware/bff'; export {default as requireAccess} from './middleware/requireAccess'; export type {RequireAccessOptions} from './middleware/requireAccess'; diff --git a/packages/express/src/middleware/authentication.ts b/packages/express/src/middleware/authentication.ts index 85c12aa4..dd79f51b 100644 --- a/packages/express/src/middleware/authentication.ts +++ b/packages/express/src/middleware/authentication.ts @@ -1,7 +1,7 @@ // Copyright 2025 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 -import {ThunderIDRuntimeError, TokenResponse, logger as Logger} from '@thunderid/node'; +import {ThunderIDRuntimeError, TokenResponse, logger as Logger, renderSignInContinuePage} from '@thunderid/node'; import express from 'express'; import {ThunderIDExpressConfig} from '../models/config'; import ThunderIDExpressClient from '../ThunderIDExpressClient'; @@ -45,6 +45,22 @@ const thunderID = (config: ThunderIDExpressConfig): express.RequestHandler => { }; }; +/** + * Makes `res.redirect` answer with a page that moves on to the target, instead of a `302`. A redirect from the + * callback still belongs to the identity provider's cross-site chain, so the browser would leave out the `Strict` + * session cookie just set, and a protected page would send the user back through sign-in without end. + */ +const continueWithPage = (res: express.Response): void => { + res.redirect = ((first: string | number, second?: string): void => { + const target: string = typeof first === 'string' ? first : (second ?? '/'); + + res + .status(200) + .set({'cache-control': 'no-store', 'content-type': 'text/html; charset=utf-8'}) + .send(renderSignInContinuePage(target)); + }) as express.Response['redirect']; +}; + /** * Returns an Express route handler for the sign-in path. * @@ -80,6 +96,9 @@ const handleSignIn = (): express.RequestHandler => { try { const response: TokenResponse = await client.signIn(req, res, next, config?.signInOptions); if (response.accessToken || response.idToken) { + if (client.getSessionCookieOptions().sameSite === 'strict') { + continueWithPage(res); + } onSignIn(res, response); } } catch (e: any) { @@ -141,7 +160,7 @@ const handleSignOut = (): express.RequestHandler => { try { const signOutURL: string = await client.signOut(sessionId); if (signOutURL) { - res.cookie(cookieName, null, {maxAge: 0}); + client.clearSessionCookie(res); res.redirect(signOutURL); } } catch (e: any) { diff --git a/packages/express/src/middleware/bff.ts b/packages/express/src/middleware/bff.ts new file mode 100644 index 00000000..eb7265c0 --- /dev/null +++ b/packages/express/src/middleware/bff.ts @@ -0,0 +1,358 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {Readable} from 'node:stream'; +import {pipeline} from 'node:stream/promises'; +import type {ReadableStream as NodeReadableStream} from 'node:stream/web'; +import { + BffAdapter, + BffConstants, + BffOptions, + BffSession, + BffSwitchResult, + CookieConfig as NodeCookieConfig, + DeviceSecretSwitchResult, + ExtendedAuthorizeRequestUrlParams, + IdToken, + SessionData, + bffRedirect, + bffSignedIn, + getVendorPrefix, + handleBffRequest, + logger as Logger, + toSafeReturnTo, +} from '@thunderid/node'; +import express from 'express'; +import {v4 as uuidv4} from 'uuid'; +import handleBackchannelLogout from './backchannelLogout'; +import ThunderIDExpressClient from '../ThunderIDExpressClient'; + +/** How long sign-in may take before the place to return to is forgotten, in milliseconds. */ +const RETURN_TO_MAX_AGE = 10 * 60 * 1000; + +type RequestWithClient = express.Request & {thunderIDAuth?: ThunderIDExpressClient}; + +/** + * How the Express BFF is set up. Every field is optional. + */ +export interface ThunderIDBffOptions extends BffOptions { + /** + * The API the proxy forwards to. Defaults to the ThunderID `baseUrl`, so the SDK's components that + * call ThunderID's own APIs, such as the user profile, work through the proxy. + */ + apiBaseUrl?: string; + /** + * The origins a state-changing request may come from. Defaults to the origin of `afterSignInUrl`, + * which is the app's origin. + */ + allowedOrigins?: string[]; +} + +/** + * Encodes fields a body parser already read back as a form. Nested objects and arrays use the bracket notation + * that `express.urlencoded({extended: true})` reads, so the API receives the fields the browser sent. + */ +const toFormBody = (fields: Record): string => { + const form = new URLSearchParams(); + + const append = (name: string, value: unknown, nested: boolean): void => { + if (Array.isArray(value)) { + // A top-level array came from a repeated field, which both parsers read back as an array. A nested one needs + // its index, which only the extended parser produces. + value.forEach((item: unknown, index: number) => + append(nested || (item !== null && typeof item === 'object') ? `${name}[${index}]` : name, item, nested), + ); + } else if (value !== null && typeof value === 'object') { + Object.entries(value).forEach(([key, item]: [string, unknown]) => append(`${name}[${key}]`, item, true)); + } else { + form.append(name, value === undefined || value === null ? '' : String(value as string | number | boolean)); + } + }; + + Object.entries(fields).forEach(([name, value]: [string, unknown]) => append(name, value, false)); + + return form.toString(); +}; + +const toWebRequest = (req: express.Request): Request => { + const url = `${req.protocol}://${req.get('host') ?? 'localhost'}${req.originalUrl}`; + const headers = new Headers(); + + Object.entries(req.headers).forEach(([name, value]: [string, string | string[] | undefined]) => { + if (Array.isArray(value)) { + value.forEach((item: string) => headers.append(name, item)); + } else if (value !== undefined) { + headers.set(name, value); + } + }); + + if (['GET', 'HEAD'].includes(req.method)) { + return new Request(url, {headers, method: req.method}); + } + + // A body parser mounted earlier may have read the body already. + const parsed: unknown = req.body; + let body: RequestInit['body']; + + if (Buffer.isBuffer(parsed)) { + body = new Uint8Array(parsed); + } else if (typeof parsed === 'string') { + body = parsed; + } else if (parsed !== undefined && parsed !== null && typeof parsed === 'object' && req.readableEnded) { + // Re-encode in the request's own media type, so the API reads the fields the browser sent. + body = req.is('application/x-www-form-urlencoded') + ? toFormBody(parsed as Record) + : JSON.stringify(parsed); + } else if (!req.readableEnded) { + body = Readable.toWeb(req) as unknown as RequestInit['body']; + } + + return new Request(url, {body, duplex: 'half', headers, method: req.method} as RequestInit); +}; + +const sendWebResponse = async (response: Response, res: express.Response): Promise => { + res.status(response.status); + response.headers.forEach((value: string, name: string) => { + res.setHeader(name, value); + }); + + if (!response.body) { + res.end(); + + return; + } + + // Sends the status and headers now, so the browser does not wait for the first chunk. + res.flushHeaders(); + + // Streamed, so an event stream from the API reaches the browser as it arrives. `pipeline` applies + // backpressure and cancels the upstream body if the browser goes away. + await pipeline(Readable.fromWeb(response.body as unknown as NodeReadableStream), res); +}; + +const createAdapter = (client: ThunderIDExpressClient, req: express.Request, res: express.Response): BffAdapter => { + const cookies = (): Record => + (req.cookies as Record | undefined) ?? {}; + const sessionIdOf = (): string | undefined => cookies()[client.getSessionCookieName()]; + const {secure} = client.getSessionCookieOptions(); + const returnToCookie: string = NodeCookieConfig.withHostPrefix( + `${getVendorPrefix(client.expressConfig?.vendor)}-return-to`, + secure, + ); + const returnToAttributes: express.CookieOptions = {httpOnly: true, path: '/', sameSite: 'lax', secure}; + + const readSession = async (sessionId: string): Promise => { + const data: SessionData | undefined = await client.getSessionData(sessionId); + + if (!data) { + return null; + } + + const claims: IdToken = await client.getDecodedIdToken(sessionId); + + return { + accessToken: data.access_token, + expiresAt: Math.floor((data.created_at + Number(data.expires_in) * 1000) / 1000), + idTokenClaims: claims as Record, + scope: data.scope, + }; + }; + + return { + async callback(): Promise { + const returnTo: string = toSafeReturnTo(cookies()[returnToCookie]); + + res.clearCookie(returnToCookie, returnToAttributes); + + const error: unknown = req.query['error']; + + if (error || !cookies()[client.getSessionStateCookieName()]) { + Logger.warn(`Sign-in did not complete: ${typeof error === 'string' ? error : 'no sign-in in progress'}.`); + client.clearSessionStateCookie(res); + + return bffRedirect('/'); + } + + // Checks the state, exchanges the code, then sets the session cookie and clears the sign-in cookie. + await client.signIn(req, res); + + return bffSignedIn(returnTo, client.getSessionCookieOptions().sameSite as string); + }, + + async getSession(): Promise { + const sessionId: string | undefined = sessionIdOf(); + + // Refreshes an expired access token, and forgets a session that cannot be refreshed. + return sessionId && (await client.isSignedIn(sessionId)) ? readSession(sessionId) : null; + }, + + async isSessionLive(): Promise { + const sessionId: string | undefined = sessionIdOf(); + + if (!sessionId) { + return false; + } + + // Only looks: a back-channel logout removes the session, and nothing here refreshes it. + return Boolean(await client.getSessionData(sessionId)); + }, + + async refresh(): Promise { + const sessionId: string | undefined = sessionIdOf(); + + if (!sessionId) { + return false; + } + + try { + await client.refreshAccessToken(sessionId); + + return true; + } catch { + // The contract ends the session when a refresh fails, so `checksession` agrees with the `401`. + client.clearSessionCookie(res); + // A failed deletion is not hidden: the session would otherwise outlive the 401. + await client.endSession(sessionId); + + return false; + } + }, + + async signIn(_request: Request, {ouId, returnTo}: {ouId?: string; returnTo: string}): Promise { + let sessionId: string | undefined = sessionIdOf(); + + if (sessionId && !ouId && (await client.isSignedIn(sessionId))) { + return bffRedirect(returnTo); + } + + sessionId ??= uuidv4(); + + const signInConfig: ExtendedAuthorizeRequestUrlParams = { + ...client.expressConfig?.signInOptions, + ...(ouId ? {organizationUnitId: ouId} : {}), + } as ExtendedAuthorizeRequestUrlParams; + const url: string = await client.getSignInUrl(signInConfig, sessionId); + + // The session cookie is set at the callback, once sign-in completes. + res.cookie(client.getSessionStateCookieName(), sessionId, client.getSessionStateCookieOptions()); + res.cookie(returnToCookie, returnTo, {...returnToAttributes, maxAge: RETURN_TO_MAX_AGE}); + + return bffRedirect(url); + }, + + async signOut(): Promise<{redirectUrl: string}> { + const sessionId: string | undefined = sessionIdOf(); + const fallback: string = client.expressConfig?.afterSignOutUrl ?? '/'; + + client.clearSessionCookie(res); + + if (!sessionId) { + return {redirectUrl: fallback}; + } + + try { + // Built before the session is cleared, so it carries the ID token as `id_token_hint`. + const redirectUrl: string = await client.signOut(sessionId); + + return {redirectUrl}; + } catch { + return {redirectUrl: fallback}; + } finally { + // Awaited, so the session cannot be used once sign-out has answered. + await client.endSession(sessionId); + } + }, + + async switchOrganizationUnit(_request: Request, ouId: string): Promise { + const sessionId: string | undefined = sessionIdOf(); + + if (!sessionId || !(await client.isSignedIn(sessionId))) { + return {error: BffConstants.Errors.LOGIN_REQUIRED, status: 401}; + } + + const result: DeviceSecretSwitchResult | undefined = await client.switchOrganizationUnitWithDeviceSecret( + ouId, + sessionId, + ); + + if (!result) { + // No device secret in the session: the browser switches through sign-in for the unit. + return {error: 'interaction_required'}; + } + + return 'error' in result ? {error: result.error} : {ok: true}; + }, + }; +}; + +/** + * Serves the BFF contract of RFC 10017 from Express, so a React or Vue app in `backend` mode can use + * this server as its BFF. Mount it after `thunderID()`: + * + * ```ts + * app.use(cookieParser()); + * app.use(thunderID({...config, afterSignInUrl: 'https://app.example.com/api/auth/callback'})); + * app.use(thunderIDBff()); + * ``` + * + * It serves, under `/api/auth`: `GET signin`, `GET callback`, `GET session`, `GET checksession`, + * `POST refresh`, `POST signout`, `POST switch`, `POST backchannel-logout` and the API proxy under + * `proxy/`. Every call the browser SDK makes must carry `X-Requested-With: XMLHttpRequest`, and no + * response carries a token. `afterSignInUrl` must be the `callback` endpoint on the app's origin. + * + * The session is kept in the SDK's session store, and the cookie holds only its ID. Requests outside + * the prefix go on to the next handler. It needs `cookie-parser` mounted first. + * + * @param options - The prefix, the API to proxy to, and the allowed origins. + */ +const thunderIDBff = (options: ThunderIDBffOptions = {}): express.RequestHandler => { + const prefix: string = (options.prefix ?? BffConstants.DEFAULT_PREFIX).replace(/\/+$/, ''); + const backchannelLogout: express.RequestHandler = handleBackchannelLogout(); + let warnedAboutCallback = false; + + return (req: express.Request, res: express.Response, next: express.NextFunction): void => { + const path: string = req.originalUrl.split('?')[0] ?? ''; + + if (path !== prefix && !path.startsWith(`${prefix}/`)) { + next(); + + return; + } + + const client: ThunderIDExpressClient | undefined = (req as RequestWithClient).thunderIDAuth; + + if (!client) { + Logger.error('thunderID() middleware must be mounted before thunderIDBff()'); + res.status(500).end(); + + return; + } + + if (path === `${prefix}${BffConstants.Endpoints.BACKCHANNEL_LOGOUT}`) { + backchannelLogout(req, res, next); + + return; + } + + const config = client.expressConfig; + const appOrigin: string | undefined = config?.afterSignInUrl ? new URL(config.afterSignInUrl).origin : undefined; + + if (!warnedAboutCallback && config?.afterSignInUrl) { + warnedAboutCallback = true; + if (new URL(config.afterSignInUrl).pathname !== `${prefix}${BffConstants.Endpoints.CALLBACK}`) { + Logger.warn(`afterSignInUrl should be ${prefix}${BffConstants.Endpoints.CALLBACK} on the app's origin.`); + } + } + + handleBffRequest(toWebRequest(req), createAdapter(client, req, res), { + ...options, + allowedOrigins: options.allowedOrigins ?? (appOrigin ? [appOrigin] : undefined), + apiBaseUrl: options.apiBaseUrl ?? config?.baseUrl, + prefix, + }) + .then((response: Response | undefined) => (response ? sendWebResponse(response, res) : next())) + .catch(next); + }; +}; + +export default thunderIDBff; diff --git a/packages/express/src/models/config.ts b/packages/express/src/models/config.ts index 42dfc506..66a6793b 100644 --- a/packages/express/src/models/config.ts +++ b/packages/express/src/models/config.ts @@ -40,7 +40,7 @@ export interface StrictExpressClientConfig { * * Inherits `vendor` and `sessionCookie.name` from `ThunderIDNodeConfig` — set * either to control the session cookie name written by this SDK (default: - * `__thunderid__session`, the same `@thunderid/node` `CookieConfig` naming + * `thunderid-session`, the same `@thunderid/node` `CookieConfig` naming * convention used by every server-side ThunderID SDK, derived from `vendor` * defaulting to `'thunderid'`). `sessionCookie.name` takes priority over the * `vendor`-derived default. diff --git a/packages/javascript/CHANGELOG.md b/packages/javascript/CHANGELOG.md index db477693..5368bb8a 100644 --- a/packages/javascript/CHANGELOG.md +++ b/packages/javascript/CHANGELOG.md @@ -2,11 +2,15 @@ No changes to this SDK since sdk/javascript/v1.27.0. -**Full Changelog**: https://github.com/thunder-id/javascript-sdks/compare/sdk/javascript/v1.27.0...sdk/javascript/v1.27.1 +**Full Changelog**: +https://github.com/thunder-id/javascript-sdks/compare/sdk/javascript/v1.27.0...sdk/javascript/v1.27.1 ## 1.27.0 ### 📝 Other Changes -* Add opt-in telemetry for page views, API calls, sign-ins and outbound links by @bhagyasakalanka in https://github.com/thunder-id/javascript-sdks/pull/188 -**Full Changelog**: https://github.com/thunder-id/javascript-sdks/compare/sdk/javascript/v1.26.0...sdk/javascript/v1.27.0 +- Add opt-in telemetry for page views, API calls, sign-ins and outbound links by @bhagyasakalanka in + https://github.com/thunder-id/javascript-sdks/pull/188 + +**Full Changelog**: +https://github.com/thunder-id/javascript-sdks/compare/sdk/javascript/v1.26.0...sdk/javascript/v1.27.0 diff --git a/packages/nextjs/CHANGELOG.md b/packages/nextjs/CHANGELOG.md index adcfb057..40f864bf 100644 --- a/packages/nextjs/CHANGELOG.md +++ b/packages/nextjs/CHANGELOG.md @@ -7,6 +7,8 @@ No changes to this SDK since sdk/nextjs/v1.24.0. ## 1.24.0 ### 📝 Other Changes -* Add opt-in telemetry for page views, API calls, sign-ins and outbound links by @bhagyasakalanka in https://github.com/thunder-id/javascript-sdks/pull/188 + +- Add opt-in telemetry for page views, API calls, sign-ins and outbound links by @bhagyasakalanka in + https://github.com/thunder-id/javascript-sdks/pull/188 **Full Changelog**: https://github.com/thunder-id/javascript-sdks/compare/sdk/nextjs/v1.23.0...sdk/nextjs/v1.24.0 diff --git a/packages/nextjs/src/server/__tests__/bff.test.ts b/packages/nextjs/src/server/__tests__/bff.test.ts new file mode 100644 index 00000000..0fb55da1 --- /dev/null +++ b/packages/nextjs/src/server/__tests__/bff.test.ts @@ -0,0 +1,208 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {afterEach, beforeEach, describe, expect, it, Mock, vi} from 'vitest'; +import SessionManager from '../../utils/SessionManager'; +import thunderIDBff from '../bff'; +import getClient from '../getClient'; + +/** A cookie jar standing in for `cookies()` from `next/headers`. */ +class Jar { + readonly values: Map = new Map(); + + readonly deleted: {name: string; secure?: boolean}[] = []; + + delete(cookie: {name: string; secure?: boolean}): void { + this.deleted.push(cookie); + this.values.delete(cookie.name); + } + + get(name: string): {value: string} | undefined { + const value: string | undefined = this.values.get(name); + + return value === undefined ? undefined : {value}; + } + + getAll(): {name: string}[] { + return [...this.values.keys()].map((name: string) => ({name})); + } + + set(name: string, value: string): void { + this.values.set(name, value); + } +} + +let jar: Jar; + +vi.mock('next/headers', () => ({cookies: vi.fn(() => Promise.resolve(jar))})); +vi.mock('../getClient', () => ({default: vi.fn()})); + +const ORIGIN = 'http://localhost:3000'; + +// An unsigned ID token: only its claims are read here. +const ID_TOKEN = `e30.${Buffer.from(JSON.stringify({email: 'a@example.com', nonce: 'n', sid: 's', sub: 'user-1'})).toString('base64url')}.`; + +const sdkCall = (path: string, init: RequestInit = {}): Request => + new Request(`${ORIGIN}/api/auth${path}`, { + ...init, + headers: {'sec-fetch-site': 'same-origin', 'x-requested-with': 'XMLHttpRequest', ...(init.headers ?? {})}, + }); + +const signIn = async (ttlSeconds = 3600): Promise => { + jar.set( + SessionManager.getSessionCookieName(), + await SessionManager.createSessionToken( + 'secret-access-token', + 'user-1', + 'session-1', + 'openid', + ttlSeconds, + 'rt', + undefined, + { + idToken: ID_TOKEN, + sid: 's', + }, + ), + ); +}; + +describe('thunderIDBff (Next.js)', () => { + let client: Record; + const {GET, POST} = thunderIDBff({apiBaseUrl: 'https://api.example.com'}); + + beforeEach(() => { + vi.stubEnv('THUNDERID_SESSION_SECRET', 'a-session-secret-that-is-at-least-32-bytes'); + jar = new Jar(); + client = { + getAuthorizeRequestUrl: vi.fn().mockResolvedValue('https://idp.example.com/oauth2/authorize?x=1'), + getConfiguration: vi.fn().mockResolvedValue({ + afterSignInUrl: `${ORIGIN}/api/auth/callback`, + baseUrl: 'https://idp.example.com', + clientId: 'c', + }), + getDecodedIdToken: vi.fn().mockResolvedValue({sid: 's', sub: 'user-1'}), + signIn: vi.fn().mockResolvedValue({ + accessToken: 'new-access-token', + expiresIn: 3600, + idToken: ID_TOKEN, + refreshToken: 'rt', + scope: 'openid', + }), + }; + Object.defineProperty(client, 'isInitialized', {value: true}); + (getClient as unknown as Mock).mockReturnValue(client); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + }); + + it('reports the user from the ID token in the cookie, without any token', async () => { + await signIn(); + const response: Response = await GET(sdkCall('/session')); + const text: string = await response.text(); + + expect(JSON.parse(text)).toMatchObject({ + isSignedIn: true, + scope: 'openid', + user: {email: 'a@example.com', sub: 'user-1'}, + }); + expect((JSON.parse(text) as {user: object}).user).not.toHaveProperty('nonce'); + expect(text).not.toContain('secret-access-token'); + }); + + it('reports a signed-out session without a cookie', async () => { + expect(await (await GET(sdkCall('/session'))).json()).toEqual({isSignedIn: false}); + expect(await (await GET(sdkCall('/checksession'))).json()).toEqual({isSignedIn: false}); + }); + + it('refuses a call without the request header', async () => { + await signIn(); + + expect((await GET(new Request(`${ORIGIN}/api/auth/session`))).status).toBe(403); + }); + + it('starts sign-in with a temporary cookie that remembers where to return', async () => { + const response: Response = await GET(new Request(`${ORIGIN}/api/auth/signin?returnTo=/orders`)); + const temp: string | undefined = jar.get(SessionManager.getTempSessionCookieName())?.value; + + expect(response.status).toBe(302); + expect(response.headers.get('location')).toBe('https://idp.example.com/oauth2/authorize?x=1'); + expect(await SessionManager.verifyTempSession(temp ?? '')).toMatchObject({returnTo: '/orders'}); + }); + + it('completes sign-in on the callback, writes the encrypted session and moves on from a page', async () => { + jar.set(SessionManager.getTempSessionCookieName(), await SessionManager.createTempSession('session-1', '/orders')); + + const response: Response = await GET(new Request(`${ORIGIN}/api/auth/callback?code=c&state=s`)); + const session = await SessionManager.verifySessionToken( + jar.get(SessionManager.getSessionCookieName())?.value ?? '', + ); + + expect(client.signIn).toHaveBeenCalledWith({code: 'c', state: 's'}, {}, 'session-1'); + // The session cookie is Strict, and a redirect from the callback would leave it out. + expect(response.status).toBe(200); + expect(await response.text()).toContain('content="0;url=/orders"'); + expect(session).toMatchObject({accessToken: 'new-access-token', idToken: ID_TOKEN, sessionId: 'session-1'}); + expect(jar.get(SessionManager.getTempSessionCookieName())).toBeUndefined(); + }); + + it('redirects from the callback when THUNDERID_SESSION_COOKIE_SAME_SITE is lax', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined); + vi.stubEnv('THUNDERID_SESSION_COOKIE_SAME_SITE', 'lax'); + jar.set(SessionManager.getTempSessionCookieName(), await SessionManager.createTempSession('session-1', '/orders')); + + const response: Response = await GET(new Request(`${ORIGIN}/api/auth/callback?code=c&state=s`)); + + expect(response.status).toBe(302); + expect(response.headers.get('location')).toBe('/orders'); + vi.unstubAllEnvs(); + }); + + it('refreshes an expired access token when the session is read', async () => { + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue( + new Response(JSON.stringify({access_token: 'refreshed-token', expires_in: 3600, scope: 'openid'}), { + status: 200, + }), + ), + ); + await signIn(-10); + + const body = (await (await GET(sdkCall('/session'))).json()) as {isSignedIn: boolean}; + const session = await SessionManager.verifySessionToken( + jar.get(SessionManager.getSessionCookieName())?.value ?? '', + ); + + expect(body.isSignedIn).toBe(true); + expect(session.accessToken).toBe('refreshed-token'); + expect(session.idToken).toBe(ID_TOKEN); + }); + + it('answers a failed refresh with 401 login_required and clears the cookie', async () => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('{}', {status: 400}))); + await signIn(-10); + + const response: Response = await POST(sdkCall('/refresh', {method: 'POST'})); + + expect(response.status).toBe(401); + expect(await response.json()).toEqual({error: 'login_required'}); + expect(jar.get(SessionManager.getSessionCookieName())).toBeUndefined(); + }); + + it('proxies an API call with the access token from the cookie', async () => { + const apiFetch: Mock = vi.fn().mockResolvedValue(new Response('{"id":"u"}')); + + vi.stubGlobal('fetch', apiFetch); + await signIn(); + + await GET(sdkCall('/proxy/users/me')); + const [target, init] = apiFetch.mock.calls[0] as [string, RequestInit]; + + expect(target).toBe('https://api.example.com/users/me'); + expect(new Headers(init.headers).get('authorization')).toBe('Bearer secret-access-token'); + }); +}); diff --git a/packages/nextjs/src/server/actions/auth/__tests__/signOutAction.test.ts b/packages/nextjs/src/server/actions/auth/__tests__/signOutAction.test.ts index db46bff4..52e6d8be 100644 --- a/packages/nextjs/src/server/actions/auth/__tests__/signOutAction.test.ts +++ b/packages/nextjs/src/server/actions/auth/__tests__/signOutAction.test.ts @@ -3,10 +3,9 @@ import {cookies} from 'next/headers'; import {afterEach, beforeEach, describe, expect, it, Mock, vi} from 'vitest'; -import {deleteChunkedCookie} from '../../../../utils/chunkedCookie'; +import {deleteChunkedCookie, getChunkedCookie} from '../../../../utils/chunkedCookie'; import SessionManager from '../../../../utils/SessionManager'; import getClient from '../../../getClient'; -import getSessionId from '../../getSessionId'; import signOutAction from '../signOutAction'; vi.mock('next/headers', () => ({ @@ -17,23 +16,32 @@ vi.mock('../../../getClient', () => ({ default: vi.fn(), })); -vi.mock('../../getSessionId', () => ({ - default: vi.fn(), -})); - vi.mock('../../../../utils/SessionManager', () => ({ default: { getSessionCookieName: vi.fn(), + getSessionCookieOptions: vi.fn(), getTempSessionCookieName: vi.fn(), + getTempSessionCookieOptions: vi.fn(), + verifySessionTokenForRefresh: vi.fn(), }, })); -vi.mock('../../../../utils/chunkedCookie', () => ({ +vi.mock('../../../../utils/chunkedCookie', async (importOriginal: () => Promise) => ({ + ...(await importOriginal()), deleteChunkedCookie: vi.fn(), + getChunkedCookie: vi.fn(), })); +/** A session cookie whose payload carries `sessionId`, or no cookie at all. */ +const withSession = (sessionId?: string): void => { + (getChunkedCookie as unknown as Mock).mockReturnValue(sessionId ? 'sealed' : undefined); + (SessionManager.verifySessionTokenForRefresh as unknown as Mock).mockResolvedValue({sessionId}); +}; + const END_SESSION_URL = 'https://localhost:8090/oauth2/logout?id_token_hint=id-token'; +const COOKIE_OPTIONS = {httpOnly: true, maxAge: 0, path: '/', sameSite: 'lax' as const, secure: true}; + describe('signOutAction', () => { let signOut: Mock; let deleteCookie: Mock; @@ -47,6 +55,8 @@ describe('signOutAction', () => { (cookies as unknown as Mock).mockResolvedValue({delete: deleteCookie}); (SessionManager.getSessionCookieName as unknown as Mock).mockReturnValue('session'); (SessionManager.getTempSessionCookieName as unknown as Mock).mockReturnValue('temp'); + (SessionManager.getSessionCookieOptions as unknown as Mock).mockReturnValue(COOKIE_OPTIONS); + (SessionManager.getTempSessionCookieOptions as unknown as Mock).mockReturnValue({...COOKIE_OPTIONS, maxAge: 900}); }); afterEach(() => { @@ -54,18 +64,38 @@ describe('signOutAction', () => { }); it('returns the end-session URL and clears the session cookies', async () => { - (getSessionId as unknown as Mock).mockResolvedValue('session-1'); + withSession('session-1'); const result = await signOutAction(); expect(signOut).toHaveBeenCalledWith({}, 'session-1'); expect(result).toEqual({data: {signOutUrl: END_SESSION_URL}, success: true}); - expect(deleteChunkedCookie).toHaveBeenCalledWith(expect.anything(), 'session'); - expect(deleteCookie).toHaveBeenCalledWith('temp'); + expect(deleteChunkedCookie).toHaveBeenCalledWith(expect.anything(), 'session', COOKIE_OPTIONS); + expect(deleteCookie).toHaveBeenCalledWith({httpOnly: true, name: 'temp', path: '/', sameSite: 'lax', secure: true}); + }); + + it('ends the server session when the access token has expired', async () => { + withSession('session-1'); + + await signOutAction(); + + // Read without the expiry check, so an expired access token still identifies the session. + expect(SessionManager.verifySessionTokenForRefresh as unknown as Mock).toHaveBeenCalledWith('sealed'); + expect(signOut).toHaveBeenCalledWith({}, 'session-1'); + }); + + it('does not ask the server when the cookie cannot be read', async () => { + (getChunkedCookie as unknown as Mock).mockReturnValue('tampered'); + (SessionManager.verifySessionTokenForRefresh as unknown as Mock).mockRejectedValue(new Error('undecryptable')); + + const result = await signOutAction(); + + expect(signOut).not.toHaveBeenCalled(); + expect(result).toEqual({data: {signOutUrl: '/'}, success: true}); }); it('succeeds without a session, without asking the server', async () => { - (getSessionId as unknown as Mock).mockResolvedValue(undefined); + withSession(); const result = await signOutAction(); @@ -74,13 +104,13 @@ describe('signOutAction', () => { }); it('still clears the session cookies when sign-out fails', async () => { - (getSessionId as unknown as Mock).mockResolvedValue('session-1'); + withSession('session-1'); signOut.mockRejectedValue(new Error('network down')); const result = await signOutAction(); expect(result).toEqual({error: 'network down', success: false}); - expect(deleteChunkedCookie).toHaveBeenCalledWith(expect.anything(), 'session'); - expect(deleteCookie).toHaveBeenCalledWith('temp'); + expect(deleteChunkedCookie).toHaveBeenCalledWith(expect.anything(), 'session', COOKIE_OPTIONS); + expect(deleteCookie).toHaveBeenCalledWith({httpOnly: true, name: 'temp', path: '/', sameSite: 'lax', secure: true}); }); }); diff --git a/packages/nextjs/src/server/actions/auth/handleOAuthCallbackAction.ts b/packages/nextjs/src/server/actions/auth/handleOAuthCallbackAction.ts index 1c78a4b9..809ed2b5 100644 --- a/packages/nextjs/src/server/actions/auth/handleOAuthCallbackAction.ts +++ b/packages/nextjs/src/server/actions/auth/handleOAuthCallbackAction.ts @@ -5,6 +5,7 @@ import {cookies} from 'next/headers'; import {ThunderIDNextConfig} from '../../../models/config'; +import {toCookieDeletion} from '../../../utils/chunkedCookie'; import logger from '../../../utils/logger'; import SessionManager from '../../../utils/SessionManager'; import setSessionCookie from '../../../utils/setSessionCookie'; @@ -93,7 +94,9 @@ const handleOAuthCallbackAction = async ( try { await setSessionCookie(thunderIDClient, cookieStore, sessionId, signInResult, config); - cookieStore.delete(SessionManager.getTempSessionCookieName()); + cookieStore.delete( + toCookieDeletion(SessionManager.getTempSessionCookieName(), SessionManager.getTempSessionCookieOptions()), + ); } catch (error) { logger.error( `[handleOAuthCallbackAction] Failed to create JWT session, continuing with legacy session: diff --git a/packages/nextjs/src/server/actions/auth/signInAction.ts b/packages/nextjs/src/server/actions/auth/signInAction.ts index e2be25fe..0ada5a24 100644 --- a/packages/nextjs/src/server/actions/auth/signInAction.ts +++ b/packages/nextjs/src/server/actions/auth/signInAction.ts @@ -14,7 +14,7 @@ import { } from '@thunderid/node'; import {cookies} from 'next/headers'; import {ThunderIDNextConfig} from '../../../models/config'; -import {getChunkedCookie, setChunkedCookie} from '../../../utils/chunkedCookie'; +import {getChunkedCookie, setChunkedCookie, toCookieDeletion} from '../../../utils/chunkedCookie'; import logger from '../../../utils/logger'; import SessionManager, {SessionTokenPayload} from '../../../utils/SessionManager'; import getClient from '../../getClient'; @@ -107,7 +107,9 @@ const signInAction = async ( throw new Error('[signInAction] Flow completed without an assertion.'); } - const idToken: IdToken = await client.getDecodedIdToken(sessionId, response.assertion); + const assertion: string = response.assertion as string; + + const idToken: IdToken = await client.getDecodedIdToken(sessionId, assertion); const userIdFromToken: string = (idToken.sub as string | undefined) ?? sessionId; const organizationId: string | undefined = (idToken['user_org'] || idToken['organization_id']) as | string @@ -123,14 +125,15 @@ const signInAction = async ( ); const sessionToken: string = await SessionManager.createSessionToken( - response.assertion, + assertion, userIdFromToken, sessionId, scopes, expiresIn, '', organizationId, - {sid: typeof idToken['sid'] === 'string' ? idToken['sid'] : undefined}, + // The assertion is the ID token of an embedded sign-in. + {idToken: assertion, sid: typeof idToken['sid'] === 'string' ? idToken['sid'] : undefined}, ); setChunkedCookie( @@ -140,7 +143,9 @@ const signInAction = async ( SessionManager.getSessionCookieOptions(sessionCookieExpiryTime), ); - cookieStore.delete(SessionManager.getTempSessionCookieName()); + cookieStore.delete( + toCookieDeletion(SessionManager.getTempSessionCookieName(), SessionManager.getTempSessionCookieOptions()), + ); const afterSignInUrl: string = await (await client.getStorageManager()).getConfigDataParameter('afterSignInUrl'); return {data: {afterSignInUrl: String(afterSignInUrl)}, success: true}; diff --git a/packages/nextjs/src/server/actions/auth/signOutAction.ts b/packages/nextjs/src/server/actions/auth/signOutAction.ts index 68058ec6..77f85fe0 100644 --- a/packages/nextjs/src/server/actions/auth/signOutAction.ts +++ b/packages/nextjs/src/server/actions/auth/signOutAction.ts @@ -4,14 +4,32 @@ 'use server'; import {cookies} from 'next/headers'; -import {deleteChunkedCookie} from '../../../utils/chunkedCookie'; +import {deleteChunkedCookie, getChunkedCookie, toCookieDeletion} from '../../../utils/chunkedCookie'; import logger from '../../../utils/logger'; import SessionManager from '../../../utils/SessionManager'; import getClient from '../../getClient'; -import getSessionId from '../getSessionId'; type RequestCookies = Awaited>; +/** + * Reads the session ID for sign-out. An expired access token still identifies the session, so sign-out + * ends the authorization server's session too. The cookie must still decrypt, and a session a + * back-channel logout ended is still refused. + */ +const getSessionIdForSignOut = async (): Promise => { + const token: string | undefined = getChunkedCookie(await cookies(), SessionManager.getSessionCookieName()); + + if (!token) { + return undefined; + } + + try { + return (await SessionManager.verifySessionTokenForRefresh(token)).sessionId; + } catch { + return undefined; + } +}; + /** * Server action for signing out a user. * Clears both JWT and legacy session cookies. @@ -26,13 +44,15 @@ const signOutAction = async (): Promise<{data?: {signOutUrl?: string}; error?: u const clearSessionCookies = async (): Promise => { const cookieStore: RequestCookies = await cookies(); - deleteChunkedCookie(cookieStore, SessionManager.getSessionCookieName()); - cookieStore.delete(SessionManager.getTempSessionCookieName()); + deleteChunkedCookie(cookieStore, SessionManager.getSessionCookieName(), SessionManager.getSessionCookieOptions(0)); + cookieStore.delete( + toCookieDeletion(SessionManager.getTempSessionCookieName(), SessionManager.getTempSessionCookieOptions()), + ); }; try { const client = getClient(); - const sessionId: string | undefined = await getSessionId(); + const sessionId: string | undefined = await getSessionIdForSignOut(); let signOutUrl = '/'; diff --git a/packages/nextjs/src/server/actions/clearSession.ts b/packages/nextjs/src/server/actions/clearSession.ts index 9dda8895..070cc928 100644 --- a/packages/nextjs/src/server/actions/clearSession.ts +++ b/packages/nextjs/src/server/actions/clearSession.ts @@ -4,7 +4,7 @@ 'use server'; import {cookies} from 'next/headers'; -import {deleteChunkedCookie} from '../../utils/chunkedCookie'; +import {deleteChunkedCookie, toCookieDeletion} from '../../utils/chunkedCookie'; import logger from '../../utils/logger'; import SessionManager from '../../utils/SessionManager'; @@ -32,8 +32,10 @@ type RequestCookies = Awaited>; */ const clearSession = async (): Promise => { const cookieStore: RequestCookies = await cookies(); - deleteChunkedCookie(cookieStore, SessionManager.getSessionCookieName()); - cookieStore.delete(SessionManager.getTempSessionCookieName()); + deleteChunkedCookie(cookieStore, SessionManager.getSessionCookieName(), SessionManager.getSessionCookieOptions(0)); + cookieStore.delete( + toCookieDeletion(SessionManager.getTempSessionCookieName(), SessionManager.getTempSessionCookieOptions()), + ); logger.debug('[clearSession] Session cookies cleared.'); }; diff --git a/packages/nextjs/src/server/actions/refreshToken.ts b/packages/nextjs/src/server/actions/refreshToken.ts index a8147189..7d4a7702 100644 --- a/packages/nextjs/src/server/actions/refreshToken.ts +++ b/packages/nextjs/src/server/actions/refreshToken.ts @@ -94,7 +94,11 @@ const refreshToken = async (): Promise => { // path covers that case on the next request. try { const cookieStore: RequestCookies = await cookies(); - deleteChunkedCookie(cookieStore, SessionManager.getSessionCookieName()); + deleteChunkedCookie( + cookieStore, + SessionManager.getSessionCookieName(), + SessionManager.getSessionCookieOptions(0), + ); logger.debug('[refreshToken] Cleared session cookie after refresh failure.'); } catch { // Intentionally swallowed — middleware handles cleanup when mutation is blocked. diff --git a/packages/nextjs/src/server/bff.ts b/packages/nextjs/src/server/bff.ts new file mode 100644 index 00000000..f0874505 --- /dev/null +++ b/packages/nextjs/src/server/bff.ts @@ -0,0 +1,337 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import { + BffAdapter, + BffConstants, + BffOptions, + BffSession, + BffSwitchResult, + ExtendedAuthorizeRequestUrlParams, + OrganizationUnitSwitchErrorCodes, + bffRedirect, + bffSignedIn, + generateSessionId, + getRequestOrigins, + handleBffRequest, + logger, + toSafeReturnTo, +} from '@thunderid/node'; +import {decodeJwt} from 'jose'; +import signOutAction from './actions/auth/signOutAction'; +import switchOrganizationUnitAction, { + SwitchOrganizationUnitActionResult, +} from './actions/auth/switchOrganizationUnitAction'; +import backchannelLogout from './backchannelLogout'; +import getClient from './getClient'; +import {ThunderIDNextConfig} from '../models/config'; +import {deleteChunkedCookie, getChunkedCookie, setChunkedCookie, toCookieDeletion} from '../utils/chunkedCookie'; +import handleRefreshToken, {HandleRefreshTokenResult} from '../utils/handleRefreshToken'; +import SessionManager, {SessionTokenPayload} from '../utils/SessionManager'; +import setSessionCookie from '../utils/setSessionCookie'; + +type RequestCookies = Awaited>; + +/** + * Reads the request's cookie store. `next/headers` is imported lazily because the package root re-exports this + * module, and a static import of `next/headers` fails a build that reaches the root from a Client Component. + */ +const cookies = async (): Promise => (await import('next/headers')).cookies(); + +/** + * How the Next.js BFF is set up. Every field is optional. + */ +export interface ThunderIDBffOptions extends BffOptions { + /** + * The API the proxy forwards to. Defaults to the ThunderID `baseUrl`, so the SDK's components that + * call ThunderID's own APIs, such as the user profile, work through the proxy. + */ + apiBaseUrl?: string; +} + +const getConfig = async (): Promise => { + const client = getClient(); + + if (!client.isInitialized) { + await client.initialize({} as ThunderIDNextConfig); + } + + return client.getConfiguration(); +}; + +const toScope = (scopes: unknown): string | undefined => + Array.isArray(scopes) ? scopes.join(' ') : typeof scopes === 'string' ? scopes : undefined; + +/** The ID token's claims, or only `sub` when the session holds no ID token. */ +const toClaims = (payload: SessionTokenPayload): Record => { + if (payload.idToken) { + try { + return decodeJwt(payload.idToken) as Record; + } catch { + logger.warn('[bff] The session holds an ID token that cannot be decoded.'); + } + } + + return {sub: payload.sub}; +}; + +const readCookie = (cookieStore: RequestCookies): string | undefined => + getChunkedCookie(cookieStore, SessionManager.getSessionCookieName()); + +const clearSessionCookie = (cookieStore: RequestCookies): void => { + deleteChunkedCookie(cookieStore, SessionManager.getSessionCookieName(), SessionManager.getSessionCookieOptions(0)); +}; + +/** + * Refreshes the session in the cookie, and writes the new one. Clears the cookie when it cannot. + * + * @returns The refreshed session, or `null` when there is none to refresh or the refresh failed. + */ +const refreshSession = async (cookieStore: RequestCookies): Promise => { + const token: string | undefined = readCookie(cookieStore); + + if (!token) { + return null; + } + + try { + const config: ThunderIDNextConfig = await getConfig(); + const result: HandleRefreshTokenResult = await handleRefreshToken( + await SessionManager.verifySessionTokenForRefresh(token), + { + baseUrl: config.baseUrl ?? '', + clientId: config.clientId ?? '', + clientSecret: config.clientSecret ?? '', + sessionCookie: config.sessionCookie, + }, + ); + + setChunkedCookie( + cookieStore, + SessionManager.getSessionCookieName(), + result.newSessionToken, + SessionManager.getSessionCookieOptions(result.sessionCookieExpiryTime), + ); + + return await SessionManager.verifySessionToken(result.newSessionToken); + } catch { + clearSessionCookie(cookieStore); + + return null; + } +}; + +const switchErrorFor = (result: Extract): BffSwitchResult => { + if (result.statusCode === 401) { + return {error: BffConstants.Errors.LOGIN_REQUIRED, status: 401}; + } + + switch (result.code) { + case OrganizationUnitSwitchErrorCodes.InteractionRequired: + return {error: 'interaction_required'}; + case OrganizationUnitSwitchErrorCodes.UnauthorizedClient: + return {error: 'unauthorized_client'}; + case OrganizationUnitSwitchErrorCodes.InvalidOrganizationUnit: + return {error: BffConstants.Errors.INVALID_REQUEST}; + default: + return {error: BffConstants.Errors.SERVER_ERROR, status: 502}; + } +}; + +const adapter: BffAdapter = { + async backchannelLogout(request: Request): Promise { + return backchannelLogout().POST(request); + }, + + async callback(request: Request): Promise { + const url = new URL(request.url); + const cookieStore: RequestCookies = await cookies(); + const tempToken: string | undefined = cookieStore.get(SessionManager.getTempSessionCookieName())?.value; + const code: string | null = url.searchParams.get('code'); + const state: string | null = url.searchParams.get('state'); + let temp: {returnTo?: string; sessionId: string} | undefined; + + try { + temp = tempToken ? await SessionManager.verifyTempSession(tempToken) : undefined; + } catch { + temp = undefined; + } + + cookieStore.delete( + toCookieDeletion(SessionManager.getTempSessionCookieName(), SessionManager.getTempSessionCookieOptions()), + ); + + if (!temp || !code || !state || url.searchParams.has('error')) { + logger.warn(`[bff] Sign-in did not complete: ${url.searchParams.get('error') ?? 'no sign-in in progress'}.`); + + return bffRedirect('/'); + } + + const client = getClient(); + const config: ThunderIDNextConfig = await getConfig(); + const tokens: Record = (await client.signIn({code, state}, {}, temp.sessionId)) as Record< + string, + unknown + >; + + await setSessionCookie(client, cookieStore, temp.sessionId, tokens, config); + + return bffSignedIn(toSafeReturnTo(temp.returnTo), SessionManager.getSessionCookieOptions(0).sameSite); + }, + + async getSession(): Promise { + const cookieStore: RequestCookies = await cookies(); + const token: string | undefined = readCookie(cookieStore); + + if (!token) { + return null; + } + + let payload: SessionTokenPayload | null; + + try { + payload = await SessionManager.verifySessionToken(token); + } catch { + // The access token expired, or the session ended: a refresh tells which. + payload = await refreshSession(cookieStore); + } + + return payload + ? { + accessToken: payload.accessToken, + expiresAt: payload.exp, + idTokenClaims: toClaims(payload), + scope: toScope(payload.scopes), + } + : null; + }, + + async isSessionLive(): Promise { + const token: string | undefined = readCookie(await cookies()); + + if (!token) { + return false; + } + + try { + // Decrypts and refuses a session a back-channel logout ended, without refreshing anything. + const payload: SessionTokenPayload = await SessionManager.verifySessionTokenForRefresh(token); + + return Boolean(payload.refreshToken) || payload.exp > Math.floor(Date.now() / 1000); + } catch { + return false; + } + }, + + async refresh(): Promise { + return Boolean(await refreshSession(await cookies())); + }, + + async signIn(_request: Request, {ouId, returnTo}: {ouId?: string; returnTo: string}): Promise { + const cookieStore: RequestCookies = await cookies(); + const token: string | undefined = readCookie(cookieStore); + let sessionId: string | undefined; + + if (token) { + try { + sessionId = (await SessionManager.verifySessionToken(token)).sessionId; + } catch { + sessionId = undefined; + } + } + + if (sessionId && !ouId) { + return bffRedirect(returnTo); + } + + sessionId ??= generateSessionId(); + + const url: string = await getClient().getAuthorizeRequestUrl( + (ouId ? {organizationUnitId: ouId} : {}) as ExtendedAuthorizeRequestUrlParams, + sessionId, + ); + + cookieStore.set( + SessionManager.getTempSessionCookieName(), + await SessionManager.createTempSession(sessionId, returnTo), + SessionManager.getTempSessionCookieOptions(), + ); + + return bffRedirect(url); + }, + + async signOut(): Promise<{redirectUrl: string}> { + const result: Awaited> = await signOutAction(); + + return {redirectUrl: result.data?.signOutUrl ?? '/'}; + }, + + async switchOrganizationUnit(_request: Request, ouId: string): Promise { + const result: SwitchOrganizationUnitActionResult = await switchOrganizationUnitAction(ouId, {redirect: false}); + + return result.success ? {ok: true} : switchErrorFor(result); + }, +}; + +/** + * Serves the BFF contract of RFC 10017 from Next.js, so a React or Vue app in `backend` mode, or the + * app's own client components, can use this app as its BFF. Add a catch-all route handler: + * + * ```ts + * // app/api/auth/[...thunderid]/route.ts + * import {thunderIDBff} from '@thunderid/nextjs/server'; + * + * export const {GET, POST} = thunderIDBff(); + * ``` + * + * It serves, under `/api/auth`: `GET signin`, `GET callback`, `GET session`, `GET checksession`, + * `POST refresh`, `POST signout`, `POST switch`, `POST backchannel-logout` and the API proxy under + * `proxy/`. Every call the browser SDK makes must carry `X-Requested-With: XMLHttpRequest`, and no + * response carries a token. To complete sign-in through it, set `afterSignInUrl` to the `callback` + * endpoint on the app's origin and register that URL with the application. + * + * The session stays in the encrypted session cookie. + * + * @param options - The prefix, the API to proxy to, and the allowed origins. + * @returns The route handlers. + */ +const thunderIDBff = ( + options: ThunderIDBffOptions = {}, +): { + DELETE: (request: Request) => Promise; + GET: (request: Request) => Promise; + PATCH: (request: Request) => Promise; + POST: (request: Request) => Promise; + PUT: (request: Request) => Promise; +} => { + const prefix: string = (options.prefix ?? BffConstants.DEFAULT_PREFIX).replace(/\/+$/, ''); + let checkedCallback = false; + + const handle = async (request: Request): Promise => { + const config: ThunderIDNextConfig = await getConfig(); + const appOrigin: string = new URL(request.url).origin; + + if (!checkedCallback && config.afterSignInUrl) { + checkedCallback = true; + if (new URL(config.afterSignInUrl, appOrigin).pathname !== `${prefix}${BffConstants.Endpoints.CALLBACK}`) { + logger.warn( + `[bff] afterSignInUrl is not ${prefix}${BffConstants.Endpoints.CALLBACK}, so sign-in started at ` + + `${prefix}${BffConstants.Endpoints.SIGN_IN} returns to the app instead of completing here.`, + ); + } + } + + const response: Response | undefined = await handleBffRequest(request, adapter, { + ...options, + prefix, + allowedOrigins: options.allowedOrigins ?? getRequestOrigins(request), + apiBaseUrl: options.apiBaseUrl ?? config.baseUrl, + }); + + return response ?? new Response(null, {status: 404}); + }; + + return {DELETE: handle, GET: handle, PATCH: handle, POST: handle, PUT: handle}; +}; + +export default thunderIDBff; diff --git a/packages/nextjs/src/server/index.ts b/packages/nextjs/src/server/index.ts index 8923eb65..43cc5c25 100644 --- a/packages/nextjs/src/server/index.ts +++ b/packages/nextjs/src/server/index.ts @@ -15,3 +15,6 @@ export {default as createRouteMatcher} from './proxy/createRouteMatcher'; export {default as backchannelLogout} from './backchannelLogout'; export type {BackchannelLogoutOptions} from './backchannelLogout'; + +export {default as thunderIDBff} from './bff'; +export type {ThunderIDBffOptions} from './bff'; diff --git a/packages/nextjs/src/server/proxy/thunderIDProxy.ts b/packages/nextjs/src/server/proxy/thunderIDProxy.ts index 661e8291..b83e2658 100644 --- a/packages/nextjs/src/server/proxy/thunderIDProxy.ts +++ b/packages/nextjs/src/server/proxy/thunderIDProxy.ts @@ -8,6 +8,7 @@ import {ThunderIDNextConfig} from '../../models/config'; import { ChunkedCookieOptions, ChunkedCookieWriter, + CookieDeletion, deleteChunkedCookie, getChunkedCookie, setChunkedCookie, @@ -113,8 +114,8 @@ const toChunkedCookieWriter = ( request: NextRequest, responseCookies: NextResponse['cookies'], ): ChunkedCookieWriter => ({ - delete: (name: string): void => { - responseCookies.delete(name); + delete: (cookie: CookieDeletion): void => { + responseCookies.delete(cookie); }, getAll: (): {name: string}[] => request.cookies.getAll(), set: (name: string, value: string, options: ChunkedCookieOptions): void => { @@ -331,7 +332,11 @@ const thunderIDProxy = // Handler returned a response (e.g. a redirect from protectRoute). // Attach the deletion so the browser discards the stale cookie (and // every chunk of it). - deleteChunkedCookie(toChunkedCookieWriter(request, handlerResponse.cookies), cookieName); + deleteChunkedCookie( + toChunkedCookieWriter(request, handlerResponse.cookies), + cookieName, + SessionManager.getSessionCookieOptions(0), + ); return handlerResponse; } @@ -340,7 +345,11 @@ const thunderIDProxy = const requestHeaders: Headers = new Headers(request.headers); requestHeaders.set('cookie', removeChunkedCookieFromHeader(request.headers.get('cookie') ?? '', cookieName)); const cleanResponse: NextResponse = NextResponse.next({request: {headers: requestHeaders}}); - deleteChunkedCookie(toChunkedCookieWriter(request, cleanResponse.cookies), cookieName); + deleteChunkedCookie( + toChunkedCookieWriter(request, cleanResponse.cookies), + cookieName, + SessionManager.getSessionCookieOptions(0), + ); return cleanResponse; } diff --git a/packages/nextjs/src/utils/SessionManager.ts b/packages/nextjs/src/utils/SessionManager.ts index 88a5010e..8232b126 100644 --- a/packages/nextjs/src/utils/SessionManager.ts +++ b/packages/nextjs/src/utils/SessionManager.ts @@ -1,19 +1,28 @@ // Copyright 2025 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 -import {ThunderIDRuntimeError, CookieConfig} from '@thunderid/node'; +import { + ThunderIDRuntimeError, + CookieConfig, + SessionCookie, + SessionCookieSameSite, + resolveSessionCookieSameSite, + resolveSessionSecret, +} from '@thunderid/node'; import type {JWTPayload} from 'jose'; -// Subpath imports keep the proxy's bundle free of jose's JWE code, whose CompressionStream use the Edge runtime rejects. -import {compactVerify} from 'jose/jws/compact/verify'; -import {SignJWT} from 'jose/jwt/sign'; -import {jwtVerify} from 'jose/jwt/verify'; import {getLoggedOutSessions} from './loggedOutSessions'; import {DEFAULT_SESSION_COOKIE_EXPIRY_TIME} from '../constants/sessionConstants'; +const TEMP_SESSION_TTL_SECONDS: number = 15 * 60; + /** * Session token payload interface */ export interface SessionTokenPayload extends JWTPayload { + /** The access token. Never sent to the browser. */ + accessToken: string; + /** The raw ID token, so the user's claims are at hand on any instance without a session store. */ + idToken?: string; /** Expiration timestamp — doubles as the access token expiry (JWT exp == access token exp) */ exp: number; /** Issued at timestamp */ @@ -37,50 +46,34 @@ export interface SessionTokenPayload extends JWTPayload { } /** - * Session management utility class for JWT-based session cookies + * Reads and writes the session cookies. Their contents are encrypted in the BFF contract's session cookie + * format (see `SessionCookie` in `@thunderid/node`), so the tokens in them cannot be read from the browser. */ class SessionManager { /** - * Get the signing secret from environment variable - * Throws error in production if not set + * The secret the session cookies are encrypted with: `THUNDERID_SESSION_SECRET`, or the deprecated + * `THUNDERID_SECRET`. Throws in production when neither is set or the secret is shorter than 32 bytes. */ - private static getSecret(): Uint8Array { - const secret: string | undefined = process.env['THUNDERID_SECRET']; - - if (!secret) { - if (process.env['NODE_ENV'] === 'production') { - throw new ThunderIDRuntimeError( - 'THUNDERID_SECRET environment variable is required in production', - 'session-secret-required', - 'nextjs', - 'Set the THUNDERID_SECRET environment variable with a secure random string', - ); - } - // Use a default secret for development (not secure) - // eslint-disable-next-line no-console - console.warn('Using default secret for development. Set THUNDERID_SECRET for production!'); - return new TextEncoder().encode('development-secret-not-for-production'); - } + private static getSecret(): string { + return resolveSessionSecret({deprecatedEnv: ['THUNDERID_SECRET'], sdk: 'nextjs'}); + } - return new TextEncoder().encode(secret); + /** + * Whether the session cookies are `Secure`, and so carry the `__Host-` prefix. + */ + private static isSecure(): boolean { + return process.env['NODE_ENV'] === 'production'; } /** * Create a temporary session cookie for login initiation */ - static async createTempSession(sessionId: string): Promise { - const secret: Uint8Array = this.getSecret(); - - const jwt: string = await new SignJWT({ - sessionId, - type: 'temp', - }) - .setProtectedHeader({alg: 'HS256'}) - .setIssuedAt() - .setExpirationTime('15m') - .sign(secret); - - return jwt; + static async createTempSession(sessionId: string, returnTo?: string): Promise { + return SessionCookie.seal( + {sessionId, type: 'temp', ...(returnTo ? {returnTo} : {})}, + this.getSecret(), + Math.floor(Date.now() / 1000) + TEMP_SESSION_TTL_SECONDS, + ); } /** @@ -117,28 +110,25 @@ class SessionManager { accessTokenTtlSeconds: number, refreshToken: string, organizationId?: string, - serverSession?: {sid?: string; signedInAt?: number}, + serverSession?: {idToken?: string; sid?: string; signedInAt?: number}, ): Promise { - const secret: Uint8Array = this.getSecret(); - - const jwt: string = await new SignJWT({ - accessToken, - organizationId, - refreshToken, - scopes, - sessionId, - // What a back-channel logout matches this session by. - sid: serverSession?.sid, - signedInAt: serverSession?.signedInAt ?? Math.floor(Date.now() / 1000), - type: 'session', - } as Omit) - .setProtectedHeader({alg: 'HS256'}) - .setSubject(userId) - .setIssuedAt() - .setExpirationTime(Math.floor(Date.now() / 1000) + accessTokenTtlSeconds) - .sign(secret); - - return jwt; + return SessionCookie.seal( + { + accessToken, + idToken: serverSession?.idToken, + organizationId, + refreshToken, + scopes, + sessionId, + // What a back-channel logout matches this session by. + sid: serverSession?.sid, + signedInAt: serverSession?.signedInAt ?? Math.floor(Date.now() / 1000), + sub: userId, + type: 'session', + } as Omit, + this.getSecret(), + Math.floor(Date.now() / 1000) + accessTokenTtlSeconds, + ); } /** @@ -146,16 +136,15 @@ class SessionManager { */ static async verifySessionToken(token: string): Promise { try { - const secret: Uint8Array = this.getSecret(); - const {payload} = await jwtVerify(token, secret); + const payload: SessionTokenPayload = await SessionCookie.unseal(token, this.getSecret()); - if (payload['type'] !== 'session') { + if (payload.type !== 'session') { throw new Error('Invalid token type'); } - await this.refuseLoggedOutSession(payload as SessionTokenPayload); + await this.refuseLoggedOutSession(payload); - return payload as SessionTokenPayload; + return payload; } catch (error) { throw new ThunderIDRuntimeError( `Invalid session token: ${error instanceof Error ? error.message : 'Unknown error'}`, @@ -167,7 +156,7 @@ class SessionManager { } /** - * Verify a session token for refresh. Validates the HMAC signature and the + * Verify a session token for refresh. Decrypts the token, which also authenticates it, and checks and the * `type === 'session'` discriminant but intentionally skips the `exp` check * so an expired access token can still be exchanged for a new one. * @@ -179,9 +168,9 @@ class SessionManager { */ static async verifySessionTokenForRefresh(token: string): Promise { try { - const secret: Uint8Array = this.getSecret(); - const {payload: rawPayload} = await compactVerify(token, secret); - const payload: SessionTokenPayload = JSON.parse(new TextDecoder().decode(rawPayload)) as SessionTokenPayload; + const payload: SessionTokenPayload = await SessionCookie.unseal(token, this.getSecret(), { + ignoreExpiry: true, + }); if (payload.type !== 'session') { throw new Error('Invalid token type'); @@ -203,16 +192,21 @@ class SessionManager { /** * Verify and decode a temporary session token */ - static async verifyTempSession(token: string): Promise<{sessionId: string}> { + static async verifyTempSession(token: string): Promise<{returnTo?: string; sessionId: string}> { try { - const secret: Uint8Array = this.getSecret(); - const {payload} = await jwtVerify(token, secret); + const payload: {returnTo?: unknown; sessionId?: unknown; type?: unknown} = await SessionCookie.unseal( + token, + this.getSecret(), + ); - if (payload['type'] !== 'temp') { + if (payload.type !== 'temp' || typeof payload.sessionId !== 'string') { throw new Error('Invalid token type'); } - return {sessionId: payload['sessionId'] as string}; + return { + sessionId: payload.sessionId, + ...(typeof payload.returnTo === 'string' ? {returnTo: payload.returnTo} : {}), + }; } catch (error) { throw new ThunderIDRuntimeError( `Invalid temporary session token: ${error instanceof Error ? error.message : 'Unknown error'}`, @@ -224,11 +218,8 @@ class SessionManager { } /** - * Get session cookie options - */ - /** - * Throws when a back-channel logout has ended the session this cookie carries. The cookie is - * still correctly signed, so this is the only thing that stops it from being used. + * Throws when a back-channel logout has ended the session this cookie carries. The cookie still + * decrypts, so this is the only thing that stops it from being used. */ private static async refuseLoggedOutSession(payload: SessionTokenPayload): Promise { const loggedOut: boolean = await getLoggedOutSessions().isLoggedOut({ @@ -242,38 +233,42 @@ class SessionManager { } } + /** + * Session cookie options. `SameSite` is `Strict` unless `THUNDERID_SESSION_COOKIE_SAME_SITE` says otherwise. + */ static getSessionCookieOptions(maxAge: number): { httpOnly: boolean; maxAge: number; path: string; - sameSite: 'lax'; + sameSite: SessionCookieSameSite; secure: boolean; } { return { httpOnly: true, maxAge, path: '/', - sameSite: 'lax' as const, - secure: process.env['NODE_ENV'] === 'production', + sameSite: resolveSessionCookieSameSite(), + secure: this.isSecure(), }; } /** - * Get temporary session cookie options + * Options of the cookie that carries a sign-in in progress. It is `Lax` whatever the session cookie is, so it + * comes back on the redirect to the callback. */ static getTempSessionCookieOptions(): { httpOnly: boolean; maxAge: number; path: string; - sameSite: 'lax'; + sameSite: SessionCookieSameSite; secure: boolean; } { return { httpOnly: true, - maxAge: 15 * 60, + maxAge: TEMP_SESSION_TTL_SECONDS, path: '/', sameSite: 'lax' as const, - secure: process.env['NODE_ENV'] === 'production', + secure: this.isSecure(), }; } @@ -281,14 +276,14 @@ class SessionManager { * Get session cookie name */ static getSessionCookieName(): string { - return CookieConfig.getSessionCookieName(); + return CookieConfig.withHostPrefix(CookieConfig.getSessionCookieName(), this.isSecure()); } /** * Get temporary session cookie name */ static getTempSessionCookieName(): string { - return CookieConfig.getTempSessionCookieName(); + return CookieConfig.withHostPrefix(CookieConfig.getTempSessionCookieName(), this.isSecure()); } } diff --git a/packages/nextjs/src/utils/__tests__/SessionManager.encryption.test.ts b/packages/nextjs/src/utils/__tests__/SessionManager.encryption.test.ts new file mode 100644 index 00000000..2a6a3a8d --- /dev/null +++ b/packages/nextjs/src/utils/__tests__/SessionManager.encryption.test.ts @@ -0,0 +1,124 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {SignJWT} from 'jose'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import SessionManager from '../SessionManager'; + +const SECRET = 'a-session-secret-that-is-at-least-32-bytes'; + +const createSession = (ttlSeconds = 60): Promise => + SessionManager.createSessionToken('access-token', 'user-1', 'session-1', 'openid', ttlSeconds, 'refresh-token'); + +describe('SessionManager session cookie', () => { + beforeEach(() => { + vi.stubEnv('THUNDERID_SESSION_SECRET', SECRET); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + vi.useRealTimers(); + }); + + it('encrypts the tokens, so the cookie does not show them', async () => { + const token: string = await createSession(); + const readable: string = token + .split('.') + .map((part: string) => Buffer.from(part, 'base64url').toString('latin1')) + .join(''); + + expect(token.split('.')).toHaveLength(5); + expect(readable).not.toContain('access-token'); + expect(readable).not.toContain('refresh-token'); + }); + + it('reads back what it wrote', async () => { + const payload = await SessionManager.verifySessionToken(await createSession()); + + expect(payload).toMatchObject({ + accessToken: 'access-token', + refreshToken: 'refresh-token', + sessionId: 'session-1', + sub: 'user-1', + type: 'session', + }); + }); + + it('refuses an expired session, but lets a refresh read it', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date('2026-01-01T00:00:00Z')); + const token: string = await createSession(60); + + vi.setSystemTime(new Date('2026-01-01T00:02:00Z')); + + await expect(SessionManager.verifySessionToken(token)).rejects.toThrow(); + await expect(SessionManager.verifySessionTokenForRefresh(token)).resolves.toMatchObject({sub: 'user-1'}); + }); + + it('treats a signed cookie from an earlier version as no session', async () => { + const legacy: string = await new SignJWT({accessToken: 'at', sessionId: 's', type: 'session'}) + .setProtectedHeader({alg: 'HS256'}) + .setSubject('user-1') + .setIssuedAt() + .setExpirationTime('1h') + .sign(new TextEncoder().encode(SECRET)); + + await expect(SessionManager.verifySessionToken(legacy)).rejects.toThrow(); + await expect(SessionManager.verifySessionTokenForRefresh(legacy)).rejects.toThrow(); + }); + + it('does not accept a temporary session as a session, or the reverse', async () => { + const temp: string = await SessionManager.createTempSession('session-1'); + + await expect(SessionManager.verifyTempSession(temp)).resolves.toEqual({sessionId: 'session-1'}); + await expect(SessionManager.verifySessionToken(temp)).rejects.toThrow(); + await expect(SessionManager.verifyTempSession(await createSession())).rejects.toThrow(); + }); + + it('still reads the deprecated THUNDERID_SECRET', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined); + vi.stubEnv('THUNDERID_SESSION_SECRET', ''); + vi.stubEnv('THUNDERID_SECRET', SECRET); + const token: string = await createSession(); + + vi.stubEnv('THUNDERID_SECRET', ''); + vi.stubEnv('THUNDERID_SESSION_SECRET', SECRET); + + await expect(SessionManager.verifySessionToken(token)).resolves.toMatchObject({sub: 'user-1'}); + }); + + it('names the cookies with __Host- and makes them Secure in production', () => { + vi.stubEnv('NODE_ENV', 'production'); + + expect(SessionManager.getSessionCookieName()).toMatch(/^__Host-/); + expect(SessionManager.getTempSessionCookieName()).toMatch(/^__Host-/); + expect(SessionManager.getSessionCookieOptions(60)).toMatchObject({path: '/', secure: true}); + }); + + it('leaves the prefix off on a plain-HTTP development server', () => { + vi.stubEnv('NODE_ENV', 'development'); + + expect(SessionManager.getSessionCookieName()).not.toMatch(/^__Host-/); + expect(SessionManager.getSessionCookieOptions(60).secure).toBe(false); + }); +}); + +describe('SessionManager cookie SameSite', () => { + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it('makes the session cookie Strict and the sign-in cookie Lax by default', () => { + expect(SessionManager.getSessionCookieOptions(60).sameSite).toBe('strict'); + expect(SessionManager.getTempSessionCookieOptions().sameSite).toBe('lax'); + expect(SessionManager.getTempSessionCookieName()).toBe('thunderid-session-state'); + }); + + it('makes the session cookie Lax when THUNDERID_SESSION_COOKIE_SAME_SITE says so', () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined); + vi.stubEnv('THUNDERID_SESSION_COOKIE_SAME_SITE', 'lax'); + + expect(SessionManager.getSessionCookieOptions(60).sameSite).toBe('lax'); + }); +}); diff --git a/packages/nextjs/src/utils/__tests__/chunkedCookie.test.ts b/packages/nextjs/src/utils/__tests__/chunkedCookie.test.ts index c8ff43a4..67f55acc 100644 --- a/packages/nextjs/src/utils/__tests__/chunkedCookie.test.ts +++ b/packages/nextjs/src/utils/__tests__/chunkedCookie.test.ts @@ -2,7 +2,13 @@ // SPDX-License-Identifier: Apache-2.0 import {describe, it, expect} from 'vitest'; -import {ChunkedCookieOptions, deleteChunkedCookie, getChunkedCookie, setChunkedCookie} from '../chunkedCookie'; +import { + ChunkedCookieOptions, + CookieDeletion, + deleteChunkedCookie, + getChunkedCookie, + setChunkedCookie, +} from '../chunkedCookie'; const OPTIONS: ChunkedCookieOptions = {httpOnly: true, maxAge: 3600, path: '/', sameSite: 'lax', secure: false}; @@ -10,8 +16,11 @@ const OPTIONS: ChunkedCookieOptions = {httpOnly: true, maxAge: 3600, path: '/', class FakeCookieJar { private readonly jar = new Map(); - delete(name: string): void { - this.jar.delete(name); + readonly deletions: CookieDeletion[] = []; + + delete(cookie: CookieDeletion): void { + this.deletions.push(cookie); + this.jar.delete(cookie.name); } get(name: string): {value: string} | undefined { @@ -85,7 +94,7 @@ describe('deleteChunkedCookie', () => { const jar = new FakeCookieJar(); setChunkedCookie(jar, 'session', 'small-value', OPTIONS); - deleteChunkedCookie(jar, 'session'); + deleteChunkedCookie(jar, 'session', OPTIONS); expect(jar.getAll()).toEqual([]); }); @@ -95,13 +104,26 @@ describe('deleteChunkedCookie', () => { setChunkedCookie(jar, 'session', 'z'.repeat(12_000), OPTIONS); expect(jar.getAll().length).toBeGreaterThan(1); - deleteChunkedCookie(jar, 'session'); + deleteChunkedCookie(jar, 'session', OPTIONS); expect(jar.getAll()).toEqual([]); }); it('is a no-op-safe call when nothing is present', () => { const jar = new FakeCookieJar(); - expect(() => deleteChunkedCookie(jar, 'session')).not.toThrow(); + expect(() => deleteChunkedCookie(jar, 'session', OPTIONS)).not.toThrow(); + }); + + it('repeats the cookie attributes but not maxAge, so a __Host- cookie is really deleted', () => { + const jar = new FakeCookieJar(); + const secure: ChunkedCookieOptions = {...OPTIONS, secure: true}; + + setChunkedCookie(jar, '__Host-session', 'z'.repeat(12_000), secure); + deleteChunkedCookie(jar, '__Host-session', secure); + + expect(jar.deletions.length).toBeGreaterThan(1); + for (const deletion of jar.deletions) { + expect(deletion).toEqual({httpOnly: true, name: deletion.name, path: '/', sameSite: 'lax', secure: true}); + } }); }); diff --git a/packages/nextjs/src/utils/__tests__/setSessionCookie.test.ts b/packages/nextjs/src/utils/__tests__/setSessionCookie.test.ts index 6538b54d..af741a96 100644 --- a/packages/nextjs/src/utils/__tests__/setSessionCookie.test.ts +++ b/packages/nextjs/src/utils/__tests__/setSessionCookie.test.ts @@ -50,7 +50,7 @@ describe('setSessionCookie', () => { 3600, 'unit-rt', 'ou-globex', - {sid: 'sid-2'}, + {idToken: 'unit-id', sid: 'sid-2'}, ]); expect(setChunkedCookie).toHaveBeenCalledWith(cookieStore, 'session', 'session-jwt', {httpOnly: true}); }); diff --git a/packages/nextjs/src/utils/chunkedCookie.ts b/packages/nextjs/src/utils/chunkedCookie.ts index 4a1bf153..71558a0b 100644 --- a/packages/nextjs/src/utils/chunkedCookie.ts +++ b/packages/nextjs/src/utils/chunkedCookie.ts @@ -1,13 +1,13 @@ // Copyright 2025 The ThunderID Authors // SPDX-License-Identifier: Apache-2.0 -import {CookieChunking} from '@thunderid/node'; +import {CookieChunking, SessionCookieSameSite} from '@thunderid/node'; export interface ChunkedCookieOptions { httpOnly: boolean; maxAge: number; path: string; - sameSite: 'lax'; + sameSite: SessionCookieSameSite; secure: boolean; } @@ -17,8 +17,21 @@ export interface ChunkedCookieReader { } /** Minimal shape shared by `cookies()` (next/headers) and `NextResponse.cookies`. */ +/** + * What a deletion repeats of the cookie's attributes. A browser ignores a deletion of a `__Host-` cookie + * that is not `Secure` with `Path=/`. `maxAge` is left out: it would override the deletion's `Expires`. + */ +export type CookieDeletion = {name: string} & Omit; + +/** + * The attributes a deletion of a cookie set with `options` repeats. + */ +export function toCookieDeletion(name: string, options: ChunkedCookieOptions): CookieDeletion { + return {httpOnly: options.httpOnly, name, path: options.path, sameSite: options.sameSite, secure: options.secure}; +} + export interface ChunkedCookieWriter { - delete(name: string): void; + delete(cookie: CookieDeletion): void; getAll(): {name: string}[]; set(name: string, value: string, options: ChunkedCookieOptions): void; } @@ -59,7 +72,7 @@ export function setChunkedCookie( for (const existingName of existing) { if (!newNames.has(existingName)) { - store.delete(existingName); + store.delete(toCookieDeletion(existingName, options)); } } @@ -72,18 +85,18 @@ export function setChunkedCookie( * Delete a cookie that may have been chunked — clears the base cookie name * and every numbered chunk present in `store`. */ -export function deleteChunkedCookie(store: ChunkedCookieWriter, name: string): void { +export function deleteChunkedCookie(store: ChunkedCookieWriter, name: string, options: ChunkedCookieOptions): void { const existing: string[] = CookieChunking.filterChunkNames( name, store.getAll().map((cookie: {name: string}) => cookie.name), ); if (existing.length === 0) { - store.delete(name); + store.delete(toCookieDeletion(name, options)); return; } for (const existingName of existing) { - store.delete(existingName); + store.delete(toCookieDeletion(existingName, options)); } } diff --git a/packages/nextjs/src/utils/handleRefreshToken.ts b/packages/nextjs/src/utils/handleRefreshToken.ts index 0b02e204..9903a373 100644 --- a/packages/nextjs/src/utils/handleRefreshToken.ts +++ b/packages/nextjs/src/utils/handleRefreshToken.ts @@ -45,6 +45,7 @@ const handleRefreshToken = async ( sid, signedInAt, iat, + idToken: storedIdToken, } = sessionPayload; if (!storedRefreshToken) { @@ -104,7 +105,7 @@ const handleRefreshToken = async ( newRefreshToken, organizationId, // A refreshed session is still the same sign-in, so it keeps what a logout matches it by. - {sid, signedInAt: signedInAt ?? iat}, + {idToken: (tokenData['id_token'] as string | undefined) ?? storedIdToken, sid, signedInAt: signedInAt ?? iat}, ); return { diff --git a/packages/nextjs/src/utils/setSessionCookie.ts b/packages/nextjs/src/utils/setSessionCookie.ts index d25aad59..a24d18e7 100644 --- a/packages/nextjs/src/utils/setSessionCookie.ts +++ b/packages/nextjs/src/utils/setSessionCookie.ts @@ -41,7 +41,10 @@ const setSessionCookie = async ( expiresIn, refreshToken, organizationId, - {sid: typeof idToken['sid'] === 'string' ? idToken['sid'] : undefined}, + { + idToken: (tokens['id_token'] ?? tokens['idToken']) as string | undefined, + sid: typeof idToken['sid'] === 'string' ? idToken['sid'] : undefined, + }, ); setChunkedCookie( diff --git a/packages/node/src/__tests__/SessionCookie.test.ts b/packages/node/src/__tests__/SessionCookie.test.ts new file mode 100644 index 00000000..3ba90415 --- /dev/null +++ b/packages/node/src/__tests__/SessionCookie.test.ts @@ -0,0 +1,154 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {hkdfSync} from 'node:crypto'; +import {CompactEncrypt, compactDecrypt} from 'jose'; +import {afterEach, describe, expect, it, vi} from 'vitest'; +import CookieConfig from '../constants/CookieConfig'; +import SessionCookie, {SessionCookieError} from '../utils/SessionCookie'; + +const SECRET = 'a-session-secret-that-is-at-least-32-bytes'; + +// The key every implementation derives, computed here with Node's own HKDF rather than the code under test. +const contractKey = (secret: string): Uint8Array => + new Uint8Array(hkdfSync('sha256', secret, new Uint8Array(0), SessionCookie.KEY_INFO, 32)); + +const now = (): number => Math.floor(Date.now() / 1000); + +const codeOf = async (promise: Promise): Promise => { + try { + await promise; + + return undefined; + } catch (error) { + return error instanceof SessionCookieError ? error.code : `not a SessionCookieError: ${String(error)}`; + } +}; + +describe('SessionCookie', () => { + afterEach(() => { + vi.useRealTimers(); + }); + + it('returns the claims it sealed, with iat and exp', async () => { + const sealed: string = await SessionCookie.seal({accessToken: 'at', sub: 'user-1'}, SECRET, now() + 60); + const claims = await SessionCookie.unseal<{accessToken: string; sub: string}>(sealed, SECRET); + + expect(claims.accessToken).toBe('at'); + expect(claims.sub).toBe('user-1'); + expect(claims.exp).toBe(now() + 60); + expect(claims.iat).toBeLessThanOrEqual(now()); + }); + + it('keeps no claim readable without the secret', async () => { + const sealed: string = await SessionCookie.seal({accessToken: 'secret-access-token'}, SECRET, now() + 60); + const readable: string = sealed + .split('.') + .map((part: string) => Buffer.from(part, 'base64url').toString('latin1')) + .join(''); + + expect(readable).not.toContain('secret-access-token'); + }); + + it('writes a standard compact JWE that jose decrypts with the contract key', async () => { + const sealed: string = await SessionCookie.seal({sub: 'user-1'}, SECRET, now() + 60); + const {plaintext, protectedHeader} = await compactDecrypt(sealed, contractKey(SECRET)); + + expect(protectedHeader).toEqual({alg: 'dir', enc: 'A256GCM', typ: 'JWT'}); + expect((JSON.parse(new TextDecoder().decode(plaintext)) as {sub: string}).sub).toBe('user-1'); + }); + + it('reads a cookie another implementation wrote with the contract key', async () => { + const claims = {exp: now() + 60, iat: now(), sub: 'from-go'}; + const written: string = await new CompactEncrypt(new TextEncoder().encode(JSON.stringify(claims))) + .setProtectedHeader({alg: 'dir', enc: 'A256GCM'}) + .encrypt(contractKey(SECRET)); + + expect((await SessionCookie.unseal<{sub: string}>(written, SECRET)).sub).toBe('from-go'); + }); + + it('refuses a cookie sealed with another secret', async () => { + const sealed: string = await SessionCookie.seal({}, `${SECRET}-other`, now() + 60); + + expect(await codeOf(SessionCookie.unseal(sealed, SECRET))).toBe('undecryptable'); + }); + + it('refuses a cookie whose ciphertext was changed', async () => { + const parts: string[] = (await SessionCookie.seal({role: 'user'}, SECRET, now() + 60)).split('.'); + const ciphertext: Buffer = Buffer.from(parts[3], 'base64url'); + + ciphertext.writeUInt8(ciphertext.readUInt8(0) ^ 1, 0); + parts[3] = ciphertext.toString('base64url'); + + expect(await codeOf(SessionCookie.unseal(parts.join('.'), SECRET))).toBe('undecryptable'); + }); + + it('refuses a cookie whose header was changed, since the header is authenticated', async () => { + const parts: string[] = (await SessionCookie.seal({}, SECRET, now() + 60)).split('.'); + + parts[0] = Buffer.from(JSON.stringify({alg: 'dir', enc: 'A256GCM', typ: 'JWT', kid: 'x'})).toString('base64url'); + + expect(await codeOf(SessionCookie.unseal(parts.join('.'), SECRET))).toBe('undecryptable'); + }); + + it('refuses any other algorithm, and compression', async () => { + const parts: string[] = (await SessionCookie.seal({}, SECRET, now() + 60)).split('.'); + const withHeader = (header: object): string => + [Buffer.from(JSON.stringify(header)).toString('base64url'), ...parts.slice(1)].join('.'); + + expect(await codeOf(SessionCookie.unseal(withHeader({alg: 'dir', enc: 'A128GCM'}), SECRET))).toBe('unsupported'); + expect(await codeOf(SessionCookie.unseal(withHeader({alg: 'A256KW', enc: 'A256GCM'}), SECRET))).toBe('unsupported'); + expect(await codeOf(SessionCookie.unseal(withHeader({alg: 'dir', enc: 'A256GCM', zip: 'DEF'}), SECRET))).toBe( + 'unsupported', + ); + }); + + it('refuses a signed JWT, such as a cookie from an earlier SDK version', async () => { + const legacy = 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyLTEifQ.c2lnbmF0dXJl'; + + expect(await codeOf(SessionCookie.unseal(legacy, SECRET))).toBe('malformed'); + expect(await codeOf(SessionCookie.unseal('not-a-cookie', SECRET))).toBe('malformed'); + expect(await codeOf(SessionCookie.unseal('a.b.c.d.e', SECRET))).toBe('malformed'); + }); + + it('refuses an expired cookie unless asked to ignore the expiry', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date('2026-01-01T00:00:00Z')); + const sealed: string = await SessionCookie.seal({sub: 'user-1'}, SECRET, now() + 60); + + vi.setSystemTime(new Date('2026-01-01T00:01:00Z')); + + expect(await codeOf(SessionCookie.unseal(sealed, SECRET))).toBe('expired'); + expect(await codeOf(SessionCookie.unseal(sealed, SECRET, {clockTolerance: 5}))).toBeUndefined(); + expect((await SessionCookie.unseal<{sub: string}>(sealed, SECRET, {ignoreExpiry: true})).sub).toBe('user-1'); + }); + + it('uses a fresh IV each time', async () => { + const a: string = await SessionCookie.seal({}, SECRET, now() + 60); + const b: string = await SessionCookie.seal({}, SECRET, now() + 60); + + expect(a.split('.')[2]).not.toBe(b.split('.')[2]); + }); + + it('accepts only secrets of at least 32 bytes', () => { + expect(SessionCookie.isUsableSecret(SECRET)).toBe(true); + expect(SessionCookie.isUsableSecret('x'.repeat(31))).toBe(false); + expect(SessionCookie.isUsableSecret(undefined)).toBe(false); + }); +}); + +describe('CookieConfig.withHostPrefix', () => { + it('adds __Host- only to a Secure cookie, and only once', () => { + expect(CookieConfig.withHostPrefix('thunderid-session', true)).toBe('__Host-thunderid-session'); + expect(CookieConfig.withHostPrefix('thunderid-session', false)).toBe('thunderid-session'); + expect(CookieConfig.withHostPrefix('__Host-session', true)).toBe('__Host-session'); + }); +}); + +describe('CookieConfig names', () => { + it('names the cookies after the vendor, in lowercase with hyphens', () => { + expect(CookieConfig.getSessionCookieName()).toBe('thunderid-session'); + expect(CookieConfig.getTempSessionCookieName()).toBe('thunderid-session-state'); + expect(CookieConfig.getSessionCookieName('acme')).toBe('acme-session'); + }); +}); diff --git a/packages/node/src/__tests__/resolveSessionCookieSameSite.test.ts b/packages/node/src/__tests__/resolveSessionCookieSameSite.test.ts new file mode 100644 index 00000000..70df71c3 --- /dev/null +++ b/packages/node/src/__tests__/resolveSessionCookieSameSite.test.ts @@ -0,0 +1,55 @@ +// Copyright 2026 The ThunderID Authors +// SPDX-License-Identifier: Apache-2.0 + +import {afterEach, describe, expect, it, vi} from 'vitest'; +import {bffSignedIn, renderSignInContinuePage} from '../bff/handleBffRequest'; +import resolveSessionCookieSameSite from '../utils/resolveSessionCookieSameSite'; + +describe('resolveSessionCookieSameSite', () => { + afterEach(() => { + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + }); + + it('is Strict by default, as RFC 10017 recommends', () => { + expect(resolveSessionCookieSameSite()).toBe('strict'); + }); + + it('takes the configured value, then THUNDERID_SESSION_COOKIE_SAME_SITE', () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined); + vi.stubEnv('THUNDERID_SESSION_COOKIE_SAME_SITE', 'LAX'); + + expect(resolveSessionCookieSameSite()).toBe('lax'); + expect(resolveSessionCookieSameSite('strict')).toBe('strict'); + }); + + it('ignores a value it does not know', () => { + vi.stubEnv('THUNDERID_SESSION_COOKIE_SAME_SITE', 'loose'); + + expect(resolveSessionCookieSameSite()).toBe('strict'); + }); +}); + +describe('the end of the callback', () => { + it('moves on from a page when the session cookie is Strict', async () => { + const response: Response = bffSignedIn('/orders', 'strict'); + + expect(response.status).toBe(200); + expect(response.headers.get('cache-control')).toBe('no-store'); + expect(await response.text()).toContain(''); + }); + + it('redirects when the session cookie is Lax', () => { + const response: Response = bffSignedIn('/orders', 'lax'); + + expect(response.status).toBe(302); + expect(response.headers.get('location')).toBe('/orders'); + }); + + it('escapes the place to go, so it cannot break out of the attribute', () => { + const page: string = renderSignInContinuePage('/a">'); + + expect(page).not.toContain('