@thunderid/nextjs 1.1.0 → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ThunderIDNextClient.js +1 -1
- package/dist/ThunderIDNextClient.js.map +1 -1
- package/dist/cjs/ThunderIDNextClient.cjs +1 -1
- package/dist/cjs/ThunderIDNextClient.cjs.map +1 -1
- package/dist/cjs/client/contexts/ThunderID/ThunderIDProvider.cjs +1 -2
- package/dist/cjs/client/contexts/ThunderID/ThunderIDProvider.cjs.map +1 -1
- package/dist/cjs/index.cjs +2 -0
- package/dist/cjs/server/actions/handleOAuthCallbackAction.cjs +2 -4
- package/dist/cjs/server/actions/handleOAuthCallbackAction.cjs.map +1 -1
- package/dist/cjs/server/actions/signInAction.cjs +1 -1
- package/dist/cjs/server/actions/signInAction.cjs.map +1 -1
- package/dist/cjs/server/backchannelLogout.cjs +92 -0
- package/dist/cjs/server/backchannelLogout.cjs.map +1 -0
- package/dist/cjs/server/index.cjs +2 -0
- package/dist/cjs/server/proxy/thunderIDProxy.cjs +4 -1
- package/dist/cjs/server/proxy/thunderIDProxy.cjs.map +1 -1
- package/dist/cjs/utils/SessionManager.cjs +17 -1
- package/dist/cjs/utils/SessionManager.cjs.map +1 -1
- package/dist/cjs/utils/handleRefreshToken.cjs +5 -2
- package/dist/cjs/utils/handleRefreshToken.cjs.map +1 -1
- package/dist/cjs/utils/loggedOutSessions.cjs +32 -0
- package/dist/cjs/utils/loggedOutSessions.cjs.map +1 -0
- package/dist/client/contexts/ThunderID/ThunderIDProvider.d.ts +1 -1
- package/dist/client/contexts/ThunderID/ThunderIDProvider.d.ts.map +1 -1
- package/dist/client/contexts/ThunderID/ThunderIDProvider.js +1 -2
- package/dist/client/contexts/ThunderID/ThunderIDProvider.js.map +1 -1
- package/dist/index.js +2 -1
- package/dist/server/actions/handleOAuthCallbackAction.d.ts +1 -2
- package/dist/server/actions/handleOAuthCallbackAction.d.ts.map +1 -1
- package/dist/server/actions/handleOAuthCallbackAction.js +2 -4
- package/dist/server/actions/handleOAuthCallbackAction.js.map +1 -1
- package/dist/server/actions/signInAction.d.ts.map +1 -1
- package/dist/server/actions/signInAction.js +1 -1
- package/dist/server/actions/signInAction.js.map +1 -1
- package/dist/server/backchannelLogout.d.ts +40 -0
- package/dist/server/backchannelLogout.d.ts.map +1 -0
- package/dist/server/backchannelLogout.js +90 -0
- package/dist/server/backchannelLogout.js.map +1 -0
- package/dist/server/index.d.ts +2 -0
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +2 -1
- package/dist/server/proxy/thunderIDProxy.d.ts +12 -1
- package/dist/server/proxy/thunderIDProxy.d.ts.map +1 -1
- package/dist/server/proxy/thunderIDProxy.js +4 -1
- package/dist/server/proxy/thunderIDProxy.js.map +1 -1
- package/dist/utils/SessionManager.d.ts +13 -1
- package/dist/utils/SessionManager.d.ts.map +1 -1
- package/dist/utils/SessionManager.js +17 -1
- package/dist/utils/SessionManager.js.map +1 -1
- package/dist/utils/handleRefreshToken.d.ts.map +1 -1
- package/dist/utils/handleRefreshToken.js +5 -2
- package/dist/utils/handleRefreshToken.js.map +1 -1
- package/dist/utils/loggedOutSessions.d.ts +12 -0
- package/dist/utils/loggedOutSessions.d.ts.map +1 -0
- package/dist/utils/loggedOutSessions.js +29 -0
- package/dist/utils/loggedOutSessions.js.map +1 -0
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"signInAction.js","names":["getClient","cookieStore: RequestCookies","sessionId: string | undefined","existingSessionToken: string | undefined","SessionManager","tempSessionToken: string | undefined","tempSessionToken: string","defaultSignInUrl: string","response: any","idToken: IdToken","userIdFromToken: string","organizationId: string | undefined","scopes: string","iat: number","exp: number","expiresIn: number","config: ThunderIDNextConfig","sessionCookieExpiryTime: number","sessionToken: string","afterSignInUrl: string"],"sources":["../../../src/server/actions/signInAction.ts"],"sourcesContent":["// Copyright 2025 The ThunderID Authors\n// SPDX-License-Identifier: Apache-2.0\n\n'use server';\n\nimport {\n generateSessionId,\n EmbeddedSignInFlowStatus,\n EmbeddedFlowExecuteRequestConfig,\n IdToken,\n isEmpty,\n} from '@thunderid/node';\nimport {cookies} from 'next/headers';\nimport {ThunderIDNextConfig} from '../../models/config';\nimport {getChunkedCookie, setChunkedCookie} from '../../utils/chunkedCookie';\nimport logger from '../../utils/logger';\nimport SessionManager, {SessionTokenPayload} from '../../utils/SessionManager';\nimport getClient from '../getClient';\n\ntype RequestCookies = Awaited<ReturnType<typeof cookies>>;\n\n/**\n * Server action for signing in a user.\n * Handles the embedded sign-in flow and manages session cookies.\n *\n * @param payload - The embedded sign-in flow payload\n * @param request - The embedded flow execute request config\n * @returns Promise that resolves when sign-in is complete\n */\nconst signInAction = async (\n payload?: any,\n request?: EmbeddedFlowExecuteRequestConfig,\n): Promise<{\n data?:\n | {\n afterSignInUrl?: string;\n signInUrl?: string;\n }\n | Record<string, unknown>;\n error?: string;\n success: boolean;\n}> => {\n try {\n const client = getClient();\n const cookieStore: RequestCookies = await cookies();\n\n let sessionId: string | undefined;\n\n const existingSessionToken: string | undefined = getChunkedCookie(\n cookieStore,\n SessionManager.getSessionCookieName(),\n );\n\n if (existingSessionToken) {\n try {\n const sessionPayload: SessionTokenPayload = await SessionManager.verifySessionToken(existingSessionToken);\n sessionId = sessionPayload.sessionId;\n } catch {\n // Invalid session token, will create new temp session\n }\n }\n\n if (!sessionId) {\n const tempSessionToken: string | undefined = cookieStore.get(SessionManager.getTempSessionCookieName())?.value;\n\n if (tempSessionToken) {\n try {\n const tempSession: {sessionId: string} = await SessionManager.verifyTempSession(tempSessionToken);\n sessionId = tempSession.sessionId;\n } catch {\n // Invalid temp session, will create new one\n }\n }\n }\n\n if (!sessionId) {\n sessionId = generateSessionId();\n\n const tempSessionToken: string = await SessionManager.createTempSession(sessionId);\n\n cookieStore.set(\n SessionManager.getTempSessionCookieName(),\n tempSessionToken,\n SessionManager.getTempSessionCookieOptions(),\n );\n }\n\n // If no payload provided, redirect to sign-in URL for redirect-based sign-in.\n if (!payload || isEmpty(payload)) {\n const defaultSignInUrl: string = await client.getAuthorizeRequestUrl({}, sessionId);\n return {data: {signInUrl: String(defaultSignInUrl)}, success: true};\n }\n\n // Handle embedded sign-in flow\n const response: any = await client.signIn(payload, request!, sessionId);\n\n if (response.flowStatus === EmbeddedSignInFlowStatus.Complete) {\n // On the V2 platform, a completed embedded flow (without a preceding `/authorize` redirect,\n // i.e. no `authId`) returns a self-contained JWT `assertion` rather than an authorization\n // code to exchange. This mirrors how @thunderid/react and @thunderid/vue treat it: the\n // assertion is used directly as the bearer session token.\n if (!response.assertion) {\n throw new Error('[signInAction] Flow completed without an assertion.');\n }\n\n const idToken: IdToken = await client.getDecodedIdToken(sessionId, response.assertion);\n const userIdFromToken: string = (idToken.sub as string | undefined) ?? sessionId;\n const organizationId: string | undefined = (idToken['user_org'] || idToken['organization_id']) as\n | string\n | undefined;\n const scopes: string = (idToken['scope'] as string | undefined) ?? '';\n const iat: number = (idToken['iat'] as number | undefined) ?? Math.floor(Date.now() / 1000);\n const exp: number = (idToken['exp'] as number | undefined) ?? iat + 3600;\n const expiresIn: number = Math.max(exp - iat, 0);\n\n const config: ThunderIDNextConfig = await client.getConfiguration();\n const sessionCookieExpiryTime: number = SessionManager.resolveSessionCookieExpiry(\n config.sessionCookie?.expiryTime,\n );\n\n const sessionToken: string = await SessionManager.createSessionToken(\n response.assertion,\n userIdFromToken,\n sessionId,\n scopes,\n expiresIn,\n '',\n organizationId,\n );\n\n setChunkedCookie(\n cookieStore,\n SessionManager.getSessionCookieName(),\n sessionToken,\n SessionManager.getSessionCookieOptions(sessionCookieExpiryTime),\n );\n\n cookieStore.delete(SessionManager.getTempSessionCookieName());\n\n const afterSignInUrl: string = await (await client.getStorageManager()).getConfigDataParameter('afterSignInUrl');\n return {data: {afterSignInUrl: String(afterSignInUrl)}, success: true};\n }\n\n return {data: response as Record<string, unknown>, success: true};\n } catch (error) {\n const message =\n error instanceof Error\n ? error.message\n : typeof (error as any)?.message === 'string'\n ? (error as any).message\n : String(error);\n logger.error(`[signInAction] Error during sign-in: ${message}`);\n return {error: message, success: false};\n }\n};\n\nexport default signInAction;\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA6BA,MAAM,eAAe,OACnB,SACA,YAUI;AACJ,KAAI;EACF,MAAM,SAASA,mBAAW;EAC1B,MAAMC,cAA8B,MAAM,SAAS;EAEnD,IAAIC;EAEJ,MAAMC,uBAA2C,iBAC/C,aACAC,uBAAe,sBAAsB,CACtC;AAED,MAAI,qBACF,KAAI;AAEF,gBAD4C,MAAMA,uBAAe,mBAAmB,qBAAqB,EAC9E;UACrB;AAKV,MAAI,CAAC,WAAW;GACd,MAAMC,mBAAuC,YAAY,IAAID,uBAAe,0BAA0B,CAAC,EAAE;AAEzG,OAAI,iBACF,KAAI;AAEF,iBADyC,MAAMA,uBAAe,kBAAkB,iBAAiB,EACzE;WAClB;;AAMZ,MAAI,CAAC,WAAW;AACd,eAAY,mBAAmB;GAE/B,MAAME,mBAA2B,MAAMF,uBAAe,kBAAkB,UAAU;AAElF,eAAY,IACVA,uBAAe,0BAA0B,EACzC,kBACAA,uBAAe,6BAA6B,CAC7C;;AAIH,MAAI,CAAC,WAAW,QAAQ,QAAQ,EAAE;GAChC,MAAMG,mBAA2B,MAAM,OAAO,uBAAuB,EAAE,EAAE,UAAU;AACnF,UAAO;IAAC,MAAM,EAAC,WAAW,OAAO,iBAAiB,EAAC;IAAE,SAAS;IAAK;;EAIrE,MAAMC,WAAgB,MAAM,OAAO,OAAO,SAAS,SAAU,UAAU;AAEvE,MAAI,SAAS,eAAe,yBAAyB,UAAU;AAK7D,OAAI,CAAC,SAAS,UACZ,OAAM,IAAI,MAAM,sDAAsD;GAGxE,MAAMC,UAAmB,MAAM,OAAO,kBAAkB,WAAW,SAAS,UAAU;GACtF,MAAMC,kBAA2B,QAAQ,OAA8B;GACvE,MAAMC,iBAAsC,QAAQ,eAAe,QAAQ;GAG3E,MAAMC,SAAkB,QAAQ,YAAmC;GACnE,MAAMC,MAAe,QAAQ,UAAiC,KAAK,MAAM,KAAK,KAAK,GAAG,IAAK;GAC3F,MAAMC,MAAe,QAAQ,UAAiC,MAAM;GACpE,MAAMC,YAAoB,KAAK,IAAI,MAAM,KAAK,EAAE;GAEhD,MAAMC,SAA8B,MAAM,OAAO,kBAAkB;GACnE,MAAMC,0BAAkCb,uBAAe,2BACrD,OAAO,eAAe,WACvB;GAED,MAAMc,eAAuB,MAAMd,uBAAe,mBAChD,SAAS,WACT,iBACA,WACA,QACA,WACA,IACA,
|
|
1
|
+
{"version":3,"file":"signInAction.js","names":["getClient","cookieStore: RequestCookies","sessionId: string | undefined","existingSessionToken: string | undefined","SessionManager","tempSessionToken: string | undefined","tempSessionToken: string","defaultSignInUrl: string","response: any","idToken: IdToken","userIdFromToken: string","organizationId: string | undefined","scopes: string","iat: number","exp: number","expiresIn: number","config: ThunderIDNextConfig","sessionCookieExpiryTime: number","sessionToken: string","afterSignInUrl: string"],"sources":["../../../src/server/actions/signInAction.ts"],"sourcesContent":["// Copyright 2025 The ThunderID Authors\n// SPDX-License-Identifier: Apache-2.0\n\n'use server';\n\nimport {\n generateSessionId,\n EmbeddedSignInFlowStatus,\n EmbeddedFlowExecuteRequestConfig,\n IdToken,\n isEmpty,\n} from '@thunderid/node';\nimport {cookies} from 'next/headers';\nimport {ThunderIDNextConfig} from '../../models/config';\nimport {getChunkedCookie, setChunkedCookie} from '../../utils/chunkedCookie';\nimport logger from '../../utils/logger';\nimport SessionManager, {SessionTokenPayload} from '../../utils/SessionManager';\nimport getClient from '../getClient';\n\ntype RequestCookies = Awaited<ReturnType<typeof cookies>>;\n\n/**\n * Server action for signing in a user.\n * Handles the embedded sign-in flow and manages session cookies.\n *\n * @param payload - The embedded sign-in flow payload\n * @param request - The embedded flow execute request config\n * @returns Promise that resolves when sign-in is complete\n */\nconst signInAction = async (\n payload?: any,\n request?: EmbeddedFlowExecuteRequestConfig,\n): Promise<{\n data?:\n | {\n afterSignInUrl?: string;\n signInUrl?: string;\n }\n | Record<string, unknown>;\n error?: string;\n success: boolean;\n}> => {\n try {\n const client = getClient();\n const cookieStore: RequestCookies = await cookies();\n\n let sessionId: string | undefined;\n\n const existingSessionToken: string | undefined = getChunkedCookie(\n cookieStore,\n SessionManager.getSessionCookieName(),\n );\n\n if (existingSessionToken) {\n try {\n const sessionPayload: SessionTokenPayload = await SessionManager.verifySessionToken(existingSessionToken);\n sessionId = sessionPayload.sessionId;\n } catch {\n // Invalid session token, will create new temp session\n }\n }\n\n if (!sessionId) {\n const tempSessionToken: string | undefined = cookieStore.get(SessionManager.getTempSessionCookieName())?.value;\n\n if (tempSessionToken) {\n try {\n const tempSession: {sessionId: string} = await SessionManager.verifyTempSession(tempSessionToken);\n sessionId = tempSession.sessionId;\n } catch {\n // Invalid temp session, will create new one\n }\n }\n }\n\n if (!sessionId) {\n sessionId = generateSessionId();\n\n const tempSessionToken: string = await SessionManager.createTempSession(sessionId);\n\n cookieStore.set(\n SessionManager.getTempSessionCookieName(),\n tempSessionToken,\n SessionManager.getTempSessionCookieOptions(),\n );\n }\n\n // If no payload provided, redirect to sign-in URL for redirect-based sign-in.\n if (!payload || isEmpty(payload)) {\n const defaultSignInUrl: string = await client.getAuthorizeRequestUrl({}, sessionId);\n return {data: {signInUrl: String(defaultSignInUrl)}, success: true};\n }\n\n // Handle embedded sign-in flow\n const response: any = await client.signIn(payload, request!, sessionId);\n\n if (response.flowStatus === EmbeddedSignInFlowStatus.Complete) {\n // On the V2 platform, a completed embedded flow (without a preceding `/authorize` redirect,\n // i.e. no `authId`) returns a self-contained JWT `assertion` rather than an authorization\n // code to exchange. This mirrors how @thunderid/react and @thunderid/vue treat it: the\n // assertion is used directly as the bearer session token.\n if (!response.assertion) {\n throw new Error('[signInAction] Flow completed without an assertion.');\n }\n\n const idToken: IdToken = await client.getDecodedIdToken(sessionId, response.assertion);\n const userIdFromToken: string = (idToken.sub as string | undefined) ?? sessionId;\n const organizationId: string | undefined = (idToken['user_org'] || idToken['organization_id']) as\n | string\n | undefined;\n const scopes: string = (idToken['scope'] as string | undefined) ?? '';\n const iat: number = (idToken['iat'] as number | undefined) ?? Math.floor(Date.now() / 1000);\n const exp: number = (idToken['exp'] as number | undefined) ?? iat + 3600;\n const expiresIn: number = Math.max(exp - iat, 0);\n\n const config: ThunderIDNextConfig = await client.getConfiguration();\n const sessionCookieExpiryTime: number = SessionManager.resolveSessionCookieExpiry(\n config.sessionCookie?.expiryTime,\n );\n\n const sessionToken: string = await SessionManager.createSessionToken(\n response.assertion,\n userIdFromToken,\n sessionId,\n scopes,\n expiresIn,\n '',\n organizationId,\n {sid: typeof idToken['sid'] === 'string' ? idToken['sid'] : undefined},\n );\n\n setChunkedCookie(\n cookieStore,\n SessionManager.getSessionCookieName(),\n sessionToken,\n SessionManager.getSessionCookieOptions(sessionCookieExpiryTime),\n );\n\n cookieStore.delete(SessionManager.getTempSessionCookieName());\n\n const afterSignInUrl: string = await (await client.getStorageManager()).getConfigDataParameter('afterSignInUrl');\n return {data: {afterSignInUrl: String(afterSignInUrl)}, success: true};\n }\n\n return {data: response as Record<string, unknown>, success: true};\n } catch (error) {\n const message =\n error instanceof Error\n ? error.message\n : typeof (error as any)?.message === 'string'\n ? (error as any).message\n : String(error);\n logger.error(`[signInAction] Error during sign-in: ${message}`);\n return {error: message, success: false};\n }\n};\n\nexport default signInAction;\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA6BA,MAAM,eAAe,OACnB,SACA,YAUI;AACJ,KAAI;EACF,MAAM,SAASA,mBAAW;EAC1B,MAAMC,cAA8B,MAAM,SAAS;EAEnD,IAAIC;EAEJ,MAAMC,uBAA2C,iBAC/C,aACAC,uBAAe,sBAAsB,CACtC;AAED,MAAI,qBACF,KAAI;AAEF,gBAD4C,MAAMA,uBAAe,mBAAmB,qBAAqB,EAC9E;UACrB;AAKV,MAAI,CAAC,WAAW;GACd,MAAMC,mBAAuC,YAAY,IAAID,uBAAe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AAe,wBAAwB,wBAAwB,CAChE;AAED,eAAY,OAAOA,uBAAe,0BAA0B,CAAC;GAE7D,MAAMe,iBAAyB,OAAO,MAAM,OAAO,mBAAmB,EAAE,uBAAuB,iBAAiB;AAChH,UAAO;IAAC,MAAM,EAAC,gBAAgB,OAAO,eAAe,EAAC;IAAE,SAAS;IAAK;;AAGxE,SAAO;GAAC,MAAM;GAAqC,SAAS;GAAK;UAC1D,OAAO;EACd,MAAM,UACJ,iBAAiB,QACb,MAAM,UACN,OAAQ,OAAe,YAAY,WAChC,MAAc,UACf,OAAO,MAAM;AACrB,iBAAO,MAAM,wCAAwC,UAAU;AAC/D,SAAO;GAAC,OAAO;GAAS,SAAS;GAAM;;;AAI3C,2BAAe"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { BackchannelLogoutResult, LogoutRecordStore } from '@thunderid/node';
|
|
2
|
+
export interface BackchannelLogoutOptions {
|
|
3
|
+
/**
|
|
4
|
+
* Called after a logout was recorded, so the application can clear what it holds for the ended
|
|
5
|
+
* sessions. Best effort: a failure is logged and the handler still answers 200, since the logout
|
|
6
|
+
* is already recorded and a retry would find nothing new.
|
|
7
|
+
*/
|
|
8
|
+
onLogout?: (result: BackchannelLogoutResult) => void | Promise<void>;
|
|
9
|
+
/**
|
|
10
|
+
* Where ended sessions are recorded. Give the same store to `thunderIDProxy()`. Needed when more
|
|
11
|
+
* than one instance of the application runs, or when the proxy runs on the Edge runtime, which
|
|
12
|
+
* shares no memory with this handler. Defaults to the memory of this process.
|
|
13
|
+
*/
|
|
14
|
+
store?: LogoutRecordStore;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Creates the route handler for OpenID Connect back-channel logout. ThunderID posts a
|
|
18
|
+
* `logout_token` to it when a session this application took part in ends. The session lives in a
|
|
19
|
+
* cookie the server cannot delete, so the handler records the logout, and every later request
|
|
20
|
+
* that presents a matching session cookie is treated as signed out.
|
|
21
|
+
*
|
|
22
|
+
* Mount it at the path registered as the application's back-channel logout URI:
|
|
23
|
+
*
|
|
24
|
+
* ```ts
|
|
25
|
+
* // app/api/auth/backchannel-logout/route.ts
|
|
26
|
+
* import {backchannelLogout} from '@thunderid/nextjs/server';
|
|
27
|
+
*
|
|
28
|
+
* export const {POST} = backchannelLogout();
|
|
29
|
+
* ```
|
|
30
|
+
*
|
|
31
|
+
* It answers `200` for a valid token, including one that names no session held here, `400` for a
|
|
32
|
+
* request or token that is not valid, and `500` when the logout could not be recorded, which
|
|
33
|
+
* makes the server try again. It needs no session cookie: the token's signature is the
|
|
34
|
+
* authentication.
|
|
35
|
+
*/
|
|
36
|
+
declare const backchannelLogout: (options?: BackchannelLogoutOptions) => {
|
|
37
|
+
POST: (request: Request) => Promise<Response>;
|
|
38
|
+
};
|
|
39
|
+
export default backchannelLogout;
|
|
40
|
+
//# sourceMappingURL=backchannelLogout.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"backchannelLogout.d.ts","sourceRoot":"","sources":["../../src/server/backchannelLogout.ts"],"names":[],"mappings":"AAGA,OAAO,EAEL,uBAAuB,EAEvB,iBAAiB,EAClB,MAAM,iBAAiB,CAAC;AAWzB,MAAM,WAAW,wBAAwB;IACvC;;;;OAIG;IACH,QAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,uBAAuB,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACrE;;;;OAIG;IACH,KAAK,CAAC,EAAE,iBAAiB,CAAC;CAC3B;AAoCD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,QAAA,MAAM,iBAAiB,GAAI,UAAS,wBAA6B,KAAG;IAAC,IAAI,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAA;CAyDjH,CAAC;AAEF,eAAe,iBAAiB,CAAC"}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { getLoggedOutSessions, setLogoutRecordStore } from "../utils/loggedOutSessions.js";
|
|
2
|
+
import SessionManager_default from "../utils/SessionManager.js";
|
|
3
|
+
import getClient_default from "./getClient.js";
|
|
4
|
+
import logger_default from "../utils/logger.js";
|
|
5
|
+
import { BackchannelLogoutConstants, InvalidLogoutTokenError } from "@thunderid/node";
|
|
6
|
+
|
|
7
|
+
//#region src/server/backchannelLogout.ts
|
|
8
|
+
const BODY_LIMIT_BYTES = 16 * 1024;
|
|
9
|
+
const respond = (status) => new Response(null, {
|
|
10
|
+
headers: { "Cache-Control": "no-store" },
|
|
11
|
+
status
|
|
12
|
+
});
|
|
13
|
+
/**
|
|
14
|
+
* Reads the request body as text, giving up once it passes the limit.
|
|
15
|
+
*/
|
|
16
|
+
const readBody = async (request) => {
|
|
17
|
+
if (Number(request.headers.get("content-length") ?? 0) > BODY_LIMIT_BYTES || !request.body) return;
|
|
18
|
+
const reader = request.body.getReader();
|
|
19
|
+
const decoder = new TextDecoder();
|
|
20
|
+
let body = "";
|
|
21
|
+
let size = 0;
|
|
22
|
+
for (;;) {
|
|
23
|
+
const { done, value } = await reader.read();
|
|
24
|
+
if (done) return body + decoder.decode();
|
|
25
|
+
size += value.byteLength;
|
|
26
|
+
if (size > BODY_LIMIT_BYTES) {
|
|
27
|
+
await reader.cancel();
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
body += decoder.decode(value, { stream: true });
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* Creates the route handler for OpenID Connect back-channel logout. ThunderID posts a
|
|
35
|
+
* `logout_token` to it when a session this application took part in ends. The session lives in a
|
|
36
|
+
* cookie the server cannot delete, so the handler records the logout, and every later request
|
|
37
|
+
* that presents a matching session cookie is treated as signed out.
|
|
38
|
+
*
|
|
39
|
+
* Mount it at the path registered as the application's back-channel logout URI:
|
|
40
|
+
*
|
|
41
|
+
* ```ts
|
|
42
|
+
* // app/api/auth/backchannel-logout/route.ts
|
|
43
|
+
* import {backchannelLogout} from '@thunderid/nextjs/server';
|
|
44
|
+
*
|
|
45
|
+
* export const {POST} = backchannelLogout();
|
|
46
|
+
* ```
|
|
47
|
+
*
|
|
48
|
+
* It answers `200` for a valid token, including one that names no session held here, `400` for a
|
|
49
|
+
* request or token that is not valid, and `500` when the logout could not be recorded, which
|
|
50
|
+
* makes the server try again. It needs no session cookie: the token's signature is the
|
|
51
|
+
* authentication.
|
|
52
|
+
*/
|
|
53
|
+
const backchannelLogout = (options = {}) => {
|
|
54
|
+
setLogoutRecordStore(options.store);
|
|
55
|
+
const POST = async (request) => {
|
|
56
|
+
if (!(request.headers.get("content-type")?.toLowerCase() ?? "").startsWith("application/x-www-form-urlencoded")) return respond(400);
|
|
57
|
+
const body = await readBody(request);
|
|
58
|
+
const logoutToken = body === void 0 ? null : new URLSearchParams(body).get(BackchannelLogoutConstants.TOKEN_PARAM);
|
|
59
|
+
if (!logoutToken) return respond(400);
|
|
60
|
+
try {
|
|
61
|
+
const client = getClient_default();
|
|
62
|
+
if (!client.isInitialized) await client.initialize({});
|
|
63
|
+
const result = await client.handleBackchannelLogout(logoutToken);
|
|
64
|
+
const config = await client.getConfiguration();
|
|
65
|
+
await getLoggedOutSessions().record({
|
|
66
|
+
...result,
|
|
67
|
+
clockTolerance: config?.tokenValidation?.idToken?.clockTolerance
|
|
68
|
+
}, SessionManager_default.resolveSessionCookieExpiry(config?.sessionCookie?.expiryTime));
|
|
69
|
+
try {
|
|
70
|
+
await options.onLogout?.(result);
|
|
71
|
+
} catch {
|
|
72
|
+
logger_default.error("[backchannelLogout] The onLogout hook failed.");
|
|
73
|
+
}
|
|
74
|
+
return respond(200);
|
|
75
|
+
} catch (error) {
|
|
76
|
+
if (error instanceof InvalidLogoutTokenError) {
|
|
77
|
+
logger_default.warn(`[backchannelLogout] Rejected a logout token (${error.code}).`);
|
|
78
|
+
return respond(400);
|
|
79
|
+
}
|
|
80
|
+
logger_default.error("[backchannelLogout] Could not complete a back-channel logout.");
|
|
81
|
+
return respond(500);
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
return { POST };
|
|
85
|
+
};
|
|
86
|
+
var backchannelLogout_default = backchannelLogout;
|
|
87
|
+
|
|
88
|
+
//#endregion
|
|
89
|
+
export { backchannelLogout_default as default };
|
|
90
|
+
//# sourceMappingURL=backchannelLogout.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"backchannelLogout.js","names":["reader: ReadableStreamDefaultReader<Uint8Array>","decoder: TextDecoder","body: string | undefined","logoutToken: string | null","client: ThunderIDNextClient","getClient","result: BackchannelLogoutResult","config: ThunderIDNextConfig","SessionManager","error: unknown"],"sources":["../../src/server/backchannelLogout.ts"],"sourcesContent":["// Copyright 2026 The ThunderID Authors\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n BackchannelLogoutConstants,\n BackchannelLogoutResult,\n InvalidLogoutTokenError,\n LogoutRecordStore,\n} from '@thunderid/node';\nimport getClient from './getClient';\nimport {ThunderIDNextConfig} from '../models/config';\nimport ThunderIDNextClient from '../ThunderIDNextClient';\nimport {getLoggedOutSessions, setLogoutRecordStore} from '../utils/loggedOutSessions';\nimport logger from '../utils/logger';\nimport SessionManager from '../utils/SessionManager';\n\n// A logout token is a kilobyte or two. The endpoint is unauthenticated, so nothing larger is read.\nconst BODY_LIMIT_BYTES = 16 * 1024;\n\nexport interface BackchannelLogoutOptions {\n /**\n * Called after a logout was recorded, so the application can clear what it holds for the ended\n * sessions. Best effort: a failure is logged and the handler still answers 200, since the logout\n * is already recorded and a retry would find nothing new.\n */\n onLogout?: (result: BackchannelLogoutResult) => void | Promise<void>;\n /**\n * Where ended sessions are recorded. Give the same store to `thunderIDProxy()`. Needed when more\n * than one instance of the application runs, or when the proxy runs on the Edge runtime, which\n * shares no memory with this handler. Defaults to the memory of this process.\n */\n store?: LogoutRecordStore;\n}\n\nconst respond = (status: number): Response => new Response(null, {headers: {'Cache-Control': 'no-store'}, status});\n\n/**\n * Reads the request body as text, giving up once it passes the limit.\n */\nconst readBody = async (request: Request): Promise<string | undefined> => {\n if (Number(request.headers.get('content-length') ?? 0) > BODY_LIMIT_BYTES || !request.body) {\n return undefined;\n }\n\n const reader: ReadableStreamDefaultReader<Uint8Array> = request.body.getReader();\n const decoder: TextDecoder = new TextDecoder();\n let body = '';\n let size = 0;\n\n for (;;) {\n const {done, value} = await reader.read();\n\n if (done) {\n return body + decoder.decode();\n }\n\n size += value.byteLength;\n\n if (size > BODY_LIMIT_BYTES) {\n await reader.cancel();\n\n return undefined;\n }\n\n body += decoder.decode(value, {stream: true});\n }\n};\n\n/**\n * Creates the route handler for OpenID Connect back-channel logout. ThunderID posts a\n * `logout_token` to it when a session this application took part in ends. The session lives in a\n * cookie the server cannot delete, so the handler records the logout, and every later request\n * that presents a matching session cookie is treated as signed out.\n *\n * Mount it at the path registered as the application's back-channel logout URI:\n *\n * ```ts\n * // app/api/auth/backchannel-logout/route.ts\n * import {backchannelLogout} from '@thunderid/nextjs/server';\n *\n * export const {POST} = backchannelLogout();\n * ```\n *\n * It answers `200` for a valid token, including one that names no session held here, `400` for a\n * request or token that is not valid, and `500` when the logout could not be recorded, which\n * makes the server try again. It needs no session cookie: the token's signature is the\n * authentication.\n */\nconst backchannelLogout = (options: BackchannelLogoutOptions = {}): {POST: (request: Request) => Promise<Response>} => {\n setLogoutRecordStore(options.store);\n\n const POST = async (request: Request): Promise<Response> => {\n const contentType: string = request.headers.get('content-type')?.toLowerCase() ?? '';\n\n if (!contentType.startsWith('application/x-www-form-urlencoded')) {\n return respond(400);\n }\n\n const body: string | undefined = await readBody(request);\n const logoutToken: string | null =\n body === undefined ? null : new URLSearchParams(body).get(BackchannelLogoutConstants.TOKEN_PARAM);\n\n if (!logoutToken) {\n return respond(400);\n }\n\n try {\n const client: ThunderIDNextClient = getClient();\n\n // A logout request can be the first thing a server process handles.\n if (!client.isInitialized) {\n await client.initialize({} as ThunderIDNextConfig);\n }\n\n const result: BackchannelLogoutResult = await client.handleBackchannelLogout(logoutToken);\n // Typed as synchronous, but it resolves from storage.\n const config: ThunderIDNextConfig = await (client.getConfiguration() as unknown as Promise<ThunderIDNextConfig>);\n\n // A session cookie cannot outlive this, so neither does the record that ends it.\n await getLoggedOutSessions().record(\n {...result, clockTolerance: config?.tokenValidation?.idToken?.clockTolerance},\n SessionManager.resolveSessionCookieExpiry(config?.sessionCookie?.expiryTime),\n );\n try {\n await options.onLogout?.(result);\n } catch {\n logger.error('[backchannelLogout] The onLogout hook failed.');\n }\n\n return respond(200);\n } catch (error: unknown) {\n if (error instanceof InvalidLogoutTokenError) {\n // The code says which check failed. The token itself is never logged.\n logger.warn(`[backchannelLogout] Rejected a logout token (${error.code}).`);\n\n return respond(400);\n }\n\n logger.error('[backchannelLogout] Could not complete a back-channel logout.');\n\n return respond(500);\n }\n };\n\n return {POST};\n};\n\nexport default backchannelLogout;\n"],"mappings":";;;;;;;AAiBA,MAAM,mBAAmB,KAAK;AAiB9B,MAAM,WAAW,WAA6B,IAAI,SAAS,MAAM;CAAC,SAAS,EAAC,iBAAiB,YAAW;CAAE;CAAO,CAAC;;;;AAKlH,MAAM,WAAW,OAAO,YAAkD;AACxE,KAAI,OAAO,QAAQ,QAAQ,IAAI,iBAAiB,IAAI,EAAE,GAAG,oBAAoB,CAAC,QAAQ,KACpF;CAGF,MAAMA,SAAkD,QAAQ,KAAK,WAAW;CAChF,MAAMC,UAAuB,IAAI,aAAa;CAC9C,IAAI,OAAO;CACX,IAAI,OAAO;AAEX,UAAS;EACP,MAAM,EAAC,MAAM,UAAS,MAAM,OAAO,MAAM;AAEzC,MAAI,KACF,QAAO,OAAO,QAAQ,QAAQ;AAGhC,UAAQ,MAAM;AAEd,MAAI,OAAO,kBAAkB;AAC3B,SAAM,OAAO,QAAQ;AAErB;;AAGF,UAAQ,QAAQ,OAAO,OAAO,EAAC,QAAQ,MAAK,CAAC;;;;;;;;;;;;;;;;;;;;;;;AAwBjD,MAAM,qBAAqB,UAAoC,EAAE,KAAsD;AACrH,sBAAqB,QAAQ,MAAM;CAEnC,MAAM,OAAO,OAAO,YAAwC;AAG1D,MAAI,EAFwB,QAAQ,QAAQ,IAAI,eAAe,EAAE,aAAa,IAAI,IAEjE,WAAW,oCAAoC,CAC9D,QAAO,QAAQ,IAAI;EAGrB,MAAMC,OAA2B,MAAM,SAAS,QAAQ;EACxD,MAAMC,cACJ,SAAS,SAAY,OAAO,IAAI,gBAAgB,KAAK,CAAC,IAAI,2BAA2B,YAAY;AAEnG,MAAI,CAAC,YACH,QAAO,QAAQ,IAAI;AAGrB,MAAI;GACF,MAAMC,SAA8BC,mBAAW;AAG/C,OAAI,CAAC,OAAO,cACV,OAAM,OAAO,WAAW,EAAE,CAAwB;GAGpD,MAAMC,SAAkC,MAAM,OAAO,wBAAwB,YAAY;GAEzF,MAAMC,SAA8B,MAAO,OAAO,kBAAkB;AAGpE,SAAM,sBAAsB,CAAC,OAC3B;IAAC,GAAG;IAAQ,gBAAgB,QAAQ,iBAAiB,SAAS;IAAe,EAC7EC,uBAAe,2BAA2B,QAAQ,eAAe,WAAW,CAC7E;AACD,OAAI;AACF,UAAM,QAAQ,WAAW,OAAO;WAC1B;AACN,mBAAO,MAAM,gDAAgD;;AAG/D,UAAO,QAAQ,IAAI;WACZC,OAAgB;AACvB,OAAI,iBAAiB,yBAAyB;AAE5C,mBAAO,KAAK,gDAAgD,MAAM,KAAK,IAAI;AAE3E,WAAO,QAAQ,IAAI;;AAGrB,kBAAO,MAAM,gEAAgE;AAE7E,UAAO,QAAQ,IAAI;;;AAIvB,QAAO,EAAC,MAAK;;AAGf,gCAAe"}
|
package/dist/server/index.d.ts
CHANGED
|
@@ -4,4 +4,6 @@ export * from './ThunderIDProvider.js';
|
|
|
4
4
|
export { default as thunderIDProxy } from './proxy/thunderIDProxy';
|
|
5
5
|
export * from './proxy/thunderIDProxy';
|
|
6
6
|
export { default as createRouteMatcher } from './proxy/createRouteMatcher';
|
|
7
|
+
export { default as backchannelLogout } from './backchannelLogout';
|
|
8
|
+
export type { BackchannelLogoutOptions } from './backchannelLogout';
|
|
7
9
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAKA,OAAO,EAAC,OAAO,IAAI,SAAS,EAAC,MAAM,aAAa,CAAC;AAEjD,OAAO,EAAC,OAAO,IAAI,iBAAiB,EAAC,MAAM,wBAAwB,CAAC;AACpE,cAAc,wBAAwB,CAAC;AAEvC,OAAO,EAAC,OAAO,IAAI,cAAc,EAAC,MAAM,wBAAwB,CAAC;AACjE,cAAc,wBAAwB,CAAC;AAEvC,OAAO,EAAC,OAAO,IAAI,kBAAkB,EAAC,MAAM,4BAA4B,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAKA,OAAO,EAAC,OAAO,IAAI,SAAS,EAAC,MAAM,aAAa,CAAC;AAEjD,OAAO,EAAC,OAAO,IAAI,iBAAiB,EAAC,MAAM,wBAAwB,CAAC;AACpE,cAAc,wBAAwB,CAAC;AAEvC,OAAO,EAAC,OAAO,IAAI,cAAc,EAAC,MAAM,wBAAwB,CAAC;AACjE,cAAc,wBAAwB,CAAC;AAEvC,OAAO,EAAC,OAAO,IAAI,kBAAkB,EAAC,MAAM,4BAA4B,CAAC;AAEzE,OAAO,EAAC,OAAO,IAAI,iBAAiB,EAAC,MAAM,qBAAqB,CAAC;AACjE,YAAY,EAAC,wBAAwB,EAAC,MAAM,qBAAqB,CAAC"}
|
package/dist/server/index.js
CHANGED
|
@@ -2,5 +2,6 @@ import thunderid_default from "./thunderid.js";
|
|
|
2
2
|
import ThunderIDProvider_default from "./ThunderIDProvider.js";
|
|
3
3
|
import thunderIDProxy_default, { removeChunkedCookieFromHeader, replaceChunkedCookieInHeader } from "./proxy/thunderIDProxy.js";
|
|
4
4
|
import createRouteMatcher_default from "./proxy/createRouteMatcher.js";
|
|
5
|
+
import backchannelLogout_default from "./backchannelLogout.js";
|
|
5
6
|
|
|
6
|
-
export { ThunderIDProvider_default as ThunderIDProvider, createRouteMatcher_default as createRouteMatcher, removeChunkedCookieFromHeader, replaceChunkedCookieInHeader, thunderIDProxy_default as thunderIDProxy, thunderid_default as thunderid };
|
|
7
|
+
export { ThunderIDProvider_default as ThunderIDProvider, backchannelLogout_default as backchannelLogout, createRouteMatcher_default as createRouteMatcher, removeChunkedCookieFromHeader, replaceChunkedCookieInHeader, thunderIDProxy_default as thunderIDProxy, thunderid_default as thunderid };
|
|
@@ -1,7 +1,18 @@
|
|
|
1
|
+
import { LogoutRecordStore } from '@thunderid/node';
|
|
1
2
|
import { NextRequest, NextResponse } from 'next/server';
|
|
2
3
|
import { ThunderIDNextConfig } from '../../models/config';
|
|
3
4
|
import { SessionTokenPayload } from '../../utils/SessionManager';
|
|
4
|
-
export type ThunderIDProxyOptions = Partial<ThunderIDNextConfig
|
|
5
|
+
export type ThunderIDProxyOptions = Partial<ThunderIDNextConfig> & {
|
|
6
|
+
/**
|
|
7
|
+
* Where sessions ended by back-channel logout are recorded. Give the same store to
|
|
8
|
+
* `backchannelLogout()`. Needed when more than one instance of the application runs, or when
|
|
9
|
+
* this proxy runs on the Edge runtime, which shares no memory with the route handler. Defaults
|
|
10
|
+
* to the memory of this process.
|
|
11
|
+
*/
|
|
12
|
+
backchannelLogout?: {
|
|
13
|
+
store?: LogoutRecordStore;
|
|
14
|
+
};
|
|
15
|
+
};
|
|
5
16
|
export interface ThunderIDProxyContext {
|
|
6
17
|
/** Get the session payload from JWT session if available */
|
|
7
18
|
getSession: () => Promise<SessionTokenPayload | undefined>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thunderIDProxy.d.ts","sourceRoot":"","sources":["../../../src/server/proxy/thunderIDProxy.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"thunderIDProxy.d.ts","sourceRoot":"","sources":["../../../src/server/proxy/thunderIDProxy.ts"],"names":[],"mappings":"AAGA,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,UAAU,qBAAqB,EAC/B,UAAU,qBAAqB,GAAG,CAAC,CAAC,GAAG,EAAE,WAAW,KAAK,qBAAqB,CAAC,KAC9E,CAAC,CAAC,OAAO,EAAE,WAAW,KAAK,OAAO,CAAC,YAAY,CAAC,CAoNlD,CAAC;AAEJ,eAAe,cAAc,CAAC"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { deleteChunkedCookie, getChunkedCookie, setChunkedCookie } from "../../utils/chunkedCookie.js";
|
|
2
|
+
import { setLogoutRecordStore } from "../../utils/loggedOutSessions.js";
|
|
2
3
|
import { REFRESH_BUFFER_SECONDS } from "../../constants/sessionConstants.js";
|
|
3
4
|
import SessionManager_default from "../../utils/SessionManager.js";
|
|
4
5
|
import decorateConfigWithNextEnv_default from "../../utils/decorateConfigWithNextEnv.js";
|
|
@@ -103,7 +104,9 @@ const toChunkedCookieWriter = (request, responseCookies) => ({
|
|
|
103
104
|
* ```
|
|
104
105
|
*/
|
|
105
106
|
const thunderIDProxy = (handler, options) => async (request) => {
|
|
106
|
-
const
|
|
107
|
+
const resolvedOptions = typeof options === "function" ? options(request) : options || {};
|
|
108
|
+
setLogoutRecordStore(resolvedOptions.backchannelLogout?.store);
|
|
109
|
+
const resolvedConfig = decorateConfigWithNextEnv_default(resolvedOptions);
|
|
107
110
|
const url = new URL(request.url);
|
|
108
111
|
const hasCallbackParams = url.searchParams.has("code") && url.searchParams.has("state");
|
|
109
112
|
let isValidOAuthCallback = false;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thunderIDProxy.js","names":["eqIdx: number","entries: {name: string; part: string}[]","remaining: string[]","newParts: string[]","resolvedConfig: ThunderIDNextConfig","decorateConfigWithNextEnv","url: URL","hasCallbackParams: boolean","tempSessionToken: string | undefined","SessionManager","verifiedSession: SessionTokenPayload | undefined","expiredSession: SessionTokenPayload | undefined","rawToken: string | undefined","decoded: SessionTokenPayload","now: number","candidateSession: SessionTokenPayload | undefined","needsRefresh: boolean","activeSession: SessionTokenPayload | undefined","refreshCookieUpdate: {expiry: number; token: string} | undefined","handleRefreshToken","rawSessionCookie: string | undefined","sessionId: string | undefined","handlerResponse: NextResponse | void","referer: string | null","refererUrl: URL","requestUrl: URL","redirectUrl: string","cookieName: string","cookieName","requestHeaders: Headers","cleanResponse: NextResponse","requestHeaders","cookieOptions: ReturnType<typeof SessionManager.getSessionCookieOptions>","updatedCookieHeader: string","response: NextResponse"],"sources":["../../../src/server/proxy/thunderIDProxy.ts"],"sourcesContent":["// Copyright 2025 The ThunderID Authors\n// SPDX-License-Identifier: Apache-2.0\n\nimport {CookieChunking} from '@thunderid/node';\nimport {NextRequest, NextResponse} from 'next/server';\nimport {REFRESH_BUFFER_SECONDS} from '../../constants/sessionConstants';\nimport {ThunderIDNextConfig} from '../../models/config';\nimport {\n ChunkedCookieOptions,\n ChunkedCookieWriter,\n deleteChunkedCookie,\n getChunkedCookie,\n setChunkedCookie,\n} from '../../utils/chunkedCookie';\nimport decorateConfigWithNextEnv from '../../utils/decorateConfigWithNextEnv';\nimport handleRefreshToken from '../../utils/handleRefreshToken';\nimport SessionManager, {SessionTokenPayload} from '../../utils/SessionManager';\nimport {getSessionFromRequest, getSessionIdFromRequest} from '../../utils/sessionUtils';\n\nexport type ThunderIDProxyOptions = Partial<ThunderIDNextConfig>;\n\nexport interface ThunderIDProxyContext {\n /** Get the session payload from JWT session if available */\n getSession: () => Promise<SessionTokenPayload | undefined>;\n /** Get the session ID from the current request */\n getSessionId: () => string | undefined;\n /** Check if the current request has a valid ThunderID session */\n isSignedIn: () => boolean;\n /**\n * Protect a route by redirecting unauthenticated users.\n * Redirect URL fallback order:\n * 1. options.redirect\n * 2. resolvedOptions.signInUrl\n * 3. resolvedOptions.defaultRedirect\n * 4. referer (if from same origin)\n * If none are available, falls back to '/'.\n */\n protectRoute: (routeOptions?: {redirect?: string}) => Promise<NextResponse | void>;\n}\n\ntype ThunderIDProxyHandler = (\n thunderid: ThunderIDProxyContext,\n req: NextRequest,\n) => Promise<NextResponse | void> | NextResponse | void;\n\n/**\n * Splits a raw Cookie header string into its `{name, part}` entries, where\n * `part` is the original `name=value` text (trimmed, never empty).\n */\nconst parseCookieHeaderParts = (cookieHeader: string): {name: string; part: string}[] =>\n cookieHeader\n .split(';')\n .map((p: string) => p.trim())\n .filter(Boolean)\n .map((part: string) => {\n const eqIdx: number = part.indexOf('=');\n const name: string = eqIdx === -1 ? part : part.slice(0, eqIdx).trim();\n return {name, part};\n });\n\n/**\n * Removes a cookie from a raw Cookie header string — the unchunked `name`\n * entry and/or any numbered `${name}.0`, `${name}.1`, ... chunk entries.\n */\nexport const removeChunkedCookieFromHeader = (cookieHeader: string, name: string): string => {\n const entries: {name: string; part: string}[] = parseCookieHeaderParts(cookieHeader);\n const toRemove = new Set<string>(\n CookieChunking.filterChunkNames(\n name,\n entries.map((e) => e.name),\n ),\n );\n\n return entries\n .filter((e) => !toRemove.has(e.name))\n .map((e) => e.part)\n .join('; ');\n};\n\n/**\n * Replaces a cookie's value inside a raw Cookie header string, splitting it\n * across numbered `${name}.0`, `${name}.1`, ... chunk entries once it would\n * exceed the ~4KB per-cookie limit browsers enforce. Any entry the cookie\n * doesn't appear in yet is appended; stale chunk entries a shrunk value no\n * longer needs are dropped.\n */\nexport const replaceChunkedCookieInHeader = (cookieHeader: string, name: string, value: string): string => {\n const remaining: string[] = parseCookieHeaderParts(removeChunkedCookieFromHeader(cookieHeader, name)).map(\n (e) => e.part,\n );\n const newParts: string[] = Object.entries(CookieChunking.split(name, value)).map(\n ([chunkName, chunkValue]: [string, string]) => `${chunkName}=${chunkValue}`,\n );\n\n return [...remaining, ...newParts].join('; ');\n};\n\n/**\n * Adapts a request/response pair into a {@link ChunkedCookieWriter}: existing\n * chunk names are discovered from the incoming request's cookies (what the\n * browser currently holds), while writes/deletes apply to the response.\n */\nconst toChunkedCookieWriter = (\n request: NextRequest,\n responseCookies: NextResponse['cookies'],\n): ChunkedCookieWriter => ({\n delete: (name: string): void => {\n responseCookies.delete(name);\n },\n getAll: (): {name: string}[] => request.cookies.getAll(),\n set: (name: string, value: string, options: ChunkedCookieOptions): void => {\n responseCookies.set(name, value, options);\n },\n});\n\n/**\n * ThunderID proxy that integrates authentication into your Next.js application.\n * Similar to Clerk's clerkMiddleware pattern.\n *\n * Proactively refreshes the access token when it is within REFRESH_BUFFER_SECONDS of\n * expiry so that Server Components always receive a fresh session. The refresh also\n * recovers expired tokens as long as a refresh token is present.\n *\n * The updated session cookie is written to:\n * - The response → browser stores the new cookie for subsequent requests.\n * - The forwarded request headers → the same-request Server Component render sees\n * the fresh token immediately without waiting for the next navigation.\n *\n * Token refresh requires baseUrl, clientId, and clientSecret. These are resolved from\n * the options argument first, then from the standard ThunderID environment variables\n * (NEXT_PUBLIC_THUNDERID_BASE_URL, NEXT_PUBLIC_THUNDERID_CLIENT_ID,\n * THUNDERID_CLIENT_SECRET). If none are available the refresh step is skipped silently.\n *\n * @param handler - Optional handler function to customize proxy behavior\n * @param options - Configuration options for the proxy\n * @returns Next.js middleware function\n *\n * @example\n * ```typescript\n * // middleware.ts - Basic usage (config read from env vars automatically)\n * import { thunderIDProxy } from '@thunderid/nextjs/server';\n *\n * export default thunderIDProxy();\n *\n * export const config = {\n * matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],\n * };\n * ```\n *\n * @example\n * ```typescript\n * // With route protection\n * import { thunderIDProxy, createRouteMatcher } from '@thunderid/nextjs/server';\n *\n * const isProtectedRoute = createRouteMatcher(['/dashboard(.*)']);\n *\n * export default thunderIDProxy(async (thunderid, req) => {\n * if (isProtectedRoute(req)) {\n * await thunderid.protectRoute();\n * }\n * });\n * ```\n */\nconst thunderIDProxy =\n (\n handler?: ThunderIDProxyHandler,\n options?: ThunderIDProxyOptions | ((req: NextRequest) => ThunderIDProxyOptions),\n ): ((request: NextRequest) => Promise<NextResponse>) =>\n async (request: NextRequest): Promise<NextResponse> => {\n const resolvedOptions: ThunderIDProxyOptions = typeof options === 'function' ? options(request) : options || {};\n\n // Resolve full config from passed options + environment variable fallbacks.\n const resolvedConfig: ThunderIDNextConfig = decorateConfigWithNextEnv(resolvedOptions as ThunderIDNextConfig);\n\n // ── OAuth callback detection ──────────────────────────────────────────────\n const url: URL = new URL(request.url);\n const hasCallbackParams: boolean = url.searchParams.has('code') && url.searchParams.has('state');\n\n let isValidOAuthCallback = false;\n if (hasCallbackParams && !url.searchParams.has('error')) {\n const tempSessionToken: string | undefined = request.cookies.get(\n SessionManager.getTempSessionCookieName(),\n )?.value;\n if (tempSessionToken) {\n try {\n await SessionManager.verifyTempSession(tempSessionToken);\n isValidOAuthCallback = true;\n } catch {\n isValidOAuthCallback = false;\n }\n }\n }\n\n // ── Session resolution ────────────────────────────────────────────────────\n // Step 1: Attempt to get a fully verified (signature + expiry) session.\n const verifiedSession: SessionTokenPayload | undefined = await getSessionFromRequest(request);\n\n // Step 2: If no verified session exists, verify the raw cookie's signature\n // without enforcing expiry. This allows the proxy to recover from an\n // expired access token as long as the JWT is authentic and a refresh token\n // is present. Skipping the signature check here would let a tampered cookie\n // drive identity-confusion attacks since handleRefreshToken reuses `sub`,\n // `sessionId`, and `organizationId` from the input payload when minting the\n // new session JWT.\n let expiredSession: SessionTokenPayload | undefined;\n if (!verifiedSession) {\n const rawToken: string | undefined = getChunkedCookie(request.cookies, SessionManager.getSessionCookieName());\n if (rawToken) {\n try {\n const decoded: SessionTokenPayload = await SessionManager.verifySessionTokenForRefresh(rawToken);\n if (decoded.refreshToken) {\n expiredSession = decoded;\n }\n } catch {\n // Forged, tampered, wrong type, or malformed — ignore.\n }\n }\n }\n\n // ── Token refresh ─────────────────────────────────────────────────────────\n const now: number = Math.floor(Date.now() / 1000);\n const candidateSession: SessionTokenPayload | undefined = verifiedSession ?? expiredSession;\n\n // Config is required to call the token endpoint.\n const hasRefreshConfig = !!(resolvedConfig.baseUrl && resolvedConfig.clientId && resolvedConfig.clientSecret);\n\n // Refresh when:\n // a) Token is verified but within the proactive buffer window, OR\n // b) Token has already expired but a refresh token is available.\n const needsRefresh: boolean =\n !isValidOAuthCallback &&\n hasRefreshConfig &&\n !!candidateSession?.refreshToken &&\n ((!!verifiedSession && verifiedSession.exp <= now + REFRESH_BUFFER_SECONDS) || !!expiredSession);\n\n let activeSession: SessionTokenPayload | undefined = verifiedSession;\n let refreshCookieUpdate: {expiry: number; token: string} | undefined;\n\n if (needsRefresh && candidateSession) {\n try {\n const {newSessionToken, sessionCookieExpiryTime} = await handleRefreshToken(candidateSession, {\n baseUrl: resolvedConfig.baseUrl!,\n clientId: resolvedConfig.clientId!,\n clientSecret: resolvedConfig.clientSecret!,\n sessionCookie: resolvedConfig.sessionCookie,\n });\n // Verify the newly minted token so activeSession reflects fresh claims.\n activeSession = await SessionManager.verifySessionToken(newSessionToken);\n refreshCookieUpdate = {expiry: sessionCookieExpiryTime, token: newSessionToken};\n } catch {\n // Refresh failed — clear the irrecoverable session.\n activeSession = undefined;\n }\n }\n\n // ── Session cleanup detection ─────────────────────────────────────────────\n // Mark stale cookies for deletion when the session is irrecoverable. Skipped\n // during OAuth callbacks where a session cookie may not exist yet.\n const rawSessionCookie: string | undefined = getChunkedCookie(\n request.cookies,\n SessionManager.getSessionCookieName(),\n );\n\n let shouldClearCookie = false;\n\n if (!isValidOAuthCallback && rawSessionCookie && !activeSession && !refreshCookieUpdate) {\n // A cookie was present but all resolution paths (verify, decode, refresh)\n // failed — the session is dead and cannot be recovered.\n shouldClearCookie = true;\n }\n\n const sessionId: string | undefined = activeSession?.sessionId ?? (await getSessionIdFromRequest(request));\n const isAuthenticated = !!activeSession;\n\n // ── Proxy context ─────────────────────────────────────────────────────────\n const thunderid: ThunderIDProxyContext = {\n getSession: async (): Promise<SessionTokenPayload | undefined> => activeSession,\n getSessionId: (): string | undefined => sessionId,\n isSignedIn: (): boolean => isAuthenticated,\n protectRoute: async (routeOptions?: {redirect?: string}): Promise<NextResponse | void> => {\n // Skip during a valid OAuth callback to avoid redirecting before the\n // callback action has had a chance to complete.\n if (isValidOAuthCallback) {\n return undefined;\n }\n\n if (!isAuthenticated) {\n const referer: string | null = request.headers.get('referer');\n let fallbackRedirect = '/';\n\n if (referer) {\n try {\n const refererUrl: URL = new URL(referer);\n const requestUrl: URL = new URL(request.url);\n if (refererUrl.origin === requestUrl.origin) {\n fallbackRedirect = refererUrl.pathname + refererUrl.search;\n }\n } catch {\n // Invalid referer — ignore.\n }\n }\n\n const redirectUrl: string = routeOptions?.redirect ?? resolvedConfig.signInUrl! ?? fallbackRedirect;\n\n return NextResponse.redirect(new URL(redirectUrl, request.url));\n }\n\n return undefined;\n },\n };\n\n // ── Handler ───────────────────────────────────────────────────────────────\n const handlerResponse: NextResponse | void = handler ? await handler(thunderid, request) : undefined;\n\n // ── Build final response ──────────────────────────────────────────────────\n if (shouldClearCookie) {\n const cookieName: string = SessionManager.getSessionCookieName();\n\n if (handlerResponse) {\n // Handler returned a response (e.g. a redirect from protectRoute).\n // Attach the deletion so the browser discards the stale cookie (and\n // every chunk of it).\n deleteChunkedCookie(toChunkedCookieWriter(request, handlerResponse.cookies), cookieName);\n return handlerResponse;\n }\n\n // Pass-through: strip the dead cookie from the forwarded request headers\n // so the same-request Server Component render sees no session at all.\n const requestHeaders: Headers = new Headers(request.headers);\n requestHeaders.set('cookie', removeChunkedCookieFromHeader(request.headers.get('cookie') ?? '', cookieName));\n const cleanResponse: NextResponse = NextResponse.next({request: {headers: requestHeaders}});\n deleteChunkedCookie(toChunkedCookieWriter(request, cleanResponse.cookies), cookieName);\n return cleanResponse;\n }\n\n if (!refreshCookieUpdate) {\n return handlerResponse ?? NextResponse.next();\n }\n\n // A token refresh occurred — the new session cookie must be applied to:\n // 1. The HTTP response so the browser stores the updated cookie.\n // 2. The forwarded request headers so the same-request Server Component\n // render reads the fresh session token instead of the expired one.\n const cookieName: string = SessionManager.getSessionCookieName();\n const cookieOptions: ReturnType<typeof SessionManager.getSessionCookieOptions> =\n SessionManager.getSessionCookieOptions(refreshCookieUpdate.expiry);\n\n if (handlerResponse) {\n // Handler returned a response (e.g. a redirect from protectRoute).\n // Attach the refresh cookie so the browser receives it even on redirects.\n setChunkedCookie(\n toChunkedCookieWriter(request, handlerResponse.cookies),\n cookieName,\n refreshCookieUpdate.token,\n cookieOptions,\n );\n return handlerResponse;\n }\n\n // Default pass-through: update both the response cookie and the request\n // Cookie header so the downstream Server Component render is not stale.\n const requestHeaders: Headers = new Headers(request.headers);\n const updatedCookieHeader: string = replaceChunkedCookieInHeader(\n request.headers.get('cookie') ?? '',\n cookieName,\n refreshCookieUpdate.token,\n );\n requestHeaders.set('cookie', updatedCookieHeader);\n\n const response: NextResponse = NextResponse.next({request: {headers: requestHeaders}});\n setChunkedCookie(\n toChunkedCookieWriter(request, response.cookies),\n cookieName,\n refreshCookieUpdate.token,\n cookieOptions,\n );\n return response;\n };\n\nexport default thunderIDProxy;\n"],"mappings":";;;;;;;;;;;;;;AAiDA,MAAM,0BAA0B,iBAC9B,aACG,MAAM,IAAI,CACV,KAAK,MAAc,EAAE,MAAM,CAAC,CAC5B,OAAO,QAAQ,CACf,KAAK,SAAiB;CACrB,MAAMA,QAAgB,KAAK,QAAQ,IAAI;AAEvC,QAAO;EAAC,MADa,UAAU,KAAK,OAAO,KAAK,MAAM,GAAG,MAAM,CAAC,MAAM;EACxD;EAAK;EACnB;;;;;AAMN,MAAa,iCAAiC,cAAsB,SAAyB;CAC3F,MAAMC,UAA0C,uBAAuB,aAAa;CACpF,MAAM,WAAW,IAAI,IACnB,eAAe,iBACb,MACA,QAAQ,KAAK,MAAM,EAAE,KAAK,CAC3B,CACF;AAED,QAAO,QACJ,QAAQ,MAAM,CAAC,SAAS,IAAI,EAAE,KAAK,CAAC,CACpC,KAAK,MAAM,EAAE,KAAK,CAClB,KAAK,KAAK;;;;;;;;;AAUf,MAAa,gCAAgC,cAAsB,MAAc,UAA0B;CACzG,MAAMC,YAAsB,uBAAuB,8BAA8B,cAAc,KAAK,CAAC,CAAC,KACnG,MAAM,EAAE,KACV;CACD,MAAMC,WAA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","remaining: string[]","newParts: string[]","resolvedOptions: ThunderIDProxyOptions","resolvedConfig: ThunderIDNextConfig","decorateConfigWithNextEnv","url: URL","hasCallbackParams: boolean","tempSessionToken: string | undefined","SessionManager","verifiedSession: SessionTokenPayload | undefined","expiredSession: SessionTokenPayload | undefined","rawToken: string | undefined","decoded: SessionTokenPayload","now: number","candidateSession: SessionTokenPayload | undefined","needsRefresh: boolean","activeSession: SessionTokenPayload | undefined","refreshCookieUpdate: {expiry: number; token: string} | undefined","handleRefreshToken","rawSessionCookie: string | undefined","sessionId: string | undefined","handlerResponse: NextResponse | void","referer: string | null","refererUrl: URL","requestUrl: URL","redirectUrl: string","cookieName: string","cookieName","requestHeaders: Headers","cleanResponse: NextResponse","requestHeaders","cookieOptions: ReturnType<typeof SessionManager.getSessionCookieOptions>","updatedCookieHeader: string","response: NextResponse"],"sources":["../../../src/server/proxy/thunderIDProxy.ts"],"sourcesContent":["// Copyright 2025 The ThunderID Authors\n// SPDX-License-Identifier: Apache-2.0\n\nimport {CookieChunking, LogoutRecordStore} from '@thunderid/node';\nimport {NextRequest, NextResponse} from 'next/server';\nimport {REFRESH_BUFFER_SECONDS} from '../../constants/sessionConstants';\nimport {ThunderIDNextConfig} from '../../models/config';\nimport {\n ChunkedCookieOptions,\n ChunkedCookieWriter,\n deleteChunkedCookie,\n getChunkedCookie,\n setChunkedCookie,\n} from '../../utils/chunkedCookie';\nimport decorateConfigWithNextEnv from '../../utils/decorateConfigWithNextEnv';\nimport handleRefreshToken from '../../utils/handleRefreshToken';\nimport {setLogoutRecordStore} from '../../utils/loggedOutSessions';\nimport SessionManager, {SessionTokenPayload} from '../../utils/SessionManager';\nimport {getSessionFromRequest, getSessionIdFromRequest} from '../../utils/sessionUtils';\n\nexport type ThunderIDProxyOptions = Partial<ThunderIDNextConfig> & {\n /**\n * Where sessions ended by back-channel logout are recorded. Give the same store to\n * `backchannelLogout()`. Needed when more than one instance of the application runs, or when\n * this proxy runs on the Edge runtime, which shares no memory with the route handler. Defaults\n * to the memory of this process.\n */\n backchannelLogout?: {store?: LogoutRecordStore};\n};\n\nexport interface ThunderIDProxyContext {\n /** Get the session payload from JWT session if available */\n getSession: () => Promise<SessionTokenPayload | undefined>;\n /** Get the session ID from the current request */\n getSessionId: () => string | undefined;\n /** Check if the current request has a valid ThunderID session */\n isSignedIn: () => boolean;\n /**\n * Protect a route by redirecting unauthenticated users.\n * Redirect URL fallback order:\n * 1. options.redirect\n * 2. resolvedOptions.signInUrl\n * 3. resolvedOptions.defaultRedirect\n * 4. referer (if from same origin)\n * If none are available, falls back to '/'.\n */\n protectRoute: (routeOptions?: {redirect?: string}) => Promise<NextResponse | void>;\n}\n\ntype ThunderIDProxyHandler = (\n thunderid: ThunderIDProxyContext,\n req: NextRequest,\n) => Promise<NextResponse | void> | NextResponse | void;\n\n/**\n * Splits a raw Cookie header string into its `{name, part}` entries, where\n * `part` is the original `name=value` text (trimmed, never empty).\n */\nconst parseCookieHeaderParts = (cookieHeader: string): {name: string; part: string}[] =>\n cookieHeader\n .split(';')\n .map((p: string) => p.trim())\n .filter(Boolean)\n .map((part: string) => {\n const eqIdx: number = part.indexOf('=');\n const name: string = eqIdx === -1 ? part : part.slice(0, eqIdx).trim();\n return {name, part};\n });\n\n/**\n * Removes a cookie from a raw Cookie header string — the unchunked `name`\n * entry and/or any numbered `${name}.0`, `${name}.1`, ... chunk entries.\n */\nexport const removeChunkedCookieFromHeader = (cookieHeader: string, name: string): string => {\n const entries: {name: string; part: string}[] = parseCookieHeaderParts(cookieHeader);\n const toRemove = new Set<string>(\n CookieChunking.filterChunkNames(\n name,\n entries.map((e) => e.name),\n ),\n );\n\n return entries\n .filter((e) => !toRemove.has(e.name))\n .map((e) => e.part)\n .join('; ');\n};\n\n/**\n * Replaces a cookie's value inside a raw Cookie header string, splitting it\n * across numbered `${name}.0`, `${name}.1`, ... chunk entries once it would\n * exceed the ~4KB per-cookie limit browsers enforce. Any entry the cookie\n * doesn't appear in yet is appended; stale chunk entries a shrunk value no\n * longer needs are dropped.\n */\nexport const replaceChunkedCookieInHeader = (cookieHeader: string, name: string, value: string): string => {\n const remaining: string[] = parseCookieHeaderParts(removeChunkedCookieFromHeader(cookieHeader, name)).map(\n (e) => e.part,\n );\n const newParts: string[] = Object.entries(CookieChunking.split(name, value)).map(\n ([chunkName, chunkValue]: [string, string]) => `${chunkName}=${chunkValue}`,\n );\n\n return [...remaining, ...newParts].join('; ');\n};\n\n/**\n * Adapts a request/response pair into a {@link ChunkedCookieWriter}: existing\n * chunk names are discovered from the incoming request's cookies (what the\n * browser currently holds), while writes/deletes apply to the response.\n */\nconst toChunkedCookieWriter = (\n request: NextRequest,\n responseCookies: NextResponse['cookies'],\n): ChunkedCookieWriter => ({\n delete: (name: string): void => {\n responseCookies.delete(name);\n },\n getAll: (): {name: string}[] => request.cookies.getAll(),\n set: (name: string, value: string, options: ChunkedCookieOptions): void => {\n responseCookies.set(name, value, options);\n },\n});\n\n/**\n * ThunderID proxy that integrates authentication into your Next.js application.\n * Similar to Clerk's clerkMiddleware pattern.\n *\n * Proactively refreshes the access token when it is within REFRESH_BUFFER_SECONDS of\n * expiry so that Server Components always receive a fresh session. The refresh also\n * recovers expired tokens as long as a refresh token is present.\n *\n * The updated session cookie is written to:\n * - The response → browser stores the new cookie for subsequent requests.\n * - The forwarded request headers → the same-request Server Component render sees\n * the fresh token immediately without waiting for the next navigation.\n *\n * Token refresh requires baseUrl, clientId, and clientSecret. These are resolved from\n * the options argument first, then from the standard ThunderID environment variables\n * (NEXT_PUBLIC_THUNDERID_BASE_URL, NEXT_PUBLIC_THUNDERID_CLIENT_ID,\n * THUNDERID_CLIENT_SECRET). If none are available the refresh step is skipped silently.\n *\n * @param handler - Optional handler function to customize proxy behavior\n * @param options - Configuration options for the proxy\n * @returns Next.js middleware function\n *\n * @example\n * ```typescript\n * // middleware.ts - Basic usage (config read from env vars automatically)\n * import { thunderIDProxy } from '@thunderid/nextjs/server';\n *\n * export default thunderIDProxy();\n *\n * export const config = {\n * matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],\n * };\n * ```\n *\n * @example\n * ```typescript\n * // With route protection\n * import { thunderIDProxy, createRouteMatcher } from '@thunderid/nextjs/server';\n *\n * const isProtectedRoute = createRouteMatcher(['/dashboard(.*)']);\n *\n * export default thunderIDProxy(async (thunderid, req) => {\n * if (isProtectedRoute(req)) {\n * await thunderid.protectRoute();\n * }\n * });\n * ```\n */\nconst thunderIDProxy =\n (\n handler?: ThunderIDProxyHandler,\n options?: ThunderIDProxyOptions | ((req: NextRequest) => ThunderIDProxyOptions),\n ): ((request: NextRequest) => Promise<NextResponse>) =>\n async (request: NextRequest): Promise<NextResponse> => {\n const resolvedOptions: ThunderIDProxyOptions = typeof options === 'function' ? options(request) : options || {};\n\n setLogoutRecordStore(resolvedOptions.backchannelLogout?.store);\n\n // Resolve full config from passed options + environment variable fallbacks.\n const resolvedConfig: ThunderIDNextConfig = decorateConfigWithNextEnv(resolvedOptions as ThunderIDNextConfig);\n\n // ── OAuth callback detection ──────────────────────────────────────────────\n const url: URL = new URL(request.url);\n const hasCallbackParams: boolean = url.searchParams.has('code') && url.searchParams.has('state');\n\n let isValidOAuthCallback = false;\n if (hasCallbackParams && !url.searchParams.has('error')) {\n const tempSessionToken: string | undefined = request.cookies.get(\n SessionManager.getTempSessionCookieName(),\n )?.value;\n if (tempSessionToken) {\n try {\n await SessionManager.verifyTempSession(tempSessionToken);\n isValidOAuthCallback = true;\n } catch {\n isValidOAuthCallback = false;\n }\n }\n }\n\n // ── Session resolution ────────────────────────────────────────────────────\n // Step 1: Attempt to get a fully verified (signature + expiry) session.\n const verifiedSession: SessionTokenPayload | undefined = await getSessionFromRequest(request);\n\n // Step 2: If no verified session exists, verify the raw cookie's signature\n // without enforcing expiry. This allows the proxy to recover from an\n // expired access token as long as the JWT is authentic and a refresh token\n // is present. Skipping the signature check here would let a tampered cookie\n // drive identity-confusion attacks since handleRefreshToken reuses `sub`,\n // `sessionId`, and `organizationId` from the input payload when minting the\n // new session JWT.\n let expiredSession: SessionTokenPayload | undefined;\n if (!verifiedSession) {\n const rawToken: string | undefined = getChunkedCookie(request.cookies, SessionManager.getSessionCookieName());\n if (rawToken) {\n try {\n const decoded: SessionTokenPayload = await SessionManager.verifySessionTokenForRefresh(rawToken);\n if (decoded.refreshToken) {\n expiredSession = decoded;\n }\n } catch {\n // Forged, tampered, wrong type, or malformed — ignore.\n }\n }\n }\n\n // ── Token refresh ─────────────────────────────────────────────────────────\n const now: number = Math.floor(Date.now() / 1000);\n const candidateSession: SessionTokenPayload | undefined = verifiedSession ?? expiredSession;\n\n // Config is required to call the token endpoint.\n const hasRefreshConfig = !!(resolvedConfig.baseUrl && resolvedConfig.clientId && resolvedConfig.clientSecret);\n\n // Refresh when:\n // a) Token is verified but within the proactive buffer window, OR\n // b) Token has already expired but a refresh token is available.\n const needsRefresh: boolean =\n !isValidOAuthCallback &&\n hasRefreshConfig &&\n !!candidateSession?.refreshToken &&\n ((!!verifiedSession && verifiedSession.exp <= now + REFRESH_BUFFER_SECONDS) || !!expiredSession);\n\n let activeSession: SessionTokenPayload | undefined = verifiedSession;\n let refreshCookieUpdate: {expiry: number; token: string} | undefined;\n\n if (needsRefresh && candidateSession) {\n try {\n const {newSessionToken, sessionCookieExpiryTime} = await handleRefreshToken(candidateSession, {\n baseUrl: resolvedConfig.baseUrl!,\n clientId: resolvedConfig.clientId!,\n clientSecret: resolvedConfig.clientSecret!,\n sessionCookie: resolvedConfig.sessionCookie,\n });\n // Verify the newly minted token so activeSession reflects fresh claims.\n activeSession = await SessionManager.verifySessionToken(newSessionToken);\n refreshCookieUpdate = {expiry: sessionCookieExpiryTime, token: newSessionToken};\n } catch {\n // Refresh failed — clear the irrecoverable session.\n activeSession = undefined;\n }\n }\n\n // ── Session cleanup detection ─────────────────────────────────────────────\n // Mark stale cookies for deletion when the session is irrecoverable. Skipped\n // during OAuth callbacks where a session cookie may not exist yet.\n const rawSessionCookie: string | undefined = getChunkedCookie(\n request.cookies,\n SessionManager.getSessionCookieName(),\n );\n\n let shouldClearCookie = false;\n\n if (!isValidOAuthCallback && rawSessionCookie && !activeSession && !refreshCookieUpdate) {\n // A cookie was present but all resolution paths (verify, decode, refresh)\n // failed — the session is dead and cannot be recovered.\n shouldClearCookie = true;\n }\n\n const sessionId: string | undefined = activeSession?.sessionId ?? (await getSessionIdFromRequest(request));\n const isAuthenticated = !!activeSession;\n\n // ── Proxy context ─────────────────────────────────────────────────────────\n const thunderid: ThunderIDProxyContext = {\n getSession: async (): Promise<SessionTokenPayload | undefined> => activeSession,\n getSessionId: (): string | undefined => sessionId,\n isSignedIn: (): boolean => isAuthenticated,\n protectRoute: async (routeOptions?: {redirect?: string}): Promise<NextResponse | void> => {\n // Skip during a valid OAuth callback to avoid redirecting before the\n // callback action has had a chance to complete.\n if (isValidOAuthCallback) {\n return undefined;\n }\n\n if (!isAuthenticated) {\n const referer: string | null = request.headers.get('referer');\n let fallbackRedirect = '/';\n\n if (referer) {\n try {\n const refererUrl: URL = new URL(referer);\n const requestUrl: URL = new URL(request.url);\n if (refererUrl.origin === requestUrl.origin) {\n fallbackRedirect = refererUrl.pathname + refererUrl.search;\n }\n } catch {\n // Invalid referer — ignore.\n }\n }\n\n const redirectUrl: string = routeOptions?.redirect ?? resolvedConfig.signInUrl! ?? fallbackRedirect;\n\n return NextResponse.redirect(new URL(redirectUrl, request.url));\n }\n\n return undefined;\n },\n };\n\n // ── Handler ───────────────────────────────────────────────────────────────\n const handlerResponse: NextResponse | void = handler ? await handler(thunderid, request) : undefined;\n\n // ── Build final response ──────────────────────────────────────────────────\n if (shouldClearCookie) {\n const cookieName: string = SessionManager.getSessionCookieName();\n\n if (handlerResponse) {\n // Handler returned a response (e.g. a redirect from protectRoute).\n // Attach the deletion so the browser discards the stale cookie (and\n // every chunk of it).\n deleteChunkedCookie(toChunkedCookieWriter(request, handlerResponse.cookies), cookieName);\n return handlerResponse;\n }\n\n // Pass-through: strip the dead cookie from the forwarded request headers\n // so the same-request Server Component render sees no session at all.\n const requestHeaders: Headers = new Headers(request.headers);\n requestHeaders.set('cookie', removeChunkedCookieFromHeader(request.headers.get('cookie') ?? '', cookieName));\n const cleanResponse: NextResponse = NextResponse.next({request: {headers: requestHeaders}});\n deleteChunkedCookie(toChunkedCookieWriter(request, cleanResponse.cookies), cookieName);\n return cleanResponse;\n }\n\n if (!refreshCookieUpdate) {\n return handlerResponse ?? NextResponse.next();\n }\n\n // A token refresh occurred — the new session cookie must be applied to:\n // 1. The HTTP response so the browser stores the updated cookie.\n // 2. The forwarded request headers so the same-request Server Component\n // render reads the fresh session token instead of the expired one.\n const cookieName: string = SessionManager.getSessionCookieName();\n const cookieOptions: ReturnType<typeof SessionManager.getSessionCookieOptions> =\n SessionManager.getSessionCookieOptions(refreshCookieUpdate.expiry);\n\n if (handlerResponse) {\n // Handler returned a response (e.g. a redirect from protectRoute).\n // Attach the refresh cookie so the browser receives it even on redirects.\n setChunkedCookie(\n toChunkedCookieWriter(request, handlerResponse.cookies),\n cookieName,\n refreshCookieUpdate.token,\n cookieOptions,\n );\n return handlerResponse;\n }\n\n // Default pass-through: update both the response cookie and the request\n // Cookie header so the downstream Server Component render is not stale.\n const requestHeaders: Headers = new Headers(request.headers);\n const updatedCookieHeader: string = replaceChunkedCookieInHeader(\n request.headers.get('cookie') ?? '',\n cookieName,\n refreshCookieUpdate.token,\n );\n requestHeaders.set('cookie', updatedCookieHeader);\n\n const response: NextResponse = NextResponse.next({request: {headers: requestHeaders}});\n setChunkedCookie(\n toChunkedCookieWriter(request, response.cookies),\n cookieName,\n refreshCookieUpdate.token,\n cookieOptions,\n );\n return response;\n };\n\nexport default thunderIDProxy;\n"],"mappings":";;;;;;;;;;;;;;;AA0DA,MAAM,0BAA0B,iBAC9B,aACG,MAAM,IAAI,CACV,KAAK,MAAc,EAAE,MAAM,CAAC,CAC5B,OAAO,QAAQ,CACf,KAAK,SAAiB;CACrB,MAAMA,QAAgB,KAAK,QAAQ,IAAI;AAEvC,QAA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BAAsB;CAChE,MAAMuB,gBACJvB,uBAAe,wBAAwB,oBAAoB,OAAO;AAEpE,KAAI,iBAAiB;AAGnB,mBACE,sBAAsB,SAAS,gBAAgB,QAAQ,EACvD,YACA,oBAAoB,OACpB,cACD;AACD,SAAO;;CAKT,MAAMoB,iBAA0B,IAAI,QAAQ,QAAQ,QAAQ;CAC5D,MAAMI,sBAA8B,6BAClC,QAAQ,QAAQ,IAAI,SAAS,IAAI,IACjC,YACA,oBAAoB,MACrB;AACD,gBAAe,IAAI,UAAU,oBAAoB;CAEjD,MAAMC,WAAyB,aAAa,KAAK,EAAC,SAAS,EAAC,SAAS,gBAAe,EAAC,CAAC;AACtF,kBACE,sBAAsB,SAAS,SAAS,QAAQ,EAChD,YACA,oBAAoB,OACpB,cACD;AACD,QAAO;;AAGX,6BAAe"}
|
|
@@ -15,6 +15,10 @@ export interface SessionTokenPayload extends JWTPayload {
|
|
|
15
15
|
scopes: string[];
|
|
16
16
|
/** Session ID */
|
|
17
17
|
sessionId: string;
|
|
18
|
+
/** The server session this session joined, from the `sid` of the ID token. */
|
|
19
|
+
sid?: string;
|
|
20
|
+
/** When the user signed in, in seconds. Kept across token refresh, unlike `iat`. */
|
|
21
|
+
signedInAt?: number;
|
|
18
22
|
/** User ID */
|
|
19
23
|
sub: string;
|
|
20
24
|
/** Token type discriminant — must be 'session' for access-session JWTs */
|
|
@@ -42,7 +46,10 @@ declare class SessionManager {
|
|
|
42
46
|
* 3. `DEFAULT_SESSION_COOKIE_EXPIRY_TIME` (24 hours)
|
|
43
47
|
*/
|
|
44
48
|
static resolveSessionCookieExpiry(configuredExpiry?: number): number;
|
|
45
|
-
static createSessionToken(accessToken: string, userId: string, sessionId: string, scopes: string, accessTokenTtlSeconds: number, refreshToken: string, organizationId?: string
|
|
49
|
+
static createSessionToken(accessToken: string, userId: string, sessionId: string, scopes: string, accessTokenTtlSeconds: number, refreshToken: string, organizationId?: string, serverSession?: {
|
|
50
|
+
sid?: string;
|
|
51
|
+
signedInAt?: number;
|
|
52
|
+
}): Promise<string>;
|
|
46
53
|
/**
|
|
47
54
|
* Verify and decode a session token
|
|
48
55
|
*/
|
|
@@ -68,6 +75,11 @@ declare class SessionManager {
|
|
|
68
75
|
/**
|
|
69
76
|
* Get session cookie options
|
|
70
77
|
*/
|
|
78
|
+
/**
|
|
79
|
+
* Throws when a back-channel logout has ended the session this cookie carries. The cookie is
|
|
80
|
+
* still correctly signed, so this is the only thing that stops it from being used.
|
|
81
|
+
*/
|
|
82
|
+
private static refuseLoggedOutSession;
|
|
71
83
|
static getSessionCookieOptions(maxAge: number): {
|
|
72
84
|
httpOnly: boolean;
|
|
73
85
|
maxAge: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SessionManager.d.ts","sourceRoot":"","sources":["../../src/utils/SessionManager.ts"],"names":[],"mappings":"AAIA,OAAO,EAAoC,UAAU,EAAC,MAAM,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"SessionManager.d.ts","sourceRoot":"","sources":["../../src/utils/SessionManager.ts"],"names":[],"mappings":"AAIA,OAAO,EAAoC,UAAU,EAAC,MAAM,MAAM,CAAC;AAInE;;GAEG;AACH,MAAM,WAAW,mBAAoB,SAAQ,UAAU;IACrD,8FAA8F;IAC9F,GAAG,EAAE,MAAM,CAAC;IACZ,0BAA0B;IAC1B,GAAG,EAAE,MAAM,CAAC;IACZ,oCAAoC;IACpC,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,yEAAyE;IACzE,YAAY,EAAE,MAAM,CAAC;IACrB,mBAAmB;IACnB,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,iBAAiB;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,8EAA8E;IAC9E,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,oFAAoF;IACpF,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,cAAc;IACd,GAAG,EAAE,MAAM,CAAC;IACZ,0EAA0E;IAC1E,IAAI,EAAE,SAAS,C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E,MAAM,CAAC;QACf,IAAI,EAAE,MAAM,CAAC;QACb,QAAQ,EAAE,KAAK,CAAC;QAChB,MAAM,EAAE,OAAO,CAAC;KACjB;IAUD;;OAEG;IACH,MAAM,CAAC,oBAAoB,IAAI,MAAM;IAIrC;;OAEG;IACH,MAAM,CAAC,wBAAwB,IAAI,MAAM;CAG1C;AAED,eAAe,cAAc,CAAC"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { getLoggedOutSessions } from "./loggedOutSessions.js";
|
|
1
2
|
import { DEFAULT_SESSION_COOKIE_EXPIRY_TIME } from "../constants/sessionConstants.js";
|
|
2
3
|
import { CookieConfig, ThunderIDRuntimeError } from "@thunderid/node";
|
|
3
4
|
import { SignJWT, compactVerify, jwtVerify } from "jose";
|
|
@@ -47,7 +48,7 @@ var SessionManager = class {
|
|
|
47
48
|
}
|
|
48
49
|
return DEFAULT_SESSION_COOKIE_EXPIRY_TIME;
|
|
49
50
|
}
|
|
50
|
-
static async createSessionToken(accessToken, userId, sessionId, scopes, accessTokenTtlSeconds, refreshToken, organizationId) {
|
|
51
|
+
static async createSessionToken(accessToken, userId, sessionId, scopes, accessTokenTtlSeconds, refreshToken, organizationId, serverSession) {
|
|
51
52
|
const secret = this.getSecret();
|
|
52
53
|
return await new SignJWT({
|
|
53
54
|
accessToken,
|
|
@@ -55,6 +56,8 @@ var SessionManager = class {
|
|
|
55
56
|
refreshToken,
|
|
56
57
|
scopes,
|
|
57
58
|
sessionId,
|
|
59
|
+
sid: serverSession?.sid,
|
|
60
|
+
signedInAt: serverSession?.signedInAt ?? Math.floor(Date.now() / 1e3),
|
|
58
61
|
type: "session"
|
|
59
62
|
}).setProtectedHeader({ alg: "HS256" }).setSubject(userId).setIssuedAt().setExpirationTime(Math.floor(Date.now() / 1e3) + accessTokenTtlSeconds).sign(secret);
|
|
60
63
|
}
|
|
@@ -65,6 +68,7 @@ var SessionManager = class {
|
|
|
65
68
|
try {
|
|
66
69
|
const { payload } = await jwtVerify(token, this.getSecret());
|
|
67
70
|
if (payload["type"] !== "session") throw new Error("Invalid token type");
|
|
71
|
+
await this.refuseLoggedOutSession(payload);
|
|
68
72
|
return payload;
|
|
69
73
|
} catch (error) {
|
|
70
74
|
throw new ThunderIDRuntimeError(`Invalid session token: ${error instanceof Error ? error.message : "Unknown error"}`, "invalid-session-token", "nextjs", "Session token verification failed");
|
|
@@ -86,6 +90,7 @@ var SessionManager = class {
|
|
|
86
90
|
const { payload: rawPayload } = await compactVerify(token, this.getSecret());
|
|
87
91
|
const payload = JSON.parse(new TextDecoder().decode(rawPayload));
|
|
88
92
|
if (payload.type !== "session") throw new Error("Invalid token type");
|
|
93
|
+
await this.refuseLoggedOutSession(payload);
|
|
89
94
|
return payload;
|
|
90
95
|
} catch (error) {
|
|
91
96
|
throw new ThunderIDRuntimeError(`Invalid session token: ${error instanceof Error ? error.message : "Unknown error"}`, "invalid-session-token-for-refresh", "nextjs", "Session token signature or type check failed during refresh");
|
|
@@ -106,6 +111,17 @@ var SessionManager = class {
|
|
|
106
111
|
/**
|
|
107
112
|
* Get session cookie options
|
|
108
113
|
*/
|
|
114
|
+
/**
|
|
115
|
+
* Throws when a back-channel logout has ended the session this cookie carries. The cookie is
|
|
116
|
+
* still correctly signed, so this is the only thing that stops it from being used.
|
|
117
|
+
*/
|
|
118
|
+
static async refuseLoggedOutSession(payload) {
|
|
119
|
+
if (await getLoggedOutSessions().isLoggedOut({
|
|
120
|
+
sid: payload.sid,
|
|
121
|
+
startedAt: payload.signedInAt ?? payload.iat,
|
|
122
|
+
sub: payload.sub
|
|
123
|
+
})) throw new Error("The session was ended by a back-channel logout");
|
|
124
|
+
}
|
|
109
125
|
static getSessionCookieOptions(maxAge) {
|
|
110
126
|
return {
|
|
111
127
|
httpOnly: true,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SessionManager.js","names":["secret: string | undefined","secret: Uint8Array","envValue: string | undefined","parsed: number","payload: SessionTokenPayload"],"sources":["../../src/utils/SessionManager.ts"],"sourcesContent":["// Copyright 2025 The ThunderID Authors\n// SPDX-License-Identifier: Apache-2.0\n\nimport {ThunderIDRuntimeError, CookieConfig} from '@thunderid/node';\nimport {SignJWT, jwtVerify, compactVerify, JWTPayload} from 'jose';\nimport {DEFAULT_SESSION_COOKIE_EXPIRY_TIME} from '../constants/sessionConstants';\n\n/**\n * Session token payload interface\n */\nexport interface SessionTokenPayload extends JWTPayload {\n /** Expiration timestamp — doubles as the access token expiry (JWT exp == access token exp) */\n exp: number;\n /** Issued at timestamp */\n iat: number;\n /** Organization ID if applicable */\n organizationId?: string;\n /** The refresh token; empty string if not provided by the auth server */\n refreshToken: string;\n /** OAuth scopes */\n scopes: string[];\n /** Session ID */\n sessionId: string;\n /** User ID */\n sub: string;\n /** Token type discriminant — must be 'session' for access-session JWTs */\n type: 'session';\n}\n\n/**\n * Session management utility class for JWT-based session cookies\n */\nclass SessionManager {\n /**\n * Get the signing secret from environment variable\n * Throws error in production if not set\n */\n private static getSecret(): Uint8Array {\n const secret: string | undefined = process.env['THUNDERID_SECRET'];\n\n if (!secret) {\n if (process.env['NODE_ENV'] === 'production') {\n throw new ThunderIDRuntimeError(\n 'THUNDERID_SECRET environment variable is required in production',\n 'session-secret-required',\n 'nextjs',\n 'Set the THUNDERID_SECRET environment variable with a secure random string',\n );\n }\n // Use a default secret for development (not secure)\n // eslint-disable-next-line no-console\n console.warn('Using default secret for development. Set THUNDERID_SECRET for production!');\n return new TextEncoder().encode('development-secret-not-for-production');\n }\n\n return new TextEncoder().encode(secret);\n }\n\n /**\n * Create a temporary session cookie for login initiation\n */\n static async createTempSession(sessionId: string): Promise<string> {\n const secret: Uint8Array = this.getSecret();\n\n const jwt: string = await new SignJWT({\n sessionId,\n type: 'temp',\n })\n .setProtectedHeader({alg: 'HS256'})\n .setIssuedAt()\n .setExpirationTime('15m')\n .sign(secret);\n\n return jwt;\n }\n\n /**\n * Resolve the session cookie expiry time in seconds.\n *\n * Resolution order (first defined value wins):\n * 1. `configuredExpiry` — value from `ThunderIDNodeConfig.sessionCookie?.expiryTime`\n * 2. `THUNDERID_SESSION_COOKIE_EXPIRY_TIME` environment variable\n * 3. `DEFAULT_SESSION_COOKIE_EXPIRY_TIME` (24 hours)\n */\n static resolveSessionCookieExpiry(configuredExpiry?: number): number {\n if (configuredExpiry != null && configuredExpiry > 0) {\n return configuredExpiry;\n }\n\n const envValue: string | undefined = process.env['THUNDERID_SESSION_COOKIE_EXPIRY_TIME'];\n\n if (envValue) {\n const parsed: number = parseInt(envValue, 10);\n\n if (!Number.isNaN(parsed) && parsed > 0) {\n return parsed;\n }\n }\n\n return DEFAULT_SESSION_COOKIE_EXPIRY_TIME;\n }\n\n static async createSessionToken(\n accessToken: string,\n userId: string,\n sessionId: string,\n scopes: string,\n accessTokenTtlSeconds: number,\n refreshToken: string,\n organizationId?: string,\n ): Promise<string> {\n const secret: Uint8Array = this.getSecret();\n\n const jwt: string = await new SignJWT({\n accessToken,\n organizationId,\n refreshToken,\n scopes,\n sessionId,\n type: 'session',\n } as Omit<SessionTokenPayload, 'sub' | 'iat' | 'exp'>)\n .setProtectedHeader({alg: 'HS256'})\n .setSubject(userId)\n .setIssuedAt()\n .setExpirationTime(Math.floor(Date.now() / 1000) + accessTokenTtlSeconds)\n .sign(secret);\n\n return jwt;\n }\n\n /**\n * Verify and decode a session token\n */\n static async verifySessionToken(token: string): Promise<SessionTokenPayload> {\n try {\n const secret: Uint8Array = this.getSecret();\n const {payload} = await jwtVerify(token, secret);\n\n if (payload['type'] !== 'session') {\n throw new Error('Invalid token type');\n }\n\n return payload as SessionTokenPayload;\n } catch (error) {\n throw new ThunderIDRuntimeError(\n `Invalid session token: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 'invalid-session-token',\n 'nextjs',\n 'Session token verification failed',\n );\n }\n }\n\n /**\n * Verify a session token for refresh. Validates the HMAC signature and the\n * `type === 'session'` discriminant but intentionally skips the `exp` check\n * so an expired access token can still be exchanged for a new one.\n *\n * Session lifetime is still bounded — the cookie's `maxAge` is set from\n * `sessionCookieExpiryTime`, so the browser drops an over-age session regardless\n * of the access-token exp embedded in the JWT.\n *\n * Never use the returned payload for authorization.\n */\n static async verifySessionTokenForRefresh(token: string): Promise<SessionTokenPayload> {\n try {\n const secret: Uint8Array = this.getSecret();\n const {payload: rawPayload} = await compactVerify(token, secret);\n const payload: SessionTokenPayload = JSON.parse(new TextDecoder().decode(rawPayload)) as SessionTokenPayload;\n\n if (payload.type !== 'session') {\n throw new Error('Invalid token type');\n }\n\n return payload;\n } catch (error) {\n throw new ThunderIDRuntimeError(\n `Invalid session token: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 'invalid-session-token-for-refresh',\n 'nextjs',\n 'Session token signature or type check failed during refresh',\n );\n }\n }\n\n /**\n * Verify and decode a temporary session token\n */\n static async verifyTempSession(token: string): Promise<{sessionId: string}> {\n try {\n const secret: Uint8Array = this.getSecret();\n const {payload} = await jwtVerify(token, secret);\n\n if (payload['type'] !== 'temp') {\n throw new Error('Invalid token type');\n }\n\n return {sessionId: payload['sessionId'] as string};\n } catch (error) {\n throw new ThunderIDRuntimeError(\n `Invalid temporary session token: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 'invalid-temp-session-token',\n 'nextjs',\n 'Temporary session token verification failed',\n );\n }\n }\n\n /**\n * Get session cookie options\n */\n static getSessionCookieOptions(maxAge: number): {\n httpOnly: boolean;\n maxAge: number;\n path: string;\n sameSite: 'lax';\n secure: boolean;\n } {\n return {\n httpOnly: true,\n maxAge,\n path: '/',\n sameSite: 'lax' as const,\n secure: process.env['NODE_ENV'] === 'production',\n };\n }\n\n /**\n * Get temporary session cookie options\n */\n static getTempSessionCookieOptions(): {\n httpOnly: boolean;\n maxAge: number;\n path: string;\n sameSite: 'lax';\n secure: boolean;\n } {\n return {\n httpOnly: true,\n maxAge: 15 * 60,\n path: '/',\n sameSite: 'lax' as const,\n secure: process.env['NODE_ENV'] === 'production',\n };\n }\n\n /**\n * Get session cookie name\n */\n static getSessionCookieName(): string {\n return CookieConfig.getSessionCookieName();\n }\n\n /**\n * Get temporary session cookie name\n */\n static getTempSessionCookieName(): string {\n return CookieConfig.getTempSessionCookieName();\n }\n}\n\nexport default SessionManager;\n"],"mappings":";;;;;;;;AAgCA,IAAM,iBAAN,MAAqB;;;;;CAKnB,OAAe,YAAwB;EACrC,MAAMA,SAA6B,QAAQ,IAAI;AAE/C,MAAI,CAAC,QAAQ;AACX,OAAI,QAAQ,IAAI,gBAAgB,aAC9B,OAAM,IAAI,sBACR,mEACA,2BACA,UACA,4EACD;AAIH,WAAQ,KAAK,6EAA6E;AAC1F,UAAO,IAAI,aAAa,CAAC,OAAO,wCAAwC;;AAG1E,SAAO,IAAI,aAAa,CAAC,OAAO,OAAO;;;;;CAMzC,aAAa,kBAAkB,WAAoC;EACjE,MAAMC,SAAqB,KAAK,WAAW;AAW3C,SAToB,MAAM,IAAI,QAAQ;GACpC;GACA,MAAM;GACP,CAAC,CACC,mBAAmB,EAAC,KAAK,SAAQ,CAAC,CAClC,aAAa,CACb,kBAAkB,MAAM,CACxB,KAAK,OAAO;;;;;;;;;;CAajB,OAAO,2BAA2B,kBAAmC;AACnE,MAAI,oBAAoB,QAAQ,mBAAmB,EACjD,QAAO;EAGT,MAAMC,WAA+B,QAAQ,IAAI;AAEjD,MAAI,UAAU;GACZ,MAAMC,SAAiB,SAAS,UAAU,GAAG;AAE7C,OAAI,CAAC,OAAO,MAAM,OAAO,IAAI,SAAS,EACpC,QAAO;;AAIX,SAAO;;CAGT,aAAa,mBACX,aACA,QACA,WACA,QACA,uBACA,cACA,gBACiB;EACjB,MAAMF,SAAqB,KAAK,WAAW;AAgB3C,SAdoB,MAAM,IAAI,QAAQ;GACpC;GACA;GACA;GACA;GACA;GACA,MAAM;GACP,CAAqD,CACnD,mBAAmB,EAAC,KAAK,SAAQ,CAAC,CAClC,WAAW,OAAO,CAClB,aAAa,CACb,kBAAkB,KAAK,MAAM,KAAK,KAAK,GAAG,IAAK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AAO,aAAa,sBAAsB;;;;;CAM5C,OAAO,2BAAmC;AACxC,SAAO,aAAa,0BAA0B;;;AAIlD,6BAAe"}
|
|
1
|
+
{"version":3,"file":"SessionManager.js","names":["secret: string | undefined","secret: Uint8Array","envValue: string | undefined","parsed: number","payload: SessionTokenPayload"],"sources":["../../src/utils/SessionManager.ts"],"sourcesContent":["// Copyright 2025 The ThunderID Authors\n// SPDX-License-Identifier: Apache-2.0\n\nimport {ThunderIDRuntimeError, CookieConfig} from '@thunderid/node';\nimport {SignJWT, jwtVerify, compactVerify, JWTPayload} from 'jose';\nimport {getLoggedOutSessions} from './loggedOutSessions';\nimport {DEFAULT_SESSION_COOKIE_EXPIRY_TIME} from '../constants/sessionConstants';\n\n/**\n * Session token payload interface\n */\nexport interface SessionTokenPayload extends JWTPayload {\n /** Expiration timestamp — doubles as the access token expiry (JWT exp == access token exp) */\n exp: number;\n /** Issued at timestamp */\n iat: number;\n /** Organization ID if applicable */\n organizationId?: string;\n /** The refresh token; empty string if not provided by the auth server */\n refreshToken: string;\n /** OAuth scopes */\n scopes: string[];\n /** Session ID */\n sessionId: string;\n /** The server session this session joined, from the `sid` of the ID token. */\n sid?: string;\n /** When the user signed in, in seconds. Kept across token refresh, unlike `iat`. */\n signedInAt?: number;\n /** User ID */\n sub: string;\n /** Token type discriminant — must be 'session' for access-session JWTs */\n type: 'session';\n}\n\n/**\n * Session management utility class for JWT-based session cookies\n */\nclass SessionManager {\n /**\n * Get the signing secret from environment variable\n * Throws error in production if not set\n */\n private static getSecret(): Uint8Array {\n const secret: string | undefined = process.env['THUNDERID_SECRET'];\n\n if (!secret) {\n if (process.env['NODE_ENV'] === 'production') {\n throw new ThunderIDRuntimeError(\n 'THUNDERID_SECRET environment variable is required in production',\n 'session-secret-required',\n 'nextjs',\n 'Set the THUNDERID_SECRET environment variable with a secure random string',\n );\n }\n // Use a default secret for development (not secure)\n // eslint-disable-next-line no-console\n console.warn('Using default secret for development. Set THUNDERID_SECRET for production!');\n return new TextEncoder().encode('development-secret-not-for-production');\n }\n\n return new TextEncoder().encode(secret);\n }\n\n /**\n * Create a temporary session cookie for login initiation\n */\n static async createTempSession(sessionId: string): Promise<string> {\n const secret: Uint8Array = this.getSecret();\n\n const jwt: string = await new SignJWT({\n sessionId,\n type: 'temp',\n })\n .setProtectedHeader({alg: 'HS256'})\n .setIssuedAt()\n .setExpirationTime('15m')\n .sign(secret);\n\n return jwt;\n }\n\n /**\n * Resolve the session cookie expiry time in seconds.\n *\n * Resolution order (first defined value wins):\n * 1. `configuredExpiry` — value from `ThunderIDNodeConfig.sessionCookie?.expiryTime`\n * 2. `THUNDERID_SESSION_COOKIE_EXPIRY_TIME` environment variable\n * 3. `DEFAULT_SESSION_COOKIE_EXPIRY_TIME` (24 hours)\n */\n static resolveSessionCookieExpiry(configuredExpiry?: number): number {\n if (configuredExpiry != null && configuredExpiry > 0) {\n return configuredExpiry;\n }\n\n const envValue: string | undefined = process.env['THUNDERID_SESSION_COOKIE_EXPIRY_TIME'];\n\n if (envValue) {\n const parsed: number = parseInt(envValue, 10);\n\n if (!Number.isNaN(parsed) && parsed > 0) {\n return parsed;\n }\n }\n\n return DEFAULT_SESSION_COOKIE_EXPIRY_TIME;\n }\n\n static async createSessionToken(\n accessToken: string,\n userId: string,\n sessionId: string,\n scopes: string,\n accessTokenTtlSeconds: number,\n refreshToken: string,\n organizationId?: string,\n serverSession?: {sid?: string; signedInAt?: number},\n ): Promise<string> {\n const secret: Uint8Array = this.getSecret();\n\n const jwt: string = await new SignJWT({\n accessToken,\n organizationId,\n refreshToken,\n scopes,\n sessionId,\n // What a back-channel logout matches this session by.\n sid: serverSession?.sid,\n signedInAt: serverSession?.signedInAt ?? Math.floor(Date.now() / 1000),\n type: 'session',\n } as Omit<SessionTokenPayload, 'sub' | 'iat' | 'exp'>)\n .setProtectedHeader({alg: 'HS256'})\n .setSubject(userId)\n .setIssuedAt()\n .setExpirationTime(Math.floor(Date.now() / 1000) + accessTokenTtlSeconds)\n .sign(secret);\n\n return jwt;\n }\n\n /**\n * Verify and decode a session token\n */\n static async verifySessionToken(token: string): Promise<SessionTokenPayload> {\n try {\n const secret: Uint8Array = this.getSecret();\n const {payload} = await jwtVerify(token, secret);\n\n if (payload['type'] !== 'session') {\n throw new Error('Invalid token type');\n }\n\n await this.refuseLoggedOutSession(payload as SessionTokenPayload);\n\n return payload as SessionTokenPayload;\n } catch (error) {\n throw new ThunderIDRuntimeError(\n `Invalid session token: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 'invalid-session-token',\n 'nextjs',\n 'Session token verification failed',\n );\n }\n }\n\n /**\n * Verify a session token for refresh. Validates the HMAC signature and the\n * `type === 'session'` discriminant but intentionally skips the `exp` check\n * so an expired access token can still be exchanged for a new one.\n *\n * Session lifetime is still bounded — the cookie's `maxAge` is set from\n * `sessionCookieExpiryTime`, so the browser drops an over-age session regardless\n * of the access-token exp embedded in the JWT.\n *\n * Never use the returned payload for authorization.\n */\n static async verifySessionTokenForRefresh(token: string): Promise<SessionTokenPayload> {\n try {\n const secret: Uint8Array = this.getSecret();\n const {payload: rawPayload} = await compactVerify(token, secret);\n const payload: SessionTokenPayload = JSON.parse(new TextDecoder().decode(rawPayload)) as SessionTokenPayload;\n\n if (payload.type !== 'session') {\n throw new Error('Invalid token type');\n }\n\n await this.refuseLoggedOutSession(payload);\n\n return payload;\n } catch (error) {\n throw new ThunderIDRuntimeError(\n `Invalid session token: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 'invalid-session-token-for-refresh',\n 'nextjs',\n 'Session token signature or type check failed during refresh',\n );\n }\n }\n\n /**\n * Verify and decode a temporary session token\n */\n static async verifyTempSession(token: string): Promise<{sessionId: string}> {\n try {\n const secret: Uint8Array = this.getSecret();\n const {payload} = await jwtVerify(token, secret);\n\n if (payload['type'] !== 'temp') {\n throw new Error('Invalid token type');\n }\n\n return {sessionId: payload['sessionId'] as string};\n } catch (error) {\n throw new ThunderIDRuntimeError(\n `Invalid temporary session token: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 'invalid-temp-session-token',\n 'nextjs',\n 'Temporary session token verification failed',\n );\n }\n }\n\n /**\n * Get session cookie options\n */\n /**\n * Throws when a back-channel logout has ended the session this cookie carries. The cookie is\n * still correctly signed, so this is the only thing that stops it from being used.\n */\n private static async refuseLoggedOutSession(payload: SessionTokenPayload): Promise<void> {\n const loggedOut: boolean = await getLoggedOutSessions().isLoggedOut({\n sid: payload.sid,\n startedAt: payload.signedInAt ?? payload.iat,\n sub: payload.sub,\n });\n\n if (loggedOut) {\n throw new Error('The session was ended by a back-channel logout');\n }\n }\n\n static getSessionCookieOptions(maxAge: number): {\n httpOnly: boolean;\n maxAge: number;\n path: string;\n sameSite: 'lax';\n secure: boolean;\n } {\n return {\n httpOnly: true,\n maxAge,\n path: '/',\n sameSite: 'lax' as const,\n secure: process.env['NODE_ENV'] === 'production',\n };\n }\n\n /**\n * Get temporary session cookie options\n */\n static getTempSessionCookieOptions(): {\n httpOnly: boolean;\n maxAge: number;\n path: string;\n sameSite: 'lax';\n secure: boolean;\n } {\n return {\n httpOnly: true,\n maxAge: 15 * 60,\n path: '/',\n sameSite: 'lax' as const,\n secure: process.env['NODE_ENV'] === 'production',\n };\n }\n\n /**\n * Get session cookie name\n */\n static getSessionCookieName(): string {\n return CookieConfig.getSessionCookieName();\n }\n\n /**\n * Get temporary session cookie name\n */\n static getTempSessionCookieName(): string {\n return CookieConfig.getTempSessionCookieName();\n }\n}\n\nexport default SessionManager;\n"],"mappings":";;;;;;;;;AAqCA,IAAM,iBAAN,MAAqB;;;;;CAKnB,OAAe,YAAwB;EACrC,MAAMA,SAA6B,QAAQ,IAAI;AAE/C,MAAI,CAAC,QAAQ;AACX,OAAI,QAAQ,IAAI,gBAAgB,aAC9B,OAAM,IAAI,sBACR,mEACA,2BACA,UACA,4EACD;AAIH,WAAQ,KAAK,6EAA6E;AAC1F,UAAO,IAAI,aAAa,CAAC,OAAO,wCAAwC;;AAG1E,SAAO,IAAI,aAAa,C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
|
|
1
|
-
{"version":3,"file":"handleRefreshToken.d.ts","sourceRoot":"","sources":["../../src/utils/handleRefreshToken.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAC,aAAa,EAAE,mBAAmB,EAAC,MAAM,iBAAiB,CAAC;AACxE,OAAuB,EAAC,mBAAmB,EAAC,MAAM,kBAAkB,CAAC;AAErE;;GAEG;AACH,MAAM,WAAW,wBAAwB;IACvC,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,CAAC,EAAE,mBAAmB,CAAC;CACrC;AAED;;;GAGG;AACH,MAAM,WAAW,wBAAwB;IACvC,eAAe,EAAE,MAAM,CAAC;IACxB,uBAAuB,EAAE,MAAM,CAAC;IAChC,aAAa,EAAE,aAAa,CAAC;CAC9B;AAED;;;;;;GAMG;AACH,QAAA,MAAM,kBAAkB,GACtB,gBAAgB,mBAAmB,EACnC,QAAQ,wBAAwB,KAC/B,OAAO,CAAC,wBAAwB,
|
|
1
|
+
{"version":3,"file":"handleRefreshToken.d.ts","sourceRoot":"","sources":["../../src/utils/handleRefreshToken.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAC,aAAa,EAAE,mBAAmB,EAAC,MAAM,iBAAiB,CAAC;AACxE,OAAuB,EAAC,mBAAmB,EAAC,MAAM,kBAAkB,CAAC;AAErE;;GAEG;AACH,MAAM,WAAW,wBAAwB;IACvC,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,CAAC,EAAE,mBAAmB,CAAC;CACrC;AAED;;;GAGG;AACH,MAAM,WAAW,wBAAwB;IACvC,eAAe,EAAE,MAAM,CAAC;IACxB,uBAAuB,EAAE,MAAM,CAAC;IAChC,aAAa,EAAE,aAAa,CAAC;CAC9B;AAED;;;;;;GAMG;AACH,QAAA,MAAM,kBAAkB,GACtB,gBAAgB,mBAAmB,EACnC,QAAQ,wBAAwB,KAC/B,OAAO,CAAC,wBAAwB,CAsFlC,CAAC;AAEF,eAAe,kBAAkB,CAAC"}
|
|
@@ -10,7 +10,7 @@ import SessionManager_default from "./SessionManager.js";
|
|
|
10
10
|
*/
|
|
11
11
|
const handleRefreshToken = async (sessionPayload, config) => {
|
|
12
12
|
const { baseUrl, clientId, clientSecret, sessionCookie } = config;
|
|
13
|
-
const { refreshToken: storedRefreshToken, sessionId, sub, scopes, organizationId } = sessionPayload;
|
|
13
|
+
const { refreshToken: storedRefreshToken, sessionId, sub, scopes, organizationId, sid, signedInAt, iat } = sessionPayload;
|
|
14
14
|
if (!storedRefreshToken) throw new Error("No refresh token found in session payload.");
|
|
15
15
|
const tokenEndpoint = `${baseUrl}/oauth2/token`;
|
|
16
16
|
const body = new URLSearchParams({
|
|
@@ -42,7 +42,10 @@ const handleRefreshToken = async (sessionPayload, config) => {
|
|
|
42
42
|
const newScopes = tokenData["scope"] ?? (Array.isArray(scopes) ? scopes.join(" ") : scopes ?? "");
|
|
43
43
|
const resolvedSessionCookieExpiry = SessionManager_default.resolveSessionCookieExpiry(sessionCookie?.expiryTime);
|
|
44
44
|
return {
|
|
45
|
-
newSessionToken: await SessionManager_default.createSessionToken(newAccessToken, sub, sessionId, newScopes, expiresIn, newRefreshToken, organizationId
|
|
45
|
+
newSessionToken: await SessionManager_default.createSessionToken(newAccessToken, sub, sessionId, newScopes, expiresIn, newRefreshToken, organizationId, {
|
|
46
|
+
sid,
|
|
47
|
+
signedInAt: signedInAt ?? iat
|
|
48
|
+
}),
|
|
46
49
|
sessionCookieExpiryTime: resolvedSessionCookieExpiry,
|
|
47
50
|
tokenResponse: {
|
|
48
51
|
accessToken: newAccessToken,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handleRefreshToken.js","names":["body: URLSearchParams","response: Response","tokenData: Record<string, unknown>","newAccessToken: string","expiresIn: number","newRefreshToken: string","newScopes: string","resolvedSessionCookieExpiry: number","SessionManager"],"sources":["../../src/utils/handleRefreshToken.ts"],"sourcesContent":["// Copyright 2025 The ThunderID Authors\n// SPDX-License-Identifier: Apache-2.0\n\nimport type {TokenResponse, SessionCookieConfig} from '@thunderid/node';\nimport SessionManager, {SessionTokenPayload} from './SessionManager';\n\n/**\n * Config required to call the token endpoint.\n */\nexport interface HandleRefreshTokenConfig {\n baseUrl: string;\n clientId: string;\n clientSecret: string;\n sessionCookie?: SessionCookieConfig;\n}\n\n/**\n * Result returned by handleRefreshToken.\n * Callers are responsible for persisting newSessionToken in the appropriate cookie context.\n */\nexport interface HandleRefreshTokenResult {\n newSessionToken: string;\n sessionCookieExpiryTime: number;\n tokenResponse: TokenResponse;\n}\n\n/**\n * Handles the OAuth refresh_token grant and builds a new session JWT string.\n *\n * Intentionally decoupled from cookie APIs so it can be called from both the Edge\n * Runtime (Next.js middleware) and the Node.js Runtime (server actions).\n * Cookie persistence is the caller's responsibility.\n */\nconst handleRefreshToken = async (\n sessionPayload: SessionTokenPayload,\n config: HandleRefreshTokenConfig,\n): Promise<HandleRefreshTokenResult> => {\n const {baseUrl, clientId, clientSecret, sessionCookie} = config;\n const {refreshToken: storedRefreshToken
|
|
1
|
+
{"version":3,"file":"handleRefreshToken.js","names":["body: URLSearchParams","response: Response","tokenData: Record<string, unknown>","newAccessToken: string","expiresIn: number","newRefreshToken: string","newScopes: string","resolvedSessionCookieExpiry: number","SessionManager"],"sources":["../../src/utils/handleRefreshToken.ts"],"sourcesContent":["// Copyright 2025 The ThunderID Authors\n// SPDX-License-Identifier: Apache-2.0\n\nimport type {TokenResponse, SessionCookieConfig} from '@thunderid/node';\nimport SessionManager, {SessionTokenPayload} from './SessionManager';\n\n/**\n * Config required to call the token endpoint.\n */\nexport interface HandleRefreshTokenConfig {\n baseUrl: string;\n clientId: string;\n clientSecret: string;\n sessionCookie?: SessionCookieConfig;\n}\n\n/**\n * Result returned by handleRefreshToken.\n * Callers are responsible for persisting newSessionToken in the appropriate cookie context.\n */\nexport interface HandleRefreshTokenResult {\n newSessionToken: string;\n sessionCookieExpiryTime: number;\n tokenResponse: TokenResponse;\n}\n\n/**\n * Handles the OAuth refresh_token grant and builds a new session JWT string.\n *\n * Intentionally decoupled from cookie APIs so it can be called from both the Edge\n * Runtime (Next.js middleware) and the Node.js Runtime (server actions).\n * Cookie persistence is the caller's responsibility.\n */\nconst handleRefreshToken = async (\n sessionPayload: SessionTokenPayload,\n config: HandleRefreshTokenConfig,\n): Promise<HandleRefreshTokenResult> => {\n const {baseUrl, clientId, clientSecret, sessionCookie} = config;\n const {\n refreshToken: storedRefreshToken,\n sessionId,\n sub,\n scopes,\n organizationId,\n sid,\n signedInAt,\n iat,\n } = sessionPayload;\n\n if (!storedRefreshToken) {\n throw new Error('No refresh token found in session payload.');\n }\n\n const tokenEndpoint = `${baseUrl}/oauth2/token`;\n const body: URLSearchParams = new URLSearchParams({\n client_id: clientId ?? '',\n client_secret: clientSecret ?? '',\n grant_type: 'refresh_token',\n refresh_token: storedRefreshToken,\n });\n\n let response: Response;\n\n try {\n response = await fetch(tokenEndpoint, {\n body: body.toString(),\n headers: {'Content-Type': 'application/x-www-form-urlencoded'},\n method: 'POST',\n });\n } catch (fetchError) {\n throw new Error(\n `Token refresh network error: ${fetchError instanceof Error ? fetchError.message : String(fetchError)}`,\n );\n }\n\n if (!response.ok) {\n throw new Error(`Token endpoint rejected refresh (HTTP ${response.status}).`);\n }\n\n let tokenData: Record<string, unknown>;\n\n try {\n tokenData = (await response.json()) as Record<string, unknown>;\n } catch {\n throw new Error('Failed to parse token endpoint response as JSON.');\n }\n\n const newAccessToken: string = tokenData['access_token'] as string;\n const expiresIn: number = tokenData['expires_in'] as number;\n // Use the rotated refresh token if the server provided one; otherwise keep the existing one.\n const newRefreshToken: string = (tokenData['refresh_token'] as string | undefined) ?? storedRefreshToken;\n const newScopes: string =\n (tokenData['scope'] as string | undefined) ??\n (Array.isArray(scopes) ? scopes.join(' ') : ((scopes as string) ?? ''));\n\n const resolvedSessionCookieExpiry: number = SessionManager.resolveSessionCookieExpiry(sessionCookie?.expiryTime);\n\n const newSessionToken: string = await SessionManager.createSessionToken(\n newAccessToken,\n sub,\n sessionId,\n newScopes,\n expiresIn,\n newRefreshToken,\n organizationId,\n // A refreshed session is still the same sign-in, so it keeps what a logout matches it by.\n {sid, signedInAt: signedInAt ?? iat},\n );\n\n return {\n newSessionToken,\n sessionCookieExpiryTime: resolvedSessionCookieExpiry,\n tokenResponse: {\n accessToken: newAccessToken,\n createdAt: Math.floor(Date.now() / 1000),\n expiresIn: String(expiresIn),\n idToken: (tokenData['id_token'] as string | undefined) ?? '',\n refreshToken: newRefreshToken,\n scope: newScopes,\n tokenType: (tokenData['token_type'] as string | undefined) ?? 'Bearer',\n },\n };\n};\n\nexport default handleRefreshToken;\n"],"mappings":";;;;;;;;;;AAiCA,MAAM,qBAAqB,OACzB,gBACA,WACsC;CACtC,MAAM,EAAC,SAAS,UAAU,cAAc,kBAAiB;CACzD,MAAM,EACJ,cAAc,oBACd,WACA,KACA,QACA,gBACA,KACA,YACA,QACE;AAEJ,KAAI,CAAC,mBACH,OAAM,IAAI,MAAM,6CAA6C;CAG/D,MAAM,gBAAgB,GAAG,QAAQ;CACjC,MAAMA,OAAwB,IAAI,gBAAgB;EAChD,WAAW,YAAY;EACvB,eAAe,gBAAgB;EAC/B,YAAY;EACZ,eAAe;EAChB,CAAC;CAEF,IAAIC;AAEJ,KAAI;AACF,aAAW,MAAM,MAAM,eAAe;GACpC,MAAM,KAAK,UAAU;GACrB,SAAS,EAAC,gBAAgB,qCAAoC;GAC9D,QAAQ;GACT,CAAC;UACK,YAAY;AACnB,QAAM,IAAI,MACR,gCAAgC,sBAAsB,QAAQ,WAAW,UAAU,OAAO,WAAW,GACtG;;AAGH,KAAI,CAAC,SAAS,GACZ,OAAM,IAAI,MAAM,yCAAyC,SAAS,OAAO,IAAI;CAG/E,IAAIC;AAEJ,KAAI;AACF,cAAa,MAAM,SAAS,MAAM;SA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