@tuwaio/siwx-server 0.1.0 → 0.2.0

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/index.d.ts CHANGED
@@ -1,67 +1,85 @@
1
+ import * as _tuwaio_siwx_core from '@tuwaio/siwx-core';
1
2
  import { SiwxVerifyPayload } from '@tuwaio/siwx-core';
2
- export { SiwxSessionLike, generateNonce as generateServerNonce, isSessionMatchingTarget } from '@tuwaio/siwx-core';
3
- import { S as SiwxSession, C as CookieOptions, a as SerializedCookieSession, b as ServerVerifyOptions, c as ServerVerifyResult } from './types-CvnkVdoo.js';
4
- export { t as toSession } from './types-CvnkVdoo.js';
5
-
6
- /**
7
- * @fileoverview Server-side CAIP-122 payload verification and session utilities.
8
- * Backend-agnostic — compatible with any Node.js or Edge runtime (Next.js, NestJS, Hono, etc.).
9
- */
3
+ export { ParsedSiwxMessage, SiwxMessageFields, SiwxSessionLike, SiwxVerificationPolicy, ValidateMessageOptions, generateNonce, generateNonce as generateServerNonce, isSessionMatchingTarget, validateMessage, validatePolicy } from '@tuwaio/siwx-core';
4
+ import { S as SiwxNonceStore, a as SiwxSessionStore, b as SiwxSession, c as SiwxSessionRecord, C as CookieOptions, d as ServerVerifyOptions, e as ServerVerifyResult } from './types-Dz3SGS59.js';
5
+ export { f as StatelessDemoLimits, g as StatelessDemoTokenPayload, t as toSession } from './types-Dz3SGS59.js';
10
6
 
11
7
  /**
12
8
  * Parses and validates a raw CAIP-122 payload (message + signature) on the server side.
13
9
  * Dynamically routes verification to the correct chain adapter based on the CAIP-2 namespace.
14
10
  *
15
- * This function is the primary entry point for server-side authentication.
16
- * It handles EVM (eip155) and Solana chains.
17
- *
18
11
  * @param payload - The `{ message, signature }` payload sent by the client.
19
- * @param options - Optional server-side verification options (nonce replay protection, etc.).
12
+ * @param options - Server-side verification options (policy, nonce replay protection, etc.).
20
13
  * @returns A `ServerVerifyResult` with `success: true` and the parsed session data, or an error.
21
- *
22
- * @example
23
- * ```ts
24
- * // In a Next.js API route or NestJS controller:
25
- * const result = await verifySiwxPayload({ message, signature }, {
26
- * usedNonces: await redis.smembers('used_nonces'),
27
- * });
28
- * if (result.success) {
29
- * // Session is valid — issue a cookie or JWT
30
- * }
31
- * ```
32
14
  */
33
15
  declare function verifySiwxPayload(payload: SiwxVerifyPayload, options?: ServerVerifyOptions): Promise<ServerVerifyResult>;
34
16
  /**
35
- * Serializes a `SiwxSession` into an `HttpOnly` cookie string.
36
- * The session data is base64url-encoded (not encrypted — use a signed cookie or JWT for production).
17
+ * Signs a stateless demo session into an authenticated compact token.
18
+ * Uses Web Crypto HMAC-SHA256.
37
19
  *
38
- * This utility is intentionally simple. For production use, wrap the session
39
- * in a signed/encrypted format using a library like `iron-session` or `jose`.
40
- *
41
- * @param session - The verified session data to serialize.
42
- * @param opts - Cookie options (name, maxAge, secure, SameSite, etc.).
43
- * @returns A `SerializedCookieSession` containing the `Set-Cookie` header value and session data.
44
- *
45
- * @example
46
- * ```ts
47
- * const { cookieHeader } = serializeCookieSession(session);
48
- * return new Response(null, { headers: { 'Set-Cookie': cookieHeader } });
49
- * ```
20
+ * @param session - The verified session to sign.
21
+ * @param secret - Server-only signing secret (minimum 32 bytes).
22
+ * @param ttlSeconds - Maximum session validity in seconds (default 1800 = 30m).
23
+ * @returns Authenticated compact token in `${payload}.${signature}` format.
50
24
  */
51
- declare function serializeCookieSession(session: SiwxSession, opts?: CookieOptions): SerializedCookieSession;
25
+ declare function signStatelessDemoSession(session: SiwxSession, secret: string, ttlSeconds?: number): Promise<string>;
52
26
  /**
53
- * Deserializes a `SiwxSession` from a base64url-encoded cookie value.
54
- * This is the inverse of `serializeCookieSession`.
27
+ * Verifies an authenticated stateless demo session token.
28
+ * Performs constant-time cryptographic verification and validates expiration and policy.
55
29
  *
56
- * @param cookieValue - The raw cookie value string (not the full header).
57
- * @returns The deserialized `SiwxSession`, or `null` if the value is invalid or malformed.
58
- *
59
- * @example
60
- * ```ts
61
- * const session = deserializeCookieSession(request.cookies.get('siwx-session'));
62
- * if (session) console.log('Session address:', session.address);
63
- * ```
30
+ * @param token - Compact token from cookie (`${payload}.${signature}`).
31
+ * @param secret - Server-only signing secret.
32
+ * @param policy - Optional verification policy to enforce.
33
+ * @returns The verified SiwxSession, or null if invalid, expired, or tampered.
34
+ */
35
+ declare function verifyStatelessDemoSession(token: string | null | undefined, secret: string, policy?: _tuwaio_siwx_core.SiwxVerificationPolicy): Promise<SiwxSession | null>;
36
+ /**
37
+ * Creates an HttpOnly Set-Cookie header value for a session.
38
+ */
39
+ declare function createSessionCookie(value: string, opts?: CookieOptions): string;
40
+ /**
41
+ * Creates a clear/destroy Set-Cookie header value.
42
+ */
43
+ declare function createClearCookie(opts?: CookieOptions): string;
44
+ /**
45
+ * Extracts a cookie value by name from a raw Cookie header string.
46
+ */
47
+ declare function parseCookie(cookieHeader: string | null | undefined, name: string): string | null;
48
+ /**
49
+ * In-memory implementation of SiwxSessionStore.
50
+ * STRICTLY for local development, prototyping, and unit testing.
51
+ * Fails closed in production environments.
52
+ */
53
+ declare class MemorySiwxSessionStore implements SiwxSessionStore {
54
+ private records;
55
+ constructor(options?: {
56
+ allowInProduction?: boolean;
57
+ });
58
+ create(input: {
59
+ session: SiwxSession;
60
+ ttlSeconds: number;
61
+ }): Promise<SiwxSessionRecord>;
62
+ get(id: string): Promise<SiwxSessionRecord | null>;
63
+ bindSubject(id: string, subjectId: string): Promise<boolean>;
64
+ revoke(id: string): Promise<void>;
65
+ }
66
+ /**
67
+ * In-memory implementation of SiwxNonceStore.
68
+ * STRICTLY for local development, prototyping, and unit testing.
69
+ * Fails closed in production environments.
64
70
  */
65
- declare function deserializeCookieSession(cookieValue: string): SiwxSession | null;
71
+ declare class MemorySiwxNonceStore implements SiwxNonceStore {
72
+ private nonces;
73
+ constructor(options?: {
74
+ allowInProduction?: boolean;
75
+ });
76
+ issue(input: {
77
+ nonce: string;
78
+ ttlSeconds: number;
79
+ }): Promise<void>;
80
+ consume(input: {
81
+ nonce: string;
82
+ }): Promise<boolean>;
83
+ }
66
84
 
67
- export { CookieOptions, SerializedCookieSession, ServerVerifyOptions, ServerVerifyResult, SiwxSession, deserializeCookieSession, serializeCookieSession, verifySiwxPayload };
85
+ export { CookieOptions, MemorySiwxNonceStore, MemorySiwxSessionStore, ServerVerifyOptions, ServerVerifyResult, SiwxNonceStore, SiwxSession, SiwxSessionRecord, SiwxSessionStore, createClearCookie, createSessionCookie, parseCookie, signStatelessDemoSession, verifySiwxPayload, verifyStatelessDemoSession };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- 'use strict';var chunk47HTX7ZQ_js=require('./chunk-47HTX7ZQ.js'),siwxCore=require('@tuwaio/siwx-core');Object.defineProperty(exports,"deserializeCookieSession",{enumerable:true,get:function(){return chunk47HTX7ZQ_js.e}});Object.defineProperty(exports,"generateServerNonce",{enumerable:true,get:function(){return chunk47HTX7ZQ_js.b}});Object.defineProperty(exports,"serializeCookieSession",{enumerable:true,get:function(){return chunk47HTX7ZQ_js.d}});Object.defineProperty(exports,"toSession",{enumerable:true,get:function(){return chunk47HTX7ZQ_js.a}});Object.defineProperty(exports,"verifySiwxPayload",{enumerable:true,get:function(){return chunk47HTX7ZQ_js.c}});Object.defineProperty(exports,"isSessionMatchingTarget",{enumerable:true,get:function(){return siwxCore.isSessionMatchingTarget}});
1
+ 'use strict';var chunk4HK2SXOC_js=require('./chunk-4HK2SXOC.js'),siwxCore=require('@tuwaio/siwx-core');Object.defineProperty(exports,"MemorySiwxNonceStore",{enumerable:true,get:function(){return chunk4HK2SXOC_js.j}});Object.defineProperty(exports,"MemorySiwxSessionStore",{enumerable:true,get:function(){return chunk4HK2SXOC_js.i}});Object.defineProperty(exports,"createClearCookie",{enumerable:true,get:function(){return chunk4HK2SXOC_js.g}});Object.defineProperty(exports,"createSessionCookie",{enumerable:true,get:function(){return chunk4HK2SXOC_js.f}});Object.defineProperty(exports,"generateServerNonce",{enumerable:true,get:function(){return chunk4HK2SXOC_js.b}});Object.defineProperty(exports,"parseCookie",{enumerable:true,get:function(){return chunk4HK2SXOC_js.h}});Object.defineProperty(exports,"signStatelessDemoSession",{enumerable:true,get:function(){return chunk4HK2SXOC_js.d}});Object.defineProperty(exports,"toSession",{enumerable:true,get:function(){return chunk4HK2SXOC_js.a}});Object.defineProperty(exports,"verifySiwxPayload",{enumerable:true,get:function(){return chunk4HK2SXOC_js.c}});Object.defineProperty(exports,"verifyStatelessDemoSession",{enumerable:true,get:function(){return chunk4HK2SXOC_js.e}});Object.defineProperty(exports,"generateNonce",{enumerable:true,get:function(){return siwxCore.generateNonce}});Object.defineProperty(exports,"isSessionMatchingTarget",{enumerable:true,get:function(){return siwxCore.isSessionMatchingTarget}});Object.defineProperty(exports,"validateMessage",{enumerable:true,get:function(){return siwxCore.validateMessage}});Object.defineProperty(exports,"validatePolicy",{enumerable:true,get:function(){return siwxCore.validatePolicy}});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- export{e as deserializeCookieSession,b as generateServerNonce,d as serializeCookieSession,a as toSession,c as verifySiwxPayload}from'./chunk-JVIBIICZ.mjs';export{isSessionMatchingTarget}from'@tuwaio/siwx-core';
1
+ export{j as MemorySiwxNonceStore,i as MemorySiwxSessionStore,g as createClearCookie,f as createSessionCookie,b as generateServerNonce,h as parseCookie,d as signStatelessDemoSession,a as toSession,c as verifySiwxPayload,e as verifyStatelessDemoSession}from'./chunk-GQ7NU6NM.mjs';export{generateNonce,isSessionMatchingTarget,validateMessage,validatePolicy}from'@tuwaio/siwx-core';
package/dist/next.d.mts CHANGED
@@ -1,43 +1,120 @@
1
- import { C as CookieOptions, b as ServerVerifyOptions } from './types-CvnkVdoo.mjs';
2
- import '@tuwaio/siwx-core';
1
+ import { SiwxVerificationPolicy } from '@tuwaio/siwx-core';
2
+ import { a as SiwxSessionStore, S as SiwxNonceStore, C as CookieOptions, d as ServerVerifyOptions, f as StatelessDemoLimits } from './types-Dz3SGS59.mjs';
3
3
 
4
4
  /**
5
5
  * @fileoverview Next.js App Router (Route Handlers) API helper for SIWX.
6
+ * Provides durable production handler and stateless demo handler.
6
7
  */
7
8
 
8
9
  interface SiwxApiHandlerOptions {
9
10
  /**
10
- * Options for cookie serialization.
11
+ * Durable session store instance (e.g. RedisSiwxSessionStore or MemorySiwxSessionStore for tests).
12
+ */
13
+ sessionStore: SiwxSessionStore;
14
+ /**
15
+ * Durable single-use nonce store instance (e.g. RedisSiwxNonceStore or MemorySiwxNonceStore for tests).
16
+ */
17
+ nonceStore: SiwxNonceStore;
18
+ /**
19
+ * Verification policy to enforce (expected domains, URIs, allowed chains, expiration limits).
20
+ */
21
+ policy?: SiwxVerificationPolicy;
22
+ /**
23
+ * Cookie configuration options (name, secure, path, domain, maxAge).
24
+ */
25
+ cookieOptions?: CookieOptions;
26
+ /**
27
+ * Additional verification options (e.g. custom public client).
28
+ */
29
+ verifyOptions?: Omit<ServerVerifyOptions, 'policy' | 'usedNonces'>;
30
+ /**
31
+ * Session time-to-live in seconds (defaults to 7 days = 604800s).
32
+ */
33
+ ttlSeconds?: number;
34
+ }
35
+ interface StatelessDemoSiwxHandlerOptions {
36
+ /**
37
+ * Server-only cryptographic secret for HMAC signing (minimum 32 characters).
38
+ * MUST NEVER be exposed to the browser or client-side bundles.
39
+ */
40
+ signingSecret: string;
41
+ /**
42
+ * Verification policy to enforce.
43
+ */
44
+ policy?: SiwxVerificationPolicy;
45
+ /**
46
+ * Cookie configuration options.
11
47
  */
12
48
  cookieOptions?: CookieOptions;
13
49
  /**
14
- * Options for server-side payload verification (e.g. nonce replays, public client).
50
+ * Demo limits (payload size, max requests).
51
+ */
52
+ demoLimits?: StatelessDemoLimits;
53
+ /**
54
+ * Additional verification options.
15
55
  */
16
- verifyOptions?: ServerVerifyOptions;
56
+ verifyOptions?: Omit<ServerVerifyOptions, 'policy'>;
57
+ /**
58
+ * Session TTL in seconds for demo profile (defaults to 1800s = 30 minutes).
59
+ */
60
+ ttlSeconds?: number;
17
61
  }
18
62
  /**
19
- * Creates a ready-to-use Next.js App Router route handler for SIWX operations.
20
- * Exposes GET, POST, and DELETE methods that handle session verification, fetching, and logout.
21
- *
22
- * Works purely with the standard Web `Request` and `Response` objects natively
23
- * supported by Next.js Route Handlers.
63
+ * Creates a standard production Next.js App Router route handler for SIWX with durable storage.
64
+ * Requires persistent session and nonce stores (Redis, PostgreSQL, etc.).
24
65
  *
25
- * @param options - Optional configuration for cookies and verification.
26
- * @returns An object with `GET`, `POST`, and `DELETE` handlers.
66
+ * @param options - Configuration including sessionStore, nonceStore, and policy.
67
+ * @returns Object with `GET`, `POST`, and `DELETE` HTTP route handlers.
27
68
  *
28
69
  * @example
29
70
  * ```ts
30
71
  * // app/api/siwx/[...siwx]/route.ts
31
72
  * import { createSiwxApiHandler } from '@tuwaio/siwx-server/next';
73
+ * import { sessionStore, nonceStore } from '@/lib/authStores';
74
+ *
75
+ * const handler = createSiwxApiHandler({
76
+ * sessionStore,
77
+ * nonceStore,
78
+ * policy: { expectedDomain: 'app.tuwa.io' },
79
+ * });
80
+ *
81
+ * export const { GET, POST, DELETE } = handler;
82
+ * ```
83
+ */
84
+ declare function createSiwxApiHandler(options: SiwxApiHandlerOptions): {
85
+ GET: (req: Request) => Promise<Response>;
86
+ POST: (req: Request) => Promise<Response>;
87
+ DELETE: (req: Request) => Promise<Response>;
88
+ };
89
+ /**
90
+ * Creates a stateless demo Next.js App Router route handler for SIWX.
91
+ * Uses authenticated HMAC-SHA256 tokens in HttpOnly cookies without requiring Redis or a database.
92
+ *
93
+ * Intended STRICTLY for zero-infrastructure demonstration apps and website prototypes.
94
+ *
95
+ * @param options - Configuration including server signingSecret, policy, and demoLimits.
96
+ * @returns Object with `GET`, `POST`, and `DELETE` HTTP route handlers.
97
+ *
98
+ * @example
99
+ * ```ts
100
+ * // app/api/siwx/[...siwx]/route.ts
101
+ * import { createStatelessDemoSiwxHandler } from '@tuwaio/siwx-server/next';
102
+ *
103
+ * const handler = createStatelessDemoSiwxHandler({
104
+ * signingSecret: process.env.SIWX_DEMO_SIGNING_SECRET!,
105
+ * policy: {
106
+ * expectedDomain: 'tuwa.io',
107
+ * requireExpirationTime: true,
108
+ * },
109
+ * });
32
110
  *
33
- * const handler = createSiwxApiHandler();
34
111
  * export const { GET, POST, DELETE } = handler;
35
112
  * ```
36
113
  */
37
- declare function createSiwxApiHandler(options?: SiwxApiHandlerOptions): {
114
+ declare function createStatelessDemoSiwxHandler(options: StatelessDemoSiwxHandlerOptions): {
38
115
  GET: (req: Request) => Promise<Response>;
39
116
  POST: (req: Request) => Promise<Response>;
40
117
  DELETE: (req: Request) => Promise<Response>;
41
118
  };
42
119
 
43
- export { type SiwxApiHandlerOptions, createSiwxApiHandler };
120
+ export { type SiwxApiHandlerOptions, type StatelessDemoSiwxHandlerOptions, createSiwxApiHandler, createStatelessDemoSiwxHandler };
package/dist/next.d.ts CHANGED
@@ -1,43 +1,120 @@
1
- import { C as CookieOptions, b as ServerVerifyOptions } from './types-CvnkVdoo.js';
2
- import '@tuwaio/siwx-core';
1
+ import { SiwxVerificationPolicy } from '@tuwaio/siwx-core';
2
+ import { a as SiwxSessionStore, S as SiwxNonceStore, C as CookieOptions, d as ServerVerifyOptions, f as StatelessDemoLimits } from './types-Dz3SGS59.js';
3
3
 
4
4
  /**
5
5
  * @fileoverview Next.js App Router (Route Handlers) API helper for SIWX.
6
+ * Provides durable production handler and stateless demo handler.
6
7
  */
7
8
 
8
9
  interface SiwxApiHandlerOptions {
9
10
  /**
10
- * Options for cookie serialization.
11
+ * Durable session store instance (e.g. RedisSiwxSessionStore or MemorySiwxSessionStore for tests).
12
+ */
13
+ sessionStore: SiwxSessionStore;
14
+ /**
15
+ * Durable single-use nonce store instance (e.g. RedisSiwxNonceStore or MemorySiwxNonceStore for tests).
16
+ */
17
+ nonceStore: SiwxNonceStore;
18
+ /**
19
+ * Verification policy to enforce (expected domains, URIs, allowed chains, expiration limits).
20
+ */
21
+ policy?: SiwxVerificationPolicy;
22
+ /**
23
+ * Cookie configuration options (name, secure, path, domain, maxAge).
24
+ */
25
+ cookieOptions?: CookieOptions;
26
+ /**
27
+ * Additional verification options (e.g. custom public client).
28
+ */
29
+ verifyOptions?: Omit<ServerVerifyOptions, 'policy' | 'usedNonces'>;
30
+ /**
31
+ * Session time-to-live in seconds (defaults to 7 days = 604800s).
32
+ */
33
+ ttlSeconds?: number;
34
+ }
35
+ interface StatelessDemoSiwxHandlerOptions {
36
+ /**
37
+ * Server-only cryptographic secret for HMAC signing (minimum 32 characters).
38
+ * MUST NEVER be exposed to the browser or client-side bundles.
39
+ */
40
+ signingSecret: string;
41
+ /**
42
+ * Verification policy to enforce.
43
+ */
44
+ policy?: SiwxVerificationPolicy;
45
+ /**
46
+ * Cookie configuration options.
11
47
  */
12
48
  cookieOptions?: CookieOptions;
13
49
  /**
14
- * Options for server-side payload verification (e.g. nonce replays, public client).
50
+ * Demo limits (payload size, max requests).
51
+ */
52
+ demoLimits?: StatelessDemoLimits;
53
+ /**
54
+ * Additional verification options.
15
55
  */
16
- verifyOptions?: ServerVerifyOptions;
56
+ verifyOptions?: Omit<ServerVerifyOptions, 'policy'>;
57
+ /**
58
+ * Session TTL in seconds for demo profile (defaults to 1800s = 30 minutes).
59
+ */
60
+ ttlSeconds?: number;
17
61
  }
18
62
  /**
19
- * Creates a ready-to-use Next.js App Router route handler for SIWX operations.
20
- * Exposes GET, POST, and DELETE methods that handle session verification, fetching, and logout.
21
- *
22
- * Works purely with the standard Web `Request` and `Response` objects natively
23
- * supported by Next.js Route Handlers.
63
+ * Creates a standard production Next.js App Router route handler for SIWX with durable storage.
64
+ * Requires persistent session and nonce stores (Redis, PostgreSQL, etc.).
24
65
  *
25
- * @param options - Optional configuration for cookies and verification.
26
- * @returns An object with `GET`, `POST`, and `DELETE` handlers.
66
+ * @param options - Configuration including sessionStore, nonceStore, and policy.
67
+ * @returns Object with `GET`, `POST`, and `DELETE` HTTP route handlers.
27
68
  *
28
69
  * @example
29
70
  * ```ts
30
71
  * // app/api/siwx/[...siwx]/route.ts
31
72
  * import { createSiwxApiHandler } from '@tuwaio/siwx-server/next';
73
+ * import { sessionStore, nonceStore } from '@/lib/authStores';
74
+ *
75
+ * const handler = createSiwxApiHandler({
76
+ * sessionStore,
77
+ * nonceStore,
78
+ * policy: { expectedDomain: 'app.tuwa.io' },
79
+ * });
80
+ *
81
+ * export const { GET, POST, DELETE } = handler;
82
+ * ```
83
+ */
84
+ declare function createSiwxApiHandler(options: SiwxApiHandlerOptions): {
85
+ GET: (req: Request) => Promise<Response>;
86
+ POST: (req: Request) => Promise<Response>;
87
+ DELETE: (req: Request) => Promise<Response>;
88
+ };
89
+ /**
90
+ * Creates a stateless demo Next.js App Router route handler for SIWX.
91
+ * Uses authenticated HMAC-SHA256 tokens in HttpOnly cookies without requiring Redis or a database.
92
+ *
93
+ * Intended STRICTLY for zero-infrastructure demonstration apps and website prototypes.
94
+ *
95
+ * @param options - Configuration including server signingSecret, policy, and demoLimits.
96
+ * @returns Object with `GET`, `POST`, and `DELETE` HTTP route handlers.
97
+ *
98
+ * @example
99
+ * ```ts
100
+ * // app/api/siwx/[...siwx]/route.ts
101
+ * import { createStatelessDemoSiwxHandler } from '@tuwaio/siwx-server/next';
102
+ *
103
+ * const handler = createStatelessDemoSiwxHandler({
104
+ * signingSecret: process.env.SIWX_DEMO_SIGNING_SECRET!,
105
+ * policy: {
106
+ * expectedDomain: 'tuwa.io',
107
+ * requireExpirationTime: true,
108
+ * },
109
+ * });
32
110
  *
33
- * const handler = createSiwxApiHandler();
34
111
  * export const { GET, POST, DELETE } = handler;
35
112
  * ```
36
113
  */
37
- declare function createSiwxApiHandler(options?: SiwxApiHandlerOptions): {
114
+ declare function createStatelessDemoSiwxHandler(options: StatelessDemoSiwxHandlerOptions): {
38
115
  GET: (req: Request) => Promise<Response>;
39
116
  POST: (req: Request) => Promise<Response>;
40
117
  DELETE: (req: Request) => Promise<Response>;
41
118
  };
42
119
 
43
- export { type SiwxApiHandlerOptions, createSiwxApiHandler };
120
+ export { type SiwxApiHandlerOptions, type StatelessDemoSiwxHandlerOptions, createSiwxApiHandler, createStatelessDemoSiwxHandler };
package/dist/next.js CHANGED
@@ -1 +1 @@
1
- 'use strict';var chunk47HTX7ZQ_js=require('./chunk-47HTX7ZQ.js');function T(i={}){let p=i.cookieOptions?.name||"siwx-session",r=async e=>{try{let s="",c=new URL(e.url).pathname.split("/").filter(Boolean);if(s=c[c.length-1]||"",e.method==="GET"&&s==="session"){let t=e.headers.get("cookie")||"",o=Object.fromEntries(t.split("; ").filter(Boolean).map(S=>{let l=S.split("=");return [l[0].trim(),l.slice(1).join("=")]}))[p];if(!o)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let a=chunk47HTX7ZQ_js.e(o);return new Response(JSON.stringify(a),{status:200,headers:{"Content-Type":"application/json"}})}if(e.method==="POST"&&s==="verify"){let t=await e.json();if(!t.message||!t.signature)return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let n=await chunk47HTX7ZQ_js.c(t,i.verifyOptions);if(!n.success)return new Response(JSON.stringify({error:n.error}),{status:401,headers:{"Content-Type":"application/json"}});if(!n.data)return new Response(JSON.stringify({error:"Verification succeeded but returned no data"}),{status:500,headers:{"Content-Type":"application/json"}});let{cookieHeader:o,session:a}=chunk47HTX7ZQ_js.d(chunk47HTX7ZQ_js.a(n.data),i.cookieOptions);return new Response(JSON.stringify(a),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":o}})}return e.method==="DELETE"&&s==="session"||e.method==="POST"&&s==="logout"?new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":`${p}=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly; SameSite=Strict`}}):new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(s){return console.error("[SIWX-SERVER] API Handler error:",s),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:r,POST:r,DELETE:r}}exports.createSiwxApiHandler=T;
1
+ 'use strict';var chunk4HK2SXOC_js=require('./chunk-4HK2SXOC.js'),siwxCore=require('@tuwaio/siwx-core');function k(e){if(!e?.sessionStore||!e?.nonceStore)throw new Error("[SIWX-SERVER] createSiwxApiHandler requires both `sessionStore` and `nonceStore`. For zero-infrastructure demos without storage, use `createStatelessDemoSiwxHandler`.");let i=e.cookieOptions?.name||"siwx-session-v2",a=e.ttlSeconds??(e.cookieOptions?.maxAge||3600*24*7),r=async n=>{try{let p=new URL(n.url).pathname.split("/").filter(Boolean),o=p[p.length-1]||"";if(n.method==="GET"&&o==="session"){let t=chunk4HK2SXOC_js.h(n.headers.get("cookie"),i);if(!t)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let s=await e.sessionStore.get(t);return new Response(JSON.stringify(s?.session??null),{status:200,headers:{"Content-Type":"application/json"}})}if((n.method==="GET"||n.method==="POST")&&o==="nonce"){let t=siwxCore.generateNonce();return await e.nonceStore.issue({nonce:t,ttlSeconds:300}),new Response(JSON.stringify({nonce:t}),{status:200,headers:{"Content-Type":"application/json"}})}if(n.method==="POST"&&o==="verify"){let t=await n.json();if(!t.message||!t.signature)return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let s=await chunk4HK2SXOC_js.c(t,{...e.verifyOptions,policy:e.policy});if(!s.success||!s.data)return new Response(JSON.stringify({error:s.error||"Verification failed"}),{status:401,headers:{"Content-Type":"application/json"}});if(!await e.nonceStore.consume({nonce:s.data.nonce}))return new Response(JSON.stringify({error:"Nonce replay detected or nonce expired"}),{status:401,headers:{"Content-Type":"application/json"}});let S=chunk4HK2SXOC_js.a(s.data),d=await e.sessionStore.create({session:S,ttlSeconds:a}),T=chunk4HK2SXOC_js.f(d.id,{...e.cookieOptions,name:i,maxAge:a});return new Response(JSON.stringify(S),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":T}})}if(n.method==="DELETE"&&o==="session"||n.method==="POST"&&o==="logout"){let t=chunk4HK2SXOC_js.h(n.headers.get("cookie"),i);return t&&await e.sessionStore.revoke(t),new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":chunk4HK2SXOC_js.g({...e.cookieOptions,name:i})}})}return new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(c){return console.error("[SIWX-SERVER] Durable Handler error:",c),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:r,POST:r,DELETE:r}}function E(e){if(!e?.signingSecret||e.signingSecret.length<32)throw new Error("[SIWX-SERVER] createStatelessDemoSiwxHandler requires a `signingSecret` of at least 32 characters.");let i=e.cookieOptions?.name||"siwx-session-v2",a=e.ttlSeconds??(e.cookieOptions?.maxAge||1800),r=async n=>{try{let p=new URL(n.url).pathname.split("/").filter(Boolean),o=p[p.length-1]||"";if(n.method==="GET"&&o==="session"){let t=chunk4HK2SXOC_js.h(n.headers.get("cookie"),i);if(!t)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let s=await chunk4HK2SXOC_js.e(t,e.signingSecret,e.policy);return new Response(JSON.stringify(s),{status:200,headers:{"Content-Type":"application/json"}})}if((n.method==="GET"||n.method==="POST")&&o==="nonce"){let t=siwxCore.generateNonce();return new Response(JSON.stringify({nonce:t}),{status:200,headers:{"Content-Type":"application/json"}})}if(n.method==="POST"&&o==="verify"){let t=await n.json();if(!t.message||!t.signature)return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let s=await chunk4HK2SXOC_js.c(t,{...e.verifyOptions,policy:e.policy});if(!s.success||!s.data)return new Response(JSON.stringify({error:s.error||"Verification failed"}),{status:401,headers:{"Content-Type":"application/json"}});let u=chunk4HK2SXOC_js.a(s.data),S=await chunk4HK2SXOC_js.d(u,e.signingSecret,a),d=chunk4HK2SXOC_js.f(S,{...e.cookieOptions,name:i,maxAge:a});return new Response(JSON.stringify(u),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":d}})}return n.method==="DELETE"&&o==="session"||n.method==="POST"&&o==="logout"?new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":chunk4HK2SXOC_js.g({...e.cookieOptions,name:i})}}):new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(c){return console.error("[SIWX-SERVER] Stateless Demo Handler error:",c),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:r,POST:r,DELETE:r}}exports.createSiwxApiHandler=k;exports.createStatelessDemoSiwxHandler=E;
package/dist/next.mjs CHANGED
@@ -1 +1 @@
1
- import {e,c,d,a}from'./chunk-JVIBIICZ.mjs';function T(i={}){let p=i.cookieOptions?.name||"siwx-session",r=async e$1=>{try{let s="",c$1=new URL(e$1.url).pathname.split("/").filter(Boolean);if(s=c$1[c$1.length-1]||"",e$1.method==="GET"&&s==="session"){let t=e$1.headers.get("cookie")||"",o=Object.fromEntries(t.split("; ").filter(Boolean).map(S=>{let l=S.split("=");return [l[0].trim(),l.slice(1).join("=")]}))[p];if(!o)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let a=e(o);return new Response(JSON.stringify(a),{status:200,headers:{"Content-Type":"application/json"}})}if(e$1.method==="POST"&&s==="verify"){let t=await e$1.json();if(!t.message||!t.signature)return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let n=await c(t,i.verifyOptions);if(!n.success)return new Response(JSON.stringify({error:n.error}),{status:401,headers:{"Content-Type":"application/json"}});if(!n.data)return new Response(JSON.stringify({error:"Verification succeeded but returned no data"}),{status:500,headers:{"Content-Type":"application/json"}});let{cookieHeader:o,session:a$1}=d(a(n.data),i.cookieOptions);return new Response(JSON.stringify(a$1),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":o}})}return e$1.method==="DELETE"&&s==="session"||e$1.method==="POST"&&s==="logout"?new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":`${p}=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly; SameSite=Strict`}}):new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(s){return console.error("[SIWX-SERVER] API Handler error:",s),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:r,POST:r,DELETE:r}}export{T as createSiwxApiHandler};
1
+ import {h,c,a,f,g,e,d}from'./chunk-GQ7NU6NM.mjs';import {generateNonce}from'@tuwaio/siwx-core';function k(e){if(!e?.sessionStore||!e?.nonceStore)throw new Error("[SIWX-SERVER] createSiwxApiHandler requires both `sessionStore` and `nonceStore`. For zero-infrastructure demos without storage, use `createStatelessDemoSiwxHandler`.");let i=e.cookieOptions?.name||"siwx-session-v2",a$1=e.ttlSeconds??(e.cookieOptions?.maxAge||3600*24*7),r=async n=>{try{let p=new URL(n.url).pathname.split("/").filter(Boolean),o=p[p.length-1]||"";if(n.method==="GET"&&o==="session"){let t=h(n.headers.get("cookie"),i);if(!t)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let s=await e.sessionStore.get(t);return new Response(JSON.stringify(s?.session??null),{status:200,headers:{"Content-Type":"application/json"}})}if((n.method==="GET"||n.method==="POST")&&o==="nonce"){let t=generateNonce();return await e.nonceStore.issue({nonce:t,ttlSeconds:300}),new Response(JSON.stringify({nonce:t}),{status:200,headers:{"Content-Type":"application/json"}})}if(n.method==="POST"&&o==="verify"){let t=await n.json();if(!t.message||!t.signature)return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let s=await c(t,{...e.verifyOptions,policy:e.policy});if(!s.success||!s.data)return new Response(JSON.stringify({error:s.error||"Verification failed"}),{status:401,headers:{"Content-Type":"application/json"}});if(!await e.nonceStore.consume({nonce:s.data.nonce}))return new Response(JSON.stringify({error:"Nonce replay detected or nonce expired"}),{status:401,headers:{"Content-Type":"application/json"}});let S=a(s.data),d=await e.sessionStore.create({session:S,ttlSeconds:a$1}),T=f(d.id,{...e.cookieOptions,name:i,maxAge:a$1});return new Response(JSON.stringify(S),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":T}})}if(n.method==="DELETE"&&o==="session"||n.method==="POST"&&o==="logout"){let t=h(n.headers.get("cookie"),i);return t&&await e.sessionStore.revoke(t),new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":g({...e.cookieOptions,name:i})}})}return new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(c){return console.error("[SIWX-SERVER] Durable Handler error:",c),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:r,POST:r,DELETE:r}}function E(e$1){if(!e$1?.signingSecret||e$1.signingSecret.length<32)throw new Error("[SIWX-SERVER] createStatelessDemoSiwxHandler requires a `signingSecret` of at least 32 characters.");let i=e$1.cookieOptions?.name||"siwx-session-v2",a$1=e$1.ttlSeconds??(e$1.cookieOptions?.maxAge||1800),r=async n=>{try{let p=new URL(n.url).pathname.split("/").filter(Boolean),o=p[p.length-1]||"";if(n.method==="GET"&&o==="session"){let t=h(n.headers.get("cookie"),i);if(!t)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let s=await e(t,e$1.signingSecret,e$1.policy);return new Response(JSON.stringify(s),{status:200,headers:{"Content-Type":"application/json"}})}if((n.method==="GET"||n.method==="POST")&&o==="nonce"){let t=generateNonce();return new Response(JSON.stringify({nonce:t}),{status:200,headers:{"Content-Type":"application/json"}})}if(n.method==="POST"&&o==="verify"){let t=await n.json();if(!t.message||!t.signature)return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let s=await c(t,{...e$1.verifyOptions,policy:e$1.policy});if(!s.success||!s.data)return new Response(JSON.stringify({error:s.error||"Verification failed"}),{status:401,headers:{"Content-Type":"application/json"}});let u=a(s.data),S=await d(u,e$1.signingSecret,a$1),d$1=f(S,{...e$1.cookieOptions,name:i,maxAge:a$1});return new Response(JSON.stringify(u),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":d$1}})}return n.method==="DELETE"&&o==="session"||n.method==="POST"&&o==="logout"?new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":g({...e$1.cookieOptions,name:i})}}):new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(c){return console.error("[SIWX-SERVER] Stateless Demo Handler error:",c),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:r,POST:r,DELETE:r}}export{k as createSiwxApiHandler,E as createStatelessDemoSiwxHandler};