@tuwaio/siwx-core 0.4.0 → 0.5.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
@@ -81,7 +81,7 @@ const result = validateMessage(parseMessage(message), {
81
81
  policy: {
82
82
  expectedDomain: 'app.tuwa.io',
83
83
  expectedUri: 'https://app.tuwa.io',
84
- allowedChainIds: ['eip155:1', 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpK'],
84
+ allowedChainIds: ['eip155:1', 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp'],
85
85
  requireExpirationTime: true,
86
86
  maxIssuedAtAgeSeconds: 300,
87
87
  maxSessionLifetimeSeconds: 24 * 60 * 60,
@@ -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
@@ -12,7 +12,7 @@ type SiwxChainNamespace = 'eip155' | 'solana';
12
12
  * A CAIP-2 chain ID in a supported namespace: `{namespace}:{reference}`.
13
13
  *
14
14
  * @example "eip155:1" (Ethereum Mainnet)
15
- * @example "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpK" (Solana Mainnet)
15
+ * @example "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp" (Solana Mainnet)
16
16
  */
17
17
  type SiwxChainId = `${SiwxChainNamespace}:${string}`;
18
18
  /**
@@ -110,8 +110,9 @@ 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.
114
- * @example ["eip155:1", "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpK"]
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.
115
+ * @example ["eip155:1", "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"]
115
116
  */
116
117
  allowedChainIds?: string[];
117
118
  /**
@@ -461,6 +462,42 @@ 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`.
472
+ *
473
+ * @param chainId - A CAIP-2 chain ID.
474
+ * @returns The genesis-hash chain ID for a known Solana cluster name; any other value unchanged (genesis-hash IDs,
475
+ * `solana:localnet`, other namespaces, bare references).
476
+ *
477
+ * @example
478
+ * ```ts
479
+ * normalizeSolanaChainId('solana:devnet'); // "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1"
480
+ * normalizeSolanaChainId('eip155:1'); // "eip155:1"
481
+ * ```
482
+ */
483
+ declare function normalizeSolanaChainId(chainId: string): string;
484
+ /**
485
+ * Checks a chain ID against the `allowedChainIds` of a verification policy. Chain IDs must match exactly, so `eip155:1`
486
+ * never allows `solana:1` or a bare `1`; the only exception is a Solana cluster, which matches under its name and its
487
+ * genesis-hash chain ID (see {@link normalizeSolanaChainId}).
488
+ *
489
+ * @param chainId - The CAIP-2 chain ID of a message or session.
490
+ * @param allowedChainIds - The allowed CAIP-2 chain IDs. Missing or empty allows every chain.
491
+ * @returns `true` when the chain is allowed.
492
+ *
493
+ * @example
494
+ * ```ts
495
+ * isChainIdAllowed('solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1', ['solana:devnet']); // true
496
+ * isChainIdAllowed('eip155:1', ['eip155:8453']); // false
497
+ * ```
498
+ */
499
+ declare function isChainIdAllowed(chainId: string, allowedChainIds?: readonly string[]): boolean;
500
+
464
501
  /**
465
502
  * @file CAIP-122 message field validators.
466
503
  * Provides individual validators and a composite `validateMessage` function.
@@ -537,7 +574,8 @@ interface SiwxSessionLike {
537
574
  *
538
575
  * A target that starts with `0x` or `eip155:` is treated as EVM and only matches `eip155:` sessions, compared
539
576
  * 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`.
577
+ * compared only when `targetChainId` is given and the session has a `chainId`; a Solana cluster matches under its name
578
+ * (`devnet`, `solana:devnet`) and its genesis-hash chain ID (see {@link normalizeSolanaChainId}).
541
579
  *
542
580
  * @param session - The session or parsed message to check. `null` and `undefined` never match.
543
581
  * @param targetAddress - The expected account, as a plain address or a CAIP-10 account ID.
@@ -554,4 +592,4 @@ interface SiwxSessionLike {
554
592
  */
555
593
  declare function isSessionMatchingTarget(session: SiwxSessionLike | null | undefined, targetAddress: string, targetChainId?: string | number): boolean;
556
594
 
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 };
595
+ 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
@@ -12,7 +12,7 @@ type SiwxChainNamespace = 'eip155' | 'solana';
12
12
  * A CAIP-2 chain ID in a supported namespace: `{namespace}:{reference}`.
13
13
  *
14
14
  * @example "eip155:1" (Ethereum Mainnet)
15
- * @example "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpK" (Solana Mainnet)
15
+ * @example "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp" (Solana Mainnet)
16
16
  */
17
17
  type SiwxChainId = `${SiwxChainNamespace}:${string}`;
18
18
  /**
@@ -110,8 +110,9 @@ 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.
114
- * @example ["eip155:1", "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpK"]
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.
115
+ * @example ["eip155:1", "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"]
115
116
  */
116
117
  allowedChainIds?: string[];
117
118
  /**
@@ -461,6 +462,42 @@ 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`.
472
+ *
473
+ * @param chainId - A CAIP-2 chain ID.
474
+ * @returns The genesis-hash chain ID for a known Solana cluster name; any other value unchanged (genesis-hash IDs,
475
+ * `solana:localnet`, other namespaces, bare references).
476
+ *
477
+ * @example
478
+ * ```ts
479
+ * normalizeSolanaChainId('solana:devnet'); // "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1"
480
+ * normalizeSolanaChainId('eip155:1'); // "eip155:1"
481
+ * ```
482
+ */
483
+ declare function normalizeSolanaChainId(chainId: string): string;
484
+ /**
485
+ * Checks a chain ID against the `allowedChainIds` of a verification policy. Chain IDs must match exactly, so `eip155:1`
486
+ * never allows `solana:1` or a bare `1`; the only exception is a Solana cluster, which matches under its name and its
487
+ * genesis-hash chain ID (see {@link normalizeSolanaChainId}).
488
+ *
489
+ * @param chainId - The CAIP-2 chain ID of a message or session.
490
+ * @param allowedChainIds - The allowed CAIP-2 chain IDs. Missing or empty allows every chain.
491
+ * @returns `true` when the chain is allowed.
492
+ *
493
+ * @example
494
+ * ```ts
495
+ * isChainIdAllowed('solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1', ['solana:devnet']); // true
496
+ * isChainIdAllowed('eip155:1', ['eip155:8453']); // false
497
+ * ```
498
+ */
499
+ declare function isChainIdAllowed(chainId: string, allowedChainIds?: readonly string[]): boolean;
500
+
464
501
  /**
465
502
  * @file CAIP-122 message field validators.
466
503
  * Provides individual validators and a composite `validateMessage` function.
@@ -537,7 +574,8 @@ interface SiwxSessionLike {
537
574
  *
538
575
  * A target that starts with `0x` or `eip155:` is treated as EVM and only matches `eip155:` sessions, compared
539
576
  * 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`.
577
+ * compared only when `targetChainId` is given and the session has a `chainId`; a Solana cluster matches under its name
578
+ * (`devnet`, `solana:devnet`) and its genesis-hash chain ID (see {@link normalizeSolanaChainId}).
541
579
  *
542
580
  * @param session - The session or parsed message to check. `null` and `undefined` never match.
543
581
  * @param targetAddress - The expected account, as a plain address or a CAIP-10 account ID.
@@ -554,4 +592,4 @@ interface SiwxSessionLike {
554
592
  */
555
593
  declare function isSessionMatchingTarget(session: SiwxSessionLike | null | undefined, targetAddress: string, targetChainId?: string | number): boolean;
556
594
 
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 };
595
+ 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';function L(e){let{domain:t,address:n,statement:s,uri:a,version:i,chainId:r,nonce:o,issuedAt:u,expirationTime:p,notBefore:c,requestId:d,resources:m}=e,l=[`${t} wants you to sign in with your blockchain account:`,n,""];if(s&&l.push(s,""),l.push(`URI: ${a}`,`Version: ${i}`,`Chain ID: ${r}`,`Nonce: ${o}`,`Issued At: ${u}`),p&&l.push(`Expiration Time: ${p}`),c&&l.push(`Not Before: ${c}`),d&&l.push(`Request ID: ${d}`),m&&m.length>0){l.push("Resources:");for(let k of m)l.push(`- ${k}`);}return l.join(`
2
+ `)}var f=class extends Error{constructor(n,s="SIWX_ERROR"){super(n);this.code=s;this.name="SiwxError",Object.setPrototypeOf(this,new.target.prototype);}code},g=class extends f{constructor(t){super(t,"SIWX_PARSE_ERROR"),this.name="SiwxParseError";}},S=class extends f{constructor(n){super(`CAIP-122 message validation failed: ${n.join(", ")}`,"SIWX_VALIDATION_ERROR");this.errors=n;this.name="SiwxValidationError";}errors},w=class extends f{constructor(t){super(t,"SIWX_VERIFICATION_ERROR"),this.name="SiwxVerificationError";}},E=class extends f{constructor(n){super(`SIWX session expired at ${n}`,"SIWX_EXPIRED_SESSION");this.expirationTime=n;this.name="SiwxExpiredSessionError";}expirationTime},I=class extends f{constructor(n){super(`Nonce has already been used: ${n}`,"SIWX_NONCE_REPLAY");this.nonce=n;this.name="SiwxNonceReplayError";}nonce},A=class extends f{constructor(n){super(`Unsupported CAIP-2 namespace: "${n}". Supported: eip155, solana`,"SIWX_UNSUPPORTED_NAMESPACE");this.namespace=n;this.name="SiwxUnsupportedNamespaceError";}namespace},h=class extends f{constructor(t,n="SIWX_POLICY_VIOLATION"){super(t,n),this.name="SiwxPolicyViolationError";}},R=class extends h{constructor(n,s){let a=Array.isArray(n)?n.join(", "):n;super(`Domain mismatch. Expected: [${a}], Received: "${s}"`,"SIWX_DOMAIN_MISMATCH");this.expected=n;this.received=s;this.name="SiwxDomainMismatchError";}expected;received},$=class extends h{constructor(n,s){let a=Array.isArray(n)?n.join(", "):n;super(`URI mismatch. Expected: [${a}], Received: "${s}"`,"SIWX_URI_MISMATCH");this.expected=n;this.received=s;this.name="SiwxUriMismatchError";}expected;received},y=class extends h{constructor(n,s){super(`Chain ID "${s}" is not allowed. Allowed: [${n.join(", ")}]`,"SIWX_CHAIN_NOT_ALLOWED");this.allowedChainIds=n;this.received=s;this.name="SiwxChainNotAllowedError";}allowedChainIds;received},T=class extends h{constructor(n,s){super(`Message issuedAt "${n}" is older than the allowed max age of ${s} seconds`,"SIWX_ISSUED_AT_STALE");this.issuedAt=n;this.maxAgeSeconds=s;this.name="SiwxIssuedAtStaleError";}issuedAt;maxAgeSeconds},b=class extends h{constructor(n,s){super(`Message issuedAt "${n}" is in the future beyond allowed clock skew of ${s} seconds`,"SIWX_ISSUED_AT_FUTURE");this.issuedAt=n;this.clockSkewSeconds=s;this.name="SiwxIssuedAtFutureError";}issuedAt;clockSkewSeconds},M=class extends h{constructor(n){super(`Message not valid before ${n}`,"SIWX_NOT_BEFORE");this.notBefore=n;this.name="SiwxNotBeforeError";}notBefore},C=class extends h{constructor(n,s){super(`Session lifetime of ${n} seconds exceeds maximum allowed lifetime of ${s} seconds`,"SIWX_SESSION_LIFETIME_EXCEEDED");this.lifetimeSeconds=n;this.maxLifetimeSeconds=s;this.name="SiwxSessionLifetimeExceededError";}lifetimeSeconds;maxLifetimeSeconds};var W=/^(?<domain>.+) wants you to sign in with your blockchain account:$/,N=/^(?<key>[A-Za-z ]+): (?<value>.+)$/,X=/^- (?<resource>.+)$/;function V(e){let t=e.split(`
3
+ `);if(t.length<5)throw new g("Message is too short to be a valid CAIP-122 message.");let n=t[0]?.match(W);if(!n?.groups?.domain)throw new g('Invalid CAIP-122 header line. Expected: "{domain} wants you to sign in with your blockchain account:"');let s=n.groups.domain,a=t[1];if(!a)throw new g("Missing address on line 2.");if(t[2]!=="")throw new g("Expected blank line after address (line 3).");let i=3,r;if(t[i]&&!N.test(t[i])){if(r=t[i],i++,t[i]!=="")throw new g("Expected blank line after statement.");i++;}let o={},u=[],p=false;for(;i<t.length;){let d=t[i];if(d===void 0){i++;continue}if(d==="Resources:"){p=true,i++;continue}if(p){let l=d.match(X);if(l?.groups?.resource){u.push(l.groups.resource),i++;continue}p=false;}let m=d.match(N);m?.groups?.key&&m.groups.value&&(o[m.groups.key]=m.groups.value),i++;}let c=["URI","Version","Chain ID","Nonce","Issued At"];for(let d of c)if(!o[d])throw new g(`Missing required field in CAIP-122 message: "${d}"`);return {domain:s,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:u.length>0?u:void 0}}var v="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",B="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",U="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",P={"solana:mainnet":v,"solana:mainnet-beta":v,"solana:devnet":B,"solana:testnet":U,"solana:4uhcVJyU9pJkvQyS88uRfhDSfZSm8DoR":U};function x(e){return Object.hasOwn(P,e)?P[e]:e}function _(e,t){if(!t||t.length===0)return true;let n=x(e);return t.some(s=>x(s)===n)}var F=/^https?:\/\/.+/,G=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/,q=/^[a-z0-9]+:[a-zA-Z0-9-]+:.+$/,z=/^[a-z0-9]+:[a-zA-Z0-9-]+$/;function j(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 Z(e){if(!q.test(e))return `address must be CAIP-10 compliant (namespace:chainRef:address). Got: "${e}"`}function Y(e){if(!F.test(e))return `uri must be a valid RFC 3986 URI starting with http(s)://. Got: "${e}"`}function H(e){if(!z.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 D(e,t){if(!G.test(e))return `${t} must be a valid ISO 8601 datetime string. Got: "${e}"`}function K(e,t=new Date,n=0){let s=new Date(e);if(isNaN(s.getTime()))return `expirationTime is not a valid date: "${e}"`;if(s.getTime()+n*1e3<t.getTime())return `Message has expired. expirationTime was: ${e}`}function O(e,t,n=new Date){if(!t)return [];let s=[];if(t.expectedDomain!==void 0){let r=Array.isArray(t.expectedDomain)?t.expectedDomain:[t.expectedDomain];r.some(u=>u.toLowerCase()===e.domain.toLowerCase())||s.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(u=>{if(e.uri===u)return true;let p=u.endsWith("/")?u.slice(0,-1):u;if(e.uri.startsWith(`${p}/`))return true;try{let c=new URL(e.uri),d=new URL(u);return c.origin.toLowerCase()===d.origin.toLowerCase()}catch{return false}})||s.push(`URI mismatch. Expected: [${r.join(", ")}], Received: "${e.uri}"`);}_(e.chainId,t.allowedChainIds)||s.push(`Chain ID "${e.chainId}" is not allowed. Allowed: [${t.allowedChainIds?.join(", ")}]`),t.requireExpirationTime&&!e.expirationTime&&s.push("expirationTime is required by verification policy.");let a=t.clockSkewSeconds??60,i=new Date(e.issuedAt);if(isNaN(i.getTime())||(t.maxIssuedAtAgeSeconds!==void 0&&(n.getTime()-i.getTime())/1e3>t.maxIssuedAtAgeSeconds+a&&s.push(`Message issuedAt "${e.issuedAt}" is older than the allowed max age of ${t.maxIssuedAtAgeSeconds} seconds`),i.getTime()-n.getTime()>a*1e3&&s.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()-n.getTime()>a*1e3&&s.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(i.getTime())){let o=(r.getTime()-i.getTime())/1e3;o>t.maxSessionLifetimeSeconds&&s.push(`Session lifetime of ${o} seconds exceeds maximum allowed lifetime of ${t.maxSessionLifetimeSeconds} seconds`);}}return s}function Q(e,t){let n=[],s=j(e.domain);s&&n.push(s);let a=Z(e.address);a&&n.push(a);let i=Y(e.uri);i&&n.push(i),e.version!=="1"&&n.push(`version must be "1". Got: "${e.version}"`);let r=H(e.chainId);r&&n.push(r);let o=J(e.nonce);o&&n.push(o);let u=D(e.issuedAt,"issuedAt");u&&n.push(u);let p=t?.policy?.clockSkewSeconds??60;if(e.expirationTime){let c=D(e.expirationTime,"expirationTime");if(c)n.push(c);else if(!t?.skipExpiration){let d=K(e.expirationTime,new Date,p);d&&n.push(d);}}if(e.notBefore){let c=D(e.notBefore,"notBefore");c&&n.push(c);}return e.statement&&e.statement.includes(`
5
+ `)&&n.push("statement must not contain newline characters."),n.push(...O(e,t?.policy??{})),{valid:n.length===0,errors:n}}function ee(){let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function te(e,t,n){if(!e||!e.address||!t)return false;let s=e.address,a=s.startsWith("eip155:"),i=s.startsWith("solana:"),r=t.includes(":")?t.split(":").pop():t,o=s.includes(":")?s.split(":").pop():s,u=r.startsWith("0x")||t.startsWith("eip155:");if(u&&!a||!u&&!i||!(a?o.toLowerCase()===r.toLowerCase():o===r))return false;if(n!=null){let c=String(n),d=a?c.startsWith("eip155:")?c:`eip155:${c}`:c.startsWith("solana:")?c:`solana:${c}`,m=e.chainId&&(i?x(e.chainId):e.chainId),l=i?x(d):d;if(m&&m!==l&&e.chainId!==c)return false}return true}exports.SiwxChainNotAllowedError=y;exports.SiwxDomainMismatchError=R;exports.SiwxError=f;exports.SiwxExpiredSessionError=E;exports.SiwxIssuedAtFutureError=b;exports.SiwxIssuedAtStaleError=T;exports.SiwxNonceReplayError=I;exports.SiwxNotBeforeError=M;exports.SiwxParseError=g;exports.SiwxPolicyViolationError=h;exports.SiwxSessionLifetimeExceededError=C;exports.SiwxUnsupportedNamespaceError=A;exports.SiwxUriMismatchError=$;exports.SiwxValidationError=S;exports.SiwxVerificationError=w;exports.buildMessage=L;exports.generateNonce=ee;exports.isChainIdAllowed=_;exports.isSessionMatchingTarget=te;exports.normalizeSolanaChainId=x;exports.parseMessage=V;exports.validateMessage=Q;exports.validatePolicy=O;
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
+ function L(e){let{domain:t,address:n,statement:s,uri:a,version:i,chainId:r,nonce:o,issuedAt:u,expirationTime:p,notBefore:c,requestId:d,resources:m}=e,l=[`${t} wants you to sign in with your blockchain account:`,n,""];if(s&&l.push(s,""),l.push(`URI: ${a}`,`Version: ${i}`,`Chain ID: ${r}`,`Nonce: ${o}`,`Issued At: ${u}`),p&&l.push(`Expiration Time: ${p}`),c&&l.push(`Not Before: ${c}`),d&&l.push(`Request ID: ${d}`),m&&m.length>0){l.push("Resources:");for(let k of m)l.push(`- ${k}`);}return l.join(`
2
+ `)}var f=class extends Error{constructor(n,s="SIWX_ERROR"){super(n);this.code=s;this.name="SiwxError",Object.setPrototypeOf(this,new.target.prototype);}code},g=class extends f{constructor(t){super(t,"SIWX_PARSE_ERROR"),this.name="SiwxParseError";}},S=class extends f{constructor(n){super(`CAIP-122 message validation failed: ${n.join(", ")}`,"SIWX_VALIDATION_ERROR");this.errors=n;this.name="SiwxValidationError";}errors},w=class extends f{constructor(t){super(t,"SIWX_VERIFICATION_ERROR"),this.name="SiwxVerificationError";}},E=class extends f{constructor(n){super(`SIWX session expired at ${n}`,"SIWX_EXPIRED_SESSION");this.expirationTime=n;this.name="SiwxExpiredSessionError";}expirationTime},I=class extends f{constructor(n){super(`Nonce has already been used: ${n}`,"SIWX_NONCE_REPLAY");this.nonce=n;this.name="SiwxNonceReplayError";}nonce},A=class extends f{constructor(n){super(`Unsupported CAIP-2 namespace: "${n}". Supported: eip155, solana`,"SIWX_UNSUPPORTED_NAMESPACE");this.namespace=n;this.name="SiwxUnsupportedNamespaceError";}namespace},h=class extends f{constructor(t,n="SIWX_POLICY_VIOLATION"){super(t,n),this.name="SiwxPolicyViolationError";}},R=class extends h{constructor(n,s){let a=Array.isArray(n)?n.join(", "):n;super(`Domain mismatch. Expected: [${a}], Received: "${s}"`,"SIWX_DOMAIN_MISMATCH");this.expected=n;this.received=s;this.name="SiwxDomainMismatchError";}expected;received},$=class extends h{constructor(n,s){let a=Array.isArray(n)?n.join(", "):n;super(`URI mismatch. Expected: [${a}], Received: "${s}"`,"SIWX_URI_MISMATCH");this.expected=n;this.received=s;this.name="SiwxUriMismatchError";}expected;received},y=class extends h{constructor(n,s){super(`Chain ID "${s}" is not allowed. Allowed: [${n.join(", ")}]`,"SIWX_CHAIN_NOT_ALLOWED");this.allowedChainIds=n;this.received=s;this.name="SiwxChainNotAllowedError";}allowedChainIds;received},T=class extends h{constructor(n,s){super(`Message issuedAt "${n}" is older than the allowed max age of ${s} seconds`,"SIWX_ISSUED_AT_STALE");this.issuedAt=n;this.maxAgeSeconds=s;this.name="SiwxIssuedAtStaleError";}issuedAt;maxAgeSeconds},b=class extends h{constructor(n,s){super(`Message issuedAt "${n}" is in the future beyond allowed clock skew of ${s} seconds`,"SIWX_ISSUED_AT_FUTURE");this.issuedAt=n;this.clockSkewSeconds=s;this.name="SiwxIssuedAtFutureError";}issuedAt;clockSkewSeconds},M=class extends h{constructor(n){super(`Message not valid before ${n}`,"SIWX_NOT_BEFORE");this.notBefore=n;this.name="SiwxNotBeforeError";}notBefore},C=class extends h{constructor(n,s){super(`Session lifetime of ${n} seconds exceeds maximum allowed lifetime of ${s} seconds`,"SIWX_SESSION_LIFETIME_EXCEEDED");this.lifetimeSeconds=n;this.maxLifetimeSeconds=s;this.name="SiwxSessionLifetimeExceededError";}lifetimeSeconds;maxLifetimeSeconds};var W=/^(?<domain>.+) wants you to sign in with your blockchain account:$/,N=/^(?<key>[A-Za-z ]+): (?<value>.+)$/,X=/^- (?<resource>.+)$/;function V(e){let t=e.split(`
3
+ `);if(t.length<5)throw new g("Message is too short to be a valid CAIP-122 message.");let n=t[0]?.match(W);if(!n?.groups?.domain)throw new g('Invalid CAIP-122 header line. Expected: "{domain} wants you to sign in with your blockchain account:"');let s=n.groups.domain,a=t[1];if(!a)throw new g("Missing address on line 2.");if(t[2]!=="")throw new g("Expected blank line after address (line 3).");let i=3,r;if(t[i]&&!N.test(t[i])){if(r=t[i],i++,t[i]!=="")throw new g("Expected blank line after statement.");i++;}let o={},u=[],p=false;for(;i<t.length;){let d=t[i];if(d===void 0){i++;continue}if(d==="Resources:"){p=true,i++;continue}if(p){let l=d.match(X);if(l?.groups?.resource){u.push(l.groups.resource),i++;continue}p=false;}let m=d.match(N);m?.groups?.key&&m.groups.value&&(o[m.groups.key]=m.groups.value),i++;}let c=["URI","Version","Chain ID","Nonce","Issued At"];for(let d of c)if(!o[d])throw new g(`Missing required field in CAIP-122 message: "${d}"`);return {domain:s,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:u.length>0?u:void 0}}var v="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",B="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",U="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",P={"solana:mainnet":v,"solana:mainnet-beta":v,"solana:devnet":B,"solana:testnet":U,"solana:4uhcVJyU9pJkvQyS88uRfhDSfZSm8DoR":U};function x(e){return Object.hasOwn(P,e)?P[e]:e}function _(e,t){if(!t||t.length===0)return true;let n=x(e);return t.some(s=>x(s)===n)}var F=/^https?:\/\/.+/,G=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/,q=/^[a-z0-9]+:[a-zA-Z0-9-]+:.+$/,z=/^[a-z0-9]+:[a-zA-Z0-9-]+$/;function j(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 Z(e){if(!q.test(e))return `address must be CAIP-10 compliant (namespace:chainRef:address). Got: "${e}"`}function Y(e){if(!F.test(e))return `uri must be a valid RFC 3986 URI starting with http(s)://. Got: "${e}"`}function H(e){if(!z.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 D(e,t){if(!G.test(e))return `${t} must be a valid ISO 8601 datetime string. Got: "${e}"`}function K(e,t=new Date,n=0){let s=new Date(e);if(isNaN(s.getTime()))return `expirationTime is not a valid date: "${e}"`;if(s.getTime()+n*1e3<t.getTime())return `Message has expired. expirationTime was: ${e}`}function O(e,t,n=new Date){if(!t)return [];let s=[];if(t.expectedDomain!==void 0){let r=Array.isArray(t.expectedDomain)?t.expectedDomain:[t.expectedDomain];r.some(u=>u.toLowerCase()===e.domain.toLowerCase())||s.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(u=>{if(e.uri===u)return true;let p=u.endsWith("/")?u.slice(0,-1):u;if(e.uri.startsWith(`${p}/`))return true;try{let c=new URL(e.uri),d=new URL(u);return c.origin.toLowerCase()===d.origin.toLowerCase()}catch{return false}})||s.push(`URI mismatch. Expected: [${r.join(", ")}], Received: "${e.uri}"`);}_(e.chainId,t.allowedChainIds)||s.push(`Chain ID "${e.chainId}" is not allowed. Allowed: [${t.allowedChainIds?.join(", ")}]`),t.requireExpirationTime&&!e.expirationTime&&s.push("expirationTime is required by verification policy.");let a=t.clockSkewSeconds??60,i=new Date(e.issuedAt);if(isNaN(i.getTime())||(t.maxIssuedAtAgeSeconds!==void 0&&(n.getTime()-i.getTime())/1e3>t.maxIssuedAtAgeSeconds+a&&s.push(`Message issuedAt "${e.issuedAt}" is older than the allowed max age of ${t.maxIssuedAtAgeSeconds} seconds`),i.getTime()-n.getTime()>a*1e3&&s.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()-n.getTime()>a*1e3&&s.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(i.getTime())){let o=(r.getTime()-i.getTime())/1e3;o>t.maxSessionLifetimeSeconds&&s.push(`Session lifetime of ${o} seconds exceeds maximum allowed lifetime of ${t.maxSessionLifetimeSeconds} seconds`);}}return s}function Q(e,t){let n=[],s=j(e.domain);s&&n.push(s);let a=Z(e.address);a&&n.push(a);let i=Y(e.uri);i&&n.push(i),e.version!=="1"&&n.push(`version must be "1". Got: "${e.version}"`);let r=H(e.chainId);r&&n.push(r);let o=J(e.nonce);o&&n.push(o);let u=D(e.issuedAt,"issuedAt");u&&n.push(u);let p=t?.policy?.clockSkewSeconds??60;if(e.expirationTime){let c=D(e.expirationTime,"expirationTime");if(c)n.push(c);else if(!t?.skipExpiration){let d=K(e.expirationTime,new Date,p);d&&n.push(d);}}if(e.notBefore){let c=D(e.notBefore,"notBefore");c&&n.push(c);}return e.statement&&e.statement.includes(`
5
+ `)&&n.push("statement must not contain newline characters."),n.push(...O(e,t?.policy??{})),{valid:n.length===0,errors:n}}function ee(){let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function te(e,t,n){if(!e||!e.address||!t)return false;let s=e.address,a=s.startsWith("eip155:"),i=s.startsWith("solana:"),r=t.includes(":")?t.split(":").pop():t,o=s.includes(":")?s.split(":").pop():s,u=r.startsWith("0x")||t.startsWith("eip155:");if(u&&!a||!u&&!i||!(a?o.toLowerCase()===r.toLowerCase():o===r))return false;if(n!=null){let c=String(n),d=a?c.startsWith("eip155:")?c:`eip155:${c}`:c.startsWith("solana:")?c:`solana:${c}`,m=e.chainId&&(i?x(e.chainId):e.chainId),l=i?x(d):d;if(m&&m!==l&&e.chainId!==c)return false}return true}export{y as SiwxChainNotAllowedError,R as SiwxDomainMismatchError,f as SiwxError,E as SiwxExpiredSessionError,b as SiwxIssuedAtFutureError,T as SiwxIssuedAtStaleError,I as SiwxNonceReplayError,M as SiwxNotBeforeError,g as SiwxParseError,h as SiwxPolicyViolationError,C as SiwxSessionLifetimeExceededError,A as SiwxUnsupportedNamespaceError,$ as SiwxUriMismatchError,S as SiwxValidationError,w as SiwxVerificationError,L as buildMessage,ee as generateNonce,_ as isChainIdAllowed,te as isSessionMatchingTarget,x as normalizeSolanaChainId,V as parseMessage,Q as validateMessage,O as validatePolicy};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tuwaio/siwx-core",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "private": false,
5
5
  "author": "Oleksandr Tkach",
6
6
  "license": "Apache-2.0",