@tuwaio/siwx-core 0.4.1 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/dist/index.d.mts +46 -5
- package/dist/index.d.ts +46 -5
- package/dist/index.js +5 -5
- package/dist/index.mjs +5 -5
- package/package.json +6 -2
package/README.md
CHANGED
|
@@ -5,14 +5,14 @@
|
|
|
5
5
|
|
|
6
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
7
|
|
|
8
|
-
|
|
8
|
+
Its only dependency is the peer [`@tuwaio/orbit-core`](https://orbit.docs.tuwa.io/packages/orbit-core), which has no dependencies of its own and reads the CAIP-2 chain and CAIP-10 account IDs and the Solana genesis-hash chain IDs. The package imports no Web3 SDK. It runs in browsers, Node.js 20+ and edge runtimes; only `generateNonce` needs the Web Crypto API.
|
|
9
9
|
|
|
10
10
|
---
|
|
11
11
|
|
|
12
12
|
## 🏛️ Core Capabilities
|
|
13
13
|
|
|
14
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.
|
|
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. Addresses and chain IDs are read with the parsers of `@tuwaio/orbit-core`, so an EVM or Solana account must be a valid address of its chain.
|
|
16
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
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
18
|
- **Nonces and errors:** `generateNonce` returns 32 random hex characters; `SiwxError` and its subclasses carry machine-readable `code`s.
|
|
@@ -24,7 +24,7 @@ Signatures are verified by the chain packages ([`@tuwaio/siwx-evm`](https://siwx
|
|
|
24
24
|
## 💾 Installation
|
|
25
25
|
|
|
26
26
|
```bash
|
|
27
|
-
pnpm add @tuwaio/siwx-core
|
|
27
|
+
pnpm add @tuwaio/siwx-core @tuwaio/orbit-core
|
|
28
28
|
```
|
|
29
29
|
|
|
30
30
|
---
|
|
@@ -96,7 +96,7 @@ if (!result.valid) {
|
|
|
96
96
|
- `validateMessage` checks formats and timing only. It does not verify the signature.
|
|
97
97
|
- Policy rules run only for the fields you set; `maxIssuedAtAgeSeconds` has no default. `clockSkewSeconds` defaults to 60 seconds.
|
|
98
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.
|
|
99
|
+
- `allowedChainIds` entries are full CAIP-2 IDs matched exactly: `eip155:1` does not allow `solana:1`, and a bare `1` matches nothing. The one exception is a Solana cluster: its Wallet Standard name and its genesis-hash ID match each other (`solana:devnet` and `solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1`), so sessions signed before the switch to genesis-hash IDs stay valid. `normalizeSolanaChainId` and `isChainIdAllowed` apply this rule.
|
|
100
100
|
- `validatePolicy(fields, policy, now?)` runs the policy rules alone and returns the list of violations.
|
|
101
101
|
|
|
102
102
|
### Matching a session to a wallet
|
package/dist/index.d.mts
CHANGED
|
@@ -110,7 +110,8 @@ interface SiwxVerificationPolicy {
|
|
|
110
110
|
expectedUri?: string | string[];
|
|
111
111
|
/**
|
|
112
112
|
* Allowed CAIP-2 chain IDs. The message `chainId` must equal one of them exactly (bare references such as `"1"`
|
|
113
|
-
* never match)
|
|
113
|
+
* never match), except that a Solana cluster matches under its name and its genesis-hash chain ID (`solana:devnet`
|
|
114
|
+
* allows `solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1`, see `isChainIdAllowed`). An empty array allows every chain.
|
|
114
115
|
* @example ["eip155:1", "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"]
|
|
115
116
|
*/
|
|
116
117
|
allowedChainIds?: string[];
|
|
@@ -461,6 +462,43 @@ declare class SiwxSessionLifetimeExceededError extends SiwxPolicyViolationError
|
|
|
461
462
|
*/
|
|
462
463
|
declare function parseMessage(message: string): ParsedSiwxMessage;
|
|
463
464
|
|
|
465
|
+
/**
|
|
466
|
+
* Returns the CAIP-2 chain ID of a public Solana cluster in the form CAIP-30 requires, the genesis hash. Wallet Standard
|
|
467
|
+
* names (`solana:mainnet`, `solana:devnet`, `solana:testnet`), `solana:mainnet-beta` and the testnet ID from before the
|
|
468
|
+
* testnet genesis reset become `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp`, `solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1` or
|
|
469
|
+
* `solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z`.
|
|
470
|
+
*
|
|
471
|
+
* Use it to compare Solana chain IDs: sessions signed before the switch to genesis-hash IDs carry `solana:devnet`. The
|
|
472
|
+
* cluster table is `SOLANA_CHAIN_IDS` of `@tuwaio/orbit-core`, read through its `getSolanaChainId`.
|
|
473
|
+
*
|
|
474
|
+
* @param chainId - A CAIP-2 chain ID.
|
|
475
|
+
* @returns The genesis-hash chain ID for a known Solana cluster name; any other value unchanged (genesis-hash IDs,
|
|
476
|
+
* `solana:localnet`, other namespaces, bare references).
|
|
477
|
+
*
|
|
478
|
+
* @example
|
|
479
|
+
* ```ts
|
|
480
|
+
* normalizeSolanaChainId('solana:devnet'); // "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1"
|
|
481
|
+
* normalizeSolanaChainId('eip155:1'); // "eip155:1"
|
|
482
|
+
* ```
|
|
483
|
+
*/
|
|
484
|
+
declare function normalizeSolanaChainId(chainId: string): string;
|
|
485
|
+
/**
|
|
486
|
+
* Checks a chain ID against the `allowedChainIds` of a verification policy. Chain IDs must match exactly, so `eip155:1`
|
|
487
|
+
* never allows `solana:1` or a bare `1`; the only exception is a Solana cluster, which matches under its name and its
|
|
488
|
+
* genesis-hash chain ID (see {@link normalizeSolanaChainId}).
|
|
489
|
+
*
|
|
490
|
+
* @param chainId - The CAIP-2 chain ID of a message or session.
|
|
491
|
+
* @param allowedChainIds - The allowed CAIP-2 chain IDs. Missing or empty allows every chain.
|
|
492
|
+
* @returns `true` when the chain is allowed.
|
|
493
|
+
*
|
|
494
|
+
* @example
|
|
495
|
+
* ```ts
|
|
496
|
+
* isChainIdAllowed('solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1', ['solana:devnet']); // true
|
|
497
|
+
* isChainIdAllowed('eip155:1', ['eip155:8453']); // false
|
|
498
|
+
* ```
|
|
499
|
+
*/
|
|
500
|
+
declare function isChainIdAllowed(chainId: string, allowedChainIds?: readonly string[]): boolean;
|
|
501
|
+
|
|
464
502
|
/**
|
|
465
503
|
* @file CAIP-122 message field validators.
|
|
466
504
|
* Provides individual validators and a composite `validateMessage` function.
|
|
@@ -535,9 +573,12 @@ interface SiwxSessionLike {
|
|
|
535
573
|
* Checks whether a SIWX session belongs to a given wallet address and, optionally, chain. Use it on the server to
|
|
536
574
|
* make sure the signed-in account is the one a request acts on.
|
|
537
575
|
*
|
|
538
|
-
*
|
|
539
|
-
*
|
|
540
|
-
*
|
|
576
|
+
* The session account is read with `parseCaip10AccountId` of `@tuwaio/orbit-core`; a session whose account is not a
|
|
577
|
+
* valid `eip155` or `solana` CAIP-10 account ID never matches. A CAIP-10 target must have the session's namespace (any
|
|
578
|
+
* of its chains); a plain target that starts with `0x` only matches `eip155:` sessions, any other plain target only
|
|
579
|
+
* `solana:` sessions. EVM accounts are compared case-insensitively, Solana accounts case-sensitively. The chain is
|
|
580
|
+
* compared only when `targetChainId` is given and the session has a `chainId`; a Solana cluster matches under its name
|
|
581
|
+
* (`devnet`, `solana:devnet`) and its genesis-hash chain ID (see {@link normalizeSolanaChainId}).
|
|
541
582
|
*
|
|
542
583
|
* @param session - The session or parsed message to check. `null` and `undefined` never match.
|
|
543
584
|
* @param targetAddress - The expected account, as a plain address or a CAIP-10 account ID.
|
|
@@ -554,4 +595,4 @@ interface SiwxSessionLike {
|
|
|
554
595
|
*/
|
|
555
596
|
declare function isSessionMatchingTarget(session: SiwxSessionLike | null | undefined, targetAddress: string, targetChainId?: string | number): boolean;
|
|
556
597
|
|
|
557
|
-
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 };
|
|
598
|
+
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, isChainIdAllowed, isSessionMatchingTarget, normalizeSolanaChainId, parseMessage, validateMessage, validatePolicy };
|
package/dist/index.d.ts
CHANGED
|
@@ -110,7 +110,8 @@ interface SiwxVerificationPolicy {
|
|
|
110
110
|
expectedUri?: string | string[];
|
|
111
111
|
/**
|
|
112
112
|
* Allowed CAIP-2 chain IDs. The message `chainId` must equal one of them exactly (bare references such as `"1"`
|
|
113
|
-
* never match)
|
|
113
|
+
* never match), except that a Solana cluster matches under its name and its genesis-hash chain ID (`solana:devnet`
|
|
114
|
+
* allows `solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1`, see `isChainIdAllowed`). An empty array allows every chain.
|
|
114
115
|
* @example ["eip155:1", "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"]
|
|
115
116
|
*/
|
|
116
117
|
allowedChainIds?: string[];
|
|
@@ -461,6 +462,43 @@ declare class SiwxSessionLifetimeExceededError extends SiwxPolicyViolationError
|
|
|
461
462
|
*/
|
|
462
463
|
declare function parseMessage(message: string): ParsedSiwxMessage;
|
|
463
464
|
|
|
465
|
+
/**
|
|
466
|
+
* Returns the CAIP-2 chain ID of a public Solana cluster in the form CAIP-30 requires, the genesis hash. Wallet Standard
|
|
467
|
+
* names (`solana:mainnet`, `solana:devnet`, `solana:testnet`), `solana:mainnet-beta` and the testnet ID from before the
|
|
468
|
+
* testnet genesis reset become `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp`, `solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1` or
|
|
469
|
+
* `solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z`.
|
|
470
|
+
*
|
|
471
|
+
* Use it to compare Solana chain IDs: sessions signed before the switch to genesis-hash IDs carry `solana:devnet`. The
|
|
472
|
+
* cluster table is `SOLANA_CHAIN_IDS` of `@tuwaio/orbit-core`, read through its `getSolanaChainId`.
|
|
473
|
+
*
|
|
474
|
+
* @param chainId - A CAIP-2 chain ID.
|
|
475
|
+
* @returns The genesis-hash chain ID for a known Solana cluster name; any other value unchanged (genesis-hash IDs,
|
|
476
|
+
* `solana:localnet`, other namespaces, bare references).
|
|
477
|
+
*
|
|
478
|
+
* @example
|
|
479
|
+
* ```ts
|
|
480
|
+
* normalizeSolanaChainId('solana:devnet'); // "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1"
|
|
481
|
+
* normalizeSolanaChainId('eip155:1'); // "eip155:1"
|
|
482
|
+
* ```
|
|
483
|
+
*/
|
|
484
|
+
declare function normalizeSolanaChainId(chainId: string): string;
|
|
485
|
+
/**
|
|
486
|
+
* Checks a chain ID against the `allowedChainIds` of a verification policy. Chain IDs must match exactly, so `eip155:1`
|
|
487
|
+
* never allows `solana:1` or a bare `1`; the only exception is a Solana cluster, which matches under its name and its
|
|
488
|
+
* genesis-hash chain ID (see {@link normalizeSolanaChainId}).
|
|
489
|
+
*
|
|
490
|
+
* @param chainId - The CAIP-2 chain ID of a message or session.
|
|
491
|
+
* @param allowedChainIds - The allowed CAIP-2 chain IDs. Missing or empty allows every chain.
|
|
492
|
+
* @returns `true` when the chain is allowed.
|
|
493
|
+
*
|
|
494
|
+
* @example
|
|
495
|
+
* ```ts
|
|
496
|
+
* isChainIdAllowed('solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1', ['solana:devnet']); // true
|
|
497
|
+
* isChainIdAllowed('eip155:1', ['eip155:8453']); // false
|
|
498
|
+
* ```
|
|
499
|
+
*/
|
|
500
|
+
declare function isChainIdAllowed(chainId: string, allowedChainIds?: readonly string[]): boolean;
|
|
501
|
+
|
|
464
502
|
/**
|
|
465
503
|
* @file CAIP-122 message field validators.
|
|
466
504
|
* Provides individual validators and a composite `validateMessage` function.
|
|
@@ -535,9 +573,12 @@ interface SiwxSessionLike {
|
|
|
535
573
|
* Checks whether a SIWX session belongs to a given wallet address and, optionally, chain. Use it on the server to
|
|
536
574
|
* make sure the signed-in account is the one a request acts on.
|
|
537
575
|
*
|
|
538
|
-
*
|
|
539
|
-
*
|
|
540
|
-
*
|
|
576
|
+
* The session account is read with `parseCaip10AccountId` of `@tuwaio/orbit-core`; a session whose account is not a
|
|
577
|
+
* valid `eip155` or `solana` CAIP-10 account ID never matches. A CAIP-10 target must have the session's namespace (any
|
|
578
|
+
* of its chains); a plain target that starts with `0x` only matches `eip155:` sessions, any other plain target only
|
|
579
|
+
* `solana:` sessions. EVM accounts are compared case-insensitively, Solana accounts case-sensitively. The chain is
|
|
580
|
+
* compared only when `targetChainId` is given and the session has a `chainId`; a Solana cluster matches under its name
|
|
581
|
+
* (`devnet`, `solana:devnet`) and its genesis-hash chain ID (see {@link normalizeSolanaChainId}).
|
|
541
582
|
*
|
|
542
583
|
* @param session - The session or parsed message to check. `null` and `undefined` never match.
|
|
543
584
|
* @param targetAddress - The expected account, as a plain address or a CAIP-10 account ID.
|
|
@@ -554,4 +595,4 @@ interface SiwxSessionLike {
|
|
|
554
595
|
*/
|
|
555
596
|
declare function isSessionMatchingTarget(session: SiwxSessionLike | null | undefined, targetAddress: string, targetChainId?: string | number): boolean;
|
|
556
597
|
|
|
557
|
-
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 };
|
|
598
|
+
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, isChainIdAllowed, isSessionMatchingTarget, normalizeSolanaChainId, parseMessage, validateMessage, validatePolicy };
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
'use strict';function
|
|
2
|
-
`)}var m=class extends Error{constructor(
|
|
3
|
-
`);if(t.length<5)throw new f("Message is too short to be a valid CAIP-122 message.");let
|
|
4
|
-
`))return "domain must not contain newline characters."}function
|
|
5
|
-
`)&&
|
|
1
|
+
'use strict';var orbitCore=require('@tuwaio/orbit-core');function O(e){let{domain:t,address:i,statement:n,uri:a,version:r,chainId:o,nonce:s,issuedAt:c,expirationTime:p,notBefore:d,requestId:u,resources:x}=e,l=[`${t} wants you to sign in with your blockchain account:`,i,""];if(n&&l.push(n,""),l.push(`URI: ${a}`,`Version: ${r}`,`Chain ID: ${o}`,`Nonce: ${s}`,`Issued At: ${c}`),p&&l.push(`Expiration Time: ${p}`),d&&l.push(`Not Before: ${d}`),u&&l.push(`Request ID: ${u}`),x&&x.length>0){l.push("Resources:");for(let P of x)l.push(`- ${P}`);}return l.join(`
|
|
2
|
+
`)}var m=class extends Error{constructor(i,n="SIWX_ERROR"){super(i);this.code=n;this.name="SiwxError",Object.setPrototypeOf(this,new.target.prototype);}code},f=class extends m{constructor(t){super(t,"SIWX_PARSE_ERROR"),this.name="SiwxParseError";}},S=class extends m{constructor(i){super(`CAIP-122 message validation failed: ${i.join(", ")}`,"SIWX_VALIDATION_ERROR");this.errors=i;this.name="SiwxValidationError";}errors},w=class extends m{constructor(t){super(t,"SIWX_VERIFICATION_ERROR"),this.name="SiwxVerificationError";}},I=class extends m{constructor(i){super(`SIWX session expired at ${i}`,"SIWX_EXPIRED_SESSION");this.expirationTime=i;this.name="SiwxExpiredSessionError";}expirationTime},E=class extends m{constructor(i){super(`Nonce has already been used: ${i}`,"SIWX_NONCE_REPLAY");this.nonce=i;this.name="SiwxNonceReplayError";}nonce},A=class extends m{constructor(i){super(`Unsupported CAIP-2 namespace: "${i}". Supported: eip155, solana`,"SIWX_UNSUPPORTED_NAMESPACE");this.namespace=i;this.name="SiwxUnsupportedNamespaceError";}namespace},g=class extends m{constructor(t,i="SIWX_POLICY_VIOLATION"){super(t,i),this.name="SiwxPolicyViolationError";}},$=class extends g{constructor(i,n){let a=Array.isArray(i)?i.join(", "):i;super(`Domain mismatch. Expected: [${a}], Received: "${n}"`,"SIWX_DOMAIN_MISMATCH");this.expected=i;this.received=n;this.name="SiwxDomainMismatchError";}expected;received},R=class extends g{constructor(i,n){let a=Array.isArray(i)?i.join(", "):i;super(`URI mismatch. Expected: [${a}], Received: "${n}"`,"SIWX_URI_MISMATCH");this.expected=i;this.received=n;this.name="SiwxUriMismatchError";}expected;received},y=class extends g{constructor(i,n){super(`Chain ID "${n}" is not allowed. Allowed: [${i.join(", ")}]`,"SIWX_CHAIN_NOT_ALLOWED");this.allowedChainIds=i;this.received=n;this.name="SiwxChainNotAllowedError";}allowedChainIds;received},b=class extends g{constructor(i,n){super(`Message issuedAt "${i}" is older than the allowed max age of ${n} seconds`,"SIWX_ISSUED_AT_STALE");this.issuedAt=i;this.maxAgeSeconds=n;this.name="SiwxIssuedAtStaleError";}issuedAt;maxAgeSeconds},M=class extends g{constructor(i,n){super(`Message issuedAt "${i}" is in the future beyond allowed clock skew of ${n} seconds`,"SIWX_ISSUED_AT_FUTURE");this.issuedAt=i;this.clockSkewSeconds=n;this.name="SiwxIssuedAtFutureError";}issuedAt;clockSkewSeconds},T=class extends g{constructor(i){super(`Message not valid before ${i}`,"SIWX_NOT_BEFORE");this.notBefore=i;this.name="SiwxNotBeforeError";}notBefore},C=class extends g{constructor(i,n){super(`Session lifetime of ${i} seconds exceeds maximum allowed lifetime of ${n} seconds`,"SIWX_SESSION_LIFETIME_EXCEEDED");this.lifetimeSeconds=i;this.maxLifetimeSeconds=n;this.name="SiwxSessionLifetimeExceededError";}lifetimeSeconds;maxLifetimeSeconds};var k=/^(?<domain>.+) wants you to sign in with your blockchain account:$/,v=/^(?<key>[A-Za-z ]+): (?<value>.+)$/,L=/^- (?<resource>.+)$/;function X(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 i=t[0]?.match(k);if(!i?.groups?.domain)throw new f('Invalid CAIP-122 header line. Expected: "{domain} wants you to sign in with your blockchain account:"');let n=i.groups.domain,a=t[1];if(!a)throw new f("Missing address on line 2.");if(t[2]!=="")throw new f("Expected blank line after address (line 3).");let r=3,o;if(t[r]&&!v.test(t[r])){if(o=t[r],r++,t[r]!=="")throw new f("Expected blank line after statement.");r++;}let s={},c=[],p=false;for(;r<t.length;){let u=t[r];if(u===void 0){r++;continue}if(u==="Resources:"){p=true,r++;continue}if(p){let l=u.match(L);if(l?.groups?.resource){c.push(l.groups.resource),r++;continue}p=false;}let x=u.match(v);x?.groups?.key&&x.groups.value&&(s[x.groups.key]=x.groups.value),r++;}let d=["URI","Version","Chain ID","Nonce","Issued At"];for(let u of d)if(!s[u])throw new f(`Missing required field in CAIP-122 message: "${u}"`);return {domain:n,address:a,statement:o,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:c.length>0?c:void 0}}function h(e){return e.startsWith("solana:")?orbitCore.getSolanaChainId(e)??e:e}function D(e,t){if(!t||t.length===0)return true;let i=h(e);return t.some(n=>h(n)===i)}var B=/^https?:\/\/.+/,F=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;function G(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 j(e){if(!orbitCore.parseCaip10AccountId(e))return `address must be CAIP-10 compliant (namespace:chainRef:address). Got: "${e}"`}function q(e){if(!B.test(e))return `uri must be a valid RFC 3986 URI starting with http(s)://. Got: "${e}"`}function z(e){if(!orbitCore.parseCaip2ChainId(e))return `chainId must be a valid CAIP-2 identifier (namespace:reference). Got: "${e}"`}function H(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(!F.test(e))return `${t} must be a valid ISO 8601 datetime string. Got: "${e}"`}function Z(e,t=new Date,i=0){let n=new Date(e);if(isNaN(n.getTime()))return `expirationTime is not a valid date: "${e}"`;if(n.getTime()+i*1e3<t.getTime())return `Message has expired. expirationTime was: ${e}`}function U(e,t,i=new Date){if(!t)return [];let n=[];if(t.expectedDomain!==void 0){let o=Array.isArray(t.expectedDomain)?t.expectedDomain:[t.expectedDomain];o.some(c=>c.toLowerCase()===e.domain.toLowerCase())||n.push(`Domain mismatch. Expected: [${o.join(", ")}], Received: "${e.domain}"`);}if(t.expectedUri!==void 0){let o=Array.isArray(t.expectedUri)?t.expectedUri:[t.expectedUri];o.some(c=>{if(e.uri===c)return true;let p=c.endsWith("/")?c.slice(0,-1):c;if(e.uri.startsWith(`${p}/`))return true;try{let d=new URL(e.uri),u=new URL(c);return d.origin.toLowerCase()===u.origin.toLowerCase()}catch{return false}})||n.push(`URI mismatch. Expected: [${o.join(", ")}], Received: "${e.uri}"`);}D(e.chainId,t.allowedChainIds)||n.push(`Chain ID "${e.chainId}" is not allowed. Allowed: [${t.allowedChainIds?.join(", ")}]`),t.requireExpirationTime&&!e.expirationTime&&n.push("expirationTime is required by verification policy.");let a=t.clockSkewSeconds??60,r=new Date(e.issuedAt);if(isNaN(r.getTime())||(t.maxIssuedAtAgeSeconds!==void 0&&(i.getTime()-r.getTime())/1e3>t.maxIssuedAtAgeSeconds+a&&n.push(`Message issuedAt "${e.issuedAt}" is older than the allowed max age of ${t.maxIssuedAtAgeSeconds} seconds`),r.getTime()-i.getTime()>a*1e3&&n.push(`Message issuedAt "${e.issuedAt}" is in the future beyond allowed clock skew of ${a} seconds`)),e.notBefore&&t.enforceNotBefore!==false){let o=new Date(e.notBefore);isNaN(o.getTime())||o.getTime()-i.getTime()>a*1e3&&n.push(`Message not valid before ${e.notBefore}`);}if(t.maxSessionLifetimeSeconds!==void 0&&e.expirationTime){let o=new Date(e.expirationTime);if(!isNaN(o.getTime())&&!isNaN(r.getTime())){let s=(o.getTime()-r.getTime())/1e3;s>t.maxSessionLifetimeSeconds&&n.push(`Session lifetime of ${s} seconds exceeds maximum allowed lifetime of ${t.maxSessionLifetimeSeconds} seconds`);}}return n}function Y(e,t){let i=[],n=G(e.domain);n&&i.push(n);let a=j(e.address);a&&i.push(a);let r=q(e.uri);r&&i.push(r),e.version!=="1"&&i.push(`version must be "1". Got: "${e.version}"`);let o=z(e.chainId);o&&i.push(o);let s=H(e.nonce);s&&i.push(s);let c=_(e.issuedAt,"issuedAt");c&&i.push(c);let p=t?.policy?.clockSkewSeconds??60;if(e.expirationTime){let d=_(e.expirationTime,"expirationTime");if(d)i.push(d);else if(!t?.skipExpiration){let u=Z(e.expirationTime,new Date,p);u&&i.push(u);}}if(e.notBefore){let d=_(e.notBefore,"notBefore");d&&i.push(d);}return e.statement&&e.statement.includes(`
|
|
5
|
+
`)&&i.push("statement must not contain newline characters."),i.push(...U(e,t?.policy??{})),{valid:i.length===0,errors:i}}function J(){let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function K(e,t,i){if(!e||!e.address||!t)return false;let n=orbitCore.parseCaip10AccountId(e.address);if(!n||n.namespace!=="eip155"&&n.namespace!=="solana")return false;let a=n.namespace==="eip155",r=t;if(t.includes(":")){let s=orbitCore.parseCaip10AccountId(t);if(s?.namespace!==n.namespace)return false;r=s.address;}else if(t.startsWith("0x")!==a)return false;if(!(a?n.address.toLowerCase()===r.toLowerCase():n.address===r))return false;if(i!=null&&e.chainId){let s=String(i),c=h(s.includes(":")?s:`${n.namespace}:${s}`);if(h(e.chainId)!==c&&e.chainId!==s)return false}return true}exports.SiwxChainNotAllowedError=y;exports.SiwxDomainMismatchError=$;exports.SiwxError=m;exports.SiwxExpiredSessionError=I;exports.SiwxIssuedAtFutureError=M;exports.SiwxIssuedAtStaleError=b;exports.SiwxNonceReplayError=E;exports.SiwxNotBeforeError=T;exports.SiwxParseError=f;exports.SiwxPolicyViolationError=g;exports.SiwxSessionLifetimeExceededError=C;exports.SiwxUnsupportedNamespaceError=A;exports.SiwxUriMismatchError=R;exports.SiwxValidationError=S;exports.SiwxVerificationError=w;exports.buildMessage=O;exports.generateNonce=J;exports.isChainIdAllowed=D;exports.isSessionMatchingTarget=K;exports.normalizeSolanaChainId=h;exports.parseMessage=X;exports.validateMessage=Y;exports.validatePolicy=U;
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
function
|
|
2
|
-
`)}var m=class extends Error{constructor(
|
|
3
|
-
`);if(t.length<5)throw new f("Message is too short to be a valid CAIP-122 message.");let
|
|
4
|
-
`))return "domain must not contain newline characters."}function
|
|
5
|
-
`)&&
|
|
1
|
+
import {getSolanaChainId,parseCaip10AccountId,parseCaip2ChainId}from'@tuwaio/orbit-core';function O(e){let{domain:t,address:i,statement:n,uri:a,version:r,chainId:o,nonce:s,issuedAt:c,expirationTime:p,notBefore:d,requestId:u,resources:x}=e,l=[`${t} wants you to sign in with your blockchain account:`,i,""];if(n&&l.push(n,""),l.push(`URI: ${a}`,`Version: ${r}`,`Chain ID: ${o}`,`Nonce: ${s}`,`Issued At: ${c}`),p&&l.push(`Expiration Time: ${p}`),d&&l.push(`Not Before: ${d}`),u&&l.push(`Request ID: ${u}`),x&&x.length>0){l.push("Resources:");for(let P of x)l.push(`- ${P}`);}return l.join(`
|
|
2
|
+
`)}var m=class extends Error{constructor(i,n="SIWX_ERROR"){super(i);this.code=n;this.name="SiwxError",Object.setPrototypeOf(this,new.target.prototype);}code},f=class extends m{constructor(t){super(t,"SIWX_PARSE_ERROR"),this.name="SiwxParseError";}},S=class extends m{constructor(i){super(`CAIP-122 message validation failed: ${i.join(", ")}`,"SIWX_VALIDATION_ERROR");this.errors=i;this.name="SiwxValidationError";}errors},w=class extends m{constructor(t){super(t,"SIWX_VERIFICATION_ERROR"),this.name="SiwxVerificationError";}},I=class extends m{constructor(i){super(`SIWX session expired at ${i}`,"SIWX_EXPIRED_SESSION");this.expirationTime=i;this.name="SiwxExpiredSessionError";}expirationTime},E=class extends m{constructor(i){super(`Nonce has already been used: ${i}`,"SIWX_NONCE_REPLAY");this.nonce=i;this.name="SiwxNonceReplayError";}nonce},A=class extends m{constructor(i){super(`Unsupported CAIP-2 namespace: "${i}". Supported: eip155, solana`,"SIWX_UNSUPPORTED_NAMESPACE");this.namespace=i;this.name="SiwxUnsupportedNamespaceError";}namespace},g=class extends m{constructor(t,i="SIWX_POLICY_VIOLATION"){super(t,i),this.name="SiwxPolicyViolationError";}},$=class extends g{constructor(i,n){let a=Array.isArray(i)?i.join(", "):i;super(`Domain mismatch. Expected: [${a}], Received: "${n}"`,"SIWX_DOMAIN_MISMATCH");this.expected=i;this.received=n;this.name="SiwxDomainMismatchError";}expected;received},R=class extends g{constructor(i,n){let a=Array.isArray(i)?i.join(", "):i;super(`URI mismatch. Expected: [${a}], Received: "${n}"`,"SIWX_URI_MISMATCH");this.expected=i;this.received=n;this.name="SiwxUriMismatchError";}expected;received},y=class extends g{constructor(i,n){super(`Chain ID "${n}" is not allowed. Allowed: [${i.join(", ")}]`,"SIWX_CHAIN_NOT_ALLOWED");this.allowedChainIds=i;this.received=n;this.name="SiwxChainNotAllowedError";}allowedChainIds;received},b=class extends g{constructor(i,n){super(`Message issuedAt "${i}" is older than the allowed max age of ${n} seconds`,"SIWX_ISSUED_AT_STALE");this.issuedAt=i;this.maxAgeSeconds=n;this.name="SiwxIssuedAtStaleError";}issuedAt;maxAgeSeconds},M=class extends g{constructor(i,n){super(`Message issuedAt "${i}" is in the future beyond allowed clock skew of ${n} seconds`,"SIWX_ISSUED_AT_FUTURE");this.issuedAt=i;this.clockSkewSeconds=n;this.name="SiwxIssuedAtFutureError";}issuedAt;clockSkewSeconds},T=class extends g{constructor(i){super(`Message not valid before ${i}`,"SIWX_NOT_BEFORE");this.notBefore=i;this.name="SiwxNotBeforeError";}notBefore},C=class extends g{constructor(i,n){super(`Session lifetime of ${i} seconds exceeds maximum allowed lifetime of ${n} seconds`,"SIWX_SESSION_LIFETIME_EXCEEDED");this.lifetimeSeconds=i;this.maxLifetimeSeconds=n;this.name="SiwxSessionLifetimeExceededError";}lifetimeSeconds;maxLifetimeSeconds};var k=/^(?<domain>.+) wants you to sign in with your blockchain account:$/,v=/^(?<key>[A-Za-z ]+): (?<value>.+)$/,L=/^- (?<resource>.+)$/;function X(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 i=t[0]?.match(k);if(!i?.groups?.domain)throw new f('Invalid CAIP-122 header line. Expected: "{domain} wants you to sign in with your blockchain account:"');let n=i.groups.domain,a=t[1];if(!a)throw new f("Missing address on line 2.");if(t[2]!=="")throw new f("Expected blank line after address (line 3).");let r=3,o;if(t[r]&&!v.test(t[r])){if(o=t[r],r++,t[r]!=="")throw new f("Expected blank line after statement.");r++;}let s={},c=[],p=false;for(;r<t.length;){let u=t[r];if(u===void 0){r++;continue}if(u==="Resources:"){p=true,r++;continue}if(p){let l=u.match(L);if(l?.groups?.resource){c.push(l.groups.resource),r++;continue}p=false;}let x=u.match(v);x?.groups?.key&&x.groups.value&&(s[x.groups.key]=x.groups.value),r++;}let d=["URI","Version","Chain ID","Nonce","Issued At"];for(let u of d)if(!s[u])throw new f(`Missing required field in CAIP-122 message: "${u}"`);return {domain:n,address:a,statement:o,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:c.length>0?c:void 0}}function h(e){return e.startsWith("solana:")?getSolanaChainId(e)??e:e}function D(e,t){if(!t||t.length===0)return true;let i=h(e);return t.some(n=>h(n)===i)}var B=/^https?:\/\/.+/,F=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;function G(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 j(e){if(!parseCaip10AccountId(e))return `address must be CAIP-10 compliant (namespace:chainRef:address). Got: "${e}"`}function q(e){if(!B.test(e))return `uri must be a valid RFC 3986 URI starting with http(s)://. Got: "${e}"`}function z(e){if(!parseCaip2ChainId(e))return `chainId must be a valid CAIP-2 identifier (namespace:reference). Got: "${e}"`}function H(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(!F.test(e))return `${t} must be a valid ISO 8601 datetime string. Got: "${e}"`}function Z(e,t=new Date,i=0){let n=new Date(e);if(isNaN(n.getTime()))return `expirationTime is not a valid date: "${e}"`;if(n.getTime()+i*1e3<t.getTime())return `Message has expired. expirationTime was: ${e}`}function U(e,t,i=new Date){if(!t)return [];let n=[];if(t.expectedDomain!==void 0){let o=Array.isArray(t.expectedDomain)?t.expectedDomain:[t.expectedDomain];o.some(c=>c.toLowerCase()===e.domain.toLowerCase())||n.push(`Domain mismatch. Expected: [${o.join(", ")}], Received: "${e.domain}"`);}if(t.expectedUri!==void 0){let o=Array.isArray(t.expectedUri)?t.expectedUri:[t.expectedUri];o.some(c=>{if(e.uri===c)return true;let p=c.endsWith("/")?c.slice(0,-1):c;if(e.uri.startsWith(`${p}/`))return true;try{let d=new URL(e.uri),u=new URL(c);return d.origin.toLowerCase()===u.origin.toLowerCase()}catch{return false}})||n.push(`URI mismatch. Expected: [${o.join(", ")}], Received: "${e.uri}"`);}D(e.chainId,t.allowedChainIds)||n.push(`Chain ID "${e.chainId}" is not allowed. Allowed: [${t.allowedChainIds?.join(", ")}]`),t.requireExpirationTime&&!e.expirationTime&&n.push("expirationTime is required by verification policy.");let a=t.clockSkewSeconds??60,r=new Date(e.issuedAt);if(isNaN(r.getTime())||(t.maxIssuedAtAgeSeconds!==void 0&&(i.getTime()-r.getTime())/1e3>t.maxIssuedAtAgeSeconds+a&&n.push(`Message issuedAt "${e.issuedAt}" is older than the allowed max age of ${t.maxIssuedAtAgeSeconds} seconds`),r.getTime()-i.getTime()>a*1e3&&n.push(`Message issuedAt "${e.issuedAt}" is in the future beyond allowed clock skew of ${a} seconds`)),e.notBefore&&t.enforceNotBefore!==false){let o=new Date(e.notBefore);isNaN(o.getTime())||o.getTime()-i.getTime()>a*1e3&&n.push(`Message not valid before ${e.notBefore}`);}if(t.maxSessionLifetimeSeconds!==void 0&&e.expirationTime){let o=new Date(e.expirationTime);if(!isNaN(o.getTime())&&!isNaN(r.getTime())){let s=(o.getTime()-r.getTime())/1e3;s>t.maxSessionLifetimeSeconds&&n.push(`Session lifetime of ${s} seconds exceeds maximum allowed lifetime of ${t.maxSessionLifetimeSeconds} seconds`);}}return n}function Y(e,t){let i=[],n=G(e.domain);n&&i.push(n);let a=j(e.address);a&&i.push(a);let r=q(e.uri);r&&i.push(r),e.version!=="1"&&i.push(`version must be "1". Got: "${e.version}"`);let o=z(e.chainId);o&&i.push(o);let s=H(e.nonce);s&&i.push(s);let c=_(e.issuedAt,"issuedAt");c&&i.push(c);let p=t?.policy?.clockSkewSeconds??60;if(e.expirationTime){let d=_(e.expirationTime,"expirationTime");if(d)i.push(d);else if(!t?.skipExpiration){let u=Z(e.expirationTime,new Date,p);u&&i.push(u);}}if(e.notBefore){let d=_(e.notBefore,"notBefore");d&&i.push(d);}return e.statement&&e.statement.includes(`
|
|
5
|
+
`)&&i.push("statement must not contain newline characters."),i.push(...U(e,t?.policy??{})),{valid:i.length===0,errors:i}}function J(){let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function K(e,t,i){if(!e||!e.address||!t)return false;let n=parseCaip10AccountId(e.address);if(!n||n.namespace!=="eip155"&&n.namespace!=="solana")return false;let a=n.namespace==="eip155",r=t;if(t.includes(":")){let s=parseCaip10AccountId(t);if(s?.namespace!==n.namespace)return false;r=s.address;}else if(t.startsWith("0x")!==a)return false;if(!(a?n.address.toLowerCase()===r.toLowerCase():n.address===r))return false;if(i!=null&&e.chainId){let s=String(i),c=h(s.includes(":")?s:`${n.namespace}:${s}`);if(h(e.chainId)!==c&&e.chainId!==s)return false}return true}export{y as SiwxChainNotAllowedError,$ as SiwxDomainMismatchError,m as SiwxError,I as SiwxExpiredSessionError,M as SiwxIssuedAtFutureError,b as SiwxIssuedAtStaleError,E as SiwxNonceReplayError,T as SiwxNotBeforeError,f as SiwxParseError,g as SiwxPolicyViolationError,C as SiwxSessionLifetimeExceededError,A as SiwxUnsupportedNamespaceError,R as SiwxUriMismatchError,S as SiwxValidationError,w as SiwxVerificationError,O as buildMessage,J as generateNonce,D as isChainIdAllowed,K as isSessionMatchingTarget,h as normalizeSolanaChainId,X as parseMessage,Y as validateMessage,U as validatePolicy};
|
package/package.json
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tuwaio/siwx-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"author": "Oleksandr Tkach",
|
|
6
6
|
"license": "Apache-2.0",
|
|
7
|
-
"description": "L1 core of SIWX (TUWA):
|
|
7
|
+
"description": "L1 core of SIWX (TUWA): CAIP-122 sign-in message builder, parser and validator with verification policies, session matching, nonces and typed errors for EVM and Solana.",
|
|
8
8
|
"main": "./dist/index.js",
|
|
9
9
|
"module": "./dist/index.mjs",
|
|
10
10
|
"types": "./dist/index.d.ts",
|
|
@@ -44,7 +44,11 @@
|
|
|
44
44
|
"url": "https://github.com/Argeare5"
|
|
45
45
|
}
|
|
46
46
|
],
|
|
47
|
+
"peerDependencies": {
|
|
48
|
+
"@tuwaio/orbit-core": ">=0.5"
|
|
49
|
+
},
|
|
47
50
|
"devDependencies": {
|
|
51
|
+
"@tuwaio/orbit-core": "^0.5.0",
|
|
48
52
|
"tsup": "^8.5.1",
|
|
49
53
|
"typescript": "6.0.3"
|
|
50
54
|
},
|