@tuwaio/siwx-server 0.3.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +144 -219
- package/dist/chunk-AEFOZH2W.mjs +2 -0
- package/dist/chunk-SS5KJYWU.js +2 -0
- package/dist/index.d.mts +181 -82
- package/dist/index.d.ts +181 -82
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/next.d.mts +61 -24
- package/dist/next.d.ts +61 -24
- package/dist/next.js +1 -1
- package/dist/next.mjs +1 -1
- package/package.json +29 -16
- package/dist/chunk-PBR725EL.mjs +0 -2
- package/dist/chunk-WPKBWXVR.js +0 -2
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
|
-
*
|
|
7
|
-
*
|
|
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 (
|
|
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 (
|
|
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
|
-
*
|
|
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
|
-
*
|
|
29
|
+
* Attributes of the session cookie. `maxAge` is replaced by the session TTL.
|
|
25
30
|
*/
|
|
26
31
|
cookieOptions?: CookieOptions;
|
|
27
32
|
/**
|
|
28
|
-
*
|
|
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
|
|
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
|
|
39
|
-
*
|
|
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
|
-
*
|
|
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
|
-
*
|
|
57
|
+
* Attributes of the session cookie. `maxAge` is replaced by the token TTL.
|
|
48
58
|
*/
|
|
49
59
|
cookieOptions?: CookieOptions;
|
|
50
60
|
/**
|
|
51
|
-
*
|
|
61
|
+
* Request limits (maximum body size of `POST /verify`).
|
|
52
62
|
*/
|
|
53
63
|
demoLimits?: StatelessDemoLimits;
|
|
54
64
|
/**
|
|
55
|
-
*
|
|
65
|
+
* Extra options of `verifySiwxPayload`, for example `publicClient` or `usedNonces`.
|
|
56
66
|
*/
|
|
57
67
|
verifyOptions?: Omit<ServerVerifyOptions, 'policy'>;
|
|
58
68
|
/**
|
|
59
|
-
*
|
|
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
|
|
65
|
-
*
|
|
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
|
-
*
|
|
68
|
-
*
|
|
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
|
|
92
|
-
*
|
|
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
|
-
*
|
|
130
|
+
* Side effects: keeps the used nonces of this handler in memory until they expire.
|
|
95
131
|
*
|
|
96
|
-
* @param options -
|
|
97
|
-
* @returns
|
|
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
|
-
*
|
|
7
|
-
*
|
|
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 (
|
|
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 (
|
|
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
|
-
*
|
|
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
|
-
*
|
|
29
|
+
* Attributes of the session cookie. `maxAge` is replaced by the session TTL.
|
|
25
30
|
*/
|
|
26
31
|
cookieOptions?: CookieOptions;
|
|
27
32
|
/**
|
|
28
|
-
*
|
|
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
|
|
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
|
|
39
|
-
*
|
|
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
|
-
*
|
|
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
|
-
*
|
|
57
|
+
* Attributes of the session cookie. `maxAge` is replaced by the token TTL.
|
|
48
58
|
*/
|
|
49
59
|
cookieOptions?: CookieOptions;
|
|
50
60
|
/**
|
|
51
|
-
*
|
|
61
|
+
* Request limits (maximum body size of `POST /verify`).
|
|
52
62
|
*/
|
|
53
63
|
demoLimits?: StatelessDemoLimits;
|
|
54
64
|
/**
|
|
55
|
-
*
|
|
65
|
+
* Extra options of `verifySiwxPayload`, for example `publicClient` or `usedNonces`.
|
|
56
66
|
*/
|
|
57
67
|
verifyOptions?: Omit<ServerVerifyOptions, 'policy'>;
|
|
58
68
|
/**
|
|
59
|
-
*
|
|
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
|
|
65
|
-
*
|
|
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
|
-
*
|
|
68
|
-
*
|
|
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
|
|
92
|
-
*
|
|
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
|
-
*
|
|
130
|
+
* Side effects: keeps the used nonces of this handler in memory until they expire.
|
|
95
131
|
*
|
|
96
|
-
* @param options -
|
|
97
|
-
* @returns
|
|
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
|
|
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 {
|
|
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.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"private": false,
|
|
5
5
|
"author": "Oleksandr Tkach",
|
|
6
6
|
"license": "Apache-2.0",
|
|
7
|
-
"description": "
|
|
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
|
-
"
|
|
42
|
-
"
|
|
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
|
-
"
|
|
46
|
+
"web3",
|
|
47
|
+
"server",
|
|
50
48
|
"session",
|
|
51
49
|
"cookie",
|
|
52
|
-
"
|
|
53
|
-
"
|
|
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.
|
|
70
|
+
"@tuwaio/siwx-core": "0.4.0",
|
|
71
|
+
"@tuwaio/siwx-evm": "0.4.1",
|
|
72
|
+
"@tuwaio/siwx-solana": "0.4.1",
|
|
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": {
|
|
74
|
-
"@tuwaio/siwx-core": "0.
|
|
75
|
-
"@tuwaio/siwx-evm": "0.
|
|
76
|
-
"@tuwaio/siwx-solana": "0.
|
|
87
|
+
"@tuwaio/siwx-core": "0.4.0",
|
|
88
|
+
"@tuwaio/siwx-evm": "0.4.1",
|
|
89
|
+
"@tuwaio/siwx-solana": "0.4.1",
|
|
77
90
|
"tsup": "^8.5.1",
|
|
78
91
|
"typescript": "6.0.3",
|
|
79
|
-
"viem": "^2.
|
|
92
|
+
"viem": "^2.57.1"
|
|
80
93
|
},
|
|
81
94
|
"scripts": {
|
|
82
95
|
"start": "tsup src/index.ts --watch",
|
package/dist/chunk-PBR725EL.mjs
DELETED
|
@@ -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};
|
package/dist/chunk-WPKBWXVR.js
DELETED
|
@@ -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;
|