@tuwaio/siwx-server 0.8.1 → 0.8.3

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.
@@ -0,0 +1,4 @@
1
+ import {formatCaip10AccountId,isRecord,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 J(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 R(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:R(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:R(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=J(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:R(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 j=600,N=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??j,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(!isRecord(a)||!isRecord(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||J(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 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>N)throw new RangeError(`[SIWX-SERVER] The JWT ttlSeconds must be an integer from 1 to ${N}.`)}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 Je(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 Re(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,Je as n,Re 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 J(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 R(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:R(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:R(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=J(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:R(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 j=600,N=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??j,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(!orbitCore.isRecord(a)||!orbitCore.isRecord(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||J(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 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>N)throw new RangeError(`[SIWX-SERVER] The JWT ttlSeconds must be an integer from 1 to ${N}.`)}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 Je(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 Re(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=Je;exports.o=Re;exports.p=ve;exports.q=Ie;exports.r=E;exports.s=_;exports.t=U;exports.u=Ce;
package/dist/index.js CHANGED
@@ -1 +1 @@
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}});
1
+ 'use strict';var chunkGHUGNJS5_js=require('./chunk-GHUGNJS5.js'),siwxCore=require('@tuwaio/siwx-core');Object.defineProperty(exports,"MemorySiwxNonceStore",{enumerable:true,get:function(){return chunkGHUGNJS5_js.t}});Object.defineProperty(exports,"MemorySiwxSessionStore",{enumerable:true,get:function(){return chunkGHUGNJS5_js.s}});Object.defineProperty(exports,"createClearCookie",{enumerable:true,get:function(){return chunkGHUGNJS5_js.q}});Object.defineProperty(exports,"createSessionCookie",{enumerable:true,get:function(){return chunkGHUGNJS5_js.p}});Object.defineProperty(exports,"createSiwxJwks",{enumerable:true,get:function(){return chunkGHUGNJS5_js.d}});Object.defineProperty(exports,"generateServerNonce",{enumerable:true,get:function(){return chunkGHUGNJS5_js.j}});Object.defineProperty(exports,"generateSiwxJwtKey",{enumerable:true,get:function(){return chunkGHUGNJS5_js.b}});Object.defineProperty(exports,"getSiwxServerSession",{enumerable:true,get:function(){return chunkGHUGNJS5_js.u}});Object.defineProperty(exports,"importSiwxJwtKey",{enumerable:true,get:function(){return chunkGHUGNJS5_js.c}});Object.defineProperty(exports,"issueStatelessDemoNonce",{enumerable:true,get:function(){return chunkGHUGNJS5_js.n}});Object.defineProperty(exports,"parseCookie",{enumerable:true,get:function(){return chunkGHUGNJS5_js.r}});Object.defineProperty(exports,"signSiwxJwt",{enumerable:true,get:function(){return chunkGHUGNJS5_js.f}});Object.defineProperty(exports,"signStatelessDemoSession",{enumerable:true,get:function(){return chunkGHUGNJS5_js.l}});Object.defineProperty(exports,"siwxJwkThumbprint",{enumerable:true,get:function(){return chunkGHUGNJS5_js.a}});Object.defineProperty(exports,"siwxJwtSubject",{enumerable:true,get:function(){return chunkGHUGNJS5_js.e}});Object.defineProperty(exports,"toSession",{enumerable:true,get:function(){return chunkGHUGNJS5_js.i}});Object.defineProperty(exports,"verifySiwxJwt",{enumerable:true,get:function(){return chunkGHUGNJS5_js.g}});Object.defineProperty(exports,"verifySiwxPayload",{enumerable:true,get:function(){return chunkGHUGNJS5_js.k}});Object.defineProperty(exports,"verifyStatelessDemoNonce",{enumerable:true,get:function(){return chunkGHUGNJS5_js.o}});Object.defineProperty(exports,"verifyStatelessDemoSession",{enumerable:true,get:function(){return chunkGHUGNJS5_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-LAMZ44ZN.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-6TXKY4B7.mjs';export{generateNonce,isSessionMatchingTarget,validateMessage,validatePolicy}from'@tuwaio/siwx-core';
package/dist/next.js CHANGED
@@ -1 +1 @@
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;
1
+ 'use strict';var chunkGHUGNJS5_js=require('./chunk-GHUGNJS5.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&&chunkGHUGNJS5_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=chunkGHUGNJS5_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 chunkGHUGNJS5_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=chunkGHUGNJS5_js.i(S.data,S.method),f=await e.sessionStore.create({session:m,ttlSeconds:u}),h=chunkGHUGNJS5_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=chunkGHUGNJS5_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 chunkGHUGNJS5_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):chunkGHUGNJS5_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=chunkGHUGNJS5_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=chunkGHUGNJS5_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":chunkGHUGNJS5_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=chunkGHUGNJS5_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 chunkGHUGNJS5_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 chunkGHUGNJS5_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 chunkGHUGNJS5_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 chunkGHUGNJS5_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=chunkGHUGNJS5_js.i(d.data),h=await chunkGHUGNJS5_js.l(f,e.signingSecret,u),L=chunkGHUGNJS5_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":chunkGHUGNJS5_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 chunkGHUGNJS5_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-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};
1
+ import {h,r,k,i,p,f,e,d,q,m,n,o,l}from'./chunk-6TXKY4B7.mjs';export{u as getSiwxServerSession}from'./chunk-6TXKY4B7.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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tuwaio/siwx-server",
3
- "version": "0.8.1",
3
+ "version": "0.8.3",
4
4
  "private": false,
5
5
  "author": "Oleksandr Tkach",
6
6
  "license": "Apache-2.0",
@@ -69,7 +69,7 @@
69
69
  }
70
70
  ],
71
71
  "peerDependencies": {
72
- "@tuwaio/orbit-core": ">=0.5",
72
+ "@tuwaio/orbit-core": ">=0.6.1",
73
73
  "@tuwaio/siwx-core": ">=0.5",
74
74
  "@tuwaio/siwx-evm": ">=0.5",
75
75
  "@tuwaio/siwx-solana": ">=0.4.2",
@@ -87,13 +87,13 @@
87
87
  }
88
88
  },
89
89
  "devDependencies": {
90
- "@tuwaio/orbit-core": "^0.6.0",
91
- "@tuwaio/siwx-core": "0.7.1",
92
- "@tuwaio/siwx-evm": "0.5.3",
93
- "@tuwaio/siwx-solana": "0.7.1",
90
+ "@tuwaio/orbit-core": "^0.6.2",
91
+ "@tuwaio/siwx-core": "0.7.3",
92
+ "@tuwaio/siwx-evm": "0.5.5",
93
+ "@tuwaio/siwx-solana": "0.7.3",
94
94
  "tsup": "^9.0.0",
95
95
  "typescript": "6.0.3",
96
- "viem": "^2.57.12"
96
+ "viem": "^2.57.20"
97
97
  },
98
98
  "scripts": {
99
99
  "start": "tsup src/index.ts --watch",
@@ -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(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};
@@ -1,4 +0,0 @@
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;