@spfn/auth 0.2.0-beta.3 → 0.2.0-beta.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/config.d.ts +4 -0
- package/dist/config.js +4 -0
- package/dist/config.js.map +1 -1
- package/dist/{dto-CLYtuAom.d.ts → dto-Bb2qFUO6.d.ts} +23 -4
- package/dist/index.d.ts +24 -6
- package/dist/nextjs/server.js +0 -1
- package/dist/nextjs/server.js.map +1 -1
- package/dist/server.d.ts +136 -5
- package/dist/server.js +166 -4
- package/dist/server.js.map +1 -1
- package/package.json +5 -5
package/dist/config.d.ts
CHANGED
|
@@ -33,6 +33,7 @@ declare const authEnvSchema: {
|
|
|
33
33
|
fallbackKeys: string[];
|
|
34
34
|
validator: _spfn_core_env.Parser<string>;
|
|
35
35
|
sensitive: boolean;
|
|
36
|
+
nextjs: boolean;
|
|
36
37
|
examples: string[];
|
|
37
38
|
type: "string";
|
|
38
39
|
} & {
|
|
@@ -42,6 +43,7 @@ declare const authEnvSchema: {
|
|
|
42
43
|
description: string;
|
|
43
44
|
default: string;
|
|
44
45
|
required: boolean;
|
|
46
|
+
nextjs: boolean;
|
|
45
47
|
examples: string[];
|
|
46
48
|
type: "string";
|
|
47
49
|
} & {
|
|
@@ -221,6 +223,7 @@ declare const env: _spfn_core_env.InferEnvType<{
|
|
|
221
223
|
fallbackKeys: string[];
|
|
222
224
|
validator: _spfn_core_env.Parser<string>;
|
|
223
225
|
sensitive: boolean;
|
|
226
|
+
nextjs: boolean;
|
|
224
227
|
examples: string[];
|
|
225
228
|
type: "string";
|
|
226
229
|
} & {
|
|
@@ -230,6 +233,7 @@ declare const env: _spfn_core_env.InferEnvType<{
|
|
|
230
233
|
description: string;
|
|
231
234
|
default: string;
|
|
232
235
|
required: boolean;
|
|
236
|
+
nextjs: boolean;
|
|
233
237
|
examples: string[];
|
|
234
238
|
type: "string";
|
|
235
239
|
} & {
|
package/dist/config.js
CHANGED
|
@@ -24,6 +24,8 @@ var authEnvSchema = defineEnvSchema({
|
|
|
24
24
|
minEntropy: 3.5
|
|
25
25
|
}),
|
|
26
26
|
sensitive: true,
|
|
27
|
+
nextjs: true,
|
|
28
|
+
// Required for Next.js RSC session validation
|
|
27
29
|
examples: [
|
|
28
30
|
"my-super-secret-session-key-at-least-32-chars-long",
|
|
29
31
|
"use-a-cryptographically-secure-random-string-here"
|
|
@@ -35,6 +37,8 @@ var authEnvSchema = defineEnvSchema({
|
|
|
35
37
|
description: "Session TTL (time to live) - supports duration strings like '7d', '12h', '45m'",
|
|
36
38
|
default: "7d",
|
|
37
39
|
required: false,
|
|
40
|
+
nextjs: true,
|
|
41
|
+
// May be needed for session validation in Next.js RSC
|
|
38
42
|
examples: ["7d", "30d", "12h", "45m", "3600"]
|
|
39
43
|
})
|
|
40
44
|
},
|
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 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 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":";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uB,qBAAqB;AAAA,IAC3D,CAAC;AAAA,EACL;AAAA,EAEA,6BAA6B;AAAA,IACzB,GAAG,UAAU;AAAA,MACT,aAAa;AAAA,MACb,UAAU;AAAA,MACV,UAAU,CAAC,SAAS,cAAc;AAAA,IACtC,CAAC;AAAA,EACL;AACJ,CAAC;;;AD5PD,IAAM,WAAW,kBAAkB,aAAa;AACzC,IAAM,MAAM,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});"],"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,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ACJ,CAAC;;;AD9PD,IAAM,WAAW,kBAAkB,aAAa;AACzC,IAAM,MAAM,SAAS,SAAS;","names":[]}
|
|
@@ -315,6 +315,24 @@ interface AuthInitOptions {
|
|
|
315
315
|
*/
|
|
316
316
|
declare const mainAuthRouter: _spfn_core_route.Router<{
|
|
317
317
|
getUserProfile: _spfn_core_route.RouteDef<{}, {}, UserProfile>;
|
|
318
|
+
updateUserProfile: _spfn_core_route.RouteDef<{
|
|
319
|
+
body: _sinclair_typebox.TObject<{
|
|
320
|
+
displayName: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
321
|
+
firstName: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
322
|
+
lastName: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
323
|
+
avatarUrl: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
324
|
+
bio: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
325
|
+
locale: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
326
|
+
timezone: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
327
|
+
dateOfBirth: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
328
|
+
gender: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
329
|
+
website: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
330
|
+
location: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
331
|
+
company: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
332
|
+
jobTitle: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
333
|
+
metadata: _sinclair_typebox.TOptional<_sinclair_typebox.TRecord<_sinclair_typebox.TString, _sinclair_typebox.TAny>>;
|
|
334
|
+
}>;
|
|
335
|
+
}, {}, ProfileInfo>;
|
|
318
336
|
getInvitation: _spfn_core_route.RouteDef<{
|
|
319
337
|
params: _sinclair_typebox.TObject<{
|
|
320
338
|
token: _sinclair_typebox.TString;
|
|
@@ -414,7 +432,7 @@ declare const mainAuthRouter: _spfn_core_route.Router<{
|
|
|
414
432
|
body: _sinclair_typebox.TObject<{
|
|
415
433
|
id: _sinclair_typebox.TNumber;
|
|
416
434
|
}>;
|
|
417
|
-
}, {},
|
|
435
|
+
}, {}, void>;
|
|
418
436
|
checkAccountExists: _spfn_core_route.RouteDef<{
|
|
419
437
|
body: _sinclair_typebox.TUnion<[_sinclair_typebox.TObject<{
|
|
420
438
|
email: _sinclair_typebox.TString;
|
|
@@ -472,7 +490,7 @@ declare const mainAuthRouter: _spfn_core_route.Router<{
|
|
|
472
490
|
}, LoginResult>;
|
|
473
491
|
logout: _spfn_core_route.RouteDef<{
|
|
474
492
|
body: _sinclair_typebox.TObject<{}>;
|
|
475
|
-
}, {},
|
|
493
|
+
}, {}, void>;
|
|
476
494
|
rotateKey: _spfn_core_route.RouteDef<{
|
|
477
495
|
body: _sinclair_typebox.TObject<{}>;
|
|
478
496
|
}, {
|
|
@@ -488,7 +506,7 @@ declare const mainAuthRouter: _spfn_core_route.Router<{
|
|
|
488
506
|
currentPassword: _sinclair_typebox.TString;
|
|
489
507
|
newPassword: _sinclair_typebox.TString;
|
|
490
508
|
}>;
|
|
491
|
-
}, {},
|
|
509
|
+
}, {}, void>;
|
|
492
510
|
getAuthSession: _spfn_core_route.RouteDef<{}, {}, {
|
|
493
511
|
role: {
|
|
494
512
|
id: number;
|
|
@@ -603,6 +621,7 @@ interface ProfileInfo {
|
|
|
603
621
|
location: string | null;
|
|
604
622
|
company: string | null;
|
|
605
623
|
jobTitle: string | null;
|
|
624
|
+
metadata: Record<string, any> | null;
|
|
606
625
|
createdAt: Date;
|
|
607
626
|
updatedAt: Date;
|
|
608
627
|
}
|
|
@@ -627,4 +646,4 @@ interface UserProfile {
|
|
|
627
646
|
profile: ProfileInfo | null;
|
|
628
647
|
}
|
|
629
648
|
|
|
630
|
-
export { VerificationPurposeSchema as $, type AuthSession as A, type ChangePasswordParams as B, type CheckAccountExistsResult as C, sendVerificationCodeService as D, verifyCodeService as E, type SendVerificationCodeParams as F, type VerifyCodeParams as G, type VerifyCodeResult as H, INVITATION_STATUSES as I, registerPublicKeyService as J, KEY_ALGORITHM as K, type LoginResult as L, rotateKeyService as M, revokeKeyService as N, type RegisterPublicKeyParams as O, type PermissionConfig as P, type RotateKeyParams as Q, type RoleConfig as R, type SendVerificationCodeResult as S, type RevokeKeyParams as T, type UserProfile as U, type VerificationTargetType as V, authenticate as W, EmailSchema as X, PhoneSchema as Y, PasswordSchema as Z, TargetTypeSchema as _, type
|
|
649
|
+
export { VerificationPurposeSchema as $, type AuthSession as A, type ChangePasswordParams as B, type CheckAccountExistsResult as C, sendVerificationCodeService as D, verifyCodeService as E, type SendVerificationCodeParams as F, type VerifyCodeParams as G, type VerifyCodeResult as H, INVITATION_STATUSES as I, registerPublicKeyService as J, KEY_ALGORITHM as K, type LoginResult as L, rotateKeyService as M, revokeKeyService as N, type RegisterPublicKeyParams as O, type PermissionConfig as P, type RotateKeyParams as Q, type RoleConfig as R, type SendVerificationCodeResult as S, type RevokeKeyParams as T, type UserProfile as U, type VerificationTargetType as V, authenticate as W, EmailSchema as X, PhoneSchema as Y, PasswordSchema as Z, TargetTypeSchema as _, type ProfileInfo as a, type RegisterResult as b, type RotateKeyResult as c, USER_STATUSES as d, SOCIAL_PROVIDERS as e, type VerificationPurpose as f, VERIFICATION_TARGET_TYPES as g, VERIFICATION_PURPOSES as h, PERMISSION_CATEGORIES as i, type PermissionCategory as j, type AuthInitOptions as k, type KeyAlgorithmType as l, mainAuthRouter as m, type InvitationStatus as n, type UserStatus as o, type SocialProvider as p, type AuthContext as q, checkAccountExistsService as r, registerService as s, loginService as t, logoutService as u, changePasswordService as v, type CheckAccountExistsParams as w, type RegisterParams as x, type LoginParams as y, type LogoutParams as z };
|
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, U as UserProfile, C as CheckAccountExistsResult, S as SendVerificationCodeResult,
|
|
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,
|
|
2
|
+
import { R as RoleConfig, P as PermissionConfig, U as UserProfile, a as ProfileInfo, C as CheckAccountExistsResult, S as SendVerificationCodeResult, b as RegisterResult, L as LoginResult, c as RotateKeyResult, m as mainAuthRouter } from './dto-Bb2qFUO6.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 './dto-Bb2qFUO6.js';
|
|
4
4
|
import * as _spfn_core_route from '@spfn/core/route';
|
|
5
5
|
import * as _sinclair_typebox from '@sinclair/typebox';
|
|
6
6
|
import '@spfn/auth/server';
|
|
@@ -75,6 +75,24 @@ declare const BASE64_PATTERN = "^[A-Za-z0-9+/]+=*$";
|
|
|
75
75
|
*/
|
|
76
76
|
declare const authApi: _spfn_core_nextjs.Client<_spfn_core_route.Router<{
|
|
77
77
|
getUserProfile: _spfn_core_route.RouteDef<{}, {}, UserProfile>;
|
|
78
|
+
updateUserProfile: _spfn_core_route.RouteDef<{
|
|
79
|
+
body: _sinclair_typebox.TObject<{
|
|
80
|
+
displayName: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
81
|
+
firstName: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
82
|
+
lastName: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
83
|
+
avatarUrl: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
84
|
+
bio: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
85
|
+
locale: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
86
|
+
timezone: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
87
|
+
dateOfBirth: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
88
|
+
gender: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
89
|
+
website: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
90
|
+
location: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
91
|
+
company: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
92
|
+
jobTitle: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
|
|
93
|
+
metadata: _sinclair_typebox.TOptional<_sinclair_typebox.TRecord<_sinclair_typebox.TString, _sinclair_typebox.TAny>>;
|
|
94
|
+
}>;
|
|
95
|
+
}, {}, ProfileInfo>;
|
|
78
96
|
getInvitation: _spfn_core_route.RouteDef<{
|
|
79
97
|
params: _sinclair_typebox.TObject<{
|
|
80
98
|
token: _sinclair_typebox.TString;
|
|
@@ -174,7 +192,7 @@ declare const authApi: _spfn_core_nextjs.Client<_spfn_core_route.Router<{
|
|
|
174
192
|
body: _sinclair_typebox.TObject<{
|
|
175
193
|
id: _sinclair_typebox.TNumber;
|
|
176
194
|
}>;
|
|
177
|
-
}, {},
|
|
195
|
+
}, {}, void>;
|
|
178
196
|
checkAccountExists: _spfn_core_route.RouteDef<{
|
|
179
197
|
body: _sinclair_typebox.TUnion<[_sinclair_typebox.TObject<{
|
|
180
198
|
email: _sinclair_typebox.TString;
|
|
@@ -232,7 +250,7 @@ declare const authApi: _spfn_core_nextjs.Client<_spfn_core_route.Router<{
|
|
|
232
250
|
}, LoginResult>;
|
|
233
251
|
logout: _spfn_core_route.RouteDef<{
|
|
234
252
|
body: _sinclair_typebox.TObject<{}>;
|
|
235
|
-
}, {},
|
|
253
|
+
}, {}, void>;
|
|
236
254
|
rotateKey: _spfn_core_route.RouteDef<{
|
|
237
255
|
body: _sinclair_typebox.TObject<{}>;
|
|
238
256
|
}, {
|
|
@@ -248,7 +266,7 @@ declare const authApi: _spfn_core_nextjs.Client<_spfn_core_route.Router<{
|
|
|
248
266
|
currentPassword: _sinclair_typebox.TString;
|
|
249
267
|
newPassword: _sinclair_typebox.TString;
|
|
250
268
|
}>;
|
|
251
|
-
}, {},
|
|
269
|
+
}, {}, void>;
|
|
252
270
|
getAuthSession: _spfn_core_route.RouteDef<{}, {}, {
|
|
253
271
|
role: {
|
|
254
272
|
id: number;
|
|
@@ -270,4 +288,4 @@ declare const authApi: _spfn_core_nextjs.Client<_spfn_core_route.Router<{
|
|
|
270
288
|
}>>;
|
|
271
289
|
type AuthRouter = typeof mainAuthRouter;
|
|
272
290
|
|
|
273
|
-
export { type AuthRouter, BASE64_PATTERN, BUILTIN_PERMISSIONS, BUILTIN_ROLES, BUILTIN_ROLE_PERMISSIONS, type BuiltinPermissionName, type BuiltinRoleName, EMAIL_PATTERN, FINGERPRINT_PATTERN, PHONE_PATTERN, PermissionConfig, RoleConfig, UUID_PATTERN, UserProfile, authApi };
|
|
291
|
+
export { type AuthRouter, BASE64_PATTERN, BUILTIN_PERMISSIONS, BUILTIN_ROLES, BUILTIN_ROLE_PERMISSIONS, type BuiltinPermissionName, type BuiltinRoleName, EMAIL_PATTERN, FINGERPRINT_PATTERN, PHONE_PATTERN, PermissionConfig, ProfileInfo, RoleConfig, UUID_PATTERN, UserProfile, authApi };
|
package/dist/nextjs/server.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/nextjs/server.ts","../../src/nextjs/guards/require-auth.tsx","../../src/nextjs/session-helpers.ts","../../src/nextjs/guards/require-role.tsx","../../src/nextjs/guards/auth-utils.ts","../../src/nextjs/guards/require-permission.tsx"],"sourcesContent":["import \"server-only\";\n\nexport { RequireAuth } from './guards/require-auth';\nexport type { RequireAuthProps } from './guards/require-auth';\n\nexport { RequireRole } from './guards/require-role';\nexport type { RequireRoleProps } from './guards/require-role';\n\nexport { RequirePermission } from './guards/require-permission';\nexport type { RequirePermissionProps } from './guards/require-permission';\n\nexport { getUserRole, getUserPermissions, hasAnyRole, hasAnyPermission } from './guards/auth-utils';\n\n// Session helpers\nexport {\n saveSession,\n getSession,\n clearSession,\n type SessionData,\n type PublicSession,\n type SaveSessionOptions\n} from './session-helpers';","/**\n * RequireAuth Guard Component\n *\n * Requires user to be authenticated\n */\n\nimport { redirect } from 'next/navigation';\nimport { getSession } from '../session-helpers';\nimport type { ReactNode } from 'react';\n\nexport interface RequireAuthProps\n{\n /**\n * Children to render if authenticated\n */\n children: ReactNode;\n\n /**\n * Path to redirect to if not authenticated\n * @default '/login'\n */\n redirectTo?: string;\n\n /**\n * Fallback UI to show instead of redirecting\n */\n fallback?: ReactNode;\n}\n\n/**\n * Require Authentication Guard\n *\n * Ensures user is logged in before rendering children\n *\n * @example\n * ```tsx\n * <RequireAuth redirectTo=\"/login\">\n * <DashboardContent />\n * </RequireAuth>\n * ```\n *\n * @example With fallback\n * ```tsx\n * <RequireAuth fallback={<LoginPrompt />}>\n * <PrivateContent />\n * </RequireAuth>\n * ```\n */\nexport async function RequireAuth({\n children,\n redirectTo = '/auth/login',\n fallback,\n}: RequireAuthProps)\n{\n const session = await getSession();\n console.log('session', session);\n\n if (!session)\n {\n if (fallback)\n {\n return <>{fallback}</>;\n }\n\n redirect(redirectTo);\n }\n\n return <>{children}</>;\n}","/**\n * Session helpers for Next.js\n *\n * Server-side only (uses next/headers)\n */\n\nimport { cookies } from 'next/headers.js';\nimport { sealSession, unsealSession, COOKIE_NAMES, getSessionTtl, parseDuration, type SessionData } from '@spfn/auth/server';\nimport { logger } from '@spfn/core/logger';\n\nexport type { SessionData };\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 console.error(error);\n\n // Session expired or invalid - log in dev mode\n // Note: Cannot delete cookies in Server Components (read-only)\n // Invalid cookies will be cleaned up on next login/logout via Route Handler or Server Action\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 * RequireRole Guard Component\n *\n * Requires user to have at least one of the specified roles\n */\n\nimport { redirect } from 'next/navigation';\nimport { getSession } from '../session-helpers';\nimport { hasAnyRole } from './auth-utils';\nimport type { ReactNode } from 'react';\n\nexport interface RequireRoleProps\n{\n /**\n * Required role(s) - user must have at least one\n */\n roles: string | string[];\n\n /**\n * Children to render if user has required role\n */\n children: ReactNode;\n\n /**\n * Path to redirect to if user doesn't have role\n * @default '/unauthorized'\n */\n redirectTo?: string;\n\n /**\n * Fallback UI to show instead of redirecting\n */\n fallback?: ReactNode;\n}\n\n/**\n * Require Role Guard\n *\n * Ensures user has at least one of the specified roles\n *\n * @example Single role\n * ```tsx\n * <RequireRole roles=\"admin\">\n * <AdminPanel />\n * </RequireRole>\n * ```\n *\n * @example Multiple roles (OR condition)\n * ```tsx\n * <RequireRole roles={['admin', 'manager']}>\n * <ManagementDashboard />\n * </RequireRole>\n * ```\n *\n * @example With fallback\n * ```tsx\n * <RequireRole roles=\"admin\" fallback={<AccessDenied />}>\n * <AdminContent />\n * </RequireRole>\n * ```\n */\nexport async function RequireRole({\n roles,\n children,\n redirectTo = '/unauthorized',\n fallback,\n}: RequireRoleProps)\n{\n const session = await getSession();\n\n // Not authenticated\n if (!session)\n {\n if (fallback)\n {\n return <>{fallback}</>;\n }\n\n redirect('/login');\n }\n\n // Normalize to array\n const requiredRoles = Array.isArray(roles) ? roles : [roles];\n\n // Check if user has any of the required roles\n const hasRole = await hasAnyRole(requiredRoles);\n\n if (!hasRole)\n {\n if (fallback)\n {\n return <>{fallback}</>;\n }\n\n redirect(redirectTo);\n }\n\n return <>{children}</>;\n}","/**\n * Server-side auth utilities for guards\n *\n * Uses authApi to check permissions in real-time\n */\n\nimport { authApi } from '@spfn/auth';\nimport { authLogger } from '@spfn/auth/server';\n\n/**\n * Get current auth session with roles and permissions via API\n */\nasync function getAuthSessionData()\n{\n try\n {\n const session = await authApi.getAuthSession.call();\n authLogger.middleware.debug('Auth session retrieved', { name: session.role?.name });\n\n return session;\n }\n catch (error)\n {\n authLogger.middleware.error('Failed to get auth session', { error });\n return null;\n }\n}\n\n/**\n * Get user role\n */\nexport async function getUserRole(): Promise<string | null>\n{\n const session = await getAuthSessionData();\n return session?.role?.name || null;\n}\n\n/**\n * Get user permissions\n */\nexport async function getUserPermissions(): Promise<string[]>\n{\n const session = await getAuthSessionData();\n\n if (!session)\n {\n return [];\n }\n\n return session.permissions?.map((p: any) => p.name) || [];\n}\n\n/**\n * Check if user has any of the specified roles\n */\nexport async function hasAnyRole(requiredRoles: string[]): Promise<boolean>\n{\n const session = await getAuthSessionData();\n if (!session)\n {\n return false;\n }\n\n return requiredRoles.includes(session.role?.name);\n}\n\n/**\n * Check if user has any of the specified permissions\n */\nexport async function hasAnyPermission(requiredPermissions: string[]): Promise<boolean>\n{\n const session = await getAuthSessionData();\n\n if (!session)\n {\n return false;\n }\n\n const userPermissionNames = session.permissions?.map((p: any) => p.name) || [];\n return requiredPermissions.some(permission => userPermissionNames.includes(permission));\n}\n","/**\n * RequirePermission Guard Component\n *\n * Requires user to have at least one of the specified permissions\n */\n\nimport { redirect } from 'next/navigation';\nimport { getSession } from '../session-helpers';\nimport { hasAnyPermission } from './auth-utils';\nimport type { ReactNode } from 'react';\n\nexport interface RequirePermissionProps\n{\n /**\n * Required permission(s) - user must have at least one\n */\n permissions: string | string[];\n\n /**\n * Children to render if user has required permission\n */\n children: ReactNode;\n\n /**\n * Path to redirect to if user doesn't have permission\n * @default '/unauthorized'\n */\n redirectTo?: string;\n\n /**\n * Fallback UI to show instead of redirecting\n */\n fallback?: ReactNode;\n}\n\n/**\n * Require Permission Guard\n *\n * Ensures user has at least one of the specified permissions\n *\n * @example Single permission\n * ```tsx\n * <RequirePermission permissions=\"user:delete\">\n * <DeleteUserButton />\n * </RequirePermission>\n * ```\n *\n * @example Multiple permissions (OR condition)\n * ```tsx\n * <RequirePermission permissions={['user:delete', 'user:update']}>\n * <UserManagement />\n * </RequirePermission>\n * ```\n *\n * @example With fallback\n * ```tsx\n * <RequirePermission permissions=\"project:create\" fallback={<UpgradePrompt />}>\n * <CreateProject />\n * </RequirePermission>\n * ```\n */\nexport async function RequirePermission({\n permissions,\n children,\n redirectTo = '/unauthorized',\n fallback,\n}: RequirePermissionProps)\n{\n const session = await getSession();\n\n // Not authenticated\n if (!session)\n {\n if (fallback)\n {\n return <>{fallback}</>;\n }\n\n redirect('/login');\n }\n\n // Normalize to array\n const requiredPermissions = Array.isArray(permissions) ? permissions : [permissions];\n\n // Check if user has any of the required permissions\n const hasPermission = await hasAnyPermission(requiredPermissions);\n\n if (!hasPermission)\n {\n if (fallback)\n {\n return <>{fallback}</>;\n }\n\n redirect(redirectTo);\n }\n\n return <>{children}</>;\n}"],"mappings":";AAAA,OAAO;;;ACMP,SAAS,gBAAgB;;;ACAzB,SAAS,eAAe;AACxB,SAAS,aAAa,eAAe,cAAc,eAAe,qBAAuC;AACzG,SAAS,cAAc;AA6DvB,eAAsB,YAClB,MACA,SAEJ;AAEI,MAAI;AAEJ,MAAI,SAAS,WAAW,QACxB;AAEI,aAAS,OAAO,QAAQ,WAAW,WAC7B,QAAQ,SACR,cAAc,QAAQ,MAAM;AAAA,EACtC,OAEA;AAEI,aAAS,cAAc;AAAA,EAC3B;AAEA,QAAM,QAAQ,MAAM,YAAY,MAAM,MAAM;AAC5C,QAAM,cAAc,MAAM,QAAQ;AAElC,cAAY,IAAI,aAAa,SAAS,OAAO;AAAA,IACzC,UAAU;AAAA,IACV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UAAS,UAAU;AAAA,EACvB;AAEA,SAAO,gBAAAD,KAAAD,WAAA,EAAG,UAAS;AACvB;;;AE5FA,SAAS,YAAAG,iBAAgB;AAqEN,qBAAAC,WAAA,OAAAC,YAAA;AAdnB,eAAsB,kBAAkB;AAAA,EACpC;AAAA,EACA;AAAA,EACA,aAAa;AAAA,EACb;AACJ,GACA;AACI,QAAM,UAAU,MAAM,WAAW;AAGjC,MAAI,CAAC,SACL;AACI,QAAI,UACJ;AACI,aAAO,gBAAAA,KAAAD,WAAA,EAAG,oBAAS;AAAA,IACvB;AAEA,IAAAE,UAAS,QAAQ;AAAA,EACrB;AAGA,QAAM,sBAAsB,MAAM,QAAQ,WAAW,IAAI,cAAc,CAAC,WAAW;AAGnF,QAAM,gBAAgB,MAAM,iBAAiB,mBAAmB;AAEhE,MAAI,CAAC,eACL;AACI,QAAI,UACJ;AACI,aAAO,gBAAAD,KAAAD,WAAA,EAAG,oBAAS;AAAA,IACvB;AAEA,IAAAE,UAAS,UAAU;AAAA,EACvB;AAEA,SAAO,gBAAAD,KAAAD,WAAA,EAAG,UAAS;AACvB;","names":["redirect","Fragment","jsx","redirect","redirect","Fragment","jsx","redirect"]}
|
|
1
|
+
{"version":3,"sources":["../../src/nextjs/server.ts","../../src/nextjs/guards/require-auth.tsx","../../src/nextjs/session-helpers.ts","../../src/nextjs/guards/require-role.tsx","../../src/nextjs/guards/auth-utils.ts","../../src/nextjs/guards/require-permission.tsx"],"sourcesContent":["import \"server-only\";\n\nexport { RequireAuth } from './guards/require-auth';\nexport type { RequireAuthProps } from './guards/require-auth';\n\nexport { RequireRole } from './guards/require-role';\nexport type { RequireRoleProps } from './guards/require-role';\n\nexport { RequirePermission } from './guards/require-permission';\nexport type { RequirePermissionProps } from './guards/require-permission';\n\nexport { getUserRole, getUserPermissions, hasAnyRole, hasAnyPermission } from './guards/auth-utils';\n\n// Session helpers\nexport {\n saveSession,\n getSession,\n clearSession,\n type SessionData,\n type PublicSession,\n type SaveSessionOptions\n} from './session-helpers';","/**\n * RequireAuth Guard Component\n *\n * Requires user to be authenticated\n */\n\nimport { redirect } from 'next/navigation';\nimport { getSession } from '../session-helpers';\nimport type { ReactNode } from 'react';\n\nexport interface RequireAuthProps\n{\n /**\n * Children to render if authenticated\n */\n children: ReactNode;\n\n /**\n * Path to redirect to if not authenticated\n * @default '/login'\n */\n redirectTo?: string;\n\n /**\n * Fallback UI to show instead of redirecting\n */\n fallback?: ReactNode;\n}\n\n/**\n * Require Authentication Guard\n *\n * Ensures user is logged in before rendering children\n *\n * @example\n * ```tsx\n * <RequireAuth redirectTo=\"/login\">\n * <DashboardContent />\n * </RequireAuth>\n * ```\n *\n * @example With fallback\n * ```tsx\n * <RequireAuth fallback={<LoginPrompt />}>\n * <PrivateContent />\n * </RequireAuth>\n * ```\n */\nexport async function RequireAuth({\n children,\n redirectTo = '/auth/login',\n fallback,\n}: RequireAuthProps)\n{\n const session = await getSession();\n\n if (!session)\n {\n if (fallback)\n {\n return <>{fallback}</>;\n }\n\n redirect(redirectTo);\n }\n\n return <>{children}</>;\n}","/**\n * Session helpers for Next.js\n *\n * Server-side only (uses next/headers)\n */\n\nimport { cookies } from 'next/headers.js';\nimport { sealSession, unsealSession, COOKIE_NAMES, getSessionTtl, parseDuration, type SessionData } from '@spfn/auth/server';\nimport { logger } from '@spfn/core/logger';\n\nexport type { SessionData };\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 console.error(error);\n\n // Session expired or invalid - log in dev mode\n // Note: Cannot delete cookies in Server Components (read-only)\n // Invalid cookies will be cleaned up on next login/logout via Route Handler or Server Action\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 * RequireRole Guard Component\n *\n * Requires user to have at least one of the specified roles\n */\n\nimport { redirect } from 'next/navigation';\nimport { getSession } from '../session-helpers';\nimport { hasAnyRole } from './auth-utils';\nimport type { ReactNode } from 'react';\n\nexport interface RequireRoleProps\n{\n /**\n * Required role(s) - user must have at least one\n */\n roles: string | string[];\n\n /**\n * Children to render if user has required role\n */\n children: ReactNode;\n\n /**\n * Path to redirect to if user doesn't have role\n * @default '/unauthorized'\n */\n redirectTo?: string;\n\n /**\n * Fallback UI to show instead of redirecting\n */\n fallback?: ReactNode;\n}\n\n/**\n * Require Role Guard\n *\n * Ensures user has at least one of the specified roles\n *\n * @example Single role\n * ```tsx\n * <RequireRole roles=\"admin\">\n * <AdminPanel />\n * </RequireRole>\n * ```\n *\n * @example Multiple roles (OR condition)\n * ```tsx\n * <RequireRole roles={['admin', 'manager']}>\n * <ManagementDashboard />\n * </RequireRole>\n * ```\n *\n * @example With fallback\n * ```tsx\n * <RequireRole roles=\"admin\" fallback={<AccessDenied />}>\n * <AdminContent />\n * </RequireRole>\n * ```\n */\nexport async function RequireRole({\n roles,\n children,\n redirectTo = '/unauthorized',\n fallback,\n}: RequireRoleProps)\n{\n const session = await getSession();\n\n // Not authenticated\n if (!session)\n {\n if (fallback)\n {\n return <>{fallback}</>;\n }\n\n redirect('/login');\n }\n\n // Normalize to array\n const requiredRoles = Array.isArray(roles) ? roles : [roles];\n\n // Check if user has any of the required roles\n const hasRole = await hasAnyRole(requiredRoles);\n\n if (!hasRole)\n {\n if (fallback)\n {\n return <>{fallback}</>;\n }\n\n redirect(redirectTo);\n }\n\n return <>{children}</>;\n}","/**\n * Server-side auth utilities for guards\n *\n * Uses authApi to check permissions in real-time\n */\n\nimport { authApi } from '@spfn/auth';\nimport { authLogger } from '@spfn/auth/server';\n\n/**\n * Get current auth session with roles and permissions via API\n */\nasync function getAuthSessionData()\n{\n try\n {\n const session = await authApi.getAuthSession.call();\n authLogger.middleware.debug('Auth session retrieved', { name: session.role?.name });\n\n return session;\n }\n catch (error)\n {\n authLogger.middleware.error('Failed to get auth session', { error });\n return null;\n }\n}\n\n/**\n * Get user role\n */\nexport async function getUserRole(): Promise<string | null>\n{\n const session = await getAuthSessionData();\n return session?.role?.name || null;\n}\n\n/**\n * Get user permissions\n */\nexport async function getUserPermissions(): Promise<string[]>\n{\n const session = await getAuthSessionData();\n\n if (!session)\n {\n return [];\n }\n\n return session.permissions?.map((p: any) => p.name) || [];\n}\n\n/**\n * Check if user has any of the specified roles\n */\nexport async function hasAnyRole(requiredRoles: string[]): Promise<boolean>\n{\n const session = await getAuthSessionData();\n if (!session)\n {\n return false;\n }\n\n return requiredRoles.includes(session.role?.name);\n}\n\n/**\n * Check if user has any of the specified permissions\n */\nexport async function hasAnyPermission(requiredPermissions: string[]): Promise<boolean>\n{\n const session = await getAuthSessionData();\n\n if (!session)\n {\n return false;\n }\n\n const userPermissionNames = session.permissions?.map((p: any) => p.name) || [];\n return requiredPermissions.some(permission => userPermissionNames.includes(permission));\n}\n","/**\n * RequirePermission Guard Component\n *\n * Requires user to have at least one of the specified permissions\n */\n\nimport { redirect } from 'next/navigation';\nimport { getSession } from '../session-helpers';\nimport { hasAnyPermission } from './auth-utils';\nimport type { ReactNode } from 'react';\n\nexport interface RequirePermissionProps\n{\n /**\n * Required permission(s) - user must have at least one\n */\n permissions: string | string[];\n\n /**\n * Children to render if user has required permission\n */\n children: ReactNode;\n\n /**\n * Path to redirect to if user doesn't have permission\n * @default '/unauthorized'\n */\n redirectTo?: string;\n\n /**\n * Fallback UI to show instead of redirecting\n */\n fallback?: ReactNode;\n}\n\n/**\n * Require Permission Guard\n *\n * Ensures user has at least one of the specified permissions\n *\n * @example Single permission\n * ```tsx\n * <RequirePermission permissions=\"user:delete\">\n * <DeleteUserButton />\n * </RequirePermission>\n * ```\n *\n * @example Multiple permissions (OR condition)\n * ```tsx\n * <RequirePermission permissions={['user:delete', 'user:update']}>\n * <UserManagement />\n * </RequirePermission>\n * ```\n *\n * @example With fallback\n * ```tsx\n * <RequirePermission permissions=\"project:create\" fallback={<UpgradePrompt />}>\n * <CreateProject />\n * </RequirePermission>\n * ```\n */\nexport async function RequirePermission({\n permissions,\n children,\n redirectTo = '/unauthorized',\n fallback,\n}: RequirePermissionProps)\n{\n const session = await getSession();\n\n // Not authenticated\n if (!session)\n {\n if (fallback)\n {\n return <>{fallback}</>;\n }\n\n redirect('/login');\n }\n\n // Normalize to array\n const requiredPermissions = Array.isArray(permissions) ? permissions : [permissions];\n\n // Check if user has any of the required permissions\n const hasPermission = await hasAnyPermission(requiredPermissions);\n\n if (!hasPermission)\n {\n if (fallback)\n {\n return <>{fallback}</>;\n }\n\n redirect(redirectTo);\n }\n\n return <>{children}</>;\n}"],"mappings":";AAAA,OAAO;;;ACMP,SAAS,gBAAgB;;;ACAzB,SAAS,eAAe;AACxB,SAAS,aAAa,eAAe,cAAc,eAAe,qBAAuC;AACzG,SAAS,cAAc;AA6DvB,eAAsB,YAClB,MACA,SAEJ;AAEI,MAAI;AAEJ,MAAI,SAAS,WAAW,QACxB;AAEI,aAAS,OAAO,QAAQ,WAAW,WAC7B,QAAQ,SACR,cAAc,QAAQ,MAAM;AAAA,EACtC,OAEA;AAEI,aAAS,cAAc;AAAA,EAC3B;AAEA,QAAM,QAAQ,MAAM,YAAY,MAAM,MAAM;AAC5C,QAAM,cAAc,MAAM,QAAQ;AAElC,cAAY,IAAI,aAAa,SAAS,OAAO;AAAA,IACzC,UAAU;AAAA,IACV,QAAQ,QAAQ,IAAI,aAAa;AAAA,IACjC,UAAU;AAAA,IACV,MAAM;AAAA,IACN;AAAA,EACJ,CAAC;AACL;AAOA,eAAsB,aACtB;AACI,QAAM,cAAc,MAAM,QAAQ;AAClC,QAAM,gBAAgB,YAAY,IAAI,aAAa,OAAO;AAE1D,MAAI,CAAC,eACL;AACI,WAAO;AAAA,EACX;AAEA,MACA;AACI,WAAO,MAAM,6BAA6B,EAAE,QAAQ,cAAc,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WAAA,EAAG,oBAAS;AAAA,IACvB;AAEA,IAAAE,UAAS,QAAQ;AAAA,EACrB;AAGA,QAAM,sBAAsB,MAAM,QAAQ,WAAW,IAAI,cAAc,CAAC,WAAW;AAGnF,QAAM,gBAAgB,MAAM,iBAAiB,mBAAmB;AAEhE,MAAI,CAAC,eACL;AACI,QAAI,UACJ;AACI,aAAO,gBAAAD,KAAAD,WAAA,EAAG,oBAAS;AAAA,IACvB;AAEA,IAAAE,UAAS,UAAU;AAAA,EACvB;AAEA,SAAO,gBAAAD,KAAAD,WAAA,EAAG,UAAS;AACvB;","names":["redirect","Fragment","jsx","redirect","redirect","Fragment","jsx","redirect"]}
|
package/dist/server.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { k as AuthInitOptions, l as KeyAlgorithmType, n as InvitationStatus, f as VerificationPurpose, j as PermissionCategory, q as AuthContext } from './dto-
|
|
2
|
-
export { B as ChangePasswordParams, w as CheckAccountExistsParams, C as CheckAccountExistsResult, X as EmailSchema, I as INVITATION_STATUSES, K as KEY_ALGORITHM, y as LoginParams, L as LoginResult, z as LogoutParams, Z as PasswordSchema, Y as PhoneSchema, x as RegisterParams, O as RegisterPublicKeyParams,
|
|
1
|
+
import { k as AuthInitOptions, l as KeyAlgorithmType, n as InvitationStatus, f as VerificationPurpose, j as PermissionCategory, q as AuthContext } from './dto-Bb2qFUO6.js';
|
|
2
|
+
export { B as ChangePasswordParams, w as CheckAccountExistsParams, C as CheckAccountExistsResult, X as EmailSchema, I as INVITATION_STATUSES, K as KEY_ALGORITHM, y as LoginParams, L as LoginResult, z as LogoutParams, Z as PasswordSchema, Y as PhoneSchema, x as RegisterParams, O as RegisterPublicKeyParams, b as RegisterResult, T as RevokeKeyParams, Q as RotateKeyParams, c as RotateKeyResult, e as SOCIAL_PROVIDERS, F as SendVerificationCodeParams, S as SendVerificationCodeResult, p as SocialProvider, _ as TargetTypeSchema, d as USER_STATUSES, o as UserStatus, h as VERIFICATION_PURPOSES, g as VERIFICATION_TARGET_TYPES, $ as VerificationPurposeSchema, V as VerificationTargetType, G as VerifyCodeParams, H as VerifyCodeResult, m as authRouter, W as authenticate, v as changePasswordService, r as checkAccountExistsService, t as loginService, u as logoutService, J as registerPublicKeyService, s as registerService, N as revokeKeyService, M as rotateKeyService, D as sendVerificationCodeService, E as verifyCodeService } from './dto-Bb2qFUO6.js';
|
|
3
3
|
import * as drizzle_orm_pg_core from 'drizzle-orm/pg-core';
|
|
4
|
-
import { UserProfile as UserProfile$1 } from '@spfn/auth';
|
|
4
|
+
import { UserProfile as UserProfile$1, ProfileInfo } from '@spfn/auth';
|
|
5
5
|
import { BaseRepository } from '@spfn/core/db';
|
|
6
6
|
import { Context } from 'hono';
|
|
7
7
|
import * as _spfn_core_route from '@spfn/core/route';
|
|
@@ -406,6 +406,19 @@ declare function hasAnyPermission(userId: string | number | bigint, permissionNa
|
|
|
406
406
|
* ```
|
|
407
407
|
*/
|
|
408
408
|
declare function hasAllPermissions(userId: string | number | bigint, permissionNames: string[]): Promise<boolean>;
|
|
409
|
+
/**
|
|
410
|
+
* Get user's role name
|
|
411
|
+
*
|
|
412
|
+
* @param userId - User ID
|
|
413
|
+
* @returns Role name or null if user has no role
|
|
414
|
+
*
|
|
415
|
+
* @example
|
|
416
|
+
* ```typescript
|
|
417
|
+
* const role = await getUserRole('123');
|
|
418
|
+
* // 'admin' or null
|
|
419
|
+
* ```
|
|
420
|
+
*/
|
|
421
|
+
declare function getUserRole(userId: string | number | bigint): Promise<string | null>;
|
|
409
422
|
/**
|
|
410
423
|
* Check if user has a specific role
|
|
411
424
|
*
|
|
@@ -1253,10 +1266,30 @@ declare function getAuthSessionService(userId: string | number | bigint): Promis
|
|
|
1253
1266
|
/**
|
|
1254
1267
|
* @spfn/auth - User Profile Service
|
|
1255
1268
|
*
|
|
1256
|
-
* Service for retrieving user profile information
|
|
1269
|
+
* Service for retrieving and updating user profile information
|
|
1257
1270
|
* Returns full user info with profile data
|
|
1258
1271
|
*/
|
|
1259
1272
|
|
|
1273
|
+
/**
|
|
1274
|
+
* Profile update parameters
|
|
1275
|
+
* All fields are optional, empty string will be converted to null
|
|
1276
|
+
*/
|
|
1277
|
+
interface UpdateProfileParams {
|
|
1278
|
+
displayName?: string;
|
|
1279
|
+
firstName?: string;
|
|
1280
|
+
lastName?: string;
|
|
1281
|
+
avatarUrl?: string;
|
|
1282
|
+
bio?: string;
|
|
1283
|
+
locale?: string;
|
|
1284
|
+
timezone?: string;
|
|
1285
|
+
dateOfBirth?: string;
|
|
1286
|
+
gender?: string;
|
|
1287
|
+
website?: string;
|
|
1288
|
+
location?: string;
|
|
1289
|
+
company?: string;
|
|
1290
|
+
jobTitle?: string;
|
|
1291
|
+
metadata?: Record<string, any>;
|
|
1292
|
+
}
|
|
1260
1293
|
/**
|
|
1261
1294
|
* Get user profile information
|
|
1262
1295
|
*
|
|
@@ -1272,6 +1305,26 @@ declare function getAuthSessionService(userId: string | number | bigint): Promis
|
|
|
1272
1305
|
* ```
|
|
1273
1306
|
*/
|
|
1274
1307
|
declare function getUserProfileService(userId: string | number | bigint): Promise<UserProfile$1>;
|
|
1308
|
+
/**
|
|
1309
|
+
* Update user profile (upsert)
|
|
1310
|
+
*
|
|
1311
|
+
* Creates profile if not exists, updates if exists
|
|
1312
|
+
* Empty strings are converted to null
|
|
1313
|
+
*
|
|
1314
|
+
* @param userId - User ID
|
|
1315
|
+
* @param params - Profile fields to update
|
|
1316
|
+
* @returns Updated profile info
|
|
1317
|
+
*
|
|
1318
|
+
* @example
|
|
1319
|
+
* ```typescript
|
|
1320
|
+
* const profile = await updateUserProfileService(123, {
|
|
1321
|
+
* displayName: 'John Doe',
|
|
1322
|
+
* bio: 'Software Engineer',
|
|
1323
|
+
* location: '', // will be saved as null
|
|
1324
|
+
* });
|
|
1325
|
+
* ```
|
|
1326
|
+
*/
|
|
1327
|
+
declare function updateUserProfileService(userId: string | number | bigint, params: UpdateProfileParams): Promise<ProfileInfo>;
|
|
1275
1328
|
|
|
1276
1329
|
/**
|
|
1277
1330
|
* @spfn/auth - Email Template Types
|
|
@@ -4130,6 +4183,32 @@ declare class UserProfilesRepository extends BaseRepository {
|
|
|
4130
4183
|
company: string | null;
|
|
4131
4184
|
jobTitle: string | null;
|
|
4132
4185
|
}>;
|
|
4186
|
+
/**
|
|
4187
|
+
* 프로필 Upsert (by User ID)
|
|
4188
|
+
*
|
|
4189
|
+
* 프로필이 없으면 생성, 있으면 업데이트
|
|
4190
|
+
* 새로 생성 시 displayName은 필수 (없으면 'User'로 설정)
|
|
4191
|
+
*/
|
|
4192
|
+
upsertByUserId(userId: number, data: Partial<Omit<NewUserProfile, 'userId'>>): Promise<{
|
|
4193
|
+
userId: number;
|
|
4194
|
+
id: number;
|
|
4195
|
+
displayName: string;
|
|
4196
|
+
createdAt: Date;
|
|
4197
|
+
updatedAt: Date;
|
|
4198
|
+
metadata: Record<string, any> | null;
|
|
4199
|
+
firstName: string | null;
|
|
4200
|
+
lastName: string | null;
|
|
4201
|
+
avatarUrl: string | null;
|
|
4202
|
+
bio: string | null;
|
|
4203
|
+
locale: string | null;
|
|
4204
|
+
timezone: string | null;
|
|
4205
|
+
dateOfBirth: string | null;
|
|
4206
|
+
gender: string | null;
|
|
4207
|
+
website: string | null;
|
|
4208
|
+
location: string | null;
|
|
4209
|
+
company: string | null;
|
|
4210
|
+
jobTitle: string | null;
|
|
4211
|
+
}>;
|
|
4133
4212
|
/**
|
|
4134
4213
|
* User ID로 프로필 데이터 조회 (formatted)
|
|
4135
4214
|
*
|
|
@@ -4148,6 +4227,7 @@ declare class UserProfilesRepository extends BaseRepository {
|
|
|
4148
4227
|
location: string | null;
|
|
4149
4228
|
company: string | null;
|
|
4150
4229
|
jobTitle: string | null;
|
|
4230
|
+
metadata: Record<string, any> | null;
|
|
4151
4231
|
createdAt: Date;
|
|
4152
4232
|
updatedAt: Date;
|
|
4153
4233
|
} | null>;
|
|
@@ -4715,6 +4795,57 @@ declare const requireAnyPermission: _spfn_core_route.NamedMiddlewareFactory<"any
|
|
|
4715
4795
|
*/
|
|
4716
4796
|
declare const requireRole: _spfn_core_route.NamedMiddlewareFactory<"role", string[]>;
|
|
4717
4797
|
|
|
4798
|
+
/**
|
|
4799
|
+
* @spfn/auth - Role Guard Middleware
|
|
4800
|
+
*
|
|
4801
|
+
* Middleware for role-based access control with allow/deny options
|
|
4802
|
+
*/
|
|
4803
|
+
/**
|
|
4804
|
+
* Role guard options
|
|
4805
|
+
*/
|
|
4806
|
+
interface RoleGuardOptions {
|
|
4807
|
+
/**
|
|
4808
|
+
* Roles to allow (OR condition)
|
|
4809
|
+
* User must have at least one of these roles
|
|
4810
|
+
*/
|
|
4811
|
+
allow?: string[];
|
|
4812
|
+
/**
|
|
4813
|
+
* Roles to deny
|
|
4814
|
+
* User with any of these roles will be rejected
|
|
4815
|
+
*/
|
|
4816
|
+
deny?: string[];
|
|
4817
|
+
}
|
|
4818
|
+
/**
|
|
4819
|
+
* Role-based access control middleware
|
|
4820
|
+
*
|
|
4821
|
+
* Must be used after authenticate middleware
|
|
4822
|
+
*
|
|
4823
|
+
* @param options - Role guard options (allow/deny)
|
|
4824
|
+
* @returns Middleware function
|
|
4825
|
+
*
|
|
4826
|
+
* @example Allow specific roles
|
|
4827
|
+
* ```typescript
|
|
4828
|
+
* export const adminRoute = route.get('/admin')
|
|
4829
|
+
* .use([authenticate, roleGuard({ allow: ['admin', 'superadmin'] })])
|
|
4830
|
+
* .handler(async (c) => { ... });
|
|
4831
|
+
* ```
|
|
4832
|
+
*
|
|
4833
|
+
* @example Deny specific roles
|
|
4834
|
+
* ```typescript
|
|
4835
|
+
* export const publicRoute = route.get('/content')
|
|
4836
|
+
* .use([authenticate, roleGuard({ deny: ['banned', 'suspended'] })])
|
|
4837
|
+
* .handler(async (c) => { ... });
|
|
4838
|
+
* ```
|
|
4839
|
+
*
|
|
4840
|
+
* @example Combined allow and deny
|
|
4841
|
+
* ```typescript
|
|
4842
|
+
* export const managerRoute = route.get('/manage')
|
|
4843
|
+
* .use([authenticate, roleGuard({ allow: ['admin', 'manager'], deny: ['suspended'] })])
|
|
4844
|
+
* .handler(async (c) => { ... });
|
|
4845
|
+
* ```
|
|
4846
|
+
*/
|
|
4847
|
+
declare const roleGuard: _spfn_core_route.NamedMiddlewareFactory<"roleGuard", [options: RoleGuardOptions]>;
|
|
4848
|
+
|
|
4718
4849
|
/**
|
|
4719
4850
|
* Auth Context Helpers
|
|
4720
4851
|
*
|
|
@@ -5068,4 +5199,4 @@ interface AuthLifecycleConfig {
|
|
|
5068
5199
|
*/
|
|
5069
5200
|
declare function createAuthLifecycle(options?: AuthInitOptions): AuthLifecycleConfig;
|
|
5070
5201
|
|
|
5071
|
-
export { type AuthConfig, AuthContext, COOKIE_NAMES, type EmailProvider, type EmailTemplateProvider, type EmailTemplateResult, type Invitation, InvitationStatus, InvitationsRepository, KeyAlgorithmType, type KeyPair, KeysRepository, type NewInvitation, type NewPermission, type NewPermissionEntity, type NewRole, type NewRoleEntity, type NewRolePermission, type NewUser, type NewUserPermission, type NewUserProfile, type NewUserPublicKey, type NewUserSocialAccount, type NewVerificationCode, type Permission, type PermissionEntity, PermissionsRepository, type Role, type RoleEntity, type RolePermission, RolePermissionsRepository, RolesRepository, type SMSProvider, type SendEmailParams, type SendEmailResult, type SendSMSParams, type SendSMSResult, type SessionData, type SessionPayload, type TokenPayload, type User, type UserPermission, UserPermissionsRepository, type UserProfile, UserProfilesRepository, type UserPublicKey, type UserSocialAccount, UsersRepository, type VerificationCode, type VerificationCodeParams, VerificationCodesRepository, VerificationPurpose, acceptInvitation, addPermissionToRole, authLogger, authSchema, cancelInvitation, configureAuth, createAuthLifecycle, createInvitation, createRole, decodeToken, deleteInvitation, deleteRole, expireOldInvitations, generateClientToken, generateKeyPair, generateKeyPairES256, generateKeyPairRS256, generateToken, getAllRoles, getAuth, getAuthConfig, getAuthSessionService, getInvitationByToken, getInvitationTemplate, getInvitationWithDetails, getKeyId, getKeySize, getPasswordResetTemplate, getRoleByName, getRolePermissions, getSessionInfo, getSessionTtl, getUser, getUserByEmailService, getUserByIdService, getUserByPhoneService, getUserId, getUserPermissions, getUserProfileService, getVerificationCodeTemplate, getWelcomeTemplate, hasAllPermissions, hasAnyPermission, hasAnyRole, hasPermission, hasRole, hashPassword, initializeAuth, invitationsRepository, keysRepository, listInvitations, parseDuration, permissions, permissionsRepository, registerEmailProvider, registerEmailTemplates, registerSMSProvider, removePermissionFromRole, requireAnyPermission, requirePermissions, requireRole, resendInvitation, rolePermissions, rolePermissionsRepository, roles, rolesRepository, sealSession, sendEmail, sendSMS, setRolePermissions, shouldRefreshSession, shouldRotateKey, unsealSession, updateLastLoginService, updateRole, updateUserService, userInvitations, userPermissions, userPermissionsRepository, userProfiles, userProfilesRepository, userPublicKeys, userSocialAccounts, users, usersRepository, validateInvitation, validatePasswordStrength, verificationCodes, verificationCodesRepository, verifyClientToken, verifyKeyFingerprint, verifyPassword, verifyToken };
|
|
5202
|
+
export { type AuthConfig, AuthContext, COOKIE_NAMES, type EmailProvider, type EmailTemplateProvider, type EmailTemplateResult, type Invitation, InvitationStatus, InvitationsRepository, KeyAlgorithmType, type KeyPair, KeysRepository, type NewInvitation, type NewPermission, type NewPermissionEntity, type NewRole, type NewRoleEntity, type NewRolePermission, type NewUser, type NewUserPermission, type NewUserProfile, type NewUserPublicKey, type NewUserSocialAccount, type NewVerificationCode, type Permission, type PermissionEntity, PermissionsRepository, type Role, type RoleEntity, type RoleGuardOptions, type RolePermission, RolePermissionsRepository, RolesRepository, type SMSProvider, type SendEmailParams, type SendEmailResult, type SendSMSParams, type SendSMSResult, type SessionData, type SessionPayload, type TokenPayload, type UpdateProfileParams, type User, type UserPermission, UserPermissionsRepository, type UserProfile, UserProfilesRepository, type UserPublicKey, type UserSocialAccount, UsersRepository, type VerificationCode, type VerificationCodeParams, VerificationCodesRepository, VerificationPurpose, acceptInvitation, addPermissionToRole, authLogger, authSchema, cancelInvitation, configureAuth, createAuthLifecycle, createInvitation, createRole, decodeToken, deleteInvitation, deleteRole, expireOldInvitations, generateClientToken, generateKeyPair, generateKeyPairES256, generateKeyPairRS256, generateToken, getAllRoles, getAuth, getAuthConfig, getAuthSessionService, getInvitationByToken, getInvitationTemplate, getInvitationWithDetails, getKeyId, getKeySize, getPasswordResetTemplate, getRoleByName, getRolePermissions, getSessionInfo, getSessionTtl, getUser, getUserByEmailService, getUserByIdService, getUserByPhoneService, getUserId, getUserPermissions, getUserProfileService, getUserRole, getVerificationCodeTemplate, getWelcomeTemplate, hasAllPermissions, hasAnyPermission, hasAnyRole, hasPermission, hasRole, hashPassword, initializeAuth, invitationsRepository, keysRepository, listInvitations, parseDuration, permissions, permissionsRepository, registerEmailProvider, registerEmailTemplates, registerSMSProvider, removePermissionFromRole, requireAnyPermission, requirePermissions, requireRole, resendInvitation, roleGuard, rolePermissions, rolePermissionsRepository, roles, rolesRepository, sealSession, sendEmail, sendSMS, setRolePermissions, shouldRefreshSession, shouldRotateKey, unsealSession, updateLastLoginService, updateRole, updateUserProfileService, updateUserService, userInvitations, userPermissions, userPermissionsRepository, userProfiles, userProfilesRepository, userPublicKeys, userSocialAccounts, users, usersRepository, validateInvitation, validatePasswordStrength, verificationCodes, verificationCodesRepository, verifyClientToken, verifyKeyFingerprint, verifyPassword, verifyToken };
|