@tuwaio/siwx-core 0.5.0 → 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
  ---
package/dist/index.d.mts CHANGED
@@ -468,7 +468,8 @@ declare function parseMessage(message: string): ParsedSiwxMessage;
468
468
  * testnet genesis reset become `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp`, `solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1` or
469
469
  * `solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z`.
470
470
  *
471
- * Use it to compare Solana chain IDs: sessions signed before the switch to genesis-hash IDs carry `solana:devnet`.
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`.
472
473
  *
473
474
  * @param chainId - A CAIP-2 chain ID.
474
475
  * @returns The genesis-hash chain ID for a known Solana cluster name; any other value unchanged (genesis-hash IDs,
@@ -572,8 +573,10 @@ interface SiwxSessionLike {
572
573
  * Checks whether a SIWX session belongs to a given wallet address and, optionally, chain. Use it on the server to
573
574
  * make sure the signed-in account is the one a request acts on.
574
575
  *
575
- * A target that starts with `0x` or `eip155:` is treated as EVM and only matches `eip155:` sessions, compared
576
- * case-insensitively; any other target only matches `solana:` sessions, compared case-sensitively. The chain is
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
577
580
  * compared only when `targetChainId` is given and the session has a `chainId`; a Solana cluster matches under its name
578
581
  * (`devnet`, `solana:devnet`) and its genesis-hash chain ID (see {@link normalizeSolanaChainId}).
579
582
  *
package/dist/index.d.ts CHANGED
@@ -468,7 +468,8 @@ declare function parseMessage(message: string): ParsedSiwxMessage;
468
468
  * testnet genesis reset become `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp`, `solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1` or
469
469
  * `solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z`.
470
470
  *
471
- * Use it to compare Solana chain IDs: sessions signed before the switch to genesis-hash IDs carry `solana:devnet`.
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`.
472
473
  *
473
474
  * @param chainId - A CAIP-2 chain ID.
474
475
  * @returns The genesis-hash chain ID for a known Solana cluster name; any other value unchanged (genesis-hash IDs,
@@ -572,8 +573,10 @@ interface SiwxSessionLike {
572
573
  * Checks whether a SIWX session belongs to a given wallet address and, optionally, chain. Use it on the server to
573
574
  * make sure the signed-in account is the one a request acts on.
574
575
  *
575
- * A target that starts with `0x` or `eip155:` is treated as EVM and only matches `eip155:` sessions, compared
576
- * case-insensitively; any other target only matches `solana:` sessions, compared case-sensitively. The chain is
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
577
580
  * compared only when `targetChainId` is given and the session has a `chainId`; a Solana cluster matches under its name
578
581
  * (`devnet`, `solana:devnet`) and its genesis-hash chain ID (see {@link normalizeSolanaChainId}).
579
582
  *
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
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;
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 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};
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.5.0",
3
+ "version": "0.6.0",
4
4
  "private": false,
5
5
  "author": "Oleksandr Tkach",
6
6
  "license": "Apache-2.0",
7
- "description": "L1 core of SIWX (TUWA): 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
  },