@tuwaio/siwx-server 0.4.2 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/chunk-NXEEBKUG.js +2 -0
- package/dist/chunk-VTRW27M2.mjs +2 -0
- package/dist/index.d.mts +6 -3
- package/dist/index.d.ts +6 -3
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/next.js +1 -1
- package/dist/next.mjs +1 -1
- package/package.json +7 -7
- package/dist/chunk-AEFOZH2W.mjs +0 -2
- package/dist/chunk-SS5KJYWU.js +0 -2
package/README.md
CHANGED
|
@@ -113,7 +113,7 @@ export const { GET, POST, DELETE } = createSiwxApiHandler({
|
|
|
113
113
|
policy: {
|
|
114
114
|
expectedDomain: 'app.tuwa.io',
|
|
115
115
|
expectedUri: 'https://app.tuwa.io',
|
|
116
|
-
allowedChainIds: ['eip155:1', 'solana:
|
|
116
|
+
allowedChainIds: ['eip155:1', 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp'],
|
|
117
117
|
requireExpirationTime: true,
|
|
118
118
|
maxIssuedAtAgeSeconds: 300,
|
|
119
119
|
},
|
|
@@ -227,7 +227,7 @@ export async function handleVerify(request: Request): Promise<Response> {
|
|
|
227
227
|
- **Nonce:** a signature proves ownership only if its nonce is fresh. Both handlers accept a nonce only if it was issued by `/nonce` in the last 300 seconds, and only once. The durable handler consumes it in your `SiwxNonceStore`, whose `consume` must be atomic and shared by every instance; the demo handler checks the nonce signature and remembers used nonces per instance. `verifySiwxPayload` alone checks nothing but the optional `usedNonces` set.
|
|
228
228
|
- **Domain and URI:** without `policy.expectedDomain`, a message signed for another site is accepted. Always set `expectedDomain` (case-insensitive exact match) and, if possible, `expectedUri` (same origin or a sub-path).
|
|
229
229
|
- **Expiry:** messages are rejected once their `expirationTime` has passed, with the same `clockSkewSeconds` tolerance as the other timing rules (60 seconds by default; set `0` for none). Set `requireExpirationTime`, `maxSessionLifetimeSeconds` and `maxIssuedAtAgeSeconds`; the last one has no default, so stale messages are accepted until you set it. Durable sessions expire through the store: `SiwxSessionStore.get` must return `null` for expired records.
|
|
230
|
-
- **Chains:** `allowedChainIds` entries are full CAIP-2 IDs matched exactly, both when a message is verified and in `getSiwxServerSession`, so `eip155:1` never allows `solana:1`.
|
|
230
|
+
- **Chains:** `allowedChainIds` entries are full CAIP-2 IDs matched exactly, both when a message is verified and in `getSiwxServerSession`, so `eip155:1` never allows `solana:1`. A Solana cluster matches under its name and its genesis-hash ID: with `solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1` allowed, sessions signed for `solana:devnet` stay valid.
|
|
231
231
|
- **Server-side checks:** `getSiwxServerSession` applies only `expectedDomain` and `allowedChainIds` of its `policy`, plus `requireExpirationTime` for durable sessions and the token expiry for demo sessions. The full policy runs when the message is verified.
|
|
232
232
|
- **Cookies:** the session cookie is always `HttpOnly`, and `Secure` and `SameSite=Strict` by default. Keep `secure: true` in production.
|
|
233
233
|
- **Secrets:** the demo `signingSecret` must be at least 32 characters and must never reach the browser. Changing it invalidates every demo session.
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var siwxCore=require('@tuwaio/siwx-core');function P(t){return {address:t.address,chainId:t.chainId,domain:t.domain,nonce:t.nonce,issuedAt:t.issuedAt,expirationTime:t.expirationTime}}async function j(t,e={}){try{let n=siwxCore.parseMessage(t.message),s=siwxCore.validateMessage(n,{skipExpiration:e.skipExpiration,policy:e.policy});if(!s.valid)return {success:!1,error:`Validation failed: ${s.errors.join(", ")}`};if(e.usedNonces?.has(n.nonce))throw new siwxCore.SiwxNonceReplayError(n.nonce);let i=n.chainId.split(":")[0];if(!i||!["eip155","solana"].includes(i))throw new siwxCore.SiwxUnsupportedNamespaceError(i??"unknown");if(i==="eip155"){let{verifyEvmSignature:r}=await import('@tuwaio/siwx-evm');return {...await r(t.message,t.signature,{skipExpiration:e.skipExpiration,publicClient:e.publicClient}),namespace:i}}if(i==="solana"){let{verifyEd25519:r}=await import('@tuwaio/siwx-solana');return {...await r(t,{skipExpiration:e.skipExpiration}),namespace:i}}return {success:!1,error:"Unsupported namespace."}}catch(n){return n instanceof siwxCore.SiwxNonceReplayError||n instanceof siwxCore.SiwxUnsupportedNamespaceError?{success:false,error:n.message}:{success:false,error:`Server verification failed: ${String(n)}`}}}function D(t){return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function N(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return atob(e)}function C(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 I(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e),s=new Uint8Array(n.length);for(let i=0;i<n.length;i++)s[i]=n.charCodeAt(i);return s}async function p(t){let e=new TextEncoder;return globalThis.crypto.subtle.importKey("raw",e.encode(t),{name:"HMAC",hash:"SHA-256"},false,["sign","verify"])}async function U(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 i=Date.now()+n*1e3,r={version:1,address:t.address,chainId:t.chainId,domain:t.domain,nonce:t.nonce,issuedAt:t.issuedAt,expirationTime:t.expirationTime??new Date(i).toISOString(),sessionId:siwxCore.generateNonce(),mode:"demo"},a=JSON.stringify(r),o=D(a),l=await p(e),u=new TextEncoder,f=await globalThis.crypto.subtle.sign("HMAC",l,u.encode(o)),c=C(new Uint8Array(f));return `${o}.${c}`}async function R(t,e,n){if(!t||typeof t!="string"||!e)return null;let s=t.split(".");if(s.length!==2)return null;let[i,r]=s;try{let a=await p(e),o=I(r),l=new TextEncoder;if(!await globalThis.crypto.subtle.verify("HMAC",a,o,l.encode(i)))return null;let f=N(i),c=JSON.parse(f);if(c.version!==1||c.mode!=="demo")return null;if(c.expirationTime){let g=new Date(c.expirationTime).getTime(),S=(n?.clockSkewSeconds??60)*1e3;if(isNaN(g)||g+S<Date.now())return null}return n?.expectedDomain!==void 0&&!(Array.isArray(n.expectedDomain)?n.expectedDomain:[n.expectedDomain]).some(S=>S.toLowerCase()===c.domain.toLowerCase())||!siwxCore.isChainIdAllowed(c.chainId,n?.allowedChainIds)?null:{address:c.address,chainId:c.chainId,domain:c.domain,nonce:c.nonce,issuedAt:c.issuedAt,expirationTime:c.expirationTime}}catch{return null}}var A="siwx-demo-nonce:",y=32,v=10,O=/^[0-9a-f]{106}$/;function V(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function M(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 H(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,s=siwxCore.generateNonce()+n.toString(16).padStart(v,"0"),i=await p(t),r=await globalThis.crypto.subtle.sign("HMAC",i,new TextEncoder().encode(A+s));return s+V(new Uint8Array(r))}async function L(t,e){if(typeof t!="string"||!e||!O.test(t))return false;let n=y+v,s=t.slice(0,n),i=t.slice(n);try{let r=await p(e);return await globalThis.crypto.subtle.verify("HMAC",r,M(i),new TextEncoder().encode(A+s))?parseInt(s.slice(y),16)*1e3>=Date.now():!1}catch{return false}}function G(t,e={}){let{name:n="siwx-session-v2",maxAge:s=3600*24*7,path:i="/",domain:r,secure:a=true,sameSite:o="Strict"}=e,l=[`${n}=${t}`,`Max-Age=${s}`,`Path=${i}`,"HttpOnly",`SameSite=${o}`];return a&&l.push("Secure"),r&&l.push(`Domain=${r}`),l.join("; ")}function X(t={}){let{name:e="siwx-session-v2",path:n="/",domain:s,secure:i=true,sameSite:r="Strict"}=t,a=[`${e}=`,`Path=${n}`,"Expires=Thu, 01 Jan 1970 00:00:00 GMT","Max-Age=0","HttpOnly",`SameSite=${r}`];return i&&a.push("Secure"),s&&a.push(`Domain=${s}`),a.join("; ")}function d(t,e){return t?Object.fromEntries(t.split("; ").filter(Boolean).map(s=>{let i=s.split("=");return [i[0].trim(),i.slice(1).join("=")]}))[e]??null:null}var h=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(),s=Date.now(),i=s+e.ttlSeconds*1e3,r={id:n,session:e.session,createdAt:s,expiresAt:i};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 s=await this.get(e);return s?(s.subjectId=n,true):false}async revoke(e){this.records.delete(e);}},b=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 q(t){let{cookieSource:e,cookieName:n="siwx-session-v2",sessionStore:s,signingSecret:i,policy:r}=t;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(s){let o=await s.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())||!siwxCore.isChainIdAllowed(o.session.chainId,r.allowedChainIds)||r.requireExpirationTime&&!o.session.expirationTime)?null:o.session}return i?R(a,i,r):null}
|
|
2
|
+
Object.defineProperty(exports,"b",{enumerable:true,get:function(){return siwxCore.generateNonce}});exports.a=P;exports.c=j;exports.d=U;exports.e=R;exports.f=H;exports.g=L;exports.h=G;exports.i=X;exports.j=d;exports.k=h;exports.l=b;exports.m=q;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {parseMessage,validateMessage,SiwxNonceReplayError,SiwxUnsupportedNamespaceError,generateNonce,isChainIdAllowed}from'@tuwaio/siwx-core';export{generateNonce as b}from'@tuwaio/siwx-core';function P(t){return {address:t.address,chainId:t.chainId,domain:t.domain,nonce:t.nonce,issuedAt:t.issuedAt,expirationTime:t.expirationTime}}async function j(t,e={}){try{let n=parseMessage(t.message),s=validateMessage(n,{skipExpiration:e.skipExpiration,policy:e.policy});if(!s.valid)return {success:!1,error:`Validation failed: ${s.errors.join(", ")}`};if(e.usedNonces?.has(n.nonce))throw new SiwxNonceReplayError(n.nonce);let i=n.chainId.split(":")[0];if(!i||!["eip155","solana"].includes(i))throw new SiwxUnsupportedNamespaceError(i??"unknown");if(i==="eip155"){let{verifyEvmSignature:r}=await import('@tuwaio/siwx-evm');return {...await r(t.message,t.signature,{skipExpiration:e.skipExpiration,publicClient:e.publicClient}),namespace:i}}if(i==="solana"){let{verifyEd25519:r}=await import('@tuwaio/siwx-solana');return {...await r(t,{skipExpiration:e.skipExpiration}),namespace:i}}return {success:!1,error:"Unsupported namespace."}}catch(n){return n instanceof SiwxNonceReplayError||n instanceof SiwxUnsupportedNamespaceError?{success:false,error:n.message}:{success:false,error:`Server verification failed: ${String(n)}`}}}function D(t){return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function N(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return atob(e)}function C(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 I(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e),s=new Uint8Array(n.length);for(let i=0;i<n.length;i++)s[i]=n.charCodeAt(i);return s}async function p(t){let e=new TextEncoder;return globalThis.crypto.subtle.importKey("raw",e.encode(t),{name:"HMAC",hash:"SHA-256"},false,["sign","verify"])}async function U(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 i=Date.now()+n*1e3,r={version:1,address:t.address,chainId:t.chainId,domain:t.domain,nonce:t.nonce,issuedAt:t.issuedAt,expirationTime:t.expirationTime??new Date(i).toISOString(),sessionId:generateNonce(),mode:"demo"},a=JSON.stringify(r),o=D(a),l=await p(e),u=new TextEncoder,f=await globalThis.crypto.subtle.sign("HMAC",l,u.encode(o)),c=C(new Uint8Array(f));return `${o}.${c}`}async function R(t,e,n){if(!t||typeof t!="string"||!e)return null;let s=t.split(".");if(s.length!==2)return null;let[i,r]=s;try{let a=await p(e),o=I(r),l=new TextEncoder;if(!await globalThis.crypto.subtle.verify("HMAC",a,o,l.encode(i)))return null;let f=N(i),c=JSON.parse(f);if(c.version!==1||c.mode!=="demo")return null;if(c.expirationTime){let g=new Date(c.expirationTime).getTime(),S=(n?.clockSkewSeconds??60)*1e3;if(isNaN(g)||g+S<Date.now())return null}return n?.expectedDomain!==void 0&&!(Array.isArray(n.expectedDomain)?n.expectedDomain:[n.expectedDomain]).some(S=>S.toLowerCase()===c.domain.toLowerCase())||!isChainIdAllowed(c.chainId,n?.allowedChainIds)?null:{address:c.address,chainId:c.chainId,domain:c.domain,nonce:c.nonce,issuedAt:c.issuedAt,expirationTime:c.expirationTime}}catch{return null}}var A="siwx-demo-nonce:",y=32,v=10,O=/^[0-9a-f]{106}$/;function V(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function M(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 H(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,s=generateNonce()+n.toString(16).padStart(v,"0"),i=await p(t),r=await globalThis.crypto.subtle.sign("HMAC",i,new TextEncoder().encode(A+s));return s+V(new Uint8Array(r))}async function L(t,e){if(typeof t!="string"||!e||!O.test(t))return false;let n=y+v,s=t.slice(0,n),i=t.slice(n);try{let r=await p(e);return await globalThis.crypto.subtle.verify("HMAC",r,M(i),new TextEncoder().encode(A+s))?parseInt(s.slice(y),16)*1e3>=Date.now():!1}catch{return false}}function G(t,e={}){let{name:n="siwx-session-v2",maxAge:s=3600*24*7,path:i="/",domain:r,secure:a=true,sameSite:o="Strict"}=e,l=[`${n}=${t}`,`Max-Age=${s}`,`Path=${i}`,"HttpOnly",`SameSite=${o}`];return a&&l.push("Secure"),r&&l.push(`Domain=${r}`),l.join("; ")}function X(t={}){let{name:e="siwx-session-v2",path:n="/",domain:s,secure:i=true,sameSite:r="Strict"}=t,a=[`${e}=`,`Path=${n}`,"Expires=Thu, 01 Jan 1970 00:00:00 GMT","Max-Age=0","HttpOnly",`SameSite=${r}`];return i&&a.push("Secure"),s&&a.push(`Domain=${s}`),a.join("; ")}function d(t,e){return t?Object.fromEntries(t.split("; ").filter(Boolean).map(s=>{let i=s.split("=");return [i[0].trim(),i.slice(1).join("=")]}))[e]??null:null}var h=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(),s=Date.now(),i=s+e.ttlSeconds*1e3,r={id:n,session:e.session,createdAt:s,expiresAt:i};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 s=await this.get(e);return s?(s.subjectId=n,true):false}async revoke(e){this.records.delete(e);}},b=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 q(t){let{cookieSource:e,cookieName:n="siwx-session-v2",sessionStore:s,signingSecret:i,policy:r}=t;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(s){let o=await s.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())||!isChainIdAllowed(o.session.chainId,r.allowedChainIds)||r.requireExpirationTime&&!o.session.expirationTime)?null:o.session}return i?R(a,i,r):null}
|
|
2
|
+
export{P as a,j as c,U as d,R as e,H as f,L as g,G as h,X as i,d as j,h as k,b as l,q as m};
|
package/dist/index.d.mts
CHANGED
|
@@ -248,7 +248,9 @@ interface GetSiwxServerSessionOptions {
|
|
|
248
248
|
signingSecret?: string;
|
|
249
249
|
/**
|
|
250
250
|
* Policy checked against the stored session. Only a subset applies: `expectedDomain`, `allowedChainIds` (exact
|
|
251
|
-
* match
|
|
251
|
+
* match, except that a Solana cluster matches under its name and its genesis-hash chain ID, so sessions signed for
|
|
252
|
+
* `solana:devnet` stay valid) and, for durable sessions, `requireExpirationTime`; for demo tokens, expiry with
|
|
253
|
+
* `clockSkewSeconds`.
|
|
252
254
|
*/
|
|
253
255
|
policy?: SiwxVerificationPolicy;
|
|
254
256
|
}
|
|
@@ -297,8 +299,9 @@ declare function signStatelessDemoSession(session: SiwxSession, secret: string,
|
|
|
297
299
|
* Verifies a token created by {@link signStatelessDemoSession}: checks the HMAC signature with Web Crypto, the
|
|
298
300
|
* token version and mode, and its expiry (with `policy.clockSkewSeconds`, 60 seconds by default).
|
|
299
301
|
*
|
|
300
|
-
* Only `expectedDomain` and `allowedChainIds` (exact match
|
|
301
|
-
* ignored because they were checked when the
|
|
302
|
+
* Only `expectedDomain` and `allowedChainIds` (exact match, except that a Solana cluster matches under its name and its
|
|
303
|
+
* genesis-hash chain ID) of the policy are applied; other policy fields are ignored because they were checked when the
|
|
304
|
+
* token was issued.
|
|
302
305
|
*
|
|
303
306
|
* @param token - The token from the session cookie.
|
|
304
307
|
* @param secret - The secret the token was signed with.
|
package/dist/index.d.ts
CHANGED
|
@@ -248,7 +248,9 @@ interface GetSiwxServerSessionOptions {
|
|
|
248
248
|
signingSecret?: string;
|
|
249
249
|
/**
|
|
250
250
|
* Policy checked against the stored session. Only a subset applies: `expectedDomain`, `allowedChainIds` (exact
|
|
251
|
-
* match
|
|
251
|
+
* match, except that a Solana cluster matches under its name and its genesis-hash chain ID, so sessions signed for
|
|
252
|
+
* `solana:devnet` stay valid) and, for durable sessions, `requireExpirationTime`; for demo tokens, expiry with
|
|
253
|
+
* `clockSkewSeconds`.
|
|
252
254
|
*/
|
|
253
255
|
policy?: SiwxVerificationPolicy;
|
|
254
256
|
}
|
|
@@ -297,8 +299,9 @@ declare function signStatelessDemoSession(session: SiwxSession, secret: string,
|
|
|
297
299
|
* Verifies a token created by {@link signStatelessDemoSession}: checks the HMAC signature with Web Crypto, the
|
|
298
300
|
* token version and mode, and its expiry (with `policy.clockSkewSeconds`, 60 seconds by default).
|
|
299
301
|
*
|
|
300
|
-
* Only `expectedDomain` and `allowedChainIds` (exact match
|
|
301
|
-
* ignored because they were checked when the
|
|
302
|
+
* Only `expectedDomain` and `allowedChainIds` (exact match, except that a Solana cluster matches under its name and its
|
|
303
|
+
* genesis-hash chain ID) of the policy are applied; other policy fields are ignored because they were checked when the
|
|
304
|
+
* token was issued.
|
|
302
305
|
*
|
|
303
306
|
* @param token - The token from the session cookie.
|
|
304
307
|
* @param secret - The secret the token was signed with.
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkNXEEBKUG_js=require('./chunk-NXEEBKUG.js'),siwxCore=require('@tuwaio/siwx-core');Object.defineProperty(exports,"MemorySiwxNonceStore",{enumerable:true,get:function(){return chunkNXEEBKUG_js.l}});Object.defineProperty(exports,"MemorySiwxSessionStore",{enumerable:true,get:function(){return chunkNXEEBKUG_js.k}});Object.defineProperty(exports,"createClearCookie",{enumerable:true,get:function(){return chunkNXEEBKUG_js.i}});Object.defineProperty(exports,"createSessionCookie",{enumerable:true,get:function(){return chunkNXEEBKUG_js.h}});Object.defineProperty(exports,"generateServerNonce",{enumerable:true,get:function(){return chunkNXEEBKUG_js.b}});Object.defineProperty(exports,"getSiwxServerSession",{enumerable:true,get:function(){return chunkNXEEBKUG_js.m}});Object.defineProperty(exports,"issueStatelessDemoNonce",{enumerable:true,get:function(){return chunkNXEEBKUG_js.f}});Object.defineProperty(exports,"parseCookie",{enumerable:true,get:function(){return chunkNXEEBKUG_js.j}});Object.defineProperty(exports,"signStatelessDemoSession",{enumerable:true,get:function(){return chunkNXEEBKUG_js.d}});Object.defineProperty(exports,"toSession",{enumerable:true,get:function(){return chunkNXEEBKUG_js.a}});Object.defineProperty(exports,"verifySiwxPayload",{enumerable:true,get:function(){return chunkNXEEBKUG_js.c}});Object.defineProperty(exports,"verifyStatelessDemoNonce",{enumerable:true,get:function(){return chunkNXEEBKUG_js.g}});Object.defineProperty(exports,"verifyStatelessDemoSession",{enumerable:true,get:function(){return chunkNXEEBKUG_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{l as MemorySiwxNonceStore,k as MemorySiwxSessionStore,i as createClearCookie,h as createSessionCookie,b as generateServerNonce,m as getSiwxServerSession,f as issueStatelessDemoNonce,j as parseCookie,d as signStatelessDemoSession,a as toSession,c as verifySiwxPayload,g as verifyStatelessDemoNonce,e as verifyStatelessDemoSession}from'./chunk-
|
|
1
|
+
export{l as MemorySiwxNonceStore,k as MemorySiwxSessionStore,i as createClearCookie,h as createSessionCookie,b as generateServerNonce,m as getSiwxServerSession,f as issueStatelessDemoNonce,j as parseCookie,d as signStatelessDemoSession,a as toSession,c as verifySiwxPayload,g as verifyStatelessDemoNonce,e as verifyStatelessDemoSession}from'./chunk-VTRW27M2.mjs';export{generateNonce,isSessionMatchingTarget,validateMessage,validatePolicy}from'@tuwaio/siwx-core';
|
package/dist/next.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkNXEEBKUG_js=require('./chunk-NXEEBKUG.js'),siwxCore=require('@tuwaio/siwx-core');var T=300;function H(e){if(!e?.sessionStore||!e?.nonceStore)throw new Error("[SIWX-SERVER] createSiwxApiHandler requires both `sessionStore` and `nonceStore`.");let p=e.cookieOptions?.name||"siwx-session-v2",u=e.ttlSeconds??(e.cookieOptions?.maxAge||3600*24*7),y=65536,l=async o=>{try{let t=new URL(o.url).pathname.split("/").filter(Boolean),a=t[t.length-1]||"";if(o.method==="GET"&&a==="session"){let n=chunkNXEEBKUG_js.j(o.headers.get("cookie"),p);if(!n)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let r=await e.sessionStore.get(n);return new Response(JSON.stringify(r?.session??null),{status:200,headers:{"Content-Type":"application/json"}})}if((o.method==="GET"||o.method==="POST")&&a==="nonce"){let n=siwxCore.generateNonce();return await e.nonceStore.issue({nonce:n,ttlSeconds:T}),new Response(JSON.stringify({nonce:n}),{status:200,headers:{"Content-Type":"application/json"}})}if(o.method==="POST"&&a==="verify"){let n=o.headers.get("content-length");if(n&&parseInt(n,10)>y)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let r=await o.text();if(r.length>y)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let s;try{s=JSON.parse(r);}catch{return new Response(JSON.stringify({error:"Invalid JSON payload"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!s||typeof s.message!="string"||typeof s.signature!="string")return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let d={message:s.message,signature:s.signature},i=await chunkNXEEBKUG_js.c(d,{...e.verifyOptions,policy:e.policy});if(!i.success||!i.data)return new Response(JSON.stringify({error:i.error||"Verification failed"}),{status:401,headers:{"Content-Type":"application/json"}});if(!await e.nonceStore.consume({nonce:i.data.nonce}))return new Response(JSON.stringify({error:"Nonce replay detected or nonce expired"}),{status:401,headers:{"Content-Type":"application/json"}});let c=chunkNXEEBKUG_js.a(i.data),C=await e.sessionStore.create({session:c,ttlSeconds:u}),g=chunkNXEEBKUG_js.h(C.id,{...e.cookieOptions,name:p,maxAge:u});return new Response(JSON.stringify(c),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":g}})}if(o.method==="DELETE"&&a==="session"||o.method==="POST"&&a==="logout"){let n=chunkNXEEBKUG_js.j(o.headers.get("cookie"),p);return n&&await e.sessionStore.revoke(n),new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":chunkNXEEBKUG_js.i({...e.cookieOptions,name:p})}})}return new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(S){return console.error("[SIWX-SERVER] Durable Handler error:",S),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:l,POST:l,DELETE:l}}function V(e){if(!e?.signingSecret||e.signingSecret.length<32)throw new Error("[SIWX-SERVER] createStatelessDemoSiwxHandler requires a `signingSecret` of at least 32 characters.");let p=e.cookieOptions?.name||"siwx-session-v2",u=e.ttlSeconds??(e.cookieOptions?.maxAge||1800),y=e.demoLimits?.maxTransactionPayloadBytes??65536,l=new Map,o=t=>{let a=Date.now();for(let[n,r]of l)r<a&&l.delete(n);return l.has(t)?false:(l.set(t,a+T*1e3),true)},S=async t=>{try{let n=new URL(t.url).pathname.split("/").filter(Boolean),r=n[n.length-1]||"";if(t.method==="GET"&&r==="session"){let s=chunkNXEEBKUG_js.j(t.headers.get("cookie"),p);if(!s)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let d=await chunkNXEEBKUG_js.e(s,e.signingSecret,e.policy);return new Response(JSON.stringify(d),{status:200,headers:{"Content-Type":"application/json"}})}if((t.method==="GET"||t.method==="POST")&&r==="nonce"){let s=await chunkNXEEBKUG_js.f(e.signingSecret,T);return new Response(JSON.stringify({nonce:s}),{status:200,headers:{"Content-Type":"application/json"}})}if(t.method==="POST"&&r==="verify"){let s=t.headers.get("content-length");if(s&&parseInt(s,10)>y)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let d=await t.text();if(d.length>y)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let i;try{i=JSON.parse(d);}catch{return new Response(JSON.stringify({error:"Invalid JSON payload"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!i||typeof i.message!="string"||typeof i.signature!="string")return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let N={message:i.message,signature:i.signature},c=await chunkNXEEBKUG_js.c(N,{...e.verifyOptions,policy:e.policy});if(!c.success||!c.data)return new Response(JSON.stringify({error:c.error||"Verification failed"}),{status:401,headers:{"Content-Type":"application/json"}});if(!await chunkNXEEBKUG_js.g(c.data.nonce,e.signingSecret)||!o(c.data.nonce))return new Response(JSON.stringify({error:"Nonce replay detected or nonce expired"}),{status:401,headers:{"Content-Type":"application/json"}});let g=chunkNXEEBKUG_js.a(c.data),J=await chunkNXEEBKUG_js.d(g,e.signingSecret,u),j=chunkNXEEBKUG_js.h(J,{...e.cookieOptions,name:p,maxAge:u});return new Response(JSON.stringify(g),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":j}})}return t.method==="DELETE"&&r==="session"||t.method==="POST"&&r==="logout"?new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":chunkNXEEBKUG_js.i({...e.cookieOptions,name:p})}}):new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(a){return console.error("[SIWX-SERVER] Stateless Demo Handler error:",a),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:S,POST:S,DELETE:S}}Object.defineProperty(exports,"getSiwxServerSession",{enumerable:true,get:function(){return chunkNXEEBKUG_js.m}});exports.createSiwxApiHandler=H;exports.createStatelessDemoSiwxHandler=V;
|
package/dist/next.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {j,c,a,h,i,e,f,g,d}from'./chunk-
|
|
1
|
+
import {j,c,a,h,i,e,f,g,d}from'./chunk-VTRW27M2.mjs';export{m as getSiwxServerSession}from'./chunk-VTRW27M2.mjs';import {generateNonce}from'@tuwaio/siwx-core';var T=300;function H(e){if(!e?.sessionStore||!e?.nonceStore)throw new Error("[SIWX-SERVER] createSiwxApiHandler requires both `sessionStore` and `nonceStore`.");let p=e.cookieOptions?.name||"siwx-session-v2",u=e.ttlSeconds??(e.cookieOptions?.maxAge||3600*24*7),y=65536,l=async o=>{try{let t=new URL(o.url).pathname.split("/").filter(Boolean),a$1=t[t.length-1]||"";if(o.method==="GET"&&a$1==="session"){let n=j(o.headers.get("cookie"),p);if(!n)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let r=await e.sessionStore.get(n);return new Response(JSON.stringify(r?.session??null),{status:200,headers:{"Content-Type":"application/json"}})}if((o.method==="GET"||o.method==="POST")&&a$1==="nonce"){let n=generateNonce();return await e.nonceStore.issue({nonce:n,ttlSeconds:T}),new Response(JSON.stringify({nonce:n}),{status:200,headers:{"Content-Type":"application/json"}})}if(o.method==="POST"&&a$1==="verify"){let n=o.headers.get("content-length");if(n&&parseInt(n,10)>y)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let r=await o.text();if(r.length>y)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let s;try{s=JSON.parse(r);}catch{return new Response(JSON.stringify({error:"Invalid JSON payload"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!s||typeof s.message!="string"||typeof s.signature!="string")return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let d={message:s.message,signature:s.signature},i=await c(d,{...e.verifyOptions,policy:e.policy});if(!i.success||!i.data)return new Response(JSON.stringify({error:i.error||"Verification failed"}),{status:401,headers:{"Content-Type":"application/json"}});if(!await e.nonceStore.consume({nonce:i.data.nonce}))return new Response(JSON.stringify({error:"Nonce replay detected or nonce expired"}),{status:401,headers:{"Content-Type":"application/json"}});let c$1=a(i.data),C=await e.sessionStore.create({session:c$1,ttlSeconds:u}),g=h(C.id,{...e.cookieOptions,name:p,maxAge:u});return new Response(JSON.stringify(c$1),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":g}})}if(o.method==="DELETE"&&a$1==="session"||o.method==="POST"&&a$1==="logout"){let n=j(o.headers.get("cookie"),p);return n&&await e.sessionStore.revoke(n),new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":i({...e.cookieOptions,name:p})}})}return new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(S){return console.error("[SIWX-SERVER] Durable Handler error:",S),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:l,POST:l,DELETE:l}}function V(e$1){if(!e$1?.signingSecret||e$1.signingSecret.length<32)throw new Error("[SIWX-SERVER] createStatelessDemoSiwxHandler requires a `signingSecret` of at least 32 characters.");let p=e$1.cookieOptions?.name||"siwx-session-v2",u=e$1.ttlSeconds??(e$1.cookieOptions?.maxAge||1800),y=e$1.demoLimits?.maxTransactionPayloadBytes??65536,l=new Map,o=t=>{let a=Date.now();for(let[n,r]of l)r<a&&l.delete(n);return l.has(t)?false:(l.set(t,a+T*1e3),true)},S=async t=>{try{let n=new URL(t.url).pathname.split("/").filter(Boolean),r=n[n.length-1]||"";if(t.method==="GET"&&r==="session"){let s=j(t.headers.get("cookie"),p);if(!s)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let d=await e(s,e$1.signingSecret,e$1.policy);return new Response(JSON.stringify(d),{status:200,headers:{"Content-Type":"application/json"}})}if((t.method==="GET"||t.method==="POST")&&r==="nonce"){let s=await f(e$1.signingSecret,T);return new Response(JSON.stringify({nonce:s}),{status:200,headers:{"Content-Type":"application/json"}})}if(t.method==="POST"&&r==="verify"){let s=t.headers.get("content-length");if(s&&parseInt(s,10)>y)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let d$1=await t.text();if(d$1.length>y)return new Response(JSON.stringify({error:"Payload Too Large"}),{status:413,headers:{"Content-Type":"application/json"}});let i;try{i=JSON.parse(d$1);}catch{return new Response(JSON.stringify({error:"Invalid JSON payload"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!i||typeof i.message!="string"||typeof i.signature!="string")return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let N={message:i.message,signature:i.signature},c$1=await c(N,{...e$1.verifyOptions,policy:e$1.policy});if(!c$1.success||!c$1.data)return new Response(JSON.stringify({error:c$1.error||"Verification failed"}),{status:401,headers:{"Content-Type":"application/json"}});if(!await g(c$1.data.nonce,e$1.signingSecret)||!o(c$1.data.nonce))return new Response(JSON.stringify({error:"Nonce replay detected or nonce expired"}),{status:401,headers:{"Content-Type":"application/json"}});let g$1=a(c$1.data),J=await d(g$1,e$1.signingSecret,u),j=h(J,{...e$1.cookieOptions,name:p,maxAge:u});return new Response(JSON.stringify(g$1),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":j}})}return t.method==="DELETE"&&r==="session"||t.method==="POST"&&r==="logout"?new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":i({...e$1.cookieOptions,name:p})}}):new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(a){return console.error("[SIWX-SERVER] Stateless Demo Handler error:",a),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:S,POST:S,DELETE:S}}export{H as createSiwxApiHandler,V as createStatelessDemoSiwxHandler};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tuwaio/siwx-server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"author": "Oleksandr Tkach",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -67,9 +67,9 @@
|
|
|
67
67
|
}
|
|
68
68
|
],
|
|
69
69
|
"peerDependencies": {
|
|
70
|
-
"@tuwaio/siwx-core": "0.
|
|
71
|
-
"@tuwaio/siwx-evm": "0.4.
|
|
72
|
-
"@tuwaio/siwx-solana": "0.4.
|
|
70
|
+
"@tuwaio/siwx-core": "0.5.0",
|
|
71
|
+
"@tuwaio/siwx-evm": "0.4.2",
|
|
72
|
+
"@tuwaio/siwx-solana": "0.4.2",
|
|
73
73
|
"viem": ">=2"
|
|
74
74
|
},
|
|
75
75
|
"peerDependenciesMeta": {
|
|
@@ -84,9 +84,9 @@
|
|
|
84
84
|
}
|
|
85
85
|
},
|
|
86
86
|
"devDependencies": {
|
|
87
|
-
"@tuwaio/siwx-core": "0.
|
|
88
|
-
"@tuwaio/siwx-evm": "0.4.
|
|
89
|
-
"@tuwaio/siwx-solana": "0.4.
|
|
87
|
+
"@tuwaio/siwx-core": "0.5.0",
|
|
88
|
+
"@tuwaio/siwx-evm": "0.4.2",
|
|
89
|
+
"@tuwaio/siwx-solana": "0.4.2",
|
|
90
90
|
"tsup": "^8.5.1",
|
|
91
91
|
"typescript": "6.0.3",
|
|
92
92
|
"viem": "^2.57.1"
|
package/dist/chunk-AEFOZH2W.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import {parseMessage,validateMessage,SiwxNonceReplayError,SiwxUnsupportedNamespaceError,generateNonce}from'@tuwaio/siwx-core';export{generateNonce as b}from'@tuwaio/siwx-core';function v(t){return {address:t.address,chainId:t.chainId,domain:t.domain,nonce:t.nonce,issuedAt:t.issuedAt,expirationTime:t.expirationTime}}async function B(t,e={}){try{let n=parseMessage(t.message),s=validateMessage(n,{skipExpiration:e.skipExpiration,policy:e.policy});if(!s.valid)return {success:!1,error:`Validation failed: ${s.errors.join(", ")}`};if(e.usedNonces?.has(n.nonce))throw new SiwxNonceReplayError(n.nonce);let i=n.chainId.split(":")[0];if(!i||!["eip155","solana"].includes(i))throw new SiwxUnsupportedNamespaceError(i??"unknown");if(i==="eip155"){let{verifyEvmSignature:r}=await import('@tuwaio/siwx-evm');return {...await r(t.message,t.signature,{skipExpiration:e.skipExpiration,publicClient:e.publicClient}),namespace:i}}if(i==="solana"){let{verifyEd25519:r}=await import('@tuwaio/siwx-solana');return {...await r(t,{skipExpiration:e.skipExpiration}),namespace:i}}return {success:!1,error:"Unsupported namespace."}}catch(n){return n instanceof SiwxNonceReplayError||n instanceof SiwxUnsupportedNamespaceError?{success:false,error:n.message}:{success:false,error:`Server verification failed: ${String(n)}`}}}function C(t){return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function k(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return atob(e)}function D(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 N(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e),s=new Uint8Array(n.length);for(let i=0;i<n.length;i++)s[i]=n.charCodeAt(i);return s}async function p(t){let e=new TextEncoder;return globalThis.crypto.subtle.importKey("raw",e.encode(t),{name:"HMAC",hash:"SHA-256"},false,["sign","verify"])}async function j(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 i=Date.now()+n*1e3,r={version:1,address:t.address,chainId:t.chainId,domain:t.domain,nonce:t.nonce,issuedAt:t.issuedAt,expirationTime:t.expirationTime??new Date(i).toISOString(),sessionId:generateNonce(),mode:"demo"},a=JSON.stringify(r),o=C(a),l=await p(e),u=new TextEncoder,f=await globalThis.crypto.subtle.sign("HMAC",l,u.encode(o)),c=D(new Uint8Array(f));return `${o}.${c}`}async function I(t,e,n){if(!t||typeof t!="string"||!e)return null;let s=t.split(".");if(s.length!==2)return null;let[i,r]=s;try{let a=await p(e),o=N(r),l=new TextEncoder;if(!await globalThis.crypto.subtle.verify("HMAC",a,o,l.encode(i)))return null;let f=k(i),c=JSON.parse(f);if(c.version!==1||c.mode!=="demo")return null;if(c.expirationTime){let g=new Date(c.expirationTime).getTime(),S=(n?.clockSkewSeconds??60)*1e3;if(isNaN(g)||g+S<Date.now())return null}return n?.expectedDomain!==void 0&&!(Array.isArray(n.expectedDomain)?n.expectedDomain:[n.expectedDomain]).some(S=>S.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}}var E="siwx-demo-nonce:",y=32,A=10,R=/^[0-9a-f]{106}$/;function O(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function V(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 U(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,s=generateNonce()+n.toString(16).padStart(A,"0"),i=await p(t),r=await globalThis.crypto.subtle.sign("HMAC",i,new TextEncoder().encode(E+s));return s+O(new Uint8Array(r))}async function H(t,e){if(typeof t!="string"||!e||!R.test(t))return false;let n=y+A,s=t.slice(0,n),i=t.slice(n);try{let r=await p(e);return await globalThis.crypto.subtle.verify("HMAC",r,V(i),new TextEncoder().encode(E+s))?parseInt(s.slice(y),16)*1e3>=Date.now():!1}catch{return false}}function L(t,e={}){let{name:n="siwx-session-v2",maxAge:s=3600*24*7,path:i="/",domain:r,secure:a=true,sameSite:o="Strict"}=e,l=[`${n}=${t}`,`Max-Age=${s}`,`Path=${i}`,"HttpOnly",`SameSite=${o}`];return a&&l.push("Secure"),r&&l.push(`Domain=${r}`),l.join("; ")}function G(t={}){let{name:e="siwx-session-v2",path:n="/",domain:s,secure:i=true,sameSite:r="Strict"}=t,a=[`${e}=`,`Path=${n}`,"Expires=Thu, 01 Jan 1970 00:00:00 GMT","Max-Age=0","HttpOnly",`SameSite=${r}`];return i&&a.push("Secure"),s&&a.push(`Domain=${s}`),a.join("; ")}function d(t,e){return t?Object.fromEntries(t.split("; ").filter(Boolean).map(s=>{let i=s.split("=");return [i[0].trim(),i.slice(1).join("=")]}))[e]??null:null}var h=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(),s=Date.now(),i=s+e.ttlSeconds*1e3,r={id:n,session:e.session,createdAt:s,expiresAt:i};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 s=await this.get(e);return s?(s.subjectId=n,true):false}async revoke(e){this.records.delete(e);}},b=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 X(t){let{cookieSource:e,cookieName:n="siwx-session-v2",sessionStore:s,signingSecret:i,policy:r}=t;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(s){let o=await s.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 i?I(a,i,r):null}
|
|
2
|
-
export{v as a,B as c,j as d,I as e,U as f,H as g,L as h,G as i,d as j,h as k,b as l,X as m};
|
package/dist/chunk-SS5KJYWU.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
'use strict';var siwxCore=require('@tuwaio/siwx-core');function v(t){return {address:t.address,chainId:t.chainId,domain:t.domain,nonce:t.nonce,issuedAt:t.issuedAt,expirationTime:t.expirationTime}}async function B(t,e={}){try{let n=siwxCore.parseMessage(t.message),s=siwxCore.validateMessage(n,{skipExpiration:e.skipExpiration,policy:e.policy});if(!s.valid)return {success:!1,error:`Validation failed: ${s.errors.join(", ")}`};if(e.usedNonces?.has(n.nonce))throw new siwxCore.SiwxNonceReplayError(n.nonce);let i=n.chainId.split(":")[0];if(!i||!["eip155","solana"].includes(i))throw new siwxCore.SiwxUnsupportedNamespaceError(i??"unknown");if(i==="eip155"){let{verifyEvmSignature:r}=await import('@tuwaio/siwx-evm');return {...await r(t.message,t.signature,{skipExpiration:e.skipExpiration,publicClient:e.publicClient}),namespace:i}}if(i==="solana"){let{verifyEd25519:r}=await import('@tuwaio/siwx-solana');return {...await r(t,{skipExpiration:e.skipExpiration}),namespace:i}}return {success:!1,error:"Unsupported namespace."}}catch(n){return n instanceof siwxCore.SiwxNonceReplayError||n instanceof siwxCore.SiwxUnsupportedNamespaceError?{success:false,error:n.message}:{success:false,error:`Server verification failed: ${String(n)}`}}}function C(t){return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function k(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return atob(e)}function D(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 N(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e),s=new Uint8Array(n.length);for(let i=0;i<n.length;i++)s[i]=n.charCodeAt(i);return s}async function p(t){let e=new TextEncoder;return globalThis.crypto.subtle.importKey("raw",e.encode(t),{name:"HMAC",hash:"SHA-256"},false,["sign","verify"])}async function j(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 i=Date.now()+n*1e3,r={version:1,address:t.address,chainId:t.chainId,domain:t.domain,nonce:t.nonce,issuedAt:t.issuedAt,expirationTime:t.expirationTime??new Date(i).toISOString(),sessionId:siwxCore.generateNonce(),mode:"demo"},a=JSON.stringify(r),o=C(a),l=await p(e),u=new TextEncoder,f=await globalThis.crypto.subtle.sign("HMAC",l,u.encode(o)),c=D(new Uint8Array(f));return `${o}.${c}`}async function I(t,e,n){if(!t||typeof t!="string"||!e)return null;let s=t.split(".");if(s.length!==2)return null;let[i,r]=s;try{let a=await p(e),o=N(r),l=new TextEncoder;if(!await globalThis.crypto.subtle.verify("HMAC",a,o,l.encode(i)))return null;let f=k(i),c=JSON.parse(f);if(c.version!==1||c.mode!=="demo")return null;if(c.expirationTime){let g=new Date(c.expirationTime).getTime(),S=(n?.clockSkewSeconds??60)*1e3;if(isNaN(g)||g+S<Date.now())return null}return n?.expectedDomain!==void 0&&!(Array.isArray(n.expectedDomain)?n.expectedDomain:[n.expectedDomain]).some(S=>S.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}}var E="siwx-demo-nonce:",y=32,A=10,R=/^[0-9a-f]{106}$/;function O(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function V(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 U(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,s=siwxCore.generateNonce()+n.toString(16).padStart(A,"0"),i=await p(t),r=await globalThis.crypto.subtle.sign("HMAC",i,new TextEncoder().encode(E+s));return s+O(new Uint8Array(r))}async function H(t,e){if(typeof t!="string"||!e||!R.test(t))return false;let n=y+A,s=t.slice(0,n),i=t.slice(n);try{let r=await p(e);return await globalThis.crypto.subtle.verify("HMAC",r,V(i),new TextEncoder().encode(E+s))?parseInt(s.slice(y),16)*1e3>=Date.now():!1}catch{return false}}function L(t,e={}){let{name:n="siwx-session-v2",maxAge:s=3600*24*7,path:i="/",domain:r,secure:a=true,sameSite:o="Strict"}=e,l=[`${n}=${t}`,`Max-Age=${s}`,`Path=${i}`,"HttpOnly",`SameSite=${o}`];return a&&l.push("Secure"),r&&l.push(`Domain=${r}`),l.join("; ")}function G(t={}){let{name:e="siwx-session-v2",path:n="/",domain:s,secure:i=true,sameSite:r="Strict"}=t,a=[`${e}=`,`Path=${n}`,"Expires=Thu, 01 Jan 1970 00:00:00 GMT","Max-Age=0","HttpOnly",`SameSite=${r}`];return i&&a.push("Secure"),s&&a.push(`Domain=${s}`),a.join("; ")}function d(t,e){return t?Object.fromEntries(t.split("; ").filter(Boolean).map(s=>{let i=s.split("=");return [i[0].trim(),i.slice(1).join("=")]}))[e]??null:null}var h=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(),s=Date.now(),i=s+e.ttlSeconds*1e3,r={id:n,session:e.session,createdAt:s,expiresAt:i};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 s=await this.get(e);return s?(s.subjectId=n,true):false}async revoke(e){this.records.delete(e);}},b=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 X(t){let{cookieSource:e,cookieName:n="siwx-session-v2",sessionStore:s,signingSecret:i,policy:r}=t;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(s){let o=await s.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 i?I(a,i,r):null}
|
|
2
|
-
Object.defineProperty(exports,"b",{enumerable:true,get:function(){return siwxCore.generateNonce}});exports.a=v;exports.c=B;exports.d=j;exports.e=I;exports.f=U;exports.g=H;exports.h=L;exports.i=G;exports.j=d;exports.k=h;exports.l=b;exports.m=X;
|