@tuwaio/siwx-server 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,6 +10,7 @@
10
10
  ## 🏛️ Core Capabilities
11
11
 
12
12
  - **`verifySiwxPayload()`**: Primary server entry point. Parses the CAIP-122 message, enforces verification policy (domain, URI, allowed chains, timing windows), checks nonce replay, and dynamically verifies EVM (`siwx-evm`) or Solana (`siwx-solana`) signatures.
13
+ - **`getSiwxServerSession()`**: Unified server helper to resolve and verify active sessions across Next.js Server Actions, Route Handlers, and Web APIs from durable stores (`sessionStore`) or stateless demo tokens (`signingSecret`).
13
14
  - **`createSiwxApiHandler()`**: Production durable session handler for Next.js App Router. Requires persistent `SiwxSessionStore` and `SiwxNonceStore` (Redis, PostgreSQL, etc.) and uses opaque session IDs in `HttpOnly` cookies.
14
15
  - **`createStatelessDemoSiwxHandler()`**: Authenticated HMAC-SHA256 session handler for zero-infrastructure demonstration environments and rapid prototyping.
15
16
  - **`signStatelessDemoSession()` / `verifyStatelessDemoSession()`**: Web Crypto API constant-time HMAC signing and verification for demo tokens.
@@ -213,6 +214,42 @@ export const { GET, POST, DELETE } = handler;
213
214
 
214
215
  ---
215
216
 
217
+ ### 3. Server Actions & Route Session Resolution (`getSiwxServerSession`)
218
+
219
+ Use `getSiwxServerSession` in Next.js Server Actions or server-side routes to securely resolve authenticated sessions without accepting client-provided session parameters:
220
+
221
+ ```ts
222
+ // app/actions/myAction.ts
223
+ 'use server';
224
+
225
+ import { cookies } from 'next/headers';
226
+ import { getSiwxServerSession } from '@tuwaio/siwx-server';
227
+ import { isSessionMatchingTarget } from '@tuwaio/siwx-core';
228
+ import { sessionStore } from '@/lib/authStores';
229
+
230
+ export async function myServerAction(targetAddress: string, data: Record<string, unknown>) {
231
+ // 1. Resolve and verify session from HTTP-Only cookie server-side
232
+ const session = await getSiwxServerSession({
233
+ cookieSource: await cookies(),
234
+ sessionStore, // Or signingSecret for demo profile
235
+ });
236
+
237
+ if (!session) {
238
+ throw new Error('Unauthorized: No active session.');
239
+ }
240
+
241
+ // 2. Enforce cryptographic subject/address binding
242
+ if (!isSessionMatchingTarget(session, targetAddress)) {
243
+ throw new Error('Forbidden: Wallet address mismatch.');
244
+ }
245
+
246
+ // 3. Execute privileged server business logic
247
+ return { success: true };
248
+ }
249
+ ```
250
+
251
+ ---
252
+
216
253
  ## 🚀 Low-Level Manual Verification API
217
254
 
218
255
  For custom controllers (NestJS, Fastify, Express, Cloudflare Workers):
@@ -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),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;
@@ -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),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};
package/dist/index.d.mts CHANGED
@@ -1,8 +1,230 @@
1
1
  import * as _tuwaio_siwx_core from '@tuwaio/siwx-core';
2
- import { SiwxVerifyPayload } from '@tuwaio/siwx-core';
2
+ import { SiwxVerificationPolicy, SiwxVerifyResult, ParsedSiwxMessage, SiwxVerifyPayload } from '@tuwaio/siwx-core';
3
3
  export { ParsedSiwxMessage, SiwxMessageFields, SiwxSessionLike, SiwxVerificationPolicy, ValidateMessageOptions, generateNonce, generateNonce as generateServerNonce, isSessionMatchingTarget, validateMessage, validatePolicy } from '@tuwaio/siwx-core';
4
- import { S as SiwxNonceStore, a as SiwxSessionStore, b as SiwxSession, c as SiwxSessionRecord, C as CookieOptions, d as ServerVerifyOptions, e as ServerVerifyResult } from './types-Dz3SGS59.mjs';
5
- export { f as StatelessDemoLimits, g as StatelessDemoTokenPayload, t as toSession } from './types-Dz3SGS59.mjs';
4
+
5
+ /**
6
+ * @fileoverview Server-side types for the @tuwaio/siwx-server package.
7
+ */
8
+
9
+ /**
10
+ * Options for the `verifySiwxPayload` function.
11
+ */
12
+ interface ServerVerifyOptions {
13
+ /**
14
+ * A set of nonces that have already been used.
15
+ * If the payload's nonce is found in this set, verification will fail
16
+ * to prevent replay attacks.
17
+ */
18
+ usedNonces?: Set<string>;
19
+ /**
20
+ * If true, skips the `expirationTime` validation check.
21
+ * Not recommended for production use.
22
+ * @default false
23
+ */
24
+ skipExpiration?: boolean;
25
+ /**
26
+ * Optional verification policy to enforce on the message fields.
27
+ */
28
+ policy?: SiwxVerificationPolicy;
29
+ /**
30
+ * Optional viem `PublicClient` instance for EVM chain EIP-1271 (smart contract wallet) verification.
31
+ */
32
+ publicClient?: any;
33
+ }
34
+ /**
35
+ * The result of a server-side verification operation, extending the base result
36
+ * with the verification method used.
37
+ */
38
+ interface ServerVerifyResult extends SiwxVerifyResult {
39
+ /**
40
+ * The CAIP-2 namespace used for verification routing.
41
+ * `eip155` for EVM chains, `solana` for Solana.
42
+ */
43
+ namespace?: 'eip155' | 'solana';
44
+ }
45
+ /**
46
+ * Represents a serializable session object derived from a verified CAIP-122 message.
47
+ */
48
+ interface SiwxSession {
49
+ /** The verified CAIP-10 blockchain address. */
50
+ address: string;
51
+ /** The CAIP-2 chain ID the session is bound to. */
52
+ chainId: string;
53
+ /** The domain that issued the session. */
54
+ domain: string;
55
+ /** The nonce that was used. Must be invalidated server-side after use. */
56
+ nonce: string;
57
+ /** ISO 8601 timestamp when the session was issued. */
58
+ issuedAt: string;
59
+ /** ISO 8601 timestamp when the session expires, if set. */
60
+ expirationTime?: string;
61
+ }
62
+ /**
63
+ * Represents a stored session record in a durable session store.
64
+ */
65
+ interface SiwxSessionRecord {
66
+ /** Unique opaque session identifier (e.g. secure random UUID). */
67
+ id: string;
68
+ /** The verified SIWX session data. */
69
+ session: SiwxSession;
70
+ /** Optional subject ID (e.g., Payload User ID or internal database ID) bound to this session. */
71
+ subjectId?: string;
72
+ /** Timestamp in milliseconds when the session record was created. */
73
+ createdAt: number;
74
+ /** Timestamp in milliseconds when the session record expires. */
75
+ expiresAt: number;
76
+ }
77
+ /**
78
+ * Durable session store interface for production environments.
79
+ */
80
+ interface SiwxSessionStore {
81
+ /**
82
+ * Creates and stores a new session record.
83
+ * @param input.session - The verified session data.
84
+ * @param input.ttlSeconds - Time-to-live in seconds.
85
+ * @returns The created session record with unique ID.
86
+ */
87
+ create(input: {
88
+ session: SiwxSession;
89
+ ttlSeconds: number;
90
+ }): Promise<SiwxSessionRecord>;
91
+ /**
92
+ * Retrieves a session record by its opaque ID.
93
+ * @param id - The session ID.
94
+ * @returns The session record, or null if not found or expired.
95
+ */
96
+ get(id: string): Promise<SiwxSessionRecord | null>;
97
+ /**
98
+ * Atomically binds a user/subject identifier to the session.
99
+ * @param id - The session ID.
100
+ * @param subjectId - The user or subject ID.
101
+ * @returns True if binding succeeded, false if session not found.
102
+ */
103
+ bindSubject(id: string, subjectId: string): Promise<boolean>;
104
+ /**
105
+ * Revokes and removes a session record.
106
+ * @param id - The session ID.
107
+ */
108
+ revoke(id: string): Promise<void>;
109
+ }
110
+ /**
111
+ * Durable nonce store interface for single-use nonce issuance and atomic consumption.
112
+ */
113
+ interface SiwxNonceStore {
114
+ /**
115
+ * Issues and stores a new challenge nonce with TTL.
116
+ * @param input.nonce - The unique nonce string.
117
+ * @param input.ttlSeconds - Time-to-live in seconds (typically 300s).
118
+ */
119
+ issue(input: {
120
+ nonce: string;
121
+ ttlSeconds: number;
122
+ }): Promise<void>;
123
+ /**
124
+ * Atomically consumes a nonce, guaranteeing single-use.
125
+ * @param input.nonce - The nonce string to consume.
126
+ * @returns True if the nonce was valid and consumed, false if already consumed or expired.
127
+ */
128
+ consume(input: {
129
+ nonce: string;
130
+ }): Promise<boolean>;
131
+ }
132
+ /**
133
+ * Compact payload structure for stateless demo session tokens.
134
+ */
135
+ interface StatelessDemoTokenPayload {
136
+ version: 1;
137
+ address: string;
138
+ chainId: string;
139
+ domain: string;
140
+ nonce: string;
141
+ issuedAt: string;
142
+ expirationTime?: string;
143
+ sessionId: string;
144
+ mode: 'demo';
145
+ }
146
+ /**
147
+ * Limits for stateless demo profile.
148
+ */
149
+ interface StatelessDemoLimits {
150
+ /** Maximum transaction payload size in bytes. */
151
+ maxTransactionPayloadBytes?: number;
152
+ /** Advisory request cap per session. */
153
+ maxRequestsPerSession?: number;
154
+ }
155
+ /**
156
+ * Options for cookie session serialization.
157
+ */
158
+ interface CookieOptions {
159
+ /**
160
+ * The name of the cookie.
161
+ * @default "siwx-session-v2"
162
+ */
163
+ name?: string;
164
+ /**
165
+ * Max age in seconds. Defaults to 7 days for durable, 30 minutes for demo.
166
+ * @default 604800
167
+ */
168
+ maxAge?: number;
169
+ /**
170
+ * The cookie path.
171
+ * @default "/"
172
+ */
173
+ path?: string;
174
+ /**
175
+ * The cookie domain.
176
+ */
177
+ domain?: string;
178
+ /**
179
+ * Whether to set the Secure flag.
180
+ * @default true
181
+ */
182
+ secure?: boolean;
183
+ /**
184
+ * The SameSite policy.
185
+ * @default "Strict"
186
+ */
187
+ sameSite?: 'Strict' | 'Lax' | 'None';
188
+ }
189
+ /**
190
+ * Options for the `getSiwxServerSession` helper function.
191
+ */
192
+ interface GetSiwxServerSessionOptions {
193
+ /**
194
+ * Cookie source:
195
+ * - A raw Cookie string (e.g. `req.headers.get('cookie')` or `"siwx-session-v2=xyz"`)
196
+ * - A Next.js ReadonlyRequestCookies object (from `await cookies()`)
197
+ * - A Web API `Request` or `Headers` object
198
+ * - Any object with a `get(name)` method
199
+ */
200
+ cookieSource: string | Request | Headers | {
201
+ get(name: string): {
202
+ value: string;
203
+ } | string | undefined | null;
204
+ } | null | undefined;
205
+ /**
206
+ * The name of the cookie.
207
+ * @default "siwx-session-v2"
208
+ */
209
+ cookieName?: string;
210
+ /**
211
+ * Durable session store (for production durable sessions).
212
+ */
213
+ sessionStore?: SiwxSessionStore;
214
+ /**
215
+ * Server HMAC secret key (for stateless demo sessions).
216
+ */
217
+ signingSecret?: string;
218
+ /**
219
+ * Optional verification policy to validate the session.
220
+ */
221
+ policy?: SiwxVerificationPolicy;
222
+ }
223
+ /**
224
+ * Converts a ParsedSiwxMessage to a lean SiwxSession object.
225
+ * @internal
226
+ */
227
+ declare function toSession(parsed: ParsedSiwxMessage): SiwxSession;
6
228
 
7
229
  /**
8
230
  * Parses and validates a raw CAIP-122 payload (message + signature) on the server side.
@@ -81,5 +303,26 @@ declare class MemorySiwxNonceStore implements SiwxNonceStore {
81
303
  nonce: string;
82
304
  }): Promise<boolean>;
83
305
  }
306
+ /**
307
+ * Resolves and verifies an active SIWX session strictly on the server side.
308
+ * Supports both durable session stores and stateless HMAC-signed demo cookies.
309
+ *
310
+ * @param options - Configuration including cookieSource, sessionStore or signingSecret, and optional policy.
311
+ * @returns The verified `SiwxSession` object, or `null` if invalid, expired, or absent.
312
+ *
313
+ * @example
314
+ * ```ts
315
+ * // In Next.js Server Actions:
316
+ * import { cookies } from 'next/headers';
317
+ * import { getSiwxServerSession } from '@tuwaio/siwx-server';
318
+ * import { sessionStore } from '@/lib/authStores';
319
+ *
320
+ * const session = await getSiwxServerSession({
321
+ * cookieSource: await cookies(),
322
+ * sessionStore,
323
+ * });
324
+ * ```
325
+ */
326
+ declare function getSiwxServerSession(options: GetSiwxServerSessionOptions): Promise<SiwxSession | null>;
84
327
 
85
- export { CookieOptions, MemorySiwxNonceStore, MemorySiwxSessionStore, ServerVerifyOptions, ServerVerifyResult, SiwxNonceStore, SiwxSession, SiwxSessionRecord, SiwxSessionStore, createClearCookie, createSessionCookie, parseCookie, signStatelessDemoSession, verifySiwxPayload, verifyStatelessDemoSession };
328
+ export { type CookieOptions, type GetSiwxServerSessionOptions, MemorySiwxNonceStore, MemorySiwxSessionStore, type ServerVerifyOptions, type ServerVerifyResult, type SiwxNonceStore, type SiwxSession, type SiwxSessionRecord, type SiwxSessionStore, type StatelessDemoLimits, type StatelessDemoTokenPayload, createClearCookie, createSessionCookie, getSiwxServerSession, parseCookie, signStatelessDemoSession, toSession, verifySiwxPayload, verifyStatelessDemoSession };
package/dist/index.d.ts CHANGED
@@ -1,8 +1,230 @@
1
1
  import * as _tuwaio_siwx_core from '@tuwaio/siwx-core';
2
- import { SiwxVerifyPayload } from '@tuwaio/siwx-core';
2
+ import { SiwxVerificationPolicy, SiwxVerifyResult, ParsedSiwxMessage, SiwxVerifyPayload } from '@tuwaio/siwx-core';
3
3
  export { ParsedSiwxMessage, SiwxMessageFields, SiwxSessionLike, SiwxVerificationPolicy, ValidateMessageOptions, generateNonce, generateNonce as generateServerNonce, isSessionMatchingTarget, validateMessage, validatePolicy } from '@tuwaio/siwx-core';
4
- import { S as SiwxNonceStore, a as SiwxSessionStore, b as SiwxSession, c as SiwxSessionRecord, C as CookieOptions, d as ServerVerifyOptions, e as ServerVerifyResult } from './types-Dz3SGS59.js';
5
- export { f as StatelessDemoLimits, g as StatelessDemoTokenPayload, t as toSession } from './types-Dz3SGS59.js';
4
+
5
+ /**
6
+ * @fileoverview Server-side types for the @tuwaio/siwx-server package.
7
+ */
8
+
9
+ /**
10
+ * Options for the `verifySiwxPayload` function.
11
+ */
12
+ interface ServerVerifyOptions {
13
+ /**
14
+ * A set of nonces that have already been used.
15
+ * If the payload's nonce is found in this set, verification will fail
16
+ * to prevent replay attacks.
17
+ */
18
+ usedNonces?: Set<string>;
19
+ /**
20
+ * If true, skips the `expirationTime` validation check.
21
+ * Not recommended for production use.
22
+ * @default false
23
+ */
24
+ skipExpiration?: boolean;
25
+ /**
26
+ * Optional verification policy to enforce on the message fields.
27
+ */
28
+ policy?: SiwxVerificationPolicy;
29
+ /**
30
+ * Optional viem `PublicClient` instance for EVM chain EIP-1271 (smart contract wallet) verification.
31
+ */
32
+ publicClient?: any;
33
+ }
34
+ /**
35
+ * The result of a server-side verification operation, extending the base result
36
+ * with the verification method used.
37
+ */
38
+ interface ServerVerifyResult extends SiwxVerifyResult {
39
+ /**
40
+ * The CAIP-2 namespace used for verification routing.
41
+ * `eip155` for EVM chains, `solana` for Solana.
42
+ */
43
+ namespace?: 'eip155' | 'solana';
44
+ }
45
+ /**
46
+ * Represents a serializable session object derived from a verified CAIP-122 message.
47
+ */
48
+ interface SiwxSession {
49
+ /** The verified CAIP-10 blockchain address. */
50
+ address: string;
51
+ /** The CAIP-2 chain ID the session is bound to. */
52
+ chainId: string;
53
+ /** The domain that issued the session. */
54
+ domain: string;
55
+ /** The nonce that was used. Must be invalidated server-side after use. */
56
+ nonce: string;
57
+ /** ISO 8601 timestamp when the session was issued. */
58
+ issuedAt: string;
59
+ /** ISO 8601 timestamp when the session expires, if set. */
60
+ expirationTime?: string;
61
+ }
62
+ /**
63
+ * Represents a stored session record in a durable session store.
64
+ */
65
+ interface SiwxSessionRecord {
66
+ /** Unique opaque session identifier (e.g. secure random UUID). */
67
+ id: string;
68
+ /** The verified SIWX session data. */
69
+ session: SiwxSession;
70
+ /** Optional subject ID (e.g., Payload User ID or internal database ID) bound to this session. */
71
+ subjectId?: string;
72
+ /** Timestamp in milliseconds when the session record was created. */
73
+ createdAt: number;
74
+ /** Timestamp in milliseconds when the session record expires. */
75
+ expiresAt: number;
76
+ }
77
+ /**
78
+ * Durable session store interface for production environments.
79
+ */
80
+ interface SiwxSessionStore {
81
+ /**
82
+ * Creates and stores a new session record.
83
+ * @param input.session - The verified session data.
84
+ * @param input.ttlSeconds - Time-to-live in seconds.
85
+ * @returns The created session record with unique ID.
86
+ */
87
+ create(input: {
88
+ session: SiwxSession;
89
+ ttlSeconds: number;
90
+ }): Promise<SiwxSessionRecord>;
91
+ /**
92
+ * Retrieves a session record by its opaque ID.
93
+ * @param id - The session ID.
94
+ * @returns The session record, or null if not found or expired.
95
+ */
96
+ get(id: string): Promise<SiwxSessionRecord | null>;
97
+ /**
98
+ * Atomically binds a user/subject identifier to the session.
99
+ * @param id - The session ID.
100
+ * @param subjectId - The user or subject ID.
101
+ * @returns True if binding succeeded, false if session not found.
102
+ */
103
+ bindSubject(id: string, subjectId: string): Promise<boolean>;
104
+ /**
105
+ * Revokes and removes a session record.
106
+ * @param id - The session ID.
107
+ */
108
+ revoke(id: string): Promise<void>;
109
+ }
110
+ /**
111
+ * Durable nonce store interface for single-use nonce issuance and atomic consumption.
112
+ */
113
+ interface SiwxNonceStore {
114
+ /**
115
+ * Issues and stores a new challenge nonce with TTL.
116
+ * @param input.nonce - The unique nonce string.
117
+ * @param input.ttlSeconds - Time-to-live in seconds (typically 300s).
118
+ */
119
+ issue(input: {
120
+ nonce: string;
121
+ ttlSeconds: number;
122
+ }): Promise<void>;
123
+ /**
124
+ * Atomically consumes a nonce, guaranteeing single-use.
125
+ * @param input.nonce - The nonce string to consume.
126
+ * @returns True if the nonce was valid and consumed, false if already consumed or expired.
127
+ */
128
+ consume(input: {
129
+ nonce: string;
130
+ }): Promise<boolean>;
131
+ }
132
+ /**
133
+ * Compact payload structure for stateless demo session tokens.
134
+ */
135
+ interface StatelessDemoTokenPayload {
136
+ version: 1;
137
+ address: string;
138
+ chainId: string;
139
+ domain: string;
140
+ nonce: string;
141
+ issuedAt: string;
142
+ expirationTime?: string;
143
+ sessionId: string;
144
+ mode: 'demo';
145
+ }
146
+ /**
147
+ * Limits for stateless demo profile.
148
+ */
149
+ interface StatelessDemoLimits {
150
+ /** Maximum transaction payload size in bytes. */
151
+ maxTransactionPayloadBytes?: number;
152
+ /** Advisory request cap per session. */
153
+ maxRequestsPerSession?: number;
154
+ }
155
+ /**
156
+ * Options for cookie session serialization.
157
+ */
158
+ interface CookieOptions {
159
+ /**
160
+ * The name of the cookie.
161
+ * @default "siwx-session-v2"
162
+ */
163
+ name?: string;
164
+ /**
165
+ * Max age in seconds. Defaults to 7 days for durable, 30 minutes for demo.
166
+ * @default 604800
167
+ */
168
+ maxAge?: number;
169
+ /**
170
+ * The cookie path.
171
+ * @default "/"
172
+ */
173
+ path?: string;
174
+ /**
175
+ * The cookie domain.
176
+ */
177
+ domain?: string;
178
+ /**
179
+ * Whether to set the Secure flag.
180
+ * @default true
181
+ */
182
+ secure?: boolean;
183
+ /**
184
+ * The SameSite policy.
185
+ * @default "Strict"
186
+ */
187
+ sameSite?: 'Strict' | 'Lax' | 'None';
188
+ }
189
+ /**
190
+ * Options for the `getSiwxServerSession` helper function.
191
+ */
192
+ interface GetSiwxServerSessionOptions {
193
+ /**
194
+ * Cookie source:
195
+ * - A raw Cookie string (e.g. `req.headers.get('cookie')` or `"siwx-session-v2=xyz"`)
196
+ * - A Next.js ReadonlyRequestCookies object (from `await cookies()`)
197
+ * - A Web API `Request` or `Headers` object
198
+ * - Any object with a `get(name)` method
199
+ */
200
+ cookieSource: string | Request | Headers | {
201
+ get(name: string): {
202
+ value: string;
203
+ } | string | undefined | null;
204
+ } | null | undefined;
205
+ /**
206
+ * The name of the cookie.
207
+ * @default "siwx-session-v2"
208
+ */
209
+ cookieName?: string;
210
+ /**
211
+ * Durable session store (for production durable sessions).
212
+ */
213
+ sessionStore?: SiwxSessionStore;
214
+ /**
215
+ * Server HMAC secret key (for stateless demo sessions).
216
+ */
217
+ signingSecret?: string;
218
+ /**
219
+ * Optional verification policy to validate the session.
220
+ */
221
+ policy?: SiwxVerificationPolicy;
222
+ }
223
+ /**
224
+ * Converts a ParsedSiwxMessage to a lean SiwxSession object.
225
+ * @internal
226
+ */
227
+ declare function toSession(parsed: ParsedSiwxMessage): SiwxSession;
6
228
 
7
229
  /**
8
230
  * Parses and validates a raw CAIP-122 payload (message + signature) on the server side.
@@ -81,5 +303,26 @@ declare class MemorySiwxNonceStore implements SiwxNonceStore {
81
303
  nonce: string;
82
304
  }): Promise<boolean>;
83
305
  }
306
+ /**
307
+ * Resolves and verifies an active SIWX session strictly on the server side.
308
+ * Supports both durable session stores and stateless HMAC-signed demo cookies.
309
+ *
310
+ * @param options - Configuration including cookieSource, sessionStore or signingSecret, and optional policy.
311
+ * @returns The verified `SiwxSession` object, or `null` if invalid, expired, or absent.
312
+ *
313
+ * @example
314
+ * ```ts
315
+ * // In Next.js Server Actions:
316
+ * import { cookies } from 'next/headers';
317
+ * import { getSiwxServerSession } from '@tuwaio/siwx-server';
318
+ * import { sessionStore } from '@/lib/authStores';
319
+ *
320
+ * const session = await getSiwxServerSession({
321
+ * cookieSource: await cookies(),
322
+ * sessionStore,
323
+ * });
324
+ * ```
325
+ */
326
+ declare function getSiwxServerSession(options: GetSiwxServerSessionOptions): Promise<SiwxSession | null>;
84
327
 
85
- export { CookieOptions, MemorySiwxNonceStore, MemorySiwxSessionStore, ServerVerifyOptions, ServerVerifyResult, SiwxNonceStore, SiwxSession, SiwxSessionRecord, SiwxSessionStore, createClearCookie, createSessionCookie, parseCookie, signStatelessDemoSession, verifySiwxPayload, verifyStatelessDemoSession };
328
+ export { type CookieOptions, type GetSiwxServerSessionOptions, MemorySiwxNonceStore, MemorySiwxSessionStore, type ServerVerifyOptions, type ServerVerifyResult, type SiwxNonceStore, type SiwxSession, type SiwxSessionRecord, type SiwxSessionStore, type StatelessDemoLimits, type StatelessDemoTokenPayload, createClearCookie, createSessionCookie, getSiwxServerSession, parseCookie, signStatelessDemoSession, toSession, verifySiwxPayload, verifyStatelessDemoSession };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- 'use strict';var chunk4HK2SXOC_js=require('./chunk-4HK2SXOC.js'),siwxCore=require('@tuwaio/siwx-core');Object.defineProperty(exports,"MemorySiwxNonceStore",{enumerable:true,get:function(){return chunk4HK2SXOC_js.j}});Object.defineProperty(exports,"MemorySiwxSessionStore",{enumerable:true,get:function(){return chunk4HK2SXOC_js.i}});Object.defineProperty(exports,"createClearCookie",{enumerable:true,get:function(){return chunk4HK2SXOC_js.g}});Object.defineProperty(exports,"createSessionCookie",{enumerable:true,get:function(){return chunk4HK2SXOC_js.f}});Object.defineProperty(exports,"generateServerNonce",{enumerable:true,get:function(){return chunk4HK2SXOC_js.b}});Object.defineProperty(exports,"parseCookie",{enumerable:true,get:function(){return chunk4HK2SXOC_js.h}});Object.defineProperty(exports,"signStatelessDemoSession",{enumerable:true,get:function(){return chunk4HK2SXOC_js.d}});Object.defineProperty(exports,"toSession",{enumerable:true,get:function(){return chunk4HK2SXOC_js.a}});Object.defineProperty(exports,"verifySiwxPayload",{enumerable:true,get:function(){return chunk4HK2SXOC_js.c}});Object.defineProperty(exports,"verifyStatelessDemoSession",{enumerable:true,get:function(){return chunk4HK2SXOC_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 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}});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- export{j as MemorySiwxNonceStore,i as MemorySiwxSessionStore,g as createClearCookie,f as createSessionCookie,b as generateServerNonce,h as parseCookie,d as signStatelessDemoSession,a as toSession,c as verifySiwxPayload,e as verifyStatelessDemoSession}from'./chunk-GQ7NU6NM.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-WXHFSBDK.mjs';export{generateNonce,isSessionMatchingTarget,validateMessage,validatePolicy}from'@tuwaio/siwx-core';
package/dist/next.d.mts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { SiwxVerificationPolicy } from '@tuwaio/siwx-core';
2
- import { a as SiwxSessionStore, S as SiwxNonceStore, C as CookieOptions, d as ServerVerifyOptions, f as StatelessDemoLimits } from './types-Dz3SGS59.mjs';
2
+ import { SiwxSessionStore, SiwxNonceStore, CookieOptions, ServerVerifyOptions, StatelessDemoLimits } from './index.mjs';
3
+ export { GetSiwxServerSessionOptions, getSiwxServerSession } from './index.mjs';
3
4
 
4
5
  /**
5
6
  * @fileoverview Next.js App Router (Route Handlers) API helper for SIWX.
package/dist/next.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { SiwxVerificationPolicy } from '@tuwaio/siwx-core';
2
- import { a as SiwxSessionStore, S as SiwxNonceStore, C as CookieOptions, d as ServerVerifyOptions, f as StatelessDemoLimits } from './types-Dz3SGS59.js';
2
+ import { SiwxSessionStore, SiwxNonceStore, CookieOptions, ServerVerifyOptions, StatelessDemoLimits } from './index.js';
3
+ export { GetSiwxServerSessionOptions, getSiwxServerSession } from './index.js';
3
4
 
4
5
  /**
5
6
  * @fileoverview Next.js App Router (Route Handlers) API helper for SIWX.
package/dist/next.js CHANGED
@@ -1 +1 @@
1
- 'use strict';var chunk4HK2SXOC_js=require('./chunk-4HK2SXOC.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=chunk4HK2SXOC_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 chunk4HK2SXOC_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=chunk4HK2SXOC_js.a(s.data),d=await e.sessionStore.create({session:S,ttlSeconds:a}),T=chunk4HK2SXOC_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=chunk4HK2SXOC_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":chunk4HK2SXOC_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=chunk4HK2SXOC_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 chunk4HK2SXOC_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 chunk4HK2SXOC_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=chunk4HK2SXOC_js.a(s.data),S=await chunk4HK2SXOC_js.d(u,e.signingSecret,a),d=chunk4HK2SXOC_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":chunk4HK2SXOC_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}}exports.createSiwxApiHandler=k;exports.createStatelessDemoSiwxHandler=E;
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;
package/dist/next.mjs CHANGED
@@ -1 +1 @@
1
- import {h,c,a,f,g,e,d}from'./chunk-GQ7NU6NM.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-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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tuwaio/siwx-server",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "private": false,
5
5
  "author": "Oleksandr Tkach",
6
6
  "license": "Apache-2.0",
@@ -1,2 +0,0 @@
1
- 'use strict';var siwxCore=require('@tuwaio/siwx-core');function b(i){return {address:i.address,chainId:i.chainId,domain:i.domain,nonce:i.nonce,issuedAt:i.issuedAt,expirationTime:i.expirationTime}}async function R(i,n={}){try{let e=siwxCore.parseMessage(i.message),s=siwxCore.validateMessage(e,{skipExpiration:n.skipExpiration,policy:n.policy});if(!s.valid)return {success:!1,error:`Validation failed: ${s.errors.join(", ")}`};if(!n.skipExpiration&&e.expirationTime&&new Date(e.expirationTime)<new Date)throw new siwxCore.SiwxExpiredSessionError(e.expirationTime);if(n.usedNonces?.has(e.nonce))throw new siwxCore.SiwxNonceReplayError(e.nonce);let t=e.chainId.split(":")[0];if(!t||!["eip155","solana"].includes(t))throw new siwxCore.SiwxUnsupportedNamespaceError(t??"unknown");if(t==="eip155"){let{verifyEvmSignature:o}=await import('@tuwaio/siwx-evm');return {...await o(i.message,i.signature,{skipExpiration:n.skipExpiration,publicClient:n.publicClient}),namespace:t}}if(t==="solana"){let{verifyEd25519:o}=await import('@tuwaio/siwx-solana');return {...await o(i,{skipExpiration:n.skipExpiration}),namespace:t}}return {success:!1,error:"Unsupported namespace."}}catch(e){return e instanceof siwxCore.SiwxExpiredSessionError||e instanceof siwxCore.SiwxNonceReplayError||e instanceof siwxCore.SiwxUnsupportedNamespaceError?{success:false,error:e.message}:{success:false,error:`Server verification failed: ${String(e)}`}}}function E(i){return btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function T(i){let n=i.replace(/-/g,"+").replace(/_/g,"/");return atob(n)}function A(i){let n="";for(let e=0;e<i.byteLength;e++)n+=String.fromCharCode(i[e]);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function k(i){let n=i.replace(/-/g,"+").replace(/_/g,"/"),e=atob(n),s=new Uint8Array(e.length);for(let t=0;t<e.length;t++)s[t]=e.charCodeAt(t);return s}async function h(i){let n=new TextEncoder;return globalThis.crypto.subtle.importKey("raw",n.encode(i),{name:"HMAC",hash:"SHA-256"},false,["sign","verify"])}async function V(i,n,e=1800){if(!n||n.length<32)throw new Error("[SIWX-SERVER] Stateless demo signing secret must be at least 32 characters long.");let t=Date.now()+e*1e3,o={version:1,address:i.address,chainId:i.chainId,domain:i.domain,nonce:i.nonce,issuedAt:i.issuedAt,expirationTime:i.expirationTime??new Date(t).toISOString(),sessionId:siwxCore.generateNonce(),mode:"demo"},a=JSON.stringify(o),l=E(a),c=await h(n),m=new TextEncoder,d=await globalThis.crypto.subtle.sign("HMAC",c,m.encode(l)),r=A(new Uint8Array(d));return `${l}.${r}`}async function N(i,n,e){if(!i||typeof i!="string"||!n)return null;let s=i.split(".");if(s.length!==2)return null;let[t,o]=s;try{let a=await h(n),l=k(o),c=new TextEncoder;if(!await globalThis.crypto.subtle.verify("HMAC",a,l,c.encode(t)))return null;let d=T(t),r=JSON.parse(d);if(r.version!==1||r.mode!=="demo")return null;if(r.expirationTime){let u=new Date(r.expirationTime).getTime(),p=(e?.clockSkewSeconds??60)*1e3;if(isNaN(u)||u+p<Date.now())return null}return e?.expectedDomain!==void 0&&!(Array.isArray(e.expectedDomain)?e.expectedDomain:[e.expectedDomain]).some(p=>p.toLowerCase()===r.domain.toLowerCase())||e?.allowedChainIds!==void 0&&e.allowedChainIds.length>0&&!e.allowedChainIds.includes(r.chainId)?null:{address:r.address,chainId:r.chainId,domain:r.domain,nonce:r.nonce,issuedAt:r.issuedAt,expirationTime:r.expirationTime}}catch{return null}}function O(i,n={}){let{name:e="siwx-session-v2",maxAge:s=3600*24*7,path:t="/",domain:o,secure:a=true,sameSite:l="Strict"}=n,c=[`${e}=${i}`,`Max-Age=${s}`,`Path=${t}`,"HttpOnly",`SameSite=${l}`];return a&&c.push("Secure"),o&&c.push(`Domain=${o}`),c.join("; ")}function $(i={}){let{name:n="siwx-session-v2",path:e="/",domain:s}=i,t=[`${n}=`,`Path=${e}`,"Expires=Thu, 01 Jan 1970 00:00:00 GMT","Max-Age=0","HttpOnly","SameSite=Strict"];return s&&t.push(`Domain=${s}`),t.join("; ")}function B(i,n){return i?Object.fromEntries(i.split("; ").filter(Boolean).map(s=>{let t=s.split("=");return [t[0].trim(),t.slice(1).join("=")]}))[n]??null:null}var f=class{records=new Map;constructor(n){if(typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV==="production"&&!n?.allowInProduction)throw new Error("[SIWX-SERVER] MemorySiwxSessionStore must not be used in production. Connect Redis or a durable store.")}async create(n){let e=siwxCore.generateNonce(),s=Date.now(),t=s+n.ttlSeconds*1e3,o={id:e,session:n.session,createdAt:s,expiresAt:t};return this.records.set(e,o),o}async get(n){let e=this.records.get(n);return e?e.expiresAt<Date.now()?(this.records.delete(n),null):e:null}async bindSubject(n,e){let s=await this.get(n);return s?(s.subjectId=e,true):false}async revoke(n){this.records.delete(n);}},w=class{nonces=new Map;constructor(n){if(typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV==="production"&&!n?.allowInProduction)throw new Error("[SIWX-SERVER] MemorySiwxNonceStore must not be used in production. Connect Redis or a durable store.")}async issue(n){let e=Date.now()+n.ttlSeconds*1e3;this.nonces.set(n.nonce,e);}async consume(n){let e=this.nonces.get(n.nonce);return !(!e||(this.nonces.delete(n.nonce),e<Date.now()))}};
2
- Object.defineProperty(exports,"b",{enumerable:true,get:function(){return siwxCore.generateNonce}});exports.a=b;exports.c=R;exports.d=V;exports.e=N;exports.f=O;exports.g=$;exports.h=B;exports.i=f;exports.j=w;
@@ -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 b(i){return {address:i.address,chainId:i.chainId,domain:i.domain,nonce:i.nonce,issuedAt:i.issuedAt,expirationTime:i.expirationTime}}async function R(i,n={}){try{let e=parseMessage(i.message),s=validateMessage(e,{skipExpiration:n.skipExpiration,policy:n.policy});if(!s.valid)return {success:!1,error:`Validation failed: ${s.errors.join(", ")}`};if(!n.skipExpiration&&e.expirationTime&&new Date(e.expirationTime)<new Date)throw new SiwxExpiredSessionError(e.expirationTime);if(n.usedNonces?.has(e.nonce))throw new SiwxNonceReplayError(e.nonce);let t=e.chainId.split(":")[0];if(!t||!["eip155","solana"].includes(t))throw new SiwxUnsupportedNamespaceError(t??"unknown");if(t==="eip155"){let{verifyEvmSignature:o}=await import('@tuwaio/siwx-evm');return {...await o(i.message,i.signature,{skipExpiration:n.skipExpiration,publicClient:n.publicClient}),namespace:t}}if(t==="solana"){let{verifyEd25519:o}=await import('@tuwaio/siwx-solana');return {...await o(i,{skipExpiration:n.skipExpiration}),namespace:t}}return {success:!1,error:"Unsupported namespace."}}catch(e){return e instanceof SiwxExpiredSessionError||e instanceof SiwxNonceReplayError||e instanceof SiwxUnsupportedNamespaceError?{success:false,error:e.message}:{success:false,error:`Server verification failed: ${String(e)}`}}}function E(i){return btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function T(i){let n=i.replace(/-/g,"+").replace(/_/g,"/");return atob(n)}function A(i){let n="";for(let e=0;e<i.byteLength;e++)n+=String.fromCharCode(i[e]);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function k(i){let n=i.replace(/-/g,"+").replace(/_/g,"/"),e=atob(n),s=new Uint8Array(e.length);for(let t=0;t<e.length;t++)s[t]=e.charCodeAt(t);return s}async function h(i){let n=new TextEncoder;return globalThis.crypto.subtle.importKey("raw",n.encode(i),{name:"HMAC",hash:"SHA-256"},false,["sign","verify"])}async function V(i,n,e=1800){if(!n||n.length<32)throw new Error("[SIWX-SERVER] Stateless demo signing secret must be at least 32 characters long.");let t=Date.now()+e*1e3,o={version:1,address:i.address,chainId:i.chainId,domain:i.domain,nonce:i.nonce,issuedAt:i.issuedAt,expirationTime:i.expirationTime??new Date(t).toISOString(),sessionId:generateNonce(),mode:"demo"},a=JSON.stringify(o),l=E(a),c=await h(n),m=new TextEncoder,d=await globalThis.crypto.subtle.sign("HMAC",c,m.encode(l)),r=A(new Uint8Array(d));return `${l}.${r}`}async function N(i,n,e){if(!i||typeof i!="string"||!n)return null;let s=i.split(".");if(s.length!==2)return null;let[t,o]=s;try{let a=await h(n),l=k(o),c=new TextEncoder;if(!await globalThis.crypto.subtle.verify("HMAC",a,l,c.encode(t)))return null;let d=T(t),r=JSON.parse(d);if(r.version!==1||r.mode!=="demo")return null;if(r.expirationTime){let u=new Date(r.expirationTime).getTime(),p=(e?.clockSkewSeconds??60)*1e3;if(isNaN(u)||u+p<Date.now())return null}return e?.expectedDomain!==void 0&&!(Array.isArray(e.expectedDomain)?e.expectedDomain:[e.expectedDomain]).some(p=>p.toLowerCase()===r.domain.toLowerCase())||e?.allowedChainIds!==void 0&&e.allowedChainIds.length>0&&!e.allowedChainIds.includes(r.chainId)?null:{address:r.address,chainId:r.chainId,domain:r.domain,nonce:r.nonce,issuedAt:r.issuedAt,expirationTime:r.expirationTime}}catch{return null}}function O(i,n={}){let{name:e="siwx-session-v2",maxAge:s=3600*24*7,path:t="/",domain:o,secure:a=true,sameSite:l="Strict"}=n,c=[`${e}=${i}`,`Max-Age=${s}`,`Path=${t}`,"HttpOnly",`SameSite=${l}`];return a&&c.push("Secure"),o&&c.push(`Domain=${o}`),c.join("; ")}function $(i={}){let{name:n="siwx-session-v2",path:e="/",domain:s}=i,t=[`${n}=`,`Path=${e}`,"Expires=Thu, 01 Jan 1970 00:00:00 GMT","Max-Age=0","HttpOnly","SameSite=Strict"];return s&&t.push(`Domain=${s}`),t.join("; ")}function B(i,n){return i?Object.fromEntries(i.split("; ").filter(Boolean).map(s=>{let t=s.split("=");return [t[0].trim(),t.slice(1).join("=")]}))[n]??null:null}var f=class{records=new Map;constructor(n){if(typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV==="production"&&!n?.allowInProduction)throw new Error("[SIWX-SERVER] MemorySiwxSessionStore must not be used in production. Connect Redis or a durable store.")}async create(n){let e=generateNonce(),s=Date.now(),t=s+n.ttlSeconds*1e3,o={id:e,session:n.session,createdAt:s,expiresAt:t};return this.records.set(e,o),o}async get(n){let e=this.records.get(n);return e?e.expiresAt<Date.now()?(this.records.delete(n),null):e:null}async bindSubject(n,e){let s=await this.get(n);return s?(s.subjectId=e,true):false}async revoke(n){this.records.delete(n);}},w=class{nonces=new Map;constructor(n){if(typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV==="production"&&!n?.allowInProduction)throw new Error("[SIWX-SERVER] MemorySiwxNonceStore must not be used in production. Connect Redis or a durable store.")}async issue(n){let e=Date.now()+n.ttlSeconds*1e3;this.nonces.set(n.nonce,e);}async consume(n){let e=this.nonces.get(n.nonce);return !(!e||(this.nonces.delete(n.nonce),e<Date.now()))}};
2
- export{b as a,R as c,V as d,N as e,O as f,$ as g,B as h,f as i,w as j};
@@ -1,193 +0,0 @@
1
- import { SiwxVerificationPolicy, SiwxVerifyResult, ParsedSiwxMessage } from '@tuwaio/siwx-core';
2
-
3
- /**
4
- * @fileoverview Server-side types for the @tuwaio/siwx-server package.
5
- */
6
-
7
- /**
8
- * Options for the `verifySiwxPayload` function.
9
- */
10
- interface ServerVerifyOptions {
11
- /**
12
- * A set of nonces that have already been used.
13
- * If the payload's nonce is found in this set, verification will fail
14
- * to prevent replay attacks.
15
- */
16
- usedNonces?: Set<string>;
17
- /**
18
- * If true, skips the `expirationTime` validation check.
19
- * Not recommended for production use.
20
- * @default false
21
- */
22
- skipExpiration?: boolean;
23
- /**
24
- * Optional verification policy to enforce on the message fields.
25
- */
26
- policy?: SiwxVerificationPolicy;
27
- /**
28
- * Optional viem `PublicClient` instance for EVM chain EIP-1271 (smart contract wallet) verification.
29
- */
30
- publicClient?: any;
31
- }
32
- /**
33
- * The result of a server-side verification operation, extending the base result
34
- * with the verification method used.
35
- */
36
- interface ServerVerifyResult extends SiwxVerifyResult {
37
- /**
38
- * The CAIP-2 namespace used for verification routing.
39
- * `eip155` for EVM chains, `solana` for Solana.
40
- */
41
- namespace?: 'eip155' | 'solana';
42
- }
43
- /**
44
- * Represents a serializable session object derived from a verified CAIP-122 message.
45
- */
46
- interface SiwxSession {
47
- /** The verified CAIP-10 blockchain address. */
48
- address: string;
49
- /** The CAIP-2 chain ID the session is bound to. */
50
- chainId: string;
51
- /** The domain that issued the session. */
52
- domain: string;
53
- /** The nonce that was used. Must be invalidated server-side after use. */
54
- nonce: string;
55
- /** ISO 8601 timestamp when the session was issued. */
56
- issuedAt: string;
57
- /** ISO 8601 timestamp when the session expires, if set. */
58
- expirationTime?: string;
59
- }
60
- /**
61
- * Represents a stored session record in a durable session store.
62
- */
63
- interface SiwxSessionRecord {
64
- /** Unique opaque session identifier (e.g. secure random UUID). */
65
- id: string;
66
- /** The verified SIWX session data. */
67
- session: SiwxSession;
68
- /** Optional subject ID (e.g., Payload User ID or internal database ID) bound to this session. */
69
- subjectId?: string;
70
- /** Timestamp in milliseconds when the session record was created. */
71
- createdAt: number;
72
- /** Timestamp in milliseconds when the session record expires. */
73
- expiresAt: number;
74
- }
75
- /**
76
- * Durable session store interface for production environments.
77
- */
78
- interface SiwxSessionStore {
79
- /**
80
- * Creates and stores a new session record.
81
- * @param input.session - The verified session data.
82
- * @param input.ttlSeconds - Time-to-live in seconds.
83
- * @returns The created session record with unique ID.
84
- */
85
- create(input: {
86
- session: SiwxSession;
87
- ttlSeconds: number;
88
- }): Promise<SiwxSessionRecord>;
89
- /**
90
- * Retrieves a session record by its opaque ID.
91
- * @param id - The session ID.
92
- * @returns The session record, or null if not found or expired.
93
- */
94
- get(id: string): Promise<SiwxSessionRecord | null>;
95
- /**
96
- * Atomically binds a user/subject identifier to the session.
97
- * @param id - The session ID.
98
- * @param subjectId - The user or subject ID.
99
- * @returns True if binding succeeded, false if session not found.
100
- */
101
- bindSubject(id: string, subjectId: string): Promise<boolean>;
102
- /**
103
- * Revokes and removes a session record.
104
- * @param id - The session ID.
105
- */
106
- revoke(id: string): Promise<void>;
107
- }
108
- /**
109
- * Durable nonce store interface for single-use nonce issuance and atomic consumption.
110
- */
111
- interface SiwxNonceStore {
112
- /**
113
- * Issues and stores a new challenge nonce with TTL.
114
- * @param input.nonce - The unique nonce string.
115
- * @param input.ttlSeconds - Time-to-live in seconds (typically 300s).
116
- */
117
- issue(input: {
118
- nonce: string;
119
- ttlSeconds: number;
120
- }): Promise<void>;
121
- /**
122
- * Atomically consumes a nonce, guaranteeing single-use.
123
- * @param input.nonce - The nonce string to consume.
124
- * @returns True if the nonce was valid and consumed, false if already consumed or expired.
125
- */
126
- consume(input: {
127
- nonce: string;
128
- }): Promise<boolean>;
129
- }
130
- /**
131
- * Compact payload structure for stateless demo session tokens.
132
- */
133
- interface StatelessDemoTokenPayload {
134
- version: 1;
135
- address: string;
136
- chainId: string;
137
- domain: string;
138
- nonce: string;
139
- issuedAt: string;
140
- expirationTime?: string;
141
- sessionId: string;
142
- mode: 'demo';
143
- }
144
- /**
145
- * Limits for stateless demo profile.
146
- */
147
- interface StatelessDemoLimits {
148
- /** Maximum transaction payload size in bytes. */
149
- maxTransactionPayloadBytes?: number;
150
- /** Advisory request cap per session. */
151
- maxRequestsPerSession?: number;
152
- }
153
- /**
154
- * Options for cookie session serialization.
155
- */
156
- interface CookieOptions {
157
- /**
158
- * The name of the cookie.
159
- * @default "siwx-session-v2"
160
- */
161
- name?: string;
162
- /**
163
- * Max age in seconds. Defaults to 7 days for durable, 30 minutes for demo.
164
- * @default 604800
165
- */
166
- maxAge?: number;
167
- /**
168
- * The cookie path.
169
- * @default "/"
170
- */
171
- path?: string;
172
- /**
173
- * The cookie domain.
174
- */
175
- domain?: string;
176
- /**
177
- * Whether to set the Secure flag.
178
- * @default true
179
- */
180
- secure?: boolean;
181
- /**
182
- * The SameSite policy.
183
- * @default "Strict"
184
- */
185
- sameSite?: 'Strict' | 'Lax' | 'None';
186
- }
187
- /**
188
- * Converts a ParsedSiwxMessage to a lean SiwxSession object.
189
- * @internal
190
- */
191
- declare function toSession(parsed: ParsedSiwxMessage): SiwxSession;
192
-
193
- export { type CookieOptions as C, type SiwxNonceStore as S, type SiwxSessionStore as a, type SiwxSession as b, type SiwxSessionRecord as c, type ServerVerifyOptions as d, type ServerVerifyResult as e, type StatelessDemoLimits as f, type StatelessDemoTokenPayload as g, toSession as t };
@@ -1,193 +0,0 @@
1
- import { SiwxVerificationPolicy, SiwxVerifyResult, ParsedSiwxMessage } from '@tuwaio/siwx-core';
2
-
3
- /**
4
- * @fileoverview Server-side types for the @tuwaio/siwx-server package.
5
- */
6
-
7
- /**
8
- * Options for the `verifySiwxPayload` function.
9
- */
10
- interface ServerVerifyOptions {
11
- /**
12
- * A set of nonces that have already been used.
13
- * If the payload's nonce is found in this set, verification will fail
14
- * to prevent replay attacks.
15
- */
16
- usedNonces?: Set<string>;
17
- /**
18
- * If true, skips the `expirationTime` validation check.
19
- * Not recommended for production use.
20
- * @default false
21
- */
22
- skipExpiration?: boolean;
23
- /**
24
- * Optional verification policy to enforce on the message fields.
25
- */
26
- policy?: SiwxVerificationPolicy;
27
- /**
28
- * Optional viem `PublicClient` instance for EVM chain EIP-1271 (smart contract wallet) verification.
29
- */
30
- publicClient?: any;
31
- }
32
- /**
33
- * The result of a server-side verification operation, extending the base result
34
- * with the verification method used.
35
- */
36
- interface ServerVerifyResult extends SiwxVerifyResult {
37
- /**
38
- * The CAIP-2 namespace used for verification routing.
39
- * `eip155` for EVM chains, `solana` for Solana.
40
- */
41
- namespace?: 'eip155' | 'solana';
42
- }
43
- /**
44
- * Represents a serializable session object derived from a verified CAIP-122 message.
45
- */
46
- interface SiwxSession {
47
- /** The verified CAIP-10 blockchain address. */
48
- address: string;
49
- /** The CAIP-2 chain ID the session is bound to. */
50
- chainId: string;
51
- /** The domain that issued the session. */
52
- domain: string;
53
- /** The nonce that was used. Must be invalidated server-side after use. */
54
- nonce: string;
55
- /** ISO 8601 timestamp when the session was issued. */
56
- issuedAt: string;
57
- /** ISO 8601 timestamp when the session expires, if set. */
58
- expirationTime?: string;
59
- }
60
- /**
61
- * Represents a stored session record in a durable session store.
62
- */
63
- interface SiwxSessionRecord {
64
- /** Unique opaque session identifier (e.g. secure random UUID). */
65
- id: string;
66
- /** The verified SIWX session data. */
67
- session: SiwxSession;
68
- /** Optional subject ID (e.g., Payload User ID or internal database ID) bound to this session. */
69
- subjectId?: string;
70
- /** Timestamp in milliseconds when the session record was created. */
71
- createdAt: number;
72
- /** Timestamp in milliseconds when the session record expires. */
73
- expiresAt: number;
74
- }
75
- /**
76
- * Durable session store interface for production environments.
77
- */
78
- interface SiwxSessionStore {
79
- /**
80
- * Creates and stores a new session record.
81
- * @param input.session - The verified session data.
82
- * @param input.ttlSeconds - Time-to-live in seconds.
83
- * @returns The created session record with unique ID.
84
- */
85
- create(input: {
86
- session: SiwxSession;
87
- ttlSeconds: number;
88
- }): Promise<SiwxSessionRecord>;
89
- /**
90
- * Retrieves a session record by its opaque ID.
91
- * @param id - The session ID.
92
- * @returns The session record, or null if not found or expired.
93
- */
94
- get(id: string): Promise<SiwxSessionRecord | null>;
95
- /**
96
- * Atomically binds a user/subject identifier to the session.
97
- * @param id - The session ID.
98
- * @param subjectId - The user or subject ID.
99
- * @returns True if binding succeeded, false if session not found.
100
- */
101
- bindSubject(id: string, subjectId: string): Promise<boolean>;
102
- /**
103
- * Revokes and removes a session record.
104
- * @param id - The session ID.
105
- */
106
- revoke(id: string): Promise<void>;
107
- }
108
- /**
109
- * Durable nonce store interface for single-use nonce issuance and atomic consumption.
110
- */
111
- interface SiwxNonceStore {
112
- /**
113
- * Issues and stores a new challenge nonce with TTL.
114
- * @param input.nonce - The unique nonce string.
115
- * @param input.ttlSeconds - Time-to-live in seconds (typically 300s).
116
- */
117
- issue(input: {
118
- nonce: string;
119
- ttlSeconds: number;
120
- }): Promise<void>;
121
- /**
122
- * Atomically consumes a nonce, guaranteeing single-use.
123
- * @param input.nonce - The nonce string to consume.
124
- * @returns True if the nonce was valid and consumed, false if already consumed or expired.
125
- */
126
- consume(input: {
127
- nonce: string;
128
- }): Promise<boolean>;
129
- }
130
- /**
131
- * Compact payload structure for stateless demo session tokens.
132
- */
133
- interface StatelessDemoTokenPayload {
134
- version: 1;
135
- address: string;
136
- chainId: string;
137
- domain: string;
138
- nonce: string;
139
- issuedAt: string;
140
- expirationTime?: string;
141
- sessionId: string;
142
- mode: 'demo';
143
- }
144
- /**
145
- * Limits for stateless demo profile.
146
- */
147
- interface StatelessDemoLimits {
148
- /** Maximum transaction payload size in bytes. */
149
- maxTransactionPayloadBytes?: number;
150
- /** Advisory request cap per session. */
151
- maxRequestsPerSession?: number;
152
- }
153
- /**
154
- * Options for cookie session serialization.
155
- */
156
- interface CookieOptions {
157
- /**
158
- * The name of the cookie.
159
- * @default "siwx-session-v2"
160
- */
161
- name?: string;
162
- /**
163
- * Max age in seconds. Defaults to 7 days for durable, 30 minutes for demo.
164
- * @default 604800
165
- */
166
- maxAge?: number;
167
- /**
168
- * The cookie path.
169
- * @default "/"
170
- */
171
- path?: string;
172
- /**
173
- * The cookie domain.
174
- */
175
- domain?: string;
176
- /**
177
- * Whether to set the Secure flag.
178
- * @default true
179
- */
180
- secure?: boolean;
181
- /**
182
- * The SameSite policy.
183
- * @default "Strict"
184
- */
185
- sameSite?: 'Strict' | 'Lax' | 'None';
186
- }
187
- /**
188
- * Converts a ParsedSiwxMessage to a lean SiwxSession object.
189
- * @internal
190
- */
191
- declare function toSession(parsed: ParsedSiwxMessage): SiwxSession;
192
-
193
- export { type CookieOptions as C, type SiwxNonceStore as S, type SiwxSessionStore as a, type SiwxSession as b, type SiwxSessionRecord as c, type ServerVerifyOptions as d, type ServerVerifyResult as e, type StatelessDemoLimits as f, type StatelessDemoTokenPayload as g, toSession as t };