@tuwaio/siwx-server 0.1.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/LICENSE +201 -0
- package/README.md +181 -0
- package/dist/chunk-47HTX7ZQ.js +2 -0
- package/dist/chunk-JVIBIICZ.mjs +2 -0
- package/dist/index.d.mts +67 -0
- package/dist/index.d.ts +67 -0
- package/dist/index.js +1 -0
- package/dist/index.mjs +1 -0
- package/dist/next.d.mts +43 -0
- package/dist/next.d.ts +43 -0
- package/dist/next.js +1 -0
- package/dist/next.mjs +1 -0
- package/dist/types-CvnkVdoo.d.mts +108 -0
- package/dist/types-CvnkVdoo.d.ts +108 -0
- package/package.json +87 -0
- package/socket.json +17 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2025 FOP Tkach Oleksandr
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
# `@tuwaio/siwx-server`
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@tuwaio/siwx-server)
|
|
4
|
+
[](./LICENSE)
|
|
5
|
+
|
|
6
|
+
> Backend utilities for `@tuwaio/siwx` (L2). Server-side CAIP-122 payload verification, session serialization, and nonce generation. Fully backend-agnostic — works with any framework.
|
|
7
|
+
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
## 🏛️ Core Capabilities
|
|
11
|
+
|
|
12
|
+
- **`verifySiwxPayload()`**: The primary server entry point. Parses the CAIP-122 message, validates all fields, checks for nonce replay attacks, and dynamically dispatches to the correct chain verifier (`siwx-evm` or `siwx-solana`) based on the CAIP-2 namespace.
|
|
13
|
+
- **`serializeCookieSession()`**: Generates a complete `Set-Cookie` header string with an `HttpOnly` session.
|
|
14
|
+
- **`deserializeCookieSession()`**: Reads and deserializes a session from a cookie value.
|
|
15
|
+
- **`generateServerNonce()`**: A convenience re-export of `generateNonce` from `siwx-core` for generating nonces server-side.
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
## 💾 Installation
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
pnpm add @tuwaio/siwx-server @tuwaio/siwx-core
|
|
23
|
+
# + chain adapters (auto-imported dynamically):
|
|
24
|
+
pnpm add @tuwaio/siwx-evm @tuwaio/siwx-solana
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## 🚀 API & Module Architecture
|
|
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
|
+
|
|
60
|
+
### `verifySiwxPayload(payload, options?): Promise<ServerVerifyResult>`
|
|
61
|
+
|
|
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`).
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
import { verifySiwxPayload, serializeCookieSession, toSession } from '@tuwaio/siwx-server';
|
|
66
|
+
|
|
67
|
+
// In a Next.js API Route or NestJS Controller:
|
|
68
|
+
export async function POST(request: Request) {
|
|
69
|
+
const { message, signature } = await request.json();
|
|
70
|
+
|
|
71
|
+
const result = await verifySiwxPayload(
|
|
72
|
+
{ message, signature },
|
|
73
|
+
{ usedNonces: await getNonceStore() }, // pass your consumed nonces set
|
|
74
|
+
);
|
|
75
|
+
|
|
76
|
+
if (!result.success) {
|
|
77
|
+
return new Response(result.error, { status: 401 });
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Session is valid — issue cookie
|
|
81
|
+
const { cookieHeader } = serializeCookieSession(toSession(result.data!));
|
|
82
|
+
return new Response('OK', {
|
|
83
|
+
headers: { 'Set-Cookie': cookieHeader },
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
### `serializeCookieSession(session, opts?): SerializedCookieSession`
|
|
89
|
+
|
|
90
|
+
Serializes a `SiwxSession` into a `Set-Cookie` header string.
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
import { serializeCookieSession } from '@tuwaio/siwx-server';
|
|
94
|
+
|
|
95
|
+
const { cookieHeader } = serializeCookieSession(session, {
|
|
96
|
+
name: 'tuwa-auth',
|
|
97
|
+
maxAge: 60 * 60 * 24 * 7, // 7 days
|
|
98
|
+
secure: true,
|
|
99
|
+
sameSite: 'Strict',
|
|
100
|
+
});
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
### `deserializeCookieSession(cookieValue): SiwxSession | null`
|
|
104
|
+
|
|
105
|
+
Reads and parses a session from a cookie value (the inverse of `serializeCookieSession`).
|
|
106
|
+
|
|
107
|
+
```ts
|
|
108
|
+
import { deserializeCookieSession } from '@tuwaio/siwx-server';
|
|
109
|
+
|
|
110
|
+
const cookie = request.cookies.get('tuwa-auth')?.value;
|
|
111
|
+
const session = deserializeCookieSession(cookie ?? '');
|
|
112
|
+
if (!session) throw new Error('No valid session');
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
### `generateServerNonce(): string`
|
|
116
|
+
|
|
117
|
+
Generates a secure nonce for sending to the client. Store it in Redis or your DB before sending.
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
import { generateServerNonce } from '@tuwaio/siwx-server';
|
|
121
|
+
|
|
122
|
+
const nonce = generateServerNonce();
|
|
123
|
+
await redis.set(`nonce:${nonce}`, '1', 'EX', 300); // expires in 5 min
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
### `toSession(parsed: ParsedSiwxMessage): SiwxSession`
|
|
127
|
+
|
|
128
|
+
Converts a `ParsedSiwxMessage` into a lean `SiwxSession` object.
|
|
129
|
+
|
|
130
|
+
```ts
|
|
131
|
+
import { toSession } from '@tuwaio/siwx-server';
|
|
132
|
+
|
|
133
|
+
const session = toSession(parsedMessage);
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
### `isSessionMatchingTarget(session, targetAddress, targetChainId?)`
|
|
137
|
+
|
|
138
|
+
Re-exported from `@tuwaio/siwx-core` for server-side authorization checks. Validates if a session matches a target account address and optional chainId.
|
|
139
|
+
|
|
140
|
+
```ts
|
|
141
|
+
import { isSessionMatchingTarget } from '@tuwaio/siwx-server';
|
|
142
|
+
|
|
143
|
+
const isValid = isSessionMatchingTarget(session, userAddress, chainId);
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
---
|
|
147
|
+
|
|
148
|
+
## Nonce Replay Protection
|
|
149
|
+
|
|
150
|
+
Always invalidate used nonces after verification:
|
|
151
|
+
|
|
152
|
+
```ts
|
|
153
|
+
const result = await verifySiwxPayload(
|
|
154
|
+
{ message, signature },
|
|
155
|
+
{
|
|
156
|
+
usedNonces: new Set(await redis.smembers('used_nonces')),
|
|
157
|
+
},
|
|
158
|
+
);
|
|
159
|
+
|
|
160
|
+
if (result.success) {
|
|
161
|
+
// Mark nonce as consumed
|
|
162
|
+
await redis.sadd('used_nonces', result.data!.nonce);
|
|
163
|
+
await redis.expire('used_nonces', 86400); // cleanup after 24h
|
|
164
|
+
}
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
---
|
|
168
|
+
|
|
169
|
+
## Peer Dependencies
|
|
170
|
+
|
|
171
|
+
| Package | Version |
|
|
172
|
+
| ------------------- | ------------- |
|
|
173
|
+
| `@tuwaio/siwx-core` | `workspace:*` |
|
|
174
|
+
|
|
175
|
+
Chain adapters are dynamically imported at runtime — only install the ones you need.
|
|
176
|
+
|
|
177
|
+
---
|
|
178
|
+
|
|
179
|
+
## 📄 License
|
|
180
|
+
|
|
181
|
+
Licensed under the **Apache-2.0 License**. See the [LICENSE](./LICENSE) file for details.
|
|
@@ -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
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
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';
|
|
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
|
+
*/
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Parses and validates a raw CAIP-122 payload (message + signature) on the server side.
|
|
13
|
+
* Dynamically routes verification to the correct chain adapter based on the CAIP-2 namespace.
|
|
14
|
+
*
|
|
15
|
+
* This function is the primary entry point for server-side authentication.
|
|
16
|
+
* It handles EVM (eip155) and Solana chains.
|
|
17
|
+
*
|
|
18
|
+
* @param payload - The `{ message, signature }` payload sent by the client.
|
|
19
|
+
* @param options - Optional server-side verification options (nonce replay protection, etc.).
|
|
20
|
+
* @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
|
+
*/
|
|
33
|
+
declare function verifySiwxPayload(payload: SiwxVerifyPayload, options?: ServerVerifyOptions): Promise<ServerVerifyResult>;
|
|
34
|
+
/**
|
|
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`.
|
|
40
|
+
*
|
|
41
|
+
* @param session - The verified session data to serialize.
|
|
42
|
+
* @param opts - Cookie options (name, maxAge, secure, SameSite, etc.).
|
|
43
|
+
* @returns A `SerializedCookieSession` containing the `Set-Cookie` header value and session data.
|
|
44
|
+
*
|
|
45
|
+
* @example
|
|
46
|
+
* ```ts
|
|
47
|
+
* const { cookieHeader } = serializeCookieSession(session);
|
|
48
|
+
* return new Response(null, { headers: { 'Set-Cookie': cookieHeader } });
|
|
49
|
+
* ```
|
|
50
|
+
*/
|
|
51
|
+
declare function serializeCookieSession(session: SiwxSession, opts?: CookieOptions): SerializedCookieSession;
|
|
52
|
+
/**
|
|
53
|
+
* Deserializes a `SiwxSession` from a base64url-encoded cookie value.
|
|
54
|
+
* This is the inverse of `serializeCookieSession`.
|
|
55
|
+
*
|
|
56
|
+
* @param cookieValue - The raw cookie value string (not the full header).
|
|
57
|
+
* @returns The deserialized `SiwxSession`, or `null` if the value is invalid or malformed.
|
|
58
|
+
*
|
|
59
|
+
* @example
|
|
60
|
+
* ```ts
|
|
61
|
+
* const session = deserializeCookieSession(request.cookies.get('siwx-session'));
|
|
62
|
+
* if (session) console.log('Session address:', session.address);
|
|
63
|
+
* ```
|
|
64
|
+
*/
|
|
65
|
+
declare function deserializeCookieSession(cookieValue: string): SiwxSession | null;
|
|
66
|
+
|
|
67
|
+
export { CookieOptions, SerializedCookieSession, ServerVerifyOptions, ServerVerifyResult, SiwxSession, deserializeCookieSession, serializeCookieSession, verifySiwxPayload };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
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.js';
|
|
4
|
+
export { t as toSession } from './types-CvnkVdoo.js';
|
|
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
|
+
*/
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Parses and validates a raw CAIP-122 payload (message + signature) on the server side.
|
|
13
|
+
* Dynamically routes verification to the correct chain adapter based on the CAIP-2 namespace.
|
|
14
|
+
*
|
|
15
|
+
* This function is the primary entry point for server-side authentication.
|
|
16
|
+
* It handles EVM (eip155) and Solana chains.
|
|
17
|
+
*
|
|
18
|
+
* @param payload - The `{ message, signature }` payload sent by the client.
|
|
19
|
+
* @param options - Optional server-side verification options (nonce replay protection, etc.).
|
|
20
|
+
* @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
|
+
*/
|
|
33
|
+
declare function verifySiwxPayload(payload: SiwxVerifyPayload, options?: ServerVerifyOptions): Promise<ServerVerifyResult>;
|
|
34
|
+
/**
|
|
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`.
|
|
40
|
+
*
|
|
41
|
+
* @param session - The verified session data to serialize.
|
|
42
|
+
* @param opts - Cookie options (name, maxAge, secure, SameSite, etc.).
|
|
43
|
+
* @returns A `SerializedCookieSession` containing the `Set-Cookie` header value and session data.
|
|
44
|
+
*
|
|
45
|
+
* @example
|
|
46
|
+
* ```ts
|
|
47
|
+
* const { cookieHeader } = serializeCookieSession(session);
|
|
48
|
+
* return new Response(null, { headers: { 'Set-Cookie': cookieHeader } });
|
|
49
|
+
* ```
|
|
50
|
+
*/
|
|
51
|
+
declare function serializeCookieSession(session: SiwxSession, opts?: CookieOptions): SerializedCookieSession;
|
|
52
|
+
/**
|
|
53
|
+
* Deserializes a `SiwxSession` from a base64url-encoded cookie value.
|
|
54
|
+
* This is the inverse of `serializeCookieSession`.
|
|
55
|
+
*
|
|
56
|
+
* @param cookieValue - The raw cookie value string (not the full header).
|
|
57
|
+
* @returns The deserialized `SiwxSession`, or `null` if the value is invalid or malformed.
|
|
58
|
+
*
|
|
59
|
+
* @example
|
|
60
|
+
* ```ts
|
|
61
|
+
* const session = deserializeCookieSession(request.cookies.get('siwx-session'));
|
|
62
|
+
* if (session) console.log('Session address:', session.address);
|
|
63
|
+
* ```
|
|
64
|
+
*/
|
|
65
|
+
declare function deserializeCookieSession(cookieValue: string): SiwxSession | null;
|
|
66
|
+
|
|
67
|
+
export { CookieOptions, SerializedCookieSession, ServerVerifyOptions, ServerVerifyResult, SiwxSession, deserializeCookieSession, serializeCookieSession, verifySiwxPayload };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunk47HTX7ZQ_js=require('./chunk-47HTX7ZQ.js'),siwxCore=require('@tuwaio/siwx-core');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}});Object.defineProperty(exports,"isSessionMatchingTarget",{enumerable:true,get:function(){return siwxCore.isSessionMatchingTarget}});
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{e as deserializeCookieSession,b as generateServerNonce,d as serializeCookieSession,a as toSession,c as verifySiwxPayload}from'./chunk-JVIBIICZ.mjs';export{isSessionMatchingTarget}from'@tuwaio/siwx-core';
|
package/dist/next.d.mts
ADDED
|
@@ -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
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@tuwaio/siwx-server",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"private": false,
|
|
5
|
+
"author": "Oleksandr Tkach",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"description": "Layer 2 (L2) of the TUWA Ecosystem. Backend utilities for @tuwaio/siwx. Parses, validates, and verifies CAIP-122 payloads on Node.js or Edge runtimes.",
|
|
8
|
+
"main": "./dist/index.js",
|
|
9
|
+
"module": "./dist/index.mjs",
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"publishConfig": {
|
|
12
|
+
"access": "public"
|
|
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
|
+
},
|
|
36
|
+
"files": [
|
|
37
|
+
"dist",
|
|
38
|
+
"socket.json"
|
|
39
|
+
],
|
|
40
|
+
"keywords": [
|
|
41
|
+
"web3",
|
|
42
|
+
"typescript",
|
|
43
|
+
"caip-122",
|
|
44
|
+
"server",
|
|
45
|
+
"backend",
|
|
46
|
+
"node",
|
|
47
|
+
"edge",
|
|
48
|
+
"authentication",
|
|
49
|
+
"verification",
|
|
50
|
+
"session",
|
|
51
|
+
"cookie",
|
|
52
|
+
"jwt",
|
|
53
|
+
"tuwa"
|
|
54
|
+
],
|
|
55
|
+
"repository": {
|
|
56
|
+
"type": "git",
|
|
57
|
+
"url": "git+https://github.com/TuwaIO/siwx.git",
|
|
58
|
+
"directory": "packages/siwx-server"
|
|
59
|
+
},
|
|
60
|
+
"homepage": "https://github.com/TuwaIO/siwx",
|
|
61
|
+
"bugs": {
|
|
62
|
+
"url": "https://github.com/TuwaIO/siwx/issues"
|
|
63
|
+
},
|
|
64
|
+
"contributors": [
|
|
65
|
+
{
|
|
66
|
+
"name": "Oleksandr Tkach",
|
|
67
|
+
"url": "https://github.com/Argeare5"
|
|
68
|
+
}
|
|
69
|
+
],
|
|
70
|
+
"peerDependencies": {
|
|
71
|
+
"@tuwaio/siwx-core": "0.1.0"
|
|
72
|
+
},
|
|
73
|
+
"devDependencies": {
|
|
74
|
+
"tsup": "^8.5.1",
|
|
75
|
+
"typescript": "^6.0.3",
|
|
76
|
+
"viem": "^2.55.11",
|
|
77
|
+
"@tuwaio/siwx-core": "0.1.0",
|
|
78
|
+
"@tuwaio/siwx-solana": "0.1.0",
|
|
79
|
+
"@tuwaio/siwx-evm": "0.1.0"
|
|
80
|
+
},
|
|
81
|
+
"scripts": {
|
|
82
|
+
"start": "tsup src/index.ts --watch",
|
|
83
|
+
"build": "tsup",
|
|
84
|
+
"test": "vitest run",
|
|
85
|
+
"test:coverage": "vitest run --coverage"
|
|
86
|
+
}
|
|
87
|
+
}
|
package/socket.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://socket.dev/config/schema.json",
|
|
3
|
+
"version": 1,
|
|
4
|
+
"issueRules": {
|
|
5
|
+
"networkAccess": "ignore",
|
|
6
|
+
"envVars": "ignore",
|
|
7
|
+
"filesystemAccess": "ignore",
|
|
8
|
+
"shellAccess": "ignore",
|
|
9
|
+
"minifiedFile": "ignore",
|
|
10
|
+
"obfuscatedFile": "ignore",
|
|
11
|
+
"urlStrings": "ignore",
|
|
12
|
+
"unpopularPackage": "ignore",
|
|
13
|
+
"unstableOwnership": "ignore",
|
|
14
|
+
"newAuthor": "ignore",
|
|
15
|
+
"gptAnomaly": "ignore"
|
|
16
|
+
}
|
|
17
|
+
}
|