@tuwaio/siwx-server 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,67 +1,328 @@
1
- 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';
1
+ import * as _tuwaio_siwx_core from '@tuwaio/siwx-core';
2
+ import { SiwxVerificationPolicy, SiwxVerifyResult, ParsedSiwxMessage, SiwxVerifyPayload } from '@tuwaio/siwx-core';
3
+ export { ParsedSiwxMessage, SiwxMessageFields, SiwxSessionLike, SiwxVerificationPolicy, ValidateMessageOptions, generateNonce, generateNonce as generateServerNonce, isSessionMatchingTarget, validateMessage, validatePolicy } from '@tuwaio/siwx-core';
5
4
 
6
5
  /**
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.).
6
+ * @fileoverview Server-side types for the @tuwaio/siwx-server package.
9
7
  */
10
8
 
9
+ /**
10
+ * Options for the `verifySiwxPayload` function.
11
+ */
12
+ interface ServerVerifyOptions {
13
+ /**
14
+ * A set of nonces that have already been used.
15
+ * If the payload's nonce is found in this set, verification will fail
16
+ * to prevent replay attacks.
17
+ */
18
+ usedNonces?: Set<string>;
19
+ /**
20
+ * If true, skips the `expirationTime` validation check.
21
+ * Not recommended for production use.
22
+ * @default false
23
+ */
24
+ skipExpiration?: boolean;
25
+ /**
26
+ * Optional verification policy to enforce on the message fields.
27
+ */
28
+ policy?: SiwxVerificationPolicy;
29
+ /**
30
+ * Optional viem `PublicClient` instance for EVM chain EIP-1271 (smart contract wallet) verification.
31
+ */
32
+ publicClient?: any;
33
+ }
34
+ /**
35
+ * The result of a server-side verification operation, extending the base result
36
+ * with the verification method used.
37
+ */
38
+ interface ServerVerifyResult extends SiwxVerifyResult {
39
+ /**
40
+ * The CAIP-2 namespace used for verification routing.
41
+ * `eip155` for EVM chains, `solana` for Solana.
42
+ */
43
+ namespace?: 'eip155' | 'solana';
44
+ }
45
+ /**
46
+ * Represents a serializable session object derived from a verified CAIP-122 message.
47
+ */
48
+ interface SiwxSession {
49
+ /** The verified CAIP-10 blockchain address. */
50
+ address: string;
51
+ /** The CAIP-2 chain ID the session is bound to. */
52
+ chainId: string;
53
+ /** The domain that issued the session. */
54
+ domain: string;
55
+ /** The nonce that was used. Must be invalidated server-side after use. */
56
+ nonce: string;
57
+ /** ISO 8601 timestamp when the session was issued. */
58
+ issuedAt: string;
59
+ /** ISO 8601 timestamp when the session expires, if set. */
60
+ expirationTime?: string;
61
+ }
62
+ /**
63
+ * Represents a stored session record in a durable session store.
64
+ */
65
+ interface SiwxSessionRecord {
66
+ /** Unique opaque session identifier (e.g. secure random UUID). */
67
+ id: string;
68
+ /** The verified SIWX session data. */
69
+ session: SiwxSession;
70
+ /** Optional subject ID (e.g., Payload User ID or internal database ID) bound to this session. */
71
+ subjectId?: string;
72
+ /** Timestamp in milliseconds when the session record was created. */
73
+ createdAt: number;
74
+ /** Timestamp in milliseconds when the session record expires. */
75
+ expiresAt: number;
76
+ }
77
+ /**
78
+ * Durable session store interface for production environments.
79
+ */
80
+ interface SiwxSessionStore {
81
+ /**
82
+ * Creates and stores a new session record.
83
+ * @param input.session - The verified session data.
84
+ * @param input.ttlSeconds - Time-to-live in seconds.
85
+ * @returns The created session record with unique ID.
86
+ */
87
+ create(input: {
88
+ session: SiwxSession;
89
+ ttlSeconds: number;
90
+ }): Promise<SiwxSessionRecord>;
91
+ /**
92
+ * Retrieves a session record by its opaque ID.
93
+ * @param id - The session ID.
94
+ * @returns The session record, or null if not found or expired.
95
+ */
96
+ get(id: string): Promise<SiwxSessionRecord | null>;
97
+ /**
98
+ * Atomically binds a user/subject identifier to the session.
99
+ * @param id - The session ID.
100
+ * @param subjectId - The user or subject ID.
101
+ * @returns True if binding succeeded, false if session not found.
102
+ */
103
+ bindSubject(id: string, subjectId: string): Promise<boolean>;
104
+ /**
105
+ * Revokes and removes a session record.
106
+ * @param id - The session ID.
107
+ */
108
+ revoke(id: string): Promise<void>;
109
+ }
110
+ /**
111
+ * Durable nonce store interface for single-use nonce issuance and atomic consumption.
112
+ */
113
+ interface SiwxNonceStore {
114
+ /**
115
+ * Issues and stores a new challenge nonce with TTL.
116
+ * @param input.nonce - The unique nonce string.
117
+ * @param input.ttlSeconds - Time-to-live in seconds (typically 300s).
118
+ */
119
+ issue(input: {
120
+ nonce: string;
121
+ ttlSeconds: number;
122
+ }): Promise<void>;
123
+ /**
124
+ * Atomically consumes a nonce, guaranteeing single-use.
125
+ * @param input.nonce - The nonce string to consume.
126
+ * @returns True if the nonce was valid and consumed, false if already consumed or expired.
127
+ */
128
+ consume(input: {
129
+ nonce: string;
130
+ }): Promise<boolean>;
131
+ }
132
+ /**
133
+ * Compact payload structure for stateless demo session tokens.
134
+ */
135
+ interface StatelessDemoTokenPayload {
136
+ version: 1;
137
+ address: string;
138
+ chainId: string;
139
+ domain: string;
140
+ nonce: string;
141
+ issuedAt: string;
142
+ expirationTime?: string;
143
+ sessionId: string;
144
+ mode: 'demo';
145
+ }
146
+ /**
147
+ * Limits for stateless demo profile.
148
+ */
149
+ interface StatelessDemoLimits {
150
+ /** Maximum transaction payload size in bytes. */
151
+ maxTransactionPayloadBytes?: number;
152
+ /** Advisory request cap per session. */
153
+ maxRequestsPerSession?: number;
154
+ }
155
+ /**
156
+ * Options for cookie session serialization.
157
+ */
158
+ interface CookieOptions {
159
+ /**
160
+ * The name of the cookie.
161
+ * @default "siwx-session-v2"
162
+ */
163
+ name?: string;
164
+ /**
165
+ * Max age in seconds. Defaults to 7 days for durable, 30 minutes for demo.
166
+ * @default 604800
167
+ */
168
+ maxAge?: number;
169
+ /**
170
+ * The cookie path.
171
+ * @default "/"
172
+ */
173
+ path?: string;
174
+ /**
175
+ * The cookie domain.
176
+ */
177
+ domain?: string;
178
+ /**
179
+ * Whether to set the Secure flag.
180
+ * @default true
181
+ */
182
+ secure?: boolean;
183
+ /**
184
+ * The SameSite policy.
185
+ * @default "Strict"
186
+ */
187
+ sameSite?: 'Strict' | 'Lax' | 'None';
188
+ }
189
+ /**
190
+ * Options for the `getSiwxServerSession` helper function.
191
+ */
192
+ interface GetSiwxServerSessionOptions {
193
+ /**
194
+ * Cookie source:
195
+ * - A raw Cookie string (e.g. `req.headers.get('cookie')` or `"siwx-session-v2=xyz"`)
196
+ * - A Next.js ReadonlyRequestCookies object (from `await cookies()`)
197
+ * - A Web API `Request` or `Headers` object
198
+ * - Any object with a `get(name)` method
199
+ */
200
+ cookieSource: string | Request | Headers | {
201
+ get(name: string): {
202
+ value: string;
203
+ } | string | undefined | null;
204
+ } | null | undefined;
205
+ /**
206
+ * The name of the cookie.
207
+ * @default "siwx-session-v2"
208
+ */
209
+ cookieName?: string;
210
+ /**
211
+ * Durable session store (for production durable sessions).
212
+ */
213
+ sessionStore?: SiwxSessionStore;
214
+ /**
215
+ * Server HMAC secret key (for stateless demo sessions).
216
+ */
217
+ signingSecret?: string;
218
+ /**
219
+ * Optional verification policy to validate the session.
220
+ */
221
+ policy?: SiwxVerificationPolicy;
222
+ }
223
+ /**
224
+ * Converts a ParsedSiwxMessage to a lean SiwxSession object.
225
+ * @internal
226
+ */
227
+ declare function toSession(parsed: ParsedSiwxMessage): SiwxSession;
228
+
11
229
  /**
12
230
  * Parses and validates a raw CAIP-122 payload (message + signature) on the server side.
13
231
  * Dynamically routes verification to the correct chain adapter based on the CAIP-2 namespace.
14
232
  *
15
- * This function is the primary entry point for server-side authentication.
16
- * It handles EVM (eip155) and Solana chains.
17
- *
18
233
  * @param payload - The `{ message, signature }` payload sent by the client.
19
- * @param options - Optional server-side verification options (nonce replay protection, etc.).
234
+ * @param options - Server-side verification options (policy, nonce replay protection, etc.).
20
235
  * @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
236
  */
33
237
  declare function verifySiwxPayload(payload: SiwxVerifyPayload, options?: ServerVerifyOptions): Promise<ServerVerifyResult>;
34
238
  /**
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).
37
- *
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`.
239
+ * Signs a stateless demo session into an authenticated compact token.
240
+ * Uses Web Crypto HMAC-SHA256.
40
241
  *
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.
242
+ * @param session - The verified session to sign.
243
+ * @param secret - Server-only signing secret (minimum 32 bytes).
244
+ * @param ttlSeconds - Maximum session validity in seconds (default 1800 = 30m).
245
+ * @returns Authenticated compact token in `${payload}.${signature}` format.
246
+ */
247
+ declare function signStatelessDemoSession(session: SiwxSession, secret: string, ttlSeconds?: number): Promise<string>;
248
+ /**
249
+ * Verifies an authenticated stateless demo session token.
250
+ * Performs constant-time cryptographic verification and validates expiration and policy.
44
251
  *
45
- * @example
46
- * ```ts
47
- * const { cookieHeader } = serializeCookieSession(session);
48
- * return new Response(null, { headers: { 'Set-Cookie': cookieHeader } });
49
- * ```
252
+ * @param token - Compact token from cookie (`${payload}.${signature}`).
253
+ * @param secret - Server-only signing secret.
254
+ * @param policy - Optional verification policy to enforce.
255
+ * @returns The verified SiwxSession, or null if invalid, expired, or tampered.
50
256
  */
51
- declare function serializeCookieSession(session: SiwxSession, opts?: CookieOptions): SerializedCookieSession;
257
+ declare function verifyStatelessDemoSession(token: string | null | undefined, secret: string, policy?: _tuwaio_siwx_core.SiwxVerificationPolicy): Promise<SiwxSession | null>;
52
258
  /**
53
- * Deserializes a `SiwxSession` from a base64url-encoded cookie value.
54
- * This is the inverse of `serializeCookieSession`.
259
+ * Creates an HttpOnly Set-Cookie header value for a session.
260
+ */
261
+ declare function createSessionCookie(value: string, opts?: CookieOptions): string;
262
+ /**
263
+ * Creates a clear/destroy Set-Cookie header value.
264
+ */
265
+ declare function createClearCookie(opts?: CookieOptions): string;
266
+ /**
267
+ * Extracts a cookie value by name from a raw Cookie header string.
268
+ */
269
+ declare function parseCookie(cookieHeader: string | null | undefined, name: string): string | null;
270
+ /**
271
+ * In-memory implementation of SiwxSessionStore.
272
+ * STRICTLY for local development, prototyping, and unit testing.
273
+ * Fails closed in production environments.
274
+ */
275
+ declare class MemorySiwxSessionStore implements SiwxSessionStore {
276
+ private records;
277
+ constructor(options?: {
278
+ allowInProduction?: boolean;
279
+ });
280
+ create(input: {
281
+ session: SiwxSession;
282
+ ttlSeconds: number;
283
+ }): Promise<SiwxSessionRecord>;
284
+ get(id: string): Promise<SiwxSessionRecord | null>;
285
+ bindSubject(id: string, subjectId: string): Promise<boolean>;
286
+ revoke(id: string): Promise<void>;
287
+ }
288
+ /**
289
+ * In-memory implementation of SiwxNonceStore.
290
+ * STRICTLY for local development, prototyping, and unit testing.
291
+ * Fails closed in production environments.
292
+ */
293
+ declare class MemorySiwxNonceStore implements SiwxNonceStore {
294
+ private nonces;
295
+ constructor(options?: {
296
+ allowInProduction?: boolean;
297
+ });
298
+ issue(input: {
299
+ nonce: string;
300
+ ttlSeconds: number;
301
+ }): Promise<void>;
302
+ consume(input: {
303
+ nonce: string;
304
+ }): Promise<boolean>;
305
+ }
306
+ /**
307
+ * Resolves and verifies an active SIWX session strictly on the server side.
308
+ * Supports both durable session stores and stateless HMAC-signed demo cookies.
55
309
  *
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.
310
+ * @param options - Configuration including cookieSource, sessionStore or signingSecret, and optional policy.
311
+ * @returns The verified `SiwxSession` object, or `null` if invalid, expired, or absent.
58
312
  *
59
313
  * @example
60
314
  * ```ts
61
- * const session = deserializeCookieSession(request.cookies.get('siwx-session'));
62
- * if (session) console.log('Session address:', session.address);
315
+ * // In Next.js Server Actions:
316
+ * import { cookies } from 'next/headers';
317
+ * import { getSiwxServerSession } from '@tuwaio/siwx-server';
318
+ * import { sessionStore } from '@/lib/authStores';
319
+ *
320
+ * const session = await getSiwxServerSession({
321
+ * cookieSource: await cookies(),
322
+ * sessionStore,
323
+ * });
63
324
  * ```
64
325
  */
65
- declare function deserializeCookieSession(cookieValue: string): SiwxSession | null;
326
+ declare function getSiwxServerSession(options: GetSiwxServerSessionOptions): Promise<SiwxSession | null>;
66
327
 
67
- export { CookieOptions, SerializedCookieSession, ServerVerifyOptions, ServerVerifyResult, SiwxSession, deserializeCookieSession, serializeCookieSession, verifySiwxPayload };
328
+ export { type CookieOptions, type GetSiwxServerSessionOptions, MemorySiwxNonceStore, MemorySiwxSessionStore, type ServerVerifyOptions, type ServerVerifyResult, type SiwxNonceStore, type SiwxSession, type SiwxSessionRecord, type SiwxSessionStore, type StatelessDemoLimits, type StatelessDemoTokenPayload, createClearCookie, createSessionCookie, getSiwxServerSession, parseCookie, signStatelessDemoSession, toSession, verifySiwxPayload, verifyStatelessDemoSession };