@tuwaio/siwx-server 0.6.0 → 0.7.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 CHANGED
@@ -14,7 +14,7 @@ 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 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.
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, over the message or its version 1 off-chain message, which hardware wallets sign). 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.
@@ -239,7 +239,9 @@ export async function handleVerify(request: Request): Promise<Response> {
239
239
  return Response.json({ error: 'Invalid nonce' }, { status: 401 });
240
240
  }
241
241
 
242
- const record = await sessionStore.create({ session: toSession(result.data), ttlSeconds: 7 * 24 * 60 * 60 });
242
+ // Keep how the wallet signed (its key or a smart contract wallet): the JWT subject depends on it.
243
+ const session = toSession(result.data, result.method);
244
+ const record = await sessionStore.create({ session, ttlSeconds: 7 * 24 * 60 * 60 });
243
245
  return Response.json(record.session, { headers: { 'Set-Cookie': createSessionCookie(record.id) } });
244
246
  }
245
247
  ```
@@ -282,7 +284,7 @@ export const { GET, POST, DELETE } = createSiwxApiHandler({
282
284
  - `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
285
  - `GET /api/siwx/jwks` returns the public keys. Give this URL to the provider.
284
286
 
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.
287
+ The `sub` claim identifies the user: the user ID you bound with `bindSubject`; otherwise, for a wallet that signs with its own key, 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. A smart contract wallet (Safe, Coinbase Smart Wallet, other ERC-4337 accounts) gets the account with its chain (`eip155:8453:0x…` in lowercase): its owners are set on each chain separately, so the same address on another network can belong to someone else. When your app links several wallets or networks to one account, bind its user ID. 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
288
 
287
289
  A service that receives the token checks it against the JWKS:
288
290
 
@@ -309,7 +311,7 @@ export async function readWallet(request: Request): Promise<string | null> {
309
311
  - **Cookies:** the session cookie is always `HttpOnly`, and `Secure` and `SameSite=Strict` by default. Keep `secure: true` in production.
310
312
  - **Secrets:** the demo `signingSecret` must be at least 32 characters and must never reach the browser. Changing it invalidates every demo session.
311
313
  - **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.
314
+ - **JWT subject:** the receiving service identifies the user by `sub`. Keep the default or build it with `siwxJwtSubject`: it is the same on every EVM network for a wallet that signs with its own key, and bound to the chain for a smart contract wallet, whose owners can differ per chain. In your own handlers, create sessions with `toSession(result.data, result.method)`; without the method, every EVM subject is bound to its chain.
313
315
 
314
316
  ---
315
317
 
@@ -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(t){let e="";for(let n=0;n<t.byteLength;n++)e+=String.fromCharCode(t[n]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function g(t){let e=atob(t.replace(/-/g,"+").replace(/_/g,"/")),n=new Uint8Array(e.length);for(let i=0;i<e.length;i++)n[i]=e.charCodeAt(i);return n}function x(t){return w(new TextEncoder().encode(t))}function h(t){return new TextDecoder().decode(g(t))}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(t){if(t.kty==="EC"&&t.crv==="P-256")return "ES256";if(t.kty==="RSA")return "RS256";throw new TypeError(`[SIWX-SERVER] Unsupported JWT key: kty ${String(t.kty)}${t.crv?`, crv ${t.crv}`:""}. Use an EC P-256 key (ES256) or an RSA key (RS256).`)}function J(t,e,n){return e==="ES256"?{kty:"EC",crv:"P-256",x:t.x,y:t.y,alg:e,kid:n,use:"sig"}:{kty:"RSA",n:t.n,e:t.e,alg:e,kid:n,use:"sig"}}async function C(t){let e;if(t.kty==="EC"&&t.crv&&t.x&&t.y)e=JSON.stringify({crv:t.crv,kty:t.kty,x:t.x,y:t.y});else if(t.kty==="RSA"&&t.e&&t.n)e=JSON.stringify({e:t.e,kty:t.kty,n:t.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(e));return w(new Uint8Array(n))}async function ue(t="ES256"){let e=t==="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(e,true,["sign","verify"]),i=await globalThis.crypto.subtle.exportKey("jwk",n.privateKey),r=K({...i,alg:t}),o=await C(r);return {privateJwk:r,publicJwk:J(r,t,o),kid:o}}async function le(t){let{privateKey:e,alg:n}=t;if(typeof e!="string")return P(e,n);let i=e.trim();if(i.startsWith("{")){let r;try{r=JSON.parse(i);}catch{throw new TypeError("[SIWX-SERVER] The JWT private key is not valid JSON.")}return P(r,n)}if(i.includes("-----BEGIN"))return G(i,n);throw new TypeError("[SIWX-SERVER] The JWT private key must be a JWK (object or JSON) or a PKCS#8 PEM.")}function de(t){let e=new Set,n=[];for(let i of t){let r="privateKey"in i?i.publicJwk:J(i,i.alg,i.kid);e.has(r.kid)||(e.add(r.kid),n.push(r));}return {keys:n}}function K(t){let e={...t};for(let n of H)delete e[n];return e}async function P(t,e){if(!t||typeof t!="object"||!t.kty)throw new TypeError("[SIWX-SERVER] The JWT private key is not a JWK.");if(!t.d)throw new TypeError("[SIWX-SERVER] The JWT key is a public key; a private key is needed to sign.");let n=R(t);if(t.alg&&t.alg!==n)throw new TypeError(`[SIWX-SERVER] The JWK alg ${t.alg} does not match its key type (${n}).`);if(e&&e!==n)throw new TypeError(`[SIWX-SERVER] Expected a ${e} key, got a ${n} key.`);if(n==="RS256"&&g(t.n??"").length*8<T)throw new TypeError(`[SIWX-SERVER] RSA keys must have at least ${T} bits.`);let i;try{i=await globalThis.crypto.subtle.importKey("jwk",K({...t,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 r=await C(t);return {alg:n,kid:r,privateKey:i,publicJwk:J(t,n,r)}}async function G(t,e){let n=t.replace(/\\n/g,`
2
+ `).replace(/\r\n/g,`
3
+ `),i=/-----BEGIN PRIVATE KEY-----([\s\S]+?)-----END PRIVATE KEY-----/.exec(n);if(!i)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 r=g(i[1].replace(/\s+/g,"").replace(/\+/g,"-").replace(/\//g,"_"));for(let o of e?[e]:["ES256","RS256"]){let a;try{let s=await globalThis.crypto.subtle.importKey("pkcs8",r,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 ${e?`a ${e}`:"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(t){let e=parseCaip10AccountId(t.address);if(!e)throw new TypeError(`[SIWX-SERVER] The session address is not a CAIP-10 account ID: "${t.address}".`);return e}function F(t,e){if(e)return e;let{chainId:n,namespace:i,address:r}=D(t);return i!=="eip155"?`${i}:${r}`:t.verificationMethod==="eip191"?`eip155:${r.toLowerCase()}`:formatCaip10AccountId(n,r.toLowerCase())??t.address.toLowerCase()}async function fe(t){let{session:e,key:n,issuer:i,audience:r,subject:o,claims:a,notAfter:s}=t,c=t.ttlSeconds??Y,S=t.now??Date.now();Q(i,c);let l=D(e);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),e.expirationTime&&u.push(Date.parse(e.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 b={...a,iss:i,sub:o??F(e),...r===void 0?{}:{aud:r},iat:p,exp:y,jti:w(globalThis.crypto.getRandomValues(new Uint8Array(16))),caip10:formatCaip10AccountId(l.chainId,l.address)??e.address,chain_id:normalizeSolanaChainId(e.chainId)},m=`${x(JSON.stringify({alg:n.alg,kid:n.kid,typ:"JWT"}))}.${x(JSON.stringify(b))}`,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(t,e){try{if(typeof t!="string")return null;let n=t.split(".");if(n.length!==3)return null;let[i,r,o]=n,a=JSON.parse(h(i)),s=JSON.parse(h(r));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(e.jwks)?e.jwks:e.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(`${i}.${r}`)))return null;let b=(e.now??Date.now())/1e3,m=e.clockSkewSeconds??60;if(s.iss!==e.issuer||typeof s.sub!="string"||s.sub.length===0||typeof s.exp!="number"||b>s.exp+m||typeof s.iat!="number"||s.iat>b+m)return null;if(e.audience!==void 0){let d=Array.isArray(e.audience)?e.audience:[e.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(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Q(t,e){if(typeof t!="string"||t.length===0)throw new TypeError("[SIWX-SERVER] The JWT issuer must be a non-empty string, for example your app URL.");if(!Number.isInteger(e)||e<1||e>W)throw new RangeError(`[SIWX-SERVER] The JWT ttlSeconds must be an integer from 1 to ${W}.`)}function Z(t,e){return {address:t.address,chainId:t.chainId,domain:t.domain,nonce:t.nonce,issuedAt:t.issuedAt,expirationTime:t.expirationTime,...e===void 0?{}:{verificationMethod:e}}}async function Te(t,e={}){try{let n=parseMessage(t.message),i=validateMessage(n,{skipExpiration:e.skipExpiration,policy:e.policy});if(!i.valid)return {success:!1,error:`Validation failed: ${i.errors.join(", ")}`};if(e.usedNonces?.has(n.nonce))throw new SiwxNonceReplayError(n.nonce);let r=parseCaip2ChainId(n.chainId)?.namespace;if(!r||!["eip155","solana"].includes(r))throw new SiwxUnsupportedNamespaceError(r??"unknown");if(r==="eip155"){let{verifyEvmSignature:o}=await import('@tuwaio/siwx-evm');return {...await o(t.message,t.signature,{skipExpiration:e.skipExpiration,publicClient:e.publicClient}),namespace:r}}if(r==="solana"){let{verifyEd25519:o}=await import('@tuwaio/siwx-solana'),a=await o(t,{skipExpiration:e.skipExpiration});return a.success?{...a,namespace:r,method:"ed25519"}:{...a,namespace:r}}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(t){let e=new TextEncoder;return globalThis.crypto.subtle.importKey("raw",e.encode(t),{name:"HMAC",hash:"SHA-256"},false,["sign","verify"])}async function Pe(t,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 r=Date.now()+n*1e3,o={version:1,address:t.address,chainId:t.chainId,domain:t.domain,nonce:t.nonce,issuedAt:t.issuedAt,expirationTime:t.expirationTime??new Date(r).toISOString(),sessionId:generateNonce(),mode:"demo"},a=JSON.stringify(o),s=x(a),c=await k(e),S=new TextEncoder,l=await globalThis.crypto.subtle.sign("HMAC",c,S.encode(s)),u=w(new Uint8Array(l));return `${s}.${u}`}async function ie(t,e,n){if(!t||typeof t!="string"||!e)return null;let i=t.split(".");if(i.length!==2)return null;let[r,o]=i;try{let a=await k(e),s=g(o),c=new TextEncoder;if(!await globalThis.crypto.subtle.verify("HMAC",a,s,c.encode(r)))return null;let l=h(r),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 X="siwx-demo-nonce:",$=32,L=10,re=/^[0-9a-f]{106}$/;function se(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function oe(t){let e=new Uint8Array(new ArrayBuffer(t.length/2));for(let n=0;n<e.length;n++)e[n]=parseInt(t.slice(n*2,n*2+2),16);return e}async function Re(t,e=300){if(!t||t.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)+e,i=generateNonce()+n.toString(16).padStart(L,"0"),r=await k(t),o=await globalThis.crypto.subtle.sign("HMAC",r,new TextEncoder().encode(X+i));return i+se(new Uint8Array(o))}async function Je(t,e){if(typeof t!="string"||!e||!re.test(t))return false;let n=$+L,i=t.slice(0,n),r=t.slice(n);try{let o=await k(e);return await globalThis.crypto.subtle.verify("HMAC",o,oe(r),new TextEncoder().encode(X+i))?parseInt(i.slice($),16)*1e3>=Date.now():!1}catch{return false}}function ve(t,e={}){let{name:n="siwx-session-v2",maxAge:i=3600*24*7,path:r="/",domain:o,secure:a=true,sameSite:s="Strict"}=e,c=[`${n}=${t}`,`Max-Age=${i}`,`Path=${r}`,"HttpOnly",`SameSite=${s}`];return a&&c.push("Secure"),o&&c.push(`Domain=${o}`),c.join("; ")}function Ie(t={}){let{name:e="siwx-session-v2",path:n="/",domain:i,secure:r=true,sameSite:o="Strict"}=t,a=[`${e}=`,`Path=${n}`,"Expires=Thu, 01 Jan 1970 00:00:00 GMT","Max-Age=0","HttpOnly",`SameSite=${o}`];return r&&a.push("Secure"),i&&a.push(`Domain=${i}`),a.join("; ")}function E(t,e){return t?Object.fromEntries(t.split("; ").filter(Boolean).map(i=>{let r=i.split("=");return [r[0].trim(),r.slice(1).join("=")]}))[e]??null:null}var _=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(),i=Date.now(),r=i+e.ttlSeconds*1e3,o={id:n,session:e.session,createdAt:i,expiresAt:r};return this.records.set(n,o),o}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 i=await this.get(e);return i?(i.subjectId=n,true):false}async revoke(e){this.records.delete(e);}},U=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 Ce(t){let{cookieSource:e,cookieName:n="siwx-session-v2",sessionStore:i,signingSecret:r,policy:o}=t;if(!e)return null;let a=null;if(typeof e=="string")a=e.includes("=")?E(e,n):e;else if(typeof e.headers=="object"&&typeof e.headers?.get=="function"){let s=e.headers.get("cookie");a=E(s,n);}else if(typeof e.get=="function"){let s=e.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 e.get=="function"){let c=e.get("cookie");c&&(a=E(c,n));}}if(!a)return null;if(i){let s=await i.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 r?ie(a,r,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,ie 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};
@@ -0,0 +1,4 @@
1
+ 'use strict';var orbitCore=require('@tuwaio/orbit-core'),siwxCore=require('@tuwaio/siwx-core');function w(t){let e="";for(let n=0;n<t.byteLength;n++)e+=String.fromCharCode(t[n]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function g(t){let e=atob(t.replace(/-/g,"+").replace(/_/g,"/")),n=new Uint8Array(e.length);for(let i=0;i<e.length;i++)n[i]=e.charCodeAt(i);return n}function x(t){return w(new TextEncoder().encode(t))}function h(t){return new TextDecoder().decode(g(t))}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(t){if(t.kty==="EC"&&t.crv==="P-256")return "ES256";if(t.kty==="RSA")return "RS256";throw new TypeError(`[SIWX-SERVER] Unsupported JWT key: kty ${String(t.kty)}${t.crv?`, crv ${t.crv}`:""}. Use an EC P-256 key (ES256) or an RSA key (RS256).`)}function J(t,e,n){return e==="ES256"?{kty:"EC",crv:"P-256",x:t.x,y:t.y,alg:e,kid:n,use:"sig"}:{kty:"RSA",n:t.n,e:t.e,alg:e,kid:n,use:"sig"}}async function C(t){let e;if(t.kty==="EC"&&t.crv&&t.x&&t.y)e=JSON.stringify({crv:t.crv,kty:t.kty,x:t.x,y:t.y});else if(t.kty==="RSA"&&t.e&&t.n)e=JSON.stringify({e:t.e,kty:t.kty,n:t.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(e));return w(new Uint8Array(n))}async function ue(t="ES256"){let e=t==="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(e,true,["sign","verify"]),i=await globalThis.crypto.subtle.exportKey("jwk",n.privateKey),r=K({...i,alg:t}),o=await C(r);return {privateJwk:r,publicJwk:J(r,t,o),kid:o}}async function le(t){let{privateKey:e,alg:n}=t;if(typeof e!="string")return P(e,n);let i=e.trim();if(i.startsWith("{")){let r;try{r=JSON.parse(i);}catch{throw new TypeError("[SIWX-SERVER] The JWT private key is not valid JSON.")}return P(r,n)}if(i.includes("-----BEGIN"))return G(i,n);throw new TypeError("[SIWX-SERVER] The JWT private key must be a JWK (object or JSON) or a PKCS#8 PEM.")}function de(t){let e=new Set,n=[];for(let i of t){let r="privateKey"in i?i.publicJwk:J(i,i.alg,i.kid);e.has(r.kid)||(e.add(r.kid),n.push(r));}return {keys:n}}function K(t){let e={...t};for(let n of H)delete e[n];return e}async function P(t,e){if(!t||typeof t!="object"||!t.kty)throw new TypeError("[SIWX-SERVER] The JWT private key is not a JWK.");if(!t.d)throw new TypeError("[SIWX-SERVER] The JWT key is a public key; a private key is needed to sign.");let n=R(t);if(t.alg&&t.alg!==n)throw new TypeError(`[SIWX-SERVER] The JWK alg ${t.alg} does not match its key type (${n}).`);if(e&&e!==n)throw new TypeError(`[SIWX-SERVER] Expected a ${e} key, got a ${n} key.`);if(n==="RS256"&&g(t.n??"").length*8<T)throw new TypeError(`[SIWX-SERVER] RSA keys must have at least ${T} bits.`);let i;try{i=await globalThis.crypto.subtle.importKey("jwk",K({...t,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 r=await C(t);return {alg:n,kid:r,privateKey:i,publicJwk:J(t,n,r)}}async function G(t,e){let n=t.replace(/\\n/g,`
2
+ `).replace(/\r\n/g,`
3
+ `),i=/-----BEGIN PRIVATE KEY-----([\s\S]+?)-----END PRIVATE KEY-----/.exec(n);if(!i)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 r=g(i[1].replace(/\s+/g,"").replace(/\+/g,"-").replace(/\//g,"_"));for(let o of e?[e]:["ES256","RS256"]){let a;try{let s=await globalThis.crypto.subtle.importKey("pkcs8",r,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 ${e?`a ${e}`:"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(t){let e=orbitCore.parseCaip10AccountId(t.address);if(!e)throw new TypeError(`[SIWX-SERVER] The session address is not a CAIP-10 account ID: "${t.address}".`);return e}function F(t,e){if(e)return e;let{chainId:n,namespace:i,address:r}=D(t);return i!=="eip155"?`${i}:${r}`:t.verificationMethod==="eip191"?`eip155:${r.toLowerCase()}`:orbitCore.formatCaip10AccountId(n,r.toLowerCase())??t.address.toLowerCase()}async function fe(t){let{session:e,key:n,issuer:i,audience:r,subject:o,claims:a,notAfter:s}=t,c=t.ttlSeconds??Y,S=t.now??Date.now();Q(i,c);let l=D(e);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),e.expirationTime&&u.push(Date.parse(e.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 b={...a,iss:i,sub:o??F(e),...r===void 0?{}:{aud:r},iat:p,exp:y,jti:w(globalThis.crypto.getRandomValues(new Uint8Array(16))),caip10:orbitCore.formatCaip10AccountId(l.chainId,l.address)??e.address,chain_id:siwxCore.normalizeSolanaChainId(e.chainId)},m=`${x(JSON.stringify({alg:n.alg,kid:n.kid,typ:"JWT"}))}.${x(JSON.stringify(b))}`,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(t,e){try{if(typeof t!="string")return null;let n=t.split(".");if(n.length!==3)return null;let[i,r,o]=n,a=JSON.parse(h(i)),s=JSON.parse(h(r));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(e.jwks)?e.jwks:e.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(`${i}.${r}`)))return null;let b=(e.now??Date.now())/1e3,m=e.clockSkewSeconds??60;if(s.iss!==e.issuer||typeof s.sub!="string"||s.sub.length===0||typeof s.exp!="number"||b>s.exp+m||typeof s.iat!="number"||s.iat>b+m)return null;if(e.audience!==void 0){let d=Array.isArray(e.audience)?e.audience:[e.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(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Q(t,e){if(typeof t!="string"||t.length===0)throw new TypeError("[SIWX-SERVER] The JWT issuer must be a non-empty string, for example your app URL.");if(!Number.isInteger(e)||e<1||e>W)throw new RangeError(`[SIWX-SERVER] The JWT ttlSeconds must be an integer from 1 to ${W}.`)}function Z(t,e){return {address:t.address,chainId:t.chainId,domain:t.domain,nonce:t.nonce,issuedAt:t.issuedAt,expirationTime:t.expirationTime,...e===void 0?{}:{verificationMethod:e}}}async function Te(t,e={}){try{let n=siwxCore.parseMessage(t.message),i=siwxCore.validateMessage(n,{skipExpiration:e.skipExpiration,policy:e.policy});if(!i.valid)return {success:!1,error:`Validation failed: ${i.errors.join(", ")}`};if(e.usedNonces?.has(n.nonce))throw new siwxCore.SiwxNonceReplayError(n.nonce);let r=orbitCore.parseCaip2ChainId(n.chainId)?.namespace;if(!r||!["eip155","solana"].includes(r))throw new siwxCore.SiwxUnsupportedNamespaceError(r??"unknown");if(r==="eip155"){let{verifyEvmSignature:o}=await import('@tuwaio/siwx-evm');return {...await o(t.message,t.signature,{skipExpiration:e.skipExpiration,publicClient:e.publicClient}),namespace:r}}if(r==="solana"){let{verifyEd25519:o}=await import('@tuwaio/siwx-solana'),a=await o(t,{skipExpiration:e.skipExpiration});return a.success?{...a,namespace:r,method:"ed25519"}:{...a,namespace:r}}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(t){let e=new TextEncoder;return globalThis.crypto.subtle.importKey("raw",e.encode(t),{name:"HMAC",hash:"SHA-256"},false,["sign","verify"])}async function Pe(t,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 r=Date.now()+n*1e3,o={version:1,address:t.address,chainId:t.chainId,domain:t.domain,nonce:t.nonce,issuedAt:t.issuedAt,expirationTime:t.expirationTime??new Date(r).toISOString(),sessionId:siwxCore.generateNonce(),mode:"demo"},a=JSON.stringify(o),s=x(a),c=await k(e),S=new TextEncoder,l=await globalThis.crypto.subtle.sign("HMAC",c,S.encode(s)),u=w(new Uint8Array(l));return `${s}.${u}`}async function ie(t,e,n){if(!t||typeof t!="string"||!e)return null;let i=t.split(".");if(i.length!==2)return null;let[r,o]=i;try{let a=await k(e),s=g(o),c=new TextEncoder;if(!await globalThis.crypto.subtle.verify("HMAC",a,s,c.encode(r)))return null;let l=h(r),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 X="siwx-demo-nonce:",$=32,L=10,re=/^[0-9a-f]{106}$/;function se(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function oe(t){let e=new Uint8Array(new ArrayBuffer(t.length/2));for(let n=0;n<e.length;n++)e[n]=parseInt(t.slice(n*2,n*2+2),16);return e}async function Re(t,e=300){if(!t||t.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)+e,i=siwxCore.generateNonce()+n.toString(16).padStart(L,"0"),r=await k(t),o=await globalThis.crypto.subtle.sign("HMAC",r,new TextEncoder().encode(X+i));return i+se(new Uint8Array(o))}async function Je(t,e){if(typeof t!="string"||!e||!re.test(t))return false;let n=$+L,i=t.slice(0,n),r=t.slice(n);try{let o=await k(e);return await globalThis.crypto.subtle.verify("HMAC",o,oe(r),new TextEncoder().encode(X+i))?parseInt(i.slice($),16)*1e3>=Date.now():!1}catch{return false}}function ve(t,e={}){let{name:n="siwx-session-v2",maxAge:i=3600*24*7,path:r="/",domain:o,secure:a=true,sameSite:s="Strict"}=e,c=[`${n}=${t}`,`Max-Age=${i}`,`Path=${r}`,"HttpOnly",`SameSite=${s}`];return a&&c.push("Secure"),o&&c.push(`Domain=${o}`),c.join("; ")}function Ie(t={}){let{name:e="siwx-session-v2",path:n="/",domain:i,secure:r=true,sameSite:o="Strict"}=t,a=[`${e}=`,`Path=${n}`,"Expires=Thu, 01 Jan 1970 00:00:00 GMT","Max-Age=0","HttpOnly",`SameSite=${o}`];return r&&a.push("Secure"),i&&a.push(`Domain=${i}`),a.join("; ")}function E(t,e){return t?Object.fromEntries(t.split("; ").filter(Boolean).map(i=>{let r=i.split("=");return [r[0].trim(),r.slice(1).join("=")]}))[e]??null:null}var _=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(),i=Date.now(),r=i+e.ttlSeconds*1e3,o={id:n,session:e.session,createdAt:i,expiresAt:r};return this.records.set(n,o),o}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 i=await this.get(e);return i?(i.subjectId=n,true):false}async revoke(e){this.records.delete(e);}},U=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 Ce(t){let{cookieSource:e,cookieName:n="siwx-session-v2",sessionStore:i,signingSecret:r,policy:o}=t;if(!e)return null;let a=null;if(typeof e=="string")a=e.includes("=")?E(e,n):e;else if(typeof e.headers=="object"&&typeof e.headers?.get=="function"){let s=e.headers.get("cookie");a=E(s,n);}else if(typeof e.get=="function"){let s=e.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 e.get=="function"){let c=e.get("cookie");c&&(a=E(c,n));}}if(!a)return null;if(i){let s=await i.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 r?ie(a,r,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=ie;exports.n=Re;exports.o=Je;exports.p=ve;exports.q=Ie;exports.r=E;exports.s=_;exports.t=U;exports.u=Ce;
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { S as SiwxSession, a as SiwxJwtKey, b as SiwxJwks, c as SiwxPublicJwk, d as SiwxJwtPayload, e as SiwxJwtAlgorithm } from './server-b6Tp6Wea.mjs';
2
- export { C as CookieOptions, G as GetSiwxServerSessionOptions, M as MemorySiwxNonceStore, f as MemorySiwxSessionStore, g as ServerVerifyOptions, h as ServerVerifyResult, i as SiwxJwtOptions, j as SiwxNonceStore, k as SiwxSessionRecord, l as SiwxSessionStore, m as StatelessDemoLimits, n as StatelessDemoTokenPayload, o as createClearCookie, p as createSessionCookie, q as getSiwxServerSession, r as issueStatelessDemoNonce, s as parseCookie, t as signStatelessDemoSession, u as toSession, v as verifySiwxPayload, w as verifyStatelessDemoNonce, x as verifyStatelessDemoSession } from './server-b6Tp6Wea.mjs';
1
+ import { S as SiwxSession, a as SiwxJwtKey, b as SiwxJwks, c as SiwxPublicJwk, d as SiwxJwtPayload, e as SiwxJwtAlgorithm } from './server-DF9N4Mq4.mjs';
2
+ export { C as CookieOptions, G as GetSiwxServerSessionOptions, M as MemorySiwxNonceStore, f as MemorySiwxSessionStore, g as ServerVerifyOptions, h as ServerVerifyResult, i as SiwxJwtOptions, j as SiwxNonceStore, k as SiwxSessionRecord, l as SiwxSessionStore, m as SiwxVerificationMethod, n as StatelessDemoLimits, o as StatelessDemoTokenPayload, p as createClearCookie, q as createSessionCookie, r as getSiwxServerSession, s as issueStatelessDemoNonce, t as parseCookie, u as signStatelessDemoSession, v as toSession, w as verifySiwxPayload, x as verifyStatelessDemoNonce, y as verifyStatelessDemoSession } from './server-DF9N4Mq4.mjs';
3
3
  export { ParsedSiwxMessage, SiwxMessageFields, SiwxSessionLike, SiwxVerificationPolicy, ValidateMessageOptions, generateNonce, generateNonce as generateServerNonce, isSessionMatchingTarget, validateMessage, validatePolicy } from '@tuwaio/siwx-core';
4
4
  import '@tuwaio/siwx-evm';
5
5
 
@@ -10,12 +10,16 @@ import '@tuwaio/siwx-evm';
10
10
  */
11
11
 
12
12
  /**
13
- * Returns the default `sub` of the JWT of a session: a stable ID of the user, so that signing in on another network
14
- * does not look like another user to the service that receives the token.
13
+ * Returns the default `sub` of the JWT of a session: a stable ID of the user for the service that receives the token.
15
14
  *
16
15
  * - `subjectId`, when set and not empty (your own user ID, bound with `SiwxSessionStore.bindSubject`);
17
- * - otherwise the account without its chain reference: `eip155:<address in lowercase>` for EVM,
18
- * `solana:<address>` for Solana (base58 is case-sensitive and kept as is), `<namespace>:<address>` otherwise.
16
+ * - an EVM account that signed with its own key (`verificationMethod` `eip191`): the account without its chain,
17
+ * `eip155:<address in lowercase>`, so signing in on another network is the same user;
18
+ * - an EVM smart contract wallet (`eip1271`, `erc6492`) or an EVM session without `verificationMethod`: the account
19
+ * with its chain, `eip155:<chain>:<address in lowercase>`. A contract wallet is controlled on each chain
20
+ * separately: the same address can have other owners on another network;
21
+ * - a Solana account: `solana:<address>` (base58 is case-sensitive and kept as is) under either form of its chain ID;
22
+ * `<namespace>:<address>` otherwise.
19
23
  *
20
24
  * Pure function.
21
25
  *
@@ -26,7 +30,8 @@ import '@tuwaio/siwx-evm';
26
30
  *
27
31
  * @example
28
32
  * ```ts
29
- * siwxJwtSubject({ ...session, address: 'eip155:8453:0xAbC…' }); // "eip155:0xabc…"
33
+ * siwxJwtSubject({ ...session, address: 'eip155:8453:0xAbC…', verificationMethod: 'eip191' }); // "eip155:0xabc…"
34
+ * siwxJwtSubject({ ...session, address: 'eip155:8453:0xAbC…', verificationMethod: 'eip1271' }); // "eip155:8453:0xabc…"
30
35
  * ```
31
36
  */
32
37
  declare function siwxJwtSubject(session: SiwxSession, subjectId?: string): string;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { S as SiwxSession, a as SiwxJwtKey, b as SiwxJwks, c as SiwxPublicJwk, d as SiwxJwtPayload, e as SiwxJwtAlgorithm } from './server-b6Tp6Wea.js';
2
- export { C as CookieOptions, G as GetSiwxServerSessionOptions, M as MemorySiwxNonceStore, f as MemorySiwxSessionStore, g as ServerVerifyOptions, h as ServerVerifyResult, i as SiwxJwtOptions, j as SiwxNonceStore, k as SiwxSessionRecord, l as SiwxSessionStore, m as StatelessDemoLimits, n as StatelessDemoTokenPayload, o as createClearCookie, p as createSessionCookie, q as getSiwxServerSession, r as issueStatelessDemoNonce, s as parseCookie, t as signStatelessDemoSession, u as toSession, v as verifySiwxPayload, w as verifyStatelessDemoNonce, x as verifyStatelessDemoSession } from './server-b6Tp6Wea.js';
1
+ import { S as SiwxSession, a as SiwxJwtKey, b as SiwxJwks, c as SiwxPublicJwk, d as SiwxJwtPayload, e as SiwxJwtAlgorithm } from './server-DF9N4Mq4.js';
2
+ export { C as CookieOptions, G as GetSiwxServerSessionOptions, M as MemorySiwxNonceStore, f as MemorySiwxSessionStore, g as ServerVerifyOptions, h as ServerVerifyResult, i as SiwxJwtOptions, j as SiwxNonceStore, k as SiwxSessionRecord, l as SiwxSessionStore, m as SiwxVerificationMethod, n as StatelessDemoLimits, o as StatelessDemoTokenPayload, p as createClearCookie, q as createSessionCookie, r as getSiwxServerSession, s as issueStatelessDemoNonce, t as parseCookie, u as signStatelessDemoSession, v as toSession, w as verifySiwxPayload, x as verifyStatelessDemoNonce, y as verifyStatelessDemoSession } from './server-DF9N4Mq4.js';
3
3
  export { ParsedSiwxMessage, SiwxMessageFields, SiwxSessionLike, SiwxVerificationPolicy, ValidateMessageOptions, generateNonce, generateNonce as generateServerNonce, isSessionMatchingTarget, validateMessage, validatePolicy } from '@tuwaio/siwx-core';
4
4
  import '@tuwaio/siwx-evm';
5
5
 
@@ -10,12 +10,16 @@ import '@tuwaio/siwx-evm';
10
10
  */
11
11
 
12
12
  /**
13
- * Returns the default `sub` of the JWT of a session: a stable ID of the user, so that signing in on another network
14
- * does not look like another user to the service that receives the token.
13
+ * Returns the default `sub` of the JWT of a session: a stable ID of the user for the service that receives the token.
15
14
  *
16
15
  * - `subjectId`, when set and not empty (your own user ID, bound with `SiwxSessionStore.bindSubject`);
17
- * - otherwise the account without its chain reference: `eip155:<address in lowercase>` for EVM,
18
- * `solana:<address>` for Solana (base58 is case-sensitive and kept as is), `<namespace>:<address>` otherwise.
16
+ * - an EVM account that signed with its own key (`verificationMethod` `eip191`): the account without its chain,
17
+ * `eip155:<address in lowercase>`, so signing in on another network is the same user;
18
+ * - an EVM smart contract wallet (`eip1271`, `erc6492`) or an EVM session without `verificationMethod`: the account
19
+ * with its chain, `eip155:<chain>:<address in lowercase>`. A contract wallet is controlled on each chain
20
+ * separately: the same address can have other owners on another network;
21
+ * - a Solana account: `solana:<address>` (base58 is case-sensitive and kept as is) under either form of its chain ID;
22
+ * `<namespace>:<address>` otherwise.
19
23
  *
20
24
  * Pure function.
21
25
  *
@@ -26,7 +30,8 @@ import '@tuwaio/siwx-evm';
26
30
  *
27
31
  * @example
28
32
  * ```ts
29
- * siwxJwtSubject({ ...session, address: 'eip155:8453:0xAbC…' }); // "eip155:0xabc…"
33
+ * siwxJwtSubject({ ...session, address: 'eip155:8453:0xAbC…', verificationMethod: 'eip191' }); // "eip155:0xabc…"
34
+ * siwxJwtSubject({ ...session, address: 'eip155:8453:0xAbC…', verificationMethod: 'eip1271' }); // "eip155:8453:0xabc…"
30
35
  * ```
31
36
  */
32
37
  declare function siwxJwtSubject(session: SiwxSession, subjectId?: string): string;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- 'use strict';var chunk455KLGU5_js=require('./chunk-455KLGU5.js'),siwxCore=require('@tuwaio/siwx-core');Object.defineProperty(exports,"MemorySiwxNonceStore",{enumerable:true,get:function(){return chunk455KLGU5_js.t}});Object.defineProperty(exports,"MemorySiwxSessionStore",{enumerable:true,get:function(){return chunk455KLGU5_js.s}});Object.defineProperty(exports,"createClearCookie",{enumerable:true,get:function(){return chunk455KLGU5_js.q}});Object.defineProperty(exports,"createSessionCookie",{enumerable:true,get:function(){return chunk455KLGU5_js.p}});Object.defineProperty(exports,"createSiwxJwks",{enumerable:true,get:function(){return chunk455KLGU5_js.d}});Object.defineProperty(exports,"generateServerNonce",{enumerable:true,get:function(){return chunk455KLGU5_js.j}});Object.defineProperty(exports,"generateSiwxJwtKey",{enumerable:true,get:function(){return chunk455KLGU5_js.b}});Object.defineProperty(exports,"getSiwxServerSession",{enumerable:true,get:function(){return chunk455KLGU5_js.u}});Object.defineProperty(exports,"importSiwxJwtKey",{enumerable:true,get:function(){return chunk455KLGU5_js.c}});Object.defineProperty(exports,"issueStatelessDemoNonce",{enumerable:true,get:function(){return chunk455KLGU5_js.n}});Object.defineProperty(exports,"parseCookie",{enumerable:true,get:function(){return chunk455KLGU5_js.r}});Object.defineProperty(exports,"signSiwxJwt",{enumerable:true,get:function(){return chunk455KLGU5_js.f}});Object.defineProperty(exports,"signStatelessDemoSession",{enumerable:true,get:function(){return chunk455KLGU5_js.l}});Object.defineProperty(exports,"siwxJwkThumbprint",{enumerable:true,get:function(){return chunk455KLGU5_js.a}});Object.defineProperty(exports,"siwxJwtSubject",{enumerable:true,get:function(){return chunk455KLGU5_js.e}});Object.defineProperty(exports,"toSession",{enumerable:true,get:function(){return chunk455KLGU5_js.i}});Object.defineProperty(exports,"verifySiwxJwt",{enumerable:true,get:function(){return chunk455KLGU5_js.g}});Object.defineProperty(exports,"verifySiwxPayload",{enumerable:true,get:function(){return chunk455KLGU5_js.k}});Object.defineProperty(exports,"verifyStatelessDemoNonce",{enumerable:true,get:function(){return chunk455KLGU5_js.o}});Object.defineProperty(exports,"verifyStatelessDemoSession",{enumerable:true,get:function(){return chunk455KLGU5_js.m}});Object.defineProperty(exports,"generateNonce",{enumerable:true,get:function(){return siwxCore.generateNonce}});Object.defineProperty(exports,"isSessionMatchingTarget",{enumerable:true,get:function(){return siwxCore.isSessionMatchingTarget}});Object.defineProperty(exports,"validateMessage",{enumerable:true,get:function(){return siwxCore.validateMessage}});Object.defineProperty(exports,"validatePolicy",{enumerable:true,get:function(){return siwxCore.validatePolicy}});
1
+ 'use strict';var chunkR2ZJU7OD_js=require('./chunk-R2ZJU7OD.js'),siwxCore=require('@tuwaio/siwx-core');Object.defineProperty(exports,"MemorySiwxNonceStore",{enumerable:true,get:function(){return chunkR2ZJU7OD_js.t}});Object.defineProperty(exports,"MemorySiwxSessionStore",{enumerable:true,get:function(){return chunkR2ZJU7OD_js.s}});Object.defineProperty(exports,"createClearCookie",{enumerable:true,get:function(){return chunkR2ZJU7OD_js.q}});Object.defineProperty(exports,"createSessionCookie",{enumerable:true,get:function(){return chunkR2ZJU7OD_js.p}});Object.defineProperty(exports,"createSiwxJwks",{enumerable:true,get:function(){return chunkR2ZJU7OD_js.d}});Object.defineProperty(exports,"generateServerNonce",{enumerable:true,get:function(){return chunkR2ZJU7OD_js.j}});Object.defineProperty(exports,"generateSiwxJwtKey",{enumerable:true,get:function(){return chunkR2ZJU7OD_js.b}});Object.defineProperty(exports,"getSiwxServerSession",{enumerable:true,get:function(){return chunkR2ZJU7OD_js.u}});Object.defineProperty(exports,"importSiwxJwtKey",{enumerable:true,get:function(){return chunkR2ZJU7OD_js.c}});Object.defineProperty(exports,"issueStatelessDemoNonce",{enumerable:true,get:function(){return chunkR2ZJU7OD_js.n}});Object.defineProperty(exports,"parseCookie",{enumerable:true,get:function(){return chunkR2ZJU7OD_js.r}});Object.defineProperty(exports,"signSiwxJwt",{enumerable:true,get:function(){return chunkR2ZJU7OD_js.f}});Object.defineProperty(exports,"signStatelessDemoSession",{enumerable:true,get:function(){return chunkR2ZJU7OD_js.l}});Object.defineProperty(exports,"siwxJwkThumbprint",{enumerable:true,get:function(){return chunkR2ZJU7OD_js.a}});Object.defineProperty(exports,"siwxJwtSubject",{enumerable:true,get:function(){return chunkR2ZJU7OD_js.e}});Object.defineProperty(exports,"toSession",{enumerable:true,get:function(){return chunkR2ZJU7OD_js.i}});Object.defineProperty(exports,"verifySiwxJwt",{enumerable:true,get:function(){return chunkR2ZJU7OD_js.g}});Object.defineProperty(exports,"verifySiwxPayload",{enumerable:true,get:function(){return chunkR2ZJU7OD_js.k}});Object.defineProperty(exports,"verifyStatelessDemoNonce",{enumerable:true,get:function(){return chunkR2ZJU7OD_js.o}});Object.defineProperty(exports,"verifyStatelessDemoSession",{enumerable:true,get:function(){return chunkR2ZJU7OD_js.m}});Object.defineProperty(exports,"generateNonce",{enumerable:true,get:function(){return siwxCore.generateNonce}});Object.defineProperty(exports,"isSessionMatchingTarget",{enumerable:true,get:function(){return siwxCore.isSessionMatchingTarget}});Object.defineProperty(exports,"validateMessage",{enumerable:true,get:function(){return siwxCore.validateMessage}});Object.defineProperty(exports,"validatePolicy",{enumerable:true,get:function(){return siwxCore.validatePolicy}});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- export{t as MemorySiwxNonceStore,s as MemorySiwxSessionStore,q as createClearCookie,p as createSessionCookie,d as createSiwxJwks,j as generateServerNonce,b as generateSiwxJwtKey,u as getSiwxServerSession,c as importSiwxJwtKey,n as issueStatelessDemoNonce,r as parseCookie,f as signSiwxJwt,l as signStatelessDemoSession,a as siwxJwkThumbprint,e as siwxJwtSubject,i as toSession,g as verifySiwxJwt,k as verifySiwxPayload,o as verifyStatelessDemoNonce,m as verifyStatelessDemoSession}from'./chunk-PZHK7SYL.mjs';export{generateNonce,isSessionMatchingTarget,validateMessage,validatePolicy}from'@tuwaio/siwx-core';
1
+ export{t as MemorySiwxNonceStore,s as MemorySiwxSessionStore,q as createClearCookie,p as createSessionCookie,d as createSiwxJwks,j as generateServerNonce,b as generateSiwxJwtKey,u as getSiwxServerSession,c as importSiwxJwtKey,n as issueStatelessDemoNonce,r as parseCookie,f as signSiwxJwt,l as signStatelessDemoSession,a as siwxJwkThumbprint,e as siwxJwtSubject,i as toSession,g as verifySiwxJwt,k as verifySiwxPayload,o as verifyStatelessDemoNonce,m as verifyStatelessDemoSession}from'./chunk-LAMZ44ZN.mjs';export{generateNonce,isSessionMatchingTarget,validateMessage,validatePolicy}from'@tuwaio/siwx-core';
package/dist/next.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { SiwxVerificationPolicy } from '@tuwaio/siwx-core';
2
- import { l as SiwxSessionStore, j as SiwxNonceStore, C as CookieOptions, g as ServerVerifyOptions, i as SiwxJwtOptions, m as StatelessDemoLimits } from './server-b6Tp6Wea.mjs';
3
- export { G as GetSiwxServerSessionOptions, q as getSiwxServerSession } from './server-b6Tp6Wea.mjs';
2
+ import { l as SiwxSessionStore, j as SiwxNonceStore, C as CookieOptions, g as ServerVerifyOptions, i as SiwxJwtOptions, n as StatelessDemoLimits } from './server-DF9N4Mq4.mjs';
3
+ export { G as GetSiwxServerSessionOptions, r as getSiwxServerSession } from './server-DF9N4Mq4.mjs';
4
4
  import '@tuwaio/siwx-evm';
5
5
 
6
6
  /**
package/dist/next.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { SiwxVerificationPolicy } from '@tuwaio/siwx-core';
2
- import { l as SiwxSessionStore, j as SiwxNonceStore, C as CookieOptions, g as ServerVerifyOptions, i as SiwxJwtOptions, m as StatelessDemoLimits } from './server-b6Tp6Wea.js';
3
- export { G as GetSiwxServerSessionOptions, q as getSiwxServerSession } from './server-b6Tp6Wea.js';
2
+ import { l as SiwxSessionStore, j as SiwxNonceStore, C as CookieOptions, g as ServerVerifyOptions, i as SiwxJwtOptions, n as StatelessDemoLimits } from './server-DF9N4Mq4.js';
3
+ export { G as GetSiwxServerSessionOptions, r as getSiwxServerSession } from './server-DF9N4Mq4.js';
4
4
  import '@tuwaio/siwx-evm';
5
5
 
6
6
  /**
package/dist/next.js CHANGED
@@ -1 +1 @@
1
- 'use strict';var chunk455KLGU5_js=require('./chunk-455KLGU5.js'),siwxCore=require('@tuwaio/siwx-core');var x=300;function B(e){if(!e?.sessionStore||!e?.nonceStore)throw new Error("[SIWX-SERVER] createSiwxApiHandler requires both `sessionStore` and `nonceStore`.");let c=e.cookieOptions?.name||"siwx-session-v2",u=e.ttlSeconds??(e.cookieOptions?.maxAge||3600*24*7),y=65536,n=e.jwt;n&&chunk455KLGU5_js.h(n.issuer,n.ttlSeconds??600);let g=async o=>{try{let p=new URL(o.url).pathname.split("/").filter(Boolean),a=p[p.length-1]||"";if(o.method==="GET"&&a==="session"){let t=chunk455KLGU5_js.r(o.headers.get("cookie"),c);if(!t)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let s=await e.sessionStore.get(t);return new Response(JSON.stringify(s?.session??null),{status:200,headers:{"Content-Type":"application/json"}})}if((o.method==="GET"||o.method==="POST")&&a==="nonce"){let t=siwxCore.generateNonce();return await e.nonceStore.issue({nonce:t,ttlSeconds:x}),new Response(JSON.stringify({nonce:t}),{status:200,headers:{"Content-Type":"application/json"}})}if(o.method==="POST"&&a==="verify"){let t=o.headers.get("content-length");if(t&&parseInt(t,10)>y)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let s=await o.text();if(s.length>y)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let i;try{i=JSON.parse(s);}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 l={message:i.message,signature:i.signature},S=await chunk455KLGU5_js.k(l,{...e.verifyOptions,policy:e.policy});if(!S.success||!S.data)return new Response(JSON.stringify({error:S.error||"Verification failed"}),{status:401,headers:{"Content-Type":"application/json"}});if(!await e.nonceStore.consume({nonce:S.data.nonce}))return new Response(JSON.stringify({error:"Nonce replay detected or nonce expired"}),{status:401,headers:{"Content-Type":"application/json"}});let m=chunk455KLGU5_js.i(S.data),f=await e.sessionStore.create({session:m,ttlSeconds:u}),h=chunk455KLGU5_js.p(f.id,{...e.cookieOptions,name:c,maxAge:u});return new Response(JSON.stringify(m),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":h}})}if(n&&o.method==="GET"&&a==="token"){let t=chunk455KLGU5_js.r(o.headers.get("cookie"),c),s=t?await e.sessionStore.get(t):null;if(!s)return new Response(JSON.stringify({error:"Not signed in"}),{status:401,headers:{"Content-Type":"application/json","Cache-Control":"no-store"}});try{let i=await chunk455KLGU5_js.f({session:s.session,key:await n.signingKey,issuer:n.issuer,audience:n.audience,ttlSeconds:n.ttlSeconds,subject:n.subject?await n.subject(s):chunk455KLGU5_js.e(s.session,s.subjectId),claims:n.claims?await n.claims(s):void 0,notAfter:s.expiresAt});return new Response(JSON.stringify(i),{status:200,headers:{"Content-Type":"application/json","Cache-Control":"no-store"}})}catch(i){if(!(i instanceof RangeError))throw i;return new Response(JSON.stringify({error:"Session expired"}),{status:401,headers:{"Content-Type":"application/json","Cache-Control":"no-store"}})}}if(n&&o.method==="GET"&&a==="jwks"){let t=chunk455KLGU5_js.d([await n.signingKey,...n.previousKeys??[]]);return new Response(JSON.stringify(t),{status:200,headers:{"Content-Type":"application/json","Cache-Control":"public, max-age=300"}})}if(o.method==="DELETE"&&a==="session"||o.method==="POST"&&a==="logout"){let t=chunk455KLGU5_js.r(o.headers.get("cookie"),c);return t&&await e.sessionStore.revoke(t),new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":chunk455KLGU5_js.q({...e.cookieOptions,name:c})}})}return new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(r){return console.error("[SIWX-SERVER] Durable Handler error:",r),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:g,POST:g,DELETE:g}}function W(e){if(!e?.signingSecret||e.signingSecret.length<32)throw new Error("[SIWX-SERVER] createStatelessDemoSiwxHandler requires a `signingSecret` of at least 32 characters.");let c=e.cookieOptions?.name||"siwx-session-v2",u=e.ttlSeconds??(e.cookieOptions?.maxAge||1800),y=e.demoLimits?.maxTransactionPayloadBytes??65536,n=new Map,g=r=>{let p=Date.now();for(let[a,t]of n)t<p&&n.delete(a);return n.has(r)?false:(n.set(r,p+x*1e3),true)},o=async r=>{try{let a=new URL(r.url).pathname.split("/").filter(Boolean),t=a[a.length-1]||"";if(r.method==="GET"&&t==="session"){let s=chunk455KLGU5_js.r(r.headers.get("cookie"),c);if(!s)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let i=await chunk455KLGU5_js.m(s,e.signingSecret,e.policy);return new Response(JSON.stringify(i),{status:200,headers:{"Content-Type":"application/json"}})}if((r.method==="GET"||r.method==="POST")&&t==="nonce"){let s=await chunk455KLGU5_js.n(e.signingSecret,x);return new Response(JSON.stringify({nonce:s}),{status:200,headers:{"Content-Type":"application/json"}})}if(r.method==="POST"&&t==="verify"){let s=r.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 i=await r.text();if(i.length>y)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let l;try{l=JSON.parse(i);}catch{return new Response(JSON.stringify({error:"Invalid JSON payload"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!l||typeof l.message!="string"||typeof l.signature!="string")return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let S={message:l.message,signature:l.signature},d=await chunk455KLGU5_js.k(S,{...e.verifyOptions,policy:e.policy});if(!d.success||!d.data)return new Response(JSON.stringify({error:d.error||"Verification failed"}),{status:401,headers:{"Content-Type":"application/json"}});if(!await chunk455KLGU5_js.o(d.data.nonce,e.signingSecret)||!g(d.data.nonce))return new Response(JSON.stringify({error:"Nonce replay detected or nonce expired"}),{status:401,headers:{"Content-Type":"application/json"}});let f=chunk455KLGU5_js.i(d.data),h=await chunk455KLGU5_js.l(f,e.signingSecret,u),L=chunk455KLGU5_js.p(h,{...e.cookieOptions,name:c,maxAge:u});return new Response(JSON.stringify(f),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":L}})}return r.method==="DELETE"&&t==="session"||r.method==="POST"&&t==="logout"?new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":chunk455KLGU5_js.q({...e.cookieOptions,name:c})}}):new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(p){return console.error("[SIWX-SERVER] Stateless Demo Handler error:",p),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:o,POST:o,DELETE:o}}Object.defineProperty(exports,"getSiwxServerSession",{enumerable:true,get:function(){return chunk455KLGU5_js.u}});exports.createSiwxApiHandler=B;exports.createStatelessDemoSiwxHandler=W;
1
+ 'use strict';var chunkR2ZJU7OD_js=require('./chunk-R2ZJU7OD.js'),siwxCore=require('@tuwaio/siwx-core');var x=300;function B(e){if(!e?.sessionStore||!e?.nonceStore)throw new Error("[SIWX-SERVER] createSiwxApiHandler requires both `sessionStore` and `nonceStore`.");let c=e.cookieOptions?.name||"siwx-session-v2",u=e.ttlSeconds??(e.cookieOptions?.maxAge||3600*24*7),y=65536,n=e.jwt;n&&chunkR2ZJU7OD_js.h(n.issuer,n.ttlSeconds??600);let g=async o=>{try{let p=new URL(o.url).pathname.split("/").filter(Boolean),a=p[p.length-1]||"";if(o.method==="GET"&&a==="session"){let t=chunkR2ZJU7OD_js.r(o.headers.get("cookie"),c);if(!t)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let s=await e.sessionStore.get(t);return new Response(JSON.stringify(s?.session??null),{status:200,headers:{"Content-Type":"application/json"}})}if((o.method==="GET"||o.method==="POST")&&a==="nonce"){let t=siwxCore.generateNonce();return await e.nonceStore.issue({nonce:t,ttlSeconds:x}),new Response(JSON.stringify({nonce:t}),{status:200,headers:{"Content-Type":"application/json"}})}if(o.method==="POST"&&a==="verify"){let t=o.headers.get("content-length");if(t&&parseInt(t,10)>y)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let s=await o.text();if(s.length>y)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let i;try{i=JSON.parse(s);}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 l={message:i.message,signature:i.signature},S=await chunkR2ZJU7OD_js.k(l,{...e.verifyOptions,policy:e.policy});if(!S.success||!S.data)return new Response(JSON.stringify({error:S.error||"Verification failed"}),{status:401,headers:{"Content-Type":"application/json"}});if(!await e.nonceStore.consume({nonce:S.data.nonce}))return new Response(JSON.stringify({error:"Nonce replay detected or nonce expired"}),{status:401,headers:{"Content-Type":"application/json"}});let m=chunkR2ZJU7OD_js.i(S.data,S.method),f=await e.sessionStore.create({session:m,ttlSeconds:u}),h=chunkR2ZJU7OD_js.p(f.id,{...e.cookieOptions,name:c,maxAge:u});return new Response(JSON.stringify(m),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":h}})}if(n&&o.method==="GET"&&a==="token"){let t=chunkR2ZJU7OD_js.r(o.headers.get("cookie"),c),s=t?await e.sessionStore.get(t):null;if(!s)return new Response(JSON.stringify({error:"Not signed in"}),{status:401,headers:{"Content-Type":"application/json","Cache-Control":"no-store"}});try{let i=await chunkR2ZJU7OD_js.f({session:s.session,key:await n.signingKey,issuer:n.issuer,audience:n.audience,ttlSeconds:n.ttlSeconds,subject:n.subject?await n.subject(s):chunkR2ZJU7OD_js.e(s.session,s.subjectId),claims:n.claims?await n.claims(s):void 0,notAfter:s.expiresAt});return new Response(JSON.stringify(i),{status:200,headers:{"Content-Type":"application/json","Cache-Control":"no-store"}})}catch(i){if(!(i instanceof RangeError))throw i;return new Response(JSON.stringify({error:"Session expired"}),{status:401,headers:{"Content-Type":"application/json","Cache-Control":"no-store"}})}}if(n&&o.method==="GET"&&a==="jwks"){let t=chunkR2ZJU7OD_js.d([await n.signingKey,...n.previousKeys??[]]);return new Response(JSON.stringify(t),{status:200,headers:{"Content-Type":"application/json","Cache-Control":"public, max-age=300"}})}if(o.method==="DELETE"&&a==="session"||o.method==="POST"&&a==="logout"){let t=chunkR2ZJU7OD_js.r(o.headers.get("cookie"),c);return t&&await e.sessionStore.revoke(t),new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":chunkR2ZJU7OD_js.q({...e.cookieOptions,name:c})}})}return new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(r){return console.error("[SIWX-SERVER] Durable Handler error:",r),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:g,POST:g,DELETE:g}}function W(e){if(!e?.signingSecret||e.signingSecret.length<32)throw new Error("[SIWX-SERVER] createStatelessDemoSiwxHandler requires a `signingSecret` of at least 32 characters.");let c=e.cookieOptions?.name||"siwx-session-v2",u=e.ttlSeconds??(e.cookieOptions?.maxAge||1800),y=e.demoLimits?.maxTransactionPayloadBytes??65536,n=new Map,g=r=>{let p=Date.now();for(let[a,t]of n)t<p&&n.delete(a);return n.has(r)?false:(n.set(r,p+x*1e3),true)},o=async r=>{try{let a=new URL(r.url).pathname.split("/").filter(Boolean),t=a[a.length-1]||"";if(r.method==="GET"&&t==="session"){let s=chunkR2ZJU7OD_js.r(r.headers.get("cookie"),c);if(!s)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let i=await chunkR2ZJU7OD_js.m(s,e.signingSecret,e.policy);return new Response(JSON.stringify(i),{status:200,headers:{"Content-Type":"application/json"}})}if((r.method==="GET"||r.method==="POST")&&t==="nonce"){let s=await chunkR2ZJU7OD_js.n(e.signingSecret,x);return new Response(JSON.stringify({nonce:s}),{status:200,headers:{"Content-Type":"application/json"}})}if(r.method==="POST"&&t==="verify"){let s=r.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 i=await r.text();if(i.length>y)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let l;try{l=JSON.parse(i);}catch{return new Response(JSON.stringify({error:"Invalid JSON payload"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!l||typeof l.message!="string"||typeof l.signature!="string")return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let S={message:l.message,signature:l.signature},d=await chunkR2ZJU7OD_js.k(S,{...e.verifyOptions,policy:e.policy});if(!d.success||!d.data)return new Response(JSON.stringify({error:d.error||"Verification failed"}),{status:401,headers:{"Content-Type":"application/json"}});if(!await chunkR2ZJU7OD_js.o(d.data.nonce,e.signingSecret)||!g(d.data.nonce))return new Response(JSON.stringify({error:"Nonce replay detected or nonce expired"}),{status:401,headers:{"Content-Type":"application/json"}});let f=chunkR2ZJU7OD_js.i(d.data),h=await chunkR2ZJU7OD_js.l(f,e.signingSecret,u),L=chunkR2ZJU7OD_js.p(h,{...e.cookieOptions,name:c,maxAge:u});return new Response(JSON.stringify(f),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":L}})}return r.method==="DELETE"&&t==="session"||r.method==="POST"&&t==="logout"?new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":chunkR2ZJU7OD_js.q({...e.cookieOptions,name:c})}}):new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(p){return console.error("[SIWX-SERVER] Stateless Demo Handler error:",p),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:o,POST:o,DELETE:o}}Object.defineProperty(exports,"getSiwxServerSession",{enumerable:true,get:function(){return chunkR2ZJU7OD_js.u}});exports.createSiwxApiHandler=B;exports.createStatelessDemoSiwxHandler=W;
package/dist/next.mjs CHANGED
@@ -1 +1 @@
1
- import {h,r,k,i,p,f,e,d,q,m,n,o,l}from'./chunk-PZHK7SYL.mjs';export{u as getSiwxServerSession}from'./chunk-PZHK7SYL.mjs';import {generateNonce}from'@tuwaio/siwx-core';var x=300;function B(e$1){if(!e$1?.sessionStore||!e$1?.nonceStore)throw new Error("[SIWX-SERVER] createSiwxApiHandler requires both `sessionStore` and `nonceStore`.");let c=e$1.cookieOptions?.name||"siwx-session-v2",u=e$1.ttlSeconds??(e$1.cookieOptions?.maxAge||3600*24*7),y=65536,n=e$1.jwt;n&&h(n.issuer,n.ttlSeconds??600);let g=async o=>{try{let p$1=new URL(o.url).pathname.split("/").filter(Boolean),a=p$1[p$1.length-1]||"";if(o.method==="GET"&&a==="session"){let t=r(o.headers.get("cookie"),c);if(!t)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let s=await e$1.sessionStore.get(t);return new Response(JSON.stringify(s?.session??null),{status:200,headers:{"Content-Type":"application/json"}})}if((o.method==="GET"||o.method==="POST")&&a==="nonce"){let t=generateNonce();return await e$1.nonceStore.issue({nonce:t,ttlSeconds:x}),new Response(JSON.stringify({nonce:t}),{status:200,headers:{"Content-Type":"application/json"}})}if(o.method==="POST"&&a==="verify"){let t=o.headers.get("content-length");if(t&&parseInt(t,10)>y)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let s=await o.text();if(s.length>y)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let i$1;try{i$1=JSON.parse(s);}catch{return new Response(JSON.stringify({error:"Invalid JSON payload"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!i$1||typeof i$1.message!="string"||typeof i$1.signature!="string")return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let l={message:i$1.message,signature:i$1.signature},S=await k(l,{...e$1.verifyOptions,policy:e$1.policy});if(!S.success||!S.data)return new Response(JSON.stringify({error:S.error||"Verification failed"}),{status:401,headers:{"Content-Type":"application/json"}});if(!await e$1.nonceStore.consume({nonce:S.data.nonce}))return new Response(JSON.stringify({error:"Nonce replay detected or nonce expired"}),{status:401,headers:{"Content-Type":"application/json"}});let m=i(S.data),f=await e$1.sessionStore.create({session:m,ttlSeconds:u}),h=p(f.id,{...e$1.cookieOptions,name:c,maxAge:u});return new Response(JSON.stringify(m),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":h}})}if(n&&o.method==="GET"&&a==="token"){let t=r(o.headers.get("cookie"),c),s=t?await e$1.sessionStore.get(t):null;if(!s)return new Response(JSON.stringify({error:"Not signed in"}),{status:401,headers:{"Content-Type":"application/json","Cache-Control":"no-store"}});try{let i=await f({session:s.session,key:await n.signingKey,issuer:n.issuer,audience:n.audience,ttlSeconds:n.ttlSeconds,subject:n.subject?await n.subject(s):e(s.session,s.subjectId),claims:n.claims?await n.claims(s):void 0,notAfter:s.expiresAt});return new Response(JSON.stringify(i),{status:200,headers:{"Content-Type":"application/json","Cache-Control":"no-store"}})}catch(i){if(!(i instanceof RangeError))throw i;return new Response(JSON.stringify({error:"Session expired"}),{status:401,headers:{"Content-Type":"application/json","Cache-Control":"no-store"}})}}if(n&&o.method==="GET"&&a==="jwks"){let t=d([await n.signingKey,...n.previousKeys??[]]);return new Response(JSON.stringify(t),{status:200,headers:{"Content-Type":"application/json","Cache-Control":"public, max-age=300"}})}if(o.method==="DELETE"&&a==="session"||o.method==="POST"&&a==="logout"){let t=r(o.headers.get("cookie"),c);return t&&await e$1.sessionStore.revoke(t),new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":q({...e$1.cookieOptions,name:c})}})}return new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(r){return console.error("[SIWX-SERVER] Durable Handler error:",r),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:g,POST:g,DELETE:g}}function W(e){if(!e?.signingSecret||e.signingSecret.length<32)throw new Error("[SIWX-SERVER] createStatelessDemoSiwxHandler requires a `signingSecret` of at least 32 characters.");let c=e.cookieOptions?.name||"siwx-session-v2",u=e.ttlSeconds??(e.cookieOptions?.maxAge||1800),y=e.demoLimits?.maxTransactionPayloadBytes??65536,n$1=new Map,g=r=>{let p=Date.now();for(let[a,t]of n$1)t<p&&n$1.delete(a);return n$1.has(r)?false:(n$1.set(r,p+x*1e3),true)},o$1=async r$1=>{try{let a=new URL(r$1.url).pathname.split("/").filter(Boolean),t=a[a.length-1]||"";if(r$1.method==="GET"&&t==="session"){let s=r(r$1.headers.get("cookie"),c);if(!s)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let i=await m(s,e.signingSecret,e.policy);return new Response(JSON.stringify(i),{status:200,headers:{"Content-Type":"application/json"}})}if((r$1.method==="GET"||r$1.method==="POST")&&t==="nonce"){let s=await n(e.signingSecret,x);return new Response(JSON.stringify({nonce:s}),{status:200,headers:{"Content-Type":"application/json"}})}if(r$1.method==="POST"&&t==="verify"){let s=r$1.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 i$1=await r$1.text();if(i$1.length>y)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let l$1;try{l$1=JSON.parse(i$1);}catch{return new Response(JSON.stringify({error:"Invalid JSON payload"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!l$1||typeof l$1.message!="string"||typeof l$1.signature!="string")return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let S={message:l$1.message,signature:l$1.signature},d=await k(S,{...e.verifyOptions,policy:e.policy});if(!d.success||!d.data)return new Response(JSON.stringify({error:d.error||"Verification failed"}),{status:401,headers:{"Content-Type":"application/json"}});if(!await o(d.data.nonce,e.signingSecret)||!g(d.data.nonce))return new Response(JSON.stringify({error:"Nonce replay detected or nonce expired"}),{status:401,headers:{"Content-Type":"application/json"}});let f=i(d.data),h=await l(f,e.signingSecret,u),L=p(h,{...e.cookieOptions,name:c,maxAge:u});return new Response(JSON.stringify(f),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":L}})}return r$1.method==="DELETE"&&t==="session"||r$1.method==="POST"&&t==="logout"?new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":q({...e.cookieOptions,name:c})}}):new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(p){return console.error("[SIWX-SERVER] Stateless Demo Handler error:",p),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:o$1,POST:o$1,DELETE:o$1}}export{B as createSiwxApiHandler,W as createStatelessDemoSiwxHandler};
1
+ import {h,r,k,i,p,f,e,d,q,m,n,o,l}from'./chunk-LAMZ44ZN.mjs';export{u as getSiwxServerSession}from'./chunk-LAMZ44ZN.mjs';import {generateNonce}from'@tuwaio/siwx-core';var x=300;function B(e$1){if(!e$1?.sessionStore||!e$1?.nonceStore)throw new Error("[SIWX-SERVER] createSiwxApiHandler requires both `sessionStore` and `nonceStore`.");let c=e$1.cookieOptions?.name||"siwx-session-v2",u=e$1.ttlSeconds??(e$1.cookieOptions?.maxAge||3600*24*7),y=65536,n=e$1.jwt;n&&h(n.issuer,n.ttlSeconds??600);let g=async o=>{try{let p$1=new URL(o.url).pathname.split("/").filter(Boolean),a=p$1[p$1.length-1]||"";if(o.method==="GET"&&a==="session"){let t=r(o.headers.get("cookie"),c);if(!t)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let s=await e$1.sessionStore.get(t);return new Response(JSON.stringify(s?.session??null),{status:200,headers:{"Content-Type":"application/json"}})}if((o.method==="GET"||o.method==="POST")&&a==="nonce"){let t=generateNonce();return await e$1.nonceStore.issue({nonce:t,ttlSeconds:x}),new Response(JSON.stringify({nonce:t}),{status:200,headers:{"Content-Type":"application/json"}})}if(o.method==="POST"&&a==="verify"){let t=o.headers.get("content-length");if(t&&parseInt(t,10)>y)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let s=await o.text();if(s.length>y)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let i$1;try{i$1=JSON.parse(s);}catch{return new Response(JSON.stringify({error:"Invalid JSON payload"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!i$1||typeof i$1.message!="string"||typeof i$1.signature!="string")return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let l={message:i$1.message,signature:i$1.signature},S=await k(l,{...e$1.verifyOptions,policy:e$1.policy});if(!S.success||!S.data)return new Response(JSON.stringify({error:S.error||"Verification failed"}),{status:401,headers:{"Content-Type":"application/json"}});if(!await e$1.nonceStore.consume({nonce:S.data.nonce}))return new Response(JSON.stringify({error:"Nonce replay detected or nonce expired"}),{status:401,headers:{"Content-Type":"application/json"}});let m=i(S.data,S.method),f=await e$1.sessionStore.create({session:m,ttlSeconds:u}),h=p(f.id,{...e$1.cookieOptions,name:c,maxAge:u});return new Response(JSON.stringify(m),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":h}})}if(n&&o.method==="GET"&&a==="token"){let t=r(o.headers.get("cookie"),c),s=t?await e$1.sessionStore.get(t):null;if(!s)return new Response(JSON.stringify({error:"Not signed in"}),{status:401,headers:{"Content-Type":"application/json","Cache-Control":"no-store"}});try{let i=await f({session:s.session,key:await n.signingKey,issuer:n.issuer,audience:n.audience,ttlSeconds:n.ttlSeconds,subject:n.subject?await n.subject(s):e(s.session,s.subjectId),claims:n.claims?await n.claims(s):void 0,notAfter:s.expiresAt});return new Response(JSON.stringify(i),{status:200,headers:{"Content-Type":"application/json","Cache-Control":"no-store"}})}catch(i){if(!(i instanceof RangeError))throw i;return new Response(JSON.stringify({error:"Session expired"}),{status:401,headers:{"Content-Type":"application/json","Cache-Control":"no-store"}})}}if(n&&o.method==="GET"&&a==="jwks"){let t=d([await n.signingKey,...n.previousKeys??[]]);return new Response(JSON.stringify(t),{status:200,headers:{"Content-Type":"application/json","Cache-Control":"public, max-age=300"}})}if(o.method==="DELETE"&&a==="session"||o.method==="POST"&&a==="logout"){let t=r(o.headers.get("cookie"),c);return t&&await e$1.sessionStore.revoke(t),new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":q({...e$1.cookieOptions,name:c})}})}return new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(r){return console.error("[SIWX-SERVER] Durable Handler error:",r),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:g,POST:g,DELETE:g}}function W(e){if(!e?.signingSecret||e.signingSecret.length<32)throw new Error("[SIWX-SERVER] createStatelessDemoSiwxHandler requires a `signingSecret` of at least 32 characters.");let c=e.cookieOptions?.name||"siwx-session-v2",u=e.ttlSeconds??(e.cookieOptions?.maxAge||1800),y=e.demoLimits?.maxTransactionPayloadBytes??65536,n$1=new Map,g=r=>{let p=Date.now();for(let[a,t]of n$1)t<p&&n$1.delete(a);return n$1.has(r)?false:(n$1.set(r,p+x*1e3),true)},o$1=async r$1=>{try{let a=new URL(r$1.url).pathname.split("/").filter(Boolean),t=a[a.length-1]||"";if(r$1.method==="GET"&&t==="session"){let s=r(r$1.headers.get("cookie"),c);if(!s)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let i=await m(s,e.signingSecret,e.policy);return new Response(JSON.stringify(i),{status:200,headers:{"Content-Type":"application/json"}})}if((r$1.method==="GET"||r$1.method==="POST")&&t==="nonce"){let s=await n(e.signingSecret,x);return new Response(JSON.stringify({nonce:s}),{status:200,headers:{"Content-Type":"application/json"}})}if(r$1.method==="POST"&&t==="verify"){let s=r$1.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 i$1=await r$1.text();if(i$1.length>y)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let l$1;try{l$1=JSON.parse(i$1);}catch{return new Response(JSON.stringify({error:"Invalid JSON payload"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!l$1||typeof l$1.message!="string"||typeof l$1.signature!="string")return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let S={message:l$1.message,signature:l$1.signature},d=await k(S,{...e.verifyOptions,policy:e.policy});if(!d.success||!d.data)return new Response(JSON.stringify({error:d.error||"Verification failed"}),{status:401,headers:{"Content-Type":"application/json"}});if(!await o(d.data.nonce,e.signingSecret)||!g(d.data.nonce))return new Response(JSON.stringify({error:"Nonce replay detected or nonce expired"}),{status:401,headers:{"Content-Type":"application/json"}});let f=i(d.data),h=await l(f,e.signingSecret,u),L=p(h,{...e.cookieOptions,name:c,maxAge:u});return new Response(JSON.stringify(f),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":L}})}return r$1.method==="DELETE"&&t==="session"||r$1.method==="POST"&&t==="logout"?new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":q({...e.cookieOptions,name:c})}}):new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(p){return console.error("[SIWX-SERVER] Stateless Demo Handler error:",p),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:o$1,POST:o$1,DELETE:o$1}}export{B as createSiwxApiHandler,W as createStatelessDemoSiwxHandler};
@@ -34,6 +34,18 @@ interface ServerVerifyOptions {
34
34
  */
35
35
  publicClient?: EvmPublicClientSource;
36
36
  }
37
+ /**
38
+ * How a signature was verified:
39
+ *
40
+ * - `eip191`: by the key of an EVM account, which controls the address on every chain;
41
+ * - `eip1271`: by a deployed EVM smart contract wallet, on the chain it signed on;
42
+ * - `erc6492`: by an EVM smart contract wallet that is not deployed yet, on the chain it signed on;
43
+ * - `ed25519`: by the key of a Solana account.
44
+ *
45
+ * A smart contract wallet is controlled on each chain separately: the same address can have other owners on another
46
+ * network.
47
+ */
48
+ type SiwxVerificationMethod = 'eip191' | 'eip1271' | 'erc6492' | 'ed25519';
37
49
  /**
38
50
  * Result of {@link verifySiwxPayload}.
39
51
  */
@@ -43,6 +55,8 @@ interface ServerVerifyResult extends SiwxVerifyResult {
43
55
  * failed before the signature check.
44
56
  */
45
57
  namespace?: 'eip155' | 'solana';
58
+ /** How the signature was verified. Present only when `success` is `true`; pass it to {@link toSession}. */
59
+ method?: SiwxVerificationMethod;
46
60
  }
47
61
  /**
48
62
  * Serializable session derived from a verified CAIP-122 message (see {@link toSession}). Returned as JSON by the
@@ -61,6 +75,12 @@ interface SiwxSession {
61
75
  issuedAt: string;
62
76
  /** ISO 8601 timestamp when the session expires, if set. */
63
77
  expirationTime?: string;
78
+ /**
79
+ * How the signature was verified (see {@link SiwxVerificationMethod}). Set by `createSiwxApiHandler`; in your own
80
+ * handlers, pass `result.method` of {@link verifySiwxPayload} to {@link toSession}. {@link siwxJwtSubject} reads
81
+ * it: without it, the subject of an EVM session keeps its chain.
82
+ */
83
+ verificationMethod?: SiwxVerificationMethod;
64
84
  }
65
85
  /**
66
86
  * A session stored in a {@link SiwxSessionStore}.
@@ -330,8 +350,9 @@ interface SiwxJwtOptions {
330
350
  */
331
351
  ttlSeconds?: number;
332
352
  /**
333
- * Builds the `sub` claim from the session record. Defaults to the bound `subjectId`, otherwise the account without
334
- * its chain (see `siwxJwtSubject`).
353
+ * Builds the `sub` claim from the session record. Defaults to the bound `subjectId`, otherwise the account: without
354
+ * its chain for a wallet that signed with its own key, with its chain for a smart contract wallet (see
355
+ * `siwxJwtSubject`).
335
356
  */
336
357
  subject?: (record: SiwxSessionRecord) => string | Promise<string>;
337
358
  /** Extra claims from the session record. Reserved claims cannot be set. */
@@ -344,8 +365,9 @@ interface SiwxJwtPayload {
344
365
  /** Issuer: the URL of your app. */
345
366
  iss: string;
346
367
  /**
347
- * Subject: a stable ID of the user. By default the user ID bound with `bindSubject`, otherwise the account without
348
- * its chain (`eip155:0x…` in lowercase, `solana:<address>`).
368
+ * Subject: a stable ID of the user. By default the user ID bound with `bindSubject`, otherwise the account: without
369
+ * its chain for a wallet that signed with its own key (`eip155:0x…` in lowercase, `solana:<address>`), with its
370
+ * chain for an EVM smart contract wallet (`eip155:<chain>:0x…` in lowercase), whose owners are set on each chain.
349
371
  */
350
372
  sub: string;
351
373
  /** Audience, when one was set. */
@@ -365,12 +387,22 @@ interface SiwxJwtPayload {
365
387
  }
366
388
  /**
367
389
  * Converts a verified CAIP-122 message into a {@link SiwxSession}: keeps `address`, `chainId`, `domain`, `nonce`,
368
- * `issuedAt` and `expirationTime`. Pure function.
390
+ * `issuedAt` and `expirationTime`, plus `verificationMethod` when given. Pure function.
369
391
  *
370
392
  * @param parsed - The verified message, for example `result.data` of {@link verifySiwxPayload}.
393
+ * @param verificationMethod - How the signature was verified: `result.method` of {@link verifySiwxPayload}. Without
394
+ * it, {@link siwxJwtSubject} keeps the chain in the subject of an EVM session.
371
395
  * @returns The session object to store or sign.
396
+ *
397
+ * @example
398
+ * ```ts
399
+ * const result = await verifySiwxPayload(payload, { policy });
400
+ * if (result.success && result.data) {
401
+ * const session = toSession(result.data, result.method);
402
+ * }
403
+ * ```
372
404
  */
373
- declare function toSession(parsed: ParsedSiwxMessage): SiwxSession;
405
+ declare function toSession(parsed: ParsedSiwxMessage, verificationMethod?: SiwxVerificationMethod): SiwxSession;
374
406
 
375
407
  /**
376
408
  * Verifies a signed CAIP-122 message on the server, for any supported chain.
@@ -542,4 +574,4 @@ declare class MemorySiwxNonceStore implements SiwxNonceStore {
542
574
  */
543
575
  declare function getSiwxServerSession(options: GetSiwxServerSessionOptions): Promise<SiwxSession | null>;
544
576
 
545
- export { type CookieOptions as C, type GetSiwxServerSessionOptions as G, MemorySiwxNonceStore as M, type SiwxSession as S, type SiwxJwtKey as a, type SiwxJwks as b, type SiwxPublicJwk as c, type SiwxJwtPayload as d, type SiwxJwtAlgorithm as e, MemorySiwxSessionStore as f, type ServerVerifyOptions as g, type ServerVerifyResult as h, type SiwxJwtOptions as i, type SiwxNonceStore as j, type SiwxSessionRecord as k, type SiwxSessionStore as l, type StatelessDemoLimits as m, type StatelessDemoTokenPayload as n, createClearCookie as o, createSessionCookie as p, getSiwxServerSession as q, issueStatelessDemoNonce as r, parseCookie as s, signStatelessDemoSession as t, toSession as u, verifySiwxPayload as v, verifyStatelessDemoNonce as w, verifyStatelessDemoSession as x };
577
+ export { type CookieOptions as C, type GetSiwxServerSessionOptions as G, MemorySiwxNonceStore as M, type SiwxSession as S, type SiwxJwtKey as a, type SiwxJwks as b, type SiwxPublicJwk as c, type SiwxJwtPayload as d, type SiwxJwtAlgorithm as e, MemorySiwxSessionStore as f, type ServerVerifyOptions as g, type ServerVerifyResult as h, type SiwxJwtOptions as i, type SiwxNonceStore as j, type SiwxSessionRecord as k, type SiwxSessionStore as l, type SiwxVerificationMethod as m, type StatelessDemoLimits as n, type StatelessDemoTokenPayload as o, createClearCookie as p, createSessionCookie as q, getSiwxServerSession as r, issueStatelessDemoNonce as s, parseCookie as t, signStatelessDemoSession as u, toSession as v, verifySiwxPayload as w, verifyStatelessDemoNonce as x, verifyStatelessDemoSession as y };
@@ -34,6 +34,18 @@ interface ServerVerifyOptions {
34
34
  */
35
35
  publicClient?: EvmPublicClientSource;
36
36
  }
37
+ /**
38
+ * How a signature was verified:
39
+ *
40
+ * - `eip191`: by the key of an EVM account, which controls the address on every chain;
41
+ * - `eip1271`: by a deployed EVM smart contract wallet, on the chain it signed on;
42
+ * - `erc6492`: by an EVM smart contract wallet that is not deployed yet, on the chain it signed on;
43
+ * - `ed25519`: by the key of a Solana account.
44
+ *
45
+ * A smart contract wallet is controlled on each chain separately: the same address can have other owners on another
46
+ * network.
47
+ */
48
+ type SiwxVerificationMethod = 'eip191' | 'eip1271' | 'erc6492' | 'ed25519';
37
49
  /**
38
50
  * Result of {@link verifySiwxPayload}.
39
51
  */
@@ -43,6 +55,8 @@ interface ServerVerifyResult extends SiwxVerifyResult {
43
55
  * failed before the signature check.
44
56
  */
45
57
  namespace?: 'eip155' | 'solana';
58
+ /** How the signature was verified. Present only when `success` is `true`; pass it to {@link toSession}. */
59
+ method?: SiwxVerificationMethod;
46
60
  }
47
61
  /**
48
62
  * Serializable session derived from a verified CAIP-122 message (see {@link toSession}). Returned as JSON by the
@@ -61,6 +75,12 @@ interface SiwxSession {
61
75
  issuedAt: string;
62
76
  /** ISO 8601 timestamp when the session expires, if set. */
63
77
  expirationTime?: string;
78
+ /**
79
+ * How the signature was verified (see {@link SiwxVerificationMethod}). Set by `createSiwxApiHandler`; in your own
80
+ * handlers, pass `result.method` of {@link verifySiwxPayload} to {@link toSession}. {@link siwxJwtSubject} reads
81
+ * it: without it, the subject of an EVM session keeps its chain.
82
+ */
83
+ verificationMethod?: SiwxVerificationMethod;
64
84
  }
65
85
  /**
66
86
  * A session stored in a {@link SiwxSessionStore}.
@@ -330,8 +350,9 @@ interface SiwxJwtOptions {
330
350
  */
331
351
  ttlSeconds?: number;
332
352
  /**
333
- * Builds the `sub` claim from the session record. Defaults to the bound `subjectId`, otherwise the account without
334
- * its chain (see `siwxJwtSubject`).
353
+ * Builds the `sub` claim from the session record. Defaults to the bound `subjectId`, otherwise the account: without
354
+ * its chain for a wallet that signed with its own key, with its chain for a smart contract wallet (see
355
+ * `siwxJwtSubject`).
335
356
  */
336
357
  subject?: (record: SiwxSessionRecord) => string | Promise<string>;
337
358
  /** Extra claims from the session record. Reserved claims cannot be set. */
@@ -344,8 +365,9 @@ interface SiwxJwtPayload {
344
365
  /** Issuer: the URL of your app. */
345
366
  iss: string;
346
367
  /**
347
- * Subject: a stable ID of the user. By default the user ID bound with `bindSubject`, otherwise the account without
348
- * its chain (`eip155:0x…` in lowercase, `solana:<address>`).
368
+ * Subject: a stable ID of the user. By default the user ID bound with `bindSubject`, otherwise the account: without
369
+ * its chain for a wallet that signed with its own key (`eip155:0x…` in lowercase, `solana:<address>`), with its
370
+ * chain for an EVM smart contract wallet (`eip155:<chain>:0x…` in lowercase), whose owners are set on each chain.
349
371
  */
350
372
  sub: string;
351
373
  /** Audience, when one was set. */
@@ -365,12 +387,22 @@ interface SiwxJwtPayload {
365
387
  }
366
388
  /**
367
389
  * Converts a verified CAIP-122 message into a {@link SiwxSession}: keeps `address`, `chainId`, `domain`, `nonce`,
368
- * `issuedAt` and `expirationTime`. Pure function.
390
+ * `issuedAt` and `expirationTime`, plus `verificationMethod` when given. Pure function.
369
391
  *
370
392
  * @param parsed - The verified message, for example `result.data` of {@link verifySiwxPayload}.
393
+ * @param verificationMethod - How the signature was verified: `result.method` of {@link verifySiwxPayload}. Without
394
+ * it, {@link siwxJwtSubject} keeps the chain in the subject of an EVM session.
371
395
  * @returns The session object to store or sign.
396
+ *
397
+ * @example
398
+ * ```ts
399
+ * const result = await verifySiwxPayload(payload, { policy });
400
+ * if (result.success && result.data) {
401
+ * const session = toSession(result.data, result.method);
402
+ * }
403
+ * ```
372
404
  */
373
- declare function toSession(parsed: ParsedSiwxMessage): SiwxSession;
405
+ declare function toSession(parsed: ParsedSiwxMessage, verificationMethod?: SiwxVerificationMethod): SiwxSession;
374
406
 
375
407
  /**
376
408
  * Verifies a signed CAIP-122 message on the server, for any supported chain.
@@ -542,4 +574,4 @@ declare class MemorySiwxNonceStore implements SiwxNonceStore {
542
574
  */
543
575
  declare function getSiwxServerSession(options: GetSiwxServerSessionOptions): Promise<SiwxSession | null>;
544
576
 
545
- export { type CookieOptions as C, type GetSiwxServerSessionOptions as G, MemorySiwxNonceStore as M, type SiwxSession as S, type SiwxJwtKey as a, type SiwxJwks as b, type SiwxPublicJwk as c, type SiwxJwtPayload as d, type SiwxJwtAlgorithm as e, MemorySiwxSessionStore as f, type ServerVerifyOptions as g, type ServerVerifyResult as h, type SiwxJwtOptions as i, type SiwxNonceStore as j, type SiwxSessionRecord as k, type SiwxSessionStore as l, type StatelessDemoLimits as m, type StatelessDemoTokenPayload as n, createClearCookie as o, createSessionCookie as p, getSiwxServerSession as q, issueStatelessDemoNonce as r, parseCookie as s, signStatelessDemoSession as t, toSession as u, verifySiwxPayload as v, verifyStatelessDemoNonce as w, verifyStatelessDemoSession as x };
577
+ export { type CookieOptions as C, type GetSiwxServerSessionOptions as G, MemorySiwxNonceStore as M, type SiwxSession as S, type SiwxJwtKey as a, type SiwxJwks as b, type SiwxPublicJwk as c, type SiwxJwtPayload as d, type SiwxJwtAlgorithm as e, MemorySiwxSessionStore as f, type ServerVerifyOptions as g, type ServerVerifyResult as h, type SiwxJwtOptions as i, type SiwxNonceStore as j, type SiwxSessionRecord as k, type SiwxSessionStore as l, type SiwxVerificationMethod as m, type StatelessDemoLimits as n, type StatelessDemoTokenPayload as o, createClearCookie as p, createSessionCookie as q, getSiwxServerSession as r, issueStatelessDemoNonce as s, parseCookie as t, signStatelessDemoSession as u, toSession as v, verifySiwxPayload as w, verifyStatelessDemoNonce as x, verifyStatelessDemoSession as y };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tuwaio/siwx-server",
3
- "version": "0.6.0",
3
+ "version": "0.7.1",
4
4
  "private": false,
5
5
  "author": "Oleksandr Tkach",
6
6
  "license": "Apache-2.0",
@@ -88,9 +88,9 @@
88
88
  },
89
89
  "devDependencies": {
90
90
  "@tuwaio/orbit-core": "^0.5.0",
91
- "@tuwaio/siwx-core": "0.6.0",
92
- "@tuwaio/siwx-evm": "0.5.0",
93
- "@tuwaio/siwx-solana": "0.5.0",
91
+ "@tuwaio/siwx-core": "0.7.0",
92
+ "@tuwaio/siwx-evm": "0.5.1",
93
+ "@tuwaio/siwx-solana": "0.6.0",
94
94
  "tsup": "^8.5.1",
95
95
  "typescript": "6.0.3",
96
96
  "viem": "^2.57.1"
@@ -1,4 +0,0 @@
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;
@@ -1,4 +0,0 @@
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};