@tuwaio/siwx-server 1.0.0-fix-initialize-alpha.1.f397697 → 1.0.0-fix-initialize-alpha.3.38c3a86

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
@@ -28,6 +28,35 @@ pnpm add @tuwaio/siwx-evm @tuwaio/siwx-solana
28
28
 
29
29
  ## API
30
30
 
31
+ ### `createSiwxApiHandler(options?)` (Next.js App Router)
32
+
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
+
35
+ ```ts
36
+ // app/api/siwx/[...siwx]/route.ts
37
+ import { createSiwxApiHandler } from '@tuwaio/siwx-server/next';
38
+
39
+ const handler = createSiwxApiHandler({
40
+ cookieOptions: {
41
+ name: 'tuwa-auth',
42
+ secure: process.env.NODE_ENV === 'production',
43
+ },
44
+ // Optional: Pass used nonces to prevent replay attacks
45
+ verifyOptions: {
46
+ // usedNonces: await getNonceStore()
47
+ }
48
+ });
49
+
50
+ // Automatically exposes GET, POST, and DELETE methods
51
+ export const { GET, POST, DELETE } = handler;
52
+ ```
53
+
54
+ ---
55
+
56
+ ## Manual Verification API
57
+
58
+ If you aren't using Next.js or prefer full control, you can use the low-level utilities.
59
+
31
60
  ### `verifySiwxPayload(payload, options?): Promise<ServerVerifyResult>`
32
61
 
33
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`).
@@ -0,0 +1,2 @@
1
+ 'use strict';var siwxCore=require('@tuwaio/siwx-core');function x(e){return {address:e.address,chainId:e.chainId,domain:e.domain,nonce:e.nonce,issuedAt:e.issuedAt,expirationTime:e.expirationTime}}async function h(e,r={}){try{let i=siwxCore.parseMessage(e.message),t=siwxCore.validateMessage(i,{skipExpiration:r.skipExpiration});if(!t.valid)return {success:!1,error:`Validation failed: ${t.errors.join(", ")}`};if(!r.skipExpiration&&i.expirationTime&&new Date(i.expirationTime)<new Date)throw new siwxCore.SiwxExpiredSessionError(i.expirationTime);if(r.usedNonces?.has(i.nonce))throw new siwxCore.SiwxNonceReplayError(i.nonce);let s=i.chainId.split(":")[0];if(!s||!["eip155","solana"].includes(s))throw new siwxCore.SiwxUnsupportedNamespaceError(s??"unknown");if(s==="eip155"){let{verifyEvmSignature:n}=await import('@tuwaio/siwx-evm');return {...await n(e.message,e.signature,{skipExpiration:r.skipExpiration,publicClient:r.publicClient}),namespace:s}}if(s==="solana"){let{verifyEd25519:n}=await import('@tuwaio/siwx-solana');return {...await n(e,{skipExpiration:r.skipExpiration}),namespace:s}}return {success:!1,error:"Unsupported namespace."}}catch(i){return i instanceof siwxCore.SiwxExpiredSessionError||i instanceof siwxCore.SiwxNonceReplayError||i instanceof siwxCore.SiwxUnsupportedNamespaceError?{success:false,error:i.message}:{success:false,error:`Server verification failed: ${String(i)}`}}}function m(e){return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function g(e){let r=e.replace(/-/g,"+").replace(/_/g,"/");return atob(r)}function E(e,r={}){let{name:i="siwx-session",maxAge:t=3600*24*7,path:s="/",domain:n,secure:o=true,sameSite:l="Strict"}=r,c=m(JSON.stringify(e)),a=[`${i}=${c}`,`Max-Age=${t}`,`Path=${s}`,"HttpOnly",`SameSite=${l}`];return o&&a.push("Secure"),n&&a.push(`Domain=${n}`),{cookieHeader:a.join("; "),session:e,cookieValue:c}}function V(e){try{let r=g(e);return JSON.parse(r)}catch{return null}}
2
+ Object.defineProperty(exports,"b",{enumerable:true,get:function(){return siwxCore.generateNonce}});exports.a=x;exports.c=h;exports.d=E;exports.e=V;
@@ -0,0 +1,2 @@
1
+ import {parseMessage,validateMessage,SiwxExpiredSessionError,SiwxNonceReplayError,SiwxUnsupportedNamespaceError}from'@tuwaio/siwx-core';export{generateNonce as b}from'@tuwaio/siwx-core';function x(e){return {address:e.address,chainId:e.chainId,domain:e.domain,nonce:e.nonce,issuedAt:e.issuedAt,expirationTime:e.expirationTime}}async function h(e,r={}){try{let i=parseMessage(e.message),t=validateMessage(i,{skipExpiration:r.skipExpiration});if(!t.valid)return {success:!1,error:`Validation failed: ${t.errors.join(", ")}`};if(!r.skipExpiration&&i.expirationTime&&new Date(i.expirationTime)<new Date)throw new SiwxExpiredSessionError(i.expirationTime);if(r.usedNonces?.has(i.nonce))throw new SiwxNonceReplayError(i.nonce);let s=i.chainId.split(":")[0];if(!s||!["eip155","solana"].includes(s))throw new SiwxUnsupportedNamespaceError(s??"unknown");if(s==="eip155"){let{verifyEvmSignature:n}=await import('@tuwaio/siwx-evm');return {...await n(e.message,e.signature,{skipExpiration:r.skipExpiration,publicClient:r.publicClient}),namespace:s}}if(s==="solana"){let{verifyEd25519:n}=await import('@tuwaio/siwx-solana');return {...await n(e,{skipExpiration:r.skipExpiration}),namespace:s}}return {success:!1,error:"Unsupported namespace."}}catch(i){return i instanceof SiwxExpiredSessionError||i instanceof SiwxNonceReplayError||i instanceof SiwxUnsupportedNamespaceError?{success:false,error:i.message}:{success:false,error:`Server verification failed: ${String(i)}`}}}function m(e){return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function g(e){let r=e.replace(/-/g,"+").replace(/_/g,"/");return atob(r)}function E(e,r={}){let{name:i="siwx-session",maxAge:t=3600*24*7,path:s="/",domain:n,secure:o=true,sameSite:l="Strict"}=r,c=m(JSON.stringify(e)),a=[`${i}=${c}`,`Max-Age=${t}`,`Path=${s}`,"HttpOnly",`SameSite=${l}`];return o&&a.push("Secure"),n&&a.push(`Domain=${n}`),{cookieHeader:a.join("; "),session:e,cookieValue:c}}function V(e){try{let r=g(e);return JSON.parse(r)}catch{return null}}
2
+ export{x as a,h as c,E as d,V as e};
package/dist/index.d.mts CHANGED
@@ -1,106 +1,7 @@
1
- import { SiwxVerifyResult, ParsedSiwxMessage, SiwxVerifyPayload } from '@tuwaio/siwx-core';
1
+ import { SiwxVerifyPayload } from '@tuwaio/siwx-core';
2
2
  export { generateNonce as generateServerNonce } from '@tuwaio/siwx-core';
3
-
4
- /**
5
- * @fileoverview Server-side types for the @tuwaio/siwx-server package.
6
- */
7
-
8
- /**
9
- * Options for the `verifySiwxPayload` function.
10
- */
11
- interface ServerVerifyOptions {
12
- /**
13
- * A set of nonces that have already been used.
14
- * If the payload's nonce is found in this set, verification will fail
15
- * to prevent replay attacks. You should populate this from your session store or cache.
16
- */
17
- usedNonces?: Set<string>;
18
- /**
19
- * If true, skips the `expirationTime` validation check.
20
- * Not recommended for production use.
21
- * @default false
22
- */
23
- skipExpiration?: boolean;
24
- }
25
- /**
26
- * The result of a server-side verification operation, extending the base result
27
- * with the verification method used.
28
- */
29
- interface ServerVerifyResult extends SiwxVerifyResult {
30
- /**
31
- * The CAIP-2 namespace used for verification routing.
32
- * `eip155` for EVM chains, `solana` for Solana.
33
- */
34
- namespace?: 'eip155' | 'solana';
35
- }
36
- /**
37
- * Represents a serializable session object derived from a verified CAIP-122 message.
38
- * This can be stored in a cookie or JWT payload.
39
- */
40
- interface SiwxSession {
41
- /** The verified CAIP-10 blockchain address. */
42
- address: string;
43
- /** The CAIP-2 chain ID the session is bound to. */
44
- chainId: string;
45
- /** The domain that issued the session. */
46
- domain: string;
47
- /** The nonce that was used. Must be invalidated server-side after use. */
48
- nonce: string;
49
- /** ISO 8601 timestamp when the session was issued. */
50
- issuedAt: string;
51
- /** ISO 8601 timestamp when the session expires, if set. */
52
- expirationTime?: string;
53
- }
54
- /**
55
- * Options for cookie session serialization.
56
- */
57
- interface CookieOptions {
58
- /**
59
- * The name of the cookie.
60
- * @default "siwx-session"
61
- */
62
- name?: string;
63
- /**
64
- * Max age in seconds. Defaults to 7 days.
65
- * @default 604800
66
- */
67
- maxAge?: number;
68
- /**
69
- * The cookie path.
70
- * @default "/"
71
- */
72
- path?: string;
73
- /**
74
- * The cookie domain.
75
- */
76
- domain?: string;
77
- /**
78
- * Whether to set the Secure flag.
79
- * @default true
80
- */
81
- secure?: boolean;
82
- /**
83
- * The SameSite policy.
84
- * @default "Strict"
85
- */
86
- sameSite?: 'Strict' | 'Lax' | 'None';
87
- }
88
- /**
89
- * The serialized cookie string and session data together.
90
- */
91
- interface SerializedCookieSession {
92
- /** The full `Set-Cookie` header value. */
93
- cookieHeader: string;
94
- /** The session data embedded in the cookie. */
95
- session: SiwxSession;
96
- /** The base64url-encoded session payload (the cookie value). */
97
- cookieValue: string;
98
- }
99
- /**
100
- * Converts a ParsedSiwxMessage to a lean SiwxSession object.
101
- * @internal
102
- */
103
- declare function toSession(parsed: ParsedSiwxMessage): SiwxSession;
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';
104
5
 
105
6
  /**
106
7
  * @fileoverview Server-side CAIP-122 payload verification and session utilities.
@@ -163,4 +64,4 @@ declare function serializeCookieSession(session: SiwxSession, opts?: CookieOptio
163
64
  */
164
65
  declare function deserializeCookieSession(cookieValue: string): SiwxSession | null;
165
66
 
166
- export { type CookieOptions, type SerializedCookieSession, type ServerVerifyOptions, type ServerVerifyResult, type SiwxSession, deserializeCookieSession, serializeCookieSession, toSession, verifySiwxPayload };
67
+ export { CookieOptions, SerializedCookieSession, ServerVerifyOptions, ServerVerifyResult, SiwxSession, deserializeCookieSession, serializeCookieSession, verifySiwxPayload };
package/dist/index.d.ts CHANGED
@@ -1,106 +1,7 @@
1
- import { SiwxVerifyResult, ParsedSiwxMessage, SiwxVerifyPayload } from '@tuwaio/siwx-core';
1
+ import { SiwxVerifyPayload } from '@tuwaio/siwx-core';
2
2
  export { generateNonce as generateServerNonce } from '@tuwaio/siwx-core';
3
-
4
- /**
5
- * @fileoverview Server-side types for the @tuwaio/siwx-server package.
6
- */
7
-
8
- /**
9
- * Options for the `verifySiwxPayload` function.
10
- */
11
- interface ServerVerifyOptions {
12
- /**
13
- * A set of nonces that have already been used.
14
- * If the payload's nonce is found in this set, verification will fail
15
- * to prevent replay attacks. You should populate this from your session store or cache.
16
- */
17
- usedNonces?: Set<string>;
18
- /**
19
- * If true, skips the `expirationTime` validation check.
20
- * Not recommended for production use.
21
- * @default false
22
- */
23
- skipExpiration?: boolean;
24
- }
25
- /**
26
- * The result of a server-side verification operation, extending the base result
27
- * with the verification method used.
28
- */
29
- interface ServerVerifyResult extends SiwxVerifyResult {
30
- /**
31
- * The CAIP-2 namespace used for verification routing.
32
- * `eip155` for EVM chains, `solana` for Solana.
33
- */
34
- namespace?: 'eip155' | 'solana';
35
- }
36
- /**
37
- * Represents a serializable session object derived from a verified CAIP-122 message.
38
- * This can be stored in a cookie or JWT payload.
39
- */
40
- interface SiwxSession {
41
- /** The verified CAIP-10 blockchain address. */
42
- address: string;
43
- /** The CAIP-2 chain ID the session is bound to. */
44
- chainId: string;
45
- /** The domain that issued the session. */
46
- domain: string;
47
- /** The nonce that was used. Must be invalidated server-side after use. */
48
- nonce: string;
49
- /** ISO 8601 timestamp when the session was issued. */
50
- issuedAt: string;
51
- /** ISO 8601 timestamp when the session expires, if set. */
52
- expirationTime?: string;
53
- }
54
- /**
55
- * Options for cookie session serialization.
56
- */
57
- interface CookieOptions {
58
- /**
59
- * The name of the cookie.
60
- * @default "siwx-session"
61
- */
62
- name?: string;
63
- /**
64
- * Max age in seconds. Defaults to 7 days.
65
- * @default 604800
66
- */
67
- maxAge?: number;
68
- /**
69
- * The cookie path.
70
- * @default "/"
71
- */
72
- path?: string;
73
- /**
74
- * The cookie domain.
75
- */
76
- domain?: string;
77
- /**
78
- * Whether to set the Secure flag.
79
- * @default true
80
- */
81
- secure?: boolean;
82
- /**
83
- * The SameSite policy.
84
- * @default "Strict"
85
- */
86
- sameSite?: 'Strict' | 'Lax' | 'None';
87
- }
88
- /**
89
- * The serialized cookie string and session data together.
90
- */
91
- interface SerializedCookieSession {
92
- /** The full `Set-Cookie` header value. */
93
- cookieHeader: string;
94
- /** The session data embedded in the cookie. */
95
- session: SiwxSession;
96
- /** The base64url-encoded session payload (the cookie value). */
97
- cookieValue: string;
98
- }
99
- /**
100
- * Converts a ParsedSiwxMessage to a lean SiwxSession object.
101
- * @internal
102
- */
103
- declare function toSession(parsed: ParsedSiwxMessage): SiwxSession;
3
+ import { S as SiwxSession, C as CookieOptions, a as SerializedCookieSession, b as ServerVerifyOptions, c as ServerVerifyResult } from './types-CvnkVdoo.js';
4
+ export { t as toSession } from './types-CvnkVdoo.js';
104
5
 
105
6
  /**
106
7
  * @fileoverview Server-side CAIP-122 payload verification and session utilities.
@@ -163,4 +64,4 @@ declare function serializeCookieSession(session: SiwxSession, opts?: CookieOptio
163
64
  */
164
65
  declare function deserializeCookieSession(cookieValue: string): SiwxSession | null;
165
66
 
166
- export { type CookieOptions, type SerializedCookieSession, type ServerVerifyOptions, type ServerVerifyResult, type SiwxSession, deserializeCookieSession, serializeCookieSession, toSession, verifySiwxPayload };
67
+ export { CookieOptions, SerializedCookieSession, ServerVerifyOptions, ServerVerifyResult, SiwxSession, deserializeCookieSession, serializeCookieSession, verifySiwxPayload };
package/dist/index.js CHANGED
@@ -1,2 +1 @@
1
- 'use strict';var siwxCore=require('@tuwaio/siwx-core');function p(e){return {address:e.address,chainId:e.chainId,domain:e.domain,nonce:e.nonce,issuedAt:e.issuedAt,expirationTime:e.expirationTime}}async function g(e,r={}){try{let i=siwxCore.parseMessage(e.message),n=siwxCore.validateMessage(i,{skipExpiration:r.skipExpiration});if(!n.valid)return {success:!1,error:`Validation failed: ${n.errors.join(", ")}`};if(!r.skipExpiration&&i.expirationTime&&new Date(i.expirationTime)<new Date)throw new siwxCore.SiwxExpiredSessionError(i.expirationTime);if(r.usedNonces?.has(i.nonce))throw new siwxCore.SiwxNonceReplayError(i.nonce);let s=i.chainId.split(":")[0];if(!s||!["eip155","solana"].includes(s))throw new siwxCore.SiwxUnsupportedNamespaceError(s??"unknown");if(s==="eip155"){let{verifyEip191:o}=await import('@tuwaio/siwx-evm');return {...await o(e.message,e.signature,{skipExpiration:r.skipExpiration}),namespace:s}}if(s==="solana"){let{verifyEd25519:o}=await import('@tuwaio/siwx-solana');return {...await o(e,{skipExpiration:r.skipExpiration}),namespace:s}}return {success:!1,error:"Unsupported namespace."}}catch(i){return i instanceof siwxCore.SiwxExpiredSessionError||i instanceof siwxCore.SiwxNonceReplayError||i instanceof siwxCore.SiwxUnsupportedNamespaceError?{success:false,error:i.message}:{success:false,error:`Server verification failed: ${String(i)}`}}}function w(e){return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function y(e){let r=e.replace(/-/g,"+").replace(/_/g,"/");return atob(r)}function k(e,r={}){let{name:i="siwx-session",maxAge:n=3600*24*7,path:s="/",domain:o,secure:t=true,sameSite:x="Strict"}=r,c=w(JSON.stringify(e)),a=[`${i}=${c}`,`Max-Age=${n}`,`Path=${s}`,"HttpOnly",`SameSite=${x}`];return t&&a.push("Secure"),o&&a.push(`Domain=${o}`),{cookieHeader:a.join("; "),session:e,cookieValue:c}}function v(e){try{let r=y(e);return JSON.parse(r)}catch{return null}}
2
- Object.defineProperty(exports,"generateServerNonce",{enumerable:true,get:function(){return siwxCore.generateNonce}});exports.deserializeCookieSession=v;exports.serializeCookieSession=k;exports.toSession=p;exports.verifySiwxPayload=g;
1
+ 'use strict';var chunk47HTX7ZQ_js=require('./chunk-47HTX7ZQ.js');Object.defineProperty(exports,"deserializeCookieSession",{enumerable:true,get:function(){return chunk47HTX7ZQ_js.e}});Object.defineProperty(exports,"generateServerNonce",{enumerable:true,get:function(){return chunk47HTX7ZQ_js.b}});Object.defineProperty(exports,"serializeCookieSession",{enumerable:true,get:function(){return chunk47HTX7ZQ_js.d}});Object.defineProperty(exports,"toSession",{enumerable:true,get:function(){return chunk47HTX7ZQ_js.a}});Object.defineProperty(exports,"verifySiwxPayload",{enumerable:true,get:function(){return chunk47HTX7ZQ_js.c}});
package/dist/index.mjs CHANGED
@@ -1,2 +1 @@
1
- import {parseMessage,validateMessage,SiwxExpiredSessionError,SiwxNonceReplayError,SiwxUnsupportedNamespaceError}from'@tuwaio/siwx-core';export{generateNonce as generateServerNonce}from'@tuwaio/siwx-core';function p(e){return {address:e.address,chainId:e.chainId,domain:e.domain,nonce:e.nonce,issuedAt:e.issuedAt,expirationTime:e.expirationTime}}async function g(e,r={}){try{let i=parseMessage(e.message),n=validateMessage(i,{skipExpiration:r.skipExpiration});if(!n.valid)return {success:!1,error:`Validation failed: ${n.errors.join(", ")}`};if(!r.skipExpiration&&i.expirationTime&&new Date(i.expirationTime)<new Date)throw new SiwxExpiredSessionError(i.expirationTime);if(r.usedNonces?.has(i.nonce))throw new SiwxNonceReplayError(i.nonce);let s=i.chainId.split(":")[0];if(!s||!["eip155","solana"].includes(s))throw new SiwxUnsupportedNamespaceError(s??"unknown");if(s==="eip155"){let{verifyEip191:o}=await import('@tuwaio/siwx-evm');return {...await o(e.message,e.signature,{skipExpiration:r.skipExpiration}),namespace:s}}if(s==="solana"){let{verifyEd25519:o}=await import('@tuwaio/siwx-solana');return {...await o(e,{skipExpiration:r.skipExpiration}),namespace:s}}return {success:!1,error:"Unsupported namespace."}}catch(i){return i instanceof SiwxExpiredSessionError||i instanceof SiwxNonceReplayError||i instanceof SiwxUnsupportedNamespaceError?{success:false,error:i.message}:{success:false,error:`Server verification failed: ${String(i)}`}}}function w(e){return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function y(e){let r=e.replace(/-/g,"+").replace(/_/g,"/");return atob(r)}function k(e,r={}){let{name:i="siwx-session",maxAge:n=3600*24*7,path:s="/",domain:o,secure:t=true,sameSite:x="Strict"}=r,c=w(JSON.stringify(e)),a=[`${i}=${c}`,`Max-Age=${n}`,`Path=${s}`,"HttpOnly",`SameSite=${x}`];return t&&a.push("Secure"),o&&a.push(`Domain=${o}`),{cookieHeader:a.join("; "),session:e,cookieValue:c}}function v(e){try{let r=y(e);return JSON.parse(r)}catch{return null}}
2
- export{v as deserializeCookieSession,k as serializeCookieSession,p as toSession,g as verifySiwxPayload};
1
+ export{e as deserializeCookieSession,b as generateServerNonce,d as serializeCookieSession,a as toSession,c as verifySiwxPayload}from'./chunk-JVIBIICZ.mjs';
@@ -0,0 +1,43 @@
1
+ import { C as CookieOptions, b as ServerVerifyOptions } from './types-CvnkVdoo.mjs';
2
+ import '@tuwaio/siwx-core';
3
+
4
+ /**
5
+ * @fileoverview Next.js App Router (Route Handlers) API helper for SIWX.
6
+ */
7
+
8
+ interface SiwxApiHandlerOptions {
9
+ /**
10
+ * Options for cookie serialization.
11
+ */
12
+ cookieOptions?: CookieOptions;
13
+ /**
14
+ * Options for server-side payload verification (e.g. nonce replays, public client).
15
+ */
16
+ verifyOptions?: ServerVerifyOptions;
17
+ }
18
+ /**
19
+ * Creates a ready-to-use Next.js App Router route handler for SIWX operations.
20
+ * Exposes GET, POST, and DELETE methods that handle session verification, fetching, and logout.
21
+ *
22
+ * Works purely with the standard Web `Request` and `Response` objects natively
23
+ * supported by Next.js Route Handlers.
24
+ *
25
+ * @param options - Optional configuration for cookies and verification.
26
+ * @returns An object with `GET`, `POST`, and `DELETE` handlers.
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * // app/api/siwx/[...siwx]/route.ts
31
+ * import { createSiwxApiHandler } from '@tuwaio/siwx-server/next';
32
+ *
33
+ * const handler = createSiwxApiHandler();
34
+ * export const { GET, POST, DELETE } = handler;
35
+ * ```
36
+ */
37
+ declare function createSiwxApiHandler(options?: SiwxApiHandlerOptions): {
38
+ GET: (req: Request) => Promise<Response>;
39
+ POST: (req: Request) => Promise<Response>;
40
+ DELETE: (req: Request) => Promise<Response>;
41
+ };
42
+
43
+ export { type SiwxApiHandlerOptions, createSiwxApiHandler };
package/dist/next.d.ts ADDED
@@ -0,0 +1,43 @@
1
+ import { C as CookieOptions, b as ServerVerifyOptions } from './types-CvnkVdoo.js';
2
+ import '@tuwaio/siwx-core';
3
+
4
+ /**
5
+ * @fileoverview Next.js App Router (Route Handlers) API helper for SIWX.
6
+ */
7
+
8
+ interface SiwxApiHandlerOptions {
9
+ /**
10
+ * Options for cookie serialization.
11
+ */
12
+ cookieOptions?: CookieOptions;
13
+ /**
14
+ * Options for server-side payload verification (e.g. nonce replays, public client).
15
+ */
16
+ verifyOptions?: ServerVerifyOptions;
17
+ }
18
+ /**
19
+ * Creates a ready-to-use Next.js App Router route handler for SIWX operations.
20
+ * Exposes GET, POST, and DELETE methods that handle session verification, fetching, and logout.
21
+ *
22
+ * Works purely with the standard Web `Request` and `Response` objects natively
23
+ * supported by Next.js Route Handlers.
24
+ *
25
+ * @param options - Optional configuration for cookies and verification.
26
+ * @returns An object with `GET`, `POST`, and `DELETE` handlers.
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * // app/api/siwx/[...siwx]/route.ts
31
+ * import { createSiwxApiHandler } from '@tuwaio/siwx-server/next';
32
+ *
33
+ * const handler = createSiwxApiHandler();
34
+ * export const { GET, POST, DELETE } = handler;
35
+ * ```
36
+ */
37
+ declare function createSiwxApiHandler(options?: SiwxApiHandlerOptions): {
38
+ GET: (req: Request) => Promise<Response>;
39
+ POST: (req: Request) => Promise<Response>;
40
+ DELETE: (req: Request) => Promise<Response>;
41
+ };
42
+
43
+ export { type SiwxApiHandlerOptions, createSiwxApiHandler };
package/dist/next.js ADDED
@@ -0,0 +1 @@
1
+ 'use strict';var chunk47HTX7ZQ_js=require('./chunk-47HTX7ZQ.js');function T(i={}){let p=i.cookieOptions?.name||"siwx-session",r=async e=>{try{let s="",c=new URL(e.url).pathname.split("/").filter(Boolean);if(s=c[c.length-1]||"",e.method==="GET"&&s==="session"){let t=e.headers.get("cookie")||"",o=Object.fromEntries(t.split("; ").filter(Boolean).map(S=>{let l=S.split("=");return [l[0].trim(),l.slice(1).join("=")]}))[p];if(!o)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let a=chunk47HTX7ZQ_js.e(o);return new Response(JSON.stringify(a),{status:200,headers:{"Content-Type":"application/json"}})}if(e.method==="POST"&&s==="verify"){let t=await e.json();if(!t.message||!t.signature)return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let n=await chunk47HTX7ZQ_js.c(t,i.verifyOptions);if(!n.success)return new Response(JSON.stringify({error:n.error}),{status:401,headers:{"Content-Type":"application/json"}});if(!n.data)return new Response(JSON.stringify({error:"Verification succeeded but returned no data"}),{status:500,headers:{"Content-Type":"application/json"}});let{cookieHeader:o,session:a}=chunk47HTX7ZQ_js.d(chunk47HTX7ZQ_js.a(n.data),i.cookieOptions);return new Response(JSON.stringify(a),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":o}})}return e.method==="DELETE"&&s==="session"||e.method==="POST"&&s==="logout"?new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":`${p}=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly; SameSite=Strict`}}):new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(s){return console.error("[SIWX-SERVER] API Handler error:",s),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:r,POST:r,DELETE:r}}exports.createSiwxApiHandler=T;
package/dist/next.mjs ADDED
@@ -0,0 +1 @@
1
+ import {e,c,d,a}from'./chunk-JVIBIICZ.mjs';function T(i={}){let p=i.cookieOptions?.name||"siwx-session",r=async e$1=>{try{let s="",c$1=new URL(e$1.url).pathname.split("/").filter(Boolean);if(s=c$1[c$1.length-1]||"",e$1.method==="GET"&&s==="session"){let t=e$1.headers.get("cookie")||"",o=Object.fromEntries(t.split("; ").filter(Boolean).map(S=>{let l=S.split("=");return [l[0].trim(),l.slice(1).join("=")]}))[p];if(!o)return new Response(JSON.stringify(null),{status:200,headers:{"Content-Type":"application/json"}});let a=e(o);return new Response(JSON.stringify(a),{status:200,headers:{"Content-Type":"application/json"}})}if(e$1.method==="POST"&&s==="verify"){let t=await e$1.json();if(!t.message||!t.signature)return new Response(JSON.stringify({error:"Missing message or signature"}),{status:400,headers:{"Content-Type":"application/json"}});let n=await c(t,i.verifyOptions);if(!n.success)return new Response(JSON.stringify({error:n.error}),{status:401,headers:{"Content-Type":"application/json"}});if(!n.data)return new Response(JSON.stringify({error:"Verification succeeded but returned no data"}),{status:500,headers:{"Content-Type":"application/json"}});let{cookieHeader:o,session:a$1}=d(a(n.data),i.cookieOptions);return new Response(JSON.stringify(a$1),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":o}})}return e$1.method==="DELETE"&&s==="session"||e$1.method==="POST"&&s==="logout"?new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json","Set-Cookie":`${p}=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly; SameSite=Strict`}}):new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{"Content-Type":"application/json"}})}catch(s){return console.error("[SIWX-SERVER] API Handler error:",s),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}};return {GET:r,POST:r,DELETE:r}}export{T as createSiwxApiHandler};
@@ -0,0 +1,108 @@
1
+ import { SiwxVerifyResult, ParsedSiwxMessage } from '@tuwaio/siwx-core';
2
+
3
+ /**
4
+ * @fileoverview Server-side types for the @tuwaio/siwx-server package.
5
+ */
6
+
7
+ /**
8
+ * Options for the `verifySiwxPayload` function.
9
+ */
10
+ interface ServerVerifyOptions {
11
+ /**
12
+ * A set of nonces that have already been used.
13
+ * If the payload's nonce is found in this set, verification will fail
14
+ * to prevent replay attacks. You should populate this from your session store or cache.
15
+ */
16
+ usedNonces?: Set<string>;
17
+ /**
18
+ * If true, skips the `expirationTime` validation check.
19
+ * Not recommended for production use.
20
+ * @default false
21
+ */
22
+ skipExpiration?: boolean;
23
+ /**
24
+ * Optional viem `PublicClient` instance for EVM chain EIP-1271 (smart contract wallet) verification.
25
+ */
26
+ publicClient?: any;
27
+ }
28
+ /**
29
+ * The result of a server-side verification operation, extending the base result
30
+ * with the verification method used.
31
+ */
32
+ interface ServerVerifyResult extends SiwxVerifyResult {
33
+ /**
34
+ * The CAIP-2 namespace used for verification routing.
35
+ * `eip155` for EVM chains, `solana` for Solana.
36
+ */
37
+ namespace?: 'eip155' | 'solana';
38
+ }
39
+ /**
40
+ * Represents a serializable session object derived from a verified CAIP-122 message.
41
+ * This can be stored in a cookie or JWT payload.
42
+ */
43
+ interface SiwxSession {
44
+ /** The verified CAIP-10 blockchain address. */
45
+ address: string;
46
+ /** The CAIP-2 chain ID the session is bound to. */
47
+ chainId: string;
48
+ /** The domain that issued the session. */
49
+ domain: string;
50
+ /** The nonce that was used. Must be invalidated server-side after use. */
51
+ nonce: string;
52
+ /** ISO 8601 timestamp when the session was issued. */
53
+ issuedAt: string;
54
+ /** ISO 8601 timestamp when the session expires, if set. */
55
+ expirationTime?: string;
56
+ }
57
+ /**
58
+ * Options for cookie session serialization.
59
+ */
60
+ interface CookieOptions {
61
+ /**
62
+ * The name of the cookie.
63
+ * @default "siwx-session"
64
+ */
65
+ name?: string;
66
+ /**
67
+ * Max age in seconds. Defaults to 7 days.
68
+ * @default 604800
69
+ */
70
+ maxAge?: number;
71
+ /**
72
+ * The cookie path.
73
+ * @default "/"
74
+ */
75
+ path?: string;
76
+ /**
77
+ * The cookie domain.
78
+ */
79
+ domain?: string;
80
+ /**
81
+ * Whether to set the Secure flag.
82
+ * @default true
83
+ */
84
+ secure?: boolean;
85
+ /**
86
+ * The SameSite policy.
87
+ * @default "Strict"
88
+ */
89
+ sameSite?: 'Strict' | 'Lax' | 'None';
90
+ }
91
+ /**
92
+ * The serialized cookie string and session data together.
93
+ */
94
+ interface SerializedCookieSession {
95
+ /** The full `Set-Cookie` header value. */
96
+ cookieHeader: string;
97
+ /** The session data embedded in the cookie. */
98
+ session: SiwxSession;
99
+ /** The base64url-encoded session payload (the cookie value). */
100
+ cookieValue: string;
101
+ }
102
+ /**
103
+ * Converts a ParsedSiwxMessage to a lean SiwxSession object.
104
+ * @internal
105
+ */
106
+ declare function toSession(parsed: ParsedSiwxMessage): SiwxSession;
107
+
108
+ export { type CookieOptions as C, type SiwxSession as S, type SerializedCookieSession as a, type ServerVerifyOptions as b, type ServerVerifyResult as c, toSession as t };
@@ -0,0 +1,108 @@
1
+ import { SiwxVerifyResult, ParsedSiwxMessage } from '@tuwaio/siwx-core';
2
+
3
+ /**
4
+ * @fileoverview Server-side types for the @tuwaio/siwx-server package.
5
+ */
6
+
7
+ /**
8
+ * Options for the `verifySiwxPayload` function.
9
+ */
10
+ interface ServerVerifyOptions {
11
+ /**
12
+ * A set of nonces that have already been used.
13
+ * If the payload's nonce is found in this set, verification will fail
14
+ * to prevent replay attacks. You should populate this from your session store or cache.
15
+ */
16
+ usedNonces?: Set<string>;
17
+ /**
18
+ * If true, skips the `expirationTime` validation check.
19
+ * Not recommended for production use.
20
+ * @default false
21
+ */
22
+ skipExpiration?: boolean;
23
+ /**
24
+ * Optional viem `PublicClient` instance for EVM chain EIP-1271 (smart contract wallet) verification.
25
+ */
26
+ publicClient?: any;
27
+ }
28
+ /**
29
+ * The result of a server-side verification operation, extending the base result
30
+ * with the verification method used.
31
+ */
32
+ interface ServerVerifyResult extends SiwxVerifyResult {
33
+ /**
34
+ * The CAIP-2 namespace used for verification routing.
35
+ * `eip155` for EVM chains, `solana` for Solana.
36
+ */
37
+ namespace?: 'eip155' | 'solana';
38
+ }
39
+ /**
40
+ * Represents a serializable session object derived from a verified CAIP-122 message.
41
+ * This can be stored in a cookie or JWT payload.
42
+ */
43
+ interface SiwxSession {
44
+ /** The verified CAIP-10 blockchain address. */
45
+ address: string;
46
+ /** The CAIP-2 chain ID the session is bound to. */
47
+ chainId: string;
48
+ /** The domain that issued the session. */
49
+ domain: string;
50
+ /** The nonce that was used. Must be invalidated server-side after use. */
51
+ nonce: string;
52
+ /** ISO 8601 timestamp when the session was issued. */
53
+ issuedAt: string;
54
+ /** ISO 8601 timestamp when the session expires, if set. */
55
+ expirationTime?: string;
56
+ }
57
+ /**
58
+ * Options for cookie session serialization.
59
+ */
60
+ interface CookieOptions {
61
+ /**
62
+ * The name of the cookie.
63
+ * @default "siwx-session"
64
+ */
65
+ name?: string;
66
+ /**
67
+ * Max age in seconds. Defaults to 7 days.
68
+ * @default 604800
69
+ */
70
+ maxAge?: number;
71
+ /**
72
+ * The cookie path.
73
+ * @default "/"
74
+ */
75
+ path?: string;
76
+ /**
77
+ * The cookie domain.
78
+ */
79
+ domain?: string;
80
+ /**
81
+ * Whether to set the Secure flag.
82
+ * @default true
83
+ */
84
+ secure?: boolean;
85
+ /**
86
+ * The SameSite policy.
87
+ * @default "Strict"
88
+ */
89
+ sameSite?: 'Strict' | 'Lax' | 'None';
90
+ }
91
+ /**
92
+ * The serialized cookie string and session data together.
93
+ */
94
+ interface SerializedCookieSession {
95
+ /** The full `Set-Cookie` header value. */
96
+ cookieHeader: string;
97
+ /** The session data embedded in the cookie. */
98
+ session: SiwxSession;
99
+ /** The base64url-encoded session payload (the cookie value). */
100
+ cookieValue: string;
101
+ }
102
+ /**
103
+ * Converts a ParsedSiwxMessage to a lean SiwxSession object.
104
+ * @internal
105
+ */
106
+ declare function toSession(parsed: ParsedSiwxMessage): SiwxSession;
107
+
108
+ export { type CookieOptions as C, type SiwxSession as S, type SerializedCookieSession as a, type ServerVerifyOptions as b, type ServerVerifyResult as c, toSession as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tuwaio/siwx-server",
3
- "version": "1.0.0-fix-initialize-alpha.1.f397697",
3
+ "version": "1.0.0-fix-initialize-alpha.3.38c3a86",
4
4
  "private": false,
5
5
  "author": "Oleksandr Tkach",
6
6
  "license": "Apache-2.0",
@@ -11,6 +11,28 @@
11
11
  "publishConfig": {
12
12
  "access": "public"
13
13
  },
14
+ "exports": {
15
+ ".": {
16
+ "import": {
17
+ "types": "./dist/index.d.mts",
18
+ "default": "./dist/index.mjs"
19
+ },
20
+ "require": {
21
+ "types": "./dist/index.d.ts",
22
+ "default": "./dist/index.js"
23
+ }
24
+ },
25
+ "./next": {
26
+ "import": {
27
+ "types": "./dist/next.d.mts",
28
+ "default": "./dist/next.mjs"
29
+ },
30
+ "require": {
31
+ "types": "./dist/next.d.ts",
32
+ "default": "./dist/next.js"
33
+ }
34
+ }
35
+ },
14
36
  "files": [
15
37
  "dist",
16
38
  "socket.json"
@@ -46,15 +68,15 @@
46
68
  }
47
69
  ],
48
70
  "peerDependencies": {
49
- "@tuwaio/siwx-core": "1.0.0-fix-initialize-alpha.1.f397697"
71
+ "@tuwaio/siwx-core": "1.0.0-fix-initialize-alpha.3.38c3a86"
50
72
  },
51
73
  "devDependencies": {
52
74
  "tsup": "^8.5.1",
53
75
  "typescript": "^6.0.3",
54
76
  "viem": "^2.55.11",
55
- "@tuwaio/siwx-evm": "1.0.0-fix-initialize-alpha.1.f397697",
56
- "@tuwaio/siwx-solana": "1.0.0-fix-initialize-alpha.1.f397697",
57
- "@tuwaio/siwx-core": "1.0.0-fix-initialize-alpha.1.f397697"
77
+ "@tuwaio/siwx-core": "1.0.0-fix-initialize-alpha.3.38c3a86",
78
+ "@tuwaio/siwx-evm": "1.0.0-fix-initialize-alpha.3.38c3a86",
79
+ "@tuwaio/siwx-solana": "1.0.0-fix-initialize-alpha.3.38c3a86"
58
80
  },
59
81
  "scripts": {
60
82
  "start": "tsup src/index.ts --watch",