@tuwaio/siwx-server 0.1.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
@@ -3,16 +3,18 @@
3
3
  [![NPM Version](https://img.shields.io/npm/v/@tuwaio/siwx-server.svg)](https://www.npmjs.com/package/@tuwaio/siwx-server)
4
4
  [![License](https://img.shields.io/npm/l/@tuwaio/siwx-server.svg)](./LICENSE)
5
5
 
6
- > Backend utilities for `@tuwaio/siwx` (L2). Server-side CAIP-122 payload verification, session serialization, and nonce generation. Fully backend-agnostic — works with any framework.
6
+ > Backend utilities for `@tuwaio/siwx` (L2). Server-side CAIP-122 payload verification, durable session store abstractions, authenticated stateless demo handlers, and single-use nonce generation. Fully backend-agnostic.
7
7
 
8
8
  ---
9
9
 
10
10
  ## 🏛️ Core Capabilities
11
11
 
12
- - **`verifySiwxPayload()`**: The primary server entry point. Parses the CAIP-122 message, validates all fields, checks for nonce replay attacks, and dynamically dispatches to the correct chain verifier (`siwx-evm` or `siwx-solana`) based on the CAIP-2 namespace.
13
- - **`serializeCookieSession()`**: Generates a complete `Set-Cookie` header string with an `HttpOnly` session.
14
- - **`deserializeCookieSession()`**: Reads and deserializes a session from a cookie value.
15
- - **`generateServerNonce()`**: A convenience re-export of `generateNonce` from `siwx-core` for generating nonces server-side.
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`).
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.
15
+ - **`createStatelessDemoSiwxHandler()`**: Authenticated HMAC-SHA256 session handler for zero-infrastructure demonstration environments and rapid prototyping.
16
+ - **`signStatelessDemoSession()` / `verifyStatelessDemoSession()`**: Web Crypto API constant-time HMAC signing and verification for demo tokens.
17
+ - **`MemorySiwxSessionStore` / `MemorySiwxNonceStore`**: In-memory stores explicitly designated for local development and testing (fails closed in production).
16
18
 
17
19
  ---
18
20
 
@@ -20,159 +22,298 @@
20
22
 
21
23
  ```bash
22
24
  pnpm add @tuwaio/siwx-server @tuwaio/siwx-core
23
- # + chain adapters (auto-imported dynamically):
25
+ # + chain adapters (dynamically imported at runtime):
24
26
  pnpm add @tuwaio/siwx-evm @tuwaio/siwx-solana
25
27
  ```
26
28
 
27
29
  ---
28
30
 
29
- ## 🚀 API & Module Architecture
31
+ ## 🛡️ Architecture Profiles
30
32
 
31
- ### `createSiwxApiHandler(options?)` (Next.js App Router)
33
+ ### 1. Durable Profile (Production Standard)
32
34
 
33
- A ready-to-use Next.js Route Handler for handling the full SIWX lifecycle (`/verify`, `/session`, `/logout`). It works purely with standard Web `Request`/`Response` APIs, keeping your backend fast and edge-compatible.
35
+ For production applications with user accounts, persistent logins, session revocation, and multi-replica horizontal scaling.
36
+
37
+ #### Step 1: Implement or Configure Auth Stores (`lib/authStores.ts`)
34
38
 
35
39
  ```ts
36
- // app/api/siwx/[...siwx]/route.ts
37
- import { createSiwxApiHandler } from '@tuwaio/siwx-server/next';
40
+ // lib/authStores.ts
41
+ import type { SiwxNonceStore, SiwxSession, SiwxSessionRecord, SiwxSessionStore } from '@tuwaio/siwx-server';
42
+ import { generateServerNonce } from '@tuwaio/siwx-server';
43
+ import Redis from 'ioredis';
38
44
 
39
- const handler = createSiwxApiHandler({
40
- cookieOptions: {
41
- name: 'tuwa-auth',
42
- secure: process.env.NODE_ENV === 'production',
45
+ const redis = new Redis(process.env.REDIS_URL || 'redis://localhost:6379');
46
+
47
+ export const sessionStore: SiwxSessionStore = {
48
+ async create({ session, ttlSeconds }: { session: SiwxSession; ttlSeconds: number }): Promise<SiwxSessionRecord> {
49
+ const id = generateServerNonce();
50
+ const createdAt = Date.now();
51
+ const expiresAt = createdAt + ttlSeconds * 1000;
52
+ const record: SiwxSessionRecord = { id, session, createdAt, expiresAt };
53
+
54
+ await redis.set(`siwx:session:${id}`, JSON.stringify(record), 'EX', ttlSeconds);
55
+ return record;
43
56
  },
44
- // Optional: Pass used nonces to prevent replay attacks
45
- verifyOptions: {
46
- // usedNonces: await getNonceStore()
57
+
58
+ async get(id: string): Promise<SiwxSessionRecord | null> {
59
+ const data = await redis.get(`siwx:session:${id}`);
60
+ return data ? JSON.parse(data) : null;
47
61
  },
48
- });
49
62
 
50
- // Automatically exposes GET, POST, and DELETE methods
51
- export const { GET, POST, DELETE } = handler;
63
+ async bindSubject(id: string, subjectId: string): Promise<boolean> {
64
+ const record = await this.get(id);
65
+ if (!record) return false;
66
+ record.subjectId = subjectId;
67
+ const ttl = Math.max(1, Math.floor((record.expiresAt - Date.now()) / 1000));
68
+ await redis.set(`siwx:session:${id}`, JSON.stringify(record), 'EX', ttl);
69
+ return true;
70
+ },
71
+
72
+ async revoke(id: string): Promise<void> {
73
+ await redis.del(`siwx:session:${id}`);
74
+ },
75
+ };
76
+
77
+ export const nonceStore: SiwxNonceStore = {
78
+ async issue({ nonce, ttlSeconds }: { nonce: string; ttlSeconds: number }): Promise<void> {
79
+ await redis.set(`siwx:nonce:${nonce}`, '1', 'EX', ttlSeconds);
80
+ },
81
+
82
+ async consume({ nonce }: { nonce: string }): Promise<boolean> {
83
+ // Atomic single-use consumption via GETDEL
84
+ const value = await redis.getdel(`siwx:nonce:${nonce}`);
85
+ return value !== null;
86
+ },
87
+ };
52
88
  ```
53
89
 
54
- ---
90
+ #### Alternative: In-Memory Stores for Local Testing / Prototyping (No Redis Needed)
55
91
 
56
- ## Manual Verification API
92
+ For local development or testing without spinning up Redis, you can use the built-in in-memory stores directly from `@tuwaio/siwx-server`:
57
93
 
58
- If you aren't using Next.js or prefer full control, you can use the low-level utilities.
94
+ ```ts
95
+ // lib/authStores.dev.ts (Zero Dependencies / In-Memory)
96
+ import { MemorySiwxNonceStore, MemorySiwxSessionStore } from '@tuwaio/siwx-server';
59
97
 
60
- ### `verifySiwxPayload(payload, options?): Promise<ServerVerifyResult>`
98
+ // Built-in in-memory stores for local testing (fails closed in production by default)
99
+ export const sessionStore = new MemorySiwxSessionStore();
100
+ export const nonceStore = new MemorySiwxNonceStore();
101
+ ```
61
102
 
62
- The main server-side verification entry point. Chain is detected automatically from the CAIP-2 `chainId` in the message. Accepts optional `options?: ServerVerifyOptions` (`usedNonces?: Set<string>`, `skipExpiration?: boolean`).
103
+ Or write a custom `Map`-based storage adapter without external dependencies:
63
104
 
64
105
  ```ts
65
- import { verifySiwxPayload, serializeCookieSession, toSession } from '@tuwaio/siwx-server';
106
+ // lib/authStores.memory.ts (Custom Zero-Dependency In-Memory Store)
107
+ import type { SiwxNonceStore, SiwxSession, SiwxSessionRecord, SiwxSessionStore } from '@tuwaio/siwx-server';
108
+ import { generateServerNonce } from '@tuwaio/siwx-server';
66
109
 
67
- // In a Next.js API Route or NestJS Controller:
68
- export async function POST(request: Request) {
69
- const { message, signature } = await request.json();
110
+ const sessionMap = new Map<string, SiwxSessionRecord>();
111
+ const nonceMap = new Map<string, number>();
112
+
113
+ export const sessionStore: SiwxSessionStore = {
114
+ async create({ session, ttlSeconds }: { session: SiwxSession; ttlSeconds: number }): Promise<SiwxSessionRecord> {
115
+ const id = generateServerNonce();
116
+ const createdAt = Date.now();
117
+ const expiresAt = createdAt + ttlSeconds * 1000;
118
+ const record: SiwxSessionRecord = { id, session, createdAt, expiresAt };
119
+ sessionMap.set(id, record);
120
+ return record;
121
+ },
70
122
 
71
- const result = await verifySiwxPayload(
72
- { message, signature },
73
- { usedNonces: await getNonceStore() }, // pass your consumed nonces set
74
- );
123
+ async get(id: string): Promise<SiwxSessionRecord | null> {
124
+ const record = sessionMap.get(id);
125
+ if (!record || record.expiresAt < Date.now()) {
126
+ sessionMap.delete(id);
127
+ return null;
128
+ }
129
+ return record;
130
+ },
75
131
 
76
- if (!result.success) {
77
- return new Response(result.error, { status: 401 });
78
- }
132
+ async bindSubject(id: string, subjectId: string): Promise<boolean> {
133
+ const record = await this.get(id);
134
+ if (!record) return false;
135
+ record.subjectId = subjectId;
136
+ return true;
137
+ },
79
138
 
80
- // Session is valid — issue cookie
81
- const { cookieHeader } = serializeCookieSession(toSession(result.data!));
82
- return new Response('OK', {
83
- headers: { 'Set-Cookie': cookieHeader },
84
- });
85
- }
86
- ```
139
+ async revoke(id: string): Promise<void> {
140
+ sessionMap.delete(id);
141
+ },
142
+ };
143
+
144
+ export const nonceStore: SiwxNonceStore = {
145
+ async issue({ nonce, ttlSeconds }: { nonce: string; ttlSeconds: number }): Promise<void> {
146
+ nonceMap.set(nonce, Date.now() + ttlSeconds * 1000);
147
+ },
87
148
 
88
- ### `serializeCookieSession(session, opts?): SerializedCookieSession`
149
+ async consume({ nonce }: { nonce: string }): Promise<boolean> {
150
+ const expiresAt = nonceMap.get(nonce);
151
+ if (!expiresAt || expiresAt < Date.now()) {
152
+ nonceMap.delete(nonce);
153
+ return false;
154
+ }
155
+ nonceMap.delete(nonce); // Atomic single-use consumption
156
+ return true;
157
+ },
158
+ };
159
+ ```
89
160
 
90
- Serializes a `SiwxSession` into a `Set-Cookie` header string.
161
+ #### Step 2: Configure the Route Handler (`app/api/siwx/[...siwx]/route.ts`)
91
162
 
92
163
  ```ts
93
- import { serializeCookieSession } from '@tuwaio/siwx-server';
164
+ // app/api/siwx/[...siwx]/route.ts
165
+ import { createSiwxApiHandler } from '@tuwaio/siwx-server/next';
166
+ import { nonceStore, sessionStore } from '@/lib/authStores';
94
167
 
95
- const { cookieHeader } = serializeCookieSession(session, {
96
- name: 'tuwa-auth',
97
- maxAge: 60 * 60 * 24 * 7, // 7 days
98
- secure: true,
99
- sameSite: 'Strict',
168
+ const handler = createSiwxApiHandler({
169
+ sessionStore,
170
+ nonceStore,
171
+ policy: {
172
+ expectedDomain: 'app.tuwa.io',
173
+ expectedUri: 'https://app.tuwa.io',
174
+ allowedChainIds: ['eip155:1', 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpK'],
175
+ maxIssuedAtAgeSeconds: 300,
176
+ },
177
+ cookieOptions: {
178
+ name: 'siwx-session-v2',
179
+ secure: process.env.NODE_ENV === 'production',
180
+ },
100
181
  });
182
+
183
+ export const { GET, POST, DELETE } = handler;
101
184
  ```
102
185
 
103
- ### `deserializeCookieSession(cookieValue): SiwxSession | null`
186
+ ---
187
+
188
+ ### 2. Stateless Demo Profile (Zero-Infrastructure Demonstration & Prototyping)
104
189
 
105
- Reads and parses a session from a cookie value (the inverse of `serializeCookieSession`).
190
+ For sandbox environments, developer playgrounds, integration tests, or demonstration websites running without a backing database or Redis instance.
106
191
 
107
192
  ```ts
108
- import { deserializeCookieSession } from '@tuwaio/siwx-server';
193
+ // app/api/siwx/[...siwx]/route.ts
194
+ import { createStatelessDemoSiwxHandler } from '@tuwaio/siwx-server/next';
195
+
196
+ const handler = createStatelessDemoSiwxHandler({
197
+ signingSecret: process.env.SIWX_DEMO_SIGNING_SECRET!, // Minimum 32 characters
198
+ policy: {
199
+ expectedDomain: 'demo.tuwa.io',
200
+ requireExpirationTime: true,
201
+ maxIssuedAtAgeSeconds: 300,
202
+ maxSessionLifetimeSeconds: 1800, // 30 minutes max session
203
+ },
204
+ cookieOptions: {
205
+ name: 'siwx-demo-session',
206
+ secure: process.env.NODE_ENV === 'production',
207
+ },
208
+ });
109
209
 
110
- const cookie = request.cookies.get('tuwa-auth')?.value;
111
- const session = deserializeCookieSession(cookie ?? '');
112
- if (!session) throw new Error('No valid session');
210
+ export const { GET, POST, DELETE } = handler;
113
211
  ```
114
212
 
115
- ### `generateServerNonce(): string`
213
+ > **Warning**: Demo mode works without a database or Redis by using a short-lived stateless session. Real projects with user accounts, persistent login, logout/revoke, multi-replica deployment, and strong protection against session replay MUST connect Redis, PostgreSQL, SQLite, or another durable storage adapter.
116
214
 
117
- Generates a secure nonce for sending to the client. Store it in Redis or your DB before sending.
215
+ ---
118
216
 
119
- ```ts
120
- import { generateServerNonce } from '@tuwaio/siwx-server';
217
+ ### 3. Server Actions & Route Session Resolution (`getSiwxServerSession`)
121
218
 
122
- const nonce = generateServerNonce();
123
- await redis.set(`nonce:${nonce}`, '1', 'EX', 300); // expires in 5 min
124
- ```
219
+ Use `getSiwxServerSession` in Next.js Server Actions or server-side routes to securely resolve authenticated sessions without accepting client-provided session parameters:
125
220
 
126
- ### `toSession(parsed: ParsedSiwxMessage): SiwxSession`
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
+ });
127
236
 
128
- Converts a `ParsedSiwxMessage` into a lean `SiwxSession` object.
237
+ if (!session) {
238
+ throw new Error('Unauthorized: No active session.');
239
+ }
129
240
 
130
- ```ts
131
- import { toSession } from '@tuwaio/siwx-server';
241
+ // 2. Enforce cryptographic subject/address binding
242
+ if (!isSessionMatchingTarget(session, targetAddress)) {
243
+ throw new Error('Forbidden: Wallet address mismatch.');
244
+ }
132
245
 
133
- const session = toSession(parsedMessage);
246
+ // 3. Execute privileged server business logic
247
+ return { success: true };
248
+ }
134
249
  ```
135
250
 
136
- ### `isSessionMatchingTarget(session, targetAddress, targetChainId?)`
251
+ ---
252
+
253
+ ## 🚀 Low-Level Manual Verification API
137
254
 
138
- Re-exported from `@tuwaio/siwx-core` for server-side authorization checks. Validates if a session matches a target account address and optional chainId.
255
+ For custom controllers (NestJS, Fastify, Express, Cloudflare Workers):
139
256
 
140
257
  ```ts
141
- import { isSessionMatchingTarget } from '@tuwaio/siwx-server';
258
+ import { toSession, verifySiwxPayload } from '@tuwaio/siwx-server';
259
+
260
+ export async function handleVerify(request: Request) {
261
+ const { message, signature } = await request.json();
262
+
263
+ const result = await verifySiwxPayload(
264
+ { message, signature },
265
+ {
266
+ policy: {
267
+ expectedDomain: 'app.tuwa.io',
268
+ allowedChainIds: ['eip155:1'],
269
+ },
270
+ },
271
+ );
272
+
273
+ if (!result.success || !result.data) {
274
+ return new Response(JSON.stringify({ error: result.error }), { status: 401 });
275
+ }
142
276
 
143
- const isValid = isSessionMatchingTarget(session, userAddress, chainId);
277
+ const session = toSession(result.data);
278
+ return new Response(JSON.stringify(session), { status: 200 });
279
+ }
144
280
  ```
145
281
 
146
282
  ---
147
283
 
148
- ## Nonce Replay Protection
284
+ ## 📦 Store Interfaces
149
285
 
150
- Always invalidate used nonces after verification:
286
+ ### `SiwxSessionStore`
151
287
 
152
288
  ```ts
153
- const result = await verifySiwxPayload(
154
- { message, signature },
155
- {
156
- usedNonces: new Set(await redis.smembers('used_nonces')),
157
- },
158
- );
159
-
160
- if (result.success) {
161
- // Mark nonce as consumed
162
- await redis.sadd('used_nonces', result.data!.nonce);
163
- await redis.expire('used_nonces', 86400); // cleanup after 24h
289
+ export interface SiwxSessionStore {
290
+ create(input: { session: SiwxSession; ttlSeconds: number }): Promise<SiwxSessionRecord>;
291
+ get(id: string): Promise<SiwxSessionRecord | null>;
292
+ bindSubject(id: string, subjectId: string): Promise<boolean>;
293
+ revoke(id: string): Promise<void>;
164
294
  }
165
295
  ```
166
296
 
167
- ---
297
+ ### `SiwxNonceStore`
168
298
 
169
- ## Peer Dependencies
299
+ ```ts
300
+ export interface SiwxNonceStore {
301
+ issue(input: { nonce: string; ttlSeconds: number }): Promise<void>;
302
+ consume(input: { nonce: string }): Promise<boolean>;
303
+ }
304
+ ```
170
305
 
171
- | Package | Version |
172
- | ------------------- | ------------- |
173
- | `@tuwaio/siwx-core` | `workspace:*` |
306
+ ### `SiwxSessionRecord`
174
307
 
175
- Chain adapters are dynamically imported at runtime — only install the ones you need.
308
+ ```ts
309
+ export interface SiwxSessionRecord {
310
+ id: string;
311
+ session: SiwxSession;
312
+ subjectId?: string;
313
+ createdAt: number;
314
+ expiresAt: number;
315
+ }
316
+ ```
176
317
 
177
318
  ---
178
319
 
@@ -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};