@tuwaio/siwx-core 0.3.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +65 -112
- package/dist/index.d.mts +217 -116
- package/dist/index.d.ts +217 -116
- package/dist/index.js +5 -5
- package/dist/index.mjs +5 -5
- package/package.json +13 -10
package/README.md
CHANGED
|
@@ -1,24 +1,23 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @tuwaio/siwx-core
|
|
2
2
|
|
|
3
3
|
[](https://www.npmjs.com/package/@tuwaio/siwx-core)
|
|
4
|
-
[](
|
|
5
|
-
[](https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-122.md)
|
|
4
|
+
[](https://github.com/TuwaIO/siwx/blob/main/packages/siwx-core/LICENSE)
|
|
6
5
|
|
|
7
|
-
|
|
6
|
+
`@tuwaio/siwx-core` is the Layer 1 (L1) package of **SIWX** (Sign-In With X), the authentication project of TUWA Stage 1 ("Core Auth & Primitives", next to Orbit Utils). It implements the [CAIP-122](https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-122.md) message format: it builds, parses and validates chain-agnostic sign-in messages for EVM (`eip155`) and Solana accounts, and defines the types and errors that the SIWX L2 packages share.
|
|
7
|
+
|
|
8
|
+
The package has **zero runtime dependencies** and imports no Web3 SDK. It runs in browsers, Node.js 20+ and edge runtimes; only `generateNonce` needs the Web Crypto API.
|
|
8
9
|
|
|
9
10
|
---
|
|
10
11
|
|
|
11
12
|
## 🏛️ Core Capabilities
|
|
12
13
|
|
|
13
|
-
|
|
14
|
+
- **Message format:** `buildMessage` formats CAIP-122 fields into the text the wallet signs (the EIP-4361 layout used by CAIP-122); `parseMessage` reads the text back and throws `SiwxParseError` when it is malformed.
|
|
15
|
+
- **Validation:** `validateMessage` checks field formats (CAIP-10 address, CAIP-2 chain ID, `http(s)` URI, nonce, ISO 8601 timestamps) and expiration, and reports every failure at once.
|
|
16
|
+
- **Verification policy:** `validatePolicy` and `SiwxVerificationPolicy` bind a message to your domain, URI, allowed chains and time windows (`issuedAt` age, `notBefore`, maximum lifetime, clock skew).
|
|
17
|
+
- **Session matching:** `isSessionMatchingTarget` checks that a session belongs to a given address and chain, case-insensitively for EVM and case-sensitively for Solana.
|
|
18
|
+
- **Nonces and errors:** `generateNonce` returns 32 random hex characters; `SiwxError` and its subclasses carry machine-readable `code`s.
|
|
14
19
|
|
|
15
|
-
|
|
16
|
-
- **Parse**: Parse raw CAIP-122 message strings into typed objects.
|
|
17
|
-
- **Validate Fields**: Validate format, CAIP-10 addresses, CAIP-2 chain identifiers, nonces, ISO 8601 timestamps, and expiration.
|
|
18
|
-
- **Enforce Security Policies**: Validate messages against strict domain, URI, allowed chain, max age, and max session lifetime policies via `validatePolicy()`.
|
|
19
|
-
- **Match Sessions**: Compare active sessions with target addresses and chains handling EVM/Solana casing and CAIP-10 formats.
|
|
20
|
-
- **Generate Nonces**: Cryptographically secure 32-character hex nonce generator using Web Crypto API.
|
|
21
|
-
- **Typed Error Hierarchy**: Comprehensive set of typed errors with machine-readable error codes.
|
|
20
|
+
Signatures are verified by the chain packages ([`@tuwaio/siwx-evm`](https://siwx.docs.tuwa.io/packages/siwx-evm), [`@tuwaio/siwx-solana`](https://siwx.docs.tuwa.io/packages/siwx-solana)) and on the server by [`@tuwaio/siwx-server`](https://siwx.docs.tuwa.io/packages/siwx-server).
|
|
22
21
|
|
|
23
22
|
---
|
|
24
23
|
|
|
@@ -30,14 +29,12 @@ pnpm add @tuwaio/siwx-core
|
|
|
30
29
|
|
|
31
30
|
---
|
|
32
31
|
|
|
33
|
-
## 🚀
|
|
34
|
-
|
|
35
|
-
### `buildMessage(fields: SiwxMessageFields): string`
|
|
32
|
+
## 🚀 Usage
|
|
36
33
|
|
|
37
|
-
|
|
34
|
+
### Building and parsing a message
|
|
38
35
|
|
|
39
|
-
```
|
|
40
|
-
import { buildMessage, generateNonce } from '@tuwaio/siwx-core';
|
|
36
|
+
```typescript
|
|
37
|
+
import { buildMessage, generateNonce, parseMessage } from '@tuwaio/siwx-core';
|
|
41
38
|
|
|
42
39
|
const message = buildMessage({
|
|
43
40
|
domain: 'app.tuwa.io',
|
|
@@ -48,138 +45,94 @@ const message = buildMessage({
|
|
|
48
45
|
chainId: 'eip155:1',
|
|
49
46
|
nonce: generateNonce(),
|
|
50
47
|
issuedAt: new Date().toISOString(),
|
|
51
|
-
expirationTime: new Date(Date.now() +
|
|
48
|
+
expirationTime: new Date(Date.now() + 10 * 60 * 1000).toISOString(),
|
|
52
49
|
});
|
|
50
|
+
|
|
51
|
+
// Throws SiwxParseError if the text is not a CAIP-122 message.
|
|
52
|
+
const fields = parseMessage(message);
|
|
53
53
|
```
|
|
54
54
|
|
|
55
|
-
|
|
55
|
+
The message the wallet shows and signs:
|
|
56
56
|
|
|
57
|
-
|
|
57
|
+
```text
|
|
58
|
+
app.tuwa.io wants you to sign in with your blockchain account:
|
|
59
|
+
eip155:1:0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B
|
|
58
60
|
|
|
59
|
-
|
|
60
|
-
import { parseMessage } from '@tuwaio/siwx-core';
|
|
61
|
+
Sign in to TUWA.
|
|
61
62
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
63
|
+
URI: https://app.tuwa.io
|
|
64
|
+
Version: 1
|
|
65
|
+
Chain ID: eip155:1
|
|
66
|
+
Nonce: 3f9c1e2a7b4d8f6051c2e9a0d7b3f418
|
|
67
|
+
Issued At: 2026-09-26T10:00:00.000Z
|
|
68
|
+
Expiration Time: 2026-09-26T10:10:00.000Z
|
|
66
69
|
```
|
|
67
70
|
|
|
68
|
-
|
|
71
|
+
`buildMessage` does not validate its input; run `validateMessage` on untrusted fields.
|
|
69
72
|
|
|
70
|
-
|
|
73
|
+
### Validating fields and a policy
|
|
71
74
|
|
|
72
|
-
```
|
|
73
|
-
import { validateMessage } from '@tuwaio/siwx-core';
|
|
75
|
+
```typescript
|
|
76
|
+
import { parseMessage, validateMessage } from '@tuwaio/siwx-core';
|
|
74
77
|
|
|
75
|
-
const
|
|
78
|
+
declare const message: string;
|
|
79
|
+
|
|
80
|
+
const result = validateMessage(parseMessage(message), {
|
|
76
81
|
policy: {
|
|
77
82
|
expectedDomain: 'app.tuwa.io',
|
|
78
83
|
expectedUri: 'https://app.tuwa.io',
|
|
79
|
-
allowedChainIds: ['eip155:1', 'solana:
|
|
84
|
+
allowedChainIds: ['eip155:1', 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp'],
|
|
80
85
|
requireExpirationTime: true,
|
|
81
86
|
maxIssuedAtAgeSeconds: 300,
|
|
82
|
-
maxSessionLifetimeSeconds:
|
|
87
|
+
maxSessionLifetimeSeconds: 24 * 60 * 60,
|
|
83
88
|
},
|
|
84
89
|
});
|
|
85
90
|
|
|
86
91
|
if (!result.valid) {
|
|
87
|
-
console.error(
|
|
92
|
+
console.error(result.errors); // one human-readable string per failed check
|
|
88
93
|
}
|
|
89
94
|
```
|
|
90
95
|
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
import { validatePolicy } from '@tuwaio/siwx-core';
|
|
97
|
-
|
|
98
|
-
const errors = validatePolicy(fields, {
|
|
99
|
-
expectedDomain: ['app.tuwa.io', 'auth.tuwa.io'],
|
|
100
|
-
allowedChainIds: ['eip155:1'],
|
|
101
|
-
maxIssuedAtAgeSeconds: 300,
|
|
102
|
-
});
|
|
103
|
-
```
|
|
104
|
-
|
|
105
|
-
### `isSessionMatchingTarget(session: SiwxSessionLike | null | undefined, targetAddress: string, targetChainId?: string | number): boolean`
|
|
96
|
+
- `validateMessage` checks formats and timing only. It does not verify the signature.
|
|
97
|
+
- Policy rules run only for the fields you set; `maxIssuedAtAgeSeconds` has no default. `clockSkewSeconds` defaults to 60 seconds.
|
|
98
|
+
- Two timing rules always apply, even without a policy: `issuedAt` must not be in the future and `notBefore` must have been reached (turn the latter off with `enforceNotBefore: false`).
|
|
99
|
+
- `allowedChainIds` entries are full CAIP-2 IDs matched exactly: `eip155:1` does not allow `solana:1`, and a bare `1` matches nothing.
|
|
100
|
+
- `validatePolicy(fields, policy, now?)` runs the policy rules alone and returns the list of violations.
|
|
106
101
|
|
|
107
|
-
|
|
102
|
+
### Matching a session to a wallet
|
|
108
103
|
|
|
109
|
-
```
|
|
104
|
+
```typescript
|
|
110
105
|
import { isSessionMatchingTarget } from '@tuwaio/siwx-core';
|
|
111
106
|
|
|
112
|
-
const
|
|
113
|
-
```
|
|
114
|
-
|
|
115
|
-
### `generateNonce(): string`
|
|
107
|
+
const session = { address: 'eip155:1:0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B', chainId: 'eip155:1' };
|
|
116
108
|
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
import { generateNonce } from '@tuwaio/siwx-core';
|
|
121
|
-
|
|
122
|
-
const nonce = generateNonce(); // e.g. "9a2f64c8d1b3e570..."
|
|
109
|
+
isSessionMatchingTarget(session, '0xab5801a7d398351b8be11c439e05c5b3259aec9b'); // true: EVM addresses ignore case
|
|
110
|
+
isSessionMatchingTarget(session, 'eip155:1:0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B', 'eip155:1'); // true
|
|
111
|
+
isSessionMatchingTarget(session, '0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B', 10); // false: other chain
|
|
123
112
|
```
|
|
124
113
|
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
## 🛡️ `SiwxVerificationPolicy` Interface
|
|
128
|
-
|
|
129
|
-
```ts
|
|
130
|
-
export interface SiwxVerificationPolicy {
|
|
131
|
-
/** Expected domain(s) requesting sign-in (e.g. "tuwa.io" or ["tuwa.io", "auth.tuwa.io"]). */
|
|
132
|
-
expectedDomain?: string | string[];
|
|
133
|
-
|
|
134
|
-
/** Expected RFC 3986 URI(s) subject of sign-in (e.g. "https://tuwa.io"). */
|
|
135
|
-
expectedUri?: string | string[];
|
|
114
|
+
### Handling errors
|
|
136
115
|
|
|
137
|
-
|
|
138
|
-
|
|
116
|
+
```typescript
|
|
117
|
+
import { parseMessage, SiwxParseError } from '@tuwaio/siwx-core';
|
|
139
118
|
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
/** Maximum session lifetime in seconds (expirationTime - issuedAt). */
|
|
147
|
-
maxSessionLifetimeSeconds?: number;
|
|
148
|
-
|
|
149
|
-
/** Allowed clock skew in seconds (default 60s). */
|
|
150
|
-
clockSkewSeconds?: number;
|
|
151
|
-
|
|
152
|
-
/** Whether to enforce notBefore timestamp (default true). */
|
|
153
|
-
enforceNotBefore?: boolean;
|
|
119
|
+
try {
|
|
120
|
+
parseMessage('not a CAIP-122 message');
|
|
121
|
+
} catch (error) {
|
|
122
|
+
if (error instanceof SiwxParseError) {
|
|
123
|
+
console.error(error.code, error.message); // "SIWX_PARSE_ERROR", "Message is too short to be a valid CAIP-122 message."
|
|
124
|
+
}
|
|
154
125
|
}
|
|
155
126
|
```
|
|
156
127
|
|
|
128
|
+
`parseMessage` and `generateNonce` are the only functions of this package that throw. The verifiers of the L2 packages return `{ success: false, error }` instead of throwing. The policy error classes (`SiwxPolicyViolationError` and its subclasses) are never thrown by SIWX; they are available for your own checks.
|
|
129
|
+
|
|
157
130
|
---
|
|
158
131
|
|
|
159
|
-
##
|
|
160
|
-
|
|
161
|
-
All errors extend `SiwxError` and carry a machine-readable `code` property.
|
|
162
|
-
|
|
163
|
-
| Class | Code | Description |
|
|
164
|
-
| ---------------------------------- | -------------------------------- | --------------------------------------------- |
|
|
165
|
-
| `SiwxError` | `SIWX_ERROR` | Base class for all SIWX errors |
|
|
166
|
-
| `SiwxParseError` | `SIWX_PARSE_ERROR` | Malformed CAIP-122 message string |
|
|
167
|
-
| `SiwxValidationError` | `SIWX_VALIDATION_ERROR` | Field validation failed |
|
|
168
|
-
| `SiwxVerificationError` | `SIWX_VERIFICATION_ERROR` | Cryptographic signature mismatch |
|
|
169
|
-
| `SiwxExpiredSessionError` | `SIWX_EXPIRED_SESSION` | Session has expired |
|
|
170
|
-
| `SiwxNonceReplayError` | `SIWX_NONCE_REPLAY` | Nonce already consumed |
|
|
171
|
-
| `SiwxUnsupportedNamespaceError` | `SIWX_UNSUPPORTED_NAMESPACE` | Unsupported CAIP-2 namespace |
|
|
172
|
-
| `SiwxPolicyViolationError` | `SIWX_POLICY_VIOLATION` | Generic policy rule violated |
|
|
173
|
-
| `SiwxDomainMismatchError` | `SIWX_DOMAIN_MISMATCH` | Message domain does not match expected domain |
|
|
174
|
-
| `SiwxUriMismatchError` | `SIWX_URI_MISMATCH` | Message URI does not match expected URI |
|
|
175
|
-
| `SiwxChainNotAllowedError` | `SIWX_CHAIN_NOT_ALLOWED` | Chain ID not present in allowed list |
|
|
176
|
-
| `SiwxIssuedAtStaleError` | `SIWX_ISSUED_AT_STALE` | `issuedAt` is older than max allowed age |
|
|
177
|
-
| `SiwxIssuedAtFutureError` | `SIWX_ISSUED_AT_FUTURE` | `issuedAt` is in the future beyond clock skew |
|
|
178
|
-
| `SiwxNotBeforeError` | `SIWX_NOT_BEFORE` | `notBefore` timestamp has not been reached |
|
|
179
|
-
| `SiwxSessionLifetimeExceededError` | `SIWX_SESSION_LIFETIME_EXCEEDED` | Session duration exceeds maximum lifetime |
|
|
132
|
+
## 📚 API Reference
|
|
180
133
|
|
|
181
|
-
|
|
134
|
+
Every export, with signatures and types generated from the source, is documented at **[siwx.docs.tuwa.io/packages/siwx-core](https://siwx.docs.tuwa.io/packages/siwx-core)**.
|
|
182
135
|
|
|
183
136
|
## 📄 License
|
|
184
137
|
|
|
185
|
-
Licensed under the **Apache-2.0 License**. See the [LICENSE](
|
|
138
|
+
Licensed under the **Apache-2.0 License**. See the [LICENSE](https://github.com/TuwaIO/siwx/blob/main/packages/siwx-core/LICENSE) file for details.
|