@tuwaio/siwx-server 0.2.2 → 0.4.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/next.d.mts CHANGED
@@ -1,71 +1,93 @@
1
1
  import { SiwxVerificationPolicy } from '@tuwaio/siwx-core';
2
2
  import { SiwxSessionStore, SiwxNonceStore, CookieOptions, ServerVerifyOptions, StatelessDemoLimits } from './index.mjs';
3
3
  export { GetSiwxServerSessionOptions, getSiwxServerSession } from './index.mjs';
4
+ import 'viem';
4
5
 
5
6
  /**
6
- * @fileoverview Next.js App Router (Route Handlers) API helper for SIWX.
7
- * Provides durable production handler and stateless demo handler.
7
+ * Next.js App Router route handlers, imported from `@tuwaio/siwx-server/next`.
8
+ *
9
+ * @module next
8
10
  */
9
11
 
10
12
  interface SiwxApiHandlerOptions {
11
13
  /**
12
- * Durable session store instance (e.g. RedisSiwxSessionStore or MemorySiwxSessionStore for tests).
14
+ * Durable session store shared by every server instance (your Redis or database implementation;
15
+ * `MemorySiwxSessionStore` in development and tests).
13
16
  */
14
17
  sessionStore: SiwxSessionStore;
15
18
  /**
16
- * Durable single-use nonce store instance (e.g. RedisSiwxNonceStore or MemorySiwxNonceStore for tests).
19
+ * Durable single-use nonce store shared by every server instance (your Redis or database implementation;
20
+ * `MemorySiwxNonceStore` in development and tests).
17
21
  */
18
22
  nonceStore: SiwxNonceStore;
19
23
  /**
20
- * Verification policy to enforce (expected domains, URIs, allowed chains, expiration limits).
24
+ * Policy enforced by `POST /verify` (domain, URI, chains, timing). Set at least `expectedDomain`: without a policy
25
+ * the message domain is not checked.
21
26
  */
22
27
  policy?: SiwxVerificationPolicy;
23
28
  /**
24
- * Cookie configuration options (name, secure, path, domain, maxAge).
29
+ * Attributes of the session cookie. `maxAge` is replaced by the session TTL.
25
30
  */
26
31
  cookieOptions?: CookieOptions;
27
32
  /**
28
- * Additional verification options (e.g. custom public client).
33
+ * Extra options of `verifySiwxPayload`, for example `publicClient` for EIP-1271 wallets.
29
34
  */
30
35
  verifyOptions?: Omit<ServerVerifyOptions, 'policy' | 'usedNonces'>;
31
36
  /**
32
- * Session time-to-live in seconds (defaults to 7 days = 604800s).
37
+ * Session lifetime in seconds, used for the store record and the cookie `Max-Age`. Defaults to
38
+ * `cookieOptions.maxAge`, then to 604800 (7 days).
33
39
  */
34
40
  ttlSeconds?: number;
35
41
  }
42
+ /**
43
+ * Options of {@link createStatelessDemoSiwxHandler}.
44
+ */
36
45
  interface StatelessDemoSiwxHandlerOptions {
37
46
  /**
38
- * Server-only cryptographic secret for HMAC signing (minimum 32 characters).
39
- * MUST NEVER be exposed to the browser or client-side bundles.
47
+ * Server-only HMAC secret of at least 32 characters. Never expose it to the browser. Rotating it invalidates every
48
+ * issued token.
40
49
  */
41
50
  signingSecret: string;
42
51
  /**
43
- * Verification policy to enforce.
52
+ * Policy enforced by `POST /verify`. For the demo profile, set `expectedDomain`, `requireExpirationTime` and a
53
+ * short `maxSessionLifetimeSeconds`.
44
54
  */
45
55
  policy?: SiwxVerificationPolicy;
46
56
  /**
47
- * Cookie configuration options.
57
+ * Attributes of the session cookie. `maxAge` is replaced by the token TTL.
48
58
  */
49
59
  cookieOptions?: CookieOptions;
50
60
  /**
51
- * Demo limits (payload size, max requests).
61
+ * Request limits (maximum body size of `POST /verify`).
52
62
  */
53
63
  demoLimits?: StatelessDemoLimits;
54
64
  /**
55
- * Additional verification options.
65
+ * Extra options of `verifySiwxPayload`, for example `publicClient` or `usedNonces`.
56
66
  */
57
67
  verifyOptions?: Omit<ServerVerifyOptions, 'policy'>;
58
68
  /**
59
- * Session TTL in seconds for demo profile (defaults to 1800s = 30 minutes).
69
+ * Token and cookie lifetime in seconds. Defaults to `cookieOptions.maxAge`, then to 1800 (30 minutes). A message
70
+ * `expirationTime`, when present, sets the token expiry instead.
60
71
  */
61
72
  ttlSeconds?: number;
62
73
  }
63
74
  /**
64
- * Creates a standard production Next.js App Router route handler for SIWX with durable storage.
65
- * Requires persistent session and nonce stores (Redis, PostgreSQL, etc.).
75
+ * Creates the SIWX route handlers of the durable (production) profile for a Next.js App Router catch-all route,
76
+ * for example `app/api/siwx/[...siwx]/route.ts`. The action is taken from the last path segment:
77
+ *
78
+ * - `GET|POST …/nonce`: issues a nonce, stores it in `nonceStore` for 300 seconds and returns `{ nonce }`.
79
+ * - `POST …/verify`: accepts a JSON `{ message, signature }` of up to 64 KB, runs `verifySiwxPayload` with the
80
+ * policy, consumes the nonce (so only nonces issued by `/nonce` are accepted, once), creates a session in
81
+ * `sessionStore`, sets the session ID as an `HttpOnly` cookie and returns the `SiwxSession` JSON.
82
+ * Responds 400 for a malformed body, 401 for a failed verification or nonce, 413 for a too large body.
83
+ * - `GET …/session`: returns the stored session of the cookie, or `null`.
84
+ * - `DELETE …/session` or `POST …/logout`: revokes the session in the store and clears the cookie.
66
85
  *
67
- * @param options - Configuration including sessionStore, nonceStore, and policy.
68
- * @returns Object with `GET`, `POST`, and `DELETE` HTTP route handlers.
86
+ * Other paths return 404; unexpected errors are logged with `console.error` and return 500.
87
+ *
88
+ * @param options - Stores, policy, cookie and verification options.
89
+ * @returns Route handlers to export as `GET`, `POST` and `DELETE`.
90
+ * @throws {Error} If `sessionStore` or `nonceStore` is missing.
69
91
  *
70
92
  * @example
71
93
  * ```ts
@@ -88,13 +110,28 @@ declare function createSiwxApiHandler(options: SiwxApiHandlerOptions): {
88
110
  DELETE: (req: Request) => Promise<Response>;
89
111
  };
90
112
  /**
91
- * Creates a stateless demo Next.js App Router route handler for SIWX.
92
- * Uses authenticated HMAC-SHA256 tokens in HttpOnly cookies without requiring Redis or a database.
113
+ * Creates the SIWX route handlers of the stateless demo profile for a Next.js App Router catch-all route. The
114
+ * session is an HMAC-signed token in an `HttpOnly` cookie (see {@link signStatelessDemoSession}), so no database or
115
+ * Redis is needed. Intended for demos and prototypes only.
116
+ *
117
+ * - `GET|POST …/nonce`: returns `{ nonce }`, a nonce signed with the secret and valid for 300 seconds (see
118
+ * {@link issueStatelessDemoNonce}). Nothing is stored.
119
+ * - `POST …/verify`: accepts a JSON `{ message, signature }` (size limit from `demoLimits`), runs
120
+ * `verifySiwxPayload` with the policy, accepts the message nonce only if it was issued by `/nonce`, has not
121
+ * expired and has not been used before on this server instance, sets the signed token as the session cookie and
122
+ * returns the `SiwxSession` JSON. Responds 400, 401 or 413 like the durable handler.
123
+ * - `GET …/session`: verifies the cookie token and returns the session, or `null`.
124
+ * - `DELETE …/session` or `POST …/logout`: clears the cookie.
125
+ *
126
+ * Security limits: used nonces are remembered in the memory of each server instance only, so with several instances
127
+ * a signed message can be replayed on another instance within the 300-second nonce lifetime; tokens cannot be
128
+ * revoked before they expire. Keep `requireExpirationTime` and a short `maxSessionLifetimeSeconds`.
93
129
  *
94
- * Intended STRICTLY for zero-infrastructure demonstration apps and website prototypes.
130
+ * Side effects: keeps the used nonces of this handler in memory until they expire.
95
131
  *
96
- * @param options - Configuration including server signingSecret, policy, and demoLimits.
97
- * @returns Object with `GET`, `POST`, and `DELETE` HTTP route handlers.
132
+ * @param options - Signing secret, policy, cookie, limits and verification options.
133
+ * @returns Route handlers to export as `GET`, `POST` and `DELETE`.
134
+ * @throws {Error} If `signingSecret` is missing or shorter than 32 characters.
98
135
  *
99
136
  * @example
100
137
  * ```ts
package/dist/next.d.ts CHANGED
@@ -1,71 +1,93 @@
1
1
  import { SiwxVerificationPolicy } from '@tuwaio/siwx-core';
2
2
  import { SiwxSessionStore, SiwxNonceStore, CookieOptions, ServerVerifyOptions, StatelessDemoLimits } from './index.js';
3
3
  export { GetSiwxServerSessionOptions, getSiwxServerSession } from './index.js';
4
+ import 'viem';
4
5
 
5
6
  /**
6
- * @fileoverview Next.js App Router (Route Handlers) API helper for SIWX.
7
- * Provides durable production handler and stateless demo handler.
7
+ * Next.js App Router route handlers, imported from `@tuwaio/siwx-server/next`.
8
+ *
9
+ * @module next
8
10
  */
9
11
 
10
12
  interface SiwxApiHandlerOptions {
11
13
  /**
12
- * Durable session store instance (e.g. RedisSiwxSessionStore or MemorySiwxSessionStore for tests).
14
+ * Durable session store shared by every server instance (your Redis or database implementation;
15
+ * `MemorySiwxSessionStore` in development and tests).
13
16
  */
14
17
  sessionStore: SiwxSessionStore;
15
18
  /**
16
- * Durable single-use nonce store instance (e.g. RedisSiwxNonceStore or MemorySiwxNonceStore for tests).
19
+ * Durable single-use nonce store shared by every server instance (your Redis or database implementation;
20
+ * `MemorySiwxNonceStore` in development and tests).
17
21
  */
18
22
  nonceStore: SiwxNonceStore;
19
23
  /**
20
- * Verification policy to enforce (expected domains, URIs, allowed chains, expiration limits).
24
+ * Policy enforced by `POST /verify` (domain, URI, chains, timing). Set at least `expectedDomain`: without a policy
25
+ * the message domain is not checked.
21
26
  */
22
27
  policy?: SiwxVerificationPolicy;
23
28
  /**
24
- * Cookie configuration options (name, secure, path, domain, maxAge).
29
+ * Attributes of the session cookie. `maxAge` is replaced by the session TTL.
25
30
  */
26
31
  cookieOptions?: CookieOptions;
27
32
  /**
28
- * Additional verification options (e.g. custom public client).
33
+ * Extra options of `verifySiwxPayload`, for example `publicClient` for EIP-1271 wallets.
29
34
  */
30
35
  verifyOptions?: Omit<ServerVerifyOptions, 'policy' | 'usedNonces'>;
31
36
  /**
32
- * Session time-to-live in seconds (defaults to 7 days = 604800s).
37
+ * Session lifetime in seconds, used for the store record and the cookie `Max-Age`. Defaults to
38
+ * `cookieOptions.maxAge`, then to 604800 (7 days).
33
39
  */
34
40
  ttlSeconds?: number;
35
41
  }
42
+ /**
43
+ * Options of {@link createStatelessDemoSiwxHandler}.
44
+ */
36
45
  interface StatelessDemoSiwxHandlerOptions {
37
46
  /**
38
- * Server-only cryptographic secret for HMAC signing (minimum 32 characters).
39
- * MUST NEVER be exposed to the browser or client-side bundles.
47
+ * Server-only HMAC secret of at least 32 characters. Never expose it to the browser. Rotating it invalidates every
48
+ * issued token.
40
49
  */
41
50
  signingSecret: string;
42
51
  /**
43
- * Verification policy to enforce.
52
+ * Policy enforced by `POST /verify`. For the demo profile, set `expectedDomain`, `requireExpirationTime` and a
53
+ * short `maxSessionLifetimeSeconds`.
44
54
  */
45
55
  policy?: SiwxVerificationPolicy;
46
56
  /**
47
- * Cookie configuration options.
57
+ * Attributes of the session cookie. `maxAge` is replaced by the token TTL.
48
58
  */
49
59
  cookieOptions?: CookieOptions;
50
60
  /**
51
- * Demo limits (payload size, max requests).
61
+ * Request limits (maximum body size of `POST /verify`).
52
62
  */
53
63
  demoLimits?: StatelessDemoLimits;
54
64
  /**
55
- * Additional verification options.
65
+ * Extra options of `verifySiwxPayload`, for example `publicClient` or `usedNonces`.
56
66
  */
57
67
  verifyOptions?: Omit<ServerVerifyOptions, 'policy'>;
58
68
  /**
59
- * Session TTL in seconds for demo profile (defaults to 1800s = 30 minutes).
69
+ * Token and cookie lifetime in seconds. Defaults to `cookieOptions.maxAge`, then to 1800 (30 minutes). A message
70
+ * `expirationTime`, when present, sets the token expiry instead.
60
71
  */
61
72
  ttlSeconds?: number;
62
73
  }
63
74
  /**
64
- * Creates a standard production Next.js App Router route handler for SIWX with durable storage.
65
- * Requires persistent session and nonce stores (Redis, PostgreSQL, etc.).
75
+ * Creates the SIWX route handlers of the durable (production) profile for a Next.js App Router catch-all route,
76
+ * for example `app/api/siwx/[...siwx]/route.ts`. The action is taken from the last path segment:
77
+ *
78
+ * - `GET|POST …/nonce`: issues a nonce, stores it in `nonceStore` for 300 seconds and returns `{ nonce }`.
79
+ * - `POST …/verify`: accepts a JSON `{ message, signature }` of up to 64 KB, runs `verifySiwxPayload` with the
80
+ * policy, consumes the nonce (so only nonces issued by `/nonce` are accepted, once), creates a session in
81
+ * `sessionStore`, sets the session ID as an `HttpOnly` cookie and returns the `SiwxSession` JSON.
82
+ * Responds 400 for a malformed body, 401 for a failed verification or nonce, 413 for a too large body.
83
+ * - `GET …/session`: returns the stored session of the cookie, or `null`.
84
+ * - `DELETE …/session` or `POST …/logout`: revokes the session in the store and clears the cookie.
66
85
  *
67
- * @param options - Configuration including sessionStore, nonceStore, and policy.
68
- * @returns Object with `GET`, `POST`, and `DELETE` HTTP route handlers.
86
+ * Other paths return 404; unexpected errors are logged with `console.error` and return 500.
87
+ *
88
+ * @param options - Stores, policy, cookie and verification options.
89
+ * @returns Route handlers to export as `GET`, `POST` and `DELETE`.
90
+ * @throws {Error} If `sessionStore` or `nonceStore` is missing.
69
91
  *
70
92
  * @example
71
93
  * ```ts
@@ -88,13 +110,28 @@ declare function createSiwxApiHandler(options: SiwxApiHandlerOptions): {
88
110
  DELETE: (req: Request) => Promise<Response>;
89
111
  };
90
112
  /**
91
- * Creates a stateless demo Next.js App Router route handler for SIWX.
92
- * Uses authenticated HMAC-SHA256 tokens in HttpOnly cookies without requiring Redis or a database.
113
+ * Creates the SIWX route handlers of the stateless demo profile for a Next.js App Router catch-all route. The
114
+ * session is an HMAC-signed token in an `HttpOnly` cookie (see {@link signStatelessDemoSession}), so no database or
115
+ * Redis is needed. Intended for demos and prototypes only.
116
+ *
117
+ * - `GET|POST …/nonce`: returns `{ nonce }`, a nonce signed with the secret and valid for 300 seconds (see
118
+ * {@link issueStatelessDemoNonce}). Nothing is stored.
119
+ * - `POST …/verify`: accepts a JSON `{ message, signature }` (size limit from `demoLimits`), runs
120
+ * `verifySiwxPayload` with the policy, accepts the message nonce only if it was issued by `/nonce`, has not
121
+ * expired and has not been used before on this server instance, sets the signed token as the session cookie and
122
+ * returns the `SiwxSession` JSON. Responds 400, 401 or 413 like the durable handler.
123
+ * - `GET …/session`: verifies the cookie token and returns the session, or `null`.
124
+ * - `DELETE …/session` or `POST …/logout`: clears the cookie.
125
+ *
126
+ * Security limits: used nonces are remembered in the memory of each server instance only, so with several instances
127
+ * a signed message can be replayed on another instance within the 300-second nonce lifetime; tokens cannot be
128
+ * revoked before they expire. Keep `requireExpirationTime` and a short `maxSessionLifetimeSeconds`.
93
129
  *
94
- * Intended STRICTLY for zero-infrastructure demonstration apps and website prototypes.
130
+ * Side effects: keeps the used nonces of this handler in memory until they expire.
95
131
  *
96
- * @param options - Configuration including server signingSecret, policy, and demoLimits.
97
- * @returns Object with `GET`, `POST`, and `DELETE` HTTP route handlers.
132
+ * @param options - Signing secret, policy, cookie, limits and verification options.
133
+ * @returns Route handlers to export as `GET`, `POST` and `DELETE`.
134
+ * @throws {Error} If `signingSecret` is missing or shorter than 32 characters.
98
135
  *
99
136
  * @example
100
137
  * ```ts
package/dist/next.js CHANGED
@@ -1 +1 @@
1
- 'use strict';var chunkWPKBWXVR_js=require('./chunk-WPKBWXVR.js'),siwxCore=require('@tuwaio/siwx-core');function j(e){if(!e?.sessionStore||!e?.nonceStore)throw new Error("[SIWX-SERVER] createSiwxApiHandler requires both `sessionStore` and `nonceStore`.");let a=e.cookieOptions?.name||"siwx-session-v2",p=e.ttlSeconds??(e.cookieOptions?.maxAge||3600*24*7),l=65536,c=async t=>{try{let d=new URL(t.url).pathname.split("/").filter(Boolean),o=d[d.length-1]||"";if(t.method==="GET"&&o==="session"){let n=chunkWPKBWXVR_js.h(t.headers.get("cookie"),a);if(!n)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let i=await e.sessionStore.get(n);return new Response(JSON.stringify(i?.session??null),{status:200,headers:{"Content-Type":"application/json"}})}if((t.method==="GET"||t.method==="POST")&&o==="nonce"){let n=siwxCore.generateNonce();return await e.nonceStore.issue({nonce:n,ttlSeconds:300}),new Response(JSON.stringify({nonce:n}),{status:200,headers:{"Content-Type":"application/json"}})}if(t.method==="POST"&&o==="verify"){let n=t.headers.get("content-length");if(n&&parseInt(n,10)>l)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let i=await t.text();if(i.length>l)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let s;try{s=JSON.parse(i);}catch{return new Response(JSON.stringify({error:"Invalid JSON payload"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!s||typeof s.message!="string"||typeof s.signature!="string")return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let g={message:s.message,signature:s.signature},r=await chunkWPKBWXVR_js.c(g,{...e.verifyOptions,policy:e.policy});if(!r.success||!r.data)return new Response(JSON.stringify({error:r.error||"Verification failed"}),{status:401,headers:{"Content-Type":"application/json"}});if(!await e.nonceStore.consume({nonce:r.data.nonce}))return new Response(JSON.stringify({error:"Nonce replay detected or nonce expired"}),{status:401,headers:{"Content-Type":"application/json"}});let y=chunkWPKBWXVR_js.a(r.data),w=await e.sessionStore.create({session:y,ttlSeconds:p}),x=chunkWPKBWXVR_js.f(w.id,{...e.cookieOptions,name:a,maxAge:p});return new Response(JSON.stringify(y),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":x}})}if(t.method==="DELETE"&&o==="session"||t.method==="POST"&&o==="logout"){let n=chunkWPKBWXVR_js.h(t.headers.get("cookie"),a);return n&&await e.sessionStore.revoke(n),new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":chunkWPKBWXVR_js.g({...e.cookieOptions,name:a})}})}return new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(S){return console.error("[SIWX-SERVER] Durable Handler error:",S),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:c,POST:c,DELETE:c}}function P(e){if(!e?.signingSecret||e.signingSecret.length<32)throw new Error("[SIWX-SERVER] createStatelessDemoSiwxHandler requires a `signingSecret` of at least 32 characters.");let a=e.cookieOptions?.name||"siwx-session-v2",p=e.ttlSeconds??(e.cookieOptions?.maxAge||1800),l=e.demoLimits?.maxTransactionPayloadBytes??65536,c=async t=>{try{let d=new URL(t.url).pathname.split("/").filter(Boolean),o=d[d.length-1]||"";if(t.method==="GET"&&o==="session"){let n=chunkWPKBWXVR_js.h(t.headers.get("cookie"),a);if(!n)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let i=await chunkWPKBWXVR_js.e(n,e.signingSecret,e.policy);return new Response(JSON.stringify(i),{status:200,headers:{"Content-Type":"application/json"}})}if((t.method==="GET"||t.method==="POST")&&o==="nonce"){let n=siwxCore.generateNonce();return new Response(JSON.stringify({nonce:n}),{status:200,headers:{"Content-Type":"application/json"}})}if(t.method==="POST"&&o==="verify"){let n=t.headers.get("content-length");if(n&&parseInt(n,10)>l)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let i=await t.text();if(i.length>l)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let s;try{s=JSON.parse(i);}catch{return new Response(JSON.stringify({error:"Invalid JSON payload"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!s||typeof s.message!="string"||typeof s.signature!="string")return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let g={message:s.message,signature:s.signature},r=await chunkWPKBWXVR_js.c(g,{...e.verifyOptions,policy:e.policy});if(!r.success||!r.data)return new Response(JSON.stringify({error:r.error||"Verification failed"}),{status:401,headers:{"Content-Type":"application/json"}});let f=chunkWPKBWXVR_js.a(r.data),y=await chunkWPKBWXVR_js.d(f,e.signingSecret,p),w=chunkWPKBWXVR_js.f(y,{...e.cookieOptions,name:a,maxAge:p});return new Response(JSON.stringify(f),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":w}})}return t.method==="DELETE"&&o==="session"||t.method==="POST"&&o==="logout"?new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":chunkWPKBWXVR_js.g({...e.cookieOptions,name:a})}}):new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(S){return console.error("[SIWX-SERVER] Stateless Demo Handler error:",S),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:c,POST:c,DELETE:c}}Object.defineProperty(exports,"getSiwxServerSession",{enumerable:true,get:function(){return chunkWPKBWXVR_js.k}});exports.createSiwxApiHandler=j;exports.createStatelessDemoSiwxHandler=P;
1
+ 'use strict';var chunkSS5KJYWU_js=require('./chunk-SS5KJYWU.js'),siwxCore=require('@tuwaio/siwx-core');var T=300;function H(e){if(!e?.sessionStore||!e?.nonceStore)throw new Error("[SIWX-SERVER] createSiwxApiHandler requires both `sessionStore` and `nonceStore`.");let p=e.cookieOptions?.name||"siwx-session-v2",u=e.ttlSeconds??(e.cookieOptions?.maxAge||3600*24*7),y=65536,l=async o=>{try{let t=new URL(o.url).pathname.split("/").filter(Boolean),a=t[t.length-1]||"";if(o.method==="GET"&&a==="session"){let n=chunkSS5KJYWU_js.j(o.headers.get("cookie"),p);if(!n)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let r=await e.sessionStore.get(n);return new Response(JSON.stringify(r?.session??null),{status:200,headers:{"Content-Type":"application/json"}})}if((o.method==="GET"||o.method==="POST")&&a==="nonce"){let n=siwxCore.generateNonce();return await e.nonceStore.issue({nonce:n,ttlSeconds:T}),new Response(JSON.stringify({nonce:n}),{status:200,headers:{"Content-Type":"application/json"}})}if(o.method==="POST"&&a==="verify"){let n=o.headers.get("content-length");if(n&&parseInt(n,10)>y)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let r=await o.text();if(r.length>y)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let s;try{s=JSON.parse(r);}catch{return new Response(JSON.stringify({error:"Invalid JSON payload"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!s||typeof s.message!="string"||typeof s.signature!="string")return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let d={message:s.message,signature:s.signature},i=await chunkSS5KJYWU_js.c(d,{...e.verifyOptions,policy:e.policy});if(!i.success||!i.data)return new Response(JSON.stringify({error:i.error||"Verification failed"}),{status:401,headers:{"Content-Type":"application/json"}});if(!await e.nonceStore.consume({nonce:i.data.nonce}))return new Response(JSON.stringify({error:"Nonce replay detected or nonce expired"}),{status:401,headers:{"Content-Type":"application/json"}});let c=chunkSS5KJYWU_js.a(i.data),C=await e.sessionStore.create({session:c,ttlSeconds:u}),g=chunkSS5KJYWU_js.h(C.id,{...e.cookieOptions,name:p,maxAge:u});return new Response(JSON.stringify(c),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":g}})}if(o.method==="DELETE"&&a==="session"||o.method==="POST"&&a==="logout"){let n=chunkSS5KJYWU_js.j(o.headers.get("cookie"),p);return n&&await e.sessionStore.revoke(n),new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":chunkSS5KJYWU_js.i({...e.cookieOptions,name:p})}})}return new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(S){return console.error("[SIWX-SERVER] Durable Handler error:",S),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:l,POST:l,DELETE:l}}function V(e){if(!e?.signingSecret||e.signingSecret.length<32)throw new Error("[SIWX-SERVER] createStatelessDemoSiwxHandler requires a `signingSecret` of at least 32 characters.");let p=e.cookieOptions?.name||"siwx-session-v2",u=e.ttlSeconds??(e.cookieOptions?.maxAge||1800),y=e.demoLimits?.maxTransactionPayloadBytes??65536,l=new Map,o=t=>{let a=Date.now();for(let[n,r]of l)r<a&&l.delete(n);return l.has(t)?false:(l.set(t,a+T*1e3),true)},S=async t=>{try{let n=new URL(t.url).pathname.split("/").filter(Boolean),r=n[n.length-1]||"";if(t.method==="GET"&&r==="session"){let s=chunkSS5KJYWU_js.j(t.headers.get("cookie"),p);if(!s)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let d=await chunkSS5KJYWU_js.e(s,e.signingSecret,e.policy);return new Response(JSON.stringify(d),{status:200,headers:{"Content-Type":"application/json"}})}if((t.method==="GET"||t.method==="POST")&&r==="nonce"){let s=await chunkSS5KJYWU_js.f(e.signingSecret,T);return new Response(JSON.stringify({nonce:s}),{status:200,headers:{"Content-Type":"application/json"}})}if(t.method==="POST"&&r==="verify"){let s=t.headers.get("content-length");if(s&&parseInt(s,10)>y)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let d=await t.text();if(d.length>y)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let i;try{i=JSON.parse(d);}catch{return new Response(JSON.stringify({error:"Invalid JSON payload"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!i||typeof i.message!="string"||typeof i.signature!="string")return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let N={message:i.message,signature:i.signature},c=await chunkSS5KJYWU_js.c(N,{...e.verifyOptions,policy:e.policy});if(!c.success||!c.data)return new Response(JSON.stringify({error:c.error||"Verification failed"}),{status:401,headers:{"Content-Type":"application/json"}});if(!await chunkSS5KJYWU_js.g(c.data.nonce,e.signingSecret)||!o(c.data.nonce))return new Response(JSON.stringify({error:"Nonce replay detected or nonce expired"}),{status:401,headers:{"Content-Type":"application/json"}});let g=chunkSS5KJYWU_js.a(c.data),J=await chunkSS5KJYWU_js.d(g,e.signingSecret,u),j=chunkSS5KJYWU_js.h(J,{...e.cookieOptions,name:p,maxAge:u});return new Response(JSON.stringify(g),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":j}})}return t.method==="DELETE"&&r==="session"||t.method==="POST"&&r==="logout"?new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":chunkSS5KJYWU_js.i({...e.cookieOptions,name:p})}}):new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(a){return console.error("[SIWX-SERVER] Stateless Demo Handler error:",a),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:S,POST:S,DELETE:S}}Object.defineProperty(exports,"getSiwxServerSession",{enumerable:true,get:function(){return chunkSS5KJYWU_js.m}});exports.createSiwxApiHandler=H;exports.createStatelessDemoSiwxHandler=V;
package/dist/next.mjs CHANGED
@@ -1 +1 @@
1
- import {h,c,a,f,g,e,d}from'./chunk-PBR725EL.mjs';export{k as getSiwxServerSession}from'./chunk-PBR725EL.mjs';import {generateNonce}from'@tuwaio/siwx-core';function j(e){if(!e?.sessionStore||!e?.nonceStore)throw new Error("[SIWX-SERVER] createSiwxApiHandler requires both `sessionStore` and `nonceStore`.");let a$1=e.cookieOptions?.name||"siwx-session-v2",p=e.ttlSeconds??(e.cookieOptions?.maxAge||3600*24*7),l=65536,c$1=async t=>{try{let d=new URL(t.url).pathname.split("/").filter(Boolean),o=d[d.length-1]||"";if(t.method==="GET"&&o==="session"){let n=h(t.headers.get("cookie"),a$1);if(!n)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let i=await e.sessionStore.get(n);return new Response(JSON.stringify(i?.session??null),{status:200,headers:{"Content-Type":"application/json"}})}if((t.method==="GET"||t.method==="POST")&&o==="nonce"){let n=generateNonce();return await e.nonceStore.issue({nonce:n,ttlSeconds:300}),new Response(JSON.stringify({nonce:n}),{status:200,headers:{"Content-Type":"application/json"}})}if(t.method==="POST"&&o==="verify"){let n=t.headers.get("content-length");if(n&&parseInt(n,10)>l)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let i=await t.text();if(i.length>l)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let s;try{s=JSON.parse(i);}catch{return new Response(JSON.stringify({error:"Invalid JSON payload"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!s||typeof s.message!="string"||typeof s.signature!="string")return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let g={message:s.message,signature:s.signature},r=await c(g,{...e.verifyOptions,policy:e.policy});if(!r.success||!r.data)return new Response(JSON.stringify({error:r.error||"Verification failed"}),{status:401,headers:{"Content-Type":"application/json"}});if(!await e.nonceStore.consume({nonce:r.data.nonce}))return new Response(JSON.stringify({error:"Nonce replay detected or nonce expired"}),{status:401,headers:{"Content-Type":"application/json"}});let y=a(r.data),w=await e.sessionStore.create({session:y,ttlSeconds:p}),x=f(w.id,{...e.cookieOptions,name:a$1,maxAge:p});return new Response(JSON.stringify(y),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":x}})}if(t.method==="DELETE"&&o==="session"||t.method==="POST"&&o==="logout"){let n=h(t.headers.get("cookie"),a$1);return n&&await e.sessionStore.revoke(n),new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":g({...e.cookieOptions,name:a$1})}})}return new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(S){return console.error("[SIWX-SERVER] Durable Handler error:",S),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:c$1,POST:c$1,DELETE:c$1}}function P(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 a$1=e$1.cookieOptions?.name||"siwx-session-v2",p=e$1.ttlSeconds??(e$1.cookieOptions?.maxAge||1800),l=e$1.demoLimits?.maxTransactionPayloadBytes??65536,c$1=async t=>{try{let d$1=new URL(t.url).pathname.split("/").filter(Boolean),o=d$1[d$1.length-1]||"";if(t.method==="GET"&&o==="session"){let n=h(t.headers.get("cookie"),a$1);if(!n)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let i=await e(n,e$1.signingSecret,e$1.policy);return new Response(JSON.stringify(i),{status:200,headers:{"Content-Type":"application/json"}})}if((t.method==="GET"||t.method==="POST")&&o==="nonce"){let n=generateNonce();return new Response(JSON.stringify({nonce:n}),{status:200,headers:{"Content-Type":"application/json"}})}if(t.method==="POST"&&o==="verify"){let n=t.headers.get("content-length");if(n&&parseInt(n,10)>l)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let i=await t.text();if(i.length>l)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let s;try{s=JSON.parse(i);}catch{return new Response(JSON.stringify({error:"Invalid JSON payload"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!s||typeof s.message!="string"||typeof s.signature!="string")return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let g={message:s.message,signature:s.signature},r=await c(g,{...e$1.verifyOptions,policy:e$1.policy});if(!r.success||!r.data)return new Response(JSON.stringify({error:r.error||"Verification failed"}),{status:401,headers:{"Content-Type":"application/json"}});let f$1=a(r.data),y=await d(f$1,e$1.signingSecret,p),w=f(y,{...e$1.cookieOptions,name:a$1,maxAge:p});return new Response(JSON.stringify(f$1),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":w}})}return t.method==="DELETE"&&o==="session"||t.method==="POST"&&o==="logout"?new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":g({...e$1.cookieOptions,name:a$1})}}):new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(S){return console.error("[SIWX-SERVER] Stateless Demo Handler error:",S),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:c$1,POST:c$1,DELETE:c$1}}export{j as createSiwxApiHandler,P as createStatelessDemoSiwxHandler};
1
+ import {j,c,a,h,i,e,f,g,d}from'./chunk-AEFOZH2W.mjs';export{m as getSiwxServerSession}from'./chunk-AEFOZH2W.mjs';import {generateNonce}from'@tuwaio/siwx-core';var T=300;function H(e){if(!e?.sessionStore||!e?.nonceStore)throw new Error("[SIWX-SERVER] createSiwxApiHandler requires both `sessionStore` and `nonceStore`.");let p=e.cookieOptions?.name||"siwx-session-v2",u=e.ttlSeconds??(e.cookieOptions?.maxAge||3600*24*7),y=65536,l=async o=>{try{let t=new URL(o.url).pathname.split("/").filter(Boolean),a$1=t[t.length-1]||"";if(o.method==="GET"&&a$1==="session"){let n=j(o.headers.get("cookie"),p);if(!n)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let r=await e.sessionStore.get(n);return new Response(JSON.stringify(r?.session??null),{status:200,headers:{"Content-Type":"application/json"}})}if((o.method==="GET"||o.method==="POST")&&a$1==="nonce"){let n=generateNonce();return await e.nonceStore.issue({nonce:n,ttlSeconds:T}),new Response(JSON.stringify({nonce:n}),{status:200,headers:{"Content-Type":"application/json"}})}if(o.method==="POST"&&a$1==="verify"){let n=o.headers.get("content-length");if(n&&parseInt(n,10)>y)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let r=await o.text();if(r.length>y)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let s;try{s=JSON.parse(r);}catch{return new Response(JSON.stringify({error:"Invalid JSON payload"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!s||typeof s.message!="string"||typeof s.signature!="string")return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let d={message:s.message,signature:s.signature},i=await c(d,{...e.verifyOptions,policy:e.policy});if(!i.success||!i.data)return new Response(JSON.stringify({error:i.error||"Verification failed"}),{status:401,headers:{"Content-Type":"application/json"}});if(!await e.nonceStore.consume({nonce:i.data.nonce}))return new Response(JSON.stringify({error:"Nonce replay detected or nonce expired"}),{status:401,headers:{"Content-Type":"application/json"}});let c$1=a(i.data),C=await e.sessionStore.create({session:c$1,ttlSeconds:u}),g=h(C.id,{...e.cookieOptions,name:p,maxAge:u});return new Response(JSON.stringify(c$1),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":g}})}if(o.method==="DELETE"&&a$1==="session"||o.method==="POST"&&a$1==="logout"){let n=j(o.headers.get("cookie"),p);return n&&await e.sessionStore.revoke(n),new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":i({...e.cookieOptions,name:p})}})}return new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(S){return console.error("[SIWX-SERVER] Durable Handler error:",S),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:l,POST:l,DELETE:l}}function V(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 p=e$1.cookieOptions?.name||"siwx-session-v2",u=e$1.ttlSeconds??(e$1.cookieOptions?.maxAge||1800),y=e$1.demoLimits?.maxTransactionPayloadBytes??65536,l=new Map,o=t=>{let a=Date.now();for(let[n,r]of l)r<a&&l.delete(n);return l.has(t)?false:(l.set(t,a+T*1e3),true)},S=async t=>{try{let n=new URL(t.url).pathname.split("/").filter(Boolean),r=n[n.length-1]||"";if(t.method==="GET"&&r==="session"){let s=j(t.headers.get("cookie"),p);if(!s)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let d=await e(s,e$1.signingSecret,e$1.policy);return new Response(JSON.stringify(d),{status:200,headers:{"Content-Type":"application/json"}})}if((t.method==="GET"||t.method==="POST")&&r==="nonce"){let s=await f(e$1.signingSecret,T);return new Response(JSON.stringify({nonce:s}),{status:200,headers:{"Content-Type":"application/json"}})}if(t.method==="POST"&&r==="verify"){let s=t.headers.get("content-length");if(s&&parseInt(s,10)>y)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let d$1=await t.text();if(d$1.length>y)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let i;try{i=JSON.parse(d$1);}catch{return new Response(JSON.stringify({error:"Invalid JSON payload"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!i||typeof i.message!="string"||typeof i.signature!="string")return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let N={message:i.message,signature:i.signature},c$1=await c(N,{...e$1.verifyOptions,policy:e$1.policy});if(!c$1.success||!c$1.data)return new Response(JSON.stringify({error:c$1.error||"Verification failed"}),{status:401,headers:{"Content-Type":"application/json"}});if(!await g(c$1.data.nonce,e$1.signingSecret)||!o(c$1.data.nonce))return new Response(JSON.stringify({error:"Nonce replay detected or nonce expired"}),{status:401,headers:{"Content-Type":"application/json"}});let g$1=a(c$1.data),J=await d(g$1,e$1.signingSecret,u),j=h(J,{...e$1.cookieOptions,name:p,maxAge:u});return new Response(JSON.stringify(g$1),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":j}})}return t.method==="DELETE"&&r==="session"||t.method==="POST"&&r==="logout"?new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":i({...e$1.cookieOptions,name:p})}}):new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(a){return console.error("[SIWX-SERVER] Stateless Demo Handler error:",a),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:S,POST:S,DELETE:S}}export{H as createSiwxApiHandler,V as createStatelessDemoSiwxHandler};
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@tuwaio/siwx-server",
3
- "version": "0.2.2",
3
+ "version": "0.4.0",
4
4
  "private": false,
5
5
  "author": "Oleksandr Tkach",
6
6
  "license": "Apache-2.0",
7
- "description": "Layer 2 (L2) of the TUWA Ecosystem. Backend utilities for @tuwaio/siwx. Parses, validates, and verifies CAIP-122 payloads on Node.js or Edge runtimes.",
7
+ "description": "L2 server package of SIWX (TUWA): backend verification of CAIP-122 sign-ins for EVM and Solana, single-use nonce and session stores, HttpOnly cookie helpers and Next.js App Router handlers.",
8
8
  "main": "./dist/index.js",
9
9
  "module": "./dist/index.mjs",
10
10
  "types": "./dist/index.d.ts",
@@ -38,19 +38,18 @@
38
38
  "socket.json"
39
39
  ],
40
40
  "keywords": [
41
- "web3",
42
- "typescript",
41
+ "tuwa",
42
+ "siwx",
43
+ "sign-in-with-x",
43
44
  "caip-122",
44
- "server",
45
- "backend",
46
- "node",
47
- "edge",
48
45
  "authentication",
49
- "verification",
46
+ "web3",
47
+ "server",
50
48
  "session",
51
49
  "cookie",
52
- "jwt",
53
- "tuwa"
50
+ "nonce",
51
+ "nextjs",
52
+ "typescript"
54
53
  ],
55
54
  "repository": {
56
55
  "type": "git",
@@ -68,15 +67,29 @@
68
67
  }
69
68
  ],
70
69
  "peerDependencies": {
71
- "@tuwaio/siwx-core": "0.2.1"
70
+ "@tuwaio/siwx-core": "0.4.0",
71
+ "@tuwaio/siwx-evm": "0.4.0",
72
+ "@tuwaio/siwx-solana": "0.4.0",
73
+ "viem": ">=2"
74
+ },
75
+ "peerDependenciesMeta": {
76
+ "@tuwaio/siwx-evm": {
77
+ "optional": true
78
+ },
79
+ "@tuwaio/siwx-solana": {
80
+ "optional": true
81
+ },
82
+ "viem": {
83
+ "optional": true
84
+ }
72
85
  },
73
86
  "devDependencies": {
87
+ "@tuwaio/siwx-core": "0.4.0",
88
+ "@tuwaio/siwx-evm": "0.4.0",
89
+ "@tuwaio/siwx-solana": "0.4.0",
74
90
  "tsup": "^8.5.1",
75
91
  "typescript": "6.0.3",
76
- "viem": "^2.55.16",
77
- "@tuwaio/siwx-core": "0.2.1",
78
- "@tuwaio/siwx-evm": "0.2.1",
79
- "@tuwaio/siwx-solana": "0.2.0"
92
+ "viem": "^2.56.9"
80
93
  },
81
94
  "scripts": {
82
95
  "start": "tsup src/index.ts --watch",
@@ -1,2 +0,0 @@
1
- import {parseMessage,validateMessage,SiwxExpiredSessionError,SiwxNonceReplayError,SiwxUnsupportedNamespaceError,generateNonce}from'@tuwaio/siwx-core';export{generateNonce as b}from'@tuwaio/siwx-core';function v(i){return {address:i.address,chainId:i.chainId,domain:i.domain,nonce:i.nonce,issuedAt:i.issuedAt,expirationTime:i.expirationTime}}async function N(i,e={}){try{let n=parseMessage(i.message),r=validateMessage(n,{skipExpiration:e.skipExpiration,policy:e.policy});if(!r.valid)return {success:!1,error:`Validation failed: ${r.errors.join(", ")}`};if(!e.skipExpiration&&n.expirationTime&&new Date(n.expirationTime)<new Date)throw new SiwxExpiredSessionError(n.expirationTime);if(e.usedNonces?.has(n.nonce))throw new SiwxNonceReplayError(n.nonce);let s=n.chainId.split(":")[0];if(!s||!["eip155","solana"].includes(s))throw new SiwxUnsupportedNamespaceError(s??"unknown");if(s==="eip155"){let{verifyEvmSignature:t}=await import('@tuwaio/siwx-evm');return {...await t(i.message,i.signature,{skipExpiration:e.skipExpiration,publicClient:e.publicClient}),namespace:s}}if(s==="solana"){let{verifyEd25519:t}=await import('@tuwaio/siwx-solana');return {...await t(i,{skipExpiration:e.skipExpiration}),namespace:s}}return {success:!1,error:"Unsupported namespace."}}catch(n){return n instanceof SiwxExpiredSessionError||n instanceof SiwxNonceReplayError||n instanceof SiwxUnsupportedNamespaceError?{success:false,error:n.message}:{success:false,error:`Server verification failed: ${String(n)}`}}}function E(i){return btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function T(i){let e=i.replace(/-/g,"+").replace(/_/g,"/");return atob(e)}function A(i){let e="";for(let n=0;n<i.byteLength;n++)e+=String.fromCharCode(i[n]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function C(i){let e=i.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e),r=new Uint8Array(n.length);for(let s=0;s<n.length;s++)r[s]=n.charCodeAt(s);return r}async function b(i){let e=new TextEncoder;return globalThis.crypto.subtle.importKey("raw",e.encode(i),{name:"HMAC",hash:"SHA-256"},false,["sign","verify"])}async function O(i,e,n=1800){if(!e||e.length<32)throw new Error("[SIWX-SERVER] Stateless demo signing secret must be at least 32 characters long.");let s=Date.now()+n*1e3,t={version:1,address:i.address,chainId:i.chainId,domain:i.domain,nonce:i.nonce,issuedAt:i.issuedAt,expirationTime:i.expirationTime??new Date(s).toISOString(),sessionId:generateNonce(),mode:"demo"},a=JSON.stringify(t),o=E(a),l=await b(e),u=new TextEncoder,p=await globalThis.crypto.subtle.sign("HMAC",l,u.encode(o)),c=A(new Uint8Array(p));return `${o}.${c}`}async function D(i,e,n){if(!i||typeof i!="string"||!e)return null;let r=i.split(".");if(r.length!==2)return null;let[s,t]=r;try{let a=await b(e),o=C(t),l=new TextEncoder;if(!await globalThis.crypto.subtle.verify("HMAC",a,o,l.encode(s)))return null;let p=T(s),c=JSON.parse(p);if(c.version!==1||c.mode!=="demo")return null;if(c.expirationTime){let S=new Date(c.expirationTime).getTime(),f=(n?.clockSkewSeconds??60)*1e3;if(isNaN(S)||S+f<Date.now())return null}return n?.expectedDomain!==void 0&&!(Array.isArray(n.expectedDomain)?n.expectedDomain:[n.expectedDomain]).some(f=>f.toLowerCase()===c.domain.toLowerCase())||n?.allowedChainIds!==void 0&&n.allowedChainIds.length>0&&!n.allowedChainIds.includes(c.chainId)?null:{address:c.address,chainId:c.chainId,domain:c.domain,nonce:c.nonce,issuedAt:c.issuedAt,expirationTime:c.expirationTime}}catch{return null}}function $(i,e={}){let{name:n="siwx-session-v2",maxAge:r=3600*24*7,path:s="/",domain:t,secure:a=true,sameSite:o="Strict"}=e,l=[`${n}=${i}`,`Max-Age=${r}`,`Path=${s}`,"HttpOnly",`SameSite=${o}`];return a&&l.push("Secure"),t&&l.push(`Domain=${t}`),l.join("; ")}function j(i={}){let{name:e="siwx-session-v2",path:n="/",domain:r,secure:s=true,sameSite:t="Strict"}=i,a=[`${e}=`,`Path=${n}`,"Expires=Thu, 01 Jan 1970 00:00:00 GMT","Max-Age=0","HttpOnly",`SameSite=${t}`];return s&&a.push("Secure"),r&&a.push(`Domain=${r}`),a.join("; ")}function d(i,e){return i?Object.fromEntries(i.split("; ").filter(Boolean).map(r=>{let s=r.split("=");return [s[0].trim(),s.slice(1).join("=")]}))[e]??null:null}var w=class{records=new Map;constructor(e){if(typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV==="production"&&!e?.allowInProduction)throw new Error("[SIWX-SERVER] MemorySiwxSessionStore must not be used in production. Connect Redis or a durable store.")}async create(e){let n=generateNonce(),r=Date.now(),s=r+e.ttlSeconds*1e3,t={id:n,session:e.session,createdAt:r,expiresAt:s};return this.records.set(n,t),t}async get(e){let n=this.records.get(e);return n?n.expiresAt<Date.now()?(this.records.delete(e),null):n:null}async bindSubject(e,n){let r=await this.get(e);return r?(r.subjectId=n,true):false}async revoke(e){this.records.delete(e);}},y=class{nonces=new Map;constructor(e){if(typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV==="production"&&!e?.allowInProduction)throw new Error("[SIWX-SERVER] MemorySiwxNonceStore must not be used in production. Connect Redis or a durable store.")}async issue(e){let n=Date.now()+e.ttlSeconds*1e3;this.nonces.set(e.nonce,n);}async consume(e){let n=this.nonces.get(e.nonce);return !(!n||(this.nonces.delete(e.nonce),n<Date.now()))}};async function B(i){let{cookieSource:e,cookieName:n="siwx-session-v2",sessionStore:r,signingSecret:s,policy:t}=i;if(!e)return null;let a=null;if(typeof e=="string")a=e.includes("=")?d(e,n):e;else if(typeof e.headers=="object"&&typeof e.headers?.get=="function"){let o=e.headers.get("cookie");a=d(o,n);}else if(typeof e.get=="function"){let o=e.get(n);if(o&&typeof o=="object"&&"value"in o)a=o.value;else if(typeof o=="string")a=o.includes("=")?d(o,n):o;else if(typeof e.get=="function"){let l=e.get("cookie");l&&(a=d(l,n));}}if(!a)return null;if(r){let o=await r.get(a);return !o?.session||t&&(t.expectedDomain!==void 0&&!(Array.isArray(t.expectedDomain)?t.expectedDomain:[t.expectedDomain]).some(u=>u.toLowerCase()===o.session.domain.toLowerCase())||t.allowedChainIds!==void 0&&t.allowedChainIds.length>0&&!t.allowedChainIds.includes(o.session.chainId)||t.requireExpirationTime&&!o.session.expirationTime)?null:o.session}return s?D(a,s,t):null}
2
- export{v as a,N as c,O as d,D as e,$ as f,j as g,d as h,w as i,y as j,B as k};
@@ -1,2 +0,0 @@
1
- 'use strict';var siwxCore=require('@tuwaio/siwx-core');function v(i){return {address:i.address,chainId:i.chainId,domain:i.domain,nonce:i.nonce,issuedAt:i.issuedAt,expirationTime:i.expirationTime}}async function N(i,e={}){try{let n=siwxCore.parseMessage(i.message),r=siwxCore.validateMessage(n,{skipExpiration:e.skipExpiration,policy:e.policy});if(!r.valid)return {success:!1,error:`Validation failed: ${r.errors.join(", ")}`};if(!e.skipExpiration&&n.expirationTime&&new Date(n.expirationTime)<new Date)throw new siwxCore.SiwxExpiredSessionError(n.expirationTime);if(e.usedNonces?.has(n.nonce))throw new siwxCore.SiwxNonceReplayError(n.nonce);let s=n.chainId.split(":")[0];if(!s||!["eip155","solana"].includes(s))throw new siwxCore.SiwxUnsupportedNamespaceError(s??"unknown");if(s==="eip155"){let{verifyEvmSignature:t}=await import('@tuwaio/siwx-evm');return {...await t(i.message,i.signature,{skipExpiration:e.skipExpiration,publicClient:e.publicClient}),namespace:s}}if(s==="solana"){let{verifyEd25519:t}=await import('@tuwaio/siwx-solana');return {...await t(i,{skipExpiration:e.skipExpiration}),namespace:s}}return {success:!1,error:"Unsupported namespace."}}catch(n){return n instanceof siwxCore.SiwxExpiredSessionError||n instanceof siwxCore.SiwxNonceReplayError||n instanceof siwxCore.SiwxUnsupportedNamespaceError?{success:false,error:n.message}:{success:false,error:`Server verification failed: ${String(n)}`}}}function E(i){return btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function T(i){let e=i.replace(/-/g,"+").replace(/_/g,"/");return atob(e)}function A(i){let e="";for(let n=0;n<i.byteLength;n++)e+=String.fromCharCode(i[n]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function C(i){let e=i.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e),r=new Uint8Array(n.length);for(let s=0;s<n.length;s++)r[s]=n.charCodeAt(s);return r}async function b(i){let e=new TextEncoder;return globalThis.crypto.subtle.importKey("raw",e.encode(i),{name:"HMAC",hash:"SHA-256"},false,["sign","verify"])}async function O(i,e,n=1800){if(!e||e.length<32)throw new Error("[SIWX-SERVER] Stateless demo signing secret must be at least 32 characters long.");let s=Date.now()+n*1e3,t={version:1,address:i.address,chainId:i.chainId,domain:i.domain,nonce:i.nonce,issuedAt:i.issuedAt,expirationTime:i.expirationTime??new Date(s).toISOString(),sessionId:siwxCore.generateNonce(),mode:"demo"},a=JSON.stringify(t),o=E(a),l=await b(e),u=new TextEncoder,p=await globalThis.crypto.subtle.sign("HMAC",l,u.encode(o)),c=A(new Uint8Array(p));return `${o}.${c}`}async function D(i,e,n){if(!i||typeof i!="string"||!e)return null;let r=i.split(".");if(r.length!==2)return null;let[s,t]=r;try{let a=await b(e),o=C(t),l=new TextEncoder;if(!await globalThis.crypto.subtle.verify("HMAC",a,o,l.encode(s)))return null;let p=T(s),c=JSON.parse(p);if(c.version!==1||c.mode!=="demo")return null;if(c.expirationTime){let S=new Date(c.expirationTime).getTime(),f=(n?.clockSkewSeconds??60)*1e3;if(isNaN(S)||S+f<Date.now())return null}return n?.expectedDomain!==void 0&&!(Array.isArray(n.expectedDomain)?n.expectedDomain:[n.expectedDomain]).some(f=>f.toLowerCase()===c.domain.toLowerCase())||n?.allowedChainIds!==void 0&&n.allowedChainIds.length>0&&!n.allowedChainIds.includes(c.chainId)?null:{address:c.address,chainId:c.chainId,domain:c.domain,nonce:c.nonce,issuedAt:c.issuedAt,expirationTime:c.expirationTime}}catch{return null}}function $(i,e={}){let{name:n="siwx-session-v2",maxAge:r=3600*24*7,path:s="/",domain:t,secure:a=true,sameSite:o="Strict"}=e,l=[`${n}=${i}`,`Max-Age=${r}`,`Path=${s}`,"HttpOnly",`SameSite=${o}`];return a&&l.push("Secure"),t&&l.push(`Domain=${t}`),l.join("; ")}function j(i={}){let{name:e="siwx-session-v2",path:n="/",domain:r,secure:s=true,sameSite:t="Strict"}=i,a=[`${e}=`,`Path=${n}`,"Expires=Thu, 01 Jan 1970 00:00:00 GMT","Max-Age=0","HttpOnly",`SameSite=${t}`];return s&&a.push("Secure"),r&&a.push(`Domain=${r}`),a.join("; ")}function d(i,e){return i?Object.fromEntries(i.split("; ").filter(Boolean).map(r=>{let s=r.split("=");return [s[0].trim(),s.slice(1).join("=")]}))[e]??null:null}var w=class{records=new Map;constructor(e){if(typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV==="production"&&!e?.allowInProduction)throw new Error("[SIWX-SERVER] MemorySiwxSessionStore must not be used in production. Connect Redis or a durable store.")}async create(e){let n=siwxCore.generateNonce(),r=Date.now(),s=r+e.ttlSeconds*1e3,t={id:n,session:e.session,createdAt:r,expiresAt:s};return this.records.set(n,t),t}async get(e){let n=this.records.get(e);return n?n.expiresAt<Date.now()?(this.records.delete(e),null):n:null}async bindSubject(e,n){let r=await this.get(e);return r?(r.subjectId=n,true):false}async revoke(e){this.records.delete(e);}},y=class{nonces=new Map;constructor(e){if(typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV==="production"&&!e?.allowInProduction)throw new Error("[SIWX-SERVER] MemorySiwxNonceStore must not be used in production. Connect Redis or a durable store.")}async issue(e){let n=Date.now()+e.ttlSeconds*1e3;this.nonces.set(e.nonce,n);}async consume(e){let n=this.nonces.get(e.nonce);return !(!n||(this.nonces.delete(e.nonce),n<Date.now()))}};async function B(i){let{cookieSource:e,cookieName:n="siwx-session-v2",sessionStore:r,signingSecret:s,policy:t}=i;if(!e)return null;let a=null;if(typeof e=="string")a=e.includes("=")?d(e,n):e;else if(typeof e.headers=="object"&&typeof e.headers?.get=="function"){let o=e.headers.get("cookie");a=d(o,n);}else if(typeof e.get=="function"){let o=e.get(n);if(o&&typeof o=="object"&&"value"in o)a=o.value;else if(typeof o=="string")a=o.includes("=")?d(o,n):o;else if(typeof e.get=="function"){let l=e.get("cookie");l&&(a=d(l,n));}}if(!a)return null;if(r){let o=await r.get(a);return !o?.session||t&&(t.expectedDomain!==void 0&&!(Array.isArray(t.expectedDomain)?t.expectedDomain:[t.expectedDomain]).some(u=>u.toLowerCase()===o.session.domain.toLowerCase())||t.allowedChainIds!==void 0&&t.allowedChainIds.length>0&&!t.allowedChainIds.includes(o.session.chainId)||t.requireExpirationTime&&!o.session.expirationTime)?null:o.session}return s?D(a,s,t):null}
2
- Object.defineProperty(exports,"b",{enumerable:true,get:function(){return siwxCore.generateNonce}});exports.a=v;exports.c=N;exports.d=O;exports.e=D;exports.f=$;exports.g=j;exports.h=d;exports.i=w;exports.j=y;exports.k=B;