@tuwaio/siwx-core 1.0.0-fix-initialize-alpha.1.f397697
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 +106 -0
- package/dist/index.d.mts +302 -0
- package/dist/index.d.ts +302 -0
- package/dist/index.js +5 -0
- package/dist/index.mjs +5 -0
- package/package.json +54 -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,106 @@
|
|
|
1
|
+
# `@tuwaio/siwx-core`
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@tuwaio/siwx-core)
|
|
4
|
+
[](./LICENSE)
|
|
5
|
+
[](https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-122.md)
|
|
6
|
+
|
|
7
|
+
> Chain-agnostic CAIP-122 message building, parsing, and validation. The L1 foundational engine of the `@tuwaio/siwx` ecosystem. **Zero dependencies.**
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## Responsibility
|
|
12
|
+
|
|
13
|
+
This package is the **core foundation**. It has one job: implementing the [CAIP-122](https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-122.md) message standard faithfully.
|
|
14
|
+
|
|
15
|
+
- **Build** compliant CAIP-122 messages from structured fields.
|
|
16
|
+
- **Parse** raw CAIP-122 message strings back into structured objects.
|
|
17
|
+
- **Validate** all fields (domain, CAIP-10 address, CAIP-2 chainId, nonce strength, ISO 8601 dates, expiration checks).
|
|
18
|
+
- **Generate** cryptographically secure nonces.
|
|
19
|
+
- Define all **types** and **error classes** used across the siwx ecosystem.
|
|
20
|
+
|
|
21
|
+
---
|
|
22
|
+
|
|
23
|
+
## Installation
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
pnpm add @tuwaio/siwx-core
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
## API
|
|
32
|
+
|
|
33
|
+
### `buildMessage(fields: SiwxMessageFields): string`
|
|
34
|
+
|
|
35
|
+
Builds a CAIP-122 compliant sign-in message string.
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
import { buildMessage, generateNonce } from '@tuwaio/siwx-core';
|
|
39
|
+
|
|
40
|
+
const message = buildMessage({
|
|
41
|
+
domain: 'app.tuwa.io',
|
|
42
|
+
address: 'eip155:1:0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B',
|
|
43
|
+
statement: 'Sign in to TUWA.',
|
|
44
|
+
uri: 'https://app.tuwa.io',
|
|
45
|
+
version: '1',
|
|
46
|
+
chainId: 'eip155:1',
|
|
47
|
+
nonce: generateNonce(),
|
|
48
|
+
issuedAt: new Date().toISOString(),
|
|
49
|
+
});
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
### `parseMessage(message: string): ParsedSiwxMessage`
|
|
53
|
+
|
|
54
|
+
Parses a raw CAIP-122 message string back into structured fields.
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
import { parseMessage } from '@tuwaio/siwx-core';
|
|
58
|
+
|
|
59
|
+
const parsed = parseMessage(rawMessage);
|
|
60
|
+
console.log(parsed.address); // "eip155:1:0xAb5801..."
|
|
61
|
+
console.log(parsed.chainId); // "eip155:1"
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### `validateMessage(fields: SiwxMessageFields, options?: { skipExpiration?: boolean }): SiwxValidationResult`
|
|
65
|
+
|
|
66
|
+
Validates all fields (domain, CAIP-10 address, URI, version, CAIP-2 chainId, nonce, ISO dates, expiration). Returns `{ valid: boolean, errors: string[] }`.
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
import { validateMessage } from '@tuwaio/siwx-core';
|
|
70
|
+
|
|
71
|
+
const { valid, errors } = validateMessage(parsedMessage);
|
|
72
|
+
if (!valid) console.error(errors);
|
|
73
|
+
|
|
74
|
+
// Optionally skip expiration checking (useful for custom server flows)
|
|
75
|
+
const { valid: isValidExpired } = validateMessage(parsedMessage, { skipExpiration: true });
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### `generateNonce(): string`
|
|
79
|
+
|
|
80
|
+
Generates a 32-character cryptographically secure hex nonce using the Web Crypto API (`globalThis.crypto.getRandomValues`). Native in Node 20+, browsers, and Edge runtimes.
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
import { generateNonce } from '@tuwaio/siwx-core';
|
|
84
|
+
const nonce = generateNonce(); // "a4f3b2c1d0e5f6..."
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
---
|
|
88
|
+
|
|
89
|
+
## Error Classes
|
|
90
|
+
|
|
91
|
+
All errors extend `SiwxError` with a typed `code` property.
|
|
92
|
+
|
|
93
|
+
| Class | Code | Description |
|
|
94
|
+
| ------------------------------- | ---------------------------- | -------------------------------------- |
|
|
95
|
+
| `SiwxParseError` | `SIWX_PARSE_ERROR` | Malformed CAIP-122 message string |
|
|
96
|
+
| `SiwxValidationError` | `SIWX_VALIDATION_ERROR` | One or more field validations failed |
|
|
97
|
+
| `SiwxVerificationError` | `SIWX_VERIFICATION_ERROR` | Signature mismatch or recovery failure |
|
|
98
|
+
| `SiwxExpiredSessionError` | `SIWX_EXPIRED_SESSION` | Session past its `expirationTime` |
|
|
99
|
+
| `SiwxNonceReplayError` | `SIWX_NONCE_REPLAY` | Nonce already consumed |
|
|
100
|
+
| `SiwxUnsupportedNamespaceError` | `SIWX_UNSUPPORTED_NAMESPACE` | Chain namespace not supported |
|
|
101
|
+
|
|
102
|
+
---
|
|
103
|
+
|
|
104
|
+
## 📄 License
|
|
105
|
+
|
|
106
|
+
Licensed under the **Apache-2.0 License**. See the [LICENSE](./LICENSE) file for details.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Core type definitions for the CAIP-122 (Sign-In With X) standard.
|
|
3
|
+
* These types are chain-agnostic and form the foundation of the entire siwx ecosystem.
|
|
4
|
+
*
|
|
5
|
+
* @see {@link https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-122.md CAIP-122 Specification}
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* Supported CAIP-2 chain namespace identifiers.
|
|
9
|
+
* Only EVM (eip155) and Solana are supported in v1.
|
|
10
|
+
*/
|
|
11
|
+
type SiwxChainNamespace = 'eip155' | 'solana';
|
|
12
|
+
/**
|
|
13
|
+
* A fully qualified CAIP-2 chain ID string.
|
|
14
|
+
* @example "eip155:1" (Ethereum Mainnet)
|
|
15
|
+
* @example "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpK" (Solana Mainnet)
|
|
16
|
+
*/
|
|
17
|
+
type SiwxChainId = `${SiwxChainNamespace}:${string}`;
|
|
18
|
+
/**
|
|
19
|
+
* The lifecycle status of a SIWX authentication session.
|
|
20
|
+
*/
|
|
21
|
+
type SiwxStatus = 'idle' | 'building' | 'signing' | 'verifying' | 'authenticated' | 'error';
|
|
22
|
+
/**
|
|
23
|
+
* The complete set of fields required to build a CAIP-122 compliant message.
|
|
24
|
+
* All fields follow the CAIP-122 specification.
|
|
25
|
+
*/
|
|
26
|
+
interface SiwxMessageFields {
|
|
27
|
+
/**
|
|
28
|
+
* The RFC 3986 URI of the domain requesting the sign-in.
|
|
29
|
+
* @example "app.tuwa.io"
|
|
30
|
+
*/
|
|
31
|
+
domain: string;
|
|
32
|
+
/**
|
|
33
|
+
* The blockchain account address performing the sign-in, CAIP-10 compliant.
|
|
34
|
+
* @example "eip155:1:0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B"
|
|
35
|
+
*/
|
|
36
|
+
address: string;
|
|
37
|
+
/**
|
|
38
|
+
* A statement (human-readable) that the user will sign.
|
|
39
|
+
* Must not contain '\n'.
|
|
40
|
+
*/
|
|
41
|
+
statement?: string;
|
|
42
|
+
/**
|
|
43
|
+
* The RFC 3986 URI referring to the resource that is the subject of the sign-in.
|
|
44
|
+
* @example "https://app.tuwa.io"
|
|
45
|
+
*/
|
|
46
|
+
uri: string;
|
|
47
|
+
/**
|
|
48
|
+
* The version of the CAIP-122 message specification.
|
|
49
|
+
* Currently always "1".
|
|
50
|
+
*/
|
|
51
|
+
version: '1';
|
|
52
|
+
/**
|
|
53
|
+
* The CAIP-2 chain ID to which the session is bound.
|
|
54
|
+
* @example "eip155:1"
|
|
55
|
+
*/
|
|
56
|
+
chainId: SiwxChainId;
|
|
57
|
+
/**
|
|
58
|
+
* A unique, secure, randomly generated string used to prevent replay attacks.
|
|
59
|
+
* @example "32891757"
|
|
60
|
+
*/
|
|
61
|
+
nonce: string;
|
|
62
|
+
/**
|
|
63
|
+
* The ISO 8601 datetime string of when the message was generated.
|
|
64
|
+
* @example "2021-09-30T16:25:24Z"
|
|
65
|
+
*/
|
|
66
|
+
issuedAt: string;
|
|
67
|
+
/**
|
|
68
|
+
* Optional ISO 8601 datetime string after which the session is no longer valid.
|
|
69
|
+
*/
|
|
70
|
+
expirationTime?: string;
|
|
71
|
+
/**
|
|
72
|
+
* Optional ISO 8601 datetime string when the session is valid from.
|
|
73
|
+
*/
|
|
74
|
+
notBefore?: string;
|
|
75
|
+
/**
|
|
76
|
+
* Optional system-specific identifier for the request.
|
|
77
|
+
*/
|
|
78
|
+
requestId?: string;
|
|
79
|
+
/**
|
|
80
|
+
* Optional list of URIs the session is valid for.
|
|
81
|
+
*/
|
|
82
|
+
resources?: string[];
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* The result of a message validation operation.
|
|
86
|
+
*/
|
|
87
|
+
interface SiwxValidationResult {
|
|
88
|
+
/** Whether the message fields are valid. */
|
|
89
|
+
valid: boolean;
|
|
90
|
+
/** List of validation error messages, empty if valid. */
|
|
91
|
+
errors: string[];
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* A parsed CAIP-122 message, structurally identical to the fields used to build it.
|
|
95
|
+
*/
|
|
96
|
+
type ParsedSiwxMessage = SiwxMessageFields;
|
|
97
|
+
/**
|
|
98
|
+
* The payload submitted for signature verification.
|
|
99
|
+
*/
|
|
100
|
+
interface SiwxVerifyPayload {
|
|
101
|
+
/** The raw CAIP-122 compliant message string that was signed. */
|
|
102
|
+
message: string;
|
|
103
|
+
/** The signature produced by the wallet. */
|
|
104
|
+
signature: string;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* The result of a signature verification operation.
|
|
108
|
+
*/
|
|
109
|
+
interface SiwxVerifyResult {
|
|
110
|
+
/** Whether the signature is valid and the message is authentic. */
|
|
111
|
+
success: boolean;
|
|
112
|
+
/**
|
|
113
|
+
* The parsed message fields if verification succeeded.
|
|
114
|
+
* Present only when `success` is true.
|
|
115
|
+
*/
|
|
116
|
+
data?: ParsedSiwxMessage;
|
|
117
|
+
/**
|
|
118
|
+
* A human-readable error if verification failed.
|
|
119
|
+
* Present only when `success` is false.
|
|
120
|
+
*/
|
|
121
|
+
error?: string;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* A chain-specific adapter interface that all siwx chain packages must implement.
|
|
125
|
+
*/
|
|
126
|
+
interface SiwxAdapter {
|
|
127
|
+
/**
|
|
128
|
+
* The CAIP-2 namespace this adapter handles.
|
|
129
|
+
*/
|
|
130
|
+
namespace: SiwxChainNamespace;
|
|
131
|
+
/**
|
|
132
|
+
* Verifies a CAIP-122 payload signature.
|
|
133
|
+
* @param payload - The message and signature to verify.
|
|
134
|
+
* @returns A promise resolving to the verification result.
|
|
135
|
+
*/
|
|
136
|
+
verify(payload: SiwxVerifyPayload): Promise<SiwxVerifyResult>;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* @fileoverview CAIP-122 compliant message builder.
|
|
141
|
+
* Generates the human-readable sign-in message string from structured fields.
|
|
142
|
+
*/
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Builds a CAIP-122 compliant sign-in message string from the provided fields.
|
|
146
|
+
* The output format follows the EIP-4361 / CAIP-122 specification exactly.
|
|
147
|
+
*
|
|
148
|
+
* @param fields - The structured fields to encode into the message.
|
|
149
|
+
* @returns A formatted, human-readable message string ready for wallet signing.
|
|
150
|
+
*
|
|
151
|
+
* @example
|
|
152
|
+
* ```ts
|
|
153
|
+
* const message = buildMessage({
|
|
154
|
+
* domain: 'app.tuwa.io',
|
|
155
|
+
* address: 'eip155:1:0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B',
|
|
156
|
+
* uri: 'https://app.tuwa.io',
|
|
157
|
+
* version: '1',
|
|
158
|
+
* chainId: 'eip155:1',
|
|
159
|
+
* nonce: 'abc123xyz',
|
|
160
|
+
* issuedAt: new Date().toISOString(),
|
|
161
|
+
* statement: 'Sign in to TUWA.',
|
|
162
|
+
* });
|
|
163
|
+
* ```
|
|
164
|
+
*/
|
|
165
|
+
declare function buildMessage(fields: SiwxMessageFields): string;
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* @fileoverview Error classes for the @tuwaio/siwx-core package.
|
|
169
|
+
* All errors are typed and carry contextual information for proper handling.
|
|
170
|
+
*/
|
|
171
|
+
/**
|
|
172
|
+
* Base error class for all siwx-related errors.
|
|
173
|
+
* Extends the native Error with an optional error code for programmatic handling.
|
|
174
|
+
*/
|
|
175
|
+
declare class SiwxError extends Error {
|
|
176
|
+
readonly code: string;
|
|
177
|
+
/**
|
|
178
|
+
* @param message - Human-readable description of the error.
|
|
179
|
+
* @param code - Optional machine-readable error code.
|
|
180
|
+
*/
|
|
181
|
+
constructor(message: string, code?: string);
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Thrown when a CAIP-122 message string cannot be parsed.
|
|
185
|
+
* This indicates the message is malformed or not CAIP-122 compliant.
|
|
186
|
+
*/
|
|
187
|
+
declare class SiwxParseError extends SiwxError {
|
|
188
|
+
/**
|
|
189
|
+
* @param message - Human-readable description of the parse failure.
|
|
190
|
+
*/
|
|
191
|
+
constructor(message: string);
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Thrown when one or more fields in a SiwxMessage fail validation.
|
|
195
|
+
* The `errors` property contains a list of all validation failures.
|
|
196
|
+
*/
|
|
197
|
+
declare class SiwxValidationError extends SiwxError {
|
|
198
|
+
readonly errors: string[];
|
|
199
|
+
/**
|
|
200
|
+
* @param errors - Array of validation error descriptions.
|
|
201
|
+
*/
|
|
202
|
+
constructor(errors: string[]);
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Thrown when a signature verification operation fails.
|
|
206
|
+
* Indicates the signature is invalid, the message was tampered with,
|
|
207
|
+
* or the signer address does not match.
|
|
208
|
+
*/
|
|
209
|
+
declare class SiwxVerificationError extends SiwxError {
|
|
210
|
+
/**
|
|
211
|
+
* @param message - Human-readable description of the verification failure.
|
|
212
|
+
*/
|
|
213
|
+
constructor(message: string);
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Thrown when the session or message has expired based on the `expirationTime` field.
|
|
217
|
+
*/
|
|
218
|
+
declare class SiwxExpiredSessionError extends SiwxError {
|
|
219
|
+
readonly expirationTime: string;
|
|
220
|
+
/**
|
|
221
|
+
* @param expirationTime - The ISO 8601 timestamp when the session expired.
|
|
222
|
+
*/
|
|
223
|
+
constructor(expirationTime: string);
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Thrown when a nonce replay attack is detected, i.e., the nonce has already been used.
|
|
227
|
+
*/
|
|
228
|
+
declare class SiwxNonceReplayError extends SiwxError {
|
|
229
|
+
readonly nonce: string;
|
|
230
|
+
/**
|
|
231
|
+
* @param nonce - The nonce that was detected as replayed.
|
|
232
|
+
*/
|
|
233
|
+
constructor(nonce: string);
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Thrown when the chain namespace in the message is not supported.
|
|
237
|
+
*/
|
|
238
|
+
declare class SiwxUnsupportedNamespaceError extends SiwxError {
|
|
239
|
+
readonly namespace: string;
|
|
240
|
+
/**
|
|
241
|
+
* @param namespace - The unsupported namespace string extracted from the message.
|
|
242
|
+
*/
|
|
243
|
+
constructor(namespace: string);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* @fileoverview CAIP-122 message parser.
|
|
248
|
+
* Converts a raw CAIP-122 compliant message string back into structured fields.
|
|
249
|
+
*/
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Parses a raw CAIP-122 compliant message string into a structured `ParsedSiwxMessage` object.
|
|
253
|
+
*
|
|
254
|
+
* @param message - The raw message string produced by `buildMessage` and signed by the wallet.
|
|
255
|
+
* @returns The structured fields extracted from the message.
|
|
256
|
+
* @throws {SiwxParseError} If the message is malformed or missing required fields.
|
|
257
|
+
*
|
|
258
|
+
* @example
|
|
259
|
+
* ```ts
|
|
260
|
+
* const parsed = parseMessage(rawMessageString);
|
|
261
|
+
* console.log(parsed.address); // "eip155:1:0xAb5..."
|
|
262
|
+
* ```
|
|
263
|
+
*/
|
|
264
|
+
declare function parseMessage(message: string): ParsedSiwxMessage;
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* @fileoverview CAIP-122 message field validators.
|
|
268
|
+
* Provides individual validators and a composite `validateMessage` function.
|
|
269
|
+
*/
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Validates all fields of a CAIP-122 message object.
|
|
273
|
+
* Collects all errors and returns them together rather than failing on the first.
|
|
274
|
+
*
|
|
275
|
+
* @param fields - The message fields to validate.
|
|
276
|
+
* @returns A `SiwxValidationResult` with `valid: true` or a list of errors.
|
|
277
|
+
*
|
|
278
|
+
* @example
|
|
279
|
+
* ```ts
|
|
280
|
+
* const result = validateMessage(parsedMessage);
|
|
281
|
+
* if (!result.valid) {
|
|
282
|
+
* console.error(result.errors);
|
|
283
|
+
* }
|
|
284
|
+
* ```
|
|
285
|
+
*/
|
|
286
|
+
declare function validateMessage(fields: SiwxMessageFields, options?: {
|
|
287
|
+
skipExpiration?: boolean;
|
|
288
|
+
}): SiwxValidationResult;
|
|
289
|
+
/**
|
|
290
|
+
* Generates a cryptographically secure random nonce string suitable for CAIP-122 messages.
|
|
291
|
+
* Produces a 16-byte random hex string (32 characters).
|
|
292
|
+
*
|
|
293
|
+
* @returns A 32-character hexadecimal nonce string.
|
|
294
|
+
*
|
|
295
|
+
* @example
|
|
296
|
+
* ```ts
|
|
297
|
+
* const nonce = generateNonce(); // e.g., "a4f3b2c1d0e5f6789..."
|
|
298
|
+
* ```
|
|
299
|
+
*/
|
|
300
|
+
declare function generateNonce(): string;
|
|
301
|
+
|
|
302
|
+
export { type ParsedSiwxMessage, type SiwxAdapter, type SiwxChainId, type SiwxChainNamespace, SiwxError, SiwxExpiredSessionError, type SiwxMessageFields, SiwxNonceReplayError, SiwxParseError, type SiwxStatus, SiwxUnsupportedNamespaceError, SiwxValidationError, type SiwxValidationResult, SiwxVerificationError, type SiwxVerifyPayload, type SiwxVerifyResult, buildMessage, generateNonce, parseMessage, validateMessage };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Core type definitions for the CAIP-122 (Sign-In With X) standard.
|
|
3
|
+
* These types are chain-agnostic and form the foundation of the entire siwx ecosystem.
|
|
4
|
+
*
|
|
5
|
+
* @see {@link https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-122.md CAIP-122 Specification}
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* Supported CAIP-2 chain namespace identifiers.
|
|
9
|
+
* Only EVM (eip155) and Solana are supported in v1.
|
|
10
|
+
*/
|
|
11
|
+
type SiwxChainNamespace = 'eip155' | 'solana';
|
|
12
|
+
/**
|
|
13
|
+
* A fully qualified CAIP-2 chain ID string.
|
|
14
|
+
* @example "eip155:1" (Ethereum Mainnet)
|
|
15
|
+
* @example "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpK" (Solana Mainnet)
|
|
16
|
+
*/
|
|
17
|
+
type SiwxChainId = `${SiwxChainNamespace}:${string}`;
|
|
18
|
+
/**
|
|
19
|
+
* The lifecycle status of a SIWX authentication session.
|
|
20
|
+
*/
|
|
21
|
+
type SiwxStatus = 'idle' | 'building' | 'signing' | 'verifying' | 'authenticated' | 'error';
|
|
22
|
+
/**
|
|
23
|
+
* The complete set of fields required to build a CAIP-122 compliant message.
|
|
24
|
+
* All fields follow the CAIP-122 specification.
|
|
25
|
+
*/
|
|
26
|
+
interface SiwxMessageFields {
|
|
27
|
+
/**
|
|
28
|
+
* The RFC 3986 URI of the domain requesting the sign-in.
|
|
29
|
+
* @example "app.tuwa.io"
|
|
30
|
+
*/
|
|
31
|
+
domain: string;
|
|
32
|
+
/**
|
|
33
|
+
* The blockchain account address performing the sign-in, CAIP-10 compliant.
|
|
34
|
+
* @example "eip155:1:0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B"
|
|
35
|
+
*/
|
|
36
|
+
address: string;
|
|
37
|
+
/**
|
|
38
|
+
* A statement (human-readable) that the user will sign.
|
|
39
|
+
* Must not contain '\n'.
|
|
40
|
+
*/
|
|
41
|
+
statement?: string;
|
|
42
|
+
/**
|
|
43
|
+
* The RFC 3986 URI referring to the resource that is the subject of the sign-in.
|
|
44
|
+
* @example "https://app.tuwa.io"
|
|
45
|
+
*/
|
|
46
|
+
uri: string;
|
|
47
|
+
/**
|
|
48
|
+
* The version of the CAIP-122 message specification.
|
|
49
|
+
* Currently always "1".
|
|
50
|
+
*/
|
|
51
|
+
version: '1';
|
|
52
|
+
/**
|
|
53
|
+
* The CAIP-2 chain ID to which the session is bound.
|
|
54
|
+
* @example "eip155:1"
|
|
55
|
+
*/
|
|
56
|
+
chainId: SiwxChainId;
|
|
57
|
+
/**
|
|
58
|
+
* A unique, secure, randomly generated string used to prevent replay attacks.
|
|
59
|
+
* @example "32891757"
|
|
60
|
+
*/
|
|
61
|
+
nonce: string;
|
|
62
|
+
/**
|
|
63
|
+
* The ISO 8601 datetime string of when the message was generated.
|
|
64
|
+
* @example "2021-09-30T16:25:24Z"
|
|
65
|
+
*/
|
|
66
|
+
issuedAt: string;
|
|
67
|
+
/**
|
|
68
|
+
* Optional ISO 8601 datetime string after which the session is no longer valid.
|
|
69
|
+
*/
|
|
70
|
+
expirationTime?: string;
|
|
71
|
+
/**
|
|
72
|
+
* Optional ISO 8601 datetime string when the session is valid from.
|
|
73
|
+
*/
|
|
74
|
+
notBefore?: string;
|
|
75
|
+
/**
|
|
76
|
+
* Optional system-specific identifier for the request.
|
|
77
|
+
*/
|
|
78
|
+
requestId?: string;
|
|
79
|
+
/**
|
|
80
|
+
* Optional list of URIs the session is valid for.
|
|
81
|
+
*/
|
|
82
|
+
resources?: string[];
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* The result of a message validation operation.
|
|
86
|
+
*/
|
|
87
|
+
interface SiwxValidationResult {
|
|
88
|
+
/** Whether the message fields are valid. */
|
|
89
|
+
valid: boolean;
|
|
90
|
+
/** List of validation error messages, empty if valid. */
|
|
91
|
+
errors: string[];
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* A parsed CAIP-122 message, structurally identical to the fields used to build it.
|
|
95
|
+
*/
|
|
96
|
+
type ParsedSiwxMessage = SiwxMessageFields;
|
|
97
|
+
/**
|
|
98
|
+
* The payload submitted for signature verification.
|
|
99
|
+
*/
|
|
100
|
+
interface SiwxVerifyPayload {
|
|
101
|
+
/** The raw CAIP-122 compliant message string that was signed. */
|
|
102
|
+
message: string;
|
|
103
|
+
/** The signature produced by the wallet. */
|
|
104
|
+
signature: string;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* The result of a signature verification operation.
|
|
108
|
+
*/
|
|
109
|
+
interface SiwxVerifyResult {
|
|
110
|
+
/** Whether the signature is valid and the message is authentic. */
|
|
111
|
+
success: boolean;
|
|
112
|
+
/**
|
|
113
|
+
* The parsed message fields if verification succeeded.
|
|
114
|
+
* Present only when `success` is true.
|
|
115
|
+
*/
|
|
116
|
+
data?: ParsedSiwxMessage;
|
|
117
|
+
/**
|
|
118
|
+
* A human-readable error if verification failed.
|
|
119
|
+
* Present only when `success` is false.
|
|
120
|
+
*/
|
|
121
|
+
error?: string;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* A chain-specific adapter interface that all siwx chain packages must implement.
|
|
125
|
+
*/
|
|
126
|
+
interface SiwxAdapter {
|
|
127
|
+
/**
|
|
128
|
+
* The CAIP-2 namespace this adapter handles.
|
|
129
|
+
*/
|
|
130
|
+
namespace: SiwxChainNamespace;
|
|
131
|
+
/**
|
|
132
|
+
* Verifies a CAIP-122 payload signature.
|
|
133
|
+
* @param payload - The message and signature to verify.
|
|
134
|
+
* @returns A promise resolving to the verification result.
|
|
135
|
+
*/
|
|
136
|
+
verify(payload: SiwxVerifyPayload): Promise<SiwxVerifyResult>;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* @fileoverview CAIP-122 compliant message builder.
|
|
141
|
+
* Generates the human-readable sign-in message string from structured fields.
|
|
142
|
+
*/
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Builds a CAIP-122 compliant sign-in message string from the provided fields.
|
|
146
|
+
* The output format follows the EIP-4361 / CAIP-122 specification exactly.
|
|
147
|
+
*
|
|
148
|
+
* @param fields - The structured fields to encode into the message.
|
|
149
|
+
* @returns A formatted, human-readable message string ready for wallet signing.
|
|
150
|
+
*
|
|
151
|
+
* @example
|
|
152
|
+
* ```ts
|
|
153
|
+
* const message = buildMessage({
|
|
154
|
+
* domain: 'app.tuwa.io',
|
|
155
|
+
* address: 'eip155:1:0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B',
|
|
156
|
+
* uri: 'https://app.tuwa.io',
|
|
157
|
+
* version: '1',
|
|
158
|
+
* chainId: 'eip155:1',
|
|
159
|
+
* nonce: 'abc123xyz',
|
|
160
|
+
* issuedAt: new Date().toISOString(),
|
|
161
|
+
* statement: 'Sign in to TUWA.',
|
|
162
|
+
* });
|
|
163
|
+
* ```
|
|
164
|
+
*/
|
|
165
|
+
declare function buildMessage(fields: SiwxMessageFields): string;
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* @fileoverview Error classes for the @tuwaio/siwx-core package.
|
|
169
|
+
* All errors are typed and carry contextual information for proper handling.
|
|
170
|
+
*/
|
|
171
|
+
/**
|
|
172
|
+
* Base error class for all siwx-related errors.
|
|
173
|
+
* Extends the native Error with an optional error code for programmatic handling.
|
|
174
|
+
*/
|
|
175
|
+
declare class SiwxError extends Error {
|
|
176
|
+
readonly code: string;
|
|
177
|
+
/**
|
|
178
|
+
* @param message - Human-readable description of the error.
|
|
179
|
+
* @param code - Optional machine-readable error code.
|
|
180
|
+
*/
|
|
181
|
+
constructor(message: string, code?: string);
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Thrown when a CAIP-122 message string cannot be parsed.
|
|
185
|
+
* This indicates the message is malformed or not CAIP-122 compliant.
|
|
186
|
+
*/
|
|
187
|
+
declare class SiwxParseError extends SiwxError {
|
|
188
|
+
/**
|
|
189
|
+
* @param message - Human-readable description of the parse failure.
|
|
190
|
+
*/
|
|
191
|
+
constructor(message: string);
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Thrown when one or more fields in a SiwxMessage fail validation.
|
|
195
|
+
* The `errors` property contains a list of all validation failures.
|
|
196
|
+
*/
|
|
197
|
+
declare class SiwxValidationError extends SiwxError {
|
|
198
|
+
readonly errors: string[];
|
|
199
|
+
/**
|
|
200
|
+
* @param errors - Array of validation error descriptions.
|
|
201
|
+
*/
|
|
202
|
+
constructor(errors: string[]);
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Thrown when a signature verification operation fails.
|
|
206
|
+
* Indicates the signature is invalid, the message was tampered with,
|
|
207
|
+
* or the signer address does not match.
|
|
208
|
+
*/
|
|
209
|
+
declare class SiwxVerificationError extends SiwxError {
|
|
210
|
+
/**
|
|
211
|
+
* @param message - Human-readable description of the verification failure.
|
|
212
|
+
*/
|
|
213
|
+
constructor(message: string);
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Thrown when the session or message has expired based on the `expirationTime` field.
|
|
217
|
+
*/
|
|
218
|
+
declare class SiwxExpiredSessionError extends SiwxError {
|
|
219
|
+
readonly expirationTime: string;
|
|
220
|
+
/**
|
|
221
|
+
* @param expirationTime - The ISO 8601 timestamp when the session expired.
|
|
222
|
+
*/
|
|
223
|
+
constructor(expirationTime: string);
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Thrown when a nonce replay attack is detected, i.e., the nonce has already been used.
|
|
227
|
+
*/
|
|
228
|
+
declare class SiwxNonceReplayError extends SiwxError {
|
|
229
|
+
readonly nonce: string;
|
|
230
|
+
/**
|
|
231
|
+
* @param nonce - The nonce that was detected as replayed.
|
|
232
|
+
*/
|
|
233
|
+
constructor(nonce: string);
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Thrown when the chain namespace in the message is not supported.
|
|
237
|
+
*/
|
|
238
|
+
declare class SiwxUnsupportedNamespaceError extends SiwxError {
|
|
239
|
+
readonly namespace: string;
|
|
240
|
+
/**
|
|
241
|
+
* @param namespace - The unsupported namespace string extracted from the message.
|
|
242
|
+
*/
|
|
243
|
+
constructor(namespace: string);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* @fileoverview CAIP-122 message parser.
|
|
248
|
+
* Converts a raw CAIP-122 compliant message string back into structured fields.
|
|
249
|
+
*/
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Parses a raw CAIP-122 compliant message string into a structured `ParsedSiwxMessage` object.
|
|
253
|
+
*
|
|
254
|
+
* @param message - The raw message string produced by `buildMessage` and signed by the wallet.
|
|
255
|
+
* @returns The structured fields extracted from the message.
|
|
256
|
+
* @throws {SiwxParseError} If the message is malformed or missing required fields.
|
|
257
|
+
*
|
|
258
|
+
* @example
|
|
259
|
+
* ```ts
|
|
260
|
+
* const parsed = parseMessage(rawMessageString);
|
|
261
|
+
* console.log(parsed.address); // "eip155:1:0xAb5..."
|
|
262
|
+
* ```
|
|
263
|
+
*/
|
|
264
|
+
declare function parseMessage(message: string): ParsedSiwxMessage;
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* @fileoverview CAIP-122 message field validators.
|
|
268
|
+
* Provides individual validators and a composite `validateMessage` function.
|
|
269
|
+
*/
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Validates all fields of a CAIP-122 message object.
|
|
273
|
+
* Collects all errors and returns them together rather than failing on the first.
|
|
274
|
+
*
|
|
275
|
+
* @param fields - The message fields to validate.
|
|
276
|
+
* @returns A `SiwxValidationResult` with `valid: true` or a list of errors.
|
|
277
|
+
*
|
|
278
|
+
* @example
|
|
279
|
+
* ```ts
|
|
280
|
+
* const result = validateMessage(parsedMessage);
|
|
281
|
+
* if (!result.valid) {
|
|
282
|
+
* console.error(result.errors);
|
|
283
|
+
* }
|
|
284
|
+
* ```
|
|
285
|
+
*/
|
|
286
|
+
declare function validateMessage(fields: SiwxMessageFields, options?: {
|
|
287
|
+
skipExpiration?: boolean;
|
|
288
|
+
}): SiwxValidationResult;
|
|
289
|
+
/**
|
|
290
|
+
* Generates a cryptographically secure random nonce string suitable for CAIP-122 messages.
|
|
291
|
+
* Produces a 16-byte random hex string (32 characters).
|
|
292
|
+
*
|
|
293
|
+
* @returns A 32-character hexadecimal nonce string.
|
|
294
|
+
*
|
|
295
|
+
* @example
|
|
296
|
+
* ```ts
|
|
297
|
+
* const nonce = generateNonce(); // e.g., "a4f3b2c1d0e5f6789..."
|
|
298
|
+
* ```
|
|
299
|
+
*/
|
|
300
|
+
declare function generateNonce(): string;
|
|
301
|
+
|
|
302
|
+
export { type ParsedSiwxMessage, type SiwxAdapter, type SiwxChainId, type SiwxChainNamespace, SiwxError, SiwxExpiredSessionError, type SiwxMessageFields, SiwxNonceReplayError, SiwxParseError, type SiwxStatus, SiwxUnsupportedNamespaceError, SiwxValidationError, type SiwxValidationResult, SiwxVerificationError, type SiwxVerifyPayload, type SiwxVerifyResult, buildMessage, generateNonce, parseMessage, validateMessage };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
'use strict';function A(e){let{domain:t,address:n,statement:c,uri:l,version:r,chainId:g,nonce:s,issuedAt:p,expirationTime:i,notBefore:h,requestId:a,resources:f}=e,o=[`${t} wants you to sign in with your blockchain account:`,n,""];if(c&&o.push(c,""),o.push(`URI: ${l}`,`Version: ${r}`,`Chain ID: ${g}`,`Nonce: ${s}`,`Issued At: ${p}`),i&&o.push(`Expiration Time: ${i}`),h&&o.push(`Not Before: ${h}`),a&&o.push(`Request ID: ${a}`),f&&f.length>0){o.push("Resources:");for(let y of f)o.push(`- ${y}`);}return o.join(`
|
|
2
|
+
`)}var d=class extends Error{constructor(n,c="SIWX_ERROR"){super(n);this.code=c;this.name="SiwxError",Object.setPrototypeOf(this,new.target.prototype);}code},u=class extends d{constructor(t){super(t,"SIWX_PARSE_ERROR"),this.name="SiwxParseError";}},m=class extends d{constructor(n){super(`CAIP-122 message validation failed: ${n.join(", ")}`,"SIWX_VALIDATION_ERROR");this.errors=n;this.name="SiwxValidationError";}errors},x=class extends d{constructor(t){super(t,"SIWX_VERIFICATION_ERROR"),this.name="SiwxVerificationError";}},E=class extends d{constructor(n){super(`SIWX session expired at ${n}`,"SIWX_EXPIRED_SESSION");this.expirationTime=n;this.name="SiwxExpiredSessionError";}expirationTime},w=class extends d{constructor(n){super(`Nonce has already been used: ${n}`,"SIWX_NONCE_REPLAY");this.nonce=n;this.name="SiwxNonceReplayError";}nonce},I=class extends d{constructor(n){super(`Unsupported CAIP-2 namespace: "${n}". Supported: eip155, solana`,"SIWX_UNSUPPORTED_NAMESPACE");this.namespace=n;this.name="SiwxUnsupportedNamespaceError";}namespace};var $=/^(?<domain>.+) wants you to sign in with your blockchain account:$/,R=/^(?<key>[A-Za-z ]+): (?<value>.+)$/,b=/^- (?<resource>.+)$/;function v(e){let t=e.split(`
|
|
3
|
+
`);if(t.length<5)throw new u("Message is too short to be a valid CAIP-122 message.");let n=t[0]?.match($);if(!n?.groups?.domain)throw new u('Invalid CAIP-122 header line. Expected: "{domain} wants you to sign in with your blockchain account:"');let c=n.groups.domain,l=t[1];if(!l)throw new u("Missing address on line 2.");if(t[2]!=="")throw new u("Expected blank line after address (line 3).");let r=3,g;if(t[r]&&!R.test(t[r])){if(g=t[r],r++,t[r]!=="")throw new u("Expected blank line after statement.");r++;}let s={},p=[],i=false;for(;r<t.length;){let a=t[r];if(a===void 0){r++;continue}if(a==="Resources:"){i=true,r++;continue}if(i){let o=a.match(b);if(o?.groups?.resource){p.push(o.groups.resource),r++;continue}i=false;}let f=a.match(R);f?.groups?.key&&f.groups.value&&(s[f.groups.key]=f.groups.value),r++;}let h=["URI","Version","Chain ID","Nonce","Issued At"];for(let a of h)if(!s[a])throw new u(`Missing required field in CAIP-122 message: "${a}"`);return {domain:c,address:l,statement:g,uri:s.URI,version:s.Version,chainId:s["Chain ID"],nonce:s.Nonce,issuedAt:s["Issued At"],expirationTime:s["Expiration Time"],notBefore:s["Not Before"],requestId:s["Request ID"],resources:p.length>0?p:void 0}}var _=/^https?:\/\/.+/,C=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/,M=/^[a-z0-9]+:[a-zA-Z0-9-]+:.+$/,P=/^[a-z0-9]+:[a-zA-Z0-9-]+$/;function N(e){if(!e||e.trim().length===0)return "domain must be a non-empty string.";if(e.includes(`
|
|
4
|
+
`))return "domain must not contain newline characters."}function X(e){if(!M.test(e))return `address must be CAIP-10 compliant (namespace:chainRef:address). Got: "${e}"`}function D(e){if(!_.test(e))return `uri must be a valid RFC 3986 URI starting with http(s)://. Got: "${e}"`}function G(e){if(!P.test(e))return `chainId must be a valid CAIP-2 identifier (namespace:reference). Got: "${e}"`}function O(e){if(!e||e.length<8)return `nonce must be at least 8 characters long. Got length: ${e?.length??0}`;if(!/^[a-zA-Z0-9]+$/.test(e))return `nonce must be alphanumeric. Got: "${e}"`}function S(e,t){if(!C.test(e))return `${t} must be a valid ISO 8601 datetime string. Got: "${e}"`}function T(e){let t=new Date(e);if(isNaN(t.getTime()))return `expirationTime is not a valid date: "${e}"`;if(t<new Date)return `Message has expired. expirationTime was: ${e}`}function V(e,t){let n=[],c=N(e.domain);c&&n.push(c);let l=X(e.address);l&&n.push(l);let r=D(e.uri);r&&n.push(r),e.version!=="1"&&n.push(`version must be "1". Got: "${e.version}"`);let g=G(e.chainId);g&&n.push(g);let s=O(e.nonce);s&&n.push(s);let p=S(e.issuedAt,"issuedAt");if(p&&n.push(p),e.expirationTime){let i=S(e.expirationTime,"expirationTime");if(i)n.push(i);else if(!t?.skipExpiration){let h=T(e.expirationTime);h&&n.push(h);}}if(e.notBefore){let i=S(e.notBefore,"notBefore");i&&n.push(i);}return e.statement&&e.statement.includes(`
|
|
5
|
+
`)&&n.push("statement must not contain newline characters."),{valid:n.length===0,errors:n}}function U(){let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}exports.SiwxError=d;exports.SiwxExpiredSessionError=E;exports.SiwxNonceReplayError=w;exports.SiwxParseError=u;exports.SiwxUnsupportedNamespaceError=I;exports.SiwxValidationError=m;exports.SiwxVerificationError=x;exports.buildMessage=A;exports.generateNonce=U;exports.parseMessage=v;exports.validateMessage=V;
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
function A(e){let{domain:t,address:n,statement:c,uri:l,version:r,chainId:g,nonce:s,issuedAt:p,expirationTime:i,notBefore:h,requestId:a,resources:f}=e,o=[`${t} wants you to sign in with your blockchain account:`,n,""];if(c&&o.push(c,""),o.push(`URI: ${l}`,`Version: ${r}`,`Chain ID: ${g}`,`Nonce: ${s}`,`Issued At: ${p}`),i&&o.push(`Expiration Time: ${i}`),h&&o.push(`Not Before: ${h}`),a&&o.push(`Request ID: ${a}`),f&&f.length>0){o.push("Resources:");for(let y of f)o.push(`- ${y}`);}return o.join(`
|
|
2
|
+
`)}var d=class extends Error{constructor(n,c="SIWX_ERROR"){super(n);this.code=c;this.name="SiwxError",Object.setPrototypeOf(this,new.target.prototype);}code},u=class extends d{constructor(t){super(t,"SIWX_PARSE_ERROR"),this.name="SiwxParseError";}},m=class extends d{constructor(n){super(`CAIP-122 message validation failed: ${n.join(", ")}`,"SIWX_VALIDATION_ERROR");this.errors=n;this.name="SiwxValidationError";}errors},x=class extends d{constructor(t){super(t,"SIWX_VERIFICATION_ERROR"),this.name="SiwxVerificationError";}},E=class extends d{constructor(n){super(`SIWX session expired at ${n}`,"SIWX_EXPIRED_SESSION");this.expirationTime=n;this.name="SiwxExpiredSessionError";}expirationTime},w=class extends d{constructor(n){super(`Nonce has already been used: ${n}`,"SIWX_NONCE_REPLAY");this.nonce=n;this.name="SiwxNonceReplayError";}nonce},I=class extends d{constructor(n){super(`Unsupported CAIP-2 namespace: "${n}". Supported: eip155, solana`,"SIWX_UNSUPPORTED_NAMESPACE");this.namespace=n;this.name="SiwxUnsupportedNamespaceError";}namespace};var $=/^(?<domain>.+) wants you to sign in with your blockchain account:$/,R=/^(?<key>[A-Za-z ]+): (?<value>.+)$/,b=/^- (?<resource>.+)$/;function v(e){let t=e.split(`
|
|
3
|
+
`);if(t.length<5)throw new u("Message is too short to be a valid CAIP-122 message.");let n=t[0]?.match($);if(!n?.groups?.domain)throw new u('Invalid CAIP-122 header line. Expected: "{domain} wants you to sign in with your blockchain account:"');let c=n.groups.domain,l=t[1];if(!l)throw new u("Missing address on line 2.");if(t[2]!=="")throw new u("Expected blank line after address (line 3).");let r=3,g;if(t[r]&&!R.test(t[r])){if(g=t[r],r++,t[r]!=="")throw new u("Expected blank line after statement.");r++;}let s={},p=[],i=false;for(;r<t.length;){let a=t[r];if(a===void 0){r++;continue}if(a==="Resources:"){i=true,r++;continue}if(i){let o=a.match(b);if(o?.groups?.resource){p.push(o.groups.resource),r++;continue}i=false;}let f=a.match(R);f?.groups?.key&&f.groups.value&&(s[f.groups.key]=f.groups.value),r++;}let h=["URI","Version","Chain ID","Nonce","Issued At"];for(let a of h)if(!s[a])throw new u(`Missing required field in CAIP-122 message: "${a}"`);return {domain:c,address:l,statement:g,uri:s.URI,version:s.Version,chainId:s["Chain ID"],nonce:s.Nonce,issuedAt:s["Issued At"],expirationTime:s["Expiration Time"],notBefore:s["Not Before"],requestId:s["Request ID"],resources:p.length>0?p:void 0}}var _=/^https?:\/\/.+/,C=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/,M=/^[a-z0-9]+:[a-zA-Z0-9-]+:.+$/,P=/^[a-z0-9]+:[a-zA-Z0-9-]+$/;function N(e){if(!e||e.trim().length===0)return "domain must be a non-empty string.";if(e.includes(`
|
|
4
|
+
`))return "domain must not contain newline characters."}function X(e){if(!M.test(e))return `address must be CAIP-10 compliant (namespace:chainRef:address). Got: "${e}"`}function D(e){if(!_.test(e))return `uri must be a valid RFC 3986 URI starting with http(s)://. Got: "${e}"`}function G(e){if(!P.test(e))return `chainId must be a valid CAIP-2 identifier (namespace:reference). Got: "${e}"`}function O(e){if(!e||e.length<8)return `nonce must be at least 8 characters long. Got length: ${e?.length??0}`;if(!/^[a-zA-Z0-9]+$/.test(e))return `nonce must be alphanumeric. Got: "${e}"`}function S(e,t){if(!C.test(e))return `${t} must be a valid ISO 8601 datetime string. Got: "${e}"`}function T(e){let t=new Date(e);if(isNaN(t.getTime()))return `expirationTime is not a valid date: "${e}"`;if(t<new Date)return `Message has expired. expirationTime was: ${e}`}function V(e,t){let n=[],c=N(e.domain);c&&n.push(c);let l=X(e.address);l&&n.push(l);let r=D(e.uri);r&&n.push(r),e.version!=="1"&&n.push(`version must be "1". Got: "${e.version}"`);let g=G(e.chainId);g&&n.push(g);let s=O(e.nonce);s&&n.push(s);let p=S(e.issuedAt,"issuedAt");if(p&&n.push(p),e.expirationTime){let i=S(e.expirationTime,"expirationTime");if(i)n.push(i);else if(!t?.skipExpiration){let h=T(e.expirationTime);h&&n.push(h);}}if(e.notBefore){let i=S(e.notBefore,"notBefore");i&&n.push(i);}return e.statement&&e.statement.includes(`
|
|
5
|
+
`)&&n.push("statement must not contain newline characters."),{valid:n.length===0,errors:n}}function U(){let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}export{d as SiwxError,E as SiwxExpiredSessionError,w as SiwxNonceReplayError,u as SiwxParseError,I as SiwxUnsupportedNamespaceError,m as SiwxValidationError,x as SiwxVerificationError,A as buildMessage,U as generateNonce,v as parseMessage,V as validateMessage};
|
package/package.json
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@tuwaio/siwx-core",
|
|
3
|
+
"version": "1.0.0-fix-initialize-alpha.1.f397697",
|
|
4
|
+
"private": false,
|
|
5
|
+
"author": "Oleksandr Tkach",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"description": "Chain-agnostic CAIP-122 message builder, parser, and validator. The L1 foundational engine of the @tuwaio/siwx ecosystem.",
|
|
8
|
+
"main": "./dist/index.js",
|
|
9
|
+
"module": "./dist/index.mjs",
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"publishConfig": {
|
|
12
|
+
"access": "public"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist",
|
|
16
|
+
"socket.json"
|
|
17
|
+
],
|
|
18
|
+
"keywords": [
|
|
19
|
+
"web3",
|
|
20
|
+
"typescript",
|
|
21
|
+
"caip-122",
|
|
22
|
+
"siwe",
|
|
23
|
+
"sign-in-with-x",
|
|
24
|
+
"authentication",
|
|
25
|
+
"headless",
|
|
26
|
+
"chain-agnostic",
|
|
27
|
+
"tuwa"
|
|
28
|
+
],
|
|
29
|
+
"repository": {
|
|
30
|
+
"type": "git",
|
|
31
|
+
"url": "git+https://github.com/TuwaIO/siwx.git",
|
|
32
|
+
"directory": "packages/siwx-core"
|
|
33
|
+
},
|
|
34
|
+
"homepage": "https://github.com/TuwaIO/siwx",
|
|
35
|
+
"bugs": {
|
|
36
|
+
"url": "https://github.com/TuwaIO/siwx/issues"
|
|
37
|
+
},
|
|
38
|
+
"contributors": [
|
|
39
|
+
{
|
|
40
|
+
"name": "Oleksandr Tkach",
|
|
41
|
+
"url": "https://github.com/Argeare5"
|
|
42
|
+
}
|
|
43
|
+
],
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"tsup": "^8.5.1",
|
|
46
|
+
"typescript": "^6.0.3"
|
|
47
|
+
},
|
|
48
|
+
"scripts": {
|
|
49
|
+
"start": "tsup src/index.ts --watch",
|
|
50
|
+
"build": "tsup",
|
|
51
|
+
"test": "vitest run",
|
|
52
|
+
"test:coverage": "vitest run --coverage"
|
|
53
|
+
}
|
|
54
|
+
}
|
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
|
+
}
|