@tuwaio/siwx-server 0.3.0 â 0.4.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 +144 -219
- package/dist/chunk-AEFOZH2W.mjs +2 -0
- package/dist/chunk-SS5KJYWU.js +2 -0
- package/dist/index.d.mts +181 -82
- package/dist/index.d.ts +181 -82
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/next.d.mts +61 -24
- package/dist/next.d.ts +61 -24
- package/dist/next.js +1 -1
- package/dist/next.mjs +1 -1
- package/package.json +29 -16
- package/dist/chunk-PBR725EL.mjs +0 -2
- package/dist/chunk-WPKBWXVR.js +0 -2
package/README.md
CHANGED
|
@@ -1,20 +1,24 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @tuwaio/siwx-server
|
|
2
2
|
|
|
3
3
|
[](https://www.npmjs.com/package/@tuwaio/siwx-server)
|
|
4
|
-
[](
|
|
4
|
+
[](https://github.com/TuwaIO/siwx/blob/main/packages/siwx-server/LICENSE)
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
`@tuwaio/siwx-server` is the server Layer 2 (L2) package of **SIWX** (Sign-In With X), the authentication project of TUWA Stage 1 ("Core Auth & Primitives", next to Orbit Utils). Built on **`@tuwaio/siwx-core`** and the Web platform APIs (`Request`, `Response`, Web Crypto), it verifies signed CAIP-122 messages for EVM and Solana on your backend, issues single-use nonces and sessions through pluggable stores, and formats the session cookie. It runs on Node.js 20+ and does not depend on a web framework, a database or a hosted service.
|
|
7
|
+
|
|
8
|
+
It has two entry points:
|
|
9
|
+
|
|
10
|
+
- `@tuwaio/siwx-server`: framework-agnostic verification, session and cookie utilities.
|
|
11
|
+
- `@tuwaio/siwx-server/next`: ready-made route handlers for a Next.js App Router catch-all route. They use only `Request` and `Response`, so they do not import `next`.
|
|
7
12
|
|
|
8
13
|
---
|
|
9
14
|
|
|
10
15
|
## ðïž Core Capabilities
|
|
11
16
|
|
|
12
|
-
-
|
|
13
|
-
-
|
|
14
|
-
-
|
|
15
|
-
-
|
|
16
|
-
-
|
|
17
|
-
- **`MemorySiwxSessionStore` / `MemorySiwxNonceStore`**: In-memory stores explicitly designated for local development and testing (fails closed in production).
|
|
17
|
+
- **Verification:** `verifySiwxPayload` parses the message, validates it against your `SiwxVerificationPolicy` and routes the signature check by chain to `@tuwaio/siwx-evm` (EIP-191, with an EIP-1271 fallback when `publicClient` is set) or `@tuwaio/siwx-solana` (ed25519). It returns a result instead of throwing.
|
|
18
|
+
- **Durable profile:** `createSiwxApiHandler` serves the nonce, verify, session and logout routes on top of your `SiwxSessionStore` and `SiwxNonceStore` (Redis, SQL, KVâŠ), with the session ID in an `HttpOnly` cookie.
|
|
19
|
+
- **Stateless demo profile:** `createStatelessDemoSiwxHandler` issues HMAC-signed nonces and keeps the session in an HMAC-signed cookie, for demos without a database.
|
|
20
|
+
- **Server-side session:** `getSiwxServerSession` reads the session from a `Request`, `Headers`, a `Cookie` header or the Next.js `cookies()` store, for Server Actions and API routes.
|
|
21
|
+
- **Building blocks:** `MemorySiwxSessionStore` and `MemorySiwxNonceStore` for development and tests, cookie helpers, demo token and demo nonce signing, and re-exports of the `@tuwaio/siwx-core` validators.
|
|
18
22
|
|
|
19
23
|
---
|
|
20
24
|
|
|
@@ -22,301 +26,222 @@
|
|
|
22
26
|
|
|
23
27
|
```bash
|
|
24
28
|
pnpm add @tuwaio/siwx-server @tuwaio/siwx-core
|
|
25
|
-
|
|
26
|
-
|
|
29
|
+
|
|
30
|
+
# Chain verifiers, loaded at runtime for the chains you accept:
|
|
31
|
+
pnpm add @tuwaio/siwx-evm viem @wagmi/core
|
|
32
|
+
pnpm add @tuwaio/siwx-solana @solana/kit @wallet-standard/base
|
|
27
33
|
```
|
|
28
34
|
|
|
29
|
-
|
|
35
|
+
> [!IMPORTANT]
|
|
36
|
+
> `@tuwaio/siwx-core` is a required peer dependency. `@tuwaio/siwx-evm`, `@tuwaio/siwx-solana` and `viem` are optional peer dependencies: `verifySiwxPayload` imports the chain package dynamically, depending on the chain of the message, so install the ones you accept together with their own peer dependencies. A message for a chain whose package is missing fails verification. `viem` provides the `PublicClient` type of the EIP-1271 option.
|
|
30
37
|
|
|
31
|
-
|
|
38
|
+
---
|
|
32
39
|
|
|
33
|
-
|
|
40
|
+
## ð Usage
|
|
34
41
|
|
|
35
|
-
|
|
42
|
+
### 1. Session and nonce stores
|
|
36
43
|
|
|
37
|
-
|
|
44
|
+
The durable profile needs a session store and a nonce store shared by every server instance. A Redis implementation (the client shape matches `ioredis`):
|
|
38
45
|
|
|
39
|
-
```
|
|
46
|
+
```typescript
|
|
40
47
|
// lib/authStores.ts
|
|
41
|
-
import
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
48
|
+
import {
|
|
49
|
+
generateServerNonce,
|
|
50
|
+
type SiwxNonceStore,
|
|
51
|
+
type SiwxSessionRecord,
|
|
52
|
+
type SiwxSessionStore,
|
|
53
|
+
} from '@tuwaio/siwx-server';
|
|
54
|
+
|
|
55
|
+
declare const redis: {
|
|
56
|
+
set(key: string, value: string, mode: 'EX', seconds: number): Promise<unknown>;
|
|
57
|
+
get(key: string): Promise<string | null>;
|
|
58
|
+
getdel(key: string): Promise<string | null>;
|
|
59
|
+
del(key: string): Promise<unknown>;
|
|
60
|
+
};
|
|
46
61
|
|
|
47
62
|
export const sessionStore: SiwxSessionStore = {
|
|
48
|
-
async create({ session, ttlSeconds }
|
|
49
|
-
const id = generateServerNonce();
|
|
63
|
+
async create({ session, ttlSeconds }) {
|
|
50
64
|
const createdAt = Date.now();
|
|
51
|
-
const
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
65
|
+
const record: SiwxSessionRecord = {
|
|
66
|
+
id: generateServerNonce(), // 128-bit random ID, becomes the cookie value
|
|
67
|
+
session,
|
|
68
|
+
createdAt,
|
|
69
|
+
expiresAt: createdAt + ttlSeconds * 1000,
|
|
70
|
+
};
|
|
71
|
+
await redis.set(`siwx:session:${record.id}`, JSON.stringify(record), 'EX', ttlSeconds);
|
|
55
72
|
return record;
|
|
56
73
|
},
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
return data ? JSON.parse(data) : null;
|
|
74
|
+
async get(id) {
|
|
75
|
+
const data = await redis.get(`siwx:session:${id}`); // expired keys are removed by Redis
|
|
76
|
+
return data ? (JSON.parse(data) as SiwxSessionRecord) : null;
|
|
61
77
|
},
|
|
62
|
-
|
|
63
|
-
async bindSubject(id: string, subjectId: string): Promise<boolean> {
|
|
78
|
+
async bindSubject(id, subjectId) {
|
|
64
79
|
const record = await this.get(id);
|
|
65
80
|
if (!record) return false;
|
|
66
|
-
record.
|
|
67
|
-
|
|
68
|
-
await redis.set(`siwx:session:${id}`, JSON.stringify(record), 'EX', ttl);
|
|
81
|
+
const ttlSeconds = Math.max(1, Math.floor((record.expiresAt - Date.now()) / 1000));
|
|
82
|
+
await redis.set(`siwx:session:${id}`, JSON.stringify({ ...record, subjectId }), 'EX', ttlSeconds);
|
|
69
83
|
return true;
|
|
70
84
|
},
|
|
71
|
-
|
|
72
|
-
async revoke(id: string): Promise<void> {
|
|
85
|
+
async revoke(id) {
|
|
73
86
|
await redis.del(`siwx:session:${id}`);
|
|
74
87
|
},
|
|
75
88
|
};
|
|
76
89
|
|
|
77
90
|
export const nonceStore: SiwxNonceStore = {
|
|
78
|
-
async issue({ nonce, ttlSeconds }
|
|
91
|
+
async issue({ nonce, ttlSeconds }) {
|
|
79
92
|
await redis.set(`siwx:nonce:${nonce}`, '1', 'EX', ttlSeconds);
|
|
80
93
|
},
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
// Atomic single-use consumption via GETDEL
|
|
84
|
-
const value = await redis.getdel(`siwx:nonce:${nonce}`);
|
|
85
|
-
return value !== null;
|
|
94
|
+
async consume({ nonce }) {
|
|
95
|
+
return (await redis.getdel(`siwx:nonce:${nonce}`)) !== null; // atomic: each nonce is accepted once
|
|
86
96
|
},
|
|
87
97
|
};
|
|
88
98
|
```
|
|
89
99
|
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
For local development or testing without spinning up Redis, you can use the built-in in-memory stores directly from `@tuwaio/siwx-server`:
|
|
93
|
-
|
|
94
|
-
```ts
|
|
95
|
-
// lib/authStores.dev.ts (Zero Dependencies / In-Memory)
|
|
96
|
-
import { MemorySiwxNonceStore, MemorySiwxSessionStore } from '@tuwaio/siwx-server';
|
|
97
|
-
|
|
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
|
-
```
|
|
102
|
-
|
|
103
|
-
Or write a custom `Map`-based storage adapter without external dependencies:
|
|
104
|
-
|
|
105
|
-
```ts
|
|
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';
|
|
109
|
-
|
|
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
|
-
},
|
|
122
|
-
|
|
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
|
-
},
|
|
131
|
-
|
|
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
|
-
},
|
|
100
|
+
For local development and tests, use `new MemorySiwxSessionStore()` and `new MemorySiwxNonceStore()`. They keep data in the memory of one process and throw when `NODE_ENV` is `production`, unless you pass `{ allowInProduction: true }`.
|
|
138
101
|
|
|
139
|
-
|
|
140
|
-
sessionMap.delete(id);
|
|
141
|
-
},
|
|
142
|
-
};
|
|
102
|
+
### 2. Route handlers (Next.js App Router)
|
|
143
103
|
|
|
144
|
-
|
|
145
|
-
async issue({ nonce, ttlSeconds }: { nonce: string; ttlSeconds: number }): Promise<void> {
|
|
146
|
-
nonceMap.set(nonce, Date.now() + ttlSeconds * 1000);
|
|
147
|
-
},
|
|
148
|
-
|
|
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
|
-
```
|
|
160
|
-
|
|
161
|
-
#### Step 2: Configure the Route Handler (`app/api/siwx/[...siwx]/route.ts`)
|
|
162
|
-
|
|
163
|
-
```ts
|
|
104
|
+
```typescript
|
|
164
105
|
// app/api/siwx/[...siwx]/route.ts
|
|
165
106
|
import { createSiwxApiHandler } from '@tuwaio/siwx-server/next';
|
|
107
|
+
|
|
166
108
|
import { nonceStore, sessionStore } from '@/lib/authStores';
|
|
167
109
|
|
|
168
|
-
const
|
|
110
|
+
export const { GET, POST, DELETE } = createSiwxApiHandler({
|
|
169
111
|
sessionStore,
|
|
170
112
|
nonceStore,
|
|
171
113
|
policy: {
|
|
172
114
|
expectedDomain: 'app.tuwa.io',
|
|
173
115
|
expectedUri: 'https://app.tuwa.io',
|
|
174
116
|
allowedChainIds: ['eip155:1', 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpK'],
|
|
175
|
-
maxIssuedAtAgeSeconds: 300,
|
|
176
|
-
},
|
|
177
|
-
cookieOptions: {
|
|
178
|
-
name: 'siwx-session-v2',
|
|
179
|
-
secure: process.env.NODE_ENV === 'production',
|
|
180
|
-
},
|
|
181
|
-
});
|
|
182
|
-
|
|
183
|
-
export const { GET, POST, DELETE } = handler;
|
|
184
|
-
```
|
|
185
|
-
|
|
186
|
-
---
|
|
187
|
-
|
|
188
|
-
### 2. Stateless Demo Profile (Zero-Infrastructure Demonstration & Prototyping)
|
|
189
|
-
|
|
190
|
-
For sandbox environments, developer playgrounds, integration tests, or demonstration websites running without a backing database or Redis instance.
|
|
191
|
-
|
|
192
|
-
```ts
|
|
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
117
|
requireExpirationTime: true,
|
|
201
118
|
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
119
|
},
|
|
120
|
+
ttlSeconds: 7 * 24 * 60 * 60, // session and cookie lifetime (default)
|
|
208
121
|
});
|
|
209
|
-
|
|
210
|
-
export const { GET, POST, DELETE } = handler;
|
|
211
122
|
```
|
|
212
123
|
|
|
213
|
-
|
|
124
|
+
The handler picks the action from the last path segment:
|
|
214
125
|
|
|
215
|
-
|
|
126
|
+
| Route | Method | Behavior |
|
|
127
|
+
| ------------------- | ------------ | --------------------------------------------------------------------------------------------------------------------------------- |
|
|
128
|
+
| `/api/siwx/nonce` | `GET` `POST` | Issues a nonce, stores it for 300 seconds, returns `{ nonce }` |
|
|
129
|
+
| `/api/siwx/verify` | `POST` | Verifies `{ message, signature }` (max 64 KB), consumes the nonce, creates the session, sets the cookie, returns the session JSON |
|
|
130
|
+
| `/api/siwx/session` | `GET` | Returns the session of the cookie, or `null` |
|
|
131
|
+
| `/api/siwx/session` | `DELETE` | Revokes the session and clears the cookie |
|
|
132
|
+
| `/api/siwx/logout` | `POST` | Same as `DELETE /api/siwx/session` |
|
|
216
133
|
|
|
217
|
-
|
|
134
|
+
`POST /verify` responds with 400 for a malformed body, 401 when verification or the nonce check fails, and 413 for a body over 64 KB. On the client, fetch the nonce from `/api/siwx/nonce` (the `getNonce` option of `useSiwx` in [`@tuwaio/siwx-react`](https://siwx.docs.tuwa.io/packages/siwx-react)): the handler only accepts nonces it has issued.
|
|
218
135
|
|
|
219
|
-
|
|
136
|
+
### 3. Reading the session on the server
|
|
220
137
|
|
|
221
|
-
```
|
|
222
|
-
// app/actions/
|
|
138
|
+
```typescript
|
|
139
|
+
// app/actions/updateProfile.ts
|
|
223
140
|
'use server';
|
|
224
141
|
|
|
142
|
+
import { getSiwxServerSession, isSessionMatchingTarget } from '@tuwaio/siwx-server';
|
|
225
143
|
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
144
|
|
|
230
|
-
|
|
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
|
-
});
|
|
145
|
+
import { sessionStore } from '@/lib/authStores';
|
|
236
146
|
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
}
|
|
147
|
+
export async function updateProfile(address: string) {
|
|
148
|
+
const session = await getSiwxServerSession({ cookieSource: await cookies(), sessionStore });
|
|
240
149
|
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
throw new Error('Forbidden: Wallet address mismatch.');
|
|
150
|
+
if (!session || !isSessionMatchingTarget(session, address)) {
|
|
151
|
+
throw new Error('Unauthorized');
|
|
244
152
|
}
|
|
245
153
|
|
|
246
|
-
//
|
|
247
|
-
return { success: true };
|
|
154
|
+
// The request is made by the owner of `address`.
|
|
248
155
|
}
|
|
249
156
|
```
|
|
250
157
|
|
|
251
|
-
|
|
158
|
+
`cookieSource` also accepts a `Request`, a `Headers` object or a `Cookie` header string, so the same call works in any framework.
|
|
159
|
+
|
|
160
|
+
### 4. Stateless demo profile
|
|
161
|
+
|
|
162
|
+
```typescript
|
|
163
|
+
// app/api/siwx/[...siwx]/route.ts
|
|
164
|
+
import { createStatelessDemoSiwxHandler } from '@tuwaio/siwx-server/next';
|
|
165
|
+
|
|
166
|
+
const signingSecret = process.env.SIWX_DEMO_SIGNING_SECRET; // server-only, at least 32 characters
|
|
167
|
+
if (!signingSecret) throw new Error('SIWX_DEMO_SIGNING_SECRET is not set');
|
|
168
|
+
|
|
169
|
+
export const { GET, POST, DELETE } = createStatelessDemoSiwxHandler({
|
|
170
|
+
signingSecret,
|
|
171
|
+
policy: {
|
|
172
|
+
expectedDomain: 'demo.tuwa.io',
|
|
173
|
+
requireExpirationTime: true,
|
|
174
|
+
maxIssuedAtAgeSeconds: 300,
|
|
175
|
+
maxSessionLifetimeSeconds: 30 * 60,
|
|
176
|
+
},
|
|
177
|
+
});
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
The routes are the same as in the durable profile, without a database:
|
|
252
181
|
|
|
253
|
-
|
|
182
|
+
- `/nonce` returns a nonce signed with `signingSecret` and valid for 300 seconds. `/verify` accepts only such nonces, and only once: used nonces are remembered in the memory of the server instance until they expire. As with the durable profile, the client must fetch the nonce (`getNonce` in `useSiwx`).
|
|
183
|
+
- The session is an HMAC-SHA256 signed token in the cookie. It expires with the message `expirationTime` (or after `ttlSeconds`, 30 minutes by default). With `maxSessionLifetimeSeconds: 1800`, set `fields.expirationTime` on the client to at most 30 minutes: `useSiwx` defaults to 24 hours.
|
|
254
184
|
|
|
255
|
-
|
|
185
|
+
> [!WARNING]
|
|
186
|
+
> With several server instances (or serverless functions), each one remembers its own used nonces, so a signed message can be replayed on another instance within the 300-second nonce lifetime. A token stays valid until it expires, even after logout, and it is signed, not encrypted. Use the demo profile only for demos and prototypes, with a short `maxSessionLifetimeSeconds`.
|
|
256
187
|
|
|
257
|
-
|
|
258
|
-
import { toSession, verifySiwxPayload } from '@tuwaio/siwx-server';
|
|
188
|
+
### 5. Other frameworks
|
|
259
189
|
|
|
260
|
-
|
|
261
|
-
|
|
190
|
+
```typescript
|
|
191
|
+
import {
|
|
192
|
+
createSessionCookie,
|
|
193
|
+
type SiwxNonceStore,
|
|
194
|
+
type SiwxSessionStore,
|
|
195
|
+
toSession,
|
|
196
|
+
verifySiwxPayload,
|
|
197
|
+
} from '@tuwaio/siwx-server';
|
|
198
|
+
|
|
199
|
+
declare const nonceStore: SiwxNonceStore;
|
|
200
|
+
declare const sessionStore: SiwxSessionStore;
|
|
201
|
+
|
|
202
|
+
export async function handleVerify(request: Request): Promise<Response> {
|
|
203
|
+
const { message, signature } = (await request.json()) as { message: string; signature: string };
|
|
262
204
|
|
|
263
205
|
const result = await verifySiwxPayload(
|
|
264
206
|
{ message, signature },
|
|
265
|
-
{
|
|
266
|
-
policy: {
|
|
267
|
-
expectedDomain: 'app.tuwa.io',
|
|
268
|
-
allowedChainIds: ['eip155:1'],
|
|
269
|
-
},
|
|
270
|
-
},
|
|
207
|
+
{ policy: { expectedDomain: 'app.tuwa.io', requireExpirationTime: true } },
|
|
271
208
|
);
|
|
209
|
+
if (!result.success || !result.data) return Response.json({ error: result.error }, { status: 401 });
|
|
272
210
|
|
|
273
|
-
|
|
274
|
-
|
|
211
|
+
// Accept only nonces issued by your nonce endpoint, once.
|
|
212
|
+
if (!(await nonceStore.consume({ nonce: result.data.nonce }))) {
|
|
213
|
+
return Response.json({ error: 'Invalid nonce' }, { status: 401 });
|
|
275
214
|
}
|
|
276
215
|
|
|
277
|
-
const
|
|
278
|
-
return
|
|
216
|
+
const record = await sessionStore.create({ session: toSession(result.data), ttlSeconds: 7 * 24 * 60 * 60 });
|
|
217
|
+
return Response.json(record.session, { headers: { 'Set-Cookie': createSessionCookie(record.id) } });
|
|
279
218
|
}
|
|
280
219
|
```
|
|
281
220
|
|
|
282
221
|
---
|
|
283
222
|
|
|
284
|
-
##
|
|
223
|
+
## ð¡ïž Security Notes
|
|
285
224
|
|
|
286
|
-
|
|
225
|
+
- **Nonce:** a signature proves ownership only if its nonce is fresh. Both handlers accept a nonce only if it was issued by `/nonce` in the last 300 seconds, and only once. The durable handler consumes it in your `SiwxNonceStore`, whose `consume` must be atomic and shared by every instance; the demo handler checks the nonce signature and remembers used nonces per instance. `verifySiwxPayload` alone checks nothing but the optional `usedNonces` set.
|
|
226
|
+
- **Domain and URI:** without `policy.expectedDomain`, a message signed for another site is accepted. Always set `expectedDomain` (case-insensitive exact match) and, if possible, `expectedUri` (same origin or a sub-path).
|
|
227
|
+
- **Expiry:** messages are rejected once their `expirationTime` has passed, with the same `clockSkewSeconds` tolerance as the other timing rules (60 seconds by default; set `0` for none). Set `requireExpirationTime`, `maxSessionLifetimeSeconds` and `maxIssuedAtAgeSeconds`; the last one has no default, so stale messages are accepted until you set it. Durable sessions expire through the store: `SiwxSessionStore.get` must return `null` for expired records.
|
|
228
|
+
- **Chains:** `allowedChainIds` entries are full CAIP-2 IDs matched exactly, both when a message is verified and in `getSiwxServerSession`, so `eip155:1` never allows `solana:1`.
|
|
229
|
+
- **Server-side checks:** `getSiwxServerSession` applies only `expectedDomain` and `allowedChainIds` of its `policy`, plus `requireExpirationTime` for durable sessions and the token expiry for demo sessions. The full policy runs when the message is verified.
|
|
230
|
+
- **Cookies:** the session cookie is always `HttpOnly`, and `Secure` and `SameSite=Strict` by default. Keep `secure: true` in production.
|
|
231
|
+
- **Secrets:** the demo `signingSecret` must be at least 32 characters and must never reach the browser. Changing it invalidates every demo session.
|
|
287
232
|
|
|
288
|
-
|
|
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>;
|
|
294
|
-
}
|
|
295
|
-
```
|
|
233
|
+
---
|
|
296
234
|
|
|
297
|
-
|
|
235
|
+
## ð External Services
|
|
298
236
|
|
|
299
|
-
|
|
300
|
-
export interface SiwxNonceStore {
|
|
301
|
-
issue(input: { nonce: string; ttlSeconds: number }): Promise<void>;
|
|
302
|
-
consume(input: { nonce: string }): Promise<boolean>;
|
|
303
|
-
}
|
|
304
|
-
```
|
|
237
|
+
The package contacts no hosts of its own. With `verifyOptions.publicClient` (or `publicClient` in `verifySiwxPayload`), the EIP-1271 fallback sends one `eth_call` to the RPC endpoint of that client. Sessions and nonces go only to the stores you provide.
|
|
305
238
|
|
|
306
|
-
|
|
239
|
+
---
|
|
307
240
|
|
|
308
|
-
|
|
309
|
-
export interface SiwxSessionRecord {
|
|
310
|
-
id: string;
|
|
311
|
-
session: SiwxSession;
|
|
312
|
-
subjectId?: string;
|
|
313
|
-
createdAt: number;
|
|
314
|
-
expiresAt: number;
|
|
315
|
-
}
|
|
316
|
-
```
|
|
241
|
+
## ð API Reference
|
|
317
242
|
|
|
318
|
-
|
|
243
|
+
Every export, with signatures and types generated from the source, is documented at **[siwx.docs.tuwa.io/packages/siwx-server](https://siwx.docs.tuwa.io/packages/siwx-server)**: the `server` module for `@tuwaio/siwx-server` and the `next` module for `@tuwaio/siwx-server/next`.
|
|
319
244
|
|
|
320
245
|
## ð License
|
|
321
246
|
|
|
322
|
-
Licensed under the **Apache-2.0 License**. See the [LICENSE](
|
|
247
|
+
Licensed under the **Apache-2.0 License**. See the [LICENSE](https://github.com/TuwaIO/siwx/blob/main/packages/siwx-server/LICENSE) file for details.
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {parseMessage,validateMessage,SiwxNonceReplayError,SiwxUnsupportedNamespaceError,generateNonce}from'@tuwaio/siwx-core';export{generateNonce as b}from'@tuwaio/siwx-core';function v(t){return {address:t.address,chainId:t.chainId,domain:t.domain,nonce:t.nonce,issuedAt:t.issuedAt,expirationTime:t.expirationTime}}async function B(t,e={}){try{let n=parseMessage(t.message),s=validateMessage(n,{skipExpiration:e.skipExpiration,policy:e.policy});if(!s.valid)return {success:!1,error:`Validation failed: ${s.errors.join(", ")}`};if(e.usedNonces?.has(n.nonce))throw new SiwxNonceReplayError(n.nonce);let i=n.chainId.split(":")[0];if(!i||!["eip155","solana"].includes(i))throw new SiwxUnsupportedNamespaceError(i??"unknown");if(i==="eip155"){let{verifyEvmSignature:r}=await import('@tuwaio/siwx-evm');return {...await r(t.message,t.signature,{skipExpiration:e.skipExpiration,publicClient:e.publicClient}),namespace:i}}if(i==="solana"){let{verifyEd25519:r}=await import('@tuwaio/siwx-solana');return {...await r(t,{skipExpiration:e.skipExpiration}),namespace:i}}return {success:!1,error:"Unsupported namespace."}}catch(n){return n instanceof SiwxNonceReplayError||n instanceof SiwxUnsupportedNamespaceError?{success:false,error:n.message}:{success:false,error:`Server verification failed: ${String(n)}`}}}function C(t){return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function k(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return atob(e)}function D(t){let e="";for(let n=0;n<t.byteLength;n++)e+=String.fromCharCode(t[n]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function N(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e),s=new Uint8Array(n.length);for(let i=0;i<n.length;i++)s[i]=n.charCodeAt(i);return s}async function p(t){let e=new TextEncoder;return globalThis.crypto.subtle.importKey("raw",e.encode(t),{name:"HMAC",hash:"SHA-256"},false,["sign","verify"])}async function j(t,e,n=1800){if(!e||e.length<32)throw new Error("[SIWX-SERVER] Stateless demo signing secret must be at least 32 characters long.");let i=Date.now()+n*1e3,r={version:1,address:t.address,chainId:t.chainId,domain:t.domain,nonce:t.nonce,issuedAt:t.issuedAt,expirationTime:t.expirationTime??new Date(i).toISOString(),sessionId:generateNonce(),mode:"demo"},a=JSON.stringify(r),o=C(a),l=await p(e),u=new TextEncoder,f=await globalThis.crypto.subtle.sign("HMAC",l,u.encode(o)),c=D(new Uint8Array(f));return `${o}.${c}`}async function I(t,e,n){if(!t||typeof t!="string"||!e)return null;let s=t.split(".");if(s.length!==2)return null;let[i,r]=s;try{let a=await p(e),o=N(r),l=new TextEncoder;if(!await globalThis.crypto.subtle.verify("HMAC",a,o,l.encode(i)))return null;let f=k(i),c=JSON.parse(f);if(c.version!==1||c.mode!=="demo")return null;if(c.expirationTime){let g=new Date(c.expirationTime).getTime(),S=(n?.clockSkewSeconds??60)*1e3;if(isNaN(g)||g+S<Date.now())return null}return n?.expectedDomain!==void 0&&!(Array.isArray(n.expectedDomain)?n.expectedDomain:[n.expectedDomain]).some(S=>S.toLowerCase()===c.domain.toLowerCase())||n?.allowedChainIds!==void 0&&n.allowedChainIds.length>0&&!n.allowedChainIds.includes(c.chainId)?null:{address:c.address,chainId:c.chainId,domain:c.domain,nonce:c.nonce,issuedAt:c.issuedAt,expirationTime:c.expirationTime}}catch{return null}}var E="siwx-demo-nonce:",y=32,A=10,R=/^[0-9a-f]{106}$/;function O(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function V(t){let e=new Uint8Array(new ArrayBuffer(t.length/2));for(let n=0;n<e.length;n++)e[n]=parseInt(t.slice(n*2,n*2+2),16);return e}async function U(t,e=300){if(!t||t.length<32)throw new Error("[SIWX-SERVER] Stateless demo signing secret must be at least 32 characters long.");let n=Math.floor(Date.now()/1e3)+e,s=generateNonce()+n.toString(16).padStart(A,"0"),i=await p(t),r=await globalThis.crypto.subtle.sign("HMAC",i,new TextEncoder().encode(E+s));return s+O(new Uint8Array(r))}async function H(t,e){if(typeof t!="string"||!e||!R.test(t))return false;let n=y+A,s=t.slice(0,n),i=t.slice(n);try{let r=await p(e);return await globalThis.crypto.subtle.verify("HMAC",r,V(i),new TextEncoder().encode(E+s))?parseInt(s.slice(y),16)*1e3>=Date.now():!1}catch{return false}}function L(t,e={}){let{name:n="siwx-session-v2",maxAge:s=3600*24*7,path:i="/",domain:r,secure:a=true,sameSite:o="Strict"}=e,l=[`${n}=${t}`,`Max-Age=${s}`,`Path=${i}`,"HttpOnly",`SameSite=${o}`];return a&&l.push("Secure"),r&&l.push(`Domain=${r}`),l.join("; ")}function G(t={}){let{name:e="siwx-session-v2",path:n="/",domain:s,secure:i=true,sameSite:r="Strict"}=t,a=[`${e}=`,`Path=${n}`,"Expires=Thu, 01 Jan 1970 00:00:00 GMT","Max-Age=0","HttpOnly",`SameSite=${r}`];return i&&a.push("Secure"),s&&a.push(`Domain=${s}`),a.join("; ")}function d(t,e){return t?Object.fromEntries(t.split("; ").filter(Boolean).map(s=>{let i=s.split("=");return [i[0].trim(),i.slice(1).join("=")]}))[e]??null:null}var h=class{records=new Map;constructor(e){if(typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV==="production"&&!e?.allowInProduction)throw new Error("[SIWX-SERVER] MemorySiwxSessionStore must not be used in production. Connect Redis or a durable store.")}async create(e){let n=generateNonce(),s=Date.now(),i=s+e.ttlSeconds*1e3,r={id:n,session:e.session,createdAt:s,expiresAt:i};return this.records.set(n,r),r}async get(e){let n=this.records.get(e);return n?n.expiresAt<Date.now()?(this.records.delete(e),null):n:null}async bindSubject(e,n){let s=await this.get(e);return s?(s.subjectId=n,true):false}async revoke(e){this.records.delete(e);}},b=class{nonces=new Map;constructor(e){if(typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV==="production"&&!e?.allowInProduction)throw new Error("[SIWX-SERVER] MemorySiwxNonceStore must not be used in production. Connect Redis or a durable store.")}async issue(e){let n=Date.now()+e.ttlSeconds*1e3;this.nonces.set(e.nonce,n);}async consume(e){let n=this.nonces.get(e.nonce);return !(!n||(this.nonces.delete(e.nonce),n<Date.now()))}};async function X(t){let{cookieSource:e,cookieName:n="siwx-session-v2",sessionStore:s,signingSecret:i,policy:r}=t;if(!e)return null;let a=null;if(typeof e=="string")a=e.includes("=")?d(e,n):e;else if(typeof e.headers=="object"&&typeof e.headers?.get=="function"){let o=e.headers.get("cookie");a=d(o,n);}else if(typeof e.get=="function"){let o=e.get(n);if(o&&typeof o=="object"&&"value"in o)a=o.value;else if(typeof o=="string")a=o.includes("=")?d(o,n):o;else if(typeof e.get=="function"){let l=e.get("cookie");l&&(a=d(l,n));}}if(!a)return null;if(s){let o=await s.get(a);return !o?.session||r&&(r.expectedDomain!==void 0&&!(Array.isArray(r.expectedDomain)?r.expectedDomain:[r.expectedDomain]).some(u=>u.toLowerCase()===o.session.domain.toLowerCase())||r.allowedChainIds!==void 0&&r.allowedChainIds.length>0&&!r.allowedChainIds.includes(o.session.chainId)||r.requireExpirationTime&&!o.session.expirationTime)?null:o.session}return i?I(a,i,r):null}
|
|
2
|
+
export{v as a,B as c,j as d,I as e,U as f,H as g,L as h,G as i,d as j,h as k,b as l,X as m};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var siwxCore=require('@tuwaio/siwx-core');function v(t){return {address:t.address,chainId:t.chainId,domain:t.domain,nonce:t.nonce,issuedAt:t.issuedAt,expirationTime:t.expirationTime}}async function B(t,e={}){try{let n=siwxCore.parseMessage(t.message),s=siwxCore.validateMessage(n,{skipExpiration:e.skipExpiration,policy:e.policy});if(!s.valid)return {success:!1,error:`Validation failed: ${s.errors.join(", ")}`};if(e.usedNonces?.has(n.nonce))throw new siwxCore.SiwxNonceReplayError(n.nonce);let i=n.chainId.split(":")[0];if(!i||!["eip155","solana"].includes(i))throw new siwxCore.SiwxUnsupportedNamespaceError(i??"unknown");if(i==="eip155"){let{verifyEvmSignature:r}=await import('@tuwaio/siwx-evm');return {...await r(t.message,t.signature,{skipExpiration:e.skipExpiration,publicClient:e.publicClient}),namespace:i}}if(i==="solana"){let{verifyEd25519:r}=await import('@tuwaio/siwx-solana');return {...await r(t,{skipExpiration:e.skipExpiration}),namespace:i}}return {success:!1,error:"Unsupported namespace."}}catch(n){return n instanceof siwxCore.SiwxNonceReplayError||n instanceof siwxCore.SiwxUnsupportedNamespaceError?{success:false,error:n.message}:{success:false,error:`Server verification failed: ${String(n)}`}}}function C(t){return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function k(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return atob(e)}function D(t){let e="";for(let n=0;n<t.byteLength;n++)e+=String.fromCharCode(t[n]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function N(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e),s=new Uint8Array(n.length);for(let i=0;i<n.length;i++)s[i]=n.charCodeAt(i);return s}async function p(t){let e=new TextEncoder;return globalThis.crypto.subtle.importKey("raw",e.encode(t),{name:"HMAC",hash:"SHA-256"},false,["sign","verify"])}async function j(t,e,n=1800){if(!e||e.length<32)throw new Error("[SIWX-SERVER] Stateless demo signing secret must be at least 32 characters long.");let i=Date.now()+n*1e3,r={version:1,address:t.address,chainId:t.chainId,domain:t.domain,nonce:t.nonce,issuedAt:t.issuedAt,expirationTime:t.expirationTime??new Date(i).toISOString(),sessionId:siwxCore.generateNonce(),mode:"demo"},a=JSON.stringify(r),o=C(a),l=await p(e),u=new TextEncoder,f=await globalThis.crypto.subtle.sign("HMAC",l,u.encode(o)),c=D(new Uint8Array(f));return `${o}.${c}`}async function I(t,e,n){if(!t||typeof t!="string"||!e)return null;let s=t.split(".");if(s.length!==2)return null;let[i,r]=s;try{let a=await p(e),o=N(r),l=new TextEncoder;if(!await globalThis.crypto.subtle.verify("HMAC",a,o,l.encode(i)))return null;let f=k(i),c=JSON.parse(f);if(c.version!==1||c.mode!=="demo")return null;if(c.expirationTime){let g=new Date(c.expirationTime).getTime(),S=(n?.clockSkewSeconds??60)*1e3;if(isNaN(g)||g+S<Date.now())return null}return n?.expectedDomain!==void 0&&!(Array.isArray(n.expectedDomain)?n.expectedDomain:[n.expectedDomain]).some(S=>S.toLowerCase()===c.domain.toLowerCase())||n?.allowedChainIds!==void 0&&n.allowedChainIds.length>0&&!n.allowedChainIds.includes(c.chainId)?null:{address:c.address,chainId:c.chainId,domain:c.domain,nonce:c.nonce,issuedAt:c.issuedAt,expirationTime:c.expirationTime}}catch{return null}}var E="siwx-demo-nonce:",y=32,A=10,R=/^[0-9a-f]{106}$/;function O(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function V(t){let e=new Uint8Array(new ArrayBuffer(t.length/2));for(let n=0;n<e.length;n++)e[n]=parseInt(t.slice(n*2,n*2+2),16);return e}async function U(t,e=300){if(!t||t.length<32)throw new Error("[SIWX-SERVER] Stateless demo signing secret must be at least 32 characters long.");let n=Math.floor(Date.now()/1e3)+e,s=siwxCore.generateNonce()+n.toString(16).padStart(A,"0"),i=await p(t),r=await globalThis.crypto.subtle.sign("HMAC",i,new TextEncoder().encode(E+s));return s+O(new Uint8Array(r))}async function H(t,e){if(typeof t!="string"||!e||!R.test(t))return false;let n=y+A,s=t.slice(0,n),i=t.slice(n);try{let r=await p(e);return await globalThis.crypto.subtle.verify("HMAC",r,V(i),new TextEncoder().encode(E+s))?parseInt(s.slice(y),16)*1e3>=Date.now():!1}catch{return false}}function L(t,e={}){let{name:n="siwx-session-v2",maxAge:s=3600*24*7,path:i="/",domain:r,secure:a=true,sameSite:o="Strict"}=e,l=[`${n}=${t}`,`Max-Age=${s}`,`Path=${i}`,"HttpOnly",`SameSite=${o}`];return a&&l.push("Secure"),r&&l.push(`Domain=${r}`),l.join("; ")}function G(t={}){let{name:e="siwx-session-v2",path:n="/",domain:s,secure:i=true,sameSite:r="Strict"}=t,a=[`${e}=`,`Path=${n}`,"Expires=Thu, 01 Jan 1970 00:00:00 GMT","Max-Age=0","HttpOnly",`SameSite=${r}`];return i&&a.push("Secure"),s&&a.push(`Domain=${s}`),a.join("; ")}function d(t,e){return t?Object.fromEntries(t.split("; ").filter(Boolean).map(s=>{let i=s.split("=");return [i[0].trim(),i.slice(1).join("=")]}))[e]??null:null}var h=class{records=new Map;constructor(e){if(typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV==="production"&&!e?.allowInProduction)throw new Error("[SIWX-SERVER] MemorySiwxSessionStore must not be used in production. Connect Redis or a durable store.")}async create(e){let n=siwxCore.generateNonce(),s=Date.now(),i=s+e.ttlSeconds*1e3,r={id:n,session:e.session,createdAt:s,expiresAt:i};return this.records.set(n,r),r}async get(e){let n=this.records.get(e);return n?n.expiresAt<Date.now()?(this.records.delete(e),null):n:null}async bindSubject(e,n){let s=await this.get(e);return s?(s.subjectId=n,true):false}async revoke(e){this.records.delete(e);}},b=class{nonces=new Map;constructor(e){if(typeof globalThis<"u"&&globalThis.process?.env?.NODE_ENV==="production"&&!e?.allowInProduction)throw new Error("[SIWX-SERVER] MemorySiwxNonceStore must not be used in production. Connect Redis or a durable store.")}async issue(e){let n=Date.now()+e.ttlSeconds*1e3;this.nonces.set(e.nonce,n);}async consume(e){let n=this.nonces.get(e.nonce);return !(!n||(this.nonces.delete(e.nonce),n<Date.now()))}};async function X(t){let{cookieSource:e,cookieName:n="siwx-session-v2",sessionStore:s,signingSecret:i,policy:r}=t;if(!e)return null;let a=null;if(typeof e=="string")a=e.includes("=")?d(e,n):e;else if(typeof e.headers=="object"&&typeof e.headers?.get=="function"){let o=e.headers.get("cookie");a=d(o,n);}else if(typeof e.get=="function"){let o=e.get(n);if(o&&typeof o=="object"&&"value"in o)a=o.value;else if(typeof o=="string")a=o.includes("=")?d(o,n):o;else if(typeof e.get=="function"){let l=e.get("cookie");l&&(a=d(l,n));}}if(!a)return null;if(s){let o=await s.get(a);return !o?.session||r&&(r.expectedDomain!==void 0&&!(Array.isArray(r.expectedDomain)?r.expectedDomain:[r.expectedDomain]).some(u=>u.toLowerCase()===o.session.domain.toLowerCase())||r.allowedChainIds!==void 0&&r.allowedChainIds.length>0&&!r.allowedChainIds.includes(o.session.chainId)||r.requireExpirationTime&&!o.session.expirationTime)?null:o.session}return i?I(a,i,r):null}
|
|
2
|
+
Object.defineProperty(exports,"b",{enumerable:true,get:function(){return siwxCore.generateNonce}});exports.a=v;exports.c=B;exports.d=j;exports.e=I;exports.f=U;exports.g=H;exports.h=L;exports.i=G;exports.j=d;exports.k=h;exports.l=b;exports.m=X;
|