@tuwaio/siwx-core 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,19 +4,21 @@
4
4
  [![License](https://img.shields.io/npm/l/@tuwaio/siwx-core.svg)](./LICENSE)
5
5
  [![CAIP-122](https://img.shields.io/badge/standard-CAIP--122-purple.svg)](https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-122.md)
6
6
 
7
- > Chain-agnostic CAIP-122 message building, parsing, and validation. The L1 foundational engine of the `@tuwaio/siwx` ecosystem. **Zero dependencies.**
7
+ > Chain-agnostic CAIP-122 message building, parsing, policy validation, and error definitions. The L1 foundational engine of the `@tuwaio/siwx` ecosystem. **Zero dependencies.**
8
8
 
9
9
  ---
10
10
 
11
11
  ## 🏛️ Core Capabilities
12
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.
13
+ This package is the **L1 core foundation** implementing the [CAIP-122](https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-122.md) standard.
14
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.
15
+ - **Build**: Format compliant CAIP-122 messages from structured fields.
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
22
 
21
23
  ---
22
24
 
@@ -28,7 +30,7 @@ pnpm add @tuwaio/siwx-core
28
30
 
29
31
  ---
30
32
 
31
- ## 🚀 API & Module Architecture
33
+ ## 🚀 API Reference
32
34
 
33
35
  ### `buildMessage(fields: SiwxMessageFields): string`
34
36
 
@@ -46,6 +48,7 @@ const message = buildMessage({
46
48
  chainId: 'eip155:1',
47
49
  nonce: generateNonce(),
48
50
  issuedAt: new Date().toISOString(),
51
+ expirationTime: new Date(Date.now() + 1000 * 60 * 30).toISOString(),
49
52
  });
50
53
  ```
51
54
 
@@ -59,56 +62,121 @@ import { parseMessage } from '@tuwaio/siwx-core';
59
62
  const parsed = parseMessage(rawMessage);
60
63
  console.log(parsed.address); // "eip155:1:0xAb5801..."
61
64
  console.log(parsed.chainId); // "eip155:1"
65
+ console.log(parsed.nonce); // "a4f3b2c1..."
62
66
  ```
63
67
 
64
- ### `validateMessage(fields: SiwxMessageFields, options?: { skipExpiration?: boolean }): SiwxValidationResult`
68
+ ### `validateMessage(fields: SiwxMessageFields, options?: ValidateMessageOptions): SiwxValidationResult`
65
69
 
66
- Validates all fields (domain, CAIP-10 address, URI, version, CAIP-2 chainId, nonce, ISO dates, expiration). Returns `{ valid: boolean, errors: string[] }`.
70
+ Validates all fields and optionally enforces a `SiwxVerificationPolicy`. Returns `{ valid: boolean, errors: string[] }`.
67
71
 
68
72
  ```ts
69
73
  import { validateMessage } from '@tuwaio/siwx-core';
70
74
 
71
- const { valid, errors } = validateMessage(parsedMessage);
72
- if (!valid) console.error(errors);
75
+ const result = validateMessage(parsedMessage, {
76
+ policy: {
77
+ expectedDomain: 'app.tuwa.io',
78
+ expectedUri: 'https://app.tuwa.io',
79
+ allowedChainIds: ['eip155:1', 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpK'],
80
+ requireExpirationTime: true,
81
+ maxIssuedAtAgeSeconds: 300,
82
+ maxSessionLifetimeSeconds: 1800,
83
+ },
84
+ });
85
+
86
+ if (!result.valid) {
87
+ console.error('Validation errors:', result.errors);
88
+ }
89
+ ```
90
+
91
+ ### `validatePolicy(fields: SiwxMessageFields, policy?: SiwxVerificationPolicy, now?: Date): string[]`
92
+
93
+ Dedicated helper for validating message fields against a verification policy.
73
94
 
74
- // Optionally skip expiration checking (useful for custom server flows)
75
- const { valid: isValidExpired } = validateMessage(parsedMessage, { skipExpiration: true });
95
+ ```ts
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
+ });
76
103
  ```
77
104
 
78
105
  ### `isSessionMatchingTarget(session: SiwxSessionLike | null | undefined, targetAddress: string, targetChainId?: string | number): boolean`
79
106
 
80
- Validates whether a SIWX session matches a target wallet address and optional chainId. Handles EVM case-insensitivity, Solana case-sensitivity, and CAIP-10/CAIP-2 normalization.
107
+ Validates whether a SIWX session matches a target wallet address and optional chainId. Handles EVM case-insensitivity, Solana case-sensitivity, and CAIP-10 / CAIP-2 normalization.
81
108
 
82
109
  ```ts
83
110
  import { isSessionMatchingTarget } from '@tuwaio/siwx-core';
84
111
 
85
- const isMatch = isSessionMatchingTarget(session, '0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B', 1);
86
- // Handles cross-chain namespace checks (EVM vs Solana) and optional chainId matching
112
+ const isMatch = isSessionMatchingTarget(session, '0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B', 'eip155:1');
87
113
  ```
88
114
 
89
115
  ### `generateNonce(): string`
90
116
 
91
- Generates a 32-character cryptographically secure hex nonce using the Web Crypto API (`globalThis.crypto.getRandomValues`). Native in Node 20+, browsers, and Edge runtimes.
117
+ Generates a 32-character cryptographically secure hex nonce using `globalThis.crypto.getRandomValues`.
92
118
 
93
119
  ```ts
94
120
  import { generateNonce } from '@tuwaio/siwx-core';
95
- const nonce = generateNonce(); // "a4f3b2c1d0e5f6..."
121
+
122
+ const nonce = generateNonce(); // e.g. "9a2f64c8d1b3e570..."
96
123
  ```
97
124
 
98
125
  ---
99
126
 
100
- ## Error Classes
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[];
136
+
137
+ /** List of allowed CAIP-2 chain IDs (e.g. ["eip155:1", "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpK"]). */
138
+ allowedChainIds?: string[];
139
+
140
+ /** Whether the message MUST include an expirationTime. */
141
+ requireExpirationTime?: boolean;
142
+
143
+ /** Maximum allowed age of issuedAt in seconds (default 300s). */
144
+ maxIssuedAtAgeSeconds?: number;
101
145
 
102
- All errors extend `SiwxError` with a typed `code` property.
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;
154
+ }
155
+ ```
156
+
157
+ ---
103
158
 
104
- | Class | Code | Description |
105
- | ------------------------------- | ---------------------------- | -------------------------------------- |
106
- | `SiwxParseError` | `SIWX_PARSE_ERROR` | Malformed CAIP-122 message string |
107
- | `SiwxValidationError` | `SIWX_VALIDATION_ERROR` | One or more field validations failed |
108
- | `SiwxVerificationError` | `SIWX_VERIFICATION_ERROR` | Signature mismatch or recovery failure |
109
- | `SiwxExpiredSessionError` | `SIWX_EXPIRED_SESSION` | Session past its `expirationTime` |
110
- | `SiwxNonceReplayError` | `SIWX_NONCE_REPLAY` | Nonce already consumed |
111
- | `SiwxUnsupportedNamespaceError` | `SIWX_UNSUPPORTED_NAMESPACE` | Chain namespace not supported |
159
+ ## 🛑 Typed Error Classes
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 |
112
180
 
113
181
  ---
114
182
 
package/dist/index.d.mts CHANGED
@@ -81,6 +81,63 @@ interface SiwxMessageFields {
81
81
  */
82
82
  resources?: string[];
83
83
  }
84
+ /**
85
+ * Policy parameters for server-side CAIP-122 message verification.
86
+ * Enforces strict security constraints including domain, URI, chain ID, and timing windows.
87
+ */
88
+ interface SiwxVerificationPolicy {
89
+ /**
90
+ * Expected domain(s) requesting sign-in (e.g. "tuwa.io" or ["tuwa.io", "staging.tuwa.io"]).
91
+ */
92
+ expectedDomain?: string | string[];
93
+ /**
94
+ * Expected RFC 3986 URI(s) subject of sign-in (e.g. "https://tuwa.io").
95
+ */
96
+ expectedUri?: string | string[];
97
+ /**
98
+ * List of allowed CAIP-2 chain IDs (e.g. ["eip155:1", "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpK"]).
99
+ */
100
+ allowedChainIds?: string[];
101
+ /**
102
+ * Whether the CAIP-122 message MUST include an `expirationTime`.
103
+ * Strongly recommended for zero-infrastructure stateless demo profiles.
104
+ */
105
+ requireExpirationTime?: boolean;
106
+ /**
107
+ * Maximum allowed age of the message's `issuedAt` in seconds.
108
+ * Prevents accepting stale sign-in messages.
109
+ * @default 300 (5 minutes)
110
+ */
111
+ maxIssuedAtAgeSeconds?: number;
112
+ /**
113
+ * Maximum allowed session lifetime in seconds (expirationTime - issuedAt).
114
+ */
115
+ maxSessionLifetimeSeconds?: number;
116
+ /**
117
+ * Allowed clock skew in seconds when validating timestamps.
118
+ * @default 60 (1 minute)
119
+ */
120
+ clockSkewSeconds?: number;
121
+ /**
122
+ * Whether to enforce the `notBefore` timestamp if present in the message.
123
+ * @default true
124
+ */
125
+ enforceNotBefore?: boolean;
126
+ }
127
+ /**
128
+ * Options for validating a CAIP-122 message object.
129
+ */
130
+ interface ValidateMessageOptions {
131
+ /**
132
+ * If true, skips the `expirationTime` validation check.
133
+ * Not recommended for production use.
134
+ */
135
+ skipExpiration?: boolean;
136
+ /**
137
+ * Optional verification policy to enforce on the message fields.
138
+ */
139
+ policy?: SiwxVerificationPolicy;
140
+ }
84
141
  /**
85
142
  * The result of a message validation operation.
86
143
  */
@@ -242,6 +299,71 @@ declare class SiwxUnsupportedNamespaceError extends SiwxError {
242
299
  */
243
300
  constructor(namespace: string);
244
301
  }
302
+ /**
303
+ * Thrown when a verification policy rule is violated.
304
+ */
305
+ declare class SiwxPolicyViolationError extends SiwxError {
306
+ /**
307
+ * @param message - Human-readable description of policy violation.
308
+ * @param code - Specific policy violation error code.
309
+ */
310
+ constructor(message: string, code?: string);
311
+ }
312
+ /**
313
+ * Thrown when the message domain does not match the expected domain policy.
314
+ */
315
+ declare class SiwxDomainMismatchError extends SiwxPolicyViolationError {
316
+ readonly expected: string | string[];
317
+ readonly received: string;
318
+ constructor(expected: string | string[], received: string);
319
+ }
320
+ /**
321
+ * Thrown when the message URI does not match the expected URI policy.
322
+ */
323
+ declare class SiwxUriMismatchError extends SiwxPolicyViolationError {
324
+ readonly expected: string | string[];
325
+ readonly received: string;
326
+ constructor(expected: string | string[], received: string);
327
+ }
328
+ /**
329
+ * Thrown when the message chain ID is not in the allowed list of chain IDs.
330
+ */
331
+ declare class SiwxChainNotAllowedError extends SiwxPolicyViolationError {
332
+ readonly allowedChainIds: string[];
333
+ readonly received: string;
334
+ constructor(allowedChainIds: string[], received: string);
335
+ }
336
+ /**
337
+ * Thrown when the message issuedAt timestamp is older than allowed by policy.
338
+ */
339
+ declare class SiwxIssuedAtStaleError extends SiwxPolicyViolationError {
340
+ readonly issuedAt: string;
341
+ readonly maxAgeSeconds: number;
342
+ constructor(issuedAt: string, maxAgeSeconds: number);
343
+ }
344
+ /**
345
+ * Thrown when the message issuedAt timestamp is in the future beyond acceptable clock skew.
346
+ */
347
+ declare class SiwxIssuedAtFutureError extends SiwxPolicyViolationError {
348
+ readonly issuedAt: string;
349
+ readonly clockSkewSeconds: number;
350
+ constructor(issuedAt: string, clockSkewSeconds: number);
351
+ }
352
+ /**
353
+ * Thrown when the message notBefore timestamp has not yet been reached.
354
+ */
355
+ declare class SiwxNotBeforeError extends SiwxPolicyViolationError {
356
+ readonly notBefore: string;
357
+ constructor(notBefore: string);
358
+ }
359
+ /**
360
+ * Thrown when the message session duration exceeds the max allowed session lifetime.
361
+ */
362
+ declare class SiwxSessionLifetimeExceededError extends SiwxPolicyViolationError {
363
+ readonly lifetimeSeconds: number;
364
+ readonly maxLifetimeSeconds: number;
365
+ constructor(lifetimeSeconds: number, maxLifetimeSeconds: number);
366
+ }
245
367
 
246
368
  /**
247
369
  * @fileoverview CAIP-122 message parser.
@@ -268,24 +390,34 @@ declare function parseMessage(message: string): ParsedSiwxMessage;
268
390
  * Provides individual validators and a composite `validateMessage` function.
269
391
  */
270
392
 
393
+ /**
394
+ * Validates a CAIP-122 message object against an optional verification policy.
395
+ *
396
+ * @param fields - The message fields to validate.
397
+ * @param policy - The verification policy to enforce.
398
+ * @param now - Reference date for timestamp validations (defaults to new Date()).
399
+ * @returns An array of policy violation error messages.
400
+ */
401
+ declare function validatePolicy(fields: SiwxMessageFields, policy?: SiwxVerificationPolicy, now?: Date): string[];
271
402
  /**
272
403
  * Validates all fields of a CAIP-122 message object.
273
404
  * Collects all errors and returns them together rather than failing on the first.
274
405
  *
275
406
  * @param fields - The message fields to validate.
407
+ * @param options - Optional validation options or verification policy.
276
408
  * @returns A `SiwxValidationResult` with `valid: true` or a list of errors.
277
409
  *
278
410
  * @example
279
411
  * ```ts
280
- * const result = validateMessage(parsedMessage);
412
+ * const result = validateMessage(parsedMessage, {
413
+ * policy: { expectedDomain: 'tuwa.io', requireExpirationTime: true },
414
+ * });
281
415
  * if (!result.valid) {
282
416
  * console.error(result.errors);
283
417
  * }
284
418
  * ```
285
419
  */
286
- declare function validateMessage(fields: SiwxMessageFields, options?: {
287
- skipExpiration?: boolean;
288
- }): SiwxValidationResult;
420
+ declare function validateMessage(fields: SiwxMessageFields, options?: ValidateMessageOptions): SiwxValidationResult;
289
421
  /**
290
422
  * Generates a cryptographically secure random nonce string suitable for CAIP-122 messages.
291
423
  * Produces a 16-byte random hex string (32 characters).
@@ -321,4 +453,4 @@ interface SiwxSessionLike {
321
453
  */
322
454
  declare function isSessionMatchingTarget(session: SiwxSessionLike | null | undefined, targetAddress: string, targetChainId?: string | number): boolean;
323
455
 
324
- export { type ParsedSiwxMessage, type SiwxAdapter, type SiwxChainId, type SiwxChainNamespace, SiwxError, SiwxExpiredSessionError, type SiwxMessageFields, SiwxNonceReplayError, SiwxParseError, type SiwxSessionLike, type SiwxStatus, SiwxUnsupportedNamespaceError, SiwxValidationError, type SiwxValidationResult, SiwxVerificationError, type SiwxVerifyPayload, type SiwxVerifyResult, buildMessage, generateNonce, isSessionMatchingTarget, parseMessage, validateMessage };
456
+ export { type ParsedSiwxMessage, type SiwxAdapter, type SiwxChainId, type SiwxChainNamespace, SiwxChainNotAllowedError, SiwxDomainMismatchError, SiwxError, SiwxExpiredSessionError, SiwxIssuedAtFutureError, SiwxIssuedAtStaleError, type SiwxMessageFields, SiwxNonceReplayError, SiwxNotBeforeError, SiwxParseError, SiwxPolicyViolationError, SiwxSessionLifetimeExceededError, type SiwxSessionLike, type SiwxStatus, SiwxUnsupportedNamespaceError, SiwxUriMismatchError, SiwxValidationError, type SiwxValidationResult, SiwxVerificationError, type SiwxVerificationPolicy, type SiwxVerifyPayload, type SiwxVerifyResult, type ValidateMessageOptions, buildMessage, generateNonce, isSessionMatchingTarget, parseMessage, validateMessage, validatePolicy };
package/dist/index.d.ts CHANGED
@@ -81,6 +81,63 @@ interface SiwxMessageFields {
81
81
  */
82
82
  resources?: string[];
83
83
  }
84
+ /**
85
+ * Policy parameters for server-side CAIP-122 message verification.
86
+ * Enforces strict security constraints including domain, URI, chain ID, and timing windows.
87
+ */
88
+ interface SiwxVerificationPolicy {
89
+ /**
90
+ * Expected domain(s) requesting sign-in (e.g. "tuwa.io" or ["tuwa.io", "staging.tuwa.io"]).
91
+ */
92
+ expectedDomain?: string | string[];
93
+ /**
94
+ * Expected RFC 3986 URI(s) subject of sign-in (e.g. "https://tuwa.io").
95
+ */
96
+ expectedUri?: string | string[];
97
+ /**
98
+ * List of allowed CAIP-2 chain IDs (e.g. ["eip155:1", "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpK"]).
99
+ */
100
+ allowedChainIds?: string[];
101
+ /**
102
+ * Whether the CAIP-122 message MUST include an `expirationTime`.
103
+ * Strongly recommended for zero-infrastructure stateless demo profiles.
104
+ */
105
+ requireExpirationTime?: boolean;
106
+ /**
107
+ * Maximum allowed age of the message's `issuedAt` in seconds.
108
+ * Prevents accepting stale sign-in messages.
109
+ * @default 300 (5 minutes)
110
+ */
111
+ maxIssuedAtAgeSeconds?: number;
112
+ /**
113
+ * Maximum allowed session lifetime in seconds (expirationTime - issuedAt).
114
+ */
115
+ maxSessionLifetimeSeconds?: number;
116
+ /**
117
+ * Allowed clock skew in seconds when validating timestamps.
118
+ * @default 60 (1 minute)
119
+ */
120
+ clockSkewSeconds?: number;
121
+ /**
122
+ * Whether to enforce the `notBefore` timestamp if present in the message.
123
+ * @default true
124
+ */
125
+ enforceNotBefore?: boolean;
126
+ }
127
+ /**
128
+ * Options for validating a CAIP-122 message object.
129
+ */
130
+ interface ValidateMessageOptions {
131
+ /**
132
+ * If true, skips the `expirationTime` validation check.
133
+ * Not recommended for production use.
134
+ */
135
+ skipExpiration?: boolean;
136
+ /**
137
+ * Optional verification policy to enforce on the message fields.
138
+ */
139
+ policy?: SiwxVerificationPolicy;
140
+ }
84
141
  /**
85
142
  * The result of a message validation operation.
86
143
  */
@@ -242,6 +299,71 @@ declare class SiwxUnsupportedNamespaceError extends SiwxError {
242
299
  */
243
300
  constructor(namespace: string);
244
301
  }
302
+ /**
303
+ * Thrown when a verification policy rule is violated.
304
+ */
305
+ declare class SiwxPolicyViolationError extends SiwxError {
306
+ /**
307
+ * @param message - Human-readable description of policy violation.
308
+ * @param code - Specific policy violation error code.
309
+ */
310
+ constructor(message: string, code?: string);
311
+ }
312
+ /**
313
+ * Thrown when the message domain does not match the expected domain policy.
314
+ */
315
+ declare class SiwxDomainMismatchError extends SiwxPolicyViolationError {
316
+ readonly expected: string | string[];
317
+ readonly received: string;
318
+ constructor(expected: string | string[], received: string);
319
+ }
320
+ /**
321
+ * Thrown when the message URI does not match the expected URI policy.
322
+ */
323
+ declare class SiwxUriMismatchError extends SiwxPolicyViolationError {
324
+ readonly expected: string | string[];
325
+ readonly received: string;
326
+ constructor(expected: string | string[], received: string);
327
+ }
328
+ /**
329
+ * Thrown when the message chain ID is not in the allowed list of chain IDs.
330
+ */
331
+ declare class SiwxChainNotAllowedError extends SiwxPolicyViolationError {
332
+ readonly allowedChainIds: string[];
333
+ readonly received: string;
334
+ constructor(allowedChainIds: string[], received: string);
335
+ }
336
+ /**
337
+ * Thrown when the message issuedAt timestamp is older than allowed by policy.
338
+ */
339
+ declare class SiwxIssuedAtStaleError extends SiwxPolicyViolationError {
340
+ readonly issuedAt: string;
341
+ readonly maxAgeSeconds: number;
342
+ constructor(issuedAt: string, maxAgeSeconds: number);
343
+ }
344
+ /**
345
+ * Thrown when the message issuedAt timestamp is in the future beyond acceptable clock skew.
346
+ */
347
+ declare class SiwxIssuedAtFutureError extends SiwxPolicyViolationError {
348
+ readonly issuedAt: string;
349
+ readonly clockSkewSeconds: number;
350
+ constructor(issuedAt: string, clockSkewSeconds: number);
351
+ }
352
+ /**
353
+ * Thrown when the message notBefore timestamp has not yet been reached.
354
+ */
355
+ declare class SiwxNotBeforeError extends SiwxPolicyViolationError {
356
+ readonly notBefore: string;
357
+ constructor(notBefore: string);
358
+ }
359
+ /**
360
+ * Thrown when the message session duration exceeds the max allowed session lifetime.
361
+ */
362
+ declare class SiwxSessionLifetimeExceededError extends SiwxPolicyViolationError {
363
+ readonly lifetimeSeconds: number;
364
+ readonly maxLifetimeSeconds: number;
365
+ constructor(lifetimeSeconds: number, maxLifetimeSeconds: number);
366
+ }
245
367
 
246
368
  /**
247
369
  * @fileoverview CAIP-122 message parser.
@@ -268,24 +390,34 @@ declare function parseMessage(message: string): ParsedSiwxMessage;
268
390
  * Provides individual validators and a composite `validateMessage` function.
269
391
  */
270
392
 
393
+ /**
394
+ * Validates a CAIP-122 message object against an optional verification policy.
395
+ *
396
+ * @param fields - The message fields to validate.
397
+ * @param policy - The verification policy to enforce.
398
+ * @param now - Reference date for timestamp validations (defaults to new Date()).
399
+ * @returns An array of policy violation error messages.
400
+ */
401
+ declare function validatePolicy(fields: SiwxMessageFields, policy?: SiwxVerificationPolicy, now?: Date): string[];
271
402
  /**
272
403
  * Validates all fields of a CAIP-122 message object.
273
404
  * Collects all errors and returns them together rather than failing on the first.
274
405
  *
275
406
  * @param fields - The message fields to validate.
407
+ * @param options - Optional validation options or verification policy.
276
408
  * @returns A `SiwxValidationResult` with `valid: true` or a list of errors.
277
409
  *
278
410
  * @example
279
411
  * ```ts
280
- * const result = validateMessage(parsedMessage);
412
+ * const result = validateMessage(parsedMessage, {
413
+ * policy: { expectedDomain: 'tuwa.io', requireExpirationTime: true },
414
+ * });
281
415
  * if (!result.valid) {
282
416
  * console.error(result.errors);
283
417
  * }
284
418
  * ```
285
419
  */
286
- declare function validateMessage(fields: SiwxMessageFields, options?: {
287
- skipExpiration?: boolean;
288
- }): SiwxValidationResult;
420
+ declare function validateMessage(fields: SiwxMessageFields, options?: ValidateMessageOptions): SiwxValidationResult;
289
421
  /**
290
422
  * Generates a cryptographically secure random nonce string suitable for CAIP-122 messages.
291
423
  * Produces a 16-byte random hex string (32 characters).
@@ -321,4 +453,4 @@ interface SiwxSessionLike {
321
453
  */
322
454
  declare function isSessionMatchingTarget(session: SiwxSessionLike | null | undefined, targetAddress: string, targetChainId?: string | number): boolean;
323
455
 
324
- export { type ParsedSiwxMessage, type SiwxAdapter, type SiwxChainId, type SiwxChainNamespace, SiwxError, SiwxExpiredSessionError, type SiwxMessageFields, SiwxNonceReplayError, SiwxParseError, type SiwxSessionLike, type SiwxStatus, SiwxUnsupportedNamespaceError, SiwxValidationError, type SiwxValidationResult, SiwxVerificationError, type SiwxVerifyPayload, type SiwxVerifyResult, buildMessage, generateNonce, isSessionMatchingTarget, parseMessage, validateMessage };
456
+ export { type ParsedSiwxMessage, type SiwxAdapter, type SiwxChainId, type SiwxChainNamespace, SiwxChainNotAllowedError, SiwxDomainMismatchError, SiwxError, SiwxExpiredSessionError, SiwxIssuedAtFutureError, SiwxIssuedAtStaleError, type SiwxMessageFields, SiwxNonceReplayError, SiwxNotBeforeError, SiwxParseError, SiwxPolicyViolationError, SiwxSessionLifetimeExceededError, type SiwxSessionLike, type SiwxStatus, SiwxUnsupportedNamespaceError, SiwxUriMismatchError, SiwxValidationError, type SiwxValidationResult, SiwxVerificationError, type SiwxVerificationPolicy, type SiwxVerifyPayload, type SiwxVerifyResult, type ValidateMessageOptions, buildMessage, generateNonce, isSessionMatchingTarget, parseMessage, validateMessage, validatePolicy };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- 'use strict';function A(e){let{domain:t,address:n,statement:o,uri:c,version:s,chainId:d,nonce:i,issuedAt:p,expirationTime:a,notBefore:r,requestId:u,resources:g}=e,f=[`${t} wants you to sign in with your blockchain account:`,n,""];if(o&&f.push(o,""),f.push(`URI: ${c}`,`Version: ${s}`,`Chain ID: ${d}`,`Nonce: ${i}`,`Issued At: ${p}`),a&&f.push(`Expiration Time: ${a}`),r&&f.push(`Not Before: ${r}`),u&&f.push(`Request ID: ${u}`),g&&g.length>0){f.push("Resources:");for(let y of g)f.push(`- ${y}`);}return f.join(`
2
- `)}var h=class extends Error{constructor(n,o="SIWX_ERROR"){super(n);this.code=o;this.name="SiwxError",Object.setPrototypeOf(this,new.target.prototype);}code},l=class extends h{constructor(t){super(t,"SIWX_PARSE_ERROR"),this.name="SiwxParseError";}},m=class extends h{constructor(n){super(`CAIP-122 message validation failed: ${n.join(", ")}`,"SIWX_VALIDATION_ERROR");this.errors=n;this.name="SiwxValidationError";}errors},x=class extends h{constructor(t){super(t,"SIWX_VERIFICATION_ERROR"),this.name="SiwxVerificationError";}},E=class extends h{constructor(n){super(`SIWX session expired at ${n}`,"SIWX_EXPIRED_SESSION");this.expirationTime=n;this.name="SiwxExpiredSessionError";}expirationTime},w=class extends h{constructor(n){super(`Nonce has already been used: ${n}`,"SIWX_NONCE_REPLAY");this.nonce=n;this.name="SiwxNonceReplayError";}nonce},S=class extends h{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 l("Message is too short to be a valid CAIP-122 message.");let n=t[0]?.match($);if(!n?.groups?.domain)throw new l('Invalid CAIP-122 header line. Expected: "{domain} wants you to sign in with your blockchain account:"');let o=n.groups.domain,c=t[1];if(!c)throw new l("Missing address on line 2.");if(t[2]!=="")throw new l("Expected blank line after address (line 3).");let s=3,d;if(t[s]&&!R.test(t[s])){if(d=t[s],s++,t[s]!=="")throw new l("Expected blank line after statement.");s++;}let i={},p=[],a=false;for(;s<t.length;){let u=t[s];if(u===void 0){s++;continue}if(u==="Resources:"){a=true,s++;continue}if(a){let f=u.match(b);if(f?.groups?.resource){p.push(f.groups.resource),s++;continue}a=false;}let g=u.match(R);g?.groups?.key&&g.groups.value&&(i[g.groups.key]=g.groups.value),s++;}let r=["URI","Version","Chain ID","Nonce","Issued At"];for(let u of r)if(!i[u])throw new l(`Missing required field in CAIP-122 message: "${u}"`);return {domain:o,address:c,statement:d,uri:i.URI,version:i.Version,chainId:i["Chain ID"],nonce:i.Nonce,issuedAt:i["Issued At"],expirationTime:i["Expiration Time"],notBefore:i["Not Before"],requestId:i["Request ID"],resources:p.length>0?p:void 0}}var M=/^https?:\/\/.+/,C=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/,_=/^[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 T(e){if(!_.test(e))return `address must be CAIP-10 compliant (namespace:chainRef:address). Got: "${e}"`}function X(e){if(!M.test(e))return `uri must be a valid RFC 3986 URI starting with http(s)://. Got: "${e}"`}function D(e){if(!P.test(e))return `chainId must be a valid CAIP-2 identifier (namespace:reference). Got: "${e}"`}function G(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 I(e,t){if(!C.test(e))return `${t} must be a valid ISO 8601 datetime string. Got: "${e}"`}function O(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 W(e,t){let n=[],o=N(e.domain);o&&n.push(o);let c=T(e.address);c&&n.push(c);let s=X(e.uri);s&&n.push(s),e.version!=="1"&&n.push(`version must be "1". Got: "${e.version}"`);let d=D(e.chainId);d&&n.push(d);let i=G(e.nonce);i&&n.push(i);let p=I(e.issuedAt,"issuedAt");if(p&&n.push(p),e.expirationTime){let a=I(e.expirationTime,"expirationTime");if(a)n.push(a);else if(!t?.skipExpiration){let r=O(e.expirationTime);r&&n.push(r);}}if(e.notBefore){let a=I(e.notBefore,"notBefore");a&&n.push(a);}return e.statement&&e.statement.includes(`
5
- `)&&n.push("statement must not contain newline characters."),{valid:n.length===0,errors:n}}function k(){let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function V(e,t,n){if(!e||!e.address||!t)return false;let o=e.address,c=o.startsWith("eip155:"),s=o.startsWith("solana:"),d=t.includes(":")?t.split(":").pop():t,i=o.includes(":")?o.split(":").pop():o,p=d.startsWith("0x")||t.startsWith("eip155:");if(p&&!c||!p&&!s||!(c?i.toLowerCase()===d.toLowerCase():i===d))return false;if(n!=null){let r=String(n),u=c?r.startsWith("eip155:")?r:`eip155:${r}`:r.startsWith("solana:")?r:`solana:${r}`;if(e.chainId&&e.chainId!==u&&e.chainId!==r)return false}return true}exports.SiwxError=h;exports.SiwxExpiredSessionError=E;exports.SiwxNonceReplayError=w;exports.SiwxParseError=l;exports.SiwxUnsupportedNamespaceError=S;exports.SiwxValidationError=m;exports.SiwxVerificationError=x;exports.buildMessage=A;exports.generateNonce=k;exports.isSessionMatchingTarget=V;exports.parseMessage=v;exports.validateMessage=W;
1
+ 'use strict';function v(e){let{domain:t,address:s,statement:i,uri:c,version:n,chainId:r,nonce:o,issuedAt:d,expirationTime:l,notBefore:a,requestId:u,resources:h}=e,p=[`${t} wants you to sign in with your blockchain account:`,s,""];if(i&&p.push(i,""),p.push(`URI: ${c}`,`Version: ${n}`,`Chain ID: ${r}`,`Nonce: ${o}`,`Issued At: ${d}`),l&&p.push(`Expiration Time: ${l}`),a&&p.push(`Not Before: ${a}`),u&&p.push(`Request ID: ${u}`),h&&h.length>0){p.push("Resources:");for(let N of h)p.push(`- ${N}`);}return p.join(`
2
+ `)}var m=class extends Error{constructor(s,i="SIWX_ERROR"){super(s);this.code=i;this.name="SiwxError",Object.setPrototypeOf(this,new.target.prototype);}code},f=class extends m{constructor(t){super(t,"SIWX_PARSE_ERROR"),this.name="SiwxParseError";}},x=class extends m{constructor(s){super(`CAIP-122 message validation failed: ${s.join(", ")}`,"SIWX_VALIDATION_ERROR");this.errors=s;this.name="SiwxValidationError";}errors},S=class extends m{constructor(t){super(t,"SIWX_VERIFICATION_ERROR"),this.name="SiwxVerificationError";}},w=class extends m{constructor(s){super(`SIWX session expired at ${s}`,"SIWX_EXPIRED_SESSION");this.expirationTime=s;this.name="SiwxExpiredSessionError";}expirationTime},E=class extends m{constructor(s){super(`Nonce has already been used: ${s}`,"SIWX_NONCE_REPLAY");this.nonce=s;this.name="SiwxNonceReplayError";}nonce},I=class extends m{constructor(s){super(`Unsupported CAIP-2 namespace: "${s}". Supported: eip155, solana`,"SIWX_UNSUPPORTED_NAMESPACE");this.namespace=s;this.name="SiwxUnsupportedNamespaceError";}namespace},g=class extends m{constructor(t,s="SIWX_POLICY_VIOLATION"){super(t,s),this.name="SiwxPolicyViolationError";}},A=class extends g{constructor(s,i){let c=Array.isArray(s)?s.join(", "):s;super(`Domain mismatch. Expected: [${c}], Received: "${i}"`,"SIWX_DOMAIN_MISMATCH");this.expected=s;this.received=i;this.name="SiwxDomainMismatchError";}expected;received},$=class extends g{constructor(s,i){let c=Array.isArray(s)?s.join(", "):s;super(`URI mismatch. Expected: [${c}], Received: "${i}"`,"SIWX_URI_MISMATCH");this.expected=s;this.received=i;this.name="SiwxUriMismatchError";}expected;received},R=class extends g{constructor(s,i){super(`Chain ID "${i}" is not allowed. Allowed: [${s.join(", ")}]`,"SIWX_CHAIN_NOT_ALLOWED");this.allowedChainIds=s;this.received=i;this.name="SiwxChainNotAllowedError";}allowedChainIds;received},y=class extends g{constructor(s,i){super(`Message issuedAt "${s}" is older than the allowed max age of ${i} seconds`,"SIWX_ISSUED_AT_STALE");this.issuedAt=s;this.maxAgeSeconds=i;this.name="SiwxIssuedAtStaleError";}issuedAt;maxAgeSeconds},b=class extends g{constructor(s,i){super(`Message issuedAt "${s}" is in the future beyond allowed clock skew of ${i} seconds`,"SIWX_ISSUED_AT_FUTURE");this.issuedAt=s;this.clockSkewSeconds=i;this.name="SiwxIssuedAtFutureError";}issuedAt;clockSkewSeconds},M=class extends g{constructor(s){super(`Message not valid before ${s}`,"SIWX_NOT_BEFORE");this.notBefore=s;this.name="SiwxNotBeforeError";}notBefore},T=class extends g{constructor(s,i){super(`Session lifetime of ${s} seconds exceeds maximum allowed lifetime of ${i} seconds`,"SIWX_SESSION_LIFETIME_EXCEEDED");this.lifetimeSeconds=s;this.maxLifetimeSeconds=i;this.name="SiwxSessionLifetimeExceededError";}lifetimeSeconds;maxLifetimeSeconds};var U=/^(?<domain>.+) wants you to sign in with your blockchain account:$/,C=/^(?<key>[A-Za-z ]+): (?<value>.+)$/,P=/^- (?<resource>.+)$/;function O(e){let t=e.split(`
3
+ `);if(t.length<5)throw new f("Message is too short to be a valid CAIP-122 message.");let s=t[0]?.match(U);if(!s?.groups?.domain)throw new f('Invalid CAIP-122 header line. Expected: "{domain} wants you to sign in with your blockchain account:"');let i=s.groups.domain,c=t[1];if(!c)throw new f("Missing address on line 2.");if(t[2]!=="")throw new f("Expected blank line after address (line 3).");let n=3,r;if(t[n]&&!C.test(t[n])){if(r=t[n],n++,t[n]!=="")throw new f("Expected blank line after statement.");n++;}let o={},d=[],l=false;for(;n<t.length;){let u=t[n];if(u===void 0){n++;continue}if(u==="Resources:"){l=true,n++;continue}if(l){let p=u.match(P);if(p?.groups?.resource){d.push(p.groups.resource),n++;continue}l=false;}let h=u.match(C);h?.groups?.key&&h.groups.value&&(o[h.groups.key]=h.groups.value),n++;}let a=["URI","Version","Chain ID","Nonce","Issued At"];for(let u of a)if(!o[u])throw new f(`Missing required field in CAIP-122 message: "${u}"`);return {domain:i,address:c,statement:r,uri:o.URI,version:o.Version,chainId:o["Chain ID"],nonce:o.Nonce,issuedAt:o["Issued At"],expirationTime:o["Expiration Time"],notBefore:o["Not Before"],requestId:o["Request ID"],resources:d.length>0?d:void 0}}var W=/^https?:\/\/.+/,X=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/,k=/^[a-z0-9]+:[a-zA-Z0-9-]+:.+$/,L=/^[a-z0-9]+:[a-zA-Z0-9-]+$/;function V(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 B(e){if(!k.test(e))return `address must be CAIP-10 compliant (namespace:chainRef:address). Got: "${e}"`}function F(e){if(!W.test(e))return `uri must be a valid RFC 3986 URI starting with http(s)://. Got: "${e}"`}function G(e){if(!L.test(e))return `chainId must be a valid CAIP-2 identifier (namespace:reference). Got: "${e}"`}function j(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 _(e,t){if(!X.test(e))return `${t} must be a valid ISO 8601 datetime string. Got: "${e}"`}function q(e,t=new Date,s=0){let i=new Date(e);if(isNaN(i.getTime()))return `expirationTime is not a valid date: "${e}"`;if(i.getTime()+s*1e3<t.getTime())return `Message has expired. expirationTime was: ${e}`}function D(e,t,s=new Date){if(!t)return [];let i=[];if(t.expectedDomain!==void 0){let r=Array.isArray(t.expectedDomain)?t.expectedDomain:[t.expectedDomain];r.some(d=>d.toLowerCase()===e.domain.toLowerCase())||i.push(`Domain mismatch. Expected: [${r.join(", ")}], Received: "${e.domain}"`);}if(t.expectedUri!==void 0){let r=Array.isArray(t.expectedUri)?t.expectedUri:[t.expectedUri];r.some(d=>{if(e.uri===d)return true;let l=d.endsWith("/")?d.slice(0,-1):d;if(e.uri.startsWith(`${l}/`))return true;try{let a=new URL(e.uri),u=new URL(d);return a.origin.toLowerCase()===u.origin.toLowerCase()}catch{return false}})||i.push(`URI mismatch. Expected: [${r.join(", ")}], Received: "${e.uri}"`);}t.allowedChainIds!==void 0&&t.allowedChainIds.length>0&&(t.allowedChainIds.includes(e.chainId)||i.push(`Chain ID "${e.chainId}" is not allowed. Allowed: [${t.allowedChainIds.join(", ")}]`)),t.requireExpirationTime&&!e.expirationTime&&i.push("expirationTime is required by verification policy.");let c=t.clockSkewSeconds??60,n=new Date(e.issuedAt);if(isNaN(n.getTime())||(t.maxIssuedAtAgeSeconds!==void 0&&(s.getTime()-n.getTime())/1e3>t.maxIssuedAtAgeSeconds+c&&i.push(`Message issuedAt "${e.issuedAt}" is older than the allowed max age of ${t.maxIssuedAtAgeSeconds} seconds`),n.getTime()-s.getTime()>c*1e3&&i.push(`Message issuedAt "${e.issuedAt}" is in the future beyond allowed clock skew of ${c} seconds`)),e.notBefore&&t.enforceNotBefore!==false){let r=new Date(e.notBefore);isNaN(r.getTime())||r.getTime()-s.getTime()>c*1e3&&i.push(`Message not valid before ${e.notBefore}`);}if(t.maxSessionLifetimeSeconds!==void 0&&e.expirationTime){let r=new Date(e.expirationTime);if(!isNaN(r.getTime())&&!isNaN(n.getTime())){let o=(r.getTime()-n.getTime())/1e3;o>t.maxSessionLifetimeSeconds&&i.push(`Session lifetime of ${o} seconds exceeds maximum allowed lifetime of ${t.maxSessionLifetimeSeconds} seconds`);}}return i}function z(e,t){let s=[],i=V(e.domain);i&&s.push(i);let c=B(e.address);c&&s.push(c);let n=F(e.uri);n&&s.push(n),e.version!=="1"&&s.push(`version must be "1". Got: "${e.version}"`);let r=G(e.chainId);r&&s.push(r);let o=j(e.nonce);o&&s.push(o);let d=_(e.issuedAt,"issuedAt");d&&s.push(d);let l=t?.policy?.clockSkewSeconds??60;if(e.expirationTime){let a=_(e.expirationTime,"expirationTime");if(a)s.push(a);else if(!t?.skipExpiration){let u=q(e.expirationTime,new Date,l);u&&s.push(u);}}if(e.notBefore){let a=_(e.notBefore,"notBefore");a&&s.push(a);}if(e.statement&&e.statement.includes(`
5
+ `)&&s.push("statement must not contain newline characters."),t?.policy){let a=D(e,t.policy);s.push(...a);}return {valid:s.length===0,errors:s}}function Z(){let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function H(e,t,s){if(!e||!e.address||!t)return false;let i=e.address,c=i.startsWith("eip155:"),n=i.startsWith("solana:"),r=t.includes(":")?t.split(":").pop():t,o=i.includes(":")?i.split(":").pop():i,d=r.startsWith("0x")||t.startsWith("eip155:");if(d&&!c||!d&&!n||!(c?o.toLowerCase()===r.toLowerCase():o===r))return false;if(s!=null){let a=String(s),u=c?a.startsWith("eip155:")?a:`eip155:${a}`:a.startsWith("solana:")?a:`solana:${a}`;if(e.chainId&&e.chainId!==u&&e.chainId!==a)return false}return true}exports.SiwxChainNotAllowedError=R;exports.SiwxDomainMismatchError=A;exports.SiwxError=m;exports.SiwxExpiredSessionError=w;exports.SiwxIssuedAtFutureError=b;exports.SiwxIssuedAtStaleError=y;exports.SiwxNonceReplayError=E;exports.SiwxNotBeforeError=M;exports.SiwxParseError=f;exports.SiwxPolicyViolationError=g;exports.SiwxSessionLifetimeExceededError=T;exports.SiwxUnsupportedNamespaceError=I;exports.SiwxUriMismatchError=$;exports.SiwxValidationError=x;exports.SiwxVerificationError=S;exports.buildMessage=v;exports.generateNonce=Z;exports.isSessionMatchingTarget=H;exports.parseMessage=O;exports.validateMessage=z;exports.validatePolicy=D;
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- function A(e){let{domain:t,address:n,statement:o,uri:c,version:s,chainId:d,nonce:i,issuedAt:p,expirationTime:a,notBefore:r,requestId:u,resources:g}=e,f=[`${t} wants you to sign in with your blockchain account:`,n,""];if(o&&f.push(o,""),f.push(`URI: ${c}`,`Version: ${s}`,`Chain ID: ${d}`,`Nonce: ${i}`,`Issued At: ${p}`),a&&f.push(`Expiration Time: ${a}`),r&&f.push(`Not Before: ${r}`),u&&f.push(`Request ID: ${u}`),g&&g.length>0){f.push("Resources:");for(let y of g)f.push(`- ${y}`);}return f.join(`
2
- `)}var h=class extends Error{constructor(n,o="SIWX_ERROR"){super(n);this.code=o;this.name="SiwxError",Object.setPrototypeOf(this,new.target.prototype);}code},l=class extends h{constructor(t){super(t,"SIWX_PARSE_ERROR"),this.name="SiwxParseError";}},m=class extends h{constructor(n){super(`CAIP-122 message validation failed: ${n.join(", ")}`,"SIWX_VALIDATION_ERROR");this.errors=n;this.name="SiwxValidationError";}errors},x=class extends h{constructor(t){super(t,"SIWX_VERIFICATION_ERROR"),this.name="SiwxVerificationError";}},E=class extends h{constructor(n){super(`SIWX session expired at ${n}`,"SIWX_EXPIRED_SESSION");this.expirationTime=n;this.name="SiwxExpiredSessionError";}expirationTime},w=class extends h{constructor(n){super(`Nonce has already been used: ${n}`,"SIWX_NONCE_REPLAY");this.nonce=n;this.name="SiwxNonceReplayError";}nonce},S=class extends h{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 l("Message is too short to be a valid CAIP-122 message.");let n=t[0]?.match($);if(!n?.groups?.domain)throw new l('Invalid CAIP-122 header line. Expected: "{domain} wants you to sign in with your blockchain account:"');let o=n.groups.domain,c=t[1];if(!c)throw new l("Missing address on line 2.");if(t[2]!=="")throw new l("Expected blank line after address (line 3).");let s=3,d;if(t[s]&&!R.test(t[s])){if(d=t[s],s++,t[s]!=="")throw new l("Expected blank line after statement.");s++;}let i={},p=[],a=false;for(;s<t.length;){let u=t[s];if(u===void 0){s++;continue}if(u==="Resources:"){a=true,s++;continue}if(a){let f=u.match(b);if(f?.groups?.resource){p.push(f.groups.resource),s++;continue}a=false;}let g=u.match(R);g?.groups?.key&&g.groups.value&&(i[g.groups.key]=g.groups.value),s++;}let r=["URI","Version","Chain ID","Nonce","Issued At"];for(let u of r)if(!i[u])throw new l(`Missing required field in CAIP-122 message: "${u}"`);return {domain:o,address:c,statement:d,uri:i.URI,version:i.Version,chainId:i["Chain ID"],nonce:i.Nonce,issuedAt:i["Issued At"],expirationTime:i["Expiration Time"],notBefore:i["Not Before"],requestId:i["Request ID"],resources:p.length>0?p:void 0}}var M=/^https?:\/\/.+/,C=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/,_=/^[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 T(e){if(!_.test(e))return `address must be CAIP-10 compliant (namespace:chainRef:address). Got: "${e}"`}function X(e){if(!M.test(e))return `uri must be a valid RFC 3986 URI starting with http(s)://. Got: "${e}"`}function D(e){if(!P.test(e))return `chainId must be a valid CAIP-2 identifier (namespace:reference). Got: "${e}"`}function G(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 I(e,t){if(!C.test(e))return `${t} must be a valid ISO 8601 datetime string. Got: "${e}"`}function O(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 W(e,t){let n=[],o=N(e.domain);o&&n.push(o);let c=T(e.address);c&&n.push(c);let s=X(e.uri);s&&n.push(s),e.version!=="1"&&n.push(`version must be "1". Got: "${e.version}"`);let d=D(e.chainId);d&&n.push(d);let i=G(e.nonce);i&&n.push(i);let p=I(e.issuedAt,"issuedAt");if(p&&n.push(p),e.expirationTime){let a=I(e.expirationTime,"expirationTime");if(a)n.push(a);else if(!t?.skipExpiration){let r=O(e.expirationTime);r&&n.push(r);}}if(e.notBefore){let a=I(e.notBefore,"notBefore");a&&n.push(a);}return e.statement&&e.statement.includes(`
5
- `)&&n.push("statement must not contain newline characters."),{valid:n.length===0,errors:n}}function k(){let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function V(e,t,n){if(!e||!e.address||!t)return false;let o=e.address,c=o.startsWith("eip155:"),s=o.startsWith("solana:"),d=t.includes(":")?t.split(":").pop():t,i=o.includes(":")?o.split(":").pop():o,p=d.startsWith("0x")||t.startsWith("eip155:");if(p&&!c||!p&&!s||!(c?i.toLowerCase()===d.toLowerCase():i===d))return false;if(n!=null){let r=String(n),u=c?r.startsWith("eip155:")?r:`eip155:${r}`:r.startsWith("solana:")?r:`solana:${r}`;if(e.chainId&&e.chainId!==u&&e.chainId!==r)return false}return true}export{h as SiwxError,E as SiwxExpiredSessionError,w as SiwxNonceReplayError,l as SiwxParseError,S as SiwxUnsupportedNamespaceError,m as SiwxValidationError,x as SiwxVerificationError,A as buildMessage,k as generateNonce,V as isSessionMatchingTarget,v as parseMessage,W as validateMessage};
1
+ function v(e){let{domain:t,address:s,statement:i,uri:c,version:n,chainId:r,nonce:o,issuedAt:d,expirationTime:l,notBefore:a,requestId:u,resources:h}=e,p=[`${t} wants you to sign in with your blockchain account:`,s,""];if(i&&p.push(i,""),p.push(`URI: ${c}`,`Version: ${n}`,`Chain ID: ${r}`,`Nonce: ${o}`,`Issued At: ${d}`),l&&p.push(`Expiration Time: ${l}`),a&&p.push(`Not Before: ${a}`),u&&p.push(`Request ID: ${u}`),h&&h.length>0){p.push("Resources:");for(let N of h)p.push(`- ${N}`);}return p.join(`
2
+ `)}var m=class extends Error{constructor(s,i="SIWX_ERROR"){super(s);this.code=i;this.name="SiwxError",Object.setPrototypeOf(this,new.target.prototype);}code},f=class extends m{constructor(t){super(t,"SIWX_PARSE_ERROR"),this.name="SiwxParseError";}},x=class extends m{constructor(s){super(`CAIP-122 message validation failed: ${s.join(", ")}`,"SIWX_VALIDATION_ERROR");this.errors=s;this.name="SiwxValidationError";}errors},S=class extends m{constructor(t){super(t,"SIWX_VERIFICATION_ERROR"),this.name="SiwxVerificationError";}},w=class extends m{constructor(s){super(`SIWX session expired at ${s}`,"SIWX_EXPIRED_SESSION");this.expirationTime=s;this.name="SiwxExpiredSessionError";}expirationTime},E=class extends m{constructor(s){super(`Nonce has already been used: ${s}`,"SIWX_NONCE_REPLAY");this.nonce=s;this.name="SiwxNonceReplayError";}nonce},I=class extends m{constructor(s){super(`Unsupported CAIP-2 namespace: "${s}". Supported: eip155, solana`,"SIWX_UNSUPPORTED_NAMESPACE");this.namespace=s;this.name="SiwxUnsupportedNamespaceError";}namespace},g=class extends m{constructor(t,s="SIWX_POLICY_VIOLATION"){super(t,s),this.name="SiwxPolicyViolationError";}},A=class extends g{constructor(s,i){let c=Array.isArray(s)?s.join(", "):s;super(`Domain mismatch. Expected: [${c}], Received: "${i}"`,"SIWX_DOMAIN_MISMATCH");this.expected=s;this.received=i;this.name="SiwxDomainMismatchError";}expected;received},$=class extends g{constructor(s,i){let c=Array.isArray(s)?s.join(", "):s;super(`URI mismatch. Expected: [${c}], Received: "${i}"`,"SIWX_URI_MISMATCH");this.expected=s;this.received=i;this.name="SiwxUriMismatchError";}expected;received},R=class extends g{constructor(s,i){super(`Chain ID "${i}" is not allowed. Allowed: [${s.join(", ")}]`,"SIWX_CHAIN_NOT_ALLOWED");this.allowedChainIds=s;this.received=i;this.name="SiwxChainNotAllowedError";}allowedChainIds;received},y=class extends g{constructor(s,i){super(`Message issuedAt "${s}" is older than the allowed max age of ${i} seconds`,"SIWX_ISSUED_AT_STALE");this.issuedAt=s;this.maxAgeSeconds=i;this.name="SiwxIssuedAtStaleError";}issuedAt;maxAgeSeconds},b=class extends g{constructor(s,i){super(`Message issuedAt "${s}" is in the future beyond allowed clock skew of ${i} seconds`,"SIWX_ISSUED_AT_FUTURE");this.issuedAt=s;this.clockSkewSeconds=i;this.name="SiwxIssuedAtFutureError";}issuedAt;clockSkewSeconds},M=class extends g{constructor(s){super(`Message not valid before ${s}`,"SIWX_NOT_BEFORE");this.notBefore=s;this.name="SiwxNotBeforeError";}notBefore},T=class extends g{constructor(s,i){super(`Session lifetime of ${s} seconds exceeds maximum allowed lifetime of ${i} seconds`,"SIWX_SESSION_LIFETIME_EXCEEDED");this.lifetimeSeconds=s;this.maxLifetimeSeconds=i;this.name="SiwxSessionLifetimeExceededError";}lifetimeSeconds;maxLifetimeSeconds};var U=/^(?<domain>.+) wants you to sign in with your blockchain account:$/,C=/^(?<key>[A-Za-z ]+): (?<value>.+)$/,P=/^- (?<resource>.+)$/;function O(e){let t=e.split(`
3
+ `);if(t.length<5)throw new f("Message is too short to be a valid CAIP-122 message.");let s=t[0]?.match(U);if(!s?.groups?.domain)throw new f('Invalid CAIP-122 header line. Expected: "{domain} wants you to sign in with your blockchain account:"');let i=s.groups.domain,c=t[1];if(!c)throw new f("Missing address on line 2.");if(t[2]!=="")throw new f("Expected blank line after address (line 3).");let n=3,r;if(t[n]&&!C.test(t[n])){if(r=t[n],n++,t[n]!=="")throw new f("Expected blank line after statement.");n++;}let o={},d=[],l=false;for(;n<t.length;){let u=t[n];if(u===void 0){n++;continue}if(u==="Resources:"){l=true,n++;continue}if(l){let p=u.match(P);if(p?.groups?.resource){d.push(p.groups.resource),n++;continue}l=false;}let h=u.match(C);h?.groups?.key&&h.groups.value&&(o[h.groups.key]=h.groups.value),n++;}let a=["URI","Version","Chain ID","Nonce","Issued At"];for(let u of a)if(!o[u])throw new f(`Missing required field in CAIP-122 message: "${u}"`);return {domain:i,address:c,statement:r,uri:o.URI,version:o.Version,chainId:o["Chain ID"],nonce:o.Nonce,issuedAt:o["Issued At"],expirationTime:o["Expiration Time"],notBefore:o["Not Before"],requestId:o["Request ID"],resources:d.length>0?d:void 0}}var W=/^https?:\/\/.+/,X=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/,k=/^[a-z0-9]+:[a-zA-Z0-9-]+:.+$/,L=/^[a-z0-9]+:[a-zA-Z0-9-]+$/;function V(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 B(e){if(!k.test(e))return `address must be CAIP-10 compliant (namespace:chainRef:address). Got: "${e}"`}function F(e){if(!W.test(e))return `uri must be a valid RFC 3986 URI starting with http(s)://. Got: "${e}"`}function G(e){if(!L.test(e))return `chainId must be a valid CAIP-2 identifier (namespace:reference). Got: "${e}"`}function j(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 _(e,t){if(!X.test(e))return `${t} must be a valid ISO 8601 datetime string. Got: "${e}"`}function q(e,t=new Date,s=0){let i=new Date(e);if(isNaN(i.getTime()))return `expirationTime is not a valid date: "${e}"`;if(i.getTime()+s*1e3<t.getTime())return `Message has expired. expirationTime was: ${e}`}function D(e,t,s=new Date){if(!t)return [];let i=[];if(t.expectedDomain!==void 0){let r=Array.isArray(t.expectedDomain)?t.expectedDomain:[t.expectedDomain];r.some(d=>d.toLowerCase()===e.domain.toLowerCase())||i.push(`Domain mismatch. Expected: [${r.join(", ")}], Received: "${e.domain}"`);}if(t.expectedUri!==void 0){let r=Array.isArray(t.expectedUri)?t.expectedUri:[t.expectedUri];r.some(d=>{if(e.uri===d)return true;let l=d.endsWith("/")?d.slice(0,-1):d;if(e.uri.startsWith(`${l}/`))return true;try{let a=new URL(e.uri),u=new URL(d);return a.origin.toLowerCase()===u.origin.toLowerCase()}catch{return false}})||i.push(`URI mismatch. Expected: [${r.join(", ")}], Received: "${e.uri}"`);}t.allowedChainIds!==void 0&&t.allowedChainIds.length>0&&(t.allowedChainIds.includes(e.chainId)||i.push(`Chain ID "${e.chainId}" is not allowed. Allowed: [${t.allowedChainIds.join(", ")}]`)),t.requireExpirationTime&&!e.expirationTime&&i.push("expirationTime is required by verification policy.");let c=t.clockSkewSeconds??60,n=new Date(e.issuedAt);if(isNaN(n.getTime())||(t.maxIssuedAtAgeSeconds!==void 0&&(s.getTime()-n.getTime())/1e3>t.maxIssuedAtAgeSeconds+c&&i.push(`Message issuedAt "${e.issuedAt}" is older than the allowed max age of ${t.maxIssuedAtAgeSeconds} seconds`),n.getTime()-s.getTime()>c*1e3&&i.push(`Message issuedAt "${e.issuedAt}" is in the future beyond allowed clock skew of ${c} seconds`)),e.notBefore&&t.enforceNotBefore!==false){let r=new Date(e.notBefore);isNaN(r.getTime())||r.getTime()-s.getTime()>c*1e3&&i.push(`Message not valid before ${e.notBefore}`);}if(t.maxSessionLifetimeSeconds!==void 0&&e.expirationTime){let r=new Date(e.expirationTime);if(!isNaN(r.getTime())&&!isNaN(n.getTime())){let o=(r.getTime()-n.getTime())/1e3;o>t.maxSessionLifetimeSeconds&&i.push(`Session lifetime of ${o} seconds exceeds maximum allowed lifetime of ${t.maxSessionLifetimeSeconds} seconds`);}}return i}function z(e,t){let s=[],i=V(e.domain);i&&s.push(i);let c=B(e.address);c&&s.push(c);let n=F(e.uri);n&&s.push(n),e.version!=="1"&&s.push(`version must be "1". Got: "${e.version}"`);let r=G(e.chainId);r&&s.push(r);let o=j(e.nonce);o&&s.push(o);let d=_(e.issuedAt,"issuedAt");d&&s.push(d);let l=t?.policy?.clockSkewSeconds??60;if(e.expirationTime){let a=_(e.expirationTime,"expirationTime");if(a)s.push(a);else if(!t?.skipExpiration){let u=q(e.expirationTime,new Date,l);u&&s.push(u);}}if(e.notBefore){let a=_(e.notBefore,"notBefore");a&&s.push(a);}if(e.statement&&e.statement.includes(`
5
+ `)&&s.push("statement must not contain newline characters."),t?.policy){let a=D(e,t.policy);s.push(...a);}return {valid:s.length===0,errors:s}}function Z(){let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function H(e,t,s){if(!e||!e.address||!t)return false;let i=e.address,c=i.startsWith("eip155:"),n=i.startsWith("solana:"),r=t.includes(":")?t.split(":").pop():t,o=i.includes(":")?i.split(":").pop():i,d=r.startsWith("0x")||t.startsWith("eip155:");if(d&&!c||!d&&!n||!(c?o.toLowerCase()===r.toLowerCase():o===r))return false;if(s!=null){let a=String(s),u=c?a.startsWith("eip155:")?a:`eip155:${a}`:a.startsWith("solana:")?a:`solana:${a}`;if(e.chainId&&e.chainId!==u&&e.chainId!==a)return false}return true}export{R as SiwxChainNotAllowedError,A as SiwxDomainMismatchError,m as SiwxError,w as SiwxExpiredSessionError,b as SiwxIssuedAtFutureError,y as SiwxIssuedAtStaleError,E as SiwxNonceReplayError,M as SiwxNotBeforeError,f as SiwxParseError,g as SiwxPolicyViolationError,T as SiwxSessionLifetimeExceededError,I as SiwxUnsupportedNamespaceError,$ as SiwxUriMismatchError,x as SiwxValidationError,S as SiwxVerificationError,v as buildMessage,Z as generateNonce,H as isSessionMatchingTarget,O as parseMessage,z as validateMessage,D as validatePolicy};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tuwaio/siwx-core",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "private": false,
5
5
  "author": "Oleksandr Tkach",
6
6
  "license": "Apache-2.0",