@tuwaio/siwx-server 0.5.1 → 0.6.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/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  [![NPM Version](https://img.shields.io/npm/v/@tuwaio/siwx-server.svg)](https://www.npmjs.com/package/@tuwaio/siwx-server)
4
4
  [![License](https://img.shields.io/npm/l/@tuwaio/siwx-server.svg)](https://github.com/TuwaIO/siwx/blob/main/packages/siwx-server/LICENSE)
5
5
 
6
- `@tuwaio/siwx-server` is the server Layer 2 (L2) package of **SIWX** (Sign-In With X), the authentication project of TUWA Stage 1 ("Core Auth & Primitives", next to Orbit Utils). Built on **`@tuwaio/siwx-core`** and the Web platform APIs (`Request`, `Response`, Web Crypto), it verifies signed CAIP-122 messages for EVM and Solana on your backend, issues single-use nonces and sessions through pluggable stores, and formats the session cookie. It runs on Node.js 20+ and does not depend on a web framework, a database or a hosted service.
6
+ `@tuwaio/siwx-server` is the server Layer 2 (L2) package of **SIWX** (Sign-In With X), the authentication project of TUWA Stage 1 ("Core Auth & Primitives", next to Orbit Utils). Built on **`@tuwaio/siwx-core`** and the Web platform APIs (`Request`, `Response`, Web Crypto), it verifies signed CAIP-122 messages for EVM and Solana on your backend, issues single-use nonces and sessions through pluggable stores, formats the session cookie, and can hand the sign-in to external auth providers as a JWT with a JWKS. It runs on Node.js 20+ and does not depend on a web framework, a database or a hosted service.
7
7
 
8
8
  It has two entry points:
9
9
 
@@ -14,10 +14,11 @@ It has two entry points:
14
14
 
15
15
  ## 🏛️ Core Capabilities
16
16
 
17
- - **Verification:** `verifySiwxPayload` parses the message, validates it against your `SiwxVerificationPolicy` and routes the signature check by chain to `@tuwaio/siwx-evm` (EIP-191, with an EIP-1271 fallback when `publicClient` is set) or `@tuwaio/siwx-solana` (ed25519). It returns a result instead of throwing.
17
+ - **Verification:** `verifySiwxPayload` parses the message, validates it against your `SiwxVerificationPolicy` and routes the signature check by chain to `@tuwaio/siwx-evm` (EIP-191, with a smart contract wallet fallback, EIP-1271 and ERC-6492, when `publicClient` gives a client for the chain of the message) or `@tuwaio/siwx-solana` (ed25519). It returns a result instead of throwing.
18
18
  - **Durable profile:** `createSiwxApiHandler` serves the nonce, verify, session and logout routes on top of your `SiwxSessionStore` and `SiwxNonceStore` (Redis, SQL, KV…), with the session ID in an `HttpOnly` cookie.
19
19
  - **Stateless demo profile:** `createStatelessDemoSiwxHandler` issues HMAC-signed nonces and keeps the session in an HMAC-signed cookie, for demos without a database.
20
20
  - **Server-side session:** `getSiwxServerSession` reads the session from a `Request`, `Headers`, a `Cookie` header or the Next.js `cookies()` store, for Server Actions and API routes.
21
+ - **JWT for external auth:** with the `jwt` option, `createSiwxApiHandler` issues a short-lived ES256 or RS256 JWT for the signed-in wallet and publishes the JWKS, for services that accept a sign-in only as a JWT: embedded wallet providers with custom authentication (for example Coinbase CDP), identity platforms and your own services. `signSiwxJwt`, `createSiwxJwks` and `verifySiwxJwt` do the same outside Next.js.
21
22
  - **Building blocks:** `MemorySiwxSessionStore` and `MemorySiwxNonceStore` for development and tests, cookie helpers, demo token and demo nonce signing, and re-exports of the `@tuwaio/siwx-core` validators.
22
23
 
23
24
  ---
@@ -25,7 +26,7 @@ It has two entry points:
25
26
  ## 💾 Installation
26
27
 
27
28
  ```bash
28
- pnpm add @tuwaio/siwx-server @tuwaio/siwx-core
29
+ pnpm add @tuwaio/siwx-server @tuwaio/siwx-core @tuwaio/orbit-core
29
30
 
30
31
  # Chain verifiers, loaded at runtime for the chains you accept:
31
32
  pnpm add @tuwaio/siwx-evm viem @wagmi/core
@@ -33,7 +34,7 @@ pnpm add @tuwaio/siwx-solana @solana/kit @wallet-standard/base
33
34
  ```
34
35
 
35
36
  > [!IMPORTANT]
36
- > `@tuwaio/siwx-core` is a required peer dependency. `@tuwaio/siwx-evm`, `@tuwaio/siwx-solana` and `viem` are optional peer dependencies: `verifySiwxPayload` imports the chain package dynamically, depending on the chain of the message, so install the ones you accept together with their own peer dependencies. A message for a chain whose package is missing fails verification. `viem` provides the `PublicClient` type of the EIP-1271 option.
37
+ > `@tuwaio/siwx-core` is a required peer dependency. `@tuwaio/siwx-evm`, `@tuwaio/siwx-solana` and `viem` are optional peer dependencies: `verifySiwxPayload` imports the chain package dynamically, depending on the chain of the message, so install the ones you accept together with their own peer dependencies. A message for a chain whose package is missing fails verification. `viem` provides the `PublicClient` type of the smart contract wallet option.
37
38
 
38
39
  ---
39
40
 
@@ -133,6 +134,29 @@ The handler picks the action from the last path segment:
133
134
 
134
135
  `POST /verify` responds with 400 for a malformed body, 401 when verification or the nonce check fails, and 413 for a body over 64 KB. On the client, fetch the nonce from `/api/siwx/nonce` (the `getNonce` option of `useSiwx` in [`@tuwaio/siwx-react`](https://siwx.docs.tuwa.io/packages/siwx-react)): the handler only accepts nonces it has issued.
135
136
 
137
+ EOA wallets need nothing more on any chain. To accept smart contract wallets (Safe, Coinbase Smart Wallet / Base Account, other ERC-4337 accounts), give `verifyOptions.publicClient` a client for every chain your users sign in on. A deployed account is checked with EIP-1271 and an account that is not deployed yet with ERC-6492, always on the chain of the message:
138
+
139
+ ```typescript
140
+ // app/api/siwx/[...siwx]/route.ts
141
+ import type { EvmVerifyClient } from '@tuwaio/siwx-evm';
142
+ import { createSiwxApiHandler } from '@tuwaio/siwx-server/next';
143
+ import { createPublicClient, http } from 'viem';
144
+ import { base, mainnet } from 'viem/chains';
145
+
146
+ import { nonceStore, sessionStore } from '@/lib/authStores';
147
+
148
+ const clients = new Map<number, EvmVerifyClient>(
149
+ [mainnet, base].map((chain) => [chain.id, createPublicClient({ chain, transport: http() })]),
150
+ );
151
+
152
+ export const { GET, POST, DELETE } = createSiwxApiHandler({
153
+ sessionStore,
154
+ nonceStore,
155
+ policy: { expectedDomain: 'app.tuwa.io', expectedUri: 'https://app.tuwa.io' },
156
+ verifyOptions: { publicClient: (chainId) => clients.get(chainId) },
157
+ });
158
+ ```
159
+
136
160
  ### 3. Reading the session on the server
137
161
 
138
162
  ```typescript
@@ -220,6 +244,59 @@ export async function handleVerify(request: Request): Promise<Response> {
220
244
  }
221
245
  ```
222
246
 
247
+ ### 6. JWT for external auth providers
248
+
249
+ Some services accept a sign-in only as a JWT they can verify with your public keys: embedded wallet providers with custom authentication (for example Coinbase CDP), identity platforms and your own services. With the `jwt` option, `createSiwxApiHandler` issues a short-lived JWT for the signed-in wallet and publishes its public keys as a JWKS. Keys are handled with the Web Crypto API; nothing else is installed.
250
+
251
+ Create a key once and store the private JWK as a secret:
252
+
253
+ ```typescript
254
+ // scripts/generate-siwx-jwt-key.mjs
255
+ import { generateSiwxJwtKey } from '@tuwaio/siwx-server';
256
+
257
+ const { privateJwk, kid } = await generateSiwxJwtKey('ES256');
258
+ console.log(`kid: ${kid}`);
259
+ console.log(`SIWX_JWT_PRIVATE_KEY='${JSON.stringify(privateJwk)}'`);
260
+ ```
261
+
262
+ Enable the routes:
263
+
264
+ ```typescript
265
+ // app/api/siwx/[...siwx]/route.ts
266
+ import { importSiwxJwtKey } from '@tuwaio/siwx-server';
267
+ import { createSiwxApiHandler } from '@tuwaio/siwx-server/next';
268
+
269
+ import { nonceStore, sessionStore } from '@/lib/authStores';
270
+
271
+ export const { GET, POST, DELETE } = createSiwxApiHandler({
272
+ sessionStore,
273
+ nonceStore,
274
+ policy: { expectedDomain: 'app.example.com' },
275
+ jwt: {
276
+ signingKey: importSiwxJwtKey({ privateKey: process.env.SIWX_JWT_PRIVATE_KEY ?? '' }),
277
+ issuer: 'https://app.example.com',
278
+ },
279
+ });
280
+ ```
281
+
282
+ - `GET /api/siwx/token` returns `{ token, expiresAt }` for the session cookie, or `401` without a session. The token lives 10 minutes by default (`ttlSeconds`, at most 7 days) and never outlives the session.
283
+ - `GET /api/siwx/jwks` returns the public keys. Give this URL to the provider.
284
+
285
+ The `sub` claim is stable for a wallet: the user ID you bound with `bindSubject`, otherwise the account without its chain (`eip155:0x…` in lowercase, `solana:<address>`), so signing in on another network does not create a new user at the provider. The account as signed is in the `caip10` claim, its chain in `chain_id`. To rotate the key, sign with the new one and pass the old one in `previousKeys` until its tokens expire.
286
+
287
+ A service that receives the token checks it against the JWKS:
288
+
289
+ ```typescript
290
+ import { type SiwxJwks, verifySiwxJwt } from '@tuwaio/siwx-server';
291
+
292
+ export async function readWallet(request: Request): Promise<string | null> {
293
+ const token = request.headers.get('authorization')?.replace(/^Bearer /, '') ?? '';
294
+ const jwks = (await (await fetch('https://app.example.com/api/siwx/jwks')).json()) as SiwxJwks;
295
+ const claims = await verifySiwxJwt(token, { jwks, issuer: 'https://app.example.com' });
296
+ return claims?.sub ?? null;
297
+ }
298
+ ```
299
+
223
300
  ---
224
301
 
225
302
  ## 🛡️ Security Notes
@@ -231,12 +308,14 @@ export async function handleVerify(request: Request): Promise<Response> {
231
308
  - **Server-side checks:** `getSiwxServerSession` applies only `expectedDomain` and `allowedChainIds` of its `policy`, plus `requireExpirationTime` for durable sessions and the token expiry for demo sessions. The full policy runs when the message is verified.
232
309
  - **Cookies:** the session cookie is always `HttpOnly`, and `Secure` and `SameSite=Strict` by default. Keep `secure: true` in production.
233
310
  - **Secrets:** the demo `signingSecret` must be at least 32 characters and must never reach the browser. Changing it invalidates every demo session.
311
+ - **JWT keys:** the private JWT key must never reach the browser. Keep tokens short-lived (the default is 10 minutes) and request a fresh one when needed instead of storing it, for example in `localStorage`. If the key leaks, generate a new one and do not list the old one in `previousKeys`: every token it signed stops verifying at once.
312
+ - **JWT subject:** the receiving service identifies the user by `sub`. Do not build it from the CAIP-10 account with its chain reference, or the same wallet becomes a new user on every EVM network.
234
313
 
235
314
  ---
236
315
 
237
316
  ## 🌐 External Services
238
317
 
239
- The package contacts no hosts of its own. With `verifyOptions.publicClient` (or `publicClient` in `verifySiwxPayload`), the EIP-1271 fallback sends one `eth_call` to the RPC endpoint of that client. Sessions and nonces go only to the stores you provide.
318
+ The package contacts no hosts of its own. With `verifyOptions.publicClient` (or `publicClient` in `verifySiwxPayload`), the smart contract wallet fallback sends one `eth_call` to the RPC endpoint of the client of the message chain. Sessions and nonces go only to the stores you provide. The `/jwks` route only answers requests; the services you give its URL to fetch it.
240
319
 
241
320
  ---
242
321
 
@@ -0,0 +1,4 @@
1
+ 'use strict';var orbitCore=require('@tuwaio/orbit-core'),siwxCore=require('@tuwaio/siwx-core');function w(e){let t="";for(let n=0;n<e.byteLength;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function g(e){let t=atob(e.replace(/-/g,"+").replace(/_/g,"/")),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function x(e){return w(new TextEncoder().encode(e))}function b(e){return new TextDecoder().decode(g(e))}var f={ES256:{importParams:{name:"ECDSA",namedCurve:"P-256"},signParams:{name:"ECDSA",hash:"SHA-256"}},RS256:{importParams:{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},signParams:{name:"RSASSA-PKCS1-v1_5"}}},T=2048,H=["key_ops","ext","use"];function R(e){if(e.kty==="EC"&&e.crv==="P-256")return "ES256";if(e.kty==="RSA")return "RS256";throw new TypeError(`[SIWX-SERVER] Unsupported JWT key: kty ${String(e.kty)}${e.crv?`, crv ${e.crv}`:""}. Use an EC P-256 key (ES256) or an RSA key (RS256).`)}function J(e,t,n){return t==="ES256"?{kty:"EC",crv:"P-256",x:e.x,y:e.y,alg:t,kid:n,use:"sig"}:{kty:"RSA",n:e.n,e:e.e,alg:t,kid:n,use:"sig"}}async function C(e){let t;if(e.kty==="EC"&&e.crv&&e.x&&e.y)t=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x,y:e.y});else if(e.kty==="RSA"&&e.e&&e.n)t=JSON.stringify({e:e.e,kty:e.kty,n:e.n});else throw new TypeError("[SIWX-SERVER] A JWK thumbprint needs an EC key with crv, x and y or an RSA key with e and n.");let n=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return w(new Uint8Array(n))}async function ue(e="ES256"){let t=e==="ES256"?{name:"ECDSA",namedCurve:"P-256"}:{name:"RSASSA-PKCS1-v1_5",modulusLength:T,publicExponent:new Uint8Array([1,0,1]),hash:"SHA-256"},n=await globalThis.crypto.subtle.generateKey(t,true,["sign","verify"]),r=await globalThis.crypto.subtle.exportKey("jwk",n.privateKey),i=K({...r,alg:e}),o=await C(i);return {privateJwk:i,publicJwk:J(i,e,o),kid:o}}async function le(e){let{privateKey:t,alg:n}=e;if(typeof t!="string")return P(t,n);let r=t.trim();if(r.startsWith("{")){let i;try{i=JSON.parse(r);}catch{throw new TypeError("[SIWX-SERVER] The JWT private key is not valid JSON.")}return P(i,n)}if(r.includes("-----BEGIN"))return L(r,n);throw new TypeError("[SIWX-SERVER] The JWT private key must be a JWK (object or JSON) or a PKCS#8 PEM.")}function de(e){let t=new Set,n=[];for(let r of e){let i="privateKey"in r?r.publicJwk:J(r,r.alg,r.kid);t.has(i.kid)||(t.add(i.kid),n.push(i));}return {keys:n}}function K(e){let t={...e};for(let n of H)delete t[n];return t}async function P(e,t){if(!e||typeof e!="object"||!e.kty)throw new TypeError("[SIWX-SERVER] The JWT private key is not a JWK.");if(!e.d)throw new TypeError("[SIWX-SERVER] The JWT key is a public key; a private key is needed to sign.");let n=R(e);if(e.alg&&e.alg!==n)throw new TypeError(`[SIWX-SERVER] The JWK alg ${e.alg} does not match its key type (${n}).`);if(t&&t!==n)throw new TypeError(`[SIWX-SERVER] Expected a ${t} key, got a ${n} key.`);if(n==="RS256"&&g(e.n??"").length*8<T)throw new TypeError(`[SIWX-SERVER] RSA keys must have at least ${T} bits.`);let r;try{r=await globalThis.crypto.subtle.importKey("jwk",K({...e,alg:n}),f[n].importParams,!1,["sign"]);}catch(o){throw new TypeError(`[SIWX-SERVER] The JWT private key could not be imported: ${String(o)}`,{cause:o})}let i=await C(e);return {alg:n,kid:i,privateKey:r,publicJwk:J(e,n,i)}}async function L(e,t){let n=e.replace(/\\n/g,`
2
+ `).replace(/\r\n/g,`
3
+ `),r=/-----BEGIN PRIVATE KEY-----([\s\S]+?)-----END PRIVATE KEY-----/.exec(n);if(!r)throw new TypeError("[SIWX-SERVER] Only PKCS#8 PEM keys (-----BEGIN PRIVATE KEY-----) are supported. Convert SEC1 or PKCS#1 keys with `openssl pkcs8 -topk8 -nocrypt`.");let i=g(r[1].replace(/\s+/g,"").replace(/\+/g,"-").replace(/\//g,"_"));for(let o of t?[t]:["ES256","RS256"]){let a;try{let s=await globalThis.crypto.subtle.importKey("pkcs8",i,f[o].importParams,!0,["sign"]);a=await globalThis.crypto.subtle.exportKey("jwk",s);}catch{continue}return P(a,o)}throw new TypeError(`[SIWX-SERVER] The PEM is not ${t?`a ${t}`:"an EC P-256 or RSA"} private key.`)}var Y=600,W=604800,z=new Set(["iss","sub","aud","iat","exp","nbf","jti","caip10","chain_id"]);function D(e){let t=orbitCore.parseCaip10AccountId(e.address);if(!t)throw new TypeError(`[SIWX-SERVER] The session address is not a CAIP-10 account ID: "${e.address}".`);return t}function F(e,t){if(t)return t;let{namespace:n,address:r}=D(e);return `${n}:${n==="eip155"?r.toLowerCase():r}`}async function fe(e){let{session:t,key:n,issuer:r,audience:i,subject:o,claims:a,notAfter:s}=e,c=e.ttlSeconds??Y,S=e.now??Date.now();Q(r,c);let l=D(t);for(let A of Object.keys(a??{}))if(z.has(A))throw new TypeError(`[SIWX-SERVER] The claim "${A}" is set by SIWX and cannot be overridden.`);let u=[S+c*1e3];s!==void 0&&u.push(s),t.expirationTime&&u.push(Date.parse(t.expirationTime));let p=Math.floor(S/1e3),y=Math.floor(Math.min(...u)/1e3);if(!(y>p))throw new RangeError("[SIWX-SERVER] The session expires before a token can be issued.");let h={...a,iss:r,sub:o??F(t),...i===void 0?{}:{aud:i},iat:p,exp:y,jti:w(globalThis.crypto.getRandomValues(new Uint8Array(16))),caip10:orbitCore.formatCaip10AccountId(l.chainId,l.address)??t.address,chain_id:siwxCore.normalizeSolanaChainId(t.chainId)},m=`${x(JSON.stringify({alg:n.alg,kid:n.kid,typ:"JWT"}))}.${x(JSON.stringify(h))}`,d=await globalThis.crypto.subtle.sign(f[n.alg].signParams,n.privateKey,new TextEncoder().encode(m));return {token:`${m}.${w(new Uint8Array(d))}`,expiresAt:y*1e3}}async function me(e,t){try{if(typeof e!="string")return null;let n=e.split(".");if(n.length!==3)return null;let[r,i,o]=n,a=JSON.parse(b(r)),s=JSON.parse(b(i));if(!N(a)||!N(s))return null;let c=a.alg;if(c!=="ES256"&&c!=="RS256"||a.typ!==void 0&&a.typ!=="JWT"||typeof a.kid!="string"||a.kid.length===0)return null;let l=(Array.isArray(t.jwks)?t.jwks:t.jwks.keys).map(d=>"privateKey"in d?d.publicJwk:d).find(d=>d.kid===a.kid);if(!l||R(l)!==c||l.alg!==void 0&&l.alg!==c)return null;let u=g(o);if(c==="ES256"&&u.length!==64)return null;let p=await globalThis.crypto.subtle.importKey("jwk",c==="ES256"?{kty:"EC",crv:"P-256",x:l.x,y:l.y}:{kty:"RSA",n:l.n,e:l.e},f[c].importParams,!1,["verify"]);if(!await globalThis.crypto.subtle.verify(f[c].signParams,p,u,new TextEncoder().encode(`${r}.${i}`)))return null;let h=(t.now??Date.now())/1e3,m=t.clockSkewSeconds??60;if(s.iss!==t.issuer||typeof s.sub!="string"||s.sub.length===0||typeof s.exp!="number"||h>s.exp+m||typeof s.iat!="number"||s.iat>h+m)return null;if(t.audience!==void 0){let d=Array.isArray(t.audience)?t.audience:[t.audience];if(!(Array.isArray(s.aud)?s.aud:[s.aud]).some(I=>typeof I=="string"&&d.includes(I)))return null}return s}catch{return null}}function N(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Q(e,t){if(typeof e!="string"||e.length===0)throw new TypeError("[SIWX-SERVER] The JWT issuer must be a non-empty string, for example your app URL.");if(!Number.isInteger(t)||t<1||t>W)throw new RangeError(`[SIWX-SERVER] The JWT ttlSeconds must be an integer from 1 to ${W}.`)}function Z(e){return {address:e.address,chainId:e.chainId,domain:e.domain,nonce:e.nonce,issuedAt:e.issuedAt,expirationTime:e.expirationTime}}async function Te(e,t={}){try{let n=siwxCore.parseMessage(e.message),r=siwxCore.validateMessage(n,{skipExpiration:t.skipExpiration,policy:t.policy});if(!r.valid)return {success:!1,error:`Validation failed: ${r.errors.join(", ")}`};if(t.usedNonces?.has(n.nonce))throw new siwxCore.SiwxNonceReplayError(n.nonce);let i=orbitCore.parseCaip2ChainId(n.chainId)?.namespace;if(!i||!["eip155","solana"].includes(i))throw new siwxCore.SiwxUnsupportedNamespaceError(i??"unknown");if(i==="eip155"){let{verifyEvmSignature:o}=await import('@tuwaio/siwx-evm');return {...await o(e.message,e.signature,{skipExpiration:t.skipExpiration,publicClient:t.publicClient}),namespace:i}}if(i==="solana"){let{verifyEd25519:o}=await import('@tuwaio/siwx-solana');return {...await o(e,{skipExpiration:t.skipExpiration}),namespace:i}}return {success:!1,error:"Unsupported namespace."}}catch(n){return n instanceof siwxCore.SiwxNonceReplayError||n instanceof siwxCore.SiwxUnsupportedNamespaceError?{success:false,error:n.message}:{success:false,error:`Server verification failed: ${String(n)}`}}}async function k(e){let t=new TextEncoder;return globalThis.crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:"SHA-256"},false,["sign","verify"])}async function Pe(e,t,n=1800){if(!t||t.length<32)throw new Error("[SIWX-SERVER] Stateless demo signing secret must be at least 32 characters long.");let i=Date.now()+n*1e3,o={version:1,address:e.address,chainId:e.chainId,domain:e.domain,nonce:e.nonce,issuedAt:e.issuedAt,expirationTime:e.expirationTime??new Date(i).toISOString(),sessionId:siwxCore.generateNonce(),mode:"demo"},a=JSON.stringify(o),s=x(a),c=await k(t),S=new TextEncoder,l=await globalThis.crypto.subtle.sign("HMAC",c,S.encode(s)),u=w(new Uint8Array(l));return `${s}.${u}`}async function re(e,t,n){if(!e||typeof e!="string"||!t)return null;let r=e.split(".");if(r.length!==2)return null;let[i,o]=r;try{let a=await k(t),s=g(o),c=new TextEncoder;if(!await globalThis.crypto.subtle.verify("HMAC",a,s,c.encode(i)))return null;let l=b(i),u=JSON.parse(l);if(u.version!==1||u.mode!=="demo")return null;if(u.expirationTime){let p=new Date(u.expirationTime).getTime(),y=(n?.clockSkewSeconds??60)*1e3;if(isNaN(p)||p+y<Date.now())return null}return n?.expectedDomain!==void 0&&!(Array.isArray(n.expectedDomain)?n.expectedDomain:[n.expectedDomain]).some(y=>y.toLowerCase()===u.domain.toLowerCase())||!siwxCore.isChainIdAllowed(u.chainId,n?.allowedChainIds)?null:{address:u.address,chainId:u.chainId,domain:u.domain,nonce:u.nonce,issuedAt:u.issuedAt,expirationTime:u.expirationTime}}catch{return null}}var B="siwx-demo-nonce:",$=32,X=10,ie=/^[0-9a-f]{106}$/;function se(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function oe(e){let t=new Uint8Array(new ArrayBuffer(e.length/2));for(let n=0;n<t.length;n++)t[n]=parseInt(e.slice(n*2,n*2+2),16);return t}async function Re(e,t=300){if(!e||e.length<32)throw new Error("[SIWX-SERVER] Stateless demo signing secret must be at least 32 characters long.");let n=Math.floor(Date.now()/1e3)+t,r=siwxCore.generateNonce()+n.toString(16).padStart(X,"0"),i=await k(e),o=await globalThis.crypto.subtle.sign("HMAC",i,new TextEncoder().encode(B+r));return r+se(new Uint8Array(o))}async function Je(e,t){if(typeof e!="string"||!t||!ie.test(e))return false;let n=$+X,r=e.slice(0,n),i=e.slice(n);try{let o=await k(t);return await globalThis.crypto.subtle.verify("HMAC",o,oe(i),new TextEncoder().encode(B+r))?parseInt(r.slice($),16)*1e3>=Date.now():!1}catch{return false}}function ve(e,t={}){let{name:n="siwx-session-v2",maxAge:r=3600*24*7,path:i="/",domain:o,secure:a=true,sameSite:s="Strict"}=t,c=[`${n}=${e}`,`Max-Age=${r}`,`Path=${i}`,"HttpOnly",`SameSite=${s}`];return a&&c.push("Secure"),o&&c.push(`Domain=${o}`),c.join("; ")}function Ie(e={}){let{name:t="siwx-session-v2",path:n="/",domain:r,secure:i=true,sameSite:o="Strict"}=e,a=[`${t}=`,`Path=${n}`,"Expires=Thu, 01 Jan 1970 00:00:00 GMT","Max-Age=0","HttpOnly",`SameSite=${o}`];return i&&a.push("Secure"),r&&a.push(`Domain=${r}`),a.join("; ")}function E(e,t){return e?Object.fromEntries(e.split("; ").filter(Boolean).map(r=>{let i=r.split("=");return [i[0].trim(),i.slice(1).join("=")]}))[t]??null:null}var _=class{records=new Map;constructor(t){if(typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV==="production"&&!t?.allowInProduction)throw new Error("[SIWX-SERVER] MemorySiwxSessionStore must not be used in production. Connect Redis or a durable store.")}async create(t){let n=siwxCore.generateNonce(),r=Date.now(),i=r+t.ttlSeconds*1e3,o={id:n,session:t.session,createdAt:r,expiresAt:i};return this.records.set(n,o),o}async get(t){let n=this.records.get(t);return n?n.expiresAt<Date.now()?(this.records.delete(t),null):n:null}async bindSubject(t,n){let r=await this.get(t);return r?(r.subjectId=n,true):false}async revoke(t){this.records.delete(t);}},U=class{nonces=new Map;constructor(t){if(typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV==="production"&&!t?.allowInProduction)throw new Error("[SIWX-SERVER] MemorySiwxNonceStore must not be used in production. Connect Redis or a durable store.")}async issue(t){let n=Date.now()+t.ttlSeconds*1e3;this.nonces.set(t.nonce,n);}async consume(t){let n=this.nonces.get(t.nonce);return !(!n||(this.nonces.delete(t.nonce),n<Date.now()))}};async function Ce(e){let{cookieSource:t,cookieName:n="siwx-session-v2",sessionStore:r,signingSecret:i,policy:o}=e;if(!t)return null;let a=null;if(typeof t=="string")a=t.includes("=")?E(t,n):t;else if(typeof t.headers=="object"&&typeof t.headers?.get=="function"){let s=t.headers.get("cookie");a=E(s,n);}else if(typeof t.get=="function"){let s=t.get(n);if(s&&typeof s=="object"&&"value"in s)a=s.value;else if(typeof s=="string")a=s.includes("=")?E(s,n):s;else if(typeof t.get=="function"){let c=t.get("cookie");c&&(a=E(c,n));}}if(!a)return null;if(r){let s=await r.get(a);return !s?.session||o&&(o.expectedDomain!==void 0&&!(Array.isArray(o.expectedDomain)?o.expectedDomain:[o.expectedDomain]).some(S=>S.toLowerCase()===s.session.domain.toLowerCase())||!siwxCore.isChainIdAllowed(s.session.chainId,o.allowedChainIds)||o.requireExpirationTime&&!s.session.expirationTime)?null:s.session}return i?re(a,i,o):null}
4
+ Object.defineProperty(exports,"j",{enumerable:true,get:function(){return siwxCore.generateNonce}});exports.a=C;exports.b=ue;exports.c=le;exports.d=de;exports.e=F;exports.f=fe;exports.g=me;exports.h=Q;exports.i=Z;exports.k=Te;exports.l=Pe;exports.m=re;exports.n=Re;exports.o=Je;exports.p=ve;exports.q=Ie;exports.r=E;exports.s=_;exports.t=U;exports.u=Ce;
@@ -0,0 +1,4 @@
1
+ import {formatCaip10AccountId,parseCaip2ChainId,parseCaip10AccountId}from'@tuwaio/orbit-core';import {normalizeSolanaChainId,parseMessage,validateMessage,SiwxNonceReplayError,SiwxUnsupportedNamespaceError,generateNonce,isChainIdAllowed}from'@tuwaio/siwx-core';export{generateNonce as j}from'@tuwaio/siwx-core';function w(e){let t="";for(let n=0;n<e.byteLength;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function g(e){let t=atob(e.replace(/-/g,"+").replace(/_/g,"/")),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function x(e){return w(new TextEncoder().encode(e))}function b(e){return new TextDecoder().decode(g(e))}var f={ES256:{importParams:{name:"ECDSA",namedCurve:"P-256"},signParams:{name:"ECDSA",hash:"SHA-256"}},RS256:{importParams:{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},signParams:{name:"RSASSA-PKCS1-v1_5"}}},T=2048,H=["key_ops","ext","use"];function R(e){if(e.kty==="EC"&&e.crv==="P-256")return "ES256";if(e.kty==="RSA")return "RS256";throw new TypeError(`[SIWX-SERVER] Unsupported JWT key: kty ${String(e.kty)}${e.crv?`, crv ${e.crv}`:""}. Use an EC P-256 key (ES256) or an RSA key (RS256).`)}function J(e,t,n){return t==="ES256"?{kty:"EC",crv:"P-256",x:e.x,y:e.y,alg:t,kid:n,use:"sig"}:{kty:"RSA",n:e.n,e:e.e,alg:t,kid:n,use:"sig"}}async function C(e){let t;if(e.kty==="EC"&&e.crv&&e.x&&e.y)t=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x,y:e.y});else if(e.kty==="RSA"&&e.e&&e.n)t=JSON.stringify({e:e.e,kty:e.kty,n:e.n});else throw new TypeError("[SIWX-SERVER] A JWK thumbprint needs an EC key with crv, x and y or an RSA key with e and n.");let n=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return w(new Uint8Array(n))}async function ue(e="ES256"){let t=e==="ES256"?{name:"ECDSA",namedCurve:"P-256"}:{name:"RSASSA-PKCS1-v1_5",modulusLength:T,publicExponent:new Uint8Array([1,0,1]),hash:"SHA-256"},n=await globalThis.crypto.subtle.generateKey(t,true,["sign","verify"]),r=await globalThis.crypto.subtle.exportKey("jwk",n.privateKey),i=K({...r,alg:e}),o=await C(i);return {privateJwk:i,publicJwk:J(i,e,o),kid:o}}async function le(e){let{privateKey:t,alg:n}=e;if(typeof t!="string")return P(t,n);let r=t.trim();if(r.startsWith("{")){let i;try{i=JSON.parse(r);}catch{throw new TypeError("[SIWX-SERVER] The JWT private key is not valid JSON.")}return P(i,n)}if(r.includes("-----BEGIN"))return L(r,n);throw new TypeError("[SIWX-SERVER] The JWT private key must be a JWK (object or JSON) or a PKCS#8 PEM.")}function de(e){let t=new Set,n=[];for(let r of e){let i="privateKey"in r?r.publicJwk:J(r,r.alg,r.kid);t.has(i.kid)||(t.add(i.kid),n.push(i));}return {keys:n}}function K(e){let t={...e};for(let n of H)delete t[n];return t}async function P(e,t){if(!e||typeof e!="object"||!e.kty)throw new TypeError("[SIWX-SERVER] The JWT private key is not a JWK.");if(!e.d)throw new TypeError("[SIWX-SERVER] The JWT key is a public key; a private key is needed to sign.");let n=R(e);if(e.alg&&e.alg!==n)throw new TypeError(`[SIWX-SERVER] The JWK alg ${e.alg} does not match its key type (${n}).`);if(t&&t!==n)throw new TypeError(`[SIWX-SERVER] Expected a ${t} key, got a ${n} key.`);if(n==="RS256"&&g(e.n??"").length*8<T)throw new TypeError(`[SIWX-SERVER] RSA keys must have at least ${T} bits.`);let r;try{r=await globalThis.crypto.subtle.importKey("jwk",K({...e,alg:n}),f[n].importParams,!1,["sign"]);}catch(o){throw new TypeError(`[SIWX-SERVER] The JWT private key could not be imported: ${String(o)}`,{cause:o})}let i=await C(e);return {alg:n,kid:i,privateKey:r,publicJwk:J(e,n,i)}}async function L(e,t){let n=e.replace(/\\n/g,`
2
+ `).replace(/\r\n/g,`
3
+ `),r=/-----BEGIN PRIVATE KEY-----([\s\S]+?)-----END PRIVATE KEY-----/.exec(n);if(!r)throw new TypeError("[SIWX-SERVER] Only PKCS#8 PEM keys (-----BEGIN PRIVATE KEY-----) are supported. Convert SEC1 or PKCS#1 keys with `openssl pkcs8 -topk8 -nocrypt`.");let i=g(r[1].replace(/\s+/g,"").replace(/\+/g,"-").replace(/\//g,"_"));for(let o of t?[t]:["ES256","RS256"]){let a;try{let s=await globalThis.crypto.subtle.importKey("pkcs8",i,f[o].importParams,!0,["sign"]);a=await globalThis.crypto.subtle.exportKey("jwk",s);}catch{continue}return P(a,o)}throw new TypeError(`[SIWX-SERVER] The PEM is not ${t?`a ${t}`:"an EC P-256 or RSA"} private key.`)}var Y=600,W=604800,z=new Set(["iss","sub","aud","iat","exp","nbf","jti","caip10","chain_id"]);function D(e){let t=parseCaip10AccountId(e.address);if(!t)throw new TypeError(`[SIWX-SERVER] The session address is not a CAIP-10 account ID: "${e.address}".`);return t}function F(e,t){if(t)return t;let{namespace:n,address:r}=D(e);return `${n}:${n==="eip155"?r.toLowerCase():r}`}async function fe(e){let{session:t,key:n,issuer:r,audience:i,subject:o,claims:a,notAfter:s}=e,c=e.ttlSeconds??Y,S=e.now??Date.now();Q(r,c);let l=D(t);for(let A of Object.keys(a??{}))if(z.has(A))throw new TypeError(`[SIWX-SERVER] The claim "${A}" is set by SIWX and cannot be overridden.`);let u=[S+c*1e3];s!==void 0&&u.push(s),t.expirationTime&&u.push(Date.parse(t.expirationTime));let p=Math.floor(S/1e3),y=Math.floor(Math.min(...u)/1e3);if(!(y>p))throw new RangeError("[SIWX-SERVER] The session expires before a token can be issued.");let h={...a,iss:r,sub:o??F(t),...i===void 0?{}:{aud:i},iat:p,exp:y,jti:w(globalThis.crypto.getRandomValues(new Uint8Array(16))),caip10:formatCaip10AccountId(l.chainId,l.address)??t.address,chain_id:normalizeSolanaChainId(t.chainId)},m=`${x(JSON.stringify({alg:n.alg,kid:n.kid,typ:"JWT"}))}.${x(JSON.stringify(h))}`,d=await globalThis.crypto.subtle.sign(f[n.alg].signParams,n.privateKey,new TextEncoder().encode(m));return {token:`${m}.${w(new Uint8Array(d))}`,expiresAt:y*1e3}}async function me(e,t){try{if(typeof e!="string")return null;let n=e.split(".");if(n.length!==3)return null;let[r,i,o]=n,a=JSON.parse(b(r)),s=JSON.parse(b(i));if(!N(a)||!N(s))return null;let c=a.alg;if(c!=="ES256"&&c!=="RS256"||a.typ!==void 0&&a.typ!=="JWT"||typeof a.kid!="string"||a.kid.length===0)return null;let l=(Array.isArray(t.jwks)?t.jwks:t.jwks.keys).map(d=>"privateKey"in d?d.publicJwk:d).find(d=>d.kid===a.kid);if(!l||R(l)!==c||l.alg!==void 0&&l.alg!==c)return null;let u=g(o);if(c==="ES256"&&u.length!==64)return null;let p=await globalThis.crypto.subtle.importKey("jwk",c==="ES256"?{kty:"EC",crv:"P-256",x:l.x,y:l.y}:{kty:"RSA",n:l.n,e:l.e},f[c].importParams,!1,["verify"]);if(!await globalThis.crypto.subtle.verify(f[c].signParams,p,u,new TextEncoder().encode(`${r}.${i}`)))return null;let h=(t.now??Date.now())/1e3,m=t.clockSkewSeconds??60;if(s.iss!==t.issuer||typeof s.sub!="string"||s.sub.length===0||typeof s.exp!="number"||h>s.exp+m||typeof s.iat!="number"||s.iat>h+m)return null;if(t.audience!==void 0){let d=Array.isArray(t.audience)?t.audience:[t.audience];if(!(Array.isArray(s.aud)?s.aud:[s.aud]).some(I=>typeof I=="string"&&d.includes(I)))return null}return s}catch{return null}}function N(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Q(e,t){if(typeof e!="string"||e.length===0)throw new TypeError("[SIWX-SERVER] The JWT issuer must be a non-empty string, for example your app URL.");if(!Number.isInteger(t)||t<1||t>W)throw new RangeError(`[SIWX-SERVER] The JWT ttlSeconds must be an integer from 1 to ${W}.`)}function Z(e){return {address:e.address,chainId:e.chainId,domain:e.domain,nonce:e.nonce,issuedAt:e.issuedAt,expirationTime:e.expirationTime}}async function Te(e,t={}){try{let n=parseMessage(e.message),r=validateMessage(n,{skipExpiration:t.skipExpiration,policy:t.policy});if(!r.valid)return {success:!1,error:`Validation failed: ${r.errors.join(", ")}`};if(t.usedNonces?.has(n.nonce))throw new SiwxNonceReplayError(n.nonce);let i=parseCaip2ChainId(n.chainId)?.namespace;if(!i||!["eip155","solana"].includes(i))throw new SiwxUnsupportedNamespaceError(i??"unknown");if(i==="eip155"){let{verifyEvmSignature:o}=await import('@tuwaio/siwx-evm');return {...await o(e.message,e.signature,{skipExpiration:t.skipExpiration,publicClient:t.publicClient}),namespace:i}}if(i==="solana"){let{verifyEd25519:o}=await import('@tuwaio/siwx-solana');return {...await o(e,{skipExpiration:t.skipExpiration}),namespace:i}}return {success:!1,error:"Unsupported namespace."}}catch(n){return n instanceof SiwxNonceReplayError||n instanceof SiwxUnsupportedNamespaceError?{success:false,error:n.message}:{success:false,error:`Server verification failed: ${String(n)}`}}}async function k(e){let t=new TextEncoder;return globalThis.crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:"SHA-256"},false,["sign","verify"])}async function Pe(e,t,n=1800){if(!t||t.length<32)throw new Error("[SIWX-SERVER] Stateless demo signing secret must be at least 32 characters long.");let i=Date.now()+n*1e3,o={version:1,address:e.address,chainId:e.chainId,domain:e.domain,nonce:e.nonce,issuedAt:e.issuedAt,expirationTime:e.expirationTime??new Date(i).toISOString(),sessionId:generateNonce(),mode:"demo"},a=JSON.stringify(o),s=x(a),c=await k(t),S=new TextEncoder,l=await globalThis.crypto.subtle.sign("HMAC",c,S.encode(s)),u=w(new Uint8Array(l));return `${s}.${u}`}async function re(e,t,n){if(!e||typeof e!="string"||!t)return null;let r=e.split(".");if(r.length!==2)return null;let[i,o]=r;try{let a=await k(t),s=g(o),c=new TextEncoder;if(!await globalThis.crypto.subtle.verify("HMAC",a,s,c.encode(i)))return null;let l=b(i),u=JSON.parse(l);if(u.version!==1||u.mode!=="demo")return null;if(u.expirationTime){let p=new Date(u.expirationTime).getTime(),y=(n?.clockSkewSeconds??60)*1e3;if(isNaN(p)||p+y<Date.now())return null}return n?.expectedDomain!==void 0&&!(Array.isArray(n.expectedDomain)?n.expectedDomain:[n.expectedDomain]).some(y=>y.toLowerCase()===u.domain.toLowerCase())||!isChainIdAllowed(u.chainId,n?.allowedChainIds)?null:{address:u.address,chainId:u.chainId,domain:u.domain,nonce:u.nonce,issuedAt:u.issuedAt,expirationTime:u.expirationTime}}catch{return null}}var B="siwx-demo-nonce:",$=32,X=10,ie=/^[0-9a-f]{106}$/;function se(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function oe(e){let t=new Uint8Array(new ArrayBuffer(e.length/2));for(let n=0;n<t.length;n++)t[n]=parseInt(e.slice(n*2,n*2+2),16);return t}async function Re(e,t=300){if(!e||e.length<32)throw new Error("[SIWX-SERVER] Stateless demo signing secret must be at least 32 characters long.");let n=Math.floor(Date.now()/1e3)+t,r=generateNonce()+n.toString(16).padStart(X,"0"),i=await k(e),o=await globalThis.crypto.subtle.sign("HMAC",i,new TextEncoder().encode(B+r));return r+se(new Uint8Array(o))}async function Je(e,t){if(typeof e!="string"||!t||!ie.test(e))return false;let n=$+X,r=e.slice(0,n),i=e.slice(n);try{let o=await k(t);return await globalThis.crypto.subtle.verify("HMAC",o,oe(i),new TextEncoder().encode(B+r))?parseInt(r.slice($),16)*1e3>=Date.now():!1}catch{return false}}function ve(e,t={}){let{name:n="siwx-session-v2",maxAge:r=3600*24*7,path:i="/",domain:o,secure:a=true,sameSite:s="Strict"}=t,c=[`${n}=${e}`,`Max-Age=${r}`,`Path=${i}`,"HttpOnly",`SameSite=${s}`];return a&&c.push("Secure"),o&&c.push(`Domain=${o}`),c.join("; ")}function Ie(e={}){let{name:t="siwx-session-v2",path:n="/",domain:r,secure:i=true,sameSite:o="Strict"}=e,a=[`${t}=`,`Path=${n}`,"Expires=Thu, 01 Jan 1970 00:00:00 GMT","Max-Age=0","HttpOnly",`SameSite=${o}`];return i&&a.push("Secure"),r&&a.push(`Domain=${r}`),a.join("; ")}function E(e,t){return e?Object.fromEntries(e.split("; ").filter(Boolean).map(r=>{let i=r.split("=");return [i[0].trim(),i.slice(1).join("=")]}))[t]??null:null}var _=class{records=new Map;constructor(t){if(typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV==="production"&&!t?.allowInProduction)throw new Error("[SIWX-SERVER] MemorySiwxSessionStore must not be used in production. Connect Redis or a durable store.")}async create(t){let n=generateNonce(),r=Date.now(),i=r+t.ttlSeconds*1e3,o={id:n,session:t.session,createdAt:r,expiresAt:i};return this.records.set(n,o),o}async get(t){let n=this.records.get(t);return n?n.expiresAt<Date.now()?(this.records.delete(t),null):n:null}async bindSubject(t,n){let r=await this.get(t);return r?(r.subjectId=n,true):false}async revoke(t){this.records.delete(t);}},U=class{nonces=new Map;constructor(t){if(typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV==="production"&&!t?.allowInProduction)throw new Error("[SIWX-SERVER] MemorySiwxNonceStore must not be used in production. Connect Redis or a durable store.")}async issue(t){let n=Date.now()+t.ttlSeconds*1e3;this.nonces.set(t.nonce,n);}async consume(t){let n=this.nonces.get(t.nonce);return !(!n||(this.nonces.delete(t.nonce),n<Date.now()))}};async function Ce(e){let{cookieSource:t,cookieName:n="siwx-session-v2",sessionStore:r,signingSecret:i,policy:o}=e;if(!t)return null;let a=null;if(typeof t=="string")a=t.includes("=")?E(t,n):t;else if(typeof t.headers=="object"&&typeof t.headers?.get=="function"){let s=t.headers.get("cookie");a=E(s,n);}else if(typeof t.get=="function"){let s=t.get(n);if(s&&typeof s=="object"&&"value"in s)a=s.value;else if(typeof s=="string")a=s.includes("=")?E(s,n):s;else if(typeof t.get=="function"){let c=t.get("cookie");c&&(a=E(c,n));}}if(!a)return null;if(r){let s=await r.get(a);return !s?.session||o&&(o.expectedDomain!==void 0&&!(Array.isArray(o.expectedDomain)?o.expectedDomain:[o.expectedDomain]).some(S=>S.toLowerCase()===s.session.domain.toLowerCase())||!isChainIdAllowed(s.session.chainId,o.allowedChainIds)||o.requireExpirationTime&&!s.session.expirationTime)?null:s.session}return i?re(a,i,o):null}
4
+ export{C as a,ue as b,le as c,de as d,F as e,fe as f,me as g,Q as h,Z as i,Te as k,Pe as l,re as m,Re as n,Je as o,ve as p,Ie as q,E as r,_ as s,U as t,Ce as u};