@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 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
- The package has **zero runtime dependencies** and imports no Web3 SDK. It runs in browsers, Node.js 20+ and edge runtimes; only `generateNonce` needs the Web Crypto API.
8
+ 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). An empty array allows every chain.
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
- * A target that starts with `0x` or `eip155:` is treated as EVM and only matches `eip155:` sessions, compared
539
- * case-insensitively; any other target only matches `solana:` sessions, compared case-sensitively. The chain is
540
- * compared only when `targetChainId` is given and the session has a `chainId`.
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). An empty array allows every chain.
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
- * A target that starts with `0x` or `eip155:` is treated as EVM and only matches `eip155:` sessions, compared
539
- * case-insensitively; any other target only matches `solana:` sessions, compared case-sensitively. The chain is
540
- * compared only when `targetChainId` is given and the session has a `chainId`.
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 v(e){let{domain:t,address:s,statement:i,uri:a,version:n,chainId:r,nonce:o,issuedAt:d,expirationTime:l,notBefore:c,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: ${a}`,`Version: ${n}`,`Chain ID: ${r}`,`Nonce: ${o}`,`Issued At: ${d}`),l&&p.push(`Expiration Time: ${l}`),c&&p.push(`Not Before: ${c}`),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},I=class extends m{constructor(s){super(`Nonce has already been used: ${s}`,"SIWX_NONCE_REPLAY");this.nonce=s;this.name="SiwxNonceReplayError";}nonce},E=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 a=Array.isArray(s)?s.join(", "):s;super(`Domain mismatch. Expected: [${a}], Received: "${i}"`,"SIWX_DOMAIN_MISMATCH");this.expected=s;this.received=i;this.name="SiwxDomainMismatchError";}expected;received},$=class extends g{constructor(s,i){let a=Array.isArray(s)?s.join(", "):s;super(`URI mismatch. Expected: [${a}], 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},b=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},M=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},y=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,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 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 c=["URI","Version","Chain ID","Nonce","Issued At"];for(let u of c)if(!o[u])throw new f(`Missing required field in CAIP-122 message: "${u}"`);return {domain:i,address:a,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 c=new URL(e.uri),u=new URL(d);return c.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 a=t.clockSkewSeconds??60,n=new Date(e.issuedAt);if(isNaN(n.getTime())||(t.maxIssuedAtAgeSeconds!==void 0&&(s.getTime()-n.getTime())/1e3>t.maxIssuedAtAgeSeconds+a&&i.push(`Message issuedAt "${e.issuedAt}" is older than the allowed max age of ${t.maxIssuedAtAgeSeconds} seconds`),n.getTime()-s.getTime()>a*1e3&&i.push(`Message issuedAt "${e.issuedAt}" is in the future beyond allowed clock skew of ${a} seconds`)),e.notBefore&&t.enforceNotBefore!==false){let r=new Date(e.notBefore);isNaN(r.getTime())||r.getTime()-s.getTime()>a*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 a=B(e.address);a&&s.push(a);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 c=_(e.expirationTime,"expirationTime");if(c)s.push(c);else if(!t?.skipExpiration){let u=q(e.expirationTime,new Date,l);u&&s.push(u);}}if(e.notBefore){let c=_(e.notBefore,"notBefore");c&&s.push(c);}return e.statement&&e.statement.includes(`
5
- `)&&s.push("statement must not contain newline characters."),s.push(...D(e,t?.policy??{})),{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,a=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&&!a||!d&&!n||!(a?o.toLowerCase()===r.toLowerCase():o===r))return false;if(s!=null){let c=String(s),u=a?c.startsWith("eip155:")?c:`eip155:${c}`:c.startsWith("solana:")?c:`solana:${c}`;if(e.chainId&&e.chainId!==u&&e.chainId!==c)return false}return true}exports.SiwxChainNotAllowedError=R;exports.SiwxDomainMismatchError=A;exports.SiwxError=m;exports.SiwxExpiredSessionError=w;exports.SiwxIssuedAtFutureError=M;exports.SiwxIssuedAtStaleError=b;exports.SiwxNonceReplayError=I;exports.SiwxNotBeforeError=y;exports.SiwxParseError=f;exports.SiwxPolicyViolationError=g;exports.SiwxSessionLifetimeExceededError=T;exports.SiwxUnsupportedNamespaceError=E;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;
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 v(e){let{domain:t,address:s,statement:i,uri:a,version:n,chainId:r,nonce:o,issuedAt:d,expirationTime:l,notBefore:c,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: ${a}`,`Version: ${n}`,`Chain ID: ${r}`,`Nonce: ${o}`,`Issued At: ${d}`),l&&p.push(`Expiration Time: ${l}`),c&&p.push(`Not Before: ${c}`),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},I=class extends m{constructor(s){super(`Nonce has already been used: ${s}`,"SIWX_NONCE_REPLAY");this.nonce=s;this.name="SiwxNonceReplayError";}nonce},E=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 a=Array.isArray(s)?s.join(", "):s;super(`Domain mismatch. Expected: [${a}], Received: "${i}"`,"SIWX_DOMAIN_MISMATCH");this.expected=s;this.received=i;this.name="SiwxDomainMismatchError";}expected;received},$=class extends g{constructor(s,i){let a=Array.isArray(s)?s.join(", "):s;super(`URI mismatch. Expected: [${a}], 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},b=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},M=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},y=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,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 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 c=["URI","Version","Chain ID","Nonce","Issued At"];for(let u of c)if(!o[u])throw new f(`Missing required field in CAIP-122 message: "${u}"`);return {domain:i,address:a,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 c=new URL(e.uri),u=new URL(d);return c.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 a=t.clockSkewSeconds??60,n=new Date(e.issuedAt);if(isNaN(n.getTime())||(t.maxIssuedAtAgeSeconds!==void 0&&(s.getTime()-n.getTime())/1e3>t.maxIssuedAtAgeSeconds+a&&i.push(`Message issuedAt "${e.issuedAt}" is older than the allowed max age of ${t.maxIssuedAtAgeSeconds} seconds`),n.getTime()-s.getTime()>a*1e3&&i.push(`Message issuedAt "${e.issuedAt}" is in the future beyond allowed clock skew of ${a} seconds`)),e.notBefore&&t.enforceNotBefore!==false){let r=new Date(e.notBefore);isNaN(r.getTime())||r.getTime()-s.getTime()>a*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 a=B(e.address);a&&s.push(a);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 c=_(e.expirationTime,"expirationTime");if(c)s.push(c);else if(!t?.skipExpiration){let u=q(e.expirationTime,new Date,l);u&&s.push(u);}}if(e.notBefore){let c=_(e.notBefore,"notBefore");c&&s.push(c);}return e.statement&&e.statement.includes(`
5
- `)&&s.push("statement must not contain newline characters."),s.push(...D(e,t?.policy??{})),{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,a=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&&!a||!d&&!n||!(a?o.toLowerCase()===r.toLowerCase():o===r))return false;if(s!=null){let c=String(s),u=a?c.startsWith("eip155:")?c:`eip155:${c}`:c.startsWith("solana:")?c:`solana:${c}`;if(e.chainId&&e.chainId!==u&&e.chainId!==c)return false}return true}export{R as SiwxChainNotAllowedError,A as SiwxDomainMismatchError,m as SiwxError,w as SiwxExpiredSessionError,M as SiwxIssuedAtFutureError,b as SiwxIssuedAtStaleError,I as SiwxNonceReplayError,y as SiwxNotBeforeError,f as SiwxParseError,g as SiwxPolicyViolationError,T as SiwxSessionLifetimeExceededError,E 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};
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.4.1",
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): zero-dependency CAIP-122 sign-in message builder, parser and validator with verification policies, session matching, nonces and typed errors for EVM and Solana.",
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
  },