@tuwaio/siwx-server 0.2.1 → 1.0.0-feat-update-alpha.2.83013b6

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,2 @@
1
+ import {parseMessage,validateMessage,SiwxExpiredSessionError,SiwxNonceReplayError,SiwxUnsupportedNamespaceError,generateNonce}from'@tuwaio/siwx-core';export{generateNonce as b}from'@tuwaio/siwx-core';function v(i){return {address:i.address,chainId:i.chainId,domain:i.domain,nonce:i.nonce,issuedAt:i.issuedAt,expirationTime:i.expirationTime}}async function N(i,e={}){try{let n=parseMessage(i.message),r=validateMessage(n,{skipExpiration:e.skipExpiration,policy:e.policy});if(!r.valid)return {success:!1,error:`Validation failed: ${r.errors.join(", ")}`};if(!e.skipExpiration&&n.expirationTime&&new Date(n.expirationTime)<new Date)throw new SiwxExpiredSessionError(n.expirationTime);if(e.usedNonces?.has(n.nonce))throw new SiwxNonceReplayError(n.nonce);let s=n.chainId.split(":")[0];if(!s||!["eip155","solana"].includes(s))throw new SiwxUnsupportedNamespaceError(s??"unknown");if(s==="eip155"){let{verifyEvmSignature:t}=await import('@tuwaio/siwx-evm');return {...await t(i.message,i.signature,{skipExpiration:e.skipExpiration,publicClient:e.publicClient}),namespace:s}}if(s==="solana"){let{verifyEd25519:t}=await import('@tuwaio/siwx-solana');return {...await t(i,{skipExpiration:e.skipExpiration}),namespace:s}}return {success:!1,error:"Unsupported namespace."}}catch(n){return n instanceof SiwxExpiredSessionError||n instanceof SiwxNonceReplayError||n instanceof SiwxUnsupportedNamespaceError?{success:false,error:n.message}:{success:false,error:`Server verification failed: ${String(n)}`}}}function E(i){return btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function T(i){let e=i.replace(/-/g,"+").replace(/_/g,"/");return atob(e)}function A(i){let e="";for(let n=0;n<i.byteLength;n++)e+=String.fromCharCode(i[n]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function C(i){let e=i.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e),r=new Uint8Array(n.length);for(let s=0;s<n.length;s++)r[s]=n.charCodeAt(s);return r}async function b(i){let e=new TextEncoder;return globalThis.crypto.subtle.importKey("raw",e.encode(i),{name:"HMAC",hash:"SHA-256"},false,["sign","verify"])}async function O(i,e,n=1800){if(!e||e.length<32)throw new Error("[SIWX-SERVER] Stateless demo signing secret must be at least 32 characters long.");let s=Date.now()+n*1e3,t={version:1,address:i.address,chainId:i.chainId,domain:i.domain,nonce:i.nonce,issuedAt:i.issuedAt,expirationTime:i.expirationTime??new Date(s).toISOString(),sessionId:generateNonce(),mode:"demo"},a=JSON.stringify(t),o=E(a),l=await b(e),u=new TextEncoder,p=await globalThis.crypto.subtle.sign("HMAC",l,u.encode(o)),c=A(new Uint8Array(p));return `${o}.${c}`}async function D(i,e,n){if(!i||typeof i!="string"||!e)return null;let r=i.split(".");if(r.length!==2)return null;let[s,t]=r;try{let a=await b(e),o=C(t),l=new TextEncoder;if(!await globalThis.crypto.subtle.verify("HMAC",a,o,l.encode(s)))return null;let p=T(s),c=JSON.parse(p);if(c.version!==1||c.mode!=="demo")return null;if(c.expirationTime){let S=new Date(c.expirationTime).getTime(),f=(n?.clockSkewSeconds??60)*1e3;if(isNaN(S)||S+f<Date.now())return null}return n?.expectedDomain!==void 0&&!(Array.isArray(n.expectedDomain)?n.expectedDomain:[n.expectedDomain]).some(f=>f.toLowerCase()===c.domain.toLowerCase())||n?.allowedChainIds!==void 0&&n.allowedChainIds.length>0&&!n.allowedChainIds.includes(c.chainId)?null:{address:c.address,chainId:c.chainId,domain:c.domain,nonce:c.nonce,issuedAt:c.issuedAt,expirationTime:c.expirationTime}}catch{return null}}function $(i,e={}){let{name:n="siwx-session-v2",maxAge:r=3600*24*7,path:s="/",domain:t,secure:a=true,sameSite:o="Strict"}=e,l=[`${n}=${i}`,`Max-Age=${r}`,`Path=${s}`,"HttpOnly",`SameSite=${o}`];return a&&l.push("Secure"),t&&l.push(`Domain=${t}`),l.join("; ")}function j(i={}){let{name:e="siwx-session-v2",path:n="/",domain:r,secure:s=true,sameSite:t="Strict"}=i,a=[`${e}=`,`Path=${n}`,"Expires=Thu, 01 Jan 1970 00:00:00 GMT","Max-Age=0","HttpOnly",`SameSite=${t}`];return s&&a.push("Secure"),r&&a.push(`Domain=${r}`),a.join("; ")}function d(i,e){return i?Object.fromEntries(i.split("; ").filter(Boolean).map(r=>{let s=r.split("=");return [s[0].trim(),s.slice(1).join("=")]}))[e]??null:null}var w=class{records=new Map;constructor(e){if(typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV==="production"&&!e?.allowInProduction)throw new Error("[SIWX-SERVER] MemorySiwxSessionStore must not be used in production. Connect Redis or a durable store.")}async create(e){let n=generateNonce(),r=Date.now(),s=r+e.ttlSeconds*1e3,t={id:n,session:e.session,createdAt:r,expiresAt:s};return this.records.set(n,t),t}async get(e){let n=this.records.get(e);return n?n.expiresAt<Date.now()?(this.records.delete(e),null):n:null}async bindSubject(e,n){let r=await this.get(e);return r?(r.subjectId=n,true):false}async revoke(e){this.records.delete(e);}},y=class{nonces=new Map;constructor(e){if(typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV==="production"&&!e?.allowInProduction)throw new Error("[SIWX-SERVER] MemorySiwxNonceStore must not be used in production. Connect Redis or a durable store.")}async issue(e){let n=Date.now()+e.ttlSeconds*1e3;this.nonces.set(e.nonce,n);}async consume(e){let n=this.nonces.get(e.nonce);return !(!n||(this.nonces.delete(e.nonce),n<Date.now()))}};async function B(i){let{cookieSource:e,cookieName:n="siwx-session-v2",sessionStore:r,signingSecret:s,policy:t}=i;if(!e)return null;let a=null;if(typeof e=="string")a=e.includes("=")?d(e,n):e;else if(typeof e.headers=="object"&&typeof e.headers?.get=="function"){let o=e.headers.get("cookie");a=d(o,n);}else if(typeof e.get=="function"){let o=e.get(n);if(o&&typeof o=="object"&&"value"in o)a=o.value;else if(typeof o=="string")a=o.includes("=")?d(o,n):o;else if(typeof e.get=="function"){let l=e.get("cookie");l&&(a=d(l,n));}}if(!a)return null;if(r){let o=await r.get(a);return !o?.session||t&&(t.expectedDomain!==void 0&&!(Array.isArray(t.expectedDomain)?t.expectedDomain:[t.expectedDomain]).some(u=>u.toLowerCase()===o.session.domain.toLowerCase())||t.allowedChainIds!==void 0&&t.allowedChainIds.length>0&&!t.allowedChainIds.includes(o.session.chainId)||t.requireExpirationTime&&!o.session.expirationTime)?null:o.session}return s?D(a,s,t):null}
2
+ export{v as a,N as c,O as d,D as e,$ as f,j as g,d as h,w as i,y as j,B as k};
@@ -0,0 +1,2 @@
1
+ 'use strict';var siwxCore=require('@tuwaio/siwx-core');function v(i){return {address:i.address,chainId:i.chainId,domain:i.domain,nonce:i.nonce,issuedAt:i.issuedAt,expirationTime:i.expirationTime}}async function N(i,e={}){try{let n=siwxCore.parseMessage(i.message),r=siwxCore.validateMessage(n,{skipExpiration:e.skipExpiration,policy:e.policy});if(!r.valid)return {success:!1,error:`Validation failed: ${r.errors.join(", ")}`};if(!e.skipExpiration&&n.expirationTime&&new Date(n.expirationTime)<new Date)throw new siwxCore.SiwxExpiredSessionError(n.expirationTime);if(e.usedNonces?.has(n.nonce))throw new siwxCore.SiwxNonceReplayError(n.nonce);let s=n.chainId.split(":")[0];if(!s||!["eip155","solana"].includes(s))throw new siwxCore.SiwxUnsupportedNamespaceError(s??"unknown");if(s==="eip155"){let{verifyEvmSignature:t}=await import('@tuwaio/siwx-evm');return {...await t(i.message,i.signature,{skipExpiration:e.skipExpiration,publicClient:e.publicClient}),namespace:s}}if(s==="solana"){let{verifyEd25519:t}=await import('@tuwaio/siwx-solana');return {...await t(i,{skipExpiration:e.skipExpiration}),namespace:s}}return {success:!1,error:"Unsupported namespace."}}catch(n){return n instanceof siwxCore.SiwxExpiredSessionError||n instanceof siwxCore.SiwxNonceReplayError||n instanceof siwxCore.SiwxUnsupportedNamespaceError?{success:false,error:n.message}:{success:false,error:`Server verification failed: ${String(n)}`}}}function E(i){return btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function T(i){let e=i.replace(/-/g,"+").replace(/_/g,"/");return atob(e)}function A(i){let e="";for(let n=0;n<i.byteLength;n++)e+=String.fromCharCode(i[n]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function C(i){let e=i.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e),r=new Uint8Array(n.length);for(let s=0;s<n.length;s++)r[s]=n.charCodeAt(s);return r}async function b(i){let e=new TextEncoder;return globalThis.crypto.subtle.importKey("raw",e.encode(i),{name:"HMAC",hash:"SHA-256"},false,["sign","verify"])}async function O(i,e,n=1800){if(!e||e.length<32)throw new Error("[SIWX-SERVER] Stateless demo signing secret must be at least 32 characters long.");let s=Date.now()+n*1e3,t={version:1,address:i.address,chainId:i.chainId,domain:i.domain,nonce:i.nonce,issuedAt:i.issuedAt,expirationTime:i.expirationTime??new Date(s).toISOString(),sessionId:siwxCore.generateNonce(),mode:"demo"},a=JSON.stringify(t),o=E(a),l=await b(e),u=new TextEncoder,p=await globalThis.crypto.subtle.sign("HMAC",l,u.encode(o)),c=A(new Uint8Array(p));return `${o}.${c}`}async function D(i,e,n){if(!i||typeof i!="string"||!e)return null;let r=i.split(".");if(r.length!==2)return null;let[s,t]=r;try{let a=await b(e),o=C(t),l=new TextEncoder;if(!await globalThis.crypto.subtle.verify("HMAC",a,o,l.encode(s)))return null;let p=T(s),c=JSON.parse(p);if(c.version!==1||c.mode!=="demo")return null;if(c.expirationTime){let S=new Date(c.expirationTime).getTime(),f=(n?.clockSkewSeconds??60)*1e3;if(isNaN(S)||S+f<Date.now())return null}return n?.expectedDomain!==void 0&&!(Array.isArray(n.expectedDomain)?n.expectedDomain:[n.expectedDomain]).some(f=>f.toLowerCase()===c.domain.toLowerCase())||n?.allowedChainIds!==void 0&&n.allowedChainIds.length>0&&!n.allowedChainIds.includes(c.chainId)?null:{address:c.address,chainId:c.chainId,domain:c.domain,nonce:c.nonce,issuedAt:c.issuedAt,expirationTime:c.expirationTime}}catch{return null}}function $(i,e={}){let{name:n="siwx-session-v2",maxAge:r=3600*24*7,path:s="/",domain:t,secure:a=true,sameSite:o="Strict"}=e,l=[`${n}=${i}`,`Max-Age=${r}`,`Path=${s}`,"HttpOnly",`SameSite=${o}`];return a&&l.push("Secure"),t&&l.push(`Domain=${t}`),l.join("; ")}function j(i={}){let{name:e="siwx-session-v2",path:n="/",domain:r,secure:s=true,sameSite:t="Strict"}=i,a=[`${e}=`,`Path=${n}`,"Expires=Thu, 01 Jan 1970 00:00:00 GMT","Max-Age=0","HttpOnly",`SameSite=${t}`];return s&&a.push("Secure"),r&&a.push(`Domain=${r}`),a.join("; ")}function d(i,e){return i?Object.fromEntries(i.split("; ").filter(Boolean).map(r=>{let s=r.split("=");return [s[0].trim(),s.slice(1).join("=")]}))[e]??null:null}var w=class{records=new Map;constructor(e){if(typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV==="production"&&!e?.allowInProduction)throw new Error("[SIWX-SERVER] MemorySiwxSessionStore must not be used in production. Connect Redis or a durable store.")}async create(e){let n=siwxCore.generateNonce(),r=Date.now(),s=r+e.ttlSeconds*1e3,t={id:n,session:e.session,createdAt:r,expiresAt:s};return this.records.set(n,t),t}async get(e){let n=this.records.get(e);return n?n.expiresAt<Date.now()?(this.records.delete(e),null):n:null}async bindSubject(e,n){let r=await this.get(e);return r?(r.subjectId=n,true):false}async revoke(e){this.records.delete(e);}},y=class{nonces=new Map;constructor(e){if(typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV==="production"&&!e?.allowInProduction)throw new Error("[SIWX-SERVER] MemorySiwxNonceStore must not be used in production. Connect Redis or a durable store.")}async issue(e){let n=Date.now()+e.ttlSeconds*1e3;this.nonces.set(e.nonce,n);}async consume(e){let n=this.nonces.get(e.nonce);return !(!n||(this.nonces.delete(e.nonce),n<Date.now()))}};async function B(i){let{cookieSource:e,cookieName:n="siwx-session-v2",sessionStore:r,signingSecret:s,policy:t}=i;if(!e)return null;let a=null;if(typeof e=="string")a=e.includes("=")?d(e,n):e;else if(typeof e.headers=="object"&&typeof e.headers?.get=="function"){let o=e.headers.get("cookie");a=d(o,n);}else if(typeof e.get=="function"){let o=e.get(n);if(o&&typeof o=="object"&&"value"in o)a=o.value;else if(typeof o=="string")a=o.includes("=")?d(o,n):o;else if(typeof e.get=="function"){let l=e.get("cookie");l&&(a=d(l,n));}}if(!a)return null;if(r){let o=await r.get(a);return !o?.session||t&&(t.expectedDomain!==void 0&&!(Array.isArray(t.expectedDomain)?t.expectedDomain:[t.expectedDomain]).some(u=>u.toLowerCase()===o.session.domain.toLowerCase())||t.allowedChainIds!==void 0&&t.allowedChainIds.length>0&&!t.allowedChainIds.includes(o.session.chainId)||t.requireExpirationTime&&!o.session.expirationTime)?null:o.session}return s?D(a,s,t):null}
2
+ Object.defineProperty(exports,"b",{enumerable:true,get:function(){return siwxCore.generateNonce}});exports.a=v;exports.c=N;exports.d=O;exports.e=D;exports.f=$;exports.g=j;exports.h=d;exports.i=w;exports.j=y;exports.k=B;
package/dist/index.d.mts CHANGED
@@ -144,13 +144,18 @@ interface StatelessDemoTokenPayload {
144
144
  mode: 'demo';
145
145
  }
146
146
  /**
147
- * Limits for stateless demo profile.
147
+ * Enforceable request boundary limits for the stateless demo profile.
148
+ *
149
+ * Note: Shared rate limits and request quotas across multiple replicas require
150
+ * a durable store or are authoritative at the Quasar App RPS / Quota layer.
148
151
  */
149
152
  interface StatelessDemoLimits {
150
- /** Maximum transaction payload size in bytes. */
153
+ /**
154
+ * Maximum allowed incoming payload body size in bytes for SIWX verification endpoints.
155
+ * Requests exceeding this limit will be rejected with HTTP 413 (Payload Too Large).
156
+ * @default 65536 (64 KB)
157
+ */
151
158
  maxTransactionPayloadBytes?: number;
152
- /** Advisory request cap per session. */
153
- maxRequestsPerSession?: number;
154
159
  }
155
160
  /**
156
161
  * Options for cookie session serialization.
package/dist/index.d.ts CHANGED
@@ -144,13 +144,18 @@ interface StatelessDemoTokenPayload {
144
144
  mode: 'demo';
145
145
  }
146
146
  /**
147
- * Limits for stateless demo profile.
147
+ * Enforceable request boundary limits for the stateless demo profile.
148
+ *
149
+ * Note: Shared rate limits and request quotas across multiple replicas require
150
+ * a durable store or are authoritative at the Quasar App RPS / Quota layer.
148
151
  */
149
152
  interface StatelessDemoLimits {
150
- /** Maximum transaction payload size in bytes. */
153
+ /**
154
+ * Maximum allowed incoming payload body size in bytes for SIWX verification endpoints.
155
+ * Requests exceeding this limit will be rejected with HTTP 413 (Payload Too Large).
156
+ * @default 65536 (64 KB)
157
+ */
151
158
  maxTransactionPayloadBytes?: number;
152
- /** Advisory request cap per session. */
153
- maxRequestsPerSession?: number;
154
159
  }
155
160
  /**
156
161
  * Options for cookie session serialization.
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- 'use strict';var chunkU25GZS7S_js=require('./chunk-U25GZS7S.js'),siwxCore=require('@tuwaio/siwx-core');Object.defineProperty(exports,"MemorySiwxNonceStore",{enumerable:true,get:function(){return chunkU25GZS7S_js.j}});Object.defineProperty(exports,"MemorySiwxSessionStore",{enumerable:true,get:function(){return chunkU25GZS7S_js.i}});Object.defineProperty(exports,"createClearCookie",{enumerable:true,get:function(){return chunkU25GZS7S_js.g}});Object.defineProperty(exports,"createSessionCookie",{enumerable:true,get:function(){return chunkU25GZS7S_js.f}});Object.defineProperty(exports,"generateServerNonce",{enumerable:true,get:function(){return chunkU25GZS7S_js.b}});Object.defineProperty(exports,"getSiwxServerSession",{enumerable:true,get:function(){return chunkU25GZS7S_js.k}});Object.defineProperty(exports,"parseCookie",{enumerable:true,get:function(){return chunkU25GZS7S_js.h}});Object.defineProperty(exports,"signStatelessDemoSession",{enumerable:true,get:function(){return chunkU25GZS7S_js.d}});Object.defineProperty(exports,"toSession",{enumerable:true,get:function(){return chunkU25GZS7S_js.a}});Object.defineProperty(exports,"verifySiwxPayload",{enumerable:true,get:function(){return chunkU25GZS7S_js.c}});Object.defineProperty(exports,"verifyStatelessDemoSession",{enumerable:true,get:function(){return chunkU25GZS7S_js.e}});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 chunkWPKBWXVR_js=require('./chunk-WPKBWXVR.js'),siwxCore=require('@tuwaio/siwx-core');Object.defineProperty(exports,"MemorySiwxNonceStore",{enumerable:true,get:function(){return chunkWPKBWXVR_js.j}});Object.defineProperty(exports,"MemorySiwxSessionStore",{enumerable:true,get:function(){return chunkWPKBWXVR_js.i}});Object.defineProperty(exports,"createClearCookie",{enumerable:true,get:function(){return chunkWPKBWXVR_js.g}});Object.defineProperty(exports,"createSessionCookie",{enumerable:true,get:function(){return chunkWPKBWXVR_js.f}});Object.defineProperty(exports,"generateServerNonce",{enumerable:true,get:function(){return chunkWPKBWXVR_js.b}});Object.defineProperty(exports,"getSiwxServerSession",{enumerable:true,get:function(){return chunkWPKBWXVR_js.k}});Object.defineProperty(exports,"parseCookie",{enumerable:true,get:function(){return chunkWPKBWXVR_js.h}});Object.defineProperty(exports,"signStatelessDemoSession",{enumerable:true,get:function(){return chunkWPKBWXVR_js.d}});Object.defineProperty(exports,"toSession",{enumerable:true,get:function(){return chunkWPKBWXVR_js.a}});Object.defineProperty(exports,"verifySiwxPayload",{enumerable:true,get:function(){return chunkWPKBWXVR_js.c}});Object.defineProperty(exports,"verifyStatelessDemoSession",{enumerable:true,get:function(){return chunkWPKBWXVR_js.e}});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{j as MemorySiwxNonceStore,i as MemorySiwxSessionStore,g as createClearCookie,f as createSessionCookie,b as generateServerNonce,k as getSiwxServerSession,h as parseCookie,d as signStatelessDemoSession,a as toSession,c as verifySiwxPayload,e as verifyStatelessDemoSession}from'./chunk-WXHFSBDK.mjs';export{generateNonce,isSessionMatchingTarget,validateMessage,validatePolicy}from'@tuwaio/siwx-core';
1
+ export{j as MemorySiwxNonceStore,i as MemorySiwxSessionStore,g as createClearCookie,f as createSessionCookie,b as generateServerNonce,k as getSiwxServerSession,h as parseCookie,d as signStatelessDemoSession,a as toSession,c as verifySiwxPayload,e as verifyStatelessDemoSession}from'./chunk-PBR725EL.mjs';export{generateNonce,isSessionMatchingTarget,validateMessage,validatePolicy}from'@tuwaio/siwx-core';
package/dist/next.js CHANGED
@@ -1 +1 @@
1
- 'use strict';var chunkU25GZS7S_js=require('./chunk-U25GZS7S.js'),siwxCore=require('@tuwaio/siwx-core');function k(e){if(!e?.sessionStore||!e?.nonceStore)throw new Error("[SIWX-SERVER] createSiwxApiHandler requires both `sessionStore` and `nonceStore`. For zero-infrastructure demos without storage, use `createStatelessDemoSiwxHandler`.");let i=e.cookieOptions?.name||"siwx-session-v2",a=e.ttlSeconds??(e.cookieOptions?.maxAge||3600*24*7),r=async n=>{try{let p=new URL(n.url).pathname.split("/").filter(Boolean),o=p[p.length-1]||"";if(n.method==="GET"&&o==="session"){let t=chunkU25GZS7S_js.h(n.headers.get("cookie"),i);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((n.method==="GET"||n.method==="POST")&&o==="nonce"){let t=siwxCore.generateNonce();return await e.nonceStore.issue({nonce:t,ttlSeconds:300}),new Response(JSON.stringify({nonce:t}),{status:200,headers:{"Content-Type":"application/json"}})}if(n.method==="POST"&&o==="verify"){let t=await n.json();if(!t.message||!t.signature)return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let s=await chunkU25GZS7S_js.c(t,{...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 S=chunkU25GZS7S_js.a(s.data),d=await e.sessionStore.create({session:S,ttlSeconds:a}),T=chunkU25GZS7S_js.f(d.id,{...e.cookieOptions,name:i,maxAge:a});return new Response(JSON.stringify(S),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":T}})}if(n.method==="DELETE"&&o==="session"||n.method==="POST"&&o==="logout"){let t=chunkU25GZS7S_js.h(n.headers.get("cookie"),i);return t&&await e.sessionStore.revoke(t),new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":chunkU25GZS7S_js.g({...e.cookieOptions,name:i})}})}return new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(c){return console.error("[SIWX-SERVER] Durable Handler error:",c),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:r,POST:r,DELETE:r}}function E(e){if(!e?.signingSecret||e.signingSecret.length<32)throw new Error("[SIWX-SERVER] createStatelessDemoSiwxHandler requires a `signingSecret` of at least 32 characters.");let i=e.cookieOptions?.name||"siwx-session-v2",a=e.ttlSeconds??(e.cookieOptions?.maxAge||1800),r=async n=>{try{let p=new URL(n.url).pathname.split("/").filter(Boolean),o=p[p.length-1]||"";if(n.method==="GET"&&o==="session"){let t=chunkU25GZS7S_js.h(n.headers.get("cookie"),i);if(!t)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let s=await chunkU25GZS7S_js.e(t,e.signingSecret,e.policy);return new Response(JSON.stringify(s),{status:200,headers:{"Content-Type":"application/json"}})}if((n.method==="GET"||n.method==="POST")&&o==="nonce"){let t=siwxCore.generateNonce();return new Response(JSON.stringify({nonce:t}),{status:200,headers:{"Content-Type":"application/json"}})}if(n.method==="POST"&&o==="verify"){let t=await n.json();if(!t.message||!t.signature)return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let s=await chunkU25GZS7S_js.c(t,{...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"}});let u=chunkU25GZS7S_js.a(s.data),S=await chunkU25GZS7S_js.d(u,e.signingSecret,a),d=chunkU25GZS7S_js.f(S,{...e.cookieOptions,name:i,maxAge:a});return new Response(JSON.stringify(u),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":d}})}return n.method==="DELETE"&&o==="session"||n.method==="POST"&&o==="logout"?new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":chunkU25GZS7S_js.g({...e.cookieOptions,name:i})}}):new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(c){return console.error("[SIWX-SERVER] Stateless Demo Handler error:",c),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:r,POST:r,DELETE:r}}Object.defineProperty(exports,"getSiwxServerSession",{enumerable:true,get:function(){return chunkU25GZS7S_js.k}});exports.createSiwxApiHandler=k;exports.createStatelessDemoSiwxHandler=E;
1
+ 'use strict';var chunkWPKBWXVR_js=require('./chunk-WPKBWXVR.js'),siwxCore=require('@tuwaio/siwx-core');function j(e){if(!e?.sessionStore||!e?.nonceStore)throw new Error("[SIWX-SERVER] createSiwxApiHandler requires both `sessionStore` and `nonceStore`.");let a=e.cookieOptions?.name||"siwx-session-v2",p=e.ttlSeconds??(e.cookieOptions?.maxAge||3600*24*7),l=65536,c=async t=>{try{let d=new URL(t.url).pathname.split("/").filter(Boolean),o=d[d.length-1]||"";if(t.method==="GET"&&o==="session"){let n=chunkWPKBWXVR_js.h(t.headers.get("cookie"),a);if(!n)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let i=await e.sessionStore.get(n);return new Response(JSON.stringify(i?.session??null),{status:200,headers:{"Content-Type":"application/json"}})}if((t.method==="GET"||t.method==="POST")&&o==="nonce"){let n=siwxCore.generateNonce();return await e.nonceStore.issue({nonce:n,ttlSeconds:300}),new Response(JSON.stringify({nonce:n}),{status:200,headers:{"Content-Type":"application/json"}})}if(t.method==="POST"&&o==="verify"){let n=t.headers.get("content-length");if(n&&parseInt(n,10)>l)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let i=await t.text();if(i.length>l)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let s;try{s=JSON.parse(i);}catch{return new Response(JSON.stringify({error:"Invalid JSON payload"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!s||typeof s.message!="string"||typeof s.signature!="string")return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let g={message:s.message,signature:s.signature},r=await chunkWPKBWXVR_js.c(g,{...e.verifyOptions,policy:e.policy});if(!r.success||!r.data)return new Response(JSON.stringify({error:r.error||"Verification failed"}),{status:401,headers:{"Content-Type":"application/json"}});if(!await e.nonceStore.consume({nonce:r.data.nonce}))return new Response(JSON.stringify({error:"Nonce replay detected or nonce expired"}),{status:401,headers:{"Content-Type":"application/json"}});let y=chunkWPKBWXVR_js.a(r.data),w=await e.sessionStore.create({session:y,ttlSeconds:p}),x=chunkWPKBWXVR_js.f(w.id,{...e.cookieOptions,name:a,maxAge:p});return new Response(JSON.stringify(y),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":x}})}if(t.method==="DELETE"&&o==="session"||t.method==="POST"&&o==="logout"){let n=chunkWPKBWXVR_js.h(t.headers.get("cookie"),a);return n&&await e.sessionStore.revoke(n),new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":chunkWPKBWXVR_js.g({...e.cookieOptions,name:a})}})}return new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(S){return console.error("[SIWX-SERVER] Durable Handler error:",S),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:c,POST:c,DELETE:c}}function P(e){if(!e?.signingSecret||e.signingSecret.length<32)throw new Error("[SIWX-SERVER] createStatelessDemoSiwxHandler requires a `signingSecret` of at least 32 characters.");let a=e.cookieOptions?.name||"siwx-session-v2",p=e.ttlSeconds??(e.cookieOptions?.maxAge||1800),l=e.demoLimits?.maxTransactionPayloadBytes??65536,c=async t=>{try{let d=new URL(t.url).pathname.split("/").filter(Boolean),o=d[d.length-1]||"";if(t.method==="GET"&&o==="session"){let n=chunkWPKBWXVR_js.h(t.headers.get("cookie"),a);if(!n)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let i=await chunkWPKBWXVR_js.e(n,e.signingSecret,e.policy);return new Response(JSON.stringify(i),{status:200,headers:{"Content-Type":"application/json"}})}if((t.method==="GET"||t.method==="POST")&&o==="nonce"){let n=siwxCore.generateNonce();return new Response(JSON.stringify({nonce:n}),{status:200,headers:{"Content-Type":"application/json"}})}if(t.method==="POST"&&o==="verify"){let n=t.headers.get("content-length");if(n&&parseInt(n,10)>l)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let i=await t.text();if(i.length>l)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let s;try{s=JSON.parse(i);}catch{return new Response(JSON.stringify({error:"Invalid JSON payload"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!s||typeof s.message!="string"||typeof s.signature!="string")return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let g={message:s.message,signature:s.signature},r=await chunkWPKBWXVR_js.c(g,{...e.verifyOptions,policy:e.policy});if(!r.success||!r.data)return new Response(JSON.stringify({error:r.error||"Verification failed"}),{status:401,headers:{"Content-Type":"application/json"}});let f=chunkWPKBWXVR_js.a(r.data),y=await chunkWPKBWXVR_js.d(f,e.signingSecret,p),w=chunkWPKBWXVR_js.f(y,{...e.cookieOptions,name:a,maxAge:p});return new Response(JSON.stringify(f),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":w}})}return t.method==="DELETE"&&o==="session"||t.method==="POST"&&o==="logout"?new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":chunkWPKBWXVR_js.g({...e.cookieOptions,name:a})}}):new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(S){return console.error("[SIWX-SERVER] Stateless Demo Handler error:",S),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:c,POST:c,DELETE:c}}Object.defineProperty(exports,"getSiwxServerSession",{enumerable:true,get:function(){return chunkWPKBWXVR_js.k}});exports.createSiwxApiHandler=j;exports.createStatelessDemoSiwxHandler=P;
package/dist/next.mjs CHANGED
@@ -1 +1 @@
1
- import {h,c,a,f,g,e,d}from'./chunk-WXHFSBDK.mjs';export{k as getSiwxServerSession}from'./chunk-WXHFSBDK.mjs';import {generateNonce}from'@tuwaio/siwx-core';function k(e){if(!e?.sessionStore||!e?.nonceStore)throw new Error("[SIWX-SERVER] createSiwxApiHandler requires both `sessionStore` and `nonceStore`. For zero-infrastructure demos without storage, use `createStatelessDemoSiwxHandler`.");let i=e.cookieOptions?.name||"siwx-session-v2",a$1=e.ttlSeconds??(e.cookieOptions?.maxAge||3600*24*7),r=async n=>{try{let p=new URL(n.url).pathname.split("/").filter(Boolean),o=p[p.length-1]||"";if(n.method==="GET"&&o==="session"){let t=h(n.headers.get("cookie"),i);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((n.method==="GET"||n.method==="POST")&&o==="nonce"){let t=generateNonce();return await e.nonceStore.issue({nonce:t,ttlSeconds:300}),new Response(JSON.stringify({nonce:t}),{status:200,headers:{"Content-Type":"application/json"}})}if(n.method==="POST"&&o==="verify"){let t=await n.json();if(!t.message||!t.signature)return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let s=await c(t,{...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 S=a(s.data),d=await e.sessionStore.create({session:S,ttlSeconds:a$1}),T=f(d.id,{...e.cookieOptions,name:i,maxAge:a$1});return new Response(JSON.stringify(S),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":T}})}if(n.method==="DELETE"&&o==="session"||n.method==="POST"&&o==="logout"){let t=h(n.headers.get("cookie"),i);return t&&await e.sessionStore.revoke(t),new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":g({...e.cookieOptions,name:i})}})}return new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(c){return console.error("[SIWX-SERVER] Durable Handler error:",c),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:r,POST:r,DELETE:r}}function E(e$1){if(!e$1?.signingSecret||e$1.signingSecret.length<32)throw new Error("[SIWX-SERVER] createStatelessDemoSiwxHandler requires a `signingSecret` of at least 32 characters.");let i=e$1.cookieOptions?.name||"siwx-session-v2",a$1=e$1.ttlSeconds??(e$1.cookieOptions?.maxAge||1800),r=async n=>{try{let p=new URL(n.url).pathname.split("/").filter(Boolean),o=p[p.length-1]||"";if(n.method==="GET"&&o==="session"){let t=h(n.headers.get("cookie"),i);if(!t)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let s=await e(t,e$1.signingSecret,e$1.policy);return new Response(JSON.stringify(s),{status:200,headers:{"Content-Type":"application/json"}})}if((n.method==="GET"||n.method==="POST")&&o==="nonce"){let t=generateNonce();return new Response(JSON.stringify({nonce:t}),{status:200,headers:{"Content-Type":"application/json"}})}if(n.method==="POST"&&o==="verify"){let t=await n.json();if(!t.message||!t.signature)return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let s=await c(t,{...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"}});let u=a(s.data),S=await d(u,e$1.signingSecret,a$1),d$1=f(S,{...e$1.cookieOptions,name:i,maxAge:a$1});return new Response(JSON.stringify(u),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":d$1}})}return n.method==="DELETE"&&o==="session"||n.method==="POST"&&o==="logout"?new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":g({...e$1.cookieOptions,name:i})}}):new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(c){return console.error("[SIWX-SERVER] Stateless Demo Handler error:",c),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:r,POST:r,DELETE:r}}export{k as createSiwxApiHandler,E as createStatelessDemoSiwxHandler};
1
+ import {h,c,a,f,g,e,d}from'./chunk-PBR725EL.mjs';export{k as getSiwxServerSession}from'./chunk-PBR725EL.mjs';import {generateNonce}from'@tuwaio/siwx-core';function j(e){if(!e?.sessionStore||!e?.nonceStore)throw new Error("[SIWX-SERVER] createSiwxApiHandler requires both `sessionStore` and `nonceStore`.");let a$1=e.cookieOptions?.name||"siwx-session-v2",p=e.ttlSeconds??(e.cookieOptions?.maxAge||3600*24*7),l=65536,c$1=async t=>{try{let d=new URL(t.url).pathname.split("/").filter(Boolean),o=d[d.length-1]||"";if(t.method==="GET"&&o==="session"){let n=h(t.headers.get("cookie"),a$1);if(!n)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let i=await e.sessionStore.get(n);return new Response(JSON.stringify(i?.session??null),{status:200,headers:{"Content-Type":"application/json"}})}if((t.method==="GET"||t.method==="POST")&&o==="nonce"){let n=generateNonce();return await e.nonceStore.issue({nonce:n,ttlSeconds:300}),new Response(JSON.stringify({nonce:n}),{status:200,headers:{"Content-Type":"application/json"}})}if(t.method==="POST"&&o==="verify"){let n=t.headers.get("content-length");if(n&&parseInt(n,10)>l)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let i=await t.text();if(i.length>l)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let s;try{s=JSON.parse(i);}catch{return new Response(JSON.stringify({error:"Invalid JSON payload"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!s||typeof s.message!="string"||typeof s.signature!="string")return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let g={message:s.message,signature:s.signature},r=await c(g,{...e.verifyOptions,policy:e.policy});if(!r.success||!r.data)return new Response(JSON.stringify({error:r.error||"Verification failed"}),{status:401,headers:{"Content-Type":"application/json"}});if(!await e.nonceStore.consume({nonce:r.data.nonce}))return new Response(JSON.stringify({error:"Nonce replay detected or nonce expired"}),{status:401,headers:{"Content-Type":"application/json"}});let y=a(r.data),w=await e.sessionStore.create({session:y,ttlSeconds:p}),x=f(w.id,{...e.cookieOptions,name:a$1,maxAge:p});return new Response(JSON.stringify(y),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":x}})}if(t.method==="DELETE"&&o==="session"||t.method==="POST"&&o==="logout"){let n=h(t.headers.get("cookie"),a$1);return n&&await e.sessionStore.revoke(n),new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":g({...e.cookieOptions,name:a$1})}})}return new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(S){return console.error("[SIWX-SERVER] Durable Handler error:",S),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:c$1,POST:c$1,DELETE:c$1}}function P(e$1){if(!e$1?.signingSecret||e$1.signingSecret.length<32)throw new Error("[SIWX-SERVER] createStatelessDemoSiwxHandler requires a `signingSecret` of at least 32 characters.");let a$1=e$1.cookieOptions?.name||"siwx-session-v2",p=e$1.ttlSeconds??(e$1.cookieOptions?.maxAge||1800),l=e$1.demoLimits?.maxTransactionPayloadBytes??65536,c$1=async t=>{try{let d$1=new URL(t.url).pathname.split("/").filter(Boolean),o=d$1[d$1.length-1]||"";if(t.method==="GET"&&o==="session"){let n=h(t.headers.get("cookie"),a$1);if(!n)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let i=await e(n,e$1.signingSecret,e$1.policy);return new Response(JSON.stringify(i),{status:200,headers:{"Content-Type":"application/json"}})}if((t.method==="GET"||t.method==="POST")&&o==="nonce"){let n=generateNonce();return new Response(JSON.stringify({nonce:n}),{status:200,headers:{"Content-Type":"application/json"}})}if(t.method==="POST"&&o==="verify"){let n=t.headers.get("content-length");if(n&&parseInt(n,10)>l)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let i=await t.text();if(i.length>l)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let s;try{s=JSON.parse(i);}catch{return new Response(JSON.stringify({error:"Invalid JSON payload"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!s||typeof s.message!="string"||typeof s.signature!="string")return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let g={message:s.message,signature:s.signature},r=await c(g,{...e$1.verifyOptions,policy:e$1.policy});if(!r.success||!r.data)return new Response(JSON.stringify({error:r.error||"Verification failed"}),{status:401,headers:{"Content-Type":"application/json"}});let f$1=a(r.data),y=await d(f$1,e$1.signingSecret,p),w=f(y,{...e$1.cookieOptions,name:a$1,maxAge:p});return new Response(JSON.stringify(f$1),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":w}})}return t.method==="DELETE"&&o==="session"||t.method==="POST"&&o==="logout"?new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":g({...e$1.cookieOptions,name:a$1})}}):new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(S){return console.error("[SIWX-SERVER] Stateless Demo Handler error:",S),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:c$1,POST:c$1,DELETE:c$1}}export{j as createSiwxApiHandler,P as createStatelessDemoSiwxHandler};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tuwaio/siwx-server",
3
- "version": "0.2.1",
3
+ "version": "1.0.0-feat-update-alpha.2.83013b6",
4
4
  "private": false,
5
5
  "author": "Oleksandr Tkach",
6
6
  "license": "Apache-2.0",
@@ -68,15 +68,15 @@
68
68
  }
69
69
  ],
70
70
  "peerDependencies": {
71
- "@tuwaio/siwx-core": "0.2.0"
71
+ "@tuwaio/siwx-core": "1.0.0-feat-update-alpha.2.83013b6"
72
72
  },
73
73
  "devDependencies": {
74
+ "@tuwaio/siwx-core": "1.0.0-feat-update-alpha.2.83013b6",
75
+ "@tuwaio/siwx-evm": "1.0.0-feat-update-alpha.2.83013b6",
76
+ "@tuwaio/siwx-solana": "1.0.0-feat-update-alpha.2.83013b6",
74
77
  "tsup": "^8.5.1",
75
- "typescript": "^6.0.3",
76
- "viem": "^2.55.11",
77
- "@tuwaio/siwx-core": "0.2.0",
78
- "@tuwaio/siwx-evm": "0.2.0",
79
- "@tuwaio/siwx-solana": "0.2.0"
78
+ "typescript": "6.0.3",
79
+ "viem": "^2.56.3"
80
80
  },
81
81
  "scripts": {
82
82
  "start": "tsup src/index.ts --watch",
@@ -1,2 +0,0 @@
1
- 'use strict';var siwxCore=require('@tuwaio/siwx-core');function v(i){return {address:i.address,chainId:i.chainId,domain:i.domain,nonce:i.nonce,issuedAt:i.issuedAt,expirationTime:i.expirationTime}}async function N(i,e={}){try{let n=siwxCore.parseMessage(i.message),t=siwxCore.validateMessage(n,{skipExpiration:e.skipExpiration,policy:e.policy});if(!t.valid)return {success:!1,error:`Validation failed: ${t.errors.join(", ")}`};if(!e.skipExpiration&&n.expirationTime&&new Date(n.expirationTime)<new Date)throw new siwxCore.SiwxExpiredSessionError(n.expirationTime);if(e.usedNonces?.has(n.nonce))throw new siwxCore.SiwxNonceReplayError(n.nonce);let s=n.chainId.split(":")[0];if(!s||!["eip155","solana"].includes(s))throw new siwxCore.SiwxUnsupportedNamespaceError(s??"unknown");if(s==="eip155"){let{verifyEvmSignature:r}=await import('@tuwaio/siwx-evm');return {...await r(i.message,i.signature,{skipExpiration:e.skipExpiration,publicClient:e.publicClient}),namespace:s}}if(s==="solana"){let{verifyEd25519:r}=await import('@tuwaio/siwx-solana');return {...await r(i,{skipExpiration:e.skipExpiration}),namespace:s}}return {success:!1,error:"Unsupported namespace."}}catch(n){return n instanceof siwxCore.SiwxExpiredSessionError||n instanceof siwxCore.SiwxNonceReplayError||n instanceof siwxCore.SiwxUnsupportedNamespaceError?{success:false,error:n.message}:{success:false,error:`Server verification failed: ${String(n)}`}}}function E(i){return btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function T(i){let e=i.replace(/-/g,"+").replace(/_/g,"/");return atob(e)}function A(i){let e="";for(let n=0;n<i.byteLength;n++)e+=String.fromCharCode(i[n]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function C(i){let e=i.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e),t=new Uint8Array(n.length);for(let s=0;s<n.length;s++)t[s]=n.charCodeAt(s);return t}async function b(i){let e=new TextEncoder;return globalThis.crypto.subtle.importKey("raw",e.encode(i),{name:"HMAC",hash:"SHA-256"},false,["sign","verify"])}async function O(i,e,n=1800){if(!e||e.length<32)throw new Error("[SIWX-SERVER] Stateless demo signing secret must be at least 32 characters long.");let s=Date.now()+n*1e3,r={version:1,address:i.address,chainId:i.chainId,domain:i.domain,nonce:i.nonce,issuedAt:i.issuedAt,expirationTime:i.expirationTime??new Date(s).toISOString(),sessionId:siwxCore.generateNonce(),mode:"demo"},a=JSON.stringify(r),o=E(a),l=await b(e),u=new TextEncoder,p=await globalThis.crypto.subtle.sign("HMAC",l,u.encode(o)),c=A(new Uint8Array(p));return `${o}.${c}`}async function D(i,e,n){if(!i||typeof i!="string"||!e)return null;let t=i.split(".");if(t.length!==2)return null;let[s,r]=t;try{let a=await b(e),o=C(r),l=new TextEncoder;if(!await globalThis.crypto.subtle.verify("HMAC",a,o,l.encode(s)))return null;let p=T(s),c=JSON.parse(p);if(c.version!==1||c.mode!=="demo")return null;if(c.expirationTime){let S=new Date(c.expirationTime).getTime(),f=(n?.clockSkewSeconds??60)*1e3;if(isNaN(S)||S+f<Date.now())return null}return n?.expectedDomain!==void 0&&!(Array.isArray(n.expectedDomain)?n.expectedDomain:[n.expectedDomain]).some(f=>f.toLowerCase()===c.domain.toLowerCase())||n?.allowedChainIds!==void 0&&n.allowedChainIds.length>0&&!n.allowedChainIds.includes(c.chainId)?null:{address:c.address,chainId:c.chainId,domain:c.domain,nonce:c.nonce,issuedAt:c.issuedAt,expirationTime:c.expirationTime}}catch{return null}}function $(i,e={}){let{name:n="siwx-session-v2",maxAge:t=3600*24*7,path:s="/",domain:r,secure:a=true,sameSite:o="Strict"}=e,l=[`${n}=${i}`,`Max-Age=${t}`,`Path=${s}`,"HttpOnly",`SameSite=${o}`];return a&&l.push("Secure"),r&&l.push(`Domain=${r}`),l.join("; ")}function j(i={}){let{name:e="siwx-session-v2",path:n="/",domain:t}=i,s=[`${e}=`,`Path=${n}`,"Expires=Thu, 01 Jan 1970 00:00:00 GMT","Max-Age=0","HttpOnly","SameSite=Strict"];return t&&s.push(`Domain=${t}`),s.join("; ")}function d(i,e){return i?Object.fromEntries(i.split("; ").filter(Boolean).map(t=>{let s=t.split("=");return [s[0].trim(),s.slice(1).join("=")]}))[e]??null:null}var w=class{records=new Map;constructor(e){if(typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV==="production"&&!e?.allowInProduction)throw new Error("[SIWX-SERVER] MemorySiwxSessionStore must not be used in production. Connect Redis or a durable store.")}async create(e){let n=siwxCore.generateNonce(),t=Date.now(),s=t+e.ttlSeconds*1e3,r={id:n,session:e.session,createdAt:t,expiresAt:s};return this.records.set(n,r),r}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 t=await this.get(e);return t?(t.subjectId=n,true):false}async revoke(e){this.records.delete(e);}},y=class{nonces=new Map;constructor(e){if(typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV==="production"&&!e?.allowInProduction)throw new Error("[SIWX-SERVER] MemorySiwxNonceStore must not be used in production. Connect Redis or a durable store.")}async issue(e){let n=Date.now()+e.ttlSeconds*1e3;this.nonces.set(e.nonce,n);}async consume(e){let n=this.nonces.get(e.nonce);return !(!n||(this.nonces.delete(e.nonce),n<Date.now()))}};async function B(i){let{cookieSource:e,cookieName:n="siwx-session-v2",sessionStore:t,signingSecret:s,policy:r}=i;if(!e)return null;let a=null;if(typeof e=="string")a=e.includes("=")?d(e,n):e;else if(typeof e.headers=="object"&&typeof e.headers?.get=="function"){let o=e.headers.get("cookie");a=d(o,n);}else if(typeof e.get=="function"){let o=e.get(n);if(o&&typeof o=="object"&&"value"in o)a=o.value;else if(typeof o=="string")a=o.includes("=")?d(o,n):o;else if(typeof e.get=="function"){let l=e.get("cookie");l&&(a=d(l,n));}}if(!a)return null;if(t){let o=await t.get(a);return !o?.session||r&&(r.expectedDomain!==void 0&&!(Array.isArray(r.expectedDomain)?r.expectedDomain:[r.expectedDomain]).some(u=>u.toLowerCase()===o.session.domain.toLowerCase())||r.allowedChainIds!==void 0&&r.allowedChainIds.length>0&&!r.allowedChainIds.includes(o.session.chainId)||r.requireExpirationTime&&!o.session.expirationTime)?null:o.session}return s?D(a,s,r):null}
2
- Object.defineProperty(exports,"b",{enumerable:true,get:function(){return siwxCore.generateNonce}});exports.a=v;exports.c=N;exports.d=O;exports.e=D;exports.f=$;exports.g=j;exports.h=d;exports.i=w;exports.j=y;exports.k=B;
@@ -1,2 +0,0 @@
1
- import {parseMessage,validateMessage,SiwxExpiredSessionError,SiwxNonceReplayError,SiwxUnsupportedNamespaceError,generateNonce}from'@tuwaio/siwx-core';export{generateNonce as b}from'@tuwaio/siwx-core';function v(i){return {address:i.address,chainId:i.chainId,domain:i.domain,nonce:i.nonce,issuedAt:i.issuedAt,expirationTime:i.expirationTime}}async function N(i,e={}){try{let n=parseMessage(i.message),t=validateMessage(n,{skipExpiration:e.skipExpiration,policy:e.policy});if(!t.valid)return {success:!1,error:`Validation failed: ${t.errors.join(", ")}`};if(!e.skipExpiration&&n.expirationTime&&new Date(n.expirationTime)<new Date)throw new SiwxExpiredSessionError(n.expirationTime);if(e.usedNonces?.has(n.nonce))throw new SiwxNonceReplayError(n.nonce);let s=n.chainId.split(":")[0];if(!s||!["eip155","solana"].includes(s))throw new SiwxUnsupportedNamespaceError(s??"unknown");if(s==="eip155"){let{verifyEvmSignature:r}=await import('@tuwaio/siwx-evm');return {...await r(i.message,i.signature,{skipExpiration:e.skipExpiration,publicClient:e.publicClient}),namespace:s}}if(s==="solana"){let{verifyEd25519:r}=await import('@tuwaio/siwx-solana');return {...await r(i,{skipExpiration:e.skipExpiration}),namespace:s}}return {success:!1,error:"Unsupported namespace."}}catch(n){return n instanceof SiwxExpiredSessionError||n instanceof SiwxNonceReplayError||n instanceof SiwxUnsupportedNamespaceError?{success:false,error:n.message}:{success:false,error:`Server verification failed: ${String(n)}`}}}function E(i){return btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function T(i){let e=i.replace(/-/g,"+").replace(/_/g,"/");return atob(e)}function A(i){let e="";for(let n=0;n<i.byteLength;n++)e+=String.fromCharCode(i[n]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function C(i){let e=i.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e),t=new Uint8Array(n.length);for(let s=0;s<n.length;s++)t[s]=n.charCodeAt(s);return t}async function b(i){let e=new TextEncoder;return globalThis.crypto.subtle.importKey("raw",e.encode(i),{name:"HMAC",hash:"SHA-256"},false,["sign","verify"])}async function O(i,e,n=1800){if(!e||e.length<32)throw new Error("[SIWX-SERVER] Stateless demo signing secret must be at least 32 characters long.");let s=Date.now()+n*1e3,r={version:1,address:i.address,chainId:i.chainId,domain:i.domain,nonce:i.nonce,issuedAt:i.issuedAt,expirationTime:i.expirationTime??new Date(s).toISOString(),sessionId:generateNonce(),mode:"demo"},a=JSON.stringify(r),o=E(a),l=await b(e),u=new TextEncoder,p=await globalThis.crypto.subtle.sign("HMAC",l,u.encode(o)),c=A(new Uint8Array(p));return `${o}.${c}`}async function D(i,e,n){if(!i||typeof i!="string"||!e)return null;let t=i.split(".");if(t.length!==2)return null;let[s,r]=t;try{let a=await b(e),o=C(r),l=new TextEncoder;if(!await globalThis.crypto.subtle.verify("HMAC",a,o,l.encode(s)))return null;let p=T(s),c=JSON.parse(p);if(c.version!==1||c.mode!=="demo")return null;if(c.expirationTime){let S=new Date(c.expirationTime).getTime(),f=(n?.clockSkewSeconds??60)*1e3;if(isNaN(S)||S+f<Date.now())return null}return n?.expectedDomain!==void 0&&!(Array.isArray(n.expectedDomain)?n.expectedDomain:[n.expectedDomain]).some(f=>f.toLowerCase()===c.domain.toLowerCase())||n?.allowedChainIds!==void 0&&n.allowedChainIds.length>0&&!n.allowedChainIds.includes(c.chainId)?null:{address:c.address,chainId:c.chainId,domain:c.domain,nonce:c.nonce,issuedAt:c.issuedAt,expirationTime:c.expirationTime}}catch{return null}}function $(i,e={}){let{name:n="siwx-session-v2",maxAge:t=3600*24*7,path:s="/",domain:r,secure:a=true,sameSite:o="Strict"}=e,l=[`${n}=${i}`,`Max-Age=${t}`,`Path=${s}`,"HttpOnly",`SameSite=${o}`];return a&&l.push("Secure"),r&&l.push(`Domain=${r}`),l.join("; ")}function j(i={}){let{name:e="siwx-session-v2",path:n="/",domain:t}=i,s=[`${e}=`,`Path=${n}`,"Expires=Thu, 01 Jan 1970 00:00:00 GMT","Max-Age=0","HttpOnly","SameSite=Strict"];return t&&s.push(`Domain=${t}`),s.join("; ")}function d(i,e){return i?Object.fromEntries(i.split("; ").filter(Boolean).map(t=>{let s=t.split("=");return [s[0].trim(),s.slice(1).join("=")]}))[e]??null:null}var w=class{records=new Map;constructor(e){if(typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV==="production"&&!e?.allowInProduction)throw new Error("[SIWX-SERVER] MemorySiwxSessionStore must not be used in production. Connect Redis or a durable store.")}async create(e){let n=generateNonce(),t=Date.now(),s=t+e.ttlSeconds*1e3,r={id:n,session:e.session,createdAt:t,expiresAt:s};return this.records.set(n,r),r}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 t=await this.get(e);return t?(t.subjectId=n,true):false}async revoke(e){this.records.delete(e);}},y=class{nonces=new Map;constructor(e){if(typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV==="production"&&!e?.allowInProduction)throw new Error("[SIWX-SERVER] MemorySiwxNonceStore must not be used in production. Connect Redis or a durable store.")}async issue(e){let n=Date.now()+e.ttlSeconds*1e3;this.nonces.set(e.nonce,n);}async consume(e){let n=this.nonces.get(e.nonce);return !(!n||(this.nonces.delete(e.nonce),n<Date.now()))}};async function B(i){let{cookieSource:e,cookieName:n="siwx-session-v2",sessionStore:t,signingSecret:s,policy:r}=i;if(!e)return null;let a=null;if(typeof e=="string")a=e.includes("=")?d(e,n):e;else if(typeof e.headers=="object"&&typeof e.headers?.get=="function"){let o=e.headers.get("cookie");a=d(o,n);}else if(typeof e.get=="function"){let o=e.get(n);if(o&&typeof o=="object"&&"value"in o)a=o.value;else if(typeof o=="string")a=o.includes("=")?d(o,n):o;else if(typeof e.get=="function"){let l=e.get("cookie");l&&(a=d(l,n));}}if(!a)return null;if(t){let o=await t.get(a);return !o?.session||r&&(r.expectedDomain!==void 0&&!(Array.isArray(r.expectedDomain)?r.expectedDomain:[r.expectedDomain]).some(u=>u.toLowerCase()===o.session.domain.toLowerCase())||r.allowedChainIds!==void 0&&r.allowedChainIds.length>0&&!r.allowedChainIds.includes(o.session.chainId)||r.requireExpirationTime&&!o.session.expirationTime)?null:o.session}return s?D(a,s,r):null}
2
- export{v as a,N as c,O as d,D as e,$ as f,j as g,d as h,w as i,y as j,B as k};