@tuwaio/siwx-server 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,16 +3,17 @@
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
+ - **`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
+ - **`createStatelessDemoSiwxHandler()`**: Authenticated HMAC-SHA256 session handler for zero-infrastructure demonstration environments and rapid prototyping.
15
+ - **`signStatelessDemoSession()` / `verifyStatelessDemoSession()`**: Web Crypto API constant-time HMAC signing and verification for demo tokens.
16
+ - **`MemorySiwxSessionStore` / `MemorySiwxNonceStore`**: In-memory stores explicitly designated for local development and testing (fails closed in production).
16
17
 
17
18
  ---
18
19
 
@@ -20,159 +21,262 @@
20
21
 
21
22
  ```bash
22
23
  pnpm add @tuwaio/siwx-server @tuwaio/siwx-core
23
- # + chain adapters (auto-imported dynamically):
24
+ # + chain adapters (dynamically imported at runtime):
24
25
  pnpm add @tuwaio/siwx-evm @tuwaio/siwx-solana
25
26
  ```
26
27
 
27
28
  ---
28
29
 
29
- ## 🚀 API & Module Architecture
30
+ ## 🛡️ Architecture Profiles
30
31
 
31
- ### `createSiwxApiHandler(options?)` (Next.js App Router)
32
+ ### 1. Durable Profile (Production Standard)
32
33
 
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.
34
+ For production applications with user accounts, persistent logins, session revocation, and multi-replica horizontal scaling.
35
+
36
+ #### Step 1: Implement or Configure Auth Stores (`lib/authStores.ts`)
34
37
 
35
38
  ```ts
36
- // app/api/siwx/[...siwx]/route.ts
37
- import { createSiwxApiHandler } from '@tuwaio/siwx-server/next';
39
+ // lib/authStores.ts
40
+ import type { SiwxNonceStore, SiwxSession, SiwxSessionRecord, SiwxSessionStore } from '@tuwaio/siwx-server';
41
+ import { generateServerNonce } from '@tuwaio/siwx-server';
42
+ import Redis from 'ioredis';
38
43
 
39
- const handler = createSiwxApiHandler({
40
- cookieOptions: {
41
- name: 'tuwa-auth',
42
- secure: process.env.NODE_ENV === 'production',
44
+ const redis = new Redis(process.env.REDIS_URL || 'redis://localhost:6379');
45
+
46
+ export const sessionStore: SiwxSessionStore = {
47
+ async create({ session, ttlSeconds }: { session: SiwxSession; ttlSeconds: number }): Promise<SiwxSessionRecord> {
48
+ const id = generateServerNonce();
49
+ const createdAt = Date.now();
50
+ const expiresAt = createdAt + ttlSeconds * 1000;
51
+ const record: SiwxSessionRecord = { id, session, createdAt, expiresAt };
52
+
53
+ await redis.set(`siwx:session:${id}`, JSON.stringify(record), 'EX', ttlSeconds);
54
+ return record;
43
55
  },
44
- // Optional: Pass used nonces to prevent replay attacks
45
- verifyOptions: {
46
- // usedNonces: await getNonceStore()
56
+
57
+ async get(id: string): Promise<SiwxSessionRecord | null> {
58
+ const data = await redis.get(`siwx:session:${id}`);
59
+ return data ? JSON.parse(data) : null;
47
60
  },
48
- });
49
61
 
50
- // Automatically exposes GET, POST, and DELETE methods
51
- export const { GET, POST, DELETE } = handler;
52
- ```
62
+ async bindSubject(id: string, subjectId: string): Promise<boolean> {
63
+ const record = await this.get(id);
64
+ if (!record) return false;
65
+ record.subjectId = subjectId;
66
+ const ttl = Math.max(1, Math.floor((record.expiresAt - Date.now()) / 1000));
67
+ await redis.set(`siwx:session:${id}`, JSON.stringify(record), 'EX', ttl);
68
+ return true;
69
+ },
53
70
 
54
- ---
71
+ async revoke(id: string): Promise<void> {
72
+ await redis.del(`siwx:session:${id}`);
73
+ },
74
+ };
55
75
 
56
- ## Manual Verification API
76
+ export const nonceStore: SiwxNonceStore = {
77
+ async issue({ nonce, ttlSeconds }: { nonce: string; ttlSeconds: number }): Promise<void> {
78
+ await redis.set(`siwx:nonce:${nonce}`, '1', 'EX', ttlSeconds);
79
+ },
57
80
 
58
- If you aren't using Next.js or prefer full control, you can use the low-level utilities.
81
+ async consume({ nonce }: { nonce: string }): Promise<boolean> {
82
+ // Atomic single-use consumption via GETDEL
83
+ const value = await redis.getdel(`siwx:nonce:${nonce}`);
84
+ return value !== null;
85
+ },
86
+ };
87
+ ```
59
88
 
60
- ### `verifySiwxPayload(payload, options?): Promise<ServerVerifyResult>`
89
+ #### Alternative: In-Memory Stores for Local Testing / Prototyping (No Redis Needed)
61
90
 
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`).
91
+ For local development or testing without spinning up Redis, you can use the built-in in-memory stores directly from `@tuwaio/siwx-server`:
63
92
 
64
93
  ```ts
65
- import { verifySiwxPayload, serializeCookieSession, toSession } from '@tuwaio/siwx-server';
94
+ // lib/authStores.dev.ts (Zero Dependencies / In-Memory)
95
+ import { MemorySiwxNonceStore, MemorySiwxSessionStore } from '@tuwaio/siwx-server';
66
96
 
67
- // In a Next.js API Route or NestJS Controller:
68
- export async function POST(request: Request) {
69
- const { message, signature } = await request.json();
97
+ // Built-in in-memory stores for local testing (fails closed in production by default)
98
+ export const sessionStore = new MemorySiwxSessionStore();
99
+ export const nonceStore = new MemorySiwxNonceStore();
100
+ ```
70
101
 
71
- const result = await verifySiwxPayload(
72
- { message, signature },
73
- { usedNonces: await getNonceStore() }, // pass your consumed nonces set
74
- );
102
+ Or write a custom `Map`-based storage adapter without external dependencies:
75
103
 
76
- if (!result.success) {
77
- return new Response(result.error, { status: 401 });
78
- }
104
+ ```ts
105
+ // lib/authStores.memory.ts (Custom Zero-Dependency In-Memory Store)
106
+ import type { SiwxNonceStore, SiwxSession, SiwxSessionRecord, SiwxSessionStore } from '@tuwaio/siwx-server';
107
+ import { generateServerNonce } from '@tuwaio/siwx-server';
79
108
 
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
- ```
109
+ const sessionMap = new Map<string, SiwxSessionRecord>();
110
+ const nonceMap = new Map<string, number>();
111
+
112
+ export const sessionStore: SiwxSessionStore = {
113
+ async create({ session, ttlSeconds }: { session: SiwxSession; ttlSeconds: number }): Promise<SiwxSessionRecord> {
114
+ const id = generateServerNonce();
115
+ const createdAt = Date.now();
116
+ const expiresAt = createdAt + ttlSeconds * 1000;
117
+ const record: SiwxSessionRecord = { id, session, createdAt, expiresAt };
118
+ sessionMap.set(id, record);
119
+ return record;
120
+ },
87
121
 
88
- ### `serializeCookieSession(session, opts?): SerializedCookieSession`
122
+ async get(id: string): Promise<SiwxSessionRecord | null> {
123
+ const record = sessionMap.get(id);
124
+ if (!record || record.expiresAt < Date.now()) {
125
+ sessionMap.delete(id);
126
+ return null;
127
+ }
128
+ return record;
129
+ },
89
130
 
90
- Serializes a `SiwxSession` into a `Set-Cookie` header string.
131
+ async bindSubject(id: string, subjectId: string): Promise<boolean> {
132
+ const record = await this.get(id);
133
+ if (!record) return false;
134
+ record.subjectId = subjectId;
135
+ return true;
136
+ },
91
137
 
92
- ```ts
93
- import { serializeCookieSession } from '@tuwaio/siwx-server';
138
+ async revoke(id: string): Promise<void> {
139
+ sessionMap.delete(id);
140
+ },
141
+ };
94
142
 
95
- const { cookieHeader } = serializeCookieSession(session, {
96
- name: 'tuwa-auth',
97
- maxAge: 60 * 60 * 24 * 7, // 7 days
98
- secure: true,
99
- sameSite: 'Strict',
100
- });
101
- ```
143
+ export const nonceStore: SiwxNonceStore = {
144
+ async issue({ nonce, ttlSeconds }: { nonce: string; ttlSeconds: number }): Promise<void> {
145
+ nonceMap.set(nonce, Date.now() + ttlSeconds * 1000);
146
+ },
102
147
 
103
- ### `deserializeCookieSession(cookieValue): SiwxSession | null`
148
+ async consume({ nonce }: { nonce: string }): Promise<boolean> {
149
+ const expiresAt = nonceMap.get(nonce);
150
+ if (!expiresAt || expiresAt < Date.now()) {
151
+ nonceMap.delete(nonce);
152
+ return false;
153
+ }
154
+ nonceMap.delete(nonce); // Atomic single-use consumption
155
+ return true;
156
+ },
157
+ };
158
+ ```
104
159
 
105
- Reads and parses a session from a cookie value (the inverse of `serializeCookieSession`).
160
+ #### Step 2: Configure the Route Handler (`app/api/siwx/[...siwx]/route.ts`)
106
161
 
107
162
  ```ts
108
- import { deserializeCookieSession } from '@tuwaio/siwx-server';
163
+ // app/api/siwx/[...siwx]/route.ts
164
+ import { createSiwxApiHandler } from '@tuwaio/siwx-server/next';
165
+ import { nonceStore, sessionStore } from '@/lib/authStores';
166
+
167
+ const handler = createSiwxApiHandler({
168
+ sessionStore,
169
+ nonceStore,
170
+ policy: {
171
+ expectedDomain: 'app.tuwa.io',
172
+ expectedUri: 'https://app.tuwa.io',
173
+ allowedChainIds: ['eip155:1', 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpK'],
174
+ maxIssuedAtAgeSeconds: 300,
175
+ },
176
+ cookieOptions: {
177
+ name: 'siwx-session-v2',
178
+ secure: process.env.NODE_ENV === 'production',
179
+ },
180
+ });
109
181
 
110
- const cookie = request.cookies.get('tuwa-auth')?.value;
111
- const session = deserializeCookieSession(cookie ?? '');
112
- if (!session) throw new Error('No valid session');
182
+ export const { GET, POST, DELETE } = handler;
113
183
  ```
114
184
 
115
- ### `generateServerNonce(): string`
185
+ ---
186
+
187
+ ### 2. Stateless Demo Profile (Zero-Infrastructure Demonstration & Prototyping)
116
188
 
117
- Generates a secure nonce for sending to the client. Store it in Redis or your DB before sending.
189
+ For sandbox environments, developer playgrounds, integration tests, or demonstration websites running without a backing database or Redis instance.
118
190
 
119
191
  ```ts
120
- import { generateServerNonce } from '@tuwaio/siwx-server';
192
+ // app/api/siwx/[...siwx]/route.ts
193
+ import { createStatelessDemoSiwxHandler } from '@tuwaio/siwx-server/next';
194
+
195
+ const handler = createStatelessDemoSiwxHandler({
196
+ signingSecret: process.env.SIWX_DEMO_SIGNING_SECRET!, // Minimum 32 characters
197
+ policy: {
198
+ expectedDomain: 'demo.tuwa.io',
199
+ requireExpirationTime: true,
200
+ maxIssuedAtAgeSeconds: 300,
201
+ maxSessionLifetimeSeconds: 1800, // 30 minutes max session
202
+ },
203
+ cookieOptions: {
204
+ name: 'siwx-demo-session',
205
+ secure: process.env.NODE_ENV === 'production',
206
+ },
207
+ });
121
208
 
122
- const nonce = generateServerNonce();
123
- await redis.set(`nonce:${nonce}`, '1', 'EX', 300); // expires in 5 min
209
+ export const { GET, POST, DELETE } = handler;
124
210
  ```
125
211
 
126
- ### `toSession(parsed: ParsedSiwxMessage): SiwxSession`
212
+ > **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.
213
+
214
+ ---
127
215
 
128
- Converts a `ParsedSiwxMessage` into a lean `SiwxSession` object.
216
+ ## 🚀 Low-Level Manual Verification API
129
217
 
130
- ```ts
131
- import { toSession } from '@tuwaio/siwx-server';
218
+ For custom controllers (NestJS, Fastify, Express, Cloudflare Workers):
132
219
 
133
- const session = toSession(parsedMessage);
134
- ```
220
+ ```ts
221
+ import { toSession, verifySiwxPayload } from '@tuwaio/siwx-server';
135
222
 
136
- ### `isSessionMatchingTarget(session, targetAddress, targetChainId?)`
223
+ export async function handleVerify(request: Request) {
224
+ const { message, signature } = await request.json();
137
225
 
138
- Re-exported from `@tuwaio/siwx-core` for server-side authorization checks. Validates if a session matches a target account address and optional chainId.
226
+ const result = await verifySiwxPayload(
227
+ { message, signature },
228
+ {
229
+ policy: {
230
+ expectedDomain: 'app.tuwa.io',
231
+ allowedChainIds: ['eip155:1'],
232
+ },
233
+ },
234
+ );
139
235
 
140
- ```ts
141
- import { isSessionMatchingTarget } from '@tuwaio/siwx-server';
236
+ if (!result.success || !result.data) {
237
+ return new Response(JSON.stringify({ error: result.error }), { status: 401 });
238
+ }
142
239
 
143
- const isValid = isSessionMatchingTarget(session, userAddress, chainId);
240
+ const session = toSession(result.data);
241
+ return new Response(JSON.stringify(session), { status: 200 });
242
+ }
144
243
  ```
145
244
 
146
245
  ---
147
246
 
148
- ## Nonce Replay Protection
247
+ ## 📦 Store Interfaces
149
248
 
150
- Always invalidate used nonces after verification:
249
+ ### `SiwxSessionStore`
151
250
 
152
251
  ```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
252
+ export interface SiwxSessionStore {
253
+ create(input: { session: SiwxSession; ttlSeconds: number }): Promise<SiwxSessionRecord>;
254
+ get(id: string): Promise<SiwxSessionRecord | null>;
255
+ bindSubject(id: string, subjectId: string): Promise<boolean>;
256
+ revoke(id: string): Promise<void>;
164
257
  }
165
258
  ```
166
259
 
167
- ---
260
+ ### `SiwxNonceStore`
168
261
 
169
- ## Peer Dependencies
262
+ ```ts
263
+ export interface SiwxNonceStore {
264
+ issue(input: { nonce: string; ttlSeconds: number }): Promise<void>;
265
+ consume(input: { nonce: string }): Promise<boolean>;
266
+ }
267
+ ```
170
268
 
171
- | Package | Version |
172
- | ------------------- | ------------- |
173
- | `@tuwaio/siwx-core` | `workspace:*` |
269
+ ### `SiwxSessionRecord`
174
270
 
175
- Chain adapters are dynamically imported at runtime — only install the ones you need.
271
+ ```ts
272
+ export interface SiwxSessionRecord {
273
+ id: string;
274
+ session: SiwxSession;
275
+ subjectId?: string;
276
+ createdAt: number;
277
+ expiresAt: number;
278
+ }
279
+ ```
176
280
 
177
281
  ---
178
282
 
@@ -0,0 +1,2 @@
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;
@@ -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 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};
package/dist/index.d.mts CHANGED
@@ -1,67 +1,85 @@
1
+ import * as _tuwaio_siwx_core from '@tuwaio/siwx-core';
1
2
  import { SiwxVerifyPayload } from '@tuwaio/siwx-core';
2
- export { SiwxSessionLike, generateNonce as generateServerNonce, isSessionMatchingTarget } from '@tuwaio/siwx-core';
3
- import { S as SiwxSession, C as CookieOptions, a as SerializedCookieSession, b as ServerVerifyOptions, c as ServerVerifyResult } from './types-CvnkVdoo.mjs';
4
- export { t as toSession } from './types-CvnkVdoo.mjs';
5
-
6
- /**
7
- * @fileoverview Server-side CAIP-122 payload verification and session utilities.
8
- * Backend-agnostic — compatible with any Node.js or Edge runtime (Next.js, NestJS, Hono, etc.).
9
- */
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';
10
6
 
11
7
  /**
12
8
  * Parses and validates a raw CAIP-122 payload (message + signature) on the server side.
13
9
  * Dynamically routes verification to the correct chain adapter based on the CAIP-2 namespace.
14
10
  *
15
- * This function is the primary entry point for server-side authentication.
16
- * It handles EVM (eip155) and Solana chains.
17
- *
18
11
  * @param payload - The `{ message, signature }` payload sent by the client.
19
- * @param options - Optional server-side verification options (nonce replay protection, etc.).
12
+ * @param options - Server-side verification options (policy, nonce replay protection, etc.).
20
13
  * @returns A `ServerVerifyResult` with `success: true` and the parsed session data, or an error.
21
- *
22
- * @example
23
- * ```ts
24
- * // In a Next.js API route or NestJS controller:
25
- * const result = await verifySiwxPayload({ message, signature }, {
26
- * usedNonces: await redis.smembers('used_nonces'),
27
- * });
28
- * if (result.success) {
29
- * // Session is valid — issue a cookie or JWT
30
- * }
31
- * ```
32
14
  */
33
15
  declare function verifySiwxPayload(payload: SiwxVerifyPayload, options?: ServerVerifyOptions): Promise<ServerVerifyResult>;
34
16
  /**
35
- * Serializes a `SiwxSession` into an `HttpOnly` cookie string.
36
- * The session data is base64url-encoded (not encrypted — use a signed cookie or JWT for production).
17
+ * Signs a stateless demo session into an authenticated compact token.
18
+ * Uses Web Crypto HMAC-SHA256.
37
19
  *
38
- * This utility is intentionally simple. For production use, wrap the session
39
- * in a signed/encrypted format using a library like `iron-session` or `jose`.
40
- *
41
- * @param session - The verified session data to serialize.
42
- * @param opts - Cookie options (name, maxAge, secure, SameSite, etc.).
43
- * @returns A `SerializedCookieSession` containing the `Set-Cookie` header value and session data.
44
- *
45
- * @example
46
- * ```ts
47
- * const { cookieHeader } = serializeCookieSession(session);
48
- * return new Response(null, { headers: { 'Set-Cookie': cookieHeader } });
49
- * ```
20
+ * @param session - The verified session to sign.
21
+ * @param secret - Server-only signing secret (minimum 32 bytes).
22
+ * @param ttlSeconds - Maximum session validity in seconds (default 1800 = 30m).
23
+ * @returns Authenticated compact token in `${payload}.${signature}` format.
50
24
  */
51
- declare function serializeCookieSession(session: SiwxSession, opts?: CookieOptions): SerializedCookieSession;
25
+ declare function signStatelessDemoSession(session: SiwxSession, secret: string, ttlSeconds?: number): Promise<string>;
52
26
  /**
53
- * Deserializes a `SiwxSession` from a base64url-encoded cookie value.
54
- * This is the inverse of `serializeCookieSession`.
27
+ * Verifies an authenticated stateless demo session token.
28
+ * Performs constant-time cryptographic verification and validates expiration and policy.
55
29
  *
56
- * @param cookieValue - The raw cookie value string (not the full header).
57
- * @returns The deserialized `SiwxSession`, or `null` if the value is invalid or malformed.
58
- *
59
- * @example
60
- * ```ts
61
- * const session = deserializeCookieSession(request.cookies.get('siwx-session'));
62
- * if (session) console.log('Session address:', session.address);
63
- * ```
30
+ * @param token - Compact token from cookie (`${payload}.${signature}`).
31
+ * @param secret - Server-only signing secret.
32
+ * @param policy - Optional verification policy to enforce.
33
+ * @returns The verified SiwxSession, or null if invalid, expired, or tampered.
34
+ */
35
+ declare function verifyStatelessDemoSession(token: string | null | undefined, secret: string, policy?: _tuwaio_siwx_core.SiwxVerificationPolicy): Promise<SiwxSession | null>;
36
+ /**
37
+ * Creates an HttpOnly Set-Cookie header value for a session.
38
+ */
39
+ declare function createSessionCookie(value: string, opts?: CookieOptions): string;
40
+ /**
41
+ * Creates a clear/destroy Set-Cookie header value.
42
+ */
43
+ declare function createClearCookie(opts?: CookieOptions): string;
44
+ /**
45
+ * Extracts a cookie value by name from a raw Cookie header string.
46
+ */
47
+ declare function parseCookie(cookieHeader: string | null | undefined, name: string): string | null;
48
+ /**
49
+ * In-memory implementation of SiwxSessionStore.
50
+ * STRICTLY for local development, prototyping, and unit testing.
51
+ * Fails closed in production environments.
52
+ */
53
+ declare class MemorySiwxSessionStore implements SiwxSessionStore {
54
+ private records;
55
+ constructor(options?: {
56
+ allowInProduction?: boolean;
57
+ });
58
+ create(input: {
59
+ session: SiwxSession;
60
+ ttlSeconds: number;
61
+ }): Promise<SiwxSessionRecord>;
62
+ get(id: string): Promise<SiwxSessionRecord | null>;
63
+ bindSubject(id: string, subjectId: string): Promise<boolean>;
64
+ revoke(id: string): Promise<void>;
65
+ }
66
+ /**
67
+ * In-memory implementation of SiwxNonceStore.
68
+ * STRICTLY for local development, prototyping, and unit testing.
69
+ * Fails closed in production environments.
64
70
  */
65
- declare function deserializeCookieSession(cookieValue: string): SiwxSession | null;
71
+ declare class MemorySiwxNonceStore implements SiwxNonceStore {
72
+ private nonces;
73
+ constructor(options?: {
74
+ allowInProduction?: boolean;
75
+ });
76
+ issue(input: {
77
+ nonce: string;
78
+ ttlSeconds: number;
79
+ }): Promise<void>;
80
+ consume(input: {
81
+ nonce: string;
82
+ }): Promise<boolean>;
83
+ }
66
84
 
67
- export { CookieOptions, SerializedCookieSession, ServerVerifyOptions, ServerVerifyResult, SiwxSession, deserializeCookieSession, serializeCookieSession, verifySiwxPayload };
85
+ export { CookieOptions, MemorySiwxNonceStore, MemorySiwxSessionStore, ServerVerifyOptions, ServerVerifyResult, SiwxNonceStore, SiwxSession, SiwxSessionRecord, SiwxSessionStore, createClearCookie, createSessionCookie, parseCookie, signStatelessDemoSession, verifySiwxPayload, verifyStatelessDemoSession };