@spfn/auth 0.3.0-beta.7 → 0.3.0-beta.8
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/README.md +378 -0
- package/dist/client-proof.d.ts +23 -12
- package/dist/client-proof.js +143 -4
- package/dist/client-proof.js.map +1 -1
- package/dist/config.d.ts +20 -0
- package/dist/config.js +9 -0
- package/dist/config.js.map +1 -1
- package/dist/errors.d.ts +76 -3
- package/dist/errors.js +45 -0
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +46 -6
- package/dist/index.js +75 -0
- package/dist/index.js.map +1 -1
- package/dist/{authenticate-Mg9D7Nys.d.ts → machine-principals-Bd5hp76H.d.ts} +343 -6
- package/dist/nextjs/api.js +190 -9
- package/dist/nextjs/api.js.map +1 -1
- package/dist/nextjs/server.js +59 -8
- package/dist/nextjs/server.js.map +1 -1
- package/dist/server.d.ts +719 -89
- package/dist/server.js +1383 -440
- package/dist/server.js.map +1 -1
- package/migrations/20260901091716_fine_arclight/migration.sql +21 -0
- package/migrations/20260901091716_fine_arclight/snapshot.json +3849 -0
- package/package.json +2 -2
package/dist/nextjs/api.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/nextjs/api.ts","../../src/server/lib/crypto.ts","../../src/server/lib/session.ts","../../src/server/logger.ts","../../src/server/lib/config.ts","../../src/nextjs/interceptors/cookie-options.ts","../../src/nextjs/interceptors/login-register.ts","../../src/nextjs/interceptors/general-auth.ts","../../src/nextjs/interceptors/key-rotation.ts","../../src/server/lib/oauth/state.ts","../../src/nextjs/session-helpers.ts","../../src/nextjs/interceptors/oauth.ts","../../src/nextjs/interceptors/signup-link.ts","../../src/nextjs/interceptors/index.ts"],"sourcesContent":["/**\n * @spfn/auth/adapters/nextjs/api\n *\n * Next.js Adapter for SPFN Auth\n *\n * Provides automatic interceptor registration for seamless auth flow:\n * - Session management (HttpOnly cookies)\n * - JWT generation and signing\n * - Public key encryption\n *\n * @requires next >= 13.0.0\n *\n * @example\n * ```typescript\n * // Just import to auto-register interceptors\n * import '@spfn/auth/nextjs/api';\n * ```\n */\n\n// Re-export interceptors for advanced usage\nimport { registerInterceptors } from '@spfn/core/nextjs/server';\nimport { authInterceptors } from './interceptors';\n\n// Auto-register interceptors on import\nregisterInterceptors('auth', authInterceptors);\n","/**\n * @spfn/auth - Client Crypto Helpers\n *\n * ES256 (ECDSA P-256) key generation and JWT signing for Next.js\n * Keys are stored in DER format (Base64 encoded) for efficiency\n *\n * Key Sizes:\n * - ES256 (ECDSA P-256): ~91 bytes (Base64: ~120 chars)\n * - RS256 (RSA 2048): ~294 bytes (Base64: ~392 chars)\n */\n\nimport { type KeyAlgorithmType } from '../types';\nimport crypto from 'crypto';\nimport jwt, { type Algorithm, type SignOptions } from 'jsonwebtoken';\n\ntype Unit =\n | 'Years'\n | 'Year'\n | 'Yrs'\n | 'Yr'\n | 'Y'\n | 'Weeks'\n | 'Week'\n | 'W'\n | 'Days'\n | 'Day'\n | 'D'\n | 'Hours'\n | 'Hour'\n | 'Hrs'\n | 'Hr'\n | 'H'\n | 'Minutes'\n | 'Minute'\n | 'Mins'\n | 'Min'\n | 'M'\n | 'Seconds'\n | 'Second'\n | 'Secs'\n | 'Sec'\n | 's'\n | 'Milliseconds'\n | 'Millisecond'\n | 'Msecs'\n | 'Msec'\n | 'Ms';\n\ntype UnitAnyCase = Unit | Uppercase<Unit> | Lowercase<Unit>;\n\ntype StringValue =\n | `${number}`\n | `${number}${UnitAnyCase}`\n | `${number} ${UnitAnyCase}`;\n\nexport interface KeyPair\n{\n privateKey: string; // Base64 encoded DER\n publicKey: string; // Base64 encoded DER\n keyId: string; // UUID\n fingerprint: string; // SHA-256 hash\n algorithm: KeyAlgorithmType;\n}\n\n/**\n * Generate ECDSA P-256 key pair (ES256)\n * Recommended for optimal size and performance\n */\nexport function generateKeyPairES256(): KeyPair\n{\n const keyId = crypto.randomUUID();\n\n const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', {\n namedCurve: 'P-256', // ES256\n publicKeyEncoding: {\n type: 'spki',\n format: 'der',\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'der',\n },\n });\n\n // Convert Buffer to Base64\n const privateKeyB64 = privateKey.toString('base64');\n const publicKeyB64 = publicKey.toString('base64');\n\n // Generate fingerprint (SHA-256 of public key)\n const fingerprint = crypto\n .createHash('sha256')\n .update(publicKey)\n .digest('hex');\n\n return {\n privateKey: privateKeyB64,\n publicKey: publicKeyB64,\n keyId,\n fingerprint,\n algorithm: 'ES256',\n };\n}\n\n/**\n * Generate RSA 2048 key pair (RS256)\n * Fallback option, larger size but wider compatibility\n */\nexport function generateKeyPairRS256(): KeyPair\n{\n const keyId = crypto.randomUUID();\n\n const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {\n modulusLength: 2048,\n publicKeyEncoding: {\n type: 'spki',\n format: 'der',\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'der',\n },\n });\n\n const privateKeyB64 = privateKey.toString('base64');\n const publicKeyB64 = publicKey.toString('base64');\n\n const fingerprint = crypto\n .createHash('sha256')\n .update(publicKey)\n .digest('hex');\n\n return {\n privateKey: privateKeyB64,\n publicKey: publicKeyB64,\n keyId,\n fingerprint,\n algorithm: 'RS256',\n };\n}\n\n/**\n * Generate key pair (defaults to ES256)\n */\nexport function generateKeyPair(\n algorithm: KeyAlgorithmType = 'ES256',\n): KeyPair\n{\n return algorithm === 'ES256'\n ? generateKeyPairES256()\n : generateKeyPairRS256();\n}\n\n/**\n * Generate JWT signed with client private key (DER format)\n */\nexport function generateClientToken(\n payload: Record<string, any>,\n privateKeyB64: string,\n algorithm: Algorithm,\n options?: {\n expiresIn?: StringValue | number;\n issuer?: string;\n },\n): string\n{\n try\n {\n // Convert Base64 back to Buffer\n const privateKeyDER = Buffer.from(privateKeyB64, 'base64');\n\n // Create key object for signing\n const privateKeyObject = crypto.createPrivateKey({\n key: privateKeyDER,\n format: 'der',\n type: 'pkcs8',\n });\n\n // Export as PEM for jwt.sign\n const privateKeyPEM = privateKeyObject.export({\n type: 'pkcs8',\n format: 'pem',\n });\n\n const signOptions: SignOptions = {\n algorithm,\n issuer: options?.issuer || 'spfn-client',\n expiresIn: options?.expiresIn ?? '15m', // Default to 15 minutes\n };\n\n return jwt.sign(payload, privateKeyPEM, signOptions);\n }\n catch (error)\n {\n throw new Error(\n `Failed to generate client token: ${error instanceof Error ? error.message : 'Unknown error'}`,\n );\n }\n}\n\n/**\n * Get key size information\n */\nexport function getKeySize(publicKeyB64: string): {\n bytes: number;\n base64Length: number;\n}\n{\n const keyDER = Buffer.from(publicKeyB64, 'base64');\n\n return {\n bytes: keyDER.length,\n base64Length: publicKeyB64.length,\n };\n}\n\n/**\n * Check if key should be rotated based on creation date\n */\nexport function shouldRotateKey(\n createdAt: Date,\n rotationDays: number = 90,\n): {\n shouldRotate: boolean;\n daysRemaining: number;\n}\n{\n const now = new Date();\n const ageInDays = Math.floor(\n (now.getTime() - createdAt.getTime()) / (1000 * 60 * 60 * 24),\n );\n const daysRemaining = Math.max(0, rotationDays - ageInDays);\n\n return {\n shouldRotate: daysRemaining <= 7, // Warn 7 days before expiry\n daysRemaining,\n };\n}\n","/**\n * @spfn/auth - Client Session Management\n *\n * Uses Jose JWE (JSON Web Encryption) to securely store session data in cookies\n * More efficient than Iron Session with better Edge Runtime support\n */\n\nimport * as jose from 'jose';\nimport { env } from '@spfn/auth/config';\nimport { env as coreEnv } from '@spfn/core/config';\nimport { authLogger } from '../logger';\n\nimport { type KeyAlgorithmType } from '../types';\n\nexport interface SessionData\n{\n userId: string;\n privateKey: string; // Base64 encoded DER\n keyId: string;\n algorithm: KeyAlgorithmType;\n}\n\n/**\n * Get session secret key derived from environment\n * Must be at least 32 characters (256-bit)\n *\n * Derives a 32-byte key using SHA-256 to ensure compatibility with Jose A256GCM\n */\nasync function getSessionSecretKey(): Promise<Uint8Array>\n{\n const secret = env.SPFN_AUTH_SESSION_SECRET;\n\n // Derive a 32-byte key using SHA-256 for A256GCM compatibility\n // Use Web Crypto API for universal compatibility (browser + Node.js)\n const encoder = new TextEncoder();\n const data = encoder.encode(secret);\n const hashBuffer = await crypto.subtle.digest('SHA-256', data);\n\n return new Uint8Array(hashBuffer);\n}\n\n/**\n * Get a short fingerprint of the current secret key for debugging\n * Logs only the first 8 hex chars of the SHA-256 hash — safe to expose\n */\nasync function getSecretFingerprint(): Promise<string>\n{\n const key = await getSessionSecretKey();\n const hash = await crypto.subtle.digest('SHA-256', key.buffer as ArrayBuffer);\n const hex = Array.from(new Uint8Array(hash))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n\n return hex.slice(0, 8);\n}\n\n/**\n * Seal session data into encrypted JWT (JWE)\n *\n * @param data - Session data to encrypt\n * @param ttl - Time to live in seconds (default: 7 days)\n * @returns Encrypted JWT string\n */\nexport async function sealSession(\n data: SessionData,\n ttl: number = 60 * 60 * 24 * 7, // 7 days\n): Promise<string>\n{\n const secret = await getSessionSecretKey();\n\n const result = await new jose.EncryptJWT({ data })\n .setProtectedHeader({ alg: 'dir', enc: 'A256GCM' })\n .setIssuedAt()\n .setExpirationTime(`${ttl}s`)\n .setIssuer('spfn-auth')\n .setAudience('spfn-client')\n .encrypt(secret);\n\n if (coreEnv.NODE_ENV !== 'production')\n {\n const fingerprint = await getSecretFingerprint();\n authLogger.session.debug(`Sealed session`, {\n secretFingerprint: fingerprint,\n resultLength: result.length,\n resultPrefix: result.slice(0, 20),\n });\n }\n\n return result;\n}\n\n/**\n * Unseal encrypted JWT (JWE) to session data\n *\n * @param jwt - Encrypted JWT string\n * @returns Session data\n * @throws Error if session is invalid or expired\n */\nexport async function unsealSession(jwt: string): Promise<SessionData>\n{\n try\n {\n const secret = await getSessionSecretKey();\n\n const { payload } = await jose.jwtDecrypt(jwt, secret, {\n issuer: 'spfn-auth',\n audience: 'spfn-client',\n });\n\n return payload.data as SessionData;\n }\n catch (err)\n {\n if (err instanceof jose.errors.JWTExpired)\n {\n throw new Error('Session expired');\n }\n\n if (err instanceof jose.errors.JWEDecryptionFailed)\n {\n // Log secret fingerprint for debugging cross-process key mismatch\n if (coreEnv.NODE_ENV !== 'production')\n {\n const fingerprint = await getSecretFingerprint();\n authLogger.session.warn(`JWE decryption failed`, {\n secretFingerprint: fingerprint,\n jwtLength: jwt.length,\n jwtPrefix: jwt.slice(0, 20),\n jwtSuffix: jwt.slice(-10),\n });\n }\n\n throw new Error('Invalid session');\n }\n\n if (err instanceof jose.errors.JWTClaimValidationFailed)\n {\n throw new Error('Session validation failed');\n }\n\n throw new Error('Failed to unseal session');\n }\n}\n\n/**\n * Get session metadata without decrypting\n *\n * @param jwt - Encrypted JWT string\n * @returns Session metadata or null if invalid\n */\nexport async function getSessionInfo(jwt: string): Promise<{\n issuedAt: Date;\n expiresAt: Date;\n issuer: string;\n audience: string;\n} | null>\n{\n const secret = await getSessionSecretKey();\n\n try\n {\n const { payload } = await jose.jwtDecrypt(jwt, secret);\n\n return {\n issuedAt: new Date(payload.iat! * 1000),\n expiresAt: new Date(payload.exp! * 1000),\n issuer: payload.iss || '',\n audience: Array.isArray(payload.aud) ? payload.aud[0] : payload.aud || '',\n };\n }\n catch (err)\n {\n // Log error for debugging but return null for graceful handling\n if (coreEnv.NODE_ENV !== 'production')\n {\n authLogger.session.warn('Failed to get session info:', err instanceof Error ? err.message : 'Unknown error');\n }\n\n return null;\n }\n}\n\n/**\n * Check if session is about to expire (within threshold)\n *\n * @param jwt - Encrypted JWT string\n * @param thresholdHours - Hours before expiry to trigger refresh (default: 24)\n * @returns True if session should be refreshed\n */\nexport async function shouldRefreshSession(\n jwt: string,\n thresholdHours: number = 24,\n): Promise<boolean>\n{\n const info = await getSessionInfo(jwt);\n\n if (!info)\n {\n return true;\n }\n\n const hoursRemaining = (info.expiresAt.getTime() - Date.now()) / (1000 * 60 * 60);\n\n return hoursRemaining < thresholdHours;\n}\n","/**\n * @spfn/auth - Centralized Logger\n *\n * All auth package loggers with consistent naming\n */\n\nimport { logger as rootLogger } from '@spfn/core/logger';\n\nexport const authLogger = {\n plugin: rootLogger.child('@spfn/auth:plugin'),\n middleware: rootLogger.child('@spfn/auth:middleware'),\n interceptor: {\n general: rootLogger.child('@spfn/auth:interceptor:general'),\n login: rootLogger.child('@spfn/auth:interceptor:login'),\n keyRotation: rootLogger.child('@spfn/auth:interceptor:key-rotation'),\n oauth: rootLogger.child('@spfn/auth:interceptor:oauth'),\n },\n session: rootLogger.child('@spfn/auth:session'),\n service: rootLogger.child('@spfn/auth:service'),\n setup: rootLogger.child('@spfn/auth:setup'),\n email: rootLogger.child('@spfn/auth:email'),\n sms: rootLogger.child('@spfn/auth:sms'),\n};\n","/**\n * @spfn/auth - Global Configuration\n *\n * Manages global auth configuration including session TTL\n */\n\nimport { env } from '@spfn/auth/config';\n\nimport type { SocialProvider } from '../types';\nimport { normalizeOptionalEmail } from '../helpers/email';\n\n/**\n * Cookie name suffix derived from the server port, so several local dev\n * instances on the same domain do not overwrite each other's sessions.\n *\n * BREAKING: this read `PORT`, which no longer exists — the framework's port is\n * `SPFN_PORT`, because `PORT` is Next.js's own variable and two processes are\n * started. An app that had `PORT` set gets different cookie names than before\n * and its existing sessions stop resolving; one sign-in fixes it.\n */\nfunction getCookieSuffix(): string\n{\n const port = process.env.SPFN_PORT;\n\n return port ? `_${port}` : '';\n}\n\n/**\n * Cookie names used by SPFN Auth\n *\n * Names include a port-based suffix so that multiple dev instances\n * on different ports don't overwrite each other's cookies.\n */\nexport const COOKIE_NAMES = {\n /** Encrypted session data (userId, privateKey, keyId, algorithm) */\n get SESSION() \n {\n return `spfn_session${getCookieSuffix()}`; \n },\n /** Current key ID (for key rotation) */\n get SESSION_KEY_ID() \n {\n return `spfn_session_key_id${getCookieSuffix()}`; \n },\n /** Pending OAuth session (privateKey, keyId, algorithm) - temporary during OAuth flow */\n get OAUTH_PENDING()\n {\n return `spfn_oauth_pending${getCookieSuffix()}`;\n },\n /** OAuth CSRF nonce — double-submit against the (encrypted) state.nonce at callback */\n get OAUTH_CSRF()\n {\n return `spfn_oauth_csrf${getCookieSuffix()}`;\n },\n /** Password-setup session for verified-email signup — temporary, single-purpose */\n get SIGNUP_SETUP()\n {\n return `spfn_signup_setup${getCookieSuffix()}`;\n },\n};\n\n/**\n * OAuth CSRF 쿠키를 PORT 접미사와 무관하게 전부 수집한다.\n *\n * 쿠키를 심는 쪽은 Next.js 프로세스, 읽는 쪽은 API 프로세스라 분리 배포에서는\n * 두 프로세스의 PORT가 달라 COOKIE_NAMES.OAUTH_CSRF 정확 일치 조회가 빗나간다.\n * nonce 자체가 랜덤값이고 암호화된 state의 nonce와 대조되므로, 접미사가 다른\n * spfn_oauth_csrf* 후보를 모두 대조 대상으로 넘겨도 안전하다.\n */\nexport function matchOAuthCsrfCookies(\n cookies: Record<string, string>,\n): { name: string; value: string }[]\n{\n return Object.entries(cookies)\n .filter(([name]) => /^spfn_oauth_csrf(_\\d+)?$/.test(name))\n .map(([name, value]) => ({ name, value }));\n}\n\n/**\n * Parse duration string to seconds\n *\n * Supports: '30d', '12h', '45m', '3600s', or plain number\n *\n * @example\n * parseDuration('30d') // 2592000 (30 days in seconds)\n * parseDuration('12h') // 43200\n * parseDuration('45m') // 2700\n * parseDuration('3600') // 3600\n */\nexport function parseDuration(duration: string | number): number\n{\n if (typeof duration === 'number')\n {\n return duration;\n }\n\n const match = duration.match(/^(\\d+)([dhms]?)$/);\n if (!match)\n {\n throw new Error(`Invalid duration format: ${duration}. Use format like '30d', '12h', '45m', '3600s', or plain number.`);\n }\n\n const value = parseInt(match[1], 10);\n const unit = match[2] || 's';\n\n switch (unit)\n {\n case 'd':\n return value * 24 * 60 * 60;\n case 'h':\n return value * 60 * 60;\n case 'm':\n return value * 60;\n case 's':\n return value;\n default:\n throw new Error(`Unknown duration unit: ${unit}`);\n }\n}\n\n/**\n * Registration channel passed to the beforeRegister hook\n *\n * - credentials: email/phone + password registration\n * - oauth: new-user signup through a social provider (web or native flow)\n * - invitation: invitation acceptance\n */\nexport type RegisterChannel = 'credentials' | 'oauth' | 'invitation';\n\n/**\n * Context passed to the beforeRegister hook\n *\n * Credentials (password, keys) are intentionally excluded — the hook is a\n * policy gate, not a credential handler.\n */\nexport interface BeforeRegisterContext\n{\n channel: RegisterChannel;\n /** Social provider — only set when channel is 'oauth' */\n provider?: SocialProvider;\n /**\n * Canonical form of the address — trimmed and lower-cased, the same form\n * the account is stored under. A policy keyed on the address (a denylist, a\n * domain allowlist) therefore matches whatever capitalization the person\n * typed, instead of being walked past by `Blocked@Example.com`.\n */\n email?: string;\n /**\n * Whether the email is verified — only set when channel is 'oauth'.\n * OAuth providers may report an unverified (spoofable) email; the created\n * account stores it as null in that case, so email-based policies must\n * check this flag. credentials/invitation emails are already verified.\n */\n emailVerified?: boolean;\n phone?: string;\n /** App-supplied registration metadata (register params / OAuth start params / invitation) */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Auth configuration\n */\nexport interface AuthConfig\n{\n /**\n * Default session TTL in seconds or duration string\n *\n * Supports:\n * - Number: seconds (e.g., 2592000)\n * - String: '30d', '12h', '45m', '3600s'\n *\n * @default 7d (7 days)\n */\n sessionTtl?: string | number;\n\n /**\n * App-injected validator that runs before a new user row is created,\n * on every registration channel (credentials, oauth, invitation).\n *\n * Throw to reject the registration — RegistrationRejectedError (403) is\n * the recommended error; any HttpError subclass keeps its own status.\n * Runs after built-in checks (verification token, duplicate account),\n * so existing error precedence is unchanged. Not called for admin\n * seeding (initializeAuth) or when linking a social account to an\n * existing user.\n *\n * Runs inside the registration DB transaction on every channel — keep it\n * fast. A slow call (e.g. an external policy API) holds a pooled DB\n * connection open for its full duration on every signup.\n *\n * @example\n * ```typescript\n * configureAuth({\n * beforeRegister: async ({ channel, metadata }) =>\n * {\n * if (channel === 'credentials' && !isOldEnough(metadata?.birthDate))\n * {\n * throw new RegistrationRejectedError({ message: 'Age requirement not met' });\n * }\n * },\n * });\n * ```\n */\n beforeRegister?: (context: BeforeRegisterContext) => void | Promise<void>;\n}\n\n/**\n * Global auth configuration state\n */\nlet globalConfig: AuthConfig = {\n sessionTtl: '7d', // Default: 7 days\n};\n\n/**\n * Configure global auth settings\n *\n * @param config - Auth configuration\n *\n * @example\n * ```typescript\n * configureAuth({\n * sessionTtl: '30d', // 30 days\n * });\n * ```\n */\nexport function configureAuth(config: AuthConfig): void\n{\n globalConfig = {\n ...globalConfig,\n ...config,\n };\n}\n\n/**\n * Get current auth configuration\n */\nexport function getAuthConfig(): AuthConfig\n{\n return { ...globalConfig };\n}\n\n/**\n * Run the app-injected beforeRegister hook if configured — throws to reject.\n *\n * Single entry point for every registration channel so a new channel cannot\n * forget the configured-check. Callers invoke this right before creating the\n * user row.\n *\n * The address is folded here rather than at each call site, for the same reason\n * the check itself lives here: three channels supply it, and a policy that sees\n * a different spelling depending on which one the person came through is a\n * policy that can be walked past.\n */\nexport async function runBeforeRegister(context: BeforeRegisterContext): Promise<void>\n{\n const { beforeRegister } = globalConfig;\n\n if (beforeRegister)\n {\n await beforeRegister({ ...context, email: normalizeOptionalEmail(context.email) });\n }\n}\n\n/**\n * Get session TTL in seconds\n *\n * Priority:\n * 1. Runtime override (remember parameter)\n * 2. Global config (configureAuth)\n * 3. Environment variable (SPFN_AUTH_SESSION_TTL) - via config module\n * 4. Default (7 days)\n */\nexport function getSessionTtl(override?: string | number): number\n{\n // 1. Runtime override\n if (override !== undefined)\n {\n return parseDuration(override);\n }\n\n // 2. Global config\n if (globalConfig.sessionTtl !== undefined)\n {\n return parseDuration(globalConfig.sessionTtl);\n }\n\n // 3. Environment variable (from config module)\n const envTtl = env.SPFN_AUTH_SESSION_TTL;\n if (envTtl)\n {\n return parseDuration(envTtl);\n }\n\n // 4. Default: 7 days\n return 7 * 24 * 60 * 60;\n}\n","/**\n * Shared cookie option helpers for auth interceptors\n *\n * SPFN_AUTH_COOKIE_SECURE env var allows overriding the Secure flag.\n * - unset: defaults to NODE_ENV === 'production'\n * - \"true\" / \"false\": explicit override\n *\n * Useful for HTTP-only staging environments (e.g. bastion over plain HTTP).\n */\n\n/**\n * Resolve whether cookies should have the Secure flag.\n *\n * Priority:\n * 1. SPFN_AUTH_COOKIE_SECURE (explicit override)\n * 2. NODE_ENV === 'production'\n */\nfunction resolveSecure(): boolean\n{\n const override = process.env.SPFN_AUTH_COOKIE_SECURE;\n\n if (override !== undefined)\n {\n return override === 'true';\n }\n\n return process.env.NODE_ENV === 'production';\n}\n\n/**\n * Whether cookies should have the Secure flag.\n * Evaluated once at module load time.\n */\nexport const cookieSecure = resolveSecure();\n","/**\n * Login/Register Interceptor\n *\n * Automatically handles key generation and session management\n * for login, register, and invitation-accept endpoints.\n * (Invitation acceptance creates the user account + key pair and\n * logs the new user in, so it follows the same key/session flow.)\n */\n\nimport type { InterceptorRule } from '@spfn/core/nextjs/server';\nimport { generateKeyPair } from '../../server/lib/crypto';\nimport { sealSession } from '../../server/lib/session';\nimport { getSessionTtl, COOKIE_NAMES } from '../../server/lib/config';\nimport { authLogger } from '../../server/logger';\nimport { cookieSecure } from './cookie-options';\n\n/**\n * Login, Register, and Invitation-Accept Interceptor\n *\n * Request: Generates key pair and adds publicKey to request body\n * Response: Saves privateKey to HttpOnly cookie\n */\nexport const loginRegisterInterceptor: InterceptorRule =\n {\n pathPattern: /^\\/_auth\\/(login|register|invitations\\/accept|signup\\/password)$/,\n method: 'POST',\n\n request: async (ctx, next) =>\n {\n // Get old session if exists (for key rotation on login)\n const oldKeyId = ctx.cookies.get(COOKIE_NAMES.SESSION_KEY_ID);\n\n // Extract remember option from request body (if provided)\n const remember = ctx.body?.remember;\n\n // Generate new key pair\n const keyPair = generateKeyPair('ES256');\n\n // Add publicKey data to request body\n if (!ctx.body)\n {\n ctx.body = {};\n }\n\n ctx.body.publicKey = keyPair.publicKey;\n ctx.body.keyId = keyPair.keyId;\n ctx.body.fingerprint = keyPair.fingerprint;\n ctx.body.algorithm = keyPair.algorithm;\n ctx.body.keySize = Buffer.from(keyPair.publicKey, 'base64').length;\n\n // Add oldKeyId for login (key rotation)\n if (ctx.path === '/_auth/login' && oldKeyId)\n {\n ctx.body.oldKeyId = oldKeyId;\n }\n\n // Remove remember from body (not part of contract)\n delete ctx.body.remember;\n\n // Store privateKey and remember in metadata for response interceptor\n ctx.metadata.privateKey = keyPair.privateKey;\n ctx.metadata.keyId = keyPair.keyId;\n ctx.metadata.algorithm = keyPair.algorithm;\n ctx.metadata.remember = remember;\n\n await next();\n },\n\n response: async (ctx, next) =>\n {\n // Only process successful responses\n if (ctx.response.status !== 200)\n {\n await next();\n\n return;\n }\n\n // Handle both wrapped ({ data: { userId } }) and direct ({ userId }) responses\n const userData = ctx.response.body?.data || ctx.response.body;\n if (!userData?.userId)\n {\n authLogger.interceptor.login.error('No userId in response');\n await next();\n\n return;\n }\n\n try\n {\n // Get session TTL (priority: runtime > global > env > default)\n const ttl = getSessionTtl(ctx.metadata.remember);\n\n // Encrypt session data\n const sessionData =\n {\n userId: userData.userId,\n privateKey: ctx.metadata.privateKey,\n keyId: ctx.metadata.keyId,\n algorithm: ctx.metadata.algorithm,\n };\n\n const sealed = await sealSession(sessionData, ttl);\n\n // Set HttpOnly session cookie\n ctx.setCookies.push({\n name: COOKIE_NAMES.SESSION,\n value: sealed,\n options: {\n httpOnly: true,\n secure: cookieSecure,\n sameSite: 'lax',\n maxAge: ttl,\n path: '/',\n },\n });\n\n // Set keyId cookie (for oldKeyId lookup)\n ctx.setCookies.push({\n name: COOKIE_NAMES.SESSION_KEY_ID,\n value: ctx.metadata.keyId,\n options: {\n httpOnly: true,\n secure: cookieSecure,\n sameSite: 'lax',\n maxAge: ttl,\n path: '/',\n },\n });\n }\n catch (error)\n {\n const err = error as Error;\n authLogger.interceptor.login.error('Failed to save session', err);\n }\n\n await next();\n },\n };\n","/**\n * General Authentication Interceptor\n *\n * Handles authentication for all API requests except login/register\n * - Session validation and renewal\n * - JWT generation and signing\n * - Expired session cleanup\n */\n\nimport type { InterceptorRule } from '@spfn/core/nextjs/server';\nimport { unsealSession, sealSession, shouldRefreshSession } from '../../server/lib/session';\nimport { generateClientToken } from '../../server/lib/crypto';\nimport { getSessionTtl, COOKIE_NAMES } from '../../server/lib/config';\nimport { authLogger } from '../../server/logger';\nimport { cookieSecure } from './cookie-options';\n\n/**\n * Check if path requires authentication\n */\nfunction requiresAuth(path: string): boolean\n{\n // Paths that don't require auth\n const publicPaths = [\n /^\\/_auth\\/login$/,\n /^\\/_auth\\/register$/,\n /^\\/_auth\\/codes$/, // Send verification code\n /^\\/_auth\\/codes\\/verify$/, // Verify code\n /^\\/_auth\\/exists$/, // Check account exists\n ];\n\n return !publicPaths.some((pattern) => pattern.test(path));\n}\n\n/**\n * General Authentication Interceptor\n *\n * Applies to all paths except login/register/codes\n * - Validates session\n * - Generates JWT token\n * - Refreshes session if needed\n * - Clears expired sessions\n */\nexport const generalAuthInterceptor: InterceptorRule =\n {\n pathPattern: '*', // Match all paths, filter by requiresAuth()\n method: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],\n\n request: async (ctx, next) =>\n {\n // Skip if path doesn't require auth\n if (!requiresAuth(ctx.path))\n {\n authLogger.interceptor.general.debug(`Public path, skipping auth: ${ctx.path}`);\n await next();\n\n return;\n }\n\n // Log available cookies\n const cookieNames = Array.from(ctx.cookies.keys());\n authLogger.interceptor.general.debug('Available cookies:', {\n cookieNames,\n totalCount: cookieNames.length,\n lookingFor: COOKIE_NAMES.SESSION,\n });\n\n const sessionCookie = ctx.cookies.get(COOKIE_NAMES.SESSION);\n\n authLogger.interceptor.general.debug('Request', {\n method: ctx.method,\n path: ctx.path,\n hasSession: !!sessionCookie,\n sessionLength: sessionCookie?.length ?? 0,\n sessionPrefix: sessionCookie?.slice(0, 20) ?? '',\n sessionSuffix: sessionCookie?.slice(-10) ?? '',\n });\n\n // No session cookie\n if (!sessionCookie)\n {\n authLogger.interceptor.general.debug('No session cookie, proceeding without auth');\n // Let request proceed - server will return 401\n await next();\n\n return;\n }\n\n try\n {\n // Decrypt and validate session\n const session = await unsealSession(sessionCookie);\n\n authLogger.interceptor.general.debug('Session valid', {\n userId: session.userId,\n keyId: session.keyId,\n });\n\n // Check if session should be refreshed (within 24h of expiry)\n const needsRefresh = await shouldRefreshSession(sessionCookie, 24);\n\n if (needsRefresh)\n {\n authLogger.interceptor.general.debug('Session needs refresh (within 24h of expiry)');\n // Mark for session renewal in response interceptor\n ctx.metadata.refreshSession = true;\n ctx.metadata.sessionData = session;\n }\n\n // Generate JWT token\n const token = generateClientToken(\n {\n userId: session.userId,\n keyId: session.keyId,\n timestamp: Date.now(),\n },\n session.privateKey,\n session.algorithm,\n { expiresIn: '15m' },\n );\n\n authLogger.interceptor.general.debug('Generated JWT token (expires in 15m)');\n\n // Add authentication headers\n ctx.headers['Authorization'] = `Bearer ${token}`;\n ctx.headers['X-Key-Id'] = session.keyId;\n\n // Store session info in metadata\n ctx.metadata.userId = session.userId;\n ctx.metadata.sessionValid = true;\n }\n catch (error)\n {\n const err = error as Error;\n const msg = err.message.toLowerCase();\n\n // Session expired or invalid\n if (msg.includes('expired') || msg.includes('invalid'))\n {\n authLogger.interceptor.general.warn('Session expired or invalid', {\n message: err.message,\n cookieLength: sessionCookie.length,\n cookiePrefix: sessionCookie.slice(0, 20),\n cookieSuffix: sessionCookie.slice(-10),\n });\n authLogger.interceptor.general.debug('Marking session for cleanup');\n\n // Mark for cleanup in response interceptor\n ctx.metadata.clearSession = true;\n ctx.metadata.sessionValid = false;\n }\n else\n {\n authLogger.interceptor.general.error('Failed to process session', err);\n }\n }\n\n await next();\n },\n\n response: async (ctx, next) =>\n {\n // Backend returned 401 with a valid session — server rejected it\n if (ctx.response.status === 401 && ctx.metadata.sessionValid)\n {\n authLogger.interceptor.general.warn('Backend returned 401, clearing session');\n\n ctx.setCookies.push({\n name: COOKIE_NAMES.SESSION,\n value: '',\n options: { maxAge: 0, path: '/' },\n });\n\n ctx.setCookies.push({\n name: COOKIE_NAMES.SESSION_KEY_ID,\n value: '',\n options: { maxAge: 0, path: '/' },\n });\n\n await next();\n\n return;\n }\n\n // Clear expired/invalid session\n if (ctx.metadata.clearSession)\n {\n ctx.setCookies.push({\n name: COOKIE_NAMES.SESSION,\n value: '',\n options: {\n maxAge: 0,\n path: '/',\n },\n });\n\n ctx.setCookies.push({\n name: COOKIE_NAMES.SESSION_KEY_ID,\n value: '',\n options: {\n maxAge: 0,\n path: '/',\n },\n });\n }\n // Refresh session if needed and request was successful\n else if (ctx.metadata.refreshSession && ctx.response.status === 200)\n {\n try\n {\n const sessionData = ctx.metadata.sessionData;\n const ttl = getSessionTtl();\n\n // Re-encrypt session with new TTL\n const sealed = await sealSession(sessionData, ttl);\n\n // Update session cookie\n ctx.setCookies.push({\n name: COOKIE_NAMES.SESSION,\n value: sealed,\n options: {\n httpOnly: true,\n secure: cookieSecure,\n sameSite: 'lax',\n maxAge: ttl,\n path: '/',\n },\n });\n\n // Update keyId cookie\n ctx.setCookies.push({\n name: COOKIE_NAMES.SESSION_KEY_ID,\n value: sessionData.keyId,\n options: {\n httpOnly: true,\n secure: cookieSecure,\n sameSite: 'lax',\n maxAge: ttl,\n path: '/',\n },\n });\n\n authLogger.interceptor.general.info('Session refreshed', {\n userId: sessionData.userId,\n sealedLength: sealed.length,\n sealedPrefix: sealed.slice(0, 20),\n });\n }\n catch (error)\n {\n const err = error as Error;\n authLogger.interceptor.general.error('Failed to refresh session', err);\n }\n }\n // Handle logout (clear session)\n else if (ctx.path === '/_auth/logout' && ctx.response.ok)\n {\n const base = {\n httpOnly: true,\n secure: cookieSecure,\n maxAge: 0,\n path: '/',\n };\n\n ctx.setCookies.push({\n name: COOKIE_NAMES.SESSION,\n value: '',\n options: { ...base, sameSite: 'lax' },\n });\n\n ctx.setCookies.push({\n name: COOKIE_NAMES.SESSION_KEY_ID,\n value: '',\n options: { ...base, sameSite: 'lax' },\n });\n\n ctx.setCookies.push({\n name: COOKIE_NAMES.OAUTH_PENDING,\n value: '',\n options: { ...base, sameSite: 'lax' },\n });\n }\n\n await next();\n },\n };\n","/**\n * Key Rotation Interceptor\n *\n * Handles key rotation with new key generation and session update\n */\n\nimport type { InterceptorRule } from '@spfn/core/nextjs/server';\nimport { generateKeyPair, generateClientToken } from '../../server/lib/crypto';\nimport { unsealSession, sealSession } from '../../server/lib/session';\nimport { getSessionTtl, COOKIE_NAMES } from '../../server/lib/config';\nimport { authLogger } from '../../server/logger';\nimport { cookieSecure } from './cookie-options';\n\n/**\n * Key Rotation Interceptor\n *\n * Request: Generates new key pair and adds to body, authenticates with current key\n * Response: Updates session with new privateKey\n */\nexport const keyRotationInterceptor: InterceptorRule =\n {\n pathPattern: '/_auth/keys/rotate',\n method: 'POST',\n\n request: async (ctx, next) =>\n {\n const sessionCookie = ctx.cookies.get(COOKIE_NAMES.SESSION);\n\n if (!sessionCookie)\n {\n await next();\n\n return;\n }\n\n try\n {\n // Get current session\n const currentSession = await unsealSession(sessionCookie);\n\n // Generate new key pair\n const newKeyPair = generateKeyPair('ES256');\n\n // Add new publicKey to request body\n if (!ctx.body)\n {\n ctx.body = {};\n }\n\n ctx.body.publicKey = newKeyPair.publicKey;\n ctx.body.keyId = newKeyPair.keyId;\n ctx.body.fingerprint = newKeyPair.fingerprint;\n ctx.body.algorithm = newKeyPair.algorithm;\n ctx.body.keySize = Buffer.from(newKeyPair.publicKey, 'base64').length;\n\n console.log('New key generated:', newKeyPair);\n console.log('publicKey:', newKeyPair.publicKey);\n console.log('keyId:', newKeyPair.keyId);\n console.log('fingerprint:', newKeyPair.fingerprint);\n\n // Authenticate with CURRENT key\n const token = generateClientToken(\n {\n userId: currentSession.userId,\n keyId: currentSession.keyId,\n action: 'rotate_key',\n timestamp: Date.now(),\n },\n currentSession.privateKey,\n currentSession.algorithm,\n {expiresIn: '15m'},\n );\n\n ctx.headers['Authorization'] = `Bearer ${token}`;\n ctx.headers['X-Key-Id'] = currentSession.keyId;\n\n // Store new key and userId in metadata\n ctx.metadata.newPrivateKey = newKeyPair.privateKey;\n ctx.metadata.newKeyId = newKeyPair.keyId;\n ctx.metadata.newAlgorithm = newKeyPair.algorithm;\n ctx.metadata.userId = currentSession.userId;\n }\n catch (error)\n {\n const err = error as Error;\n authLogger.interceptor.keyRotation.error('Failed to prepare key rotation', err);\n }\n\n await next();\n },\n\n response: async (ctx, next) =>\n {\n // Only update session on successful rotation\n if (ctx.response.status !== 200)\n {\n await next();\n\n return;\n }\n\n if (!ctx.metadata.newPrivateKey || !ctx.metadata.userId)\n {\n authLogger.interceptor.keyRotation.error('Missing key rotation metadata');\n await next();\n\n return;\n }\n\n try\n {\n // Get session TTL\n const ttl = getSessionTtl();\n\n // Create new session with rotated key\n const newSessionData =\n {\n userId: ctx.metadata.userId,\n privateKey: ctx.metadata.newPrivateKey,\n keyId: ctx.metadata.newKeyId,\n algorithm: ctx.metadata.newAlgorithm,\n };\n\n const sealed = await sealSession(newSessionData, ttl);\n\n // Update session cookie\n ctx.setCookies.push({\n name: COOKIE_NAMES.SESSION,\n value: sealed,\n options: {\n httpOnly: true,\n secure: cookieSecure,\n sameSite: 'lax',\n maxAge: ttl,\n path: '/',\n },\n });\n\n // Update keyId cookie\n ctx.setCookies.push({\n name: COOKIE_NAMES.SESSION_KEY_ID,\n value: ctx.metadata.newKeyId,\n options: {\n httpOnly: true,\n secure: cookieSecure,\n sameSite: 'lax',\n maxAge: ttl,\n path: '/',\n },\n });\n }\n catch (error)\n {\n const err = error as Error;\n authLogger.interceptor.keyRotation.error('Failed to update session after rotation', err);\n }\n\n await next();\n },\n };\n","/**\n * OAuth State Management\n *\n * CSRF 방지를 위한 state 파라미터 암호화/복호화\n * - returnUrl: OAuth 성공 후 리다이렉트할 URL\n * - nonce: CSRF 방지용 일회용 토큰\n * - provider: OAuth provider (google, github 등)\n * - publicKey, keyId, fingerprint, algorithm: 클라이언트 키 정보\n * - expiresAt: state 만료 시간\n */\n\nimport * as jose from 'jose';\nimport { env } from '@spfn/auth/config';\nimport { type KeyAlgorithmType } from '../../types';\n\nexport interface OAuthState\n{\n returnUrl: string;\n nonce: string;\n provider: string;\n publicKey: string;\n keyId: string;\n fingerprint: string;\n algorithm: KeyAlgorithmType;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Get encryption key derived from session secret\n */\nasync function getStateKey(): Promise<Uint8Array>\n{\n const secret = env.SPFN_AUTH_SESSION_SECRET;\n const encoder = new TextEncoder();\n const data = encoder.encode(`oauth-state:${secret}`);\n const hashBuffer = await crypto.subtle.digest('SHA-256', data);\n\n return new Uint8Array(hashBuffer);\n}\n\n/**\n * Generate random nonce\n */\nfunction generateNonce(): string\n{\n const array = new Uint8Array(16);\n crypto.getRandomValues(array);\n\n return Array.from(array, b => b.toString(16).padStart(2, '0')).join('');\n}\n\n/**\n * Generate a CSRF nonce for the OAuth flow. The caller passes it to\n * createOAuthState AND sets it as the oauth_csrf cookie, so the callback can\n * double-submit-verify the flow was initiated by this same browser.\n */\nexport function generateOAuthNonce(): string\n{\n return generateNonce();\n}\n\nexport interface CreateOAuthStateParams\n{\n provider: string;\n returnUrl: string;\n publicKey: string;\n keyId: string;\n fingerprint: string;\n algorithm: KeyAlgorithmType;\n metadata?: Record<string, unknown>;\n /**\n * CSRF nonce bound into the state. Pass the same value as the oauth_csrf\n * cookie. Defaults to a fresh nonce (unbound — legacy/no-CSRF callers).\n */\n nonce?: string;\n}\n\n/**\n * OAuth state 생성 및 암호화\n *\n * @param params - state 생성에 필요한 파라미터\n * @returns 암호화된 state 문자열\n */\nexport async function createOAuthState(params: CreateOAuthStateParams): Promise<string>\n{\n const key = await getStateKey();\n\n const state: OAuthState = {\n returnUrl: params.returnUrl,\n nonce: params.nonce ?? generateNonce(),\n provider: params.provider,\n publicKey: params.publicKey,\n keyId: params.keyId,\n fingerprint: params.fingerprint,\n algorithm: params.algorithm,\n metadata: params.metadata,\n };\n\n const jwe = await new jose.EncryptJWT({ state })\n .setProtectedHeader({ alg: 'dir', enc: 'A256GCM' })\n .setIssuedAt()\n .setExpirationTime('10m')\n .encrypt(key);\n\n // URL-safe base64 encoding\n return encodeURIComponent(jwe);\n}\n\n/**\n * OAuth state 복호화 및 검증\n *\n * @param encryptedState - 암호화된 state 문자열\n * @returns 복호화된 state 객체\n * @throws Error if state is invalid or expired (JWE exp claim으로 자동 검증)\n */\nexport async function verifyOAuthState(encryptedState: string): Promise<OAuthState>\n{\n const key = await getStateKey();\n\n const jwe = decodeURIComponent(encryptedState);\n const { payload } = await jose.jwtDecrypt(jwe, key);\n\n return payload.state as OAuthState;\n}\n","/**\n * Session helpers for Next.js\n *\n * Server-side only (uses next/headers)\n */\n\nimport * as jose from 'jose';\nimport { cookies } from 'next/headers.js';\nimport { sealSession, unsealSession, type SessionData } from '../server/lib/session';\nimport { COOKIE_NAMES, getSessionTtl, parseDuration } from '../server/lib/config';\nimport { type KeyAlgorithmType } from '../server/types';\nimport { env } from '@spfn/auth/config';\nimport { logger } from '@spfn/core/logger';\n\nexport type { SessionData };\n\n/**\n * Pending OAuth session data (before user ID is known)\n */\nexport interface PendingSessionData\n{\n privateKey: string;\n keyId: string;\n algorithm: KeyAlgorithmType;\n}\n\n/**\n * Public session information (excludes sensitive data)\n */\nexport interface PublicSession\n{\n /** User ID */\n userId: string;\n}\n\n/**\n * Options for saveSession\n */\nexport interface SaveSessionOptions\n{\n /**\n * Session TTL (time to live)\n *\n * Supports:\n * - Number: seconds (e.g., 2592000)\n * - String: duration format ('30d', '12h', '45m', '3600s')\n *\n * If not provided, uses global configuration:\n * 1. Global config (configureAuth)\n * 2. Environment variable (SPFN_AUTH_SESSION_TTL)\n * 3. Default (7d)\n */\n maxAge?: number | string;\n\n /**\n * Remember me option\n *\n * When true, uses extended session duration (if configured)\n */\n remember?: boolean;\n}\n\n/**\n * Save session to HttpOnly cookie\n *\n * @param data - Session data to save\n * @param options - Session options (maxAge, remember)\n *\n * @example\n * ```typescript\n * // Use global configuration\n * await saveSession(sessionData);\n *\n * // Custom TTL with duration string\n * await saveSession(sessionData, { maxAge: '30d' });\n *\n * // Custom TTL in seconds\n * await saveSession(sessionData, { maxAge: 2592000 });\n *\n * // Remember me\n * await saveSession(sessionData, { remember: true });\n * ```\n */\nexport async function saveSession(\n data: SessionData,\n options?: SaveSessionOptions,\n): Promise<void>\n{\n // Calculate maxAge\n let maxAge: number;\n\n if (options?.maxAge !== undefined)\n {\n // Custom maxAge provided\n maxAge = typeof options.maxAge === 'number'\n ? options.maxAge\n : parseDuration(options.maxAge);\n }\n else\n {\n // Use getSessionTtl for consistent configuration\n maxAge = getSessionTtl();\n }\n\n const token = await sealSession(data, maxAge);\n const cookieStore = await cookies();\n\n cookieStore.set(COOKIE_NAMES.SESSION, token, {\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'lax',\n path: '/',\n maxAge,\n });\n}\n\n/**\n * Get session from HttpOnly cookie\n *\n * Returns public session info only (excludes privateKey, algorithm, keyId)\n */\nexport async function getSession(): Promise<PublicSession | null>\n{\n const cookieStore = await cookies();\n const sessionCookie = cookieStore.get(COOKIE_NAMES.SESSION);\n\n if (!sessionCookie)\n {\n return null;\n }\n\n try\n {\n // Never log the cookie value — it's the sealed session token.\n logger.debug('Validating session cookie', { present: true });\n const session = await unsealSession(sessionCookie.value);\n\n // Return only public information\n return {\n userId: session.userId,\n };\n }\n catch (error)\n {\n // Session expired or invalid\n // Note: Cannot delete cookies in Server Components (read-only)\n // Use validateSessionMiddleware() in Next.js middleware for automatic cleanup\n logger.debug('Session validation failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n\n return null;\n }\n}\n\n/**\n * Clear session cookie\n */\nexport async function clearSession(): Promise<void>\n{\n const cookieStore = await cookies();\n cookieStore.delete(COOKIE_NAMES.SESSION);\n cookieStore.delete(COOKIE_NAMES.SESSION_KEY_ID);\n}\n\n// ============================================================================\n// Pending OAuth Session (for OAuth flow)\n// ============================================================================\n\n/**\n * Get encryption key for pending session\n */\nasync function getPendingSessionKey(): Promise<Uint8Array>\n{\n const secret = env.SPFN_AUTH_SESSION_SECRET;\n const encoder = new TextEncoder();\n const data = encoder.encode(`oauth-pending:${secret}`);\n const hashBuffer = await crypto.subtle.digest('SHA-256', data);\n\n return new Uint8Array(hashBuffer);\n}\n\n/**\n * Seal pending session data (for OAuth flow)\n *\n * @param data - Pending session data (privateKey, keyId, algorithm)\n * @param ttl - Time to live in seconds (default: 10 minutes)\n */\nexport async function sealPendingSession(\n data: PendingSessionData,\n ttl: number = 600,\n): Promise<string>\n{\n const key = await getPendingSessionKey();\n\n return await new jose.EncryptJWT({ data })\n .setProtectedHeader({ alg: 'dir', enc: 'A256GCM' })\n .setIssuedAt()\n .setExpirationTime(`${ttl}s`)\n .setIssuer('spfn-auth')\n .setAudience('spfn-oauth')\n .encrypt(key);\n}\n\n/**\n * Unseal pending session data\n *\n * @param jwt - Encrypted pending session token\n */\nexport async function unsealPendingSession(jwt: string): Promise<PendingSessionData>\n{\n const key = await getPendingSessionKey();\n\n const { payload } = await jose.jwtDecrypt(jwt, key, {\n issuer: 'spfn-auth',\n audience: 'spfn-oauth',\n });\n\n return payload.data as PendingSessionData;\n}\n\n/**\n * Get pending session from cookie\n */\nexport async function getPendingSession(): Promise<PendingSessionData | null>\n{\n const cookieStore = await cookies();\n const pendingCookie = cookieStore.get(COOKIE_NAMES.OAUTH_PENDING);\n\n if (!pendingCookie)\n {\n return null;\n }\n\n try\n {\n return await unsealPendingSession(pendingCookie.value);\n }\n catch (error)\n {\n logger.debug('Pending session validation failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n\n return null;\n }\n}\n\n/**\n * Clear pending session cookie\n */\nexport async function clearPendingSession(): Promise<void>\n{\n const cookieStore = await cookies();\n cookieStore.delete(COOKIE_NAMES.OAUTH_PENDING);\n}\n","/**\n * OAuth Interceptors\n *\n * 1. oauthUrlInterceptor: OAuth URL 요청 시 키쌍 생성 및 state 주입\n * 2. oauthFinalizeInterceptor: OAuth 완료 시 pending session에서 세션 저장\n */\n\nimport type { InterceptorRule, ResponseInterceptorContext } from '@spfn/core/nextjs/server';\nimport { generateKeyPair } from '../../server/lib/crypto';\nimport { createOAuthState, generateOAuthNonce } from '../../server/lib/oauth/state';\nimport { sealSession } from '../../server/lib/session';\nimport { COOKIE_NAMES, getSessionTtl } from '../../server/lib/config';\nimport { authLogger } from '../../server/logger';\nimport { sealPendingSession, unsealPendingSession } from '../session-helpers';\nimport { cookieSecure } from './cookie-options';\n\n/**\n * OAuth URL Interceptor\n *\n * POST /_auth/oauth/:provider/url 요청을 가로채서\n * 키쌍 생성 및 state 주입 처리\n */\nexport const oauthUrlInterceptor: InterceptorRule = {\n pathPattern: /^\\/_auth\\/oauth\\/\\w+\\/url$/,\n method: 'POST',\n\n request: async (ctx, next) =>\n {\n const provider = ctx.path.split('/')[3]; // google, github, etc.\n const returnUrl = ctx.body?.returnUrl || '/';\n const metadata = ctx.body?.metadata as Record<string, unknown> | undefined;\n\n // 키쌍 생성\n const keyPair = generateKeyPair('ES256');\n\n // CSRF nonce: bound into the state AND set as the oauth_csrf cookie below,\n // so the backend callback can confirm the flow started in THIS browser.\n const csrfNonce = generateOAuthNonce();\n\n // state 생성 (publicKey 포함)\n const state = await createOAuthState({\n provider,\n returnUrl,\n publicKey: keyPair.publicKey,\n keyId: keyPair.keyId,\n fingerprint: keyPair.fingerprint,\n algorithm: keyPair.algorithm,\n nonce: csrfNonce,\n metadata,\n });\n\n // body에 state 주입\n if (!ctx.body)\n {\n ctx.body = {};\n }\n ctx.body.state = state;\n\n // pending session 저장용 metadata\n ctx.metadata.pendingSession = {\n privateKey: keyPair.privateKey,\n keyId: keyPair.keyId,\n algorithm: keyPair.algorithm,\n };\n ctx.metadata.oauthCsrf = csrfNonce;\n\n authLogger.interceptor.oauth?.debug?.('OAuth state created', {\n provider,\n keyId: keyPair.keyId,\n });\n\n await next();\n },\n\n response: async (ctx, next) =>\n {\n // 성공 응답이고 pending session이 있으면 쿠키 설정\n if (ctx.response.ok && ctx.metadata.pendingSession)\n {\n try\n {\n const sealed = await sealPendingSession(ctx.metadata.pendingSession);\n\n ctx.setCookies.push({\n name: COOKIE_NAMES.OAUTH_PENDING,\n value: sealed,\n options: {\n httpOnly: true,\n secure: cookieSecure,\n sameSite: 'lax', // OAuth 리다이렉트 허용\n maxAge: 600, // 10분\n path: '/',\n },\n });\n\n // CSRF nonce cookie (double-submit against the state.nonce at callback)\n if (ctx.metadata.oauthCsrf)\n {\n ctx.setCookies.push({\n name: COOKIE_NAMES.OAUTH_CSRF,\n value: ctx.metadata.oauthCsrf,\n options: {\n httpOnly: true,\n secure: cookieSecure,\n sameSite: 'lax',\n maxAge: 600,\n path: '/',\n },\n });\n }\n\n authLogger.interceptor.oauth?.debug?.('Pending session cookie set', {\n keyId: ctx.metadata.pendingSession.keyId,\n });\n }\n catch (error)\n {\n const err = error as Error;\n authLogger.interceptor.oauth?.error?.('Failed to set pending session', err);\n }\n }\n\n await next();\n },\n};\n\n/**\n * Finalize 실패 시 에러 응답 설정 + pending 쿠키 정리\n */\nfunction setFinalizeError(ctx: ResponseInterceptorContext, message: string): void\n{\n ctx.response.ok = false;\n ctx.response.status = 401;\n ctx.response.statusText = 'Unauthorized';\n ctx.response.body = { success: false, message };\n\n ctx.setCookies.push({\n name: COOKIE_NAMES.OAUTH_PENDING,\n value: '',\n options: {\n httpOnly: true,\n secure: cookieSecure,\n sameSite: 'lax',\n maxAge: 0,\n path: '/',\n },\n });\n}\n\n/**\n * OAuth Finalize Interceptor\n *\n * POST /_auth/oauth/finalize 요청을 가로채서\n * pending session에서 세션 저장\n */\nexport const oauthFinalizeInterceptor: InterceptorRule = {\n pathPattern: /^\\/_auth\\/oauth\\/finalize$/,\n method: 'POST',\n\n response: async (ctx, next) =>\n {\n // 성공 응답일 때만 처리\n if (!ctx.response.ok)\n {\n await next();\n\n return;\n }\n\n const pendingCookie = ctx.cookies.get(COOKIE_NAMES.OAUTH_PENDING);\n if (!pendingCookie)\n {\n authLogger.interceptor.oauth?.warn?.('No pending session cookie found');\n setFinalizeError(ctx, 'OAuth session expired. Please try again.');\n await next();\n\n return;\n }\n\n try\n {\n // pending session에서 privateKey 복원\n const pendingSession = await unsealPendingSession(pendingCookie);\n\n // body에서 userId, keyId 추출\n const { userId, keyId } = ctx.response.body || {};\n\n if (!userId || !keyId)\n {\n authLogger.interceptor.oauth?.error?.('Missing userId or keyId in response');\n setFinalizeError(ctx, 'OAuth finalize failed: missing credentials');\n await next();\n\n return;\n }\n\n // keyId 일치 확인\n if (pendingSession.keyId !== keyId)\n {\n authLogger.interceptor.oauth?.error?.('KeyId mismatch', {\n expected: pendingSession.keyId,\n received: keyId,\n });\n setFinalizeError(ctx, 'OAuth session mismatch. Please try again.');\n await next();\n\n return;\n }\n\n // 세션 생성.\n // `userId` here is the value reflected by /_auth/oauth/finalize (a UI\n // convenience, not a trust anchor). It's safe to seal: keyId was matched\n // against the pending cookie above, the session is sealed, and the\n // backend re-derives identity from keyId on every request — see the\n // SECURITY note on the oauthFinalize route handler.\n const ttl = getSessionTtl();\n const sessionToken = await sealSession({\n userId,\n privateKey: pendingSession.privateKey,\n keyId: pendingSession.keyId,\n algorithm: pendingSession.algorithm,\n }, ttl);\n\n // 세션 쿠키 설정\n ctx.setCookies.push({\n name: COOKIE_NAMES.SESSION,\n value: sessionToken,\n options: {\n httpOnly: true,\n secure: cookieSecure,\n sameSite: 'lax',\n maxAge: ttl,\n path: '/',\n },\n });\n\n // keyId 쿠키 설정\n ctx.setCookies.push({\n name: COOKIE_NAMES.SESSION_KEY_ID,\n value: keyId,\n options: {\n httpOnly: true,\n secure: cookieSecure,\n sameSite: 'lax',\n maxAge: ttl,\n path: '/',\n },\n });\n\n // pending session 쿠키 삭제 (maxAge: 0)\n ctx.setCookies.push({\n name: COOKIE_NAMES.OAUTH_PENDING,\n value: '',\n options: {\n httpOnly: true,\n secure: cookieSecure,\n sameSite: 'lax',\n maxAge: 0,\n path: '/',\n },\n });\n\n authLogger.interceptor.oauth?.debug?.('OAuth session finalized', {\n userId,\n keyId,\n });\n }\n catch (error)\n {\n const err = error as Error;\n authLogger.interceptor.oauth?.error?.('Failed to finalize OAuth session', err);\n setFinalizeError(ctx, err.message);\n }\n\n await next();\n },\n};\n","/**\n * Verified-Email Signup Interceptor\n *\n * Carries the password-setup session between the two browser-facing steps of the\n * verified-email signup, so the secret that authorizes password setup lives in an\n * HttpOnly cookie and never in page script.\n *\n * On the confirm response it moves `setupSecret` out of the body and into the\n * cookie. On the password request it puts the cookie back into the body, the same\n * way `loginRegisterInterceptor` injects a device key. Both interceptors match\n * `/_auth/signup/password` and both run — matching rules execute as a chain in\n * registration order, they do not compete — so the password request arrives with\n * the setup secret and a freshly generated key.\n */\n\nimport type { InterceptorRule } from '@spfn/core/nextjs/server';\nimport { COOKIE_NAMES } from '../../server/lib/config';\nimport { authLogger } from '../../server/logger';\nimport { cookieSecure } from './cookie-options';\n\n/**\n * Setup-session cookie lifetime, in seconds.\n *\n * Deliberately a little longer than the server-side setup session: the server\n * decides when the session dies, and a cookie that expired first would turn an\n * expired-session refusal into a missing-cookie one, which reads as a different\n * bug to whoever is looking.\n */\nconst SETUP_COOKIE_TTL_SECONDS = 60 * 60;\n\n/**\n * Cookie carrying the password-setup session.\n */\nfunction setupCookie(value: string, maxAge: number)\n{\n return {\n name: COOKIE_NAMES.SIGNUP_SETUP,\n value,\n options: {\n httpOnly: true,\n secure: cookieSecure,\n sameSite: 'lax' as const,\n maxAge,\n path: '/',\n },\n };\n}\n\nexport const signupLinkInterceptor: InterceptorRule = {\n pathPattern: /^\\/_auth\\/signup\\/(email\\/confirm|password)$/,\n method: 'POST',\n\n request: async (ctx, next) =>\n {\n if (ctx.path === '/_auth/signup/password')\n {\n const cookie = ctx.cookies.get(COOKIE_NAMES.SIGNUP_SETUP);\n\n if (cookie)\n {\n if (!ctx.body)\n {\n ctx.body = {};\n }\n\n ctx.body.setupSecret = cookie;\n }\n }\n\n await next();\n },\n\n response: async (ctx, next) =>\n {\n if (!ctx.response.ok)\n {\n // A refusal here is often the user's to fix — a password that fails\n // the strength policy, an app policy that rejected the signup. The\n // setup session survives those on the server, so the cookie has to\n // survive them too, or the retry has nothing to present.\n await next();\n\n return;\n }\n\n if (ctx.path === '/_auth/signup/email/confirm')\n {\n const secret = ctx.response.body?.setupSecret;\n\n if (!secret)\n {\n authLogger.interceptor.oauth?.error?.('Signup confirm response carried no setup secret');\n await next();\n\n return;\n }\n\n ctx.setCookies.push(setupCookie(secret, SETUP_COOKIE_TTL_SECONDS));\n\n // The browser must never see it — an HttpOnly cookie that page\n // script can also read out of the JSON body is not HttpOnly.\n delete ctx.response.body.setupSecret;\n }\n\n if (ctx.path === '/_auth/signup/password')\n {\n // Spent. Clearing it stops a stale cookie from being presented to a\n // session the server has already marked used.\n ctx.setCookies.push(setupCookie('', 0));\n }\n\n await next();\n },\n};\n","/**\n * Auth Interceptors for Next.js Proxy\n *\n * Automatically registers interceptors for authentication flow\n *\n * Every rule whose path and method match runs, as a chain in this order — they\n * do not compete for a single match. Two of them share /_auth/signup/password on\n * purpose: signupLinkInterceptor supplies the setup secret and\n * loginRegisterInterceptor supplies the device key.\n *\n * Order matters - more specific interceptors first:\n * 1. signupLinkInterceptor - Most specific (verified-email signup only)\n * 2. loginRegisterInterceptor - Specific (login/register/signup password)\n * 3. keyRotationInterceptor - Specific (key rotation only)\n * 4. oauthUrlInterceptor - OAuth URL generation (key generation + state injection)\n * 5. generalAuthInterceptor - General (all authenticated requests)\n */\n\nimport { loginRegisterInterceptor } from './login-register';\nimport { generalAuthInterceptor } from './general-auth';\nimport { keyRotationInterceptor } from './key-rotation';\nimport { oauthUrlInterceptor, oauthFinalizeInterceptor } from './oauth';\nimport { signupLinkInterceptor } from './signup-link';\n\n/**\n * All auth interceptors\n *\n * Execution order:\n * 1. signupLinkInterceptor - Handles verified-email signup (setup secret ↔ HttpOnly cookie)\n * 2. loginRegisterInterceptor - Handles login/register/signup password (key generation + session save)\n * 3. keyRotationInterceptor - Handles key rotation (new key generation + session update)\n * 4. oauthUrlInterceptor - Handles OAuth URL requests (key generation + state injection + pending session)\n * 5. oauthFinalizeInterceptor - Handles OAuth finalize (pending session → full session)\n * 6. generalAuthInterceptor - Handles all authenticated requests (session validation + JWT injection + session renewal)\n */\nexport const authInterceptors = [\n signupLinkInterceptor,\n loginRegisterInterceptor,\n keyRotationInterceptor,\n oauthUrlInterceptor,\n oauthFinalizeInterceptor,\n generalAuthInterceptor,\n];\n\nexport { loginRegisterInterceptor } from './login-register';\nexport { generalAuthInterceptor } from './general-auth';\nexport { keyRotationInterceptor } from './key-rotation';\nexport { oauthUrlInterceptor, oauthFinalizeInterceptor } from './oauth';\nexport { signupLinkInterceptor } from './signup-link';\n\n// Deprecated: use generalAuthInterceptor instead\nexport { generalAuthInterceptor as authenticationInterceptor };\n"],"mappings":";AAoBA,SAAS,4BAA4B;;;ACRrC,OAAOA,aAAY;AACnB,OAAO,SAA+C;AAuD/C,SAAS,uBAChB;AACI,QAAM,QAAQA,QAAO,WAAW;AAEhC,QAAM,EAAE,YAAY,UAAU,IAAIA,QAAO,oBAAoB,MAAM;AAAA,IAC/D,YAAY;AAAA;AAAA,IACZ,mBAAmB;AAAA,MACf,MAAM;AAAA,MACN,QAAQ;AAAA,IACZ;AAAA,IACA,oBAAoB;AAAA,MAChB,MAAM;AAAA,MACN,QAAQ;AAAA,IACZ;AAAA,EACJ,CAAC;AAGD,QAAM,gBAAgB,WAAW,SAAS,QAAQ;AAClD,QAAM,eAAe,UAAU,SAAS,QAAQ;AAGhD,QAAM,cAAcA,QACf,WAAW,QAAQ,EACnB,OAAO,SAAS,EAChB,OAAO,KAAK;AAEjB,SAAO;AAAA,IACH,YAAY;AAAA,IACZ,WAAW;AAAA,IACX;AAAA,IACA;AAAA,IACA,WAAW;AAAA,EACf;AACJ;AAMO,SAAS,uBAChB;AACI,QAAM,QAAQA,QAAO,WAAW;AAEhC,QAAM,EAAE,YAAY,UAAU,IAAIA,QAAO,oBAAoB,OAAO;AAAA,IAChE,eAAe;AAAA,IACf,mBAAmB;AAAA,MACf,MAAM;AAAA,MACN,QAAQ;AAAA,IACZ;AAAA,IACA,oBAAoB;AA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|
|
1
|
+
{"version":3,"sources":["../../src/nextjs/api.ts","../../src/server/lib/crypto.ts","../../src/server/lib/session.ts","../../src/server/logger.ts","../../src/server/lib/config.ts","../../src/nextjs/interceptors/cookie-options.ts","../../src/server/lib/csrf.ts","../../src/nextjs/interceptors/csrf.ts","../../src/nextjs/interceptors/login-register.ts","../../src/nextjs/interceptors/general-auth.ts","../../src/nextjs/interceptors/key-rotation.ts","../../src/server/lib/oauth/state.ts","../../src/nextjs/session-helpers.ts","../../src/nextjs/interceptors/oauth.ts","../../src/nextjs/interceptors/signup-link.ts","../../src/nextjs/interceptors/index.ts"],"sourcesContent":["/**\n * @spfn/auth/adapters/nextjs/api\n *\n * Next.js Adapter for SPFN Auth\n *\n * Provides automatic interceptor registration for seamless auth flow:\n * - Session management (HttpOnly cookies)\n * - JWT generation and signing\n * - Public key encryption\n *\n * @requires next >= 13.0.0\n *\n * @example\n * ```typescript\n * // Just import to auto-register interceptors\n * import '@spfn/auth/nextjs/api';\n * ```\n */\n\n// Re-export interceptors for advanced usage\nimport { registerInterceptors } from '@spfn/core/nextjs/server';\nimport { authInterceptors } from './interceptors';\n\n// Auto-register interceptors on import\nregisterInterceptors('auth', authInterceptors);\n","/**\n * @spfn/auth - Client Crypto Helpers\n *\n * ES256 (ECDSA P-256) key generation and JWT signing for Next.js\n * Keys are stored in DER format (Base64 encoded) for efficiency\n *\n * Key Sizes:\n * - ES256 (ECDSA P-256): ~91 bytes (Base64: ~120 chars)\n * - RS256 (RSA 2048): ~294 bytes (Base64: ~392 chars)\n */\n\nimport { type KeyAlgorithmType } from '../types';\nimport crypto from 'crypto';\nimport jwt, { type Algorithm, type SignOptions } from 'jsonwebtoken';\n\ntype Unit =\n | 'Years'\n | 'Year'\n | 'Yrs'\n | 'Yr'\n | 'Y'\n | 'Weeks'\n | 'Week'\n | 'W'\n | 'Days'\n | 'Day'\n | 'D'\n | 'Hours'\n | 'Hour'\n | 'Hrs'\n | 'Hr'\n | 'H'\n | 'Minutes'\n | 'Minute'\n | 'Mins'\n | 'Min'\n | 'M'\n | 'Seconds'\n | 'Second'\n | 'Secs'\n | 'Sec'\n | 's'\n | 'Milliseconds'\n | 'Millisecond'\n | 'Msecs'\n | 'Msec'\n | 'Ms';\n\ntype UnitAnyCase = Unit | Uppercase<Unit> | Lowercase<Unit>;\n\ntype StringValue =\n | `${number}`\n | `${number}${UnitAnyCase}`\n | `${number} ${UnitAnyCase}`;\n\nexport interface KeyPair\n{\n privateKey: string; // Base64 encoded DER\n publicKey: string; // Base64 encoded DER\n keyId: string; // UUID\n fingerprint: string; // SHA-256 hash\n algorithm: KeyAlgorithmType;\n}\n\n/**\n * Generate ECDSA P-256 key pair (ES256)\n * Recommended for optimal size and performance\n */\nexport function generateKeyPairES256(): KeyPair\n{\n const keyId = crypto.randomUUID();\n\n const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', {\n namedCurve: 'P-256', // ES256\n publicKeyEncoding: {\n type: 'spki',\n format: 'der',\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'der',\n },\n });\n\n // Convert Buffer to Base64\n const privateKeyB64 = privateKey.toString('base64');\n const publicKeyB64 = publicKey.toString('base64');\n\n // Generate fingerprint (SHA-256 of public key)\n const fingerprint = crypto\n .createHash('sha256')\n .update(publicKey)\n .digest('hex');\n\n return {\n privateKey: privateKeyB64,\n publicKey: publicKeyB64,\n keyId,\n fingerprint,\n algorithm: 'ES256',\n };\n}\n\n/**\n * Generate RSA 2048 key pair (RS256)\n * Fallback option, larger size but wider compatibility\n */\nexport function generateKeyPairRS256(): KeyPair\n{\n const keyId = crypto.randomUUID();\n\n const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {\n modulusLength: 2048,\n publicKeyEncoding: {\n type: 'spki',\n format: 'der',\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'der',\n },\n });\n\n const privateKeyB64 = privateKey.toString('base64');\n const publicKeyB64 = publicKey.toString('base64');\n\n const fingerprint = crypto\n .createHash('sha256')\n .update(publicKey)\n .digest('hex');\n\n return {\n privateKey: privateKeyB64,\n publicKey: publicKeyB64,\n keyId,\n fingerprint,\n algorithm: 'RS256',\n };\n}\n\n/**\n * Generate key pair (defaults to ES256)\n */\nexport function generateKeyPair(\n algorithm: KeyAlgorithmType = 'ES256',\n): KeyPair\n{\n return algorithm === 'ES256'\n ? generateKeyPairES256()\n : generateKeyPairRS256();\n}\n\n/**\n * Generate JWT signed with client private key (DER format)\n */\nexport function generateClientToken(\n payload: Record<string, any>,\n privateKeyB64: string,\n algorithm: Algorithm,\n options?: {\n expiresIn?: StringValue | number;\n issuer?: string;\n },\n): string\n{\n try\n {\n // Convert Base64 back to Buffer\n const privateKeyDER = Buffer.from(privateKeyB64, 'base64');\n\n // Create key object for signing\n const privateKeyObject = crypto.createPrivateKey({\n key: privateKeyDER,\n format: 'der',\n type: 'pkcs8',\n });\n\n // Export as PEM for jwt.sign\n const privateKeyPEM = privateKeyObject.export({\n type: 'pkcs8',\n format: 'pem',\n });\n\n const signOptions: SignOptions = {\n algorithm,\n issuer: options?.issuer || 'spfn-client',\n expiresIn: options?.expiresIn ?? '15m', // Default to 15 minutes\n };\n\n return jwt.sign(payload, privateKeyPEM, signOptions);\n }\n catch (error)\n {\n throw new Error(\n `Failed to generate client token: ${error instanceof Error ? error.message : 'Unknown error'}`,\n );\n }\n}\n\n/**\n * Get key size information\n */\nexport function getKeySize(publicKeyB64: string): {\n bytes: number;\n base64Length: number;\n}\n{\n const keyDER = Buffer.from(publicKeyB64, 'base64');\n\n return {\n bytes: keyDER.length,\n base64Length: publicKeyB64.length,\n };\n}\n\n/**\n * Check if key should be rotated based on creation date\n */\nexport function shouldRotateKey(\n createdAt: Date,\n rotationDays: number = 90,\n): {\n shouldRotate: boolean;\n daysRemaining: number;\n}\n{\n const now = new Date();\n const ageInDays = Math.floor(\n (now.getTime() - createdAt.getTime()) / (1000 * 60 * 60 * 24),\n );\n const daysRemaining = Math.max(0, rotationDays - ageInDays);\n\n return {\n shouldRotate: daysRemaining <= 7, // Warn 7 days before expiry\n daysRemaining,\n };\n}\n","/**\n * @spfn/auth - Client Session Management\n *\n * Uses Jose JWE (JSON Web Encryption) to securely store session data in cookies\n * More efficient than Iron Session with better Edge Runtime support\n */\n\nimport * as jose from 'jose';\nimport { env } from '@spfn/auth/config';\nimport { env as coreEnv } from '@spfn/core/config';\nimport { authLogger } from '../logger';\n\nimport { type KeyAlgorithmType } from '../types';\n\nexport interface SessionData\n{\n userId: string;\n privateKey: string; // Base64 encoded DER\n keyId: string;\n algorithm: KeyAlgorithmType;\n}\n\n/**\n * Get session secret key derived from environment\n * Must be at least 32 characters (256-bit)\n *\n * Derives a 32-byte key using SHA-256 to ensure compatibility with Jose A256GCM\n */\nasync function getSessionSecretKey(): Promise<Uint8Array>\n{\n const secret = env.SPFN_AUTH_SESSION_SECRET;\n\n // Derive a 32-byte key using SHA-256 for A256GCM compatibility\n // Use Web Crypto API for universal compatibility (browser + Node.js)\n const encoder = new TextEncoder();\n const data = encoder.encode(secret);\n const hashBuffer = await crypto.subtle.digest('SHA-256', data);\n\n return new Uint8Array(hashBuffer);\n}\n\n/**\n * Get a short fingerprint of the current secret key for debugging\n * Logs only the first 8 hex chars of the SHA-256 hash — safe to expose\n */\nasync function getSecretFingerprint(): Promise<string>\n{\n const key = await getSessionSecretKey();\n const hash = await crypto.subtle.digest('SHA-256', key.buffer as ArrayBuffer);\n const hex = Array.from(new Uint8Array(hash))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n\n return hex.slice(0, 8);\n}\n\n/**\n * Seal session data into encrypted JWT (JWE)\n *\n * @param data - Session data to encrypt\n * @param ttl - Time to live in seconds (default: 7 days)\n * @returns Encrypted JWT string\n */\nexport async function sealSession(\n data: SessionData,\n ttl: number = 60 * 60 * 24 * 7, // 7 days\n): Promise<string>\n{\n const secret = await getSessionSecretKey();\n\n const result = await new jose.EncryptJWT({ data })\n .setProtectedHeader({ alg: 'dir', enc: 'A256GCM' })\n .setIssuedAt()\n .setExpirationTime(`${ttl}s`)\n .setIssuer('spfn-auth')\n .setAudience('spfn-client')\n .encrypt(secret);\n\n if (coreEnv.NODE_ENV !== 'production')\n {\n const fingerprint = await getSecretFingerprint();\n authLogger.session.debug(`Sealed session`, {\n secretFingerprint: fingerprint,\n resultLength: result.length,\n resultPrefix: result.slice(0, 20),\n });\n }\n\n return result;\n}\n\n/**\n * Unseal encrypted JWT (JWE) to session data\n *\n * @param jwt - Encrypted JWT string\n * @returns Session data\n * @throws Error if session is invalid or expired\n */\nexport async function unsealSession(jwt: string): Promise<SessionData>\n{\n try\n {\n const secret = await getSessionSecretKey();\n\n const { payload } = await jose.jwtDecrypt(jwt, secret, {\n issuer: 'spfn-auth',\n audience: 'spfn-client',\n });\n\n return payload.data as SessionData;\n }\n catch (err)\n {\n if (err instanceof jose.errors.JWTExpired)\n {\n throw new Error('Session expired');\n }\n\n if (err instanceof jose.errors.JWEDecryptionFailed)\n {\n // Log secret fingerprint for debugging cross-process key mismatch\n if (coreEnv.NODE_ENV !== 'production')\n {\n const fingerprint = await getSecretFingerprint();\n authLogger.session.warn(`JWE decryption failed`, {\n secretFingerprint: fingerprint,\n jwtLength: jwt.length,\n jwtPrefix: jwt.slice(0, 20),\n jwtSuffix: jwt.slice(-10),\n });\n }\n\n throw new Error('Invalid session');\n }\n\n if (err instanceof jose.errors.JWTClaimValidationFailed)\n {\n throw new Error('Session validation failed');\n }\n\n throw new Error('Failed to unseal session');\n }\n}\n\n/**\n * Get session metadata without decrypting\n *\n * @param jwt - Encrypted JWT string\n * @returns Session metadata or null if invalid\n */\nexport async function getSessionInfo(jwt: string): Promise<{\n issuedAt: Date;\n expiresAt: Date;\n issuer: string;\n audience: string;\n} | null>\n{\n const secret = await getSessionSecretKey();\n\n try\n {\n const { payload } = await jose.jwtDecrypt(jwt, secret);\n\n return {\n issuedAt: new Date(payload.iat! * 1000),\n expiresAt: new Date(payload.exp! * 1000),\n issuer: payload.iss || '',\n audience: Array.isArray(payload.aud) ? payload.aud[0] : payload.aud || '',\n };\n }\n catch (err)\n {\n // Log error for debugging but return null for graceful handling\n if (coreEnv.NODE_ENV !== 'production')\n {\n authLogger.session.warn('Failed to get session info:', err instanceof Error ? err.message : 'Unknown error');\n }\n\n return null;\n }\n}\n\n/**\n * Check if session is about to expire (within threshold)\n *\n * @param jwt - Encrypted JWT string\n * @param thresholdHours - Hours before expiry to trigger refresh (default: 24)\n * @returns True if session should be refreshed\n */\nexport async function shouldRefreshSession(\n jwt: string,\n thresholdHours: number = 24,\n): Promise<boolean>\n{\n const info = await getSessionInfo(jwt);\n\n if (!info)\n {\n return true;\n }\n\n const hoursRemaining = (info.expiresAt.getTime() - Date.now()) / (1000 * 60 * 60);\n\n return hoursRemaining < thresholdHours;\n}\n","/**\n * @spfn/auth - Centralized Logger\n *\n * All auth package loggers with consistent naming\n */\n\nimport { logger as rootLogger } from '@spfn/core/logger';\n\nexport const authLogger = {\n plugin: rootLogger.child('@spfn/auth:plugin'),\n middleware: rootLogger.child('@spfn/auth:middleware'),\n interceptor: {\n general: rootLogger.child('@spfn/auth:interceptor:general'),\n login: rootLogger.child('@spfn/auth:interceptor:login'),\n keyRotation: rootLogger.child('@spfn/auth:interceptor:key-rotation'),\n oauth: rootLogger.child('@spfn/auth:interceptor:oauth'),\n csrf: rootLogger.child('@spfn/auth:interceptor:csrf'),\n },\n session: rootLogger.child('@spfn/auth:session'),\n service: rootLogger.child('@spfn/auth:service'),\n setup: rootLogger.child('@spfn/auth:setup'),\n email: rootLogger.child('@spfn/auth:email'),\n sms: rootLogger.child('@spfn/auth:sms'),\n};\n","/**\n * @spfn/auth - Global Configuration\n *\n * Manages global auth configuration including session TTL\n */\n\nimport { env } from '@spfn/auth/config';\n\nimport type { SocialProvider } from '../types';\nimport { normalizeOptionalEmail } from '../helpers/email';\nimport { authLogger } from '../logger';\n\n/**\n * Cookie name suffix derived from the server port, so several local dev\n * instances on the same domain do not overwrite each other's sessions.\n *\n * BREAKING: this read `PORT`, which no longer exists — the framework's port is\n * `SPFN_PORT`, because `PORT` is Next.js's own variable and two processes are\n * started. An app that had `PORT` set gets different cookie names than before\n * and its existing sessions stop resolving; one sign-in fixes it.\n */\nfunction getCookieSuffix(): string\n{\n const port = process.env.SPFN_PORT;\n\n return port ? `_${port}` : '';\n}\n\n/**\n * Cookie names used by SPFN Auth\n *\n * Names include a port-based suffix so that multiple dev instances\n * on different ports don't overwrite each other's cookies.\n */\nexport const COOKIE_NAMES = {\n /** Encrypted session data (userId, privateKey, keyId, algorithm) */\n get SESSION() \n {\n return `spfn_session${getCookieSuffix()}`; \n },\n /** Current key ID (for key rotation) */\n get SESSION_KEY_ID() \n {\n return `spfn_session_key_id${getCookieSuffix()}`; \n },\n /** Pending OAuth session (privateKey, keyId, algorithm) - temporary during OAuth flow */\n get OAUTH_PENDING()\n {\n return `spfn_oauth_pending${getCookieSuffix()}`;\n },\n /** OAuth CSRF nonce — double-submit against the (encrypted) state.nonce at callback */\n get OAUTH_CSRF()\n {\n return `spfn_oauth_csrf${getCookieSuffix()}`;\n },\n /** Password-setup session for verified-email signup — temporary, single-purpose */\n get SIGNUP_SETUP()\n {\n return `spfn_signup_setup${getCookieSuffix()}`;\n },\n /** CSRF token — the only cookie here the browser can read */\n get CSRF()\n {\n return `spfn_csrf${getCookieSuffix()}`;\n },\n};\n\n/**\n * OAuth CSRF 쿠키를 PORT 접미사와 무관하게 전부 수집한다.\n *\n * 쿠키를 심는 쪽은 Next.js 프로세스, 읽는 쪽은 API 프로세스라 분리 배포에서는\n * 두 프로세스의 PORT가 달라 COOKIE_NAMES.OAUTH_CSRF 정확 일치 조회가 빗나간다.\n * nonce 자체가 랜덤값이고 암호화된 state의 nonce와 대조되므로, 접미사가 다른\n * spfn_oauth_csrf* 후보를 모두 대조 대상으로 넘겨도 안전하다.\n */\nexport function matchOAuthCsrfCookies(\n cookies: Record<string, string>,\n): { name: string; value: string }[]\n{\n return Object.entries(cookies)\n .filter(([name]) => /^spfn_oauth_csrf(_\\d+)?$/.test(name))\n .map(([name, value]) => ({ name, value }));\n}\n\n/**\n * Parse duration string to seconds\n *\n * Supports: '30d', '12h', '45m', '3600s', or plain number\n *\n * @example\n * parseDuration('30d') // 2592000 (30 days in seconds)\n * parseDuration('12h') // 43200\n * parseDuration('45m') // 2700\n * parseDuration('3600') // 3600\n */\nexport function parseDuration(duration: string | number): number\n{\n if (typeof duration === 'number')\n {\n return duration;\n }\n\n const match = duration.match(/^(\\d+)([dhms]?)$/);\n if (!match)\n {\n throw new Error(`Invalid duration format: ${duration}. Use format like '30d', '12h', '45m', '3600s', or plain number.`);\n }\n\n const value = parseInt(match[1], 10);\n const unit = match[2] || 's';\n\n switch (unit)\n {\n case 'd':\n return value * 24 * 60 * 60;\n case 'h':\n return value * 60 * 60;\n case 'm':\n return value * 60;\n case 's':\n return value;\n default:\n throw new Error(`Unknown duration unit: ${unit}`);\n }\n}\n\n/**\n * Registration channel passed to the beforeRegister hook\n *\n * - credentials: email/phone + password registration\n * - oauth: new-user signup through a social provider (web or native flow)\n * - invitation: invitation acceptance\n */\nexport type RegisterChannel = 'credentials' | 'oauth' | 'invitation';\n\n/**\n * Context passed to the beforeRegister hook\n *\n * Credentials (password, keys) are intentionally excluded — the hook is a\n * policy gate, not a credential handler.\n */\nexport interface BeforeRegisterContext\n{\n channel: RegisterChannel;\n /** Social provider — only set when channel is 'oauth' */\n provider?: SocialProvider;\n /**\n * Canonical form of the address — trimmed and lower-cased, the same form\n * the account is stored under. A policy keyed on the address (a denylist, a\n * domain allowlist) therefore matches whatever capitalization the person\n * typed, instead of being walked past by `Blocked@Example.com`.\n */\n email?: string;\n /**\n * Whether the email is verified — only set when channel is 'oauth'.\n * OAuth providers may report an unverified (spoofable) email; the created\n * account stores it as null in that case, so email-based policies must\n * check this flag. credentials/invitation emails are already verified.\n */\n emailVerified?: boolean;\n phone?: string;\n /** App-supplied registration metadata (register params / OAuth start params / invitation) */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * How the Next.js proxy treats a cookie-authenticated mutation that arrives\n * without a valid CSRF header.\n *\n * - `off`: no check\n * - `warn`: allow it through, log one line per request that would be refused\n * - `enforce`: refuse it with 403\n */\nexport type CsrfMode = 'off' | 'warn' | 'enforce';\n\n/**\n * CSRF configuration for the Next.js proxy\n */\nexport interface AuthCsrfConfig\n{\n /**\n * @default 'warn' — an existing app gets signal before it gets breakage.\n * `SPFN_AUTH_CSRF` sets it when this is not; new apps scaffolded by\n * `spfn init` are given `enforce`.\n */\n mode?: CsrfMode;\n\n /**\n * Backend paths that skip the check, matched exactly.\n *\n * These are route paths as the backend sees them (`/webhooks/stripe`), not\n * `/api/rpc/...` URLs, with route params already substituted. Intended for\n * endpoints a browser session never calls — webhook receivers and the like.\n * A path listed here is unprotected for cookie callers too, so list only\n * endpoints that carry their own authentication.\n */\n exemptPaths?: string[];\n}\n\n/**\n * Auth configuration\n */\nexport interface AuthConfig\n{\n /**\n * Default session TTL in seconds or duration string\n *\n * Supports:\n * - Number: seconds (e.g., 2592000)\n * - String: '30d', '12h', '45m', '3600s'\n *\n * @default 7d (7 days)\n */\n sessionTtl?: string | number;\n\n /**\n * App-injected validator that runs before a new user row is created,\n * on every registration channel (credentials, oauth, invitation).\n *\n * Throw to reject the registration — RegistrationRejectedError (403) is\n * the recommended error; any HttpError subclass keeps its own status.\n * Runs after built-in checks (verification token, duplicate account),\n * so existing error precedence is unchanged. Not called for admin\n * seeding (initializeAuth) or when linking a social account to an\n * existing user.\n *\n * Runs inside the registration DB transaction on every channel — keep it\n * fast. A slow call (e.g. an external policy API) holds a pooled DB\n * connection open for its full duration on every signup.\n *\n * @example\n * ```typescript\n * configureAuth({\n * beforeRegister: async ({ channel, metadata }) =>\n * {\n * if (channel === 'credentials' && !isOldEnough(metadata?.birthDate))\n * {\n * throw new RegistrationRejectedError({ message: 'Age requirement not met' });\n * }\n * },\n * });\n * ```\n */\n beforeRegister?: (context: BeforeRegisterContext) => void | Promise<void>;\n\n /**\n * CSRF protection for cookie-session mutations, enforced in the Next.js proxy.\n *\n * @example\n * ```typescript\n * configureAuth({\n * csrf: { mode: 'enforce', exemptPaths: ['/webhooks/stripe'] },\n * });\n * ```\n */\n csrf?: AuthCsrfConfig;\n}\n\n/**\n * Global auth configuration state\n */\nlet globalConfig: AuthConfig = {\n sessionTtl: '7d', // Default: 7 days\n};\n\n/**\n * Configure global auth settings\n *\n * @param config - Auth configuration\n *\n * @example\n * ```typescript\n * configureAuth({\n * sessionTtl: '30d', // 30 days\n * });\n * ```\n */\nexport function configureAuth(config: AuthConfig): void\n{\n globalConfig = {\n ...globalConfig,\n ...config,\n };\n}\n\n/**\n * Get current auth configuration\n */\nexport function getAuthConfig(): AuthConfig\n{\n return { ...globalConfig };\n}\n\n/**\n * Run the app-injected beforeRegister hook if configured — throws to reject.\n *\n * Single entry point for every registration channel so a new channel cannot\n * forget the configured-check. Callers invoke this right before creating the\n * user row.\n *\n * The address is folded here rather than at each call site, for the same reason\n * the check itself lives here: three channels supply it, and a policy that sees\n * a different spelling depending on which one the person came through is a\n * policy that can be walked past.\n */\nexport async function runBeforeRegister(context: BeforeRegisterContext): Promise<void>\n{\n const { beforeRegister } = globalConfig;\n\n if (beforeRegister)\n {\n await beforeRegister({ ...context, email: normalizeOptionalEmail(context.email) });\n }\n}\n\n/**\n * Get session TTL in seconds\n *\n * Priority:\n * 1. Runtime override (remember parameter)\n * 2. Global config (configureAuth)\n * 3. Environment variable (SPFN_AUTH_SESSION_TTL) - via config module\n * 4. Default (7 days)\n */\nexport function getSessionTtl(override?: string | number): number\n{\n // 1. Runtime override\n if (override !== undefined)\n {\n return parseDuration(override);\n }\n\n // 2. Global config\n if (globalConfig.sessionTtl !== undefined)\n {\n return parseDuration(globalConfig.sessionTtl);\n }\n\n // 3. Environment variable (from config module)\n const envTtl = env.SPFN_AUTH_SESSION_TTL;\n if (envTtl)\n {\n return parseDuration(envTtl);\n }\n\n // 4. Default: 7 days\n return 7 * 24 * 60 * 60;\n}\n\nconst CSRF_MODES: CsrfMode[] = ['off', 'warn', 'enforce'];\n\n/** The typo notice is a property of the process, not of a request */\nlet unrecognizedCsrfModeReported = false;\n\n/**\n * Get the CSRF mode\n *\n * Priority:\n * 1. Global config (configureAuth)\n * 2. Environment variable (SPFN_AUTH_CSRF)\n * 3. Default ('warn')\n *\n * An unrecognized value is a typo in the one setting that turns the check on;\n * it resolves to `enforce` and says so, rather than quietly leaving mutations\n * unprotected. It says so once per process: this runs on every mutation, so a\n * per-call error would be pure repetition burying the rest of the log.\n */\nexport function getCsrfMode(): CsrfMode\n{\n const configured = globalConfig.csrf?.mode ?? env.SPFN_AUTH_CSRF;\n\n if (!configured)\n {\n return 'warn';\n }\n\n const normalized = String(configured).trim().toLowerCase() as CsrfMode;\n\n if (!CSRF_MODES.includes(normalized))\n {\n if (!unrecognizedCsrfModeReported)\n {\n unrecognizedCsrfModeReported = true;\n authLogger.interceptor.csrf.error(\n `Unrecognized CSRF mode \"${configured}\" — expected off | warn | enforce. Enforcing.`,\n );\n }\n\n return 'enforce';\n }\n\n return normalized;\n}\n\n/**\n * Get the paths exempted from the CSRF check (exact match, backend route paths)\n */\nexport function getCsrfExemptPaths(): string[]\n{\n return globalConfig.csrf?.exemptPaths ?? [];\n}\n","/**\n * Shared cookie option helpers for auth interceptors\n *\n * SPFN_AUTH_COOKIE_SECURE env var allows overriding the Secure flag.\n * - unset: defaults to NODE_ENV === 'production'\n * - \"true\" / \"false\": explicit override\n *\n * Useful for HTTP-only staging environments (e.g. bastion over plain HTTP).\n */\n\n/**\n * Resolve whether cookies should have the Secure flag.\n *\n * Priority:\n * 1. SPFN_AUTH_COOKIE_SECURE (explicit override)\n * 2. NODE_ENV === 'production'\n */\nfunction resolveSecure(): boolean\n{\n const override = process.env.SPFN_AUTH_COOKIE_SECURE;\n\n if (override !== undefined)\n {\n return override === 'true';\n }\n\n return process.env.NODE_ENV === 'production';\n}\n\n/**\n * Whether cookies should have the Secure flag.\n * Evaluated once at module load time.\n */\nexport const cookieSecure = resolveSecure();\n","/**\n * @spfn/auth - CSRF token derivation\n *\n * The token is an HMAC of the session's key id under a subkey derived from the\n * session secret. Two properties follow from that shape:\n *\n * - The proxy recomputes it from the session it just unsealed, so a value an\n * attacker planted in the readable cookie (sibling-subdomain cookie tossing)\n * never verifies. Nothing here compares a cookie against a header.\n * - It is bound to the key id, so rotating the session key invalidates it.\n *\n * No new secret: the subkey is a labelled HMAC of SPFN_AUTH_SESSION_SECRET, so\n * the key that encrypts sessions is never used verbatim as the token key.\n */\n\nimport { env } from '@spfn/auth/config';\n\n/** Header the readable CSRF cookie is mirrored into by the client. */\nexport const CSRF_HEADER = 'x-spfn-csrf';\n\n/** Domain-separation label for the CSRF subkey. */\nconst CSRF_SUBKEY_LABEL = 'spfn-auth-csrf-token-v1';\n\n/**\n * Upper bound on candidate values accepted in one header.\n *\n * Deliberately generous, and must stay in step with MAX_CANDIDATES in\n * @spfn/core's client: verification recomputes the expected value once and then\n * only compares fixed-length strings, so an extra candidate costs a few hundred\n * nanoseconds, while a candidate dropped below this line is a user locked out of\n * every mutation. A low cap is not a security control either — accepting a match\n * among many is no weaker than accepting one, because every candidate still has\n * to equal a value recomputed from the session.\n */\nconst MAX_CANDIDATES = 32;\n\n/**\n * Resolve the session secret, refusing to derive anything without one.\n *\n * `env` throws on a missing required variable, but returns undefined when\n * SKIP_ENV_VALIDATION is set — and hashing `undefined` would yield a token every\n * deployment could compute. Fail closed instead.\n */\nfunction sessionSecret(): string\n{\n const secret = env.SPFN_AUTH_SESSION_SECRET;\n\n if (!secret)\n {\n throw new Error(\n 'SPFN_AUTH_SESSION_SECRET is required for CSRF protection. '\n + 'Set it (sessions need it anyway), or set SPFN_AUTH_CSRF=off.',\n );\n }\n\n return secret;\n}\n\n/**\n * HMAC-SHA256 over Web Crypto, so this works in the Edge runtime too.\n */\nasync function hmacSha256(key: Uint8Array, message: string): Promise<Uint8Array>\n{\n const cryptoKey = await crypto.subtle.importKey(\n 'raw',\n key.buffer as ArrayBuffer,\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n );\n\n const signature = await crypto.subtle.sign('HMAC', cryptoKey, new TextEncoder().encode(message));\n\n return new Uint8Array(signature);\n}\n\nfunction toHex(bytes: Uint8Array): string\n{\n return Array.from(bytes).map((b) => b.toString(16).padStart(2, '0')).join('');\n}\n\n/**\n * Derive the CSRF token for a session key id.\n *\n * @param keyId - Session key id (`SessionData.keyId`)\n * @returns 64-char hex token — safe to put in a readable cookie, it reveals\n * neither the secret nor the key id\n */\nexport async function deriveCsrfToken(keyId: string): Promise<string>\n{\n const subkey = await hmacSha256(new TextEncoder().encode(sessionSecret()), CSRF_SUBKEY_LABEL);\n\n return toHex(await hmacSha256(subkey, keyId));\n}\n\n/**\n * Constant-time string comparison.\n *\n * Named for the string it takes, so it does not collide with node's Buffer-based\n * `timingSafeEqual` — which this package also uses, in the OAuth providers. It is\n * not re-exported from the package barrel for the same reason.\n *\n * Length is compared first and leaks only the length, which is fixed and public.\n */\nexport function timingSafeEqualString(a: string, b: string): boolean\n{\n if (a.length !== b.length)\n {\n return false;\n }\n\n let difference = 0;\n\n for (let i = 0; i < a.length; i++)\n {\n difference |= a.charCodeAt(i) ^ b.charCodeAt(i);\n }\n\n return difference === 0;\n}\n\n/**\n * Whether a presented header value carries the expected token.\n *\n * The header may carry several comma-separated candidates — a browser sees every\n * `spfn_csrf*` cookie set on the host and cannot tell which dev instance owns\n * which, nor which of two same-named cookies a sibling subdomain tossed in.\n *\n * Every candidate the client is allowed to send is checked — the cap here is the\n * one it selects against — so a genuine value is never evicted by tossed ones\n * that happen to sort ahead of it. A header longer than that can only come from a\n * client that ignored the shared bound, and its surplus is dropped. Accepting any\n * match is no weaker than accepting one: a candidate the attacker chose still has\n * to equal a value recomputed from the session.\n */\nexport function matchesCsrfToken(expected: string, presented: string | null | undefined): boolean\n{\n if (!presented)\n {\n return false;\n }\n\n return presented\n .split(',', MAX_CANDIDATES)\n .some((candidate) => timingSafeEqualString(expected, candidate.trim()));\n}\n","/**\n * CSRF check for cookie-authenticated mutations\n *\n * Enforced here, in the Next.js proxy, because this is the only layer that knows\n * a request's credential was ambient: the browser sends an encrypted HttpOnly\n * session cookie, generalAuthInterceptor turns it into a short-lived bearer JWT,\n * and the backend then sees `scheme:'bearer'` for cookie callers and genuine\n * bearer callers alike. Requests the proxy does not authenticate from the session\n * cookie — no session, direct-to-backend bearer, clientProofV1, machine and ops\n * tokens — never reach this code and are unaffected.\n *\n * The threat model is in the README: the session cookie is SameSite=Lax, so this\n * covers what Lax does not (sibling-subdomain pivots, legacy browsers, domain\n * layout drift) and covers nothing an XSS on your own origin could not do anyway.\n */\n\nimport type { ProxyAbort, RequestInterceptorContext } from '@spfn/core/nextjs/server';\nimport type { SetCookie } from '@spfn/core/nextjs';\n\nimport { getCsrfMode, getCsrfExemptPaths, getSessionTtl, COOKIE_NAMES } from '../../server/lib/config';\nimport { CSRF_HEADER, deriveCsrfToken, matchesCsrfToken, timingSafeEqualString } from '../../server/lib/csrf';\nimport { authLogger } from '../../server/logger';\nimport { cookieSecure } from './cookie-options';\n\n/**\n * Methods that cannot mutate, so they need no token.\n *\n * Compared against the resolved *route* method, not the method the browser used\n * to reach the proxy: `GET /api/rpc/deleteAccount?input=…` is forwarded to the\n * backend as the route's DELETE, and SameSite=Lax does send the session cookie on\n * a cross-site top-level GET navigation. Gating on the wire method would leave\n * every mutation reachable that way.\n */\nconst SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);\n\n/**\n * The readable CSRF cookie, as every place that issues one builds it.\n *\n * Mirrors the session cookie's attributes minus HttpOnly — the client has to read\n * it — and carries only the HMAC, never the key id it derives from.\n */\nfunction csrfCookie(token: string, ttl: number): SetCookie\n{\n return {\n name: COOKIE_NAMES.CSRF,\n value: token,\n options: {\n httpOnly: false,\n secure: cookieSecure,\n sameSite: 'lax',\n maxAge: ttl,\n path: '/',\n },\n };\n}\n\n/**\n * The 403 a failed check answers with.\n *\n * The body is the same whatever the reason: a caller learns that the request was\n * refused, never whether the header was absent, wrong, or impossible to check.\n *\n * It carries no cookie. The caller attaches one afterwards where there is a value\n * to attach — see refuseInvalidCsrf for why that order matters.\n */\nfunction refusal(): ProxyAbort\n{\n return {\n status: 403,\n body: {\n error: 'Forbidden',\n message: 'CSRF token missing or invalid',\n },\n setCookies: [],\n };\n}\n\n/**\n * Refuse a cookie-authenticated mutation that has no valid CSRF header.\n *\n * Call only once the session has been unsealed — a refusal must never be the\n * answer to a request that had no session, or the status alone would tell an\n * unauthenticated caller whether someone is signed in. Unauthenticated requests\n * keep taking the existing path (the backend answers 401).\n *\n * The refusal carries a fresh CSRF cookie. A refused request skips the backend\n * and every response interceptor, so this is the only chance to repair a browser\n * whose token cookie went missing or stale — without it the client would be told\n * \"wrong token\" while holding nothing better to try, and the documented recovery\n * would need an unrelated GET to happen first.\n *\n * @param ctx - Request interceptor context, mutated with `abort` on refusal\n * @param keyId - Key id of the session that authenticated this request\n * @returns True when the request was refused and the caller must stop\n */\nexport async function refuseInvalidCsrf(\n ctx: RequestInterceptorContext,\n keyId: string,\n): Promise<boolean>\n{\n const mode = getCsrfMode();\n\n if (mode === 'off' || SAFE_METHODS.has(ctx.method.toUpperCase()))\n {\n return false;\n }\n\n if (getCsrfExemptPaths().includes(ctx.path))\n {\n authLogger.interceptor.csrf.debug('Path is CSRF-exempt', { path: ctx.path });\n\n return false;\n }\n\n let expected: string;\n\n try\n {\n expected = await deriveCsrfToken(keyId);\n }\n catch (error)\n {\n // Fail closed, in every mode including the default `warn`. A deployment\n // that cannot derive the token is misconfigured, not unprotected, and\n // letting warn wave these through would leave a broken install silently\n // open while its logs looked like a healthy one's. No cookie either —\n // there is no value to issue.\n authLogger.interceptor.csrf.error(\n 'Cannot derive the CSRF token — refusing regardless of mode',\n error as Error,\n );\n\n ctx.abort = refusal();\n\n return true;\n }\n\n // Read the header off the ORIGINAL browser request. ctx.headers is the set\n // buildProxyHeaders() forwards to the backend, and that is a fixed allowlist\n // — the CSRF header is not on it, deliberately: it is proxy-terminated and\n // has no meaning past this point. Reading ctx.headers here would refuse\n // every request instead.\n const presented = ctx.request.headers.get(CSRF_HEADER);\n\n if (matchesCsrfToken(expected, presented))\n {\n return false;\n }\n\n // One line per request that fails the check, in either mode. Never the\n // expected token or the key id — the log would otherwise hand out what the\n // check exists to withhold.\n const detail = {\n method: ctx.method,\n path: ctx.path,\n headerPresent: !!presented,\n };\n\n if (mode === 'warn')\n {\n authLogger.interceptor.csrf.warn('CSRF check would refuse this request (mode=warn)', detail);\n\n return false;\n }\n\n authLogger.interceptor.csrf.warn('CSRF check refused this request', detail);\n\n ctx.abort = refusal();\n\n // The repair is attached after the refusal is already in place. Building the\n // cookie needs the session TTL, which parses configuration and throws on a\n // malformed value — and a throw on the way out of here is swallowed upstream,\n // which would hand the caller the backend's 401 instead of this 403. Refusing\n // without the repair costs one user one extra page load; refusing with the\n // wrong status changes what the check means.\n ctx.abort.setCookies = [csrfCookie(expected, getSessionTtl())];\n\n return true;\n}\n\n/**\n * Queue the readable CSRF cookie for a session.\n *\n * Set wherever a session is established or renewed.\n *\n * Queued in every mode, including `off`, so that turning enforcement on later\n * does not require everyone to sign in again.\n */\nexport async function pushCsrfCookie(\n setCookies: SetCookie[],\n keyId: string,\n ttl: number,\n): Promise<void>\n{\n setCookies.push(csrfCookie(await deriveCsrfToken(keyId), ttl));\n}\n\n/**\n * Queue the readable CSRF cookie when the request's copy is missing or stale.\n *\n * The other half of the recovery path: a session that predates this feature\n * carries no cookie, and one whose value stopped matching — a key rotated down a\n * path that did not reissue, a jar half-cleared by an extension — would\n * otherwise sit broken until the session came within a day of expiry. A cookie\n * that is present but no longer matches is reissued; presence alone is not\n * proof. Any authenticated response repairs it, which is what makes one page\n * load enough.\n *\n * A derivation failure is logged rather than thrown: the request-side check\n * already refuses those, and turning every authenticated response into a 500 on\n * top of that helps nobody diagnose it.\n */\nexport async function pushCsrfCookieIfStale(\n setCookies: SetCookie[],\n presented: string | undefined,\n keyId: string,\n): Promise<void>\n{\n try\n {\n const token = await deriveCsrfToken(keyId);\n\n if (presented && timingSafeEqualString(token, presented))\n {\n return;\n }\n\n setCookies.push(csrfCookie(token, getSessionTtl()));\n }\n catch (error)\n {\n authLogger.interceptor.csrf.error('Cannot reissue the CSRF cookie', error as Error);\n }\n}\n\n/**\n * Queue removal of the readable CSRF cookie (logout, expired session).\n */\nexport function pushCsrfCookieRemoval(setCookies: SetCookie[]): void\n{\n setCookies.push({\n name: COOKIE_NAMES.CSRF,\n value: '',\n options: { maxAge: 0, path: '/' },\n });\n}\n","/**\n * Login/Register Interceptor\n *\n * Automatically handles key generation and session management\n * for login, register, and invitation-accept endpoints.\n * (Invitation acceptance creates the user account + key pair and\n * logs the new user in, so it follows the same key/session flow.)\n */\n\nimport type { InterceptorRule } from '@spfn/core/nextjs/server';\nimport { generateKeyPair } from '../../server/lib/crypto';\nimport { sealSession } from '../../server/lib/session';\nimport { getSessionTtl, COOKIE_NAMES } from '../../server/lib/config';\nimport { authLogger } from '../../server/logger';\nimport { cookieSecure } from './cookie-options';\nimport { pushCsrfCookie } from './csrf';\n\n/**\n * Login, Register, and Invitation-Accept Interceptor\n *\n * Request: Generates key pair and adds publicKey to request body\n * Response: Saves privateKey to HttpOnly cookie\n */\nexport const loginRegisterInterceptor: InterceptorRule =\n {\n pathPattern: /^\\/_auth\\/(login|register|invitations\\/accept|signup\\/password)$/,\n method: 'POST',\n\n request: async (ctx, next) =>\n {\n // Get old session if exists (for key rotation on login)\n const oldKeyId = ctx.cookies.get(COOKIE_NAMES.SESSION_KEY_ID);\n\n // Extract remember option from request body (if provided)\n const remember = ctx.body?.remember;\n\n // Generate new key pair\n const keyPair = generateKeyPair('ES256');\n\n // Add publicKey data to request body\n if (!ctx.body)\n {\n ctx.body = {};\n }\n\n ctx.body.publicKey = keyPair.publicKey;\n ctx.body.keyId = keyPair.keyId;\n ctx.body.fingerprint = keyPair.fingerprint;\n ctx.body.algorithm = keyPair.algorithm;\n ctx.body.keySize = Buffer.from(keyPair.publicKey, 'base64').length;\n\n // Add oldKeyId for login (key rotation)\n if (ctx.path === '/_auth/login' && oldKeyId)\n {\n ctx.body.oldKeyId = oldKeyId;\n }\n\n // Remove remember from body (not part of contract)\n delete ctx.body.remember;\n\n // Store privateKey and remember in metadata for response interceptor\n ctx.metadata.privateKey = keyPair.privateKey;\n ctx.metadata.keyId = keyPair.keyId;\n ctx.metadata.algorithm = keyPair.algorithm;\n ctx.metadata.remember = remember;\n\n await next();\n },\n\n response: async (ctx, next) =>\n {\n // Only process successful responses\n if (ctx.response.status !== 200)\n {\n await next();\n\n return;\n }\n\n // Handle both wrapped ({ data: { userId } }) and direct ({ userId }) responses\n const userData = ctx.response.body?.data || ctx.response.body;\n if (!userData?.userId)\n {\n authLogger.interceptor.login.error('No userId in response');\n await next();\n\n return;\n }\n\n try\n {\n // Get session TTL (priority: runtime > global > env > default)\n const ttl = getSessionTtl(ctx.metadata.remember);\n\n // Encrypt session data\n const sessionData =\n {\n userId: userData.userId,\n privateKey: ctx.metadata.privateKey,\n keyId: ctx.metadata.keyId,\n algorithm: ctx.metadata.algorithm,\n };\n\n const sealed = await sealSession(sessionData, ttl);\n\n // Set HttpOnly session cookie\n ctx.setCookies.push({\n name: COOKIE_NAMES.SESSION,\n value: sealed,\n options: {\n httpOnly: true,\n secure: cookieSecure,\n sameSite: 'lax',\n maxAge: ttl,\n path: '/',\n },\n });\n\n // Set keyId cookie (for oldKeyId lookup)\n ctx.setCookies.push({\n name: COOKIE_NAMES.SESSION_KEY_ID,\n value: ctx.metadata.keyId,\n options: {\n httpOnly: true,\n secure: cookieSecure,\n sameSite: 'lax',\n maxAge: ttl,\n path: '/',\n },\n });\n\n // Set the readable CSRF cookie the client mirrors into a header\n await pushCsrfCookie(ctx.setCookies, ctx.metadata.keyId, ttl);\n }\n catch (error)\n {\n const err = error as Error;\n authLogger.interceptor.login.error('Failed to save session', err);\n }\n\n await next();\n },\n };\n","/**\n * General Authentication Interceptor\n *\n * Handles authentication for all API requests except login/register\n * - Session validation and renewal\n * - JWT generation and signing\n * - Expired session cleanup\n */\n\nimport type { InterceptorRule } from '@spfn/core/nextjs/server';\nimport { unsealSession, sealSession, shouldRefreshSession } from '../../server/lib/session';\nimport { generateClientToken } from '../../server/lib/crypto';\nimport { getSessionTtl, COOKIE_NAMES } from '../../server/lib/config';\nimport { authLogger } from '../../server/logger';\nimport { cookieSecure } from './cookie-options';\nimport { refuseInvalidCsrf, pushCsrfCookie, pushCsrfCookieIfStale, pushCsrfCookieRemoval } from './csrf';\n\n/**\n * Check if path requires authentication\n */\nfunction requiresAuth(path: string): boolean\n{\n // Paths that don't require auth\n const publicPaths = [\n /^\\/_auth\\/login$/,\n /^\\/_auth\\/register$/,\n /^\\/_auth\\/codes$/, // Send verification code\n /^\\/_auth\\/codes\\/verify$/, // Verify code\n /^\\/_auth\\/exists$/, // Check account exists\n ];\n\n return !publicPaths.some((pattern) => pattern.test(path));\n}\n\n/**\n * General Authentication Interceptor\n *\n * Applies to all paths except login/register/codes\n * - Validates session\n * - Generates JWT token\n * - Refreshes session if needed\n * - Clears expired sessions\n */\nexport const generalAuthInterceptor: InterceptorRule =\n {\n pathPattern: '*', // Match all paths, filter by requiresAuth()\n method: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],\n\n request: async (ctx, next) =>\n {\n // Skip if path doesn't require auth\n if (!requiresAuth(ctx.path))\n {\n authLogger.interceptor.general.debug(`Public path, skipping auth: ${ctx.path}`);\n await next();\n\n return;\n }\n\n // Log available cookies\n const cookieNames = Array.from(ctx.cookies.keys());\n authLogger.interceptor.general.debug('Available cookies:', {\n cookieNames,\n totalCount: cookieNames.length,\n lookingFor: COOKIE_NAMES.SESSION,\n });\n\n const sessionCookie = ctx.cookies.get(COOKIE_NAMES.SESSION);\n\n authLogger.interceptor.general.debug('Request', {\n method: ctx.method,\n path: ctx.path,\n hasSession: !!sessionCookie,\n sessionLength: sessionCookie?.length ?? 0,\n sessionPrefix: sessionCookie?.slice(0, 20) ?? '',\n sessionSuffix: sessionCookie?.slice(-10) ?? '',\n });\n\n // No session cookie\n if (!sessionCookie)\n {\n authLogger.interceptor.general.debug('No session cookie, proceeding without auth');\n // Let request proceed - server will return 401\n await next();\n\n return;\n }\n\n try\n {\n // Decrypt and validate session\n const session = await unsealSession(sessionCookie);\n\n authLogger.interceptor.general.debug('Session valid', {\n userId: session.userId,\n keyId: session.keyId,\n });\n\n // The request is authenticated from the session cookie — the one\n // fact only this layer knows, and the whole reason the CSRF check\n // lives here. Refusals stop before the backend is called.\n if (await refuseInvalidCsrf(ctx, session.keyId))\n {\n return;\n }\n\n // Check if session should be refreshed (within 24h of expiry)\n const needsRefresh = await shouldRefreshSession(sessionCookie, 24);\n\n if (needsRefresh)\n {\n authLogger.interceptor.general.debug('Session needs refresh (within 24h of expiry)');\n // Mark for session renewal in response interceptor\n ctx.metadata.refreshSession = true;\n ctx.metadata.sessionData = session;\n }\n\n // Generate JWT token\n const token = generateClientToken(\n {\n userId: session.userId,\n keyId: session.keyId,\n timestamp: Date.now(),\n },\n session.privateKey,\n session.algorithm,\n { expiresIn: '15m' },\n );\n\n authLogger.interceptor.general.debug('Generated JWT token (expires in 15m)');\n\n // Add authentication headers\n ctx.headers['Authorization'] = `Bearer ${token}`;\n ctx.headers['X-Key-Id'] = session.keyId;\n\n // Store session info in metadata\n ctx.metadata.userId = session.userId;\n ctx.metadata.keyId = session.keyId;\n ctx.metadata.sessionValid = true;\n }\n catch (error)\n {\n const err = error as Error;\n const msg = err.message.toLowerCase();\n\n // Session expired or invalid\n if (msg.includes('expired') || msg.includes('invalid'))\n {\n authLogger.interceptor.general.warn('Session expired or invalid', {\n message: err.message,\n cookieLength: sessionCookie.length,\n cookiePrefix: sessionCookie.slice(0, 20),\n cookieSuffix: sessionCookie.slice(-10),\n });\n authLogger.interceptor.general.debug('Marking session for cleanup');\n\n // Mark for cleanup in response interceptor\n ctx.metadata.clearSession = true;\n ctx.metadata.sessionValid = false;\n }\n else\n {\n authLogger.interceptor.general.error('Failed to process session', err);\n }\n }\n\n await next();\n },\n\n response: async (ctx, next) =>\n {\n // Backend returned 401 with a valid session — server rejected it\n if (ctx.response.status === 401 && ctx.metadata.sessionValid)\n {\n authLogger.interceptor.general.warn('Backend returned 401, clearing session');\n\n ctx.setCookies.push({\n name: COOKIE_NAMES.SESSION,\n value: '',\n options: { maxAge: 0, path: '/' },\n });\n\n ctx.setCookies.push({\n name: COOKIE_NAMES.SESSION_KEY_ID,\n value: '',\n options: { maxAge: 0, path: '/' },\n });\n\n pushCsrfCookieRemoval(ctx.setCookies);\n\n await next();\n\n return;\n }\n\n // Clear expired/invalid session\n if (ctx.metadata.clearSession)\n {\n ctx.setCookies.push({\n name: COOKIE_NAMES.SESSION,\n value: '',\n options: {\n maxAge: 0,\n path: '/',\n },\n });\n\n ctx.setCookies.push({\n name: COOKIE_NAMES.SESSION_KEY_ID,\n value: '',\n options: {\n maxAge: 0,\n path: '/',\n },\n });\n\n pushCsrfCookieRemoval(ctx.setCookies);\n }\n // Refresh session if needed and request was successful\n else if (ctx.metadata.refreshSession && ctx.response.status === 200)\n {\n try\n {\n const sessionData = ctx.metadata.sessionData;\n const ttl = getSessionTtl();\n\n // Re-encrypt session with new TTL\n const sealed = await sealSession(sessionData, ttl);\n\n // Update session cookie\n ctx.setCookies.push({\n name: COOKIE_NAMES.SESSION,\n value: sealed,\n options: {\n httpOnly: true,\n secure: cookieSecure,\n sameSite: 'lax',\n maxAge: ttl,\n path: '/',\n },\n });\n\n // Update keyId cookie\n ctx.setCookies.push({\n name: COOKIE_NAMES.SESSION_KEY_ID,\n value: sessionData.keyId,\n options: {\n httpOnly: true,\n secure: cookieSecure,\n sameSite: 'lax',\n maxAge: ttl,\n path: '/',\n },\n });\n\n // Renewed session, renewed CSRF cookie — same lifetime, so the\n // readable value never outlives the session it belongs to.\n await pushCsrfCookie(ctx.setCookies, sessionData.keyId, ttl);\n\n authLogger.interceptor.general.info('Session refreshed', {\n userId: sessionData.userId,\n sealedLength: sealed.length,\n sealedPrefix: sealed.slice(0, 20),\n });\n }\n catch (error)\n {\n const err = error as Error;\n authLogger.interceptor.general.error('Failed to refresh session', err);\n }\n }\n // Handle logout (clear session)\n else if (ctx.path === '/_auth/logout' && ctx.response.ok)\n {\n const base = {\n httpOnly: true,\n secure: cookieSecure,\n maxAge: 0,\n path: '/',\n };\n\n ctx.setCookies.push({\n name: COOKIE_NAMES.SESSION,\n value: '',\n options: { ...base, sameSite: 'lax' },\n });\n\n ctx.setCookies.push({\n name: COOKIE_NAMES.SESSION_KEY_ID,\n value: '',\n options: { ...base, sameSite: 'lax' },\n });\n\n ctx.setCookies.push({\n name: COOKIE_NAMES.OAUTH_PENDING,\n value: '',\n options: { ...base, sameSite: 'lax' },\n });\n\n pushCsrfCookieRemoval(ctx.setCookies);\n }\n\n // A session that predates CSRF protection carries no readable cookie,\n // and renewal only happens near expiry — an app switching to enforce\n // would otherwise refuse every mutation from everyone already signed\n // in, for days. Issue it on any authenticated response whose cookie is\n // missing or no longer matches; reads pass the check, so a page load\n // is enough to heal.\n const csrfQueued = ctx.setCookies.some(cookie => cookie.name === COOKIE_NAMES.CSRF);\n\n if (ctx.metadata.sessionValid && !csrfQueued)\n {\n await pushCsrfCookieIfStale(\n ctx.setCookies,\n ctx.cookies.get(COOKIE_NAMES.CSRF),\n ctx.metadata.keyId,\n );\n }\n\n await next();\n },\n };\n","/**\n * Key Rotation Interceptor\n *\n * Handles key rotation with new key generation and session update\n */\n\nimport type { InterceptorRule } from '@spfn/core/nextjs/server';\nimport { generateKeyPair, generateClientToken } from '../../server/lib/crypto';\nimport { unsealSession, sealSession } from '../../server/lib/session';\nimport { getSessionTtl, COOKIE_NAMES } from '../../server/lib/config';\nimport { authLogger } from '../../server/logger';\nimport { cookieSecure } from './cookie-options';\nimport { pushCsrfCookie } from './csrf';\n\n/**\n * Key Rotation Interceptor\n *\n * Request: Generates new key pair and adds to body, authenticates with current key\n * Response: Updates session with new privateKey\n */\nexport const keyRotationInterceptor: InterceptorRule =\n {\n pathPattern: '/_auth/keys/rotate',\n method: 'POST',\n\n request: async (ctx, next) =>\n {\n const sessionCookie = ctx.cookies.get(COOKIE_NAMES.SESSION);\n\n if (!sessionCookie)\n {\n await next();\n\n return;\n }\n\n try\n {\n // Get current session\n const currentSession = await unsealSession(sessionCookie);\n\n // Generate new key pair\n const newKeyPair = generateKeyPair('ES256');\n\n // Add new publicKey to request body\n if (!ctx.body)\n {\n ctx.body = {};\n }\n\n ctx.body.publicKey = newKeyPair.publicKey;\n ctx.body.keyId = newKeyPair.keyId;\n ctx.body.fingerprint = newKeyPair.fingerprint;\n ctx.body.algorithm = newKeyPair.algorithm;\n ctx.body.keySize = Buffer.from(newKeyPair.publicKey, 'base64').length;\n\n // Identity of the new key only — the pair carries `privateKey`,\n // the credential the session is sealed around.\n authLogger.interceptor.keyRotation.debug('Generated a new key pair', {\n keyId: newKeyPair.keyId,\n fingerprint: newKeyPair.fingerprint,\n algorithm: newKeyPair.algorithm,\n });\n\n // Authenticate with CURRENT key\n const token = generateClientToken(\n {\n userId: currentSession.userId,\n keyId: currentSession.keyId,\n action: 'rotate_key',\n timestamp: Date.now(),\n },\n currentSession.privateKey,\n currentSession.algorithm,\n {expiresIn: '15m'},\n );\n\n ctx.headers['Authorization'] = `Bearer ${token}`;\n ctx.headers['X-Key-Id'] = currentSession.keyId;\n\n // Store new key and userId in metadata\n ctx.metadata.newPrivateKey = newKeyPair.privateKey;\n ctx.metadata.newKeyId = newKeyPair.keyId;\n ctx.metadata.newAlgorithm = newKeyPair.algorithm;\n ctx.metadata.userId = currentSession.userId;\n }\n catch (error)\n {\n const err = error as Error;\n authLogger.interceptor.keyRotation.error('Failed to prepare key rotation', err);\n }\n\n await next();\n },\n\n response: async (ctx, next) =>\n {\n // Only update session on successful rotation\n if (ctx.response.status !== 200)\n {\n await next();\n\n return;\n }\n\n if (!ctx.metadata.newPrivateKey || !ctx.metadata.userId)\n {\n authLogger.interceptor.keyRotation.error('Missing key rotation metadata');\n await next();\n\n return;\n }\n\n try\n {\n // Get session TTL\n const ttl = getSessionTtl();\n\n // Create new session with rotated key\n const newSessionData =\n {\n userId: ctx.metadata.userId,\n privateKey: ctx.metadata.newPrivateKey,\n keyId: ctx.metadata.newKeyId,\n algorithm: ctx.metadata.newAlgorithm,\n };\n\n const sealed = await sealSession(newSessionData, ttl);\n\n // Update session cookie\n ctx.setCookies.push({\n name: COOKIE_NAMES.SESSION,\n value: sealed,\n options: {\n httpOnly: true,\n secure: cookieSecure,\n sameSite: 'lax',\n maxAge: ttl,\n path: '/',\n },\n });\n\n // Update keyId cookie\n ctx.setCookies.push({\n name: COOKIE_NAMES.SESSION_KEY_ID,\n value: ctx.metadata.newKeyId,\n options: {\n httpOnly: true,\n secure: cookieSecure,\n sameSite: 'lax',\n maxAge: ttl,\n path: '/',\n },\n });\n\n // Rotation changes the key id the token is derived from, so the\n // old CSRF value stops verifying — reissue it in the same response.\n await pushCsrfCookie(ctx.setCookies, ctx.metadata.newKeyId, ttl);\n }\n catch (error)\n {\n const err = error as Error;\n authLogger.interceptor.keyRotation.error('Failed to update session after rotation', err);\n }\n\n await next();\n },\n };\n","/**\n * OAuth State Management\n *\n * CSRF 방지를 위한 state 파라미터 암호화/복호화\n * - returnUrl: OAuth 성공 후 리다이렉트할 URL\n * - nonce: CSRF 방지용 일회용 토큰\n * - provider: OAuth provider (google, github 등)\n * - publicKey, keyId, fingerprint, algorithm: 클라이언트 키 정보\n * - expiresAt: state 만료 시간\n */\n\nimport * as jose from 'jose';\nimport { env } from '@spfn/auth/config';\nimport { type KeyAlgorithmType } from '../../types';\n\nexport interface OAuthState\n{\n returnUrl: string;\n nonce: string;\n provider: string;\n publicKey: string;\n keyId: string;\n fingerprint: string;\n algorithm: KeyAlgorithmType;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Get encryption key derived from session secret\n */\nasync function getStateKey(): Promise<Uint8Array>\n{\n const secret = env.SPFN_AUTH_SESSION_SECRET;\n const encoder = new TextEncoder();\n const data = encoder.encode(`oauth-state:${secret}`);\n const hashBuffer = await crypto.subtle.digest('SHA-256', data);\n\n return new Uint8Array(hashBuffer);\n}\n\n/**\n * Generate random nonce\n */\nfunction generateNonce(): string\n{\n const array = new Uint8Array(16);\n crypto.getRandomValues(array);\n\n return Array.from(array, b => b.toString(16).padStart(2, '0')).join('');\n}\n\n/**\n * Generate a CSRF nonce for the OAuth flow. The caller passes it to\n * createOAuthState AND sets it as the oauth_csrf cookie, so the callback can\n * double-submit-verify the flow was initiated by this same browser.\n */\nexport function generateOAuthNonce(): string\n{\n return generateNonce();\n}\n\nexport interface CreateOAuthStateParams\n{\n provider: string;\n returnUrl: string;\n publicKey: string;\n keyId: string;\n fingerprint: string;\n algorithm: KeyAlgorithmType;\n metadata?: Record<string, unknown>;\n /**\n * CSRF nonce bound into the state. Pass the same value as the oauth_csrf\n * cookie. Defaults to a fresh nonce (unbound — legacy/no-CSRF callers).\n */\n nonce?: string;\n}\n\n/**\n * OAuth state 생성 및 암호화\n *\n * @param params - state 생성에 필요한 파라미터\n * @returns 암호화된 state 문자열\n */\nexport async function createOAuthState(params: CreateOAuthStateParams): Promise<string>\n{\n const key = await getStateKey();\n\n const state: OAuthState = {\n returnUrl: params.returnUrl,\n nonce: params.nonce ?? generateNonce(),\n provider: params.provider,\n publicKey: params.publicKey,\n keyId: params.keyId,\n fingerprint: params.fingerprint,\n algorithm: params.algorithm,\n metadata: params.metadata,\n };\n\n const jwe = await new jose.EncryptJWT({ state })\n .setProtectedHeader({ alg: 'dir', enc: 'A256GCM' })\n .setIssuedAt()\n .setExpirationTime('10m')\n .encrypt(key);\n\n // URL-safe base64 encoding\n return encodeURIComponent(jwe);\n}\n\n/**\n * OAuth state 복호화 및 검증\n *\n * @param encryptedState - 암호화된 state 문자열\n * @returns 복호화된 state 객체\n * @throws Error if state is invalid or expired (JWE exp claim으로 자동 검증)\n */\nexport async function verifyOAuthState(encryptedState: string): Promise<OAuthState>\n{\n const key = await getStateKey();\n\n const jwe = decodeURIComponent(encryptedState);\n const { payload } = await jose.jwtDecrypt(jwe, key);\n\n return payload.state as OAuthState;\n}\n","/**\n * Session helpers for Next.js\n *\n * Server-side only (uses next/headers)\n */\n\nimport * as jose from 'jose';\nimport { cookies } from 'next/headers.js';\nimport { sealSession, unsealSession, type SessionData } from '../server/lib/session';\nimport { deriveCsrfToken } from '../server/lib/csrf';\nimport { COOKIE_NAMES, getSessionTtl, parseDuration } from '../server/lib/config';\nimport { type KeyAlgorithmType } from '../server/types';\nimport { env } from '@spfn/auth/config';\nimport { logger } from '@spfn/core/logger';\n\nexport type { SessionData };\n\n/**\n * Pending OAuth session data (before user ID is known)\n */\nexport interface PendingSessionData\n{\n privateKey: string;\n keyId: string;\n algorithm: KeyAlgorithmType;\n}\n\n/**\n * Public session information (excludes sensitive data)\n */\nexport interface PublicSession\n{\n /** User ID */\n userId: string;\n}\n\n/**\n * Options for saveSession\n */\nexport interface SaveSessionOptions\n{\n /**\n * Session TTL (time to live)\n *\n * Supports:\n * - Number: seconds (e.g., 2592000)\n * - String: duration format ('30d', '12h', '45m', '3600s')\n *\n * If not provided, uses global configuration:\n * 1. Global config (configureAuth)\n * 2. Environment variable (SPFN_AUTH_SESSION_TTL)\n * 3. Default (7d)\n */\n maxAge?: number | string;\n\n /**\n * Remember me option\n *\n * When true, uses extended session duration (if configured)\n */\n remember?: boolean;\n}\n\n/**\n * Save session to HttpOnly cookie\n *\n * @param data - Session data to save\n * @param options - Session options (maxAge, remember)\n *\n * @example\n * ```typescript\n * // Use global configuration\n * await saveSession(sessionData);\n *\n * // Custom TTL with duration string\n * await saveSession(sessionData, { maxAge: '30d' });\n *\n * // Custom TTL in seconds\n * await saveSession(sessionData, { maxAge: 2592000 });\n *\n * // Remember me\n * await saveSession(sessionData, { remember: true });\n * ```\n */\nexport async function saveSession(\n data: SessionData,\n options?: SaveSessionOptions,\n): Promise<void>\n{\n // Calculate maxAge\n let maxAge: number;\n\n if (options?.maxAge !== undefined)\n {\n // Custom maxAge provided\n maxAge = typeof options.maxAge === 'number'\n ? options.maxAge\n : parseDuration(options.maxAge);\n }\n else\n {\n // Use getSessionTtl for consistent configuration\n maxAge = getSessionTtl();\n }\n\n const token = await sealSession(data, maxAge);\n const cookieStore = await cookies();\n\n cookieStore.set(COOKIE_NAMES.SESSION, token, {\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'lax',\n path: '/',\n maxAge,\n });\n\n // Readable companion: the client mirrors it into x-spfn-csrf, and the proxy\n // refuses cookie-session mutations that arrive without it. A session saved\n // here without one would be a session that cannot mutate anything.\n cookieStore.set(COOKIE_NAMES.CSRF, await deriveCsrfToken(data.keyId), {\n httpOnly: false,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'lax',\n path: '/',\n maxAge,\n });\n}\n\n/**\n * Get session from HttpOnly cookie\n *\n * Returns public session info only (excludes privateKey, algorithm, keyId)\n */\nexport async function getSession(): Promise<PublicSession | null>\n{\n const cookieStore = await cookies();\n const sessionCookie = cookieStore.get(COOKIE_NAMES.SESSION);\n\n if (!sessionCookie)\n {\n return null;\n }\n\n try\n {\n // Never log the cookie value — it's the sealed session token.\n logger.debug('Validating session cookie', { present: true });\n const session = await unsealSession(sessionCookie.value);\n\n // Return only public information\n return {\n userId: session.userId,\n };\n }\n catch (error)\n {\n // Session expired or invalid\n // Note: Cannot delete cookies in Server Components (read-only)\n // Use validateSessionMiddleware() in Next.js middleware for automatic cleanup\n logger.debug('Session validation failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n\n return null;\n }\n}\n\n/**\n * Clear session cookie\n */\nexport async function clearSession(): Promise<void>\n{\n const cookieStore = await cookies();\n cookieStore.delete(COOKIE_NAMES.SESSION);\n cookieStore.delete(COOKIE_NAMES.SESSION_KEY_ID);\n cookieStore.delete(COOKIE_NAMES.CSRF);\n}\n\n// ============================================================================\n// Pending OAuth Session (for OAuth flow)\n// ============================================================================\n\n/**\n * Get encryption key for pending session\n */\nasync function getPendingSessionKey(): Promise<Uint8Array>\n{\n const secret = env.SPFN_AUTH_SESSION_SECRET;\n const encoder = new TextEncoder();\n const data = encoder.encode(`oauth-pending:${secret}`);\n const hashBuffer = await crypto.subtle.digest('SHA-256', data);\n\n return new Uint8Array(hashBuffer);\n}\n\n/**\n * Seal pending session data (for OAuth flow)\n *\n * @param data - Pending session data (privateKey, keyId, algorithm)\n * @param ttl - Time to live in seconds (default: 10 minutes)\n */\nexport async function sealPendingSession(\n data: PendingSessionData,\n ttl: number = 600,\n): Promise<string>\n{\n const key = await getPendingSessionKey();\n\n return await new jose.EncryptJWT({ data })\n .setProtectedHeader({ alg: 'dir', enc: 'A256GCM' })\n .setIssuedAt()\n .setExpirationTime(`${ttl}s`)\n .setIssuer('spfn-auth')\n .setAudience('spfn-oauth')\n .encrypt(key);\n}\n\n/**\n * Unseal pending session data\n *\n * @param jwt - Encrypted pending session token\n */\nexport async function unsealPendingSession(jwt: string): Promise<PendingSessionData>\n{\n const key = await getPendingSessionKey();\n\n const { payload } = await jose.jwtDecrypt(jwt, key, {\n issuer: 'spfn-auth',\n audience: 'spfn-oauth',\n });\n\n return payload.data as PendingSessionData;\n}\n\n/**\n * Get pending session from cookie\n */\nexport async function getPendingSession(): Promise<PendingSessionData | null>\n{\n const cookieStore = await cookies();\n const pendingCookie = cookieStore.get(COOKIE_NAMES.OAUTH_PENDING);\n\n if (!pendingCookie)\n {\n return null;\n }\n\n try\n {\n return await unsealPendingSession(pendingCookie.value);\n }\n catch (error)\n {\n logger.debug('Pending session validation failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n\n return null;\n }\n}\n\n/**\n * Clear pending session cookie\n */\nexport async function clearPendingSession(): Promise<void>\n{\n const cookieStore = await cookies();\n cookieStore.delete(COOKIE_NAMES.OAUTH_PENDING);\n}\n","/**\n * OAuth Interceptors\n *\n * 1. oauthUrlInterceptor: OAuth URL 요청 시 키쌍 생성 및 state 주입\n * 2. oauthFinalizeInterceptor: OAuth 완료 시 pending session에서 세션 저장\n */\n\nimport type { InterceptorRule, ResponseInterceptorContext } from '@spfn/core/nextjs/server';\nimport { generateKeyPair } from '../../server/lib/crypto';\nimport { createOAuthState, generateOAuthNonce } from '../../server/lib/oauth/state';\nimport { sealSession } from '../../server/lib/session';\nimport { COOKIE_NAMES, getSessionTtl } from '../../server/lib/config';\nimport { authLogger } from '../../server/logger';\nimport { sealPendingSession, unsealPendingSession } from '../session-helpers';\nimport { cookieSecure } from './cookie-options';\nimport { pushCsrfCookie } from './csrf';\n\n/**\n * OAuth URL Interceptor\n *\n * POST /_auth/oauth/:provider/url 요청을 가로채서\n * 키쌍 생성 및 state 주입 처리\n */\nexport const oauthUrlInterceptor: InterceptorRule = {\n pathPattern: /^\\/_auth\\/oauth\\/\\w+\\/url$/,\n method: 'POST',\n\n request: async (ctx, next) =>\n {\n const provider = ctx.path.split('/')[3]; // google, github, etc.\n const returnUrl = ctx.body?.returnUrl || '/';\n const metadata = ctx.body?.metadata as Record<string, unknown> | undefined;\n\n // 키쌍 생성\n const keyPair = generateKeyPair('ES256');\n\n // CSRF nonce: bound into the state AND set as the oauth_csrf cookie below,\n // so the backend callback can confirm the flow started in THIS browser.\n const csrfNonce = generateOAuthNonce();\n\n // state 생성 (publicKey 포함)\n const state = await createOAuthState({\n provider,\n returnUrl,\n publicKey: keyPair.publicKey,\n keyId: keyPair.keyId,\n fingerprint: keyPair.fingerprint,\n algorithm: keyPair.algorithm,\n nonce: csrfNonce,\n metadata,\n });\n\n // body에 state 주입\n if (!ctx.body)\n {\n ctx.body = {};\n }\n ctx.body.state = state;\n\n // pending session 저장용 metadata\n ctx.metadata.pendingSession = {\n privateKey: keyPair.privateKey,\n keyId: keyPair.keyId,\n algorithm: keyPair.algorithm,\n };\n ctx.metadata.oauthCsrf = csrfNonce;\n\n authLogger.interceptor.oauth?.debug?.('OAuth state created', {\n provider,\n keyId: keyPair.keyId,\n });\n\n await next();\n },\n\n response: async (ctx, next) =>\n {\n // 성공 응답이고 pending session이 있으면 쿠키 설정\n if (ctx.response.ok && ctx.metadata.pendingSession)\n {\n try\n {\n const sealed = await sealPendingSession(ctx.metadata.pendingSession);\n\n ctx.setCookies.push({\n name: COOKIE_NAMES.OAUTH_PENDING,\n value: sealed,\n options: {\n httpOnly: true,\n secure: cookieSecure,\n sameSite: 'lax', // OAuth 리다이렉트 허용\n maxAge: 600, // 10분\n path: '/',\n },\n });\n\n // CSRF nonce cookie (double-submit against the state.nonce at callback)\n if (ctx.metadata.oauthCsrf)\n {\n ctx.setCookies.push({\n name: COOKIE_NAMES.OAUTH_CSRF,\n value: ctx.metadata.oauthCsrf,\n options: {\n httpOnly: true,\n secure: cookieSecure,\n sameSite: 'lax',\n maxAge: 600,\n path: '/',\n },\n });\n }\n\n authLogger.interceptor.oauth?.debug?.('Pending session cookie set', {\n keyId: ctx.metadata.pendingSession.keyId,\n });\n }\n catch (error)\n {\n const err = error as Error;\n authLogger.interceptor.oauth?.error?.('Failed to set pending session', err);\n }\n }\n\n await next();\n },\n};\n\n/**\n * Finalize 실패 시 에러 응답 설정 + pending 쿠키 정리\n */\nfunction setFinalizeError(ctx: ResponseInterceptorContext, message: string): void\n{\n ctx.response.ok = false;\n ctx.response.status = 401;\n ctx.response.statusText = 'Unauthorized';\n ctx.response.body = { success: false, message };\n\n ctx.setCookies.push({\n name: COOKIE_NAMES.OAUTH_PENDING,\n value: '',\n options: {\n httpOnly: true,\n secure: cookieSecure,\n sameSite: 'lax',\n maxAge: 0,\n path: '/',\n },\n });\n}\n\n/**\n * OAuth Finalize Interceptor\n *\n * POST /_auth/oauth/finalize 요청을 가로채서\n * pending session에서 세션 저장\n */\nexport const oauthFinalizeInterceptor: InterceptorRule = {\n pathPattern: /^\\/_auth\\/oauth\\/finalize$/,\n method: 'POST',\n\n response: async (ctx, next) =>\n {\n // 성공 응답일 때만 처리\n if (!ctx.response.ok)\n {\n await next();\n\n return;\n }\n\n const pendingCookie = ctx.cookies.get(COOKIE_NAMES.OAUTH_PENDING);\n if (!pendingCookie)\n {\n authLogger.interceptor.oauth?.warn?.('No pending session cookie found');\n setFinalizeError(ctx, 'OAuth session expired. Please try again.');\n await next();\n\n return;\n }\n\n try\n {\n // pending session에서 privateKey 복원\n const pendingSession = await unsealPendingSession(pendingCookie);\n\n // body에서 userId, keyId 추출\n const { userId, keyId } = ctx.response.body || {};\n\n if (!userId || !keyId)\n {\n authLogger.interceptor.oauth?.error?.('Missing userId or keyId in response');\n setFinalizeError(ctx, 'OAuth finalize failed: missing credentials');\n await next();\n\n return;\n }\n\n // keyId 일치 확인\n if (pendingSession.keyId !== keyId)\n {\n authLogger.interceptor.oauth?.error?.('KeyId mismatch', {\n expected: pendingSession.keyId,\n received: keyId,\n });\n setFinalizeError(ctx, 'OAuth session mismatch. Please try again.');\n await next();\n\n return;\n }\n\n // 세션 생성.\n // `userId` here is the value reflected by /_auth/oauth/finalize (a UI\n // convenience, not a trust anchor). It's safe to seal: keyId was matched\n // against the pending cookie above, the session is sealed, and the\n // backend re-derives identity from keyId on every request — see the\n // SECURITY note on the oauthFinalize route handler.\n const ttl = getSessionTtl();\n const sessionToken = await sealSession({\n userId,\n privateKey: pendingSession.privateKey,\n keyId: pendingSession.keyId,\n algorithm: pendingSession.algorithm,\n }, ttl);\n\n // 세션 쿠키 설정\n ctx.setCookies.push({\n name: COOKIE_NAMES.SESSION,\n value: sessionToken,\n options: {\n httpOnly: true,\n secure: cookieSecure,\n sameSite: 'lax',\n maxAge: ttl,\n path: '/',\n },\n });\n\n // keyId 쿠키 설정\n ctx.setCookies.push({\n name: COOKIE_NAMES.SESSION_KEY_ID,\n value: keyId,\n options: {\n httpOnly: true,\n secure: cookieSecure,\n sameSite: 'lax',\n maxAge: ttl,\n path: '/',\n },\n });\n\n // Set the readable CSRF cookie the client mirrors into a header\n await pushCsrfCookie(ctx.setCookies, keyId, ttl);\n\n // pending session 쿠키 삭제 (maxAge: 0)\n ctx.setCookies.push({\n name: COOKIE_NAMES.OAUTH_PENDING,\n value: '',\n options: {\n httpOnly: true,\n secure: cookieSecure,\n sameSite: 'lax',\n maxAge: 0,\n path: '/',\n },\n });\n\n authLogger.interceptor.oauth?.debug?.('OAuth session finalized', {\n userId,\n keyId,\n });\n }\n catch (error)\n {\n const err = error as Error;\n authLogger.interceptor.oauth?.error?.('Failed to finalize OAuth session', err);\n setFinalizeError(ctx, err.message);\n }\n\n await next();\n },\n};\n","/**\n * Verified-Email Signup Interceptor\n *\n * Carries the password-setup session between the two browser-facing steps of the\n * verified-email signup, so the secret that authorizes password setup lives in an\n * HttpOnly cookie and never in page script.\n *\n * On the confirm response it moves `setupSecret` out of the body and into the\n * cookie. On the password request it puts the cookie back into the body, the same\n * way `loginRegisterInterceptor` injects a device key. Both interceptors match\n * `/_auth/signup/password` and both run — matching rules execute as a chain in\n * registration order, they do not compete — so the password request arrives with\n * the setup secret and a freshly generated key.\n */\n\nimport type { InterceptorRule } from '@spfn/core/nextjs/server';\nimport { COOKIE_NAMES } from '../../server/lib/config';\nimport { authLogger } from '../../server/logger';\nimport { cookieSecure } from './cookie-options';\n\n/**\n * Setup-session cookie lifetime, in seconds.\n *\n * Deliberately a little longer than the server-side setup session: the server\n * decides when the session dies, and a cookie that expired first would turn an\n * expired-session refusal into a missing-cookie one, which reads as a different\n * bug to whoever is looking.\n */\nconst SETUP_COOKIE_TTL_SECONDS = 60 * 60;\n\n/**\n * Cookie carrying the password-setup session.\n */\nfunction setupCookie(value: string, maxAge: number)\n{\n return {\n name: COOKIE_NAMES.SIGNUP_SETUP,\n value,\n options: {\n httpOnly: true,\n secure: cookieSecure,\n sameSite: 'lax' as const,\n maxAge,\n path: '/',\n },\n };\n}\n\nexport const signupLinkInterceptor: InterceptorRule = {\n pathPattern: /^\\/_auth\\/signup\\/(email\\/confirm|password)$/,\n method: 'POST',\n\n request: async (ctx, next) =>\n {\n if (ctx.path === '/_auth/signup/password')\n {\n const cookie = ctx.cookies.get(COOKIE_NAMES.SIGNUP_SETUP);\n\n if (cookie)\n {\n if (!ctx.body)\n {\n ctx.body = {};\n }\n\n ctx.body.setupSecret = cookie;\n }\n }\n\n await next();\n },\n\n response: async (ctx, next) =>\n {\n if (!ctx.response.ok)\n {\n // A refusal here is often the user's to fix — a password that fails\n // the strength policy, an app policy that rejected the signup. The\n // setup session survives those on the server, so the cookie has to\n // survive them too, or the retry has nothing to present.\n await next();\n\n return;\n }\n\n if (ctx.path === '/_auth/signup/email/confirm')\n {\n const secret = ctx.response.body?.setupSecret;\n\n if (!secret)\n {\n authLogger.interceptor.oauth?.error?.('Signup confirm response carried no setup secret');\n await next();\n\n return;\n }\n\n ctx.setCookies.push(setupCookie(secret, SETUP_COOKIE_TTL_SECONDS));\n\n // The browser must never see it — an HttpOnly cookie that page\n // script can also read out of the JSON body is not HttpOnly.\n delete ctx.response.body.setupSecret;\n }\n\n if (ctx.path === '/_auth/signup/password')\n {\n // Spent. Clearing it stops a stale cookie from being presented to a\n // session the server has already marked used.\n ctx.setCookies.push(setupCookie('', 0));\n }\n\n await next();\n },\n};\n","/**\n * Auth Interceptors for Next.js Proxy\n *\n * Automatically registers interceptors for authentication flow\n *\n * Every rule whose path and method match runs, as a chain in this order — they\n * do not compete for a single match. Two of them share /_auth/signup/password on\n * purpose: signupLinkInterceptor supplies the setup secret and\n * loginRegisterInterceptor supplies the device key.\n *\n * Order matters - more specific interceptors first:\n * 1. signupLinkInterceptor - Most specific (verified-email signup only)\n * 2. loginRegisterInterceptor - Specific (login/register/signup password)\n * 3. keyRotationInterceptor - Specific (key rotation only)\n * 4. oauthUrlInterceptor - OAuth URL generation (key generation + state injection)\n * 5. generalAuthInterceptor - General (all authenticated requests)\n */\n\nimport { loginRegisterInterceptor } from './login-register';\nimport { generalAuthInterceptor } from './general-auth';\nimport { keyRotationInterceptor } from './key-rotation';\nimport { oauthUrlInterceptor, oauthFinalizeInterceptor } from './oauth';\nimport { signupLinkInterceptor } from './signup-link';\n\n/**\n * All auth interceptors\n *\n * Execution order:\n * 1. signupLinkInterceptor - Handles verified-email signup (setup secret ↔ HttpOnly cookie)\n * 2. loginRegisterInterceptor - Handles login/register/signup password (key generation + session save)\n * 3. keyRotationInterceptor - Handles key rotation (new key generation + session update)\n * 4. oauthUrlInterceptor - Handles OAuth URL requests (key generation + state injection + pending session)\n * 5. oauthFinalizeInterceptor - Handles OAuth finalize (pending session → full session)\n * 6. generalAuthInterceptor - Handles all authenticated requests (session validation + JWT injection + session renewal)\n */\nexport const authInterceptors = [\n signupLinkInterceptor,\n loginRegisterInterceptor,\n keyRotationInterceptor,\n oauthUrlInterceptor,\n oauthFinalizeInterceptor,\n generalAuthInterceptor,\n];\n\nexport { loginRegisterInterceptor } from './login-register';\nexport { generalAuthInterceptor } from './general-auth';\nexport { keyRotationInterceptor } from './key-rotation';\nexport { oauthUrlInterceptor, oauthFinalizeInterceptor } from './oauth';\nexport { signupLinkInterceptor } from './signup-link';\n\n// Deprecated: use generalAuthInterceptor instead\nexport { generalAuthInterceptor as authenticationInterceptor };\n"],"mappings":";AAoBA,SAAS,4BAA4B;;;ACRrC,OAAOA,aAAY;AACnB,OAAO,SAA+C;AAuD/C,SAAS,uBAChB;AACI,QAAM,QAAQA,QAAO,WAAW;AAEhC,QAAM,EAAE,YAAY,UAAU,IAAIA,QAAO,oBAAoB,MAAM;AAAA,IAC/D,YAAY;AAAA;AAAA,IACZ,mBAAmB;AAAA,MACf,MAAM;AAAA,MACN,QAAQ;AAAA,IACZ;AAAA,IACA,oBAAoB;AAAA,MAChB,MAAM;AAAA,MACN,QAAQ;AAAA,IACZ;AAAA,EACJ,CAAC;AAGD,QAAM,gBAAgB,WAAW,SAAS,QAAQ;AAClD,QAAM,eAAe,UAAU,SAAS,QAAQ;AAGhD,QAAM,cAAcA,QACf,WAAW,QAAQ,EACnB,OAAO,SAAS,EAChB,OAAO,KAAK;AAEjB,SAAO;AAAA,IACH,YAAY;AAAA,IACZ,WAAW;AAAA,IACX;AAAA,IACA;AAAA,IACA,WAAW;AAAA,EACf;AACJ;AAMO,SAAS,uBAChB;AACI,QAAM,Q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