@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 +201 -97
- package/dist/chunk-4HK2SXOC.js +2 -0
- package/dist/chunk-GQ7NU6NM.mjs +2 -0
- package/dist/index.d.mts +68 -50
- package/dist/index.d.ts +68 -50
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/next.d.mts +92 -15
- package/dist/next.d.ts +92 -15
- package/dist/next.js +1 -1
- package/dist/next.mjs +1 -1
- package/dist/types-Dz3SGS59.d.mts +193 -0
- package/dist/types-Dz3SGS59.d.ts +193 -0
- package/package.json +5 -5
- package/dist/chunk-47HTX7ZQ.js +0 -2
- package/dist/chunk-JVIBIICZ.mjs +0 -2
- package/dist/types-CvnkVdoo.d.mts +0 -108
- package/dist/types-CvnkVdoo.d.ts +0 -108
package/README.md
CHANGED
|
@@ -3,16 +3,17 @@
|
|
|
3
3
|
[](https://www.npmjs.com/package/@tuwaio/siwx-server)
|
|
4
4
|
[](./LICENSE)
|
|
5
5
|
|
|
6
|
-
> Backend utilities for `@tuwaio/siwx` (L2). Server-side CAIP-122 payload verification, session
|
|
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()`**:
|
|
13
|
-
- **`
|
|
14
|
-
- **`
|
|
15
|
-
- **`
|
|
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 (
|
|
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
|
-
##
|
|
30
|
+
## 🛡️ Architecture Profiles
|
|
30
31
|
|
|
31
|
-
###
|
|
32
|
+
### 1. Durable Profile (Production Standard)
|
|
32
33
|
|
|
33
|
-
|
|
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
|
-
//
|
|
37
|
-
import {
|
|
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
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
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
|
-
|
|
45
|
-
|
|
46
|
-
|
|
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
|
-
|
|
51
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
89
|
+
#### Alternative: In-Memory Stores for Local Testing / Prototyping (No Redis Needed)
|
|
61
90
|
|
|
62
|
-
|
|
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
|
-
|
|
94
|
+
// lib/authStores.dev.ts (Zero Dependencies / In-Memory)
|
|
95
|
+
import { MemorySiwxNonceStore, MemorySiwxSessionStore } from '@tuwaio/siwx-server';
|
|
66
96
|
|
|
67
|
-
//
|
|
68
|
-
export
|
|
69
|
-
|
|
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
|
-
|
|
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
|
-
|
|
77
|
-
|
|
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
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
93
|
-
|
|
138
|
+
async revoke(id: string): Promise<void> {
|
|
139
|
+
sessionMap.delete(id);
|
|
140
|
+
},
|
|
141
|
+
};
|
|
94
142
|
|
|
95
|
-
const
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
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
|
-
|
|
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
|
-
|
|
160
|
+
#### Step 2: Configure the Route Handler (`app/api/siwx/[...siwx]/route.ts`)
|
|
106
161
|
|
|
107
162
|
```ts
|
|
108
|
-
|
|
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
|
|
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
|
-
|
|
185
|
+
---
|
|
186
|
+
|
|
187
|
+
### 2. Stateless Demo Profile (Zero-Infrastructure Demonstration & Prototyping)
|
|
116
188
|
|
|
117
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
216
|
+
## 🚀 Low-Level Manual Verification API
|
|
129
217
|
|
|
130
|
-
|
|
131
|
-
import { toSession } from '@tuwaio/siwx-server';
|
|
218
|
+
For custom controllers (NestJS, Fastify, Express, Cloudflare Workers):
|
|
132
219
|
|
|
133
|
-
|
|
134
|
-
|
|
220
|
+
```ts
|
|
221
|
+
import { toSession, verifySiwxPayload } from '@tuwaio/siwx-server';
|
|
135
222
|
|
|
136
|
-
|
|
223
|
+
export async function handleVerify(request: Request) {
|
|
224
|
+
const { message, signature } = await request.json();
|
|
137
225
|
|
|
138
|
-
|
|
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
|
-
|
|
141
|
-
|
|
236
|
+
if (!result.success || !result.data) {
|
|
237
|
+
return new Response(JSON.stringify({ error: result.error }), { status: 401 });
|
|
238
|
+
}
|
|
142
239
|
|
|
143
|
-
const
|
|
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
|
-
##
|
|
247
|
+
## 📦 Store Interfaces
|
|
149
248
|
|
|
150
|
-
|
|
249
|
+
### `SiwxSessionStore`
|
|
151
250
|
|
|
152
251
|
```ts
|
|
153
|
-
|
|
154
|
-
{
|
|
155
|
-
|
|
156
|
-
|
|
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
|
-
|
|
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
|
-
|
|
172
|
-
| ------------------- | ------------- |
|
|
173
|
-
| `@tuwaio/siwx-core` | `workspace:*` |
|
|
269
|
+
### `SiwxSessionRecord`
|
|
174
270
|
|
|
175
|
-
|
|
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,
|
|
4
|
-
export { t as toSession } from './types-
|
|
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 -
|
|
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
|
-
*
|
|
36
|
-
*
|
|
17
|
+
* Signs a stateless demo session into an authenticated compact token.
|
|
18
|
+
* Uses Web Crypto HMAC-SHA256.
|
|
37
19
|
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
* @
|
|
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
|
|
25
|
+
declare function signStatelessDemoSession(session: SiwxSession, secret: string, ttlSeconds?: number): Promise<string>;
|
|
52
26
|
/**
|
|
53
|
-
*
|
|
54
|
-
*
|
|
27
|
+
* Verifies an authenticated stateless demo session token.
|
|
28
|
+
* Performs constant-time cryptographic verification and validates expiration and policy.
|
|
55
29
|
*
|
|
56
|
-
* @param
|
|
57
|
-
* @
|
|
58
|
-
*
|
|
59
|
-
* @
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
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
|
|
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,
|
|
85
|
+
export { CookieOptions, MemorySiwxNonceStore, MemorySiwxSessionStore, ServerVerifyOptions, ServerVerifyResult, SiwxNonceStore, SiwxSession, SiwxSessionRecord, SiwxSessionStore, createClearCookie, createSessionCookie, parseCookie, signStatelessDemoSession, verifySiwxPayload, verifyStatelessDemoSession };
|