@spfn/auth 0.2.0-beta.11 → 0.2.0-beta.13
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 +338 -8
- package/dist/{authenticate-CU6_zQaa.d.ts → authenticate-Cz2FjLdB.d.ts} +113 -1
- package/dist/config.d.ts +120 -0
- package/dist/config.js +72 -0
- package/dist/config.js.map +1 -1
- package/dist/index.d.ts +46 -2
- package/dist/nextjs/api.js +186 -0
- package/dist/nextjs/api.js.map +1 -1
- package/dist/nextjs/client.js +80 -0
- package/dist/nextjs/client.js.map +1 -0
- package/dist/nextjs/server.d.ts +68 -2
- package/dist/nextjs/server.js +125 -2
- package/dist/nextjs/server.js.map +1 -1
- package/dist/server.d.ts +243 -3
- package/dist/server.js +594 -23
- package/dist/server.js.map +1 -1
- package/package.json +10 -3
package/dist/config.js
CHANGED
|
@@ -231,6 +231,78 @@ var authEnvSchema = defineEnvSchema({
|
|
|
231
231
|
required: false,
|
|
232
232
|
examples: ["MyApp", "Your Company"]
|
|
233
233
|
})
|
|
234
|
+
},
|
|
235
|
+
SPFN_APP_URL: {
|
|
236
|
+
...envString({
|
|
237
|
+
description: "Next.js application URL. Used for OAuth callback redirects.",
|
|
238
|
+
default: "http://localhost:3000",
|
|
239
|
+
required: false,
|
|
240
|
+
examples: [
|
|
241
|
+
"https://app.example.com",
|
|
242
|
+
"http://localhost:3000"
|
|
243
|
+
]
|
|
244
|
+
})
|
|
245
|
+
},
|
|
246
|
+
// ============================================================================
|
|
247
|
+
// OAuth Configuration - Google
|
|
248
|
+
// ============================================================================
|
|
249
|
+
SPFN_AUTH_GOOGLE_CLIENT_ID: {
|
|
250
|
+
...envString({
|
|
251
|
+
description: "Google OAuth 2.0 Client ID. When set, Google OAuth routes are automatically enabled.",
|
|
252
|
+
required: false,
|
|
253
|
+
examples: ["123456789-abc123.apps.googleusercontent.com"]
|
|
254
|
+
})
|
|
255
|
+
},
|
|
256
|
+
SPFN_AUTH_GOOGLE_CLIENT_SECRET: {
|
|
257
|
+
...envString({
|
|
258
|
+
description: "Google OAuth 2.0 Client Secret",
|
|
259
|
+
required: false,
|
|
260
|
+
sensitive: true,
|
|
261
|
+
examples: ["GOCSPX-abcdefghijklmnop"]
|
|
262
|
+
})
|
|
263
|
+
},
|
|
264
|
+
SPFN_AUTH_GOOGLE_SCOPES: {
|
|
265
|
+
...envString({
|
|
266
|
+
description: 'Comma-separated Google OAuth scopes. Defaults to "email,profile" if not set.',
|
|
267
|
+
required: false,
|
|
268
|
+
examples: [
|
|
269
|
+
"email,profile",
|
|
270
|
+
"email,profile,https://www.googleapis.com/auth/gmail.readonly",
|
|
271
|
+
"email,profile,https://www.googleapis.com/auth/calendar.readonly"
|
|
272
|
+
]
|
|
273
|
+
})
|
|
274
|
+
},
|
|
275
|
+
SPFN_AUTH_GOOGLE_REDIRECT_URI: {
|
|
276
|
+
...envString({
|
|
277
|
+
description: "Google OAuth callback URL. Defaults to {SPFN_API_URL}/_auth/oauth/google/callback",
|
|
278
|
+
required: false,
|
|
279
|
+
examples: [
|
|
280
|
+
"https://api.example.com/_auth/oauth/google/callback",
|
|
281
|
+
"http://localhost:8790/_auth/oauth/google/callback"
|
|
282
|
+
]
|
|
283
|
+
})
|
|
284
|
+
},
|
|
285
|
+
SPFN_AUTH_OAUTH_SUCCESS_URL: {
|
|
286
|
+
...envString({
|
|
287
|
+
description: "OAuth callback page URL. This page should use OAuthCallback component to finalize session.",
|
|
288
|
+
required: false,
|
|
289
|
+
default: "/auth/callback",
|
|
290
|
+
examples: [
|
|
291
|
+
"/auth/callback",
|
|
292
|
+
"https://app.example.com/auth/callback"
|
|
293
|
+
]
|
|
294
|
+
})
|
|
295
|
+
},
|
|
296
|
+
SPFN_AUTH_OAUTH_ERROR_URL: {
|
|
297
|
+
...envString({
|
|
298
|
+
description: "URL to redirect after OAuth error. Use {error} placeholder for error message.",
|
|
299
|
+
required: false,
|
|
300
|
+
default: "http://localhost:3000/auth/error?error={error}",
|
|
301
|
+
examples: [
|
|
302
|
+
"https://app.example.com/auth/error?error={error}",
|
|
303
|
+
"http://localhost:3000/auth/error?error={error}"
|
|
304
|
+
]
|
|
305
|
+
})
|
|
234
306
|
}
|
|
235
307
|
});
|
|
236
308
|
|
package/dist/config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/config/index.ts","../src/config/schema.ts"],"sourcesContent":["/**\n * Core Package Configuration\n *\n * @example\n * ```typescript\n * import { registry } from '@spfn/core/config';\n *\n * const env = registry.validate();\n * console.log(env.DB_POOL_MAX);\n * ```\n *\n * @module config\n */\n\nimport { createEnvRegistry } from '@spfn/core/env';\nimport { authEnvSchema } from './schema';\n\nexport { authEnvSchema as envSchema } from './schema';\n\n/**\n * Environment registry\n */\nconst registry = createEnvRegistry(authEnvSchema);\nexport const env = registry.validate();","/**\n * Auth Environment Variable Schema\n *\n * Centralized schema definition for all environment variables used in @spfn/auth.\n * This provides type safety, validation, and documentation for Auth configuration.\n *\n * @module config/schema\n */\n\nimport {\n defineEnvSchema,\n envString,\n envNumber,\n createSecureSecretParser,\n createPasswordParser,\n} from '@spfn/core/env';\n\n/**\n * Auth environment variable schema\n *\n * Defines all Auth environment variables with:\n * - Type information\n * - Default values\n * - Validation rules\n * - Documentation\n *\n * @example\n * ```typescript\n * import { authEnvSchema } from '@spfn/auth/config';\n *\n * // Access schema information\n * console.log(authEnvSchema.SPFN_AUTH_SESSION_SECRET.description);\n * console.log(authEnvSchema.SPFN_AUTH_JWT_EXPIRES_IN.default);\n * ```\n */\nexport const authEnvSchema = defineEnvSchema({\n // ============================================================================\n // Session Configuration\n // ============================================================================\n SPFN_AUTH_SESSION_SECRET: {\n ...envString({\n description: 'Session encryption secret (minimum 32 characters for AES-256)',\n required: true,\n fallbackKeys: ['SESSION_SECRET'],\n validator: createSecureSecretParser({\n minLength: 32,\n minUniqueChars: 16,\n minEntropy: 3.5,\n }),\n sensitive: true,\n nextjs: true, // Required for Next.js RSC session validation\n examples: [\n 'my-super-secret-session-key-at-least-32-chars-long',\n 'use-a-cryptographically-secure-random-string-here',\n ],\n }),\n },\n\n SPFN_AUTH_SESSION_TTL: {\n ...envString({\n description: 'Session TTL (time to live) - supports duration strings like \\'7d\\', \\'12h\\', \\'45m\\'',\n default: '7d',\n required: false,\n nextjs: true, // May be needed for session validation in Next.js RSC\n examples: ['7d', '30d', '12h', '45m', '3600'],\n }),\n },\n\n // ============================================================================\n // JWT Configuration\n // ============================================================================\n SPFN_AUTH_JWT_SECRET: {\n ...envString({\n description: 'JWT signing secret for server-signed tokens (legacy mode)',\n default: 'dev-secret-key-change-in-production',\n required: false,\n examples: [\n 'your-jwt-secret-key-here',\n 'use-different-from-session-secret',\n ],\n }),\n },\n\n SPFN_AUTH_JWT_EXPIRES_IN: {\n ...envString({\n description: 'JWT token expiration time (e.g., \\'7d\\', \\'24h\\', \\'1h\\')',\n default: '7d',\n required: false,\n examples: ['7d', '24h', '1h', '30m'],\n }),\n },\n\n // ============================================================================\n // Security Configuration\n // ============================================================================\n SPFN_AUTH_BCRYPT_SALT_ROUNDS: {\n ...envNumber({\n description: 'Bcrypt salt rounds (cost factor, higher = more secure but slower)',\n default: 10,\n required: false,\n examples: [10, 12, 14],\n }),\n key: 'SPFN_AUTH_BCRYPT_SALT_ROUNDS',\n },\n\n SPFN_AUTH_VERIFICATION_TOKEN_SECRET: {\n ...envString({\n description: 'Verification token secret for email verification, password reset, etc.',\n required: true,\n examples: [\n 'your-verification-token-secret',\n 'can-be-different-from-jwt-secret',\n ],\n }),\n },\n\n // ============================================================================\n // Admin Account Configuration\n // ============================================================================\n SPFN_AUTH_ADMIN_ACCOUNTS: {\n ...envString({\n description: 'JSON array of admin accounts (recommended for multiple admins)',\n required: false,\n examples: [\n '[{\"email\":\"admin@example.com\",\"password\":\"secure-pass\",\"role\":\"admin\"}]',\n '[{\"email\":\"super@example.com\",\"password\":\"pass1\",\"role\":\"superadmin\"},{\"email\":\"admin@example.com\",\"password\":\"pass2\",\"role\":\"admin\"}]',\n ],\n }),\n },\n\n SPFN_AUTH_ADMIN_EMAILS: {\n ...envString({\n description: 'Comma-separated list of admin emails (legacy CSV format)',\n required: false,\n examples: [\n 'admin@example.com,user@example.com',\n 'super@example.com,admin@example.com,user@example.com',\n ],\n }),\n },\n\n SPFN_AUTH_ADMIN_PASSWORDS: {\n ...envString({\n description: 'Comma-separated list of admin passwords (legacy CSV format)',\n required: false,\n examples: [\n 'admin-pass,user-pass',\n 'super-pass,admin-pass,user-pass',\n ],\n }),\n },\n\n SPFN_AUTH_ADMIN_ROLES: {\n ...envString({\n description: 'Comma-separated list of admin roles (legacy CSV format)',\n required: false,\n examples: [\n 'admin,user',\n 'superadmin,admin,user',\n ],\n }),\n },\n\n SPFN_AUTH_ADMIN_EMAIL: {\n ...envString({\n description: 'Single admin email (simplest format)',\n required: false,\n examples: ['admin@example.com'],\n }),\n },\n\n SPFN_AUTH_ADMIN_PASSWORD: {\n ...envString({\n description: 'Single admin password (simplest format)',\n required: false,\n validator: createPasswordParser({\n minLength: 8,\n requireUppercase: true,\n requireLowercase: true,\n requireNumber: true,\n requireSpecial: true,\n }),\n sensitive: true,\n examples: ['SecureAdmin123!'],\n }),\n },\n\n // ============================================================================\n // API Configuration\n // ============================================================================\n SPFN_API_URL: {\n ...envString({\n description: 'Base API URL for invitation links and other external-facing URLs',\n default: 'http://localhost:8790',\n required: false,\n examples: [\n 'https://api.example.com',\n 'http://localhost:8790',\n ],\n }),\n },\n\n // ============================================================================\n // AWS SNS Configuration (SMS)\n // ============================================================================\n SPFN_AUTH_AWS_REGION: {\n ...envString({\n description: 'AWS region for SNS service',\n default: 'ap-northeast-2',\n required: false,\n examples: ['ap-northeast-2', 'us-east-1', 'eu-west-1'],\n }),\n },\n\n SPFN_AUTH_AWS_SNS_ACCESS_KEY_ID: {\n ...envString({\n description: 'AWS SNS access key ID (optional, uses default credentials chain if not provided)',\n required: false,\n sensitive: true,\n examples: ['AKIAIOSFODNN7EXAMPLE'],\n }),\n },\n\n SPFN_AUTH_AWS_SNS_SECRET_ACCESS_KEY: {\n ...envString({\n description: 'AWS SNS secret access key (optional, uses default credentials chain if not provided)',\n required: false,\n sensitive: true,\n examples: ['wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY'],\n }),\n },\n\n SPFN_AUTH_AWS_SNS_SENDER_ID: {\n ...envString({\n description: 'SMS sender ID displayed to recipients (max 11 characters, alphanumeric)',\n required: false,\n examples: ['MyApp', 'YourBrand'],\n }),\n },\n\n // ============================================================================\n // AWS SES Configuration (Email)\n // ============================================================================\n SPFN_AUTH_AWS_SES_ACCESS_KEY_ID: {\n ...envString({\n description: 'AWS SES access key ID (optional, uses default credentials chain if not provided)',\n required: false,\n sensitive: true,\n examples: ['AKIAIOSFODNN7EXAMPLE'],\n }),\n },\n\n SPFN_AUTH_AWS_SES_SECRET_ACCESS_KEY: {\n ...envString({\n description: 'AWS SES secret access key (optional, uses default credentials chain if not provided)',\n required: false,\n sensitive: true,\n examples: ['wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY'],\n }),\n },\n\n SPFN_AUTH_AWS_SES_FROM_EMAIL: {\n ...envString({\n description: 'Sender email address (must be verified in AWS SES)',\n required: false,\n examples: ['noreply@example.com', 'auth@yourdomain.com'],\n }),\n },\n\n SPFN_AUTH_AWS_SES_FROM_NAME: {\n ...envString({\n description: 'Sender display name',\n required: false,\n examples: ['MyApp', 'Your Company'],\n }),\n },\n});"],"mappings":";AAcA,SAAS,yBAAyB;;;ACLlC;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AAoBA,IAAM,gBAAgB,gBAAgB;AAAA;AAAA;AAAA;AAAA,EAIzC,0BAA0B;AAAA,IACtB,GAAG,UAAU;AAAA,MACT,aAAa;AAAA,MACb,UAAU;AAAA,MACV,cAAc,CAAC,gBAAgB;AAAA,MAC/B,WAAW,yBAAyB;AAAA,QAChC,W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AM,SAAS,SAAS;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/config/index.ts","../src/config/schema.ts"],"sourcesContent":["/**\n * Core Package Configuration\n *\n * @example\n * ```typescript\n * import { registry } from '@spfn/core/config';\n *\n * const env = registry.validate();\n * console.log(env.DB_POOL_MAX);\n * ```\n *\n * @module config\n */\n\nimport { createEnvRegistry } from '@spfn/core/env';\nimport { authEnvSchema } from './schema';\n\nexport { authEnvSchema as envSchema } from './schema';\n\n/**\n * Environment registry\n */\nconst registry = createEnvRegistry(authEnvSchema);\nexport const env = registry.validate();","/**\n * Auth Environment Variable Schema\n *\n * Centralized schema definition for all environment variables used in @spfn/auth.\n * This provides type safety, validation, and documentation for Auth configuration.\n *\n * @module config/schema\n */\n\nimport {\n defineEnvSchema,\n envString,\n envNumber,\n createSecureSecretParser,\n createPasswordParser,\n} from '@spfn/core/env';\n\n/**\n * Auth environment variable schema\n *\n * Defines all Auth environment variables with:\n * - Type information\n * - Default values\n * - Validation rules\n * - Documentation\n *\n * @example\n * ```typescript\n * import { authEnvSchema } from '@spfn/auth/config';\n *\n * // Access schema information\n * console.log(authEnvSchema.SPFN_AUTH_SESSION_SECRET.description);\n * console.log(authEnvSchema.SPFN_AUTH_JWT_EXPIRES_IN.default);\n * ```\n */\nexport const authEnvSchema = defineEnvSchema({\n // ============================================================================\n // Session Configuration\n // ============================================================================\n SPFN_AUTH_SESSION_SECRET: {\n ...envString({\n description: 'Session encryption secret (minimum 32 characters for AES-256)',\n required: true,\n fallbackKeys: ['SESSION_SECRET'],\n validator: createSecureSecretParser({\n minLength: 32,\n minUniqueChars: 16,\n minEntropy: 3.5,\n }),\n sensitive: true,\n nextjs: true, // Required for Next.js RSC session validation\n examples: [\n 'my-super-secret-session-key-at-least-32-chars-long',\n 'use-a-cryptographically-secure-random-string-here',\n ],\n }),\n },\n\n SPFN_AUTH_SESSION_TTL: {\n ...envString({\n description: 'Session TTL (time to live) - supports duration strings like \\'7d\\', \\'12h\\', \\'45m\\'',\n default: '7d',\n required: false,\n nextjs: true, // May be needed for session validation in Next.js RSC\n examples: ['7d', '30d', '12h', '45m', '3600'],\n }),\n },\n\n // ============================================================================\n // JWT Configuration\n // ============================================================================\n SPFN_AUTH_JWT_SECRET: {\n ...envString({\n description: 'JWT signing secret for server-signed tokens (legacy mode)',\n default: 'dev-secret-key-change-in-production',\n required: false,\n examples: [\n 'your-jwt-secret-key-here',\n 'use-different-from-session-secret',\n ],\n }),\n },\n\n SPFN_AUTH_JWT_EXPIRES_IN: {\n ...envString({\n description: 'JWT token expiration time (e.g., \\'7d\\', \\'24h\\', \\'1h\\')',\n default: '7d',\n required: false,\n examples: ['7d', '24h', '1h', '30m'],\n }),\n },\n\n // ============================================================================\n // Security Configuration\n // ============================================================================\n SPFN_AUTH_BCRYPT_SALT_ROUNDS: {\n ...envNumber({\n description: 'Bcrypt salt rounds (cost factor, higher = more secure but slower)',\n default: 10,\n required: false,\n examples: [10, 12, 14],\n }),\n key: 'SPFN_AUTH_BCRYPT_SALT_ROUNDS',\n },\n\n SPFN_AUTH_VERIFICATION_TOKEN_SECRET: {\n ...envString({\n description: 'Verification token secret for email verification, password reset, etc.',\n required: true,\n examples: [\n 'your-verification-token-secret',\n 'can-be-different-from-jwt-secret',\n ],\n }),\n },\n\n // ============================================================================\n // Admin Account Configuration\n // ============================================================================\n SPFN_AUTH_ADMIN_ACCOUNTS: {\n ...envString({\n description: 'JSON array of admin accounts (recommended for multiple admins)',\n required: false,\n examples: [\n '[{\"email\":\"admin@example.com\",\"password\":\"secure-pass\",\"role\":\"admin\"}]',\n '[{\"email\":\"super@example.com\",\"password\":\"pass1\",\"role\":\"superadmin\"},{\"email\":\"admin@example.com\",\"password\":\"pass2\",\"role\":\"admin\"}]',\n ],\n }),\n },\n\n SPFN_AUTH_ADMIN_EMAILS: {\n ...envString({\n description: 'Comma-separated list of admin emails (legacy CSV format)',\n required: false,\n examples: [\n 'admin@example.com,user@example.com',\n 'super@example.com,admin@example.com,user@example.com',\n ],\n }),\n },\n\n SPFN_AUTH_ADMIN_PASSWORDS: {\n ...envString({\n description: 'Comma-separated list of admin passwords (legacy CSV format)',\n required: false,\n examples: [\n 'admin-pass,user-pass',\n 'super-pass,admin-pass,user-pass',\n ],\n }),\n },\n\n SPFN_AUTH_ADMIN_ROLES: {\n ...envString({\n description: 'Comma-separated list of admin roles (legacy CSV format)',\n required: false,\n examples: [\n 'admin,user',\n 'superadmin,admin,user',\n ],\n }),\n },\n\n SPFN_AUTH_ADMIN_EMAIL: {\n ...envString({\n description: 'Single admin email (simplest format)',\n required: false,\n examples: ['admin@example.com'],\n }),\n },\n\n SPFN_AUTH_ADMIN_PASSWORD: {\n ...envString({\n description: 'Single admin password (simplest format)',\n required: false,\n validator: createPasswordParser({\n minLength: 8,\n requireUppercase: true,\n requireLowercase: true,\n requireNumber: true,\n requireSpecial: true,\n }),\n sensitive: true,\n examples: ['SecureAdmin123!'],\n }),\n },\n\n // ============================================================================\n // API Configuration\n // ============================================================================\n SPFN_API_URL: {\n ...envString({\n description: 'Base API URL for invitation links and other external-facing URLs',\n default: 'http://localhost:8790',\n required: false,\n examples: [\n 'https://api.example.com',\n 'http://localhost:8790',\n ],\n }),\n },\n\n // ============================================================================\n // AWS SNS Configuration (SMS)\n // ============================================================================\n SPFN_AUTH_AWS_REGION: {\n ...envString({\n description: 'AWS region for SNS service',\n default: 'ap-northeast-2',\n required: false,\n examples: ['ap-northeast-2', 'us-east-1', 'eu-west-1'],\n }),\n },\n\n SPFN_AUTH_AWS_SNS_ACCESS_KEY_ID: {\n ...envString({\n description: 'AWS SNS access key ID (optional, uses default credentials chain if not provided)',\n required: false,\n sensitive: true,\n examples: ['AKIAIOSFODNN7EXAMPLE'],\n }),\n },\n\n SPFN_AUTH_AWS_SNS_SECRET_ACCESS_KEY: {\n ...envString({\n description: 'AWS SNS secret access key (optional, uses default credentials chain if not provided)',\n required: false,\n sensitive: true,\n examples: ['wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY'],\n }),\n },\n\n SPFN_AUTH_AWS_SNS_SENDER_ID: {\n ...envString({\n description: 'SMS sender ID displayed to recipients (max 11 characters, alphanumeric)',\n required: false,\n examples: ['MyApp', 'YourBrand'],\n }),\n },\n\n // ============================================================================\n // AWS SES Configuration (Email)\n // ============================================================================\n SPFN_AUTH_AWS_SES_ACCESS_KEY_ID: {\n ...envString({\n description: 'AWS SES access key ID (optional, uses default credentials chain if not provided)',\n required: false,\n sensitive: true,\n examples: ['AKIAIOSFODNN7EXAMPLE'],\n }),\n },\n\n SPFN_AUTH_AWS_SES_SECRET_ACCESS_KEY: {\n ...envString({\n description: 'AWS SES secret access key (optional, uses default credentials chain if not provided)',\n required: false,\n sensitive: true,\n examples: ['wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY'],\n }),\n },\n\n SPFN_AUTH_AWS_SES_FROM_EMAIL: {\n ...envString({\n description: 'Sender email address (must be verified in AWS SES)',\n required: false,\n examples: ['noreply@example.com', 'auth@yourdomain.com'],\n }),\n },\n\n SPFN_AUTH_AWS_SES_FROM_NAME: {\n ...envString({\n description: 'Sender display name',\n required: false,\n examples: ['MyApp', 'Your Company'],\n }),\n },\n\n SPFN_APP_URL: {\n ...envString({\n description: 'Next.js application URL. Used for OAuth callback redirects.',\n default: 'http://localhost:3000',\n required: false,\n examples: [\n 'https://app.example.com',\n 'http://localhost:3000',\n ],\n }),\n },\n\n // ============================================================================\n // OAuth Configuration - Google\n // ============================================================================\n SPFN_AUTH_GOOGLE_CLIENT_ID: {\n ...envString({\n description: 'Google OAuth 2.0 Client ID. When set, Google OAuth routes are automatically enabled.',\n required: false,\n examples: ['123456789-abc123.apps.googleusercontent.com'],\n }),\n },\n\n SPFN_AUTH_GOOGLE_CLIENT_SECRET: {\n ...envString({\n description: 'Google OAuth 2.0 Client Secret',\n required: false,\n sensitive: true,\n examples: ['GOCSPX-abcdefghijklmnop'],\n }),\n },\n\n SPFN_AUTH_GOOGLE_SCOPES: {\n ...envString({\n description: 'Comma-separated Google OAuth scopes. Defaults to \"email,profile\" if not set.',\n required: false,\n examples: [\n 'email,profile',\n 'email,profile,https://www.googleapis.com/auth/gmail.readonly',\n 'email,profile,https://www.googleapis.com/auth/calendar.readonly',\n ],\n }),\n },\n\n SPFN_AUTH_GOOGLE_REDIRECT_URI: {\n ...envString({\n description: 'Google OAuth callback URL. Defaults to {SPFN_API_URL}/_auth/oauth/google/callback',\n required: false,\n examples: [\n 'https://api.example.com/_auth/oauth/google/callback',\n 'http://localhost:8790/_auth/oauth/google/callback',\n ],\n }),\n },\n\n SPFN_AUTH_OAUTH_SUCCESS_URL: {\n ...envString({\n description: 'OAuth callback page URL. This page should use OAuthCallback component to finalize session.',\n required: false,\n default: '/auth/callback',\n examples: [\n '/auth/callback',\n 'https://app.example.com/auth/callback',\n ],\n }),\n },\n\n SPFN_AUTH_OAUTH_ERROR_URL: {\n ...envString({\n description: 'URL to redirect after OAuth error. Use {error} placeholder for error message.',\n required: false,\n default: 'http://localhost:3000/auth/error?error={error}',\n examples: [\n 'https://app.example.com/auth/error?error={error}',\n 'http://localhost:3000/auth/error?error={error}',\n ],\n }),\n },\n});"],"mappings":";AAcA,SAAS,yBAAyB;;;ACLlC;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AAoBA,IAAM,gBAAgB,gBAAgB;AAAA;AAAA;AAAA;AAAA,EAIzC,0BAA0B;AAAA,IACtB,GAAG,UAAU;AAAA,MACT,aAAa;AAAA,MACb,UAAU;AAAA,MACV,cAAc,CAAC,gBAAgB;AAAA,MAC/B,WAAW,yBAAyB;AAAA,QAChC,WAAW;AAAA,QACX,gBAAgB;AAAA,QAChB,YAAY;AAAA,MAChB,CAAC;AAAA,MACD,WAAW;AAAA,MACX,QAAQ;AAAA;AAAA,MACR,UAAU;AAAA,QACN;AAAA,QACA;AAAA,MACJ;AAAA,IACJ,CAAC;AAAA,EACL;AAAA,EAEA,uBAAuB;AAAA,I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A,MACV,UAAU,CAAC,6CAA6C;AAAA,IAC5D,CAAC;AAAA,EACL;AAAA,EAEA,gCAAgC;AAAA,IAC5B,GAAG,UAAU;AAAA,MACT,aAAa;AAAA,MACb,UAAU;AAAA,MACV,WAAW;AAAA,MACX,UAAU,CAAC,yBAAyB;AAAA,IACxC,CAAC;AAAA,EACL;AAAA,EAEA,yBAAyB;AAAA,IACrB,GAAG,UAAU;AAAA,MACT,aAAa;AAAA,MACb,UAAU;AAAA,MACV,UAAU;AAAA,QACN;AAAA,QACA;AAAA,QACA;AAAA,MACJ;AAAA,IACJ,CAAC;AAAA,EACL;AAAA,EAEA,+BAA+B;AAAA,IAC3B,GAAG,UAAU;AAAA,MACT,aAAa;AAAA,MACb,UAAU;AAAA,MACV,UAAU;AAAA,QACN;AAAA,QACA;AAAA,MACJ;AAAA,IACJ,CAAC;AAAA,EACL;AAAA,EAEA,6BAA6B;AAAA,IACzB,GAAG,UAAU;AAAA,MACT,aAAa;AAAA,MACb,UAAU;AAAA,MACV,SAAS;AAAA,MACT,UAAU;AAAA,QACN;AAAA,QACA;AAAA,MACJ;AAAA,IACJ,CAAC;AAAA,EACL;AAAA,EAEA,2BAA2B;AAAA,IACvB,GAAG,UAAU;AAAA,MACT,aAAa;AAAA,MACb,UAAU;AAAA,MACV,SAAS;AAAA,MACT,UAAU;AAAA,QACN;AAAA,QACA;AAAA,MACJ;AAAA,IACJ,CAAC;AAAA,EACL;AACJ,CAAC;;;AD7UD,IAAM,WAAW,kBAAkB,aAAa;AACzC,IAAM,MAAM,SAAS,SAAS;","names":[]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as _spfn_core_nextjs from '@spfn/core/nextjs';
|
|
2
|
-
import { R as RoleConfig, P as PermissionConfig, C as CheckAccountExistsResult, S as SendVerificationCodeResult, a as RegisterResult, L as LoginResult, b as RotateKeyResult, U as UserProfile, c as ProfileInfo, m as mainAuthRouter } from './authenticate-
|
|
3
|
-
export { k as AuthInitOptions, A as AuthSession, I as INVITATION_STATUSES, n as InvitationStatus, K as KEY_ALGORITHM, l as KeyAlgorithmType, i as PERMISSION_CATEGORIES, j as PermissionCategory, e as SOCIAL_PROVIDERS, p as SocialProvider, d as USER_STATUSES, o as UserStatus, h as VERIFICATION_PURPOSES, g as VERIFICATION_TARGET_TYPES, f as VerificationPurpose, V as VerificationTargetType } from './authenticate-
|
|
2
|
+
import { R as RoleConfig, P as PermissionConfig, C as CheckAccountExistsResult, S as SendVerificationCodeResult, a as RegisterResult, L as LoginResult, b as RotateKeyResult, O as OAuthStartResult, U as UserProfile, c as ProfileInfo, m as mainAuthRouter } from './authenticate-Cz2FjLdB.js';
|
|
3
|
+
export { k as AuthInitOptions, A as AuthSession, I as INVITATION_STATUSES, n as InvitationStatus, K as KEY_ALGORITHM, l as KeyAlgorithmType, i as PERMISSION_CATEGORIES, j as PermissionCategory, e as SOCIAL_PROVIDERS, p as SocialProvider, d as USER_STATUSES, o as UserStatus, h as VERIFICATION_PURPOSES, g as VERIFICATION_TARGET_TYPES, f as VerificationPurpose, V as VerificationTargetType } from './authenticate-Cz2FjLdB.js';
|
|
4
4
|
import * as _spfn_core_route from '@spfn/core/route';
|
|
5
5
|
import { HttpMethod } from '@spfn/core/route';
|
|
6
6
|
import * as _sinclair_typebox from '@sinclair/typebox';
|
|
@@ -175,6 +175,50 @@ declare const authApi: _spfn_core_nextjs.Client<_spfn_core_route.Router<{
|
|
|
175
175
|
emailVerified: boolean;
|
|
176
176
|
phoneVerified: boolean;
|
|
177
177
|
}>;
|
|
178
|
+
oauthGoogleStart: _spfn_core_route.RouteDef<{
|
|
179
|
+
query: _sinclair_typebox.TObject<{
|
|
180
|
+
state: _sinclair_typebox.TString;
|
|
181
|
+
}>;
|
|
182
|
+
}, {}, Response>;
|
|
183
|
+
oauthGoogleCallback: _spfn_core_route.RouteDef<{
|
|
184
|
+
query: _sinclair_typebox.TObject<{
|
|
185
|
+
code: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
186
|
+
state: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
187
|
+
error: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
188
|
+
error_description: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
189
|
+
}>;
|
|
190
|
+
}, {}, Response>;
|
|
191
|
+
oauthStart: _spfn_core_route.RouteDef<{
|
|
192
|
+
body: _sinclair_typebox.TObject<{
|
|
193
|
+
provider: _sinclair_typebox.TUnion<_sinclair_typebox.TLiteral<"google" | "github" | "kakao" | "naver">[]>;
|
|
194
|
+
returnUrl: _sinclair_typebox.TString;
|
|
195
|
+
publicKey: _sinclair_typebox.TString;
|
|
196
|
+
keyId: _sinclair_typebox.TString;
|
|
197
|
+
fingerprint: _sinclair_typebox.TString;
|
|
198
|
+
algorithm: _sinclair_typebox.TUnion<_sinclair_typebox.TLiteral<"ES256" | "RS256">[]>;
|
|
199
|
+
}>;
|
|
200
|
+
}, {}, OAuthStartResult>;
|
|
201
|
+
oauthProviders: _spfn_core_route.RouteDef<{}, {}, {
|
|
202
|
+
providers: ("google" | "github" | "kakao" | "naver")[];
|
|
203
|
+
}>;
|
|
204
|
+
getGoogleOAuthUrl: _spfn_core_route.RouteDef<{
|
|
205
|
+
body: _sinclair_typebox.TObject<{
|
|
206
|
+
returnUrl: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
207
|
+
state: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
208
|
+
}>;
|
|
209
|
+
}, {}, {
|
|
210
|
+
authUrl: string;
|
|
211
|
+
}>;
|
|
212
|
+
oauthFinalize: _spfn_core_route.RouteDef<{
|
|
213
|
+
body: _sinclair_typebox.TObject<{
|
|
214
|
+
userId: _sinclair_typebox.TString;
|
|
215
|
+
keyId: _sinclair_typebox.TString;
|
|
216
|
+
returnUrl: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
217
|
+
}>;
|
|
218
|
+
}, {}, {
|
|
219
|
+
success: boolean;
|
|
220
|
+
returnUrl: string;
|
|
221
|
+
}>;
|
|
178
222
|
getInvitation: _spfn_core_route.RouteDef<{
|
|
179
223
|
params: _sinclair_typebox.TObject<{
|
|
180
224
|
token: _sinclair_typebox.TString;
|
package/dist/nextjs/api.js
CHANGED
|
@@ -333,10 +333,196 @@ var keyRotationInterceptor = {
|
|
|
333
333
|
}
|
|
334
334
|
};
|
|
335
335
|
|
|
336
|
+
// src/nextjs/interceptors/oauth.ts
|
|
337
|
+
import {
|
|
338
|
+
generateKeyPair as generateKeyPair3,
|
|
339
|
+
createOAuthState,
|
|
340
|
+
sealSession as sealSession5,
|
|
341
|
+
COOKIE_NAMES as COOKIE_NAMES5,
|
|
342
|
+
getSessionTtl as getSessionTtl5,
|
|
343
|
+
authLogger as authLogger4
|
|
344
|
+
} from "@spfn/auth/server";
|
|
345
|
+
|
|
346
|
+
// src/nextjs/session-helpers.ts
|
|
347
|
+
import * as jose from "jose";
|
|
348
|
+
import { cookies } from "next/headers.js";
|
|
349
|
+
import {
|
|
350
|
+
sealSession as sealSession4,
|
|
351
|
+
unsealSession as unsealSession3,
|
|
352
|
+
COOKIE_NAMES as COOKIE_NAMES4,
|
|
353
|
+
getSessionTtl as getSessionTtl4,
|
|
354
|
+
parseDuration
|
|
355
|
+
} from "@spfn/auth/server";
|
|
356
|
+
import { env as env3 } from "@spfn/auth/config";
|
|
357
|
+
import { logger } from "@spfn/core/logger";
|
|
358
|
+
async function getPendingSessionKey() {
|
|
359
|
+
const secret = env3.SPFN_AUTH_SESSION_SECRET;
|
|
360
|
+
const encoder = new TextEncoder();
|
|
361
|
+
const data = encoder.encode(`oauth-pending:${secret}`);
|
|
362
|
+
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
|
|
363
|
+
return new Uint8Array(hashBuffer);
|
|
364
|
+
}
|
|
365
|
+
async function sealPendingSession(data, ttl = 600) {
|
|
366
|
+
const key = await getPendingSessionKey();
|
|
367
|
+
return await new jose.EncryptJWT({ data }).setProtectedHeader({ alg: "dir", enc: "A256GCM" }).setIssuedAt().setExpirationTime(`${ttl}s`).setIssuer("spfn-auth").setAudience("spfn-oauth").encrypt(key);
|
|
368
|
+
}
|
|
369
|
+
async function unsealPendingSession(jwt) {
|
|
370
|
+
const key = await getPendingSessionKey();
|
|
371
|
+
const { payload } = await jose.jwtDecrypt(jwt, key, {
|
|
372
|
+
issuer: "spfn-auth",
|
|
373
|
+
audience: "spfn-oauth"
|
|
374
|
+
});
|
|
375
|
+
return payload.data;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
// src/nextjs/interceptors/oauth.ts
|
|
379
|
+
import { env as env4 } from "@spfn/core/config";
|
|
380
|
+
var oauthUrlInterceptor = {
|
|
381
|
+
pathPattern: /^\/_auth\/oauth\/\w+\/url$/,
|
|
382
|
+
method: "POST",
|
|
383
|
+
request: async (ctx, next) => {
|
|
384
|
+
const provider = ctx.path.split("/")[3];
|
|
385
|
+
const returnUrl = ctx.body?.returnUrl || "/";
|
|
386
|
+
const keyPair = generateKeyPair3("ES256");
|
|
387
|
+
const state = await createOAuthState({
|
|
388
|
+
provider,
|
|
389
|
+
returnUrl,
|
|
390
|
+
publicKey: keyPair.publicKey,
|
|
391
|
+
keyId: keyPair.keyId,
|
|
392
|
+
fingerprint: keyPair.fingerprint,
|
|
393
|
+
algorithm: keyPair.algorithm
|
|
394
|
+
});
|
|
395
|
+
if (!ctx.body) {
|
|
396
|
+
ctx.body = {};
|
|
397
|
+
}
|
|
398
|
+
ctx.body.state = state;
|
|
399
|
+
ctx.metadata.pendingSession = {
|
|
400
|
+
privateKey: keyPair.privateKey,
|
|
401
|
+
keyId: keyPair.keyId,
|
|
402
|
+
algorithm: keyPair.algorithm
|
|
403
|
+
};
|
|
404
|
+
authLogger4.interceptor.oauth?.debug?.("OAuth state created", {
|
|
405
|
+
provider,
|
|
406
|
+
keyId: keyPair.keyId
|
|
407
|
+
});
|
|
408
|
+
await next();
|
|
409
|
+
},
|
|
410
|
+
response: async (ctx, next) => {
|
|
411
|
+
if (ctx.response.ok && ctx.metadata.pendingSession) {
|
|
412
|
+
try {
|
|
413
|
+
const sealed = await sealPendingSession(ctx.metadata.pendingSession);
|
|
414
|
+
ctx.setCookies.push({
|
|
415
|
+
name: COOKIE_NAMES5.OAUTH_PENDING,
|
|
416
|
+
value: sealed,
|
|
417
|
+
options: {
|
|
418
|
+
httpOnly: true,
|
|
419
|
+
secure: env4.NODE_ENV === "production",
|
|
420
|
+
sameSite: "lax",
|
|
421
|
+
// OAuth 리다이렉트 허용
|
|
422
|
+
maxAge: 600,
|
|
423
|
+
// 10분
|
|
424
|
+
path: "/"
|
|
425
|
+
}
|
|
426
|
+
});
|
|
427
|
+
authLogger4.interceptor.oauth?.debug?.("Pending session cookie set", {
|
|
428
|
+
keyId: ctx.metadata.pendingSession.keyId
|
|
429
|
+
});
|
|
430
|
+
} catch (error) {
|
|
431
|
+
const err = error;
|
|
432
|
+
authLogger4.interceptor.oauth?.error?.("Failed to set pending session", err);
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
await next();
|
|
436
|
+
}
|
|
437
|
+
};
|
|
438
|
+
var oauthFinalizeInterceptor = {
|
|
439
|
+
pathPattern: /^\/_auth\/oauth\/finalize$/,
|
|
440
|
+
method: "POST",
|
|
441
|
+
response: async (ctx, next) => {
|
|
442
|
+
if (!ctx.response.ok) {
|
|
443
|
+
await next();
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
const pendingCookie = ctx.cookies.get(COOKIE_NAMES5.OAUTH_PENDING);
|
|
447
|
+
if (!pendingCookie) {
|
|
448
|
+
authLogger4.interceptor.oauth?.warn?.("No pending session cookie found");
|
|
449
|
+
await next();
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
try {
|
|
453
|
+
const pendingSession = await unsealPendingSession(pendingCookie);
|
|
454
|
+
const { userId, keyId } = ctx.response.body || {};
|
|
455
|
+
if (!userId || !keyId) {
|
|
456
|
+
authLogger4.interceptor.oauth?.error?.("Missing userId or keyId in response");
|
|
457
|
+
await next();
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
if (pendingSession.keyId !== keyId) {
|
|
461
|
+
authLogger4.interceptor.oauth?.error?.("KeyId mismatch", {
|
|
462
|
+
expected: pendingSession.keyId,
|
|
463
|
+
received: keyId
|
|
464
|
+
});
|
|
465
|
+
await next();
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
468
|
+
const ttl = getSessionTtl5();
|
|
469
|
+
const sessionToken = await sealSession5({
|
|
470
|
+
userId,
|
|
471
|
+
privateKey: pendingSession.privateKey,
|
|
472
|
+
keyId: pendingSession.keyId,
|
|
473
|
+
algorithm: pendingSession.algorithm
|
|
474
|
+
}, ttl);
|
|
475
|
+
ctx.setCookies.push({
|
|
476
|
+
name: COOKIE_NAMES5.SESSION,
|
|
477
|
+
value: sessionToken,
|
|
478
|
+
options: {
|
|
479
|
+
httpOnly: true,
|
|
480
|
+
secure: env4.NODE_ENV === "production",
|
|
481
|
+
sameSite: "strict",
|
|
482
|
+
maxAge: ttl,
|
|
483
|
+
path: "/"
|
|
484
|
+
}
|
|
485
|
+
});
|
|
486
|
+
ctx.setCookies.push({
|
|
487
|
+
name: COOKIE_NAMES5.SESSION_KEY_ID,
|
|
488
|
+
value: keyId,
|
|
489
|
+
options: {
|
|
490
|
+
httpOnly: true,
|
|
491
|
+
secure: env4.NODE_ENV === "production",
|
|
492
|
+
sameSite: "strict",
|
|
493
|
+
maxAge: ttl,
|
|
494
|
+
path: "/"
|
|
495
|
+
}
|
|
496
|
+
});
|
|
497
|
+
ctx.setCookies.push({
|
|
498
|
+
name: COOKIE_NAMES5.OAUTH_PENDING,
|
|
499
|
+
value: "",
|
|
500
|
+
options: {
|
|
501
|
+
httpOnly: true,
|
|
502
|
+
secure: env4.NODE_ENV === "production",
|
|
503
|
+
sameSite: "lax",
|
|
504
|
+
maxAge: 0,
|
|
505
|
+
path: "/"
|
|
506
|
+
}
|
|
507
|
+
});
|
|
508
|
+
authLogger4.interceptor.oauth?.debug?.("OAuth session finalized", {
|
|
509
|
+
userId,
|
|
510
|
+
keyId
|
|
511
|
+
});
|
|
512
|
+
} catch (error) {
|
|
513
|
+
const err = error;
|
|
514
|
+
authLogger4.interceptor.oauth?.error?.("Failed to finalize OAuth session", err);
|
|
515
|
+
}
|
|
516
|
+
await next();
|
|
517
|
+
}
|
|
518
|
+
};
|
|
519
|
+
|
|
336
520
|
// src/nextjs/interceptors/index.ts
|
|
337
521
|
var authInterceptors = [
|
|
338
522
|
loginRegisterInterceptor,
|
|
339
523
|
keyRotationInterceptor,
|
|
524
|
+
oauthUrlInterceptor,
|
|
525
|
+
oauthFinalizeInterceptor,
|
|
340
526
|
generalAuthInterceptor
|
|
341
527
|
];
|
|
342
528
|
|
package/dist/nextjs/api.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/nextjs/api.ts","../../src/nextjs/interceptors/login-register.ts","../../src/nextjs/interceptors/general-auth.ts","../../src/nextjs/interceptors/key-rotation.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 * Login/Register Interceptor\n *\n * Automatically handles key generation and session management\n * for login and register endpoints\n */\n\nimport type { InterceptorRule } from '@spfn/core/nextjs';\nimport { generateKeyPair, sealSession, getSessionTtl, COOKIE_NAMES, authLogger } from '@spfn/auth/server';\nimport { env } from '@spfn/core/config';\n\n/**\n * Login and Register 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)$/,\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 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 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: env.NODE_ENV === 'production',\n sameSite: 'strict',\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: env.NODE_ENV === 'production',\n sameSite: 'strict',\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 * 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';\nimport { unsealSession, sealSession, shouldRefreshSession, generateClientToken, getSessionTtl, COOKIE_NAMES, authLogger } from '@spfn/auth/server';\nimport { env } from '@spfn/core/config';\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 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 sessionCookieValue: sessionCookie ? '***EXISTS***' : 'NOT_FOUND',\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 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\n // Session expired or invalid\n if (err.message.includes('expired') || err.message.includes('invalid'))\n {\n authLogger.interceptor.general.warn('Session expired or invalid', { message: err.message });\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 // 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: env.NODE_ENV === 'production',\n sameSite: 'strict',\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: process.env.NODE_ENV === 'production',\n sameSite: 'strict',\n maxAge: ttl,\n path: '/',\n },\n });\n\n authLogger.interceptor.general.info('Session refreshed', { userId: sessionData.userId });\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 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\n await next();\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';\nimport { generateKeyPair, unsealSession, sealSession, generateClientToken, getSessionTtl, COOKIE_NAMES, authLogger } from '@spfn/auth/server';\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 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 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 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: process.env.NODE_ENV === 'production',\n sameSite: 'strict',\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: process.env.NODE_ENV === 'production',\n sameSite: 'strict',\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 * Auth Interceptors for Next.js Proxy\n *\n * Automatically registers interceptors for authentication flow\n *\n * Order matters - more specific interceptors first:\n * 1. loginRegisterInterceptor - Most specific (login/register only)\n * 2. keyRotationInterceptor - Specific (key rotation only)\n * 3. generalAuthInterceptor - General (all authenticated requests)\n */\n\nimport { loginRegisterInterceptor } from './login-register';\nimport { generalAuthInterceptor } from './general-auth';\nimport { keyRotationInterceptor } from './key-rotation';\n\n/**\n * All auth interceptors\n *\n * Execution order:\n * 1. loginRegisterInterceptor - Handles login/register (key generation + session save)\n * 2. keyRotationInterceptor - Handles key rotation (new key generation + session update)\n * 3. generalAuthInterceptor - Handles all authenticated requests (session validation + JWT injection + session renewal)\n */\nexport const authInterceptors = [\n loginRegisterInterceptor,\n keyRotationInterceptor,\n generalAuthInterceptor,\n];\n\nexport { loginRegisterInterceptor } from './login-register';\nexport { generalAuthInterceptor } from './general-auth';\nexport { keyRotationInterceptor } from './key-rotation';\n\n// Deprecated: use generalAuthInterceptor instead\nexport { generalAuthInterceptor as authenticationInterceptor };"],"mappings":";AAoBA,SAAS,4BAA4B;;;ACZrC,SAAS,iBAAiB,aAAa,eAAe,cAAc,kBAAkB;AACtF,SAAS,WAAW;AAQb,IAAM,2BACT;AAAA,EACI,aAAa;AAAA,EACb,QAAQ;AAAA,EAER,SAAS,OAAO,KAAK,SACrB;AAEI,UAAM,WAAW,IAAI,QAAQ,IAAI,aAAa,cAAc;AAG5D,UAAM,WAAW,IAAI,MAAM;AAG3B,UAAM,UAAU,gBAAgB,OAAO;AAGvC,QAAI,CAAC,IAAI,MACT;AACI,UAAI,OAAO,CAAC;AAAA,IAChB;AAEA,QAAI,KAAK,YAAY,QAAQ;AAC7B,QAAI,KAAK,QAAQ,QAAQ;AACzB,QAAI,KAAK,cAAc,QAAQ;AAC/B,QAAI,KAAK,YAAY,QAAQ;AAC7B,QAAI,KAAK,UAAU,OAAO,KAAK,QAAQ,WAAW,QAAQ,EAAE;AAG5D,QAAI,IAAI,SAAS,kBAAkB,UACnC;AACI,UAAI,KAAK,WAAW;AAAA,IACxB;AAGA,WAAO,IAAI,KAAK;AAGhB,QAAI,SAAS,aAAa,QAAQ;AAClC,QAAI,SAAS,QAAQ,QAAQ;AAC7B,QAAI,SAAS,YAAY,QAAQ;AACjC,QAAI,SAAS,WAAW;AAExB,UAAM,KAAK;AAAA,EACf;AAAA,EAEA,UAAU,OAAO,KAAK,SACtB;AAEI,QAAI,IAAI,SAAS,WAAW,KAC5B;AACI,YAAM,KAAK;AACX;AAAA,IACJ;AAGA,UAAM,WAAW,IAAI,SAAS,MAAM,QAAQ,IAAI,SAAS;AACzD,QAAI,CAAC,UAAU,QACf;AACI,iBAAW,YAAY,MAAM,MAAM,uBAAuB;AAC1D,YAAM,KAAK;AACX;AAAA,IACJ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A,YAAW,YAAY,YAAY,MAAM,+BAA+B;AACxE,YAAM,KAAK;AACX;AAAA,IACJ;AAEA,QACA;AAEI,YAAM,MAAMF,eAAc;AAG1B,YAAM,iBACN;AAAA,QACI,QAAQ,IAAI,SAAS;AAAA,QACrB,YAAY,IAAI,SAAS;AAAA,QACzB,OAAO,IAAI,SAAS;AAAA,QACpB,WAAW,IAAI,SAAS;AAAA,MAC5B;AAEA,YAAM,SAAS,MAAMF,aAAY,gBAAgB,GAAG;AAGpD,UAAI,WAAW,KAAK;AAAA,QAChB,MAAMG,cAAa;AAAA,QACnB,OAAO;AAAA,QACP,SAAS;AAAA,UACL,UAAU;AAAA,UACV,QAAQ,QAAQ,IAAI,aAAa;AAAA,UACjC,UAAU;AAAA,UACV,QAAQ;AAAA,UACR,MAAM;AAAA,QACV;AAAA,MACJ,CAAC;AAGD,UAAI,WAAW,KAAK;AAAA,QAChB,MAAMA,cAAa;AAAA,QACnB,OAAO,IAAI,SAAS;AAAA,QACpB,SAAS;AAAA,UACL,UAAU;AAAA,UACV,QAAQ,QAAQ,IAAI,aAAa;AAAA,UACjC,UAAU;AAAA,UACV,QAAQ;AAAA,UACR,MAAM;AAAA,QACV;AAAA,MACJ,CAAC;AAAA,IACL,SACO,OACP;AACI,YAAM,MAAM;AACZ,MAAAC,YAAW,YAAY,YAAY,MAAM,2CAA2C,GAAG;AAAA,IAC3F;AAEA,UAAM,KAAK;AAAA,EACf;AACJ;;;ACjIO,IAAM,mBAAmB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AACJ;;;AJHA,qBAAqB,QAAQ,gBAAgB;","names":["sealSession","getSessionTtl","COOKIE_NAMES","authLogger","env","generateKeyPair","unsealSession","sealSession","generateClientToken","getSessionTtl","COOKIE_NAMES","authLogger"]}
|
|
1
|
+
{"version":3,"sources":["../../src/nextjs/api.ts","../../src/nextjs/interceptors/login-register.ts","../../src/nextjs/interceptors/general-auth.ts","../../src/nextjs/interceptors/key-rotation.ts","../../src/nextjs/interceptors/oauth.ts","../../src/nextjs/session-helpers.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 * Login/Register Interceptor\n *\n * Automatically handles key generation and session management\n * for login and register endpoints\n */\n\nimport type { InterceptorRule } from '@spfn/core/nextjs';\nimport { generateKeyPair, sealSession, getSessionTtl, COOKIE_NAMES, authLogger } from '@spfn/auth/server';\nimport { env } from '@spfn/core/config';\n\n/**\n * Login and Register 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)$/,\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 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 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: env.NODE_ENV === 'production',\n sameSite: 'strict',\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: env.NODE_ENV === 'production',\n sameSite: 'strict',\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 * 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';\nimport { unsealSession, sealSession, shouldRefreshSession, generateClientToken, getSessionTtl, COOKIE_NAMES, authLogger } from '@spfn/auth/server';\nimport { env } from '@spfn/core/config';\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 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 sessionCookieValue: sessionCookie ? '***EXISTS***' : 'NOT_FOUND',\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 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\n // Session expired or invalid\n if (err.message.includes('expired') || err.message.includes('invalid'))\n {\n authLogger.interceptor.general.warn('Session expired or invalid', { message: err.message });\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 // 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: env.NODE_ENV === 'production',\n sameSite: 'strict',\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: process.env.NODE_ENV === 'production',\n sameSite: 'strict',\n maxAge: ttl,\n path: '/',\n },\n });\n\n authLogger.interceptor.general.info('Session refreshed', { userId: sessionData.userId });\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 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\n await next();\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';\nimport { generateKeyPair, unsealSession, sealSession, generateClientToken, getSessionTtl, COOKIE_NAMES, authLogger } from '@spfn/auth/server';\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 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 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 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: process.env.NODE_ENV === 'production',\n sameSite: 'strict',\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: process.env.NODE_ENV === 'production',\n sameSite: 'strict',\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 * OAuth Interceptors\n *\n * 1. oauthUrlInterceptor: OAuth URL 요청 시 키쌍 생성 및 state 주입\n * 2. oauthFinalizeInterceptor: OAuth 완료 시 pending session에서 세션 저장\n */\n\nimport type { InterceptorRule } from '@spfn/core/nextjs';\nimport {\n generateKeyPair,\n createOAuthState,\n sealSession,\n COOKIE_NAMES,\n getSessionTtl,\n authLogger,\n} from '@spfn/auth/server';\nimport { sealPendingSession, unsealPendingSession } from '../session-helpers';\nimport { env } from '@spfn/core/config';\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\n // 키쌍 생성\n const keyPair = generateKeyPair('ES256');\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 });\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\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: env.NODE_ENV === 'production',\n sameSite: 'lax', // OAuth 리다이렉트 허용\n maxAge: 600, // 10분\n path: '/',\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 * 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 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 await next();\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 await next();\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 await next();\n return;\n }\n\n // 세션 생성\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: env.NODE_ENV === 'production',\n sameSite: 'strict',\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: env.NODE_ENV === 'production',\n sameSite: 'strict',\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: env.NODE_ENV === 'production',\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 }\n\n await next();\n },\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 {\n sealSession,\n unsealSession,\n COOKIE_NAMES,\n getSessionTtl,\n parseDuration,\n type SessionData,\n type KeyAlgorithmType,\n} from '@spfn/auth/server';\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: 'strict',\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 logger.debug('Validating session cookie', { cookie: sessionCookie.value });\n const session = await unsealSession(sessionCookie.value);\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 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 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 * Auth Interceptors for Next.js Proxy\n *\n * Automatically registers interceptors for authentication flow\n *\n * Order matters - more specific interceptors first:\n * 1. loginRegisterInterceptor - Most specific (login/register only)\n * 2. keyRotationInterceptor - Specific (key rotation only)\n * 3. oauthUrlInterceptor - OAuth URL generation (key generation + state injection)\n * 4. 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';\n\n/**\n * All auth interceptors\n *\n * Execution order:\n * 1. loginRegisterInterceptor - Handles login/register (key generation + session save)\n * 2. keyRotationInterceptor - Handles key rotation (new key generation + session update)\n * 3. oauthUrlInterceptor - Handles OAuth URL requests (key generation + state injection + pending session)\n * 4. oauthFinalizeInterceptor - Handles OAuth finalize (pending session → full session)\n * 5. generalAuthInterceptor - Handles all authenticated requests (session validation + JWT injection + session renewal)\n */\nexport const authInterceptors = [\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';\n\n// Deprecated: use generalAuthInterceptor instead\nexport { generalAuthInterceptor as authenticationInterceptor };"],"mappings":";AAoBA,SAAS,4BAA4B;;;ACZrC,SAAS,iBAAiB,aAAa,eAAe,cAAc,kBAAkB;AACtF,SAAS,WAAW;AAQb,IAAM,2BACT;AAAA,EACI,aAAa;AAAA,EACb,QAAQ;AAAA,EAER,SAAS,OAAO,KAAK,SACrB;AAEI,UAAM,WAAW,IAAI,QAAQ,IAAI,aAAa,cAAc;AAG5D,UAAM,WAAW,IAAI,MAAM;AAG3B,UAAM,UAAU,gBAAgB,OAAO;AAG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AI,WAAW,KAAK;AAAA,QAChB,MAAMF,cAAa;AAAA,QACnB,OAAO;AAAA,QACP,SAAS;AAAA,UACL,UAAU;AAAA,UACV,QAAQH,KAAI,aAAa;AAAA,UACzB,UAAU;AAAA,UACV,QAAQ;AAAA,UACR,MAAM;AAAA,QACV;AAAA,MACJ,CAAC;AAGD,UAAI,WAAW,KAAK;AAAA,QAChB,MAAMG,cAAa;AAAA,QACnB,OAAO;AAAA,QACP,SAAS;AAAA,UACL,UAAU;AAAA,UACV,QAAQH,KAAI,aAAa;AAAA,UACzB,UAAU;AAAA,UACV,QAAQ;AAAA,UACR,MAAM;AAAA,QACV;AAAA,MACJ,CAAC;AAGD,UAAI,WAAW,KAAK;AAAA,QAChB,MAAMG,cAAa;AAAA,QACnB,OAAO;AAAA,QACP,SAAS;AAAA,UACL,UAAU;AAAA,UACV,QAAQH,KAAI,aAAa;AAAA,UACzB,UAAU;AAAA,UACV,QAAQ;AAAA,UACR,MAAM;AAAA,QACV;AAAA,MACJ,CAAC;AAED,MAAAE,YAAW,YAAY,OAAO,QAAQ,2BAA2B;AAAA,QAC7D;AAAA,QACA;AAAA,MACJ,CAAC;AAAA,IACL,SACO,OACP;AACI,YAAM,MAAM;AACZ,MAAAA,YAAW,YAAY,OAAO,QAAQ,oCAAoC,GAAG;AAAA,IACjF;AAEA,UAAM,KAAK;AAAA,EACf;AACJ;;;AEhMO,IAAM,mBAAmB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACJ;;;ANTA,qBAAqB,QAAQ,gBAAgB;","names":["sealSession","getSessionTtl","COOKIE_NAMES","authLogger","env","generateKeyPair","unsealSession","sealSession","generateClientToken","getSessionTtl","COOKIE_NAMES","authLogger","generateKeyPair","sealSession","COOKIE_NAMES","getSessionTtl","authLogger","sealSession","unsealSession","COOKIE_NAMES","getSessionTtl","env","env","env","generateKeyPair","authLogger","COOKIE_NAMES","getSessionTtl","sealSession"]}
|