@tuwaio/siwx-core 0.6.0 → 0.7.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
@@ -11,8 +11,8 @@ Its only dependency is the peer [`@tuwaio/orbit-core`](https://orbit.docs.tuwa.i
11
11
 
12
12
  ## 🏛️ Core Capabilities
13
13
 
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. 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.
14
+ - **Message format:** `buildMessage` formats CAIP-122 fields into the text the wallet signs (the EIP-4361 layout used by CAIP-122) and throws `SiwxValidationError` when a required field is missing or a field contains a line break; `parseMessage` reads the text back and throws `SiwxParseError` when it is malformed, including a header whose domain is not an RFC 3986 authority.
15
+ - **Validation:** `validateMessage` checks field formats (`domain` as an RFC 3986 authority such as `app.example.com` or `localhost:3000`, 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.
@@ -68,7 +68,7 @@ Issued At: 2026-09-26T10:00:00.000Z
68
68
  Expiration Time: 2026-09-26T10:10:00.000Z
69
69
  ```
70
70
 
71
- `buildMessage` does not validate its input; run `validateMessage` on untrusted fields.
71
+ `buildMessage` only checks that the message can be built: every required field is a non-empty string and no field contains a line break, which would add lines to the signed text (it throws `SiwxValidationError` otherwise). Run `validateMessage` on untrusted fields for the formats and timing.
72
72
 
73
73
  ### Validating fields and a policy
74
74
 
package/dist/index.d.mts CHANGED
@@ -222,10 +222,13 @@ interface SiwxAdapter {
222
222
  * Formats CAIP-122 message fields into the plain-text message that the wallet signs (the EIP-4361 layout used by
223
223
  * CAIP-122). Optional fields are omitted when empty.
224
224
  *
225
- * Pure function: it does not validate the fields. Run {@link validateMessage} first if the input is untrusted.
225
+ * Pure function. It only checks that the message can be built: every required field is a non-empty string and no
226
+ * field contains a line break (which would add or change lines of the signed message). It does not check formats or
227
+ * timing: run {@link validateMessage} for that, as verifiers do.
226
228
  *
227
229
  * @param fields - The message fields to format.
228
230
  * @returns The message lines joined with `\n`, ready to be signed and parseable by {@link parseMessage}.
231
+ * @throws {@link SiwxValidationError} When a required field is missing or empty, or a field contains a line break.
229
232
  *
230
233
  * @example
231
234
  * ```ts
package/dist/index.d.ts CHANGED
@@ -222,10 +222,13 @@ interface SiwxAdapter {
222
222
  * Formats CAIP-122 message fields into the plain-text message that the wallet signs (the EIP-4361 layout used by
223
223
  * CAIP-122). Optional fields are omitted when empty.
224
224
  *
225
- * Pure function: it does not validate the fields. Run {@link validateMessage} first if the input is untrusted.
225
+ * Pure function. It only checks that the message can be built: every required field is a non-empty string and no
226
+ * field contains a line break (which would add or change lines of the signed message). It does not check formats or
227
+ * timing: run {@link validateMessage} for that, as verifiers do.
226
228
  *
227
229
  * @param fields - The message fields to format.
228
230
  * @returns The message lines joined with `\n`, ready to be signed and parseable by {@link parseMessage}.
231
+ * @throws {@link SiwxValidationError} When a required field is missing or empty, or a field contains a line break.
229
232
  *
230
233
  * @example
231
234
  * ```ts
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- 'use strict';var orbitCore=require('@tuwaio/orbit-core');function O(e){let{domain:t,address:i,statement:n,uri:a,version:r,chainId:o,nonce:s,issuedAt:c,expirationTime:p,notBefore:d,requestId:u,resources:x}=e,l=[`${t} wants you to sign in with your blockchain account:`,i,""];if(n&&l.push(n,""),l.push(`URI: ${a}`,`Version: ${r}`,`Chain ID: ${o}`,`Nonce: ${s}`,`Issued At: ${c}`),p&&l.push(`Expiration Time: ${p}`),d&&l.push(`Not Before: ${d}`),u&&l.push(`Request ID: ${u}`),x&&x.length>0){l.push("Resources:");for(let P of x)l.push(`- ${P}`);}return l.join(`
2
- `)}var m=class extends Error{constructor(i,n="SIWX_ERROR"){super(i);this.code=n;this.name="SiwxError",Object.setPrototypeOf(this,new.target.prototype);}code},f=class extends m{constructor(t){super(t,"SIWX_PARSE_ERROR"),this.name="SiwxParseError";}},S=class extends m{constructor(i){super(`CAIP-122 message validation failed: ${i.join(", ")}`,"SIWX_VALIDATION_ERROR");this.errors=i;this.name="SiwxValidationError";}errors},w=class extends m{constructor(t){super(t,"SIWX_VERIFICATION_ERROR"),this.name="SiwxVerificationError";}},I=class extends m{constructor(i){super(`SIWX session expired at ${i}`,"SIWX_EXPIRED_SESSION");this.expirationTime=i;this.name="SiwxExpiredSessionError";}expirationTime},E=class extends m{constructor(i){super(`Nonce has already been used: ${i}`,"SIWX_NONCE_REPLAY");this.nonce=i;this.name="SiwxNonceReplayError";}nonce},A=class extends m{constructor(i){super(`Unsupported CAIP-2 namespace: "${i}". Supported: eip155, solana`,"SIWX_UNSUPPORTED_NAMESPACE");this.namespace=i;this.name="SiwxUnsupportedNamespaceError";}namespace},g=class extends m{constructor(t,i="SIWX_POLICY_VIOLATION"){super(t,i),this.name="SiwxPolicyViolationError";}},$=class extends g{constructor(i,n){let a=Array.isArray(i)?i.join(", "):i;super(`Domain mismatch. Expected: [${a}], Received: "${n}"`,"SIWX_DOMAIN_MISMATCH");this.expected=i;this.received=n;this.name="SiwxDomainMismatchError";}expected;received},R=class extends g{constructor(i,n){let a=Array.isArray(i)?i.join(", "):i;super(`URI mismatch. Expected: [${a}], Received: "${n}"`,"SIWX_URI_MISMATCH");this.expected=i;this.received=n;this.name="SiwxUriMismatchError";}expected;received},y=class extends g{constructor(i,n){super(`Chain ID "${n}" is not allowed. Allowed: [${i.join(", ")}]`,"SIWX_CHAIN_NOT_ALLOWED");this.allowedChainIds=i;this.received=n;this.name="SiwxChainNotAllowedError";}allowedChainIds;received},b=class extends g{constructor(i,n){super(`Message issuedAt "${i}" is older than the allowed max age of ${n} seconds`,"SIWX_ISSUED_AT_STALE");this.issuedAt=i;this.maxAgeSeconds=n;this.name="SiwxIssuedAtStaleError";}issuedAt;maxAgeSeconds},M=class extends g{constructor(i,n){super(`Message issuedAt "${i}" is in the future beyond allowed clock skew of ${n} seconds`,"SIWX_ISSUED_AT_FUTURE");this.issuedAt=i;this.clockSkewSeconds=n;this.name="SiwxIssuedAtFutureError";}issuedAt;clockSkewSeconds},T=class extends g{constructor(i){super(`Message not valid before ${i}`,"SIWX_NOT_BEFORE");this.notBefore=i;this.name="SiwxNotBeforeError";}notBefore},C=class extends g{constructor(i,n){super(`Session lifetime of ${i} seconds exceeds maximum allowed lifetime of ${n} seconds`,"SIWX_SESSION_LIFETIME_EXCEEDED");this.lifetimeSeconds=i;this.maxLifetimeSeconds=n;this.name="SiwxSessionLifetimeExceededError";}lifetimeSeconds;maxLifetimeSeconds};var k=/^(?<domain>.+) wants you to sign in with your blockchain account:$/,v=/^(?<key>[A-Za-z ]+): (?<value>.+)$/,L=/^- (?<resource>.+)$/;function X(e){let t=e.split(`
3
- `);if(t.length<5)throw new f("Message is too short to be a valid CAIP-122 message.");let i=t[0]?.match(k);if(!i?.groups?.domain)throw new f('Invalid CAIP-122 header line. Expected: "{domain} wants you to sign in with your blockchain account:"');let n=i.groups.domain,a=t[1];if(!a)throw new f("Missing address on line 2.");if(t[2]!=="")throw new f("Expected blank line after address (line 3).");let r=3,o;if(t[r]&&!v.test(t[r])){if(o=t[r],r++,t[r]!=="")throw new f("Expected blank line after statement.");r++;}let s={},c=[],p=false;for(;r<t.length;){let u=t[r];if(u===void 0){r++;continue}if(u==="Resources:"){p=true,r++;continue}if(p){let l=u.match(L);if(l?.groups?.resource){c.push(l.groups.resource),r++;continue}p=false;}let x=u.match(v);x?.groups?.key&&x.groups.value&&(s[x.groups.key]=x.groups.value),r++;}let d=["URI","Version","Chain ID","Nonce","Issued At"];for(let u of d)if(!s[u])throw new f(`Missing required field in CAIP-122 message: "${u}"`);return {domain:n,address:a,statement:o,uri:s.URI,version:s.Version,chainId:s["Chain ID"],nonce:s.Nonce,issuedAt:s["Issued At"],expirationTime:s["Expiration Time"],notBefore:s["Not Before"],requestId:s["Request ID"],resources:c.length>0?c:void 0}}function h(e){return e.startsWith("solana:")?orbitCore.getSolanaChainId(e)??e:e}function D(e,t){if(!t||t.length===0)return true;let i=h(e);return t.some(n=>h(n)===i)}var B=/^https?:\/\/.+/,F=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;function G(e){if(!e||e.trim().length===0)return "domain must be a non-empty string.";if(e.includes(`
4
- `))return "domain must not contain newline characters."}function j(e){if(!orbitCore.parseCaip10AccountId(e))return `address must be CAIP-10 compliant (namespace:chainRef:address). Got: "${e}"`}function q(e){if(!B.test(e))return `uri must be a valid RFC 3986 URI starting with http(s)://. Got: "${e}"`}function z(e){if(!orbitCore.parseCaip2ChainId(e))return `chainId must be a valid CAIP-2 identifier (namespace:reference). Got: "${e}"`}function H(e){if(!e||e.length<8)return `nonce must be at least 8 characters long. Got length: ${e?.length??0}`;if(!/^[a-zA-Z0-9]+$/.test(e))return `nonce must be alphanumeric. Got: "${e}"`}function _(e,t){if(!F.test(e))return `${t} must be a valid ISO 8601 datetime string. Got: "${e}"`}function Z(e,t=new Date,i=0){let n=new Date(e);if(isNaN(n.getTime()))return `expirationTime is not a valid date: "${e}"`;if(n.getTime()+i*1e3<t.getTime())return `Message has expired. expirationTime was: ${e}`}function U(e,t,i=new Date){if(!t)return [];let n=[];if(t.expectedDomain!==void 0){let o=Array.isArray(t.expectedDomain)?t.expectedDomain:[t.expectedDomain];o.some(c=>c.toLowerCase()===e.domain.toLowerCase())||n.push(`Domain mismatch. Expected: [${o.join(", ")}], Received: "${e.domain}"`);}if(t.expectedUri!==void 0){let o=Array.isArray(t.expectedUri)?t.expectedUri:[t.expectedUri];o.some(c=>{if(e.uri===c)return true;let p=c.endsWith("/")?c.slice(0,-1):c;if(e.uri.startsWith(`${p}/`))return true;try{let d=new URL(e.uri),u=new URL(c);return d.origin.toLowerCase()===u.origin.toLowerCase()}catch{return false}})||n.push(`URI mismatch. Expected: [${o.join(", ")}], Received: "${e.uri}"`);}D(e.chainId,t.allowedChainIds)||n.push(`Chain ID "${e.chainId}" is not allowed. Allowed: [${t.allowedChainIds?.join(", ")}]`),t.requireExpirationTime&&!e.expirationTime&&n.push("expirationTime is required by verification policy.");let a=t.clockSkewSeconds??60,r=new Date(e.issuedAt);if(isNaN(r.getTime())||(t.maxIssuedAtAgeSeconds!==void 0&&(i.getTime()-r.getTime())/1e3>t.maxIssuedAtAgeSeconds+a&&n.push(`Message issuedAt "${e.issuedAt}" is older than the allowed max age of ${t.maxIssuedAtAgeSeconds} seconds`),r.getTime()-i.getTime()>a*1e3&&n.push(`Message issuedAt "${e.issuedAt}" is in the future beyond allowed clock skew of ${a} seconds`)),e.notBefore&&t.enforceNotBefore!==false){let o=new Date(e.notBefore);isNaN(o.getTime())||o.getTime()-i.getTime()>a*1e3&&n.push(`Message not valid before ${e.notBefore}`);}if(t.maxSessionLifetimeSeconds!==void 0&&e.expirationTime){let o=new Date(e.expirationTime);if(!isNaN(o.getTime())&&!isNaN(r.getTime())){let s=(o.getTime()-r.getTime())/1e3;s>t.maxSessionLifetimeSeconds&&n.push(`Session lifetime of ${s} seconds exceeds maximum allowed lifetime of ${t.maxSessionLifetimeSeconds} seconds`);}}return n}function Y(e,t){let i=[],n=G(e.domain);n&&i.push(n);let a=j(e.address);a&&i.push(a);let r=q(e.uri);r&&i.push(r),e.version!=="1"&&i.push(`version must be "1". Got: "${e.version}"`);let o=z(e.chainId);o&&i.push(o);let s=H(e.nonce);s&&i.push(s);let c=_(e.issuedAt,"issuedAt");c&&i.push(c);let p=t?.policy?.clockSkewSeconds??60;if(e.expirationTime){let d=_(e.expirationTime,"expirationTime");if(d)i.push(d);else if(!t?.skipExpiration){let u=Z(e.expirationTime,new Date,p);u&&i.push(u);}}if(e.notBefore){let d=_(e.notBefore,"notBefore");d&&i.push(d);}return e.statement&&e.statement.includes(`
5
- `)&&i.push("statement must not contain newline characters."),i.push(...U(e,t?.policy??{})),{valid:i.length===0,errors:i}}function J(){let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function K(e,t,i){if(!e||!e.address||!t)return false;let n=orbitCore.parseCaip10AccountId(e.address);if(!n||n.namespace!=="eip155"&&n.namespace!=="solana")return false;let a=n.namespace==="eip155",r=t;if(t.includes(":")){let s=orbitCore.parseCaip10AccountId(t);if(s?.namespace!==n.namespace)return false;r=s.address;}else if(t.startsWith("0x")!==a)return false;if(!(a?n.address.toLowerCase()===r.toLowerCase():n.address===r))return false;if(i!=null&&e.chainId){let s=String(i),c=h(s.includes(":")?s:`${n.namespace}:${s}`);if(h(e.chainId)!==c&&e.chainId!==s)return false}return true}exports.SiwxChainNotAllowedError=y;exports.SiwxDomainMismatchError=$;exports.SiwxError=m;exports.SiwxExpiredSessionError=I;exports.SiwxIssuedAtFutureError=M;exports.SiwxIssuedAtStaleError=b;exports.SiwxNonceReplayError=E;exports.SiwxNotBeforeError=T;exports.SiwxParseError=f;exports.SiwxPolicyViolationError=g;exports.SiwxSessionLifetimeExceededError=C;exports.SiwxUnsupportedNamespaceError=A;exports.SiwxUriMismatchError=R;exports.SiwxValidationError=S;exports.SiwxVerificationError=w;exports.buildMessage=O;exports.generateNonce=J;exports.isChainIdAllowed=D;exports.isSessionMatchingTarget=K;exports.normalizeSolanaChainId=h;exports.parseMessage=X;exports.validateMessage=Y;exports.validatePolicy=U;
1
+ 'use strict';var orbitCore=require('@tuwaio/orbit-core');var l=class extends Error{constructor(n,s="SIWX_ERROR"){super(n);this.code=s;this.name="SiwxError",Object.setPrototypeOf(this,new.target.prototype);}code},m=class extends l{constructor(t){super(t,"SIWX_PARSE_ERROR"),this.name="SiwxParseError";}},I=class extends l{constructor(n){super(`CAIP-122 message validation failed: ${n.join(", ")}`,"SIWX_VALIDATION_ERROR");this.errors=n;this.name="SiwxValidationError";}errors},$=class extends l{constructor(t){super(t,"SIWX_VERIFICATION_ERROR"),this.name="SiwxVerificationError";}},R=class extends l{constructor(n){super(`SIWX session expired at ${n}`,"SIWX_EXPIRED_SESSION");this.expirationTime=n;this.name="SiwxExpiredSessionError";}expirationTime},y=class extends l{constructor(n){super(`Nonce has already been used: ${n}`,"SIWX_NONCE_REPLAY");this.nonce=n;this.name="SiwxNonceReplayError";}nonce},b=class extends l{constructor(n){super(`Unsupported CAIP-2 namespace: "${n}". Supported: eip155, solana`,"SIWX_UNSUPPORTED_NAMESPACE");this.namespace=n;this.name="SiwxUnsupportedNamespaceError";}namespace},f=class extends l{constructor(t,n="SIWX_POLICY_VIOLATION"){super(t,n),this.name="SiwxPolicyViolationError";}},T=class extends f{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},M=class extends f{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},C=class extends f{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},_=class extends f{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},D=class extends f{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},N=class extends f{constructor(n){super(`Message not valid before ${n}`,"SIWX_NOT_BEFORE");this.notBefore=n;this.name="SiwxNotBeforeError";}notBefore},v=class extends f{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 P=["domain","address","uri","version","chainId","nonce","issuedAt"],W=[...P,"statement","expirationTime","notBefore","requestId"];function F(e){let t=[];for(let p of P){let A=e[p];(typeof A!="string"||A.trim().length===0)&&t.push(`${p} is required. Got: ${JSON.stringify(A)??"undefined"}`);}let n=p=>typeof p=="string"&&/[\r\n]/.test(p);for(let p of W)n(e[p])&&t.push(`${p} must not contain line breaks.`);if(e.resources?.some(n)&&t.push("resources must not contain line breaks."),t.length>0)throw new I(t);let{domain:s,address:a,statement:i,uri:o,version:r,chainId:c,nonce:g,issuedAt:d,expirationTime:u,notBefore:x,requestId:w,resources:E}=e,h=[`${s} wants you to sign in with your blockchain account:`,a,""];if(i&&h.push(i,""),h.push(`URI: ${o}`,`Version: ${r}`,`Chain ID: ${c}`,`Nonce: ${g}`,`Issued At: ${d}`),u&&h.push(`Expiration Time: ${u}`),x&&h.push(`Not Before: ${x}`),w&&h.push(`Request ID: ${w}`),E&&E.length>0){h.push("Resources:");for(let p of E)h.push(`- ${p}`);}return h.join(`
2
+ `)}function S(e){return e.startsWith("solana:")?orbitCore.getSolanaChainId(e)??e:e}function U(e,t){if(!t||t.length===0)return true;let n=S(e);return t.some(s=>S(s)===n)}var L=/^[A-Za-z0-9\-._~%!$&'()*+,;=:@[\]]+$/,j=/^https?:\/\/.+/,q=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;function z(e){if(!e||e.trim().length===0)return "domain must be a non-empty string.";if(e.includes(`
3
+ `))return "domain must not contain newline characters.";if(!L.test(e))return `domain must be an RFC 3986 authority such as "app.example.com" or "localhost:3000". Got: ${JSON.stringify(e)}`}function H(e){if(!orbitCore.parseCaip10AccountId(e))return `address must be CAIP-10 compliant (namespace:chainRef:address). Got: "${e}"`}function Y(e){if(!j.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 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 O(e,t){if(!q.test(e))return `${t} must be a valid ISO 8601 datetime string. Got: "${e}"`}function Q(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 X(e,t,n=new Date){if(!t)return [];let s=[];if(t.expectedDomain!==void 0){let o=Array.isArray(t.expectedDomain)?t.expectedDomain:[t.expectedDomain];o.some(c=>c.toLowerCase()===e.domain.toLowerCase())||s.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 g=c.endsWith("/")?c.slice(0,-1):c;if(e.uri.startsWith(`${g}/`))return true;try{let d=new URL(e.uri),u=new URL(c);return d.origin.toLowerCase()===u.origin.toLowerCase()}catch{return false}})||s.push(`URI mismatch. Expected: [${o.join(", ")}], Received: "${e.uri}"`);}U(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 o=new Date(e.notBefore);isNaN(o.getTime())||o.getTime()-n.getTime()>a*1e3&&s.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(i.getTime())){let r=(o.getTime()-i.getTime())/1e3;r>t.maxSessionLifetimeSeconds&&s.push(`Session lifetime of ${r} seconds exceeds maximum allowed lifetime of ${t.maxSessionLifetimeSeconds} seconds`);}}return s}function K(e,t){let n=[],s=z(e.domain);s&&n.push(s);let a=H(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 o=Z(e.chainId);o&&n.push(o);let r=J(e.nonce);r&&n.push(r);let c=O(e.issuedAt,"issuedAt");c&&n.push(c);let g=t?.policy?.clockSkewSeconds??60;if(e.expirationTime){let d=O(e.expirationTime,"expirationTime");if(d)n.push(d);else if(!t?.skipExpiration){let u=Q(e.expirationTime,new Date,g);u&&n.push(u);}}if(e.notBefore){let d=O(e.notBefore,"notBefore");d&&n.push(d);}return e.statement&&e.statement.includes(`
4
+ `)&&n.push("statement must not contain newline characters."),n.push(...X(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=orbitCore.parseCaip10AccountId(e.address);if(!s||s.namespace!=="eip155"&&s.namespace!=="solana")return false;let a=s.namespace==="eip155",i=t;if(t.includes(":")){let r=orbitCore.parseCaip10AccountId(t);if(r?.namespace!==s.namespace)return false;i=r.address;}else if(t.startsWith("0x")!==a)return false;if(!(a?s.address.toLowerCase()===i.toLowerCase():s.address===i))return false;if(n!=null&&e.chainId){let r=String(n),c=S(r.includes(":")?r:`${s.namespace}:${r}`);if(S(e.chainId)!==c&&e.chainId!==r)return false}return true}var ne=new RegExp(`^(?<domain>${L.source.slice(1,-1)}) wants you to sign in with your blockchain account:$`),V=/^(?<key>[A-Za-z ]+): (?<value>.+)$/,se=/^- (?<resource>.+)$/;function ie(e){let t=e.split(`
5
+ `);if(t.length<5)throw new m("Message is too short to be a valid CAIP-122 message.");let n=t[0]?.match(ne);if(!n?.groups?.domain)throw new m('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 m("Missing address on line 2.");if(t[2]!=="")throw new m("Expected blank line after address (line 3).");let i=3,o;if(t[i]&&!V.test(t[i])){if(o=t[i],i++,t[i]!=="")throw new m("Expected blank line after statement.");i++;}let r={},c=[],g=false;for(;i<t.length;){let u=t[i];if(u===void 0){i++;continue}if(u==="Resources:"){g=true,i++;continue}if(g){let w=u.match(se);if(w?.groups?.resource){c.push(w.groups.resource),i++;continue}g=false;}let x=u.match(V);x?.groups?.key&&x.groups.value&&(r[x.groups.key]=x.groups.value),i++;}let d=["URI","Version","Chain ID","Nonce","Issued At"];for(let u of d)if(!r[u])throw new m(`Missing required field in CAIP-122 message: "${u}"`);return {domain:s,address:a,statement:o,uri:r.URI,version:r.Version,chainId:r["Chain ID"],nonce:r.Nonce,issuedAt:r["Issued At"],expirationTime:r["Expiration Time"],notBefore:r["Not Before"],requestId:r["Request ID"],resources:c.length>0?c:void 0}}exports.SiwxChainNotAllowedError=C;exports.SiwxDomainMismatchError=T;exports.SiwxError=l;exports.SiwxExpiredSessionError=R;exports.SiwxIssuedAtFutureError=D;exports.SiwxIssuedAtStaleError=_;exports.SiwxNonceReplayError=y;exports.SiwxNotBeforeError=N;exports.SiwxParseError=m;exports.SiwxPolicyViolationError=f;exports.SiwxSessionLifetimeExceededError=v;exports.SiwxUnsupportedNamespaceError=b;exports.SiwxUriMismatchError=M;exports.SiwxValidationError=I;exports.SiwxVerificationError=$;exports.buildMessage=F;exports.generateNonce=ee;exports.isChainIdAllowed=U;exports.isSessionMatchingTarget=te;exports.normalizeSolanaChainId=S;exports.parseMessage=ie;exports.validateMessage=K;exports.validatePolicy=X;
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import {getSolanaChainId,parseCaip10AccountId,parseCaip2ChainId}from'@tuwaio/orbit-core';function O(e){let{domain:t,address:i,statement:n,uri:a,version:r,chainId:o,nonce:s,issuedAt:c,expirationTime:p,notBefore:d,requestId:u,resources:x}=e,l=[`${t} wants you to sign in with your blockchain account:`,i,""];if(n&&l.push(n,""),l.push(`URI: ${a}`,`Version: ${r}`,`Chain ID: ${o}`,`Nonce: ${s}`,`Issued At: ${c}`),p&&l.push(`Expiration Time: ${p}`),d&&l.push(`Not Before: ${d}`),u&&l.push(`Request ID: ${u}`),x&&x.length>0){l.push("Resources:");for(let P of x)l.push(`- ${P}`);}return l.join(`
2
- `)}var m=class extends Error{constructor(i,n="SIWX_ERROR"){super(i);this.code=n;this.name="SiwxError",Object.setPrototypeOf(this,new.target.prototype);}code},f=class extends m{constructor(t){super(t,"SIWX_PARSE_ERROR"),this.name="SiwxParseError";}},S=class extends m{constructor(i){super(`CAIP-122 message validation failed: ${i.join(", ")}`,"SIWX_VALIDATION_ERROR");this.errors=i;this.name="SiwxValidationError";}errors},w=class extends m{constructor(t){super(t,"SIWX_VERIFICATION_ERROR"),this.name="SiwxVerificationError";}},I=class extends m{constructor(i){super(`SIWX session expired at ${i}`,"SIWX_EXPIRED_SESSION");this.expirationTime=i;this.name="SiwxExpiredSessionError";}expirationTime},E=class extends m{constructor(i){super(`Nonce has already been used: ${i}`,"SIWX_NONCE_REPLAY");this.nonce=i;this.name="SiwxNonceReplayError";}nonce},A=class extends m{constructor(i){super(`Unsupported CAIP-2 namespace: "${i}". Supported: eip155, solana`,"SIWX_UNSUPPORTED_NAMESPACE");this.namespace=i;this.name="SiwxUnsupportedNamespaceError";}namespace},g=class extends m{constructor(t,i="SIWX_POLICY_VIOLATION"){super(t,i),this.name="SiwxPolicyViolationError";}},$=class extends g{constructor(i,n){let a=Array.isArray(i)?i.join(", "):i;super(`Domain mismatch. Expected: [${a}], Received: "${n}"`,"SIWX_DOMAIN_MISMATCH");this.expected=i;this.received=n;this.name="SiwxDomainMismatchError";}expected;received},R=class extends g{constructor(i,n){let a=Array.isArray(i)?i.join(", "):i;super(`URI mismatch. Expected: [${a}], Received: "${n}"`,"SIWX_URI_MISMATCH");this.expected=i;this.received=n;this.name="SiwxUriMismatchError";}expected;received},y=class extends g{constructor(i,n){super(`Chain ID "${n}" is not allowed. Allowed: [${i.join(", ")}]`,"SIWX_CHAIN_NOT_ALLOWED");this.allowedChainIds=i;this.received=n;this.name="SiwxChainNotAllowedError";}allowedChainIds;received},b=class extends g{constructor(i,n){super(`Message issuedAt "${i}" is older than the allowed max age of ${n} seconds`,"SIWX_ISSUED_AT_STALE");this.issuedAt=i;this.maxAgeSeconds=n;this.name="SiwxIssuedAtStaleError";}issuedAt;maxAgeSeconds},M=class extends g{constructor(i,n){super(`Message issuedAt "${i}" is in the future beyond allowed clock skew of ${n} seconds`,"SIWX_ISSUED_AT_FUTURE");this.issuedAt=i;this.clockSkewSeconds=n;this.name="SiwxIssuedAtFutureError";}issuedAt;clockSkewSeconds},T=class extends g{constructor(i){super(`Message not valid before ${i}`,"SIWX_NOT_BEFORE");this.notBefore=i;this.name="SiwxNotBeforeError";}notBefore},C=class extends g{constructor(i,n){super(`Session lifetime of ${i} seconds exceeds maximum allowed lifetime of ${n} seconds`,"SIWX_SESSION_LIFETIME_EXCEEDED");this.lifetimeSeconds=i;this.maxLifetimeSeconds=n;this.name="SiwxSessionLifetimeExceededError";}lifetimeSeconds;maxLifetimeSeconds};var k=/^(?<domain>.+) wants you to sign in with your blockchain account:$/,v=/^(?<key>[A-Za-z ]+): (?<value>.+)$/,L=/^- (?<resource>.+)$/;function X(e){let t=e.split(`
3
- `);if(t.length<5)throw new f("Message is too short to be a valid CAIP-122 message.");let i=t[0]?.match(k);if(!i?.groups?.domain)throw new f('Invalid CAIP-122 header line. Expected: "{domain} wants you to sign in with your blockchain account:"');let n=i.groups.domain,a=t[1];if(!a)throw new f("Missing address on line 2.");if(t[2]!=="")throw new f("Expected blank line after address (line 3).");let r=3,o;if(t[r]&&!v.test(t[r])){if(o=t[r],r++,t[r]!=="")throw new f("Expected blank line after statement.");r++;}let s={},c=[],p=false;for(;r<t.length;){let u=t[r];if(u===void 0){r++;continue}if(u==="Resources:"){p=true,r++;continue}if(p){let l=u.match(L);if(l?.groups?.resource){c.push(l.groups.resource),r++;continue}p=false;}let x=u.match(v);x?.groups?.key&&x.groups.value&&(s[x.groups.key]=x.groups.value),r++;}let d=["URI","Version","Chain ID","Nonce","Issued At"];for(let u of d)if(!s[u])throw new f(`Missing required field in CAIP-122 message: "${u}"`);return {domain:n,address:a,statement:o,uri:s.URI,version:s.Version,chainId:s["Chain ID"],nonce:s.Nonce,issuedAt:s["Issued At"],expirationTime:s["Expiration Time"],notBefore:s["Not Before"],requestId:s["Request ID"],resources:c.length>0?c:void 0}}function h(e){return e.startsWith("solana:")?getSolanaChainId(e)??e:e}function D(e,t){if(!t||t.length===0)return true;let i=h(e);return t.some(n=>h(n)===i)}var B=/^https?:\/\/.+/,F=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;function G(e){if(!e||e.trim().length===0)return "domain must be a non-empty string.";if(e.includes(`
4
- `))return "domain must not contain newline characters."}function j(e){if(!parseCaip10AccountId(e))return `address must be CAIP-10 compliant (namespace:chainRef:address). Got: "${e}"`}function q(e){if(!B.test(e))return `uri must be a valid RFC 3986 URI starting with http(s)://. Got: "${e}"`}function z(e){if(!parseCaip2ChainId(e))return `chainId must be a valid CAIP-2 identifier (namespace:reference). Got: "${e}"`}function H(e){if(!e||e.length<8)return `nonce must be at least 8 characters long. Got length: ${e?.length??0}`;if(!/^[a-zA-Z0-9]+$/.test(e))return `nonce must be alphanumeric. Got: "${e}"`}function _(e,t){if(!F.test(e))return `${t} must be a valid ISO 8601 datetime string. Got: "${e}"`}function Z(e,t=new Date,i=0){let n=new Date(e);if(isNaN(n.getTime()))return `expirationTime is not a valid date: "${e}"`;if(n.getTime()+i*1e3<t.getTime())return `Message has expired. expirationTime was: ${e}`}function U(e,t,i=new Date){if(!t)return [];let n=[];if(t.expectedDomain!==void 0){let o=Array.isArray(t.expectedDomain)?t.expectedDomain:[t.expectedDomain];o.some(c=>c.toLowerCase()===e.domain.toLowerCase())||n.push(`Domain mismatch. Expected: [${o.join(", ")}], Received: "${e.domain}"`);}if(t.expectedUri!==void 0){let o=Array.isArray(t.expectedUri)?t.expectedUri:[t.expectedUri];o.some(c=>{if(e.uri===c)return true;let p=c.endsWith("/")?c.slice(0,-1):c;if(e.uri.startsWith(`${p}/`))return true;try{let d=new URL(e.uri),u=new URL(c);return d.origin.toLowerCase()===u.origin.toLowerCase()}catch{return false}})||n.push(`URI mismatch. Expected: [${o.join(", ")}], Received: "${e.uri}"`);}D(e.chainId,t.allowedChainIds)||n.push(`Chain ID "${e.chainId}" is not allowed. Allowed: [${t.allowedChainIds?.join(", ")}]`),t.requireExpirationTime&&!e.expirationTime&&n.push("expirationTime is required by verification policy.");let a=t.clockSkewSeconds??60,r=new Date(e.issuedAt);if(isNaN(r.getTime())||(t.maxIssuedAtAgeSeconds!==void 0&&(i.getTime()-r.getTime())/1e3>t.maxIssuedAtAgeSeconds+a&&n.push(`Message issuedAt "${e.issuedAt}" is older than the allowed max age of ${t.maxIssuedAtAgeSeconds} seconds`),r.getTime()-i.getTime()>a*1e3&&n.push(`Message issuedAt "${e.issuedAt}" is in the future beyond allowed clock skew of ${a} seconds`)),e.notBefore&&t.enforceNotBefore!==false){let o=new Date(e.notBefore);isNaN(o.getTime())||o.getTime()-i.getTime()>a*1e3&&n.push(`Message not valid before ${e.notBefore}`);}if(t.maxSessionLifetimeSeconds!==void 0&&e.expirationTime){let o=new Date(e.expirationTime);if(!isNaN(o.getTime())&&!isNaN(r.getTime())){let s=(o.getTime()-r.getTime())/1e3;s>t.maxSessionLifetimeSeconds&&n.push(`Session lifetime of ${s} seconds exceeds maximum allowed lifetime of ${t.maxSessionLifetimeSeconds} seconds`);}}return n}function Y(e,t){let i=[],n=G(e.domain);n&&i.push(n);let a=j(e.address);a&&i.push(a);let r=q(e.uri);r&&i.push(r),e.version!=="1"&&i.push(`version must be "1". Got: "${e.version}"`);let o=z(e.chainId);o&&i.push(o);let s=H(e.nonce);s&&i.push(s);let c=_(e.issuedAt,"issuedAt");c&&i.push(c);let p=t?.policy?.clockSkewSeconds??60;if(e.expirationTime){let d=_(e.expirationTime,"expirationTime");if(d)i.push(d);else if(!t?.skipExpiration){let u=Z(e.expirationTime,new Date,p);u&&i.push(u);}}if(e.notBefore){let d=_(e.notBefore,"notBefore");d&&i.push(d);}return e.statement&&e.statement.includes(`
5
- `)&&i.push("statement must not contain newline characters."),i.push(...U(e,t?.policy??{})),{valid:i.length===0,errors:i}}function J(){let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function K(e,t,i){if(!e||!e.address||!t)return false;let n=parseCaip10AccountId(e.address);if(!n||n.namespace!=="eip155"&&n.namespace!=="solana")return false;let a=n.namespace==="eip155",r=t;if(t.includes(":")){let s=parseCaip10AccountId(t);if(s?.namespace!==n.namespace)return false;r=s.address;}else if(t.startsWith("0x")!==a)return false;if(!(a?n.address.toLowerCase()===r.toLowerCase():n.address===r))return false;if(i!=null&&e.chainId){let s=String(i),c=h(s.includes(":")?s:`${n.namespace}:${s}`);if(h(e.chainId)!==c&&e.chainId!==s)return false}return true}export{y as SiwxChainNotAllowedError,$ as SiwxDomainMismatchError,m as SiwxError,I as SiwxExpiredSessionError,M as SiwxIssuedAtFutureError,b as SiwxIssuedAtStaleError,E as SiwxNonceReplayError,T as SiwxNotBeforeError,f as SiwxParseError,g as SiwxPolicyViolationError,C as SiwxSessionLifetimeExceededError,A as SiwxUnsupportedNamespaceError,R as SiwxUriMismatchError,S as SiwxValidationError,w as SiwxVerificationError,O as buildMessage,J as generateNonce,D as isChainIdAllowed,K as isSessionMatchingTarget,h as normalizeSolanaChainId,X as parseMessage,Y as validateMessage,U as validatePolicy};
1
+ import {getSolanaChainId,parseCaip10AccountId,parseCaip2ChainId}from'@tuwaio/orbit-core';var l=class extends Error{constructor(n,s="SIWX_ERROR"){super(n);this.code=s;this.name="SiwxError",Object.setPrototypeOf(this,new.target.prototype);}code},m=class extends l{constructor(t){super(t,"SIWX_PARSE_ERROR"),this.name="SiwxParseError";}},I=class extends l{constructor(n){super(`CAIP-122 message validation failed: ${n.join(", ")}`,"SIWX_VALIDATION_ERROR");this.errors=n;this.name="SiwxValidationError";}errors},$=class extends l{constructor(t){super(t,"SIWX_VERIFICATION_ERROR"),this.name="SiwxVerificationError";}},R=class extends l{constructor(n){super(`SIWX session expired at ${n}`,"SIWX_EXPIRED_SESSION");this.expirationTime=n;this.name="SiwxExpiredSessionError";}expirationTime},y=class extends l{constructor(n){super(`Nonce has already been used: ${n}`,"SIWX_NONCE_REPLAY");this.nonce=n;this.name="SiwxNonceReplayError";}nonce},b=class extends l{constructor(n){super(`Unsupported CAIP-2 namespace: "${n}". Supported: eip155, solana`,"SIWX_UNSUPPORTED_NAMESPACE");this.namespace=n;this.name="SiwxUnsupportedNamespaceError";}namespace},f=class extends l{constructor(t,n="SIWX_POLICY_VIOLATION"){super(t,n),this.name="SiwxPolicyViolationError";}},T=class extends f{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},M=class extends f{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},C=class extends f{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},_=class extends f{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},D=class extends f{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},N=class extends f{constructor(n){super(`Message not valid before ${n}`,"SIWX_NOT_BEFORE");this.notBefore=n;this.name="SiwxNotBeforeError";}notBefore},v=class extends f{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 P=["domain","address","uri","version","chainId","nonce","issuedAt"],W=[...P,"statement","expirationTime","notBefore","requestId"];function F(e){let t=[];for(let p of P){let A=e[p];(typeof A!="string"||A.trim().length===0)&&t.push(`${p} is required. Got: ${JSON.stringify(A)??"undefined"}`);}let n=p=>typeof p=="string"&&/[\r\n]/.test(p);for(let p of W)n(e[p])&&t.push(`${p} must not contain line breaks.`);if(e.resources?.some(n)&&t.push("resources must not contain line breaks."),t.length>0)throw new I(t);let{domain:s,address:a,statement:i,uri:o,version:r,chainId:c,nonce:g,issuedAt:d,expirationTime:u,notBefore:x,requestId:w,resources:E}=e,h=[`${s} wants you to sign in with your blockchain account:`,a,""];if(i&&h.push(i,""),h.push(`URI: ${o}`,`Version: ${r}`,`Chain ID: ${c}`,`Nonce: ${g}`,`Issued At: ${d}`),u&&h.push(`Expiration Time: ${u}`),x&&h.push(`Not Before: ${x}`),w&&h.push(`Request ID: ${w}`),E&&E.length>0){h.push("Resources:");for(let p of E)h.push(`- ${p}`);}return h.join(`
2
+ `)}function S(e){return e.startsWith("solana:")?getSolanaChainId(e)??e:e}function U(e,t){if(!t||t.length===0)return true;let n=S(e);return t.some(s=>S(s)===n)}var L=/^[A-Za-z0-9\-._~%!$&'()*+,;=:@[\]]+$/,j=/^https?:\/\/.+/,q=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;function z(e){if(!e||e.trim().length===0)return "domain must be a non-empty string.";if(e.includes(`
3
+ `))return "domain must not contain newline characters.";if(!L.test(e))return `domain must be an RFC 3986 authority such as "app.example.com" or "localhost:3000". Got: ${JSON.stringify(e)}`}function H(e){if(!parseCaip10AccountId(e))return `address must be CAIP-10 compliant (namespace:chainRef:address). Got: "${e}"`}function Y(e){if(!j.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 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 O(e,t){if(!q.test(e))return `${t} must be a valid ISO 8601 datetime string. Got: "${e}"`}function Q(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 X(e,t,n=new Date){if(!t)return [];let s=[];if(t.expectedDomain!==void 0){let o=Array.isArray(t.expectedDomain)?t.expectedDomain:[t.expectedDomain];o.some(c=>c.toLowerCase()===e.domain.toLowerCase())||s.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 g=c.endsWith("/")?c.slice(0,-1):c;if(e.uri.startsWith(`${g}/`))return true;try{let d=new URL(e.uri),u=new URL(c);return d.origin.toLowerCase()===u.origin.toLowerCase()}catch{return false}})||s.push(`URI mismatch. Expected: [${o.join(", ")}], Received: "${e.uri}"`);}U(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 o=new Date(e.notBefore);isNaN(o.getTime())||o.getTime()-n.getTime()>a*1e3&&s.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(i.getTime())){let r=(o.getTime()-i.getTime())/1e3;r>t.maxSessionLifetimeSeconds&&s.push(`Session lifetime of ${r} seconds exceeds maximum allowed lifetime of ${t.maxSessionLifetimeSeconds} seconds`);}}return s}function K(e,t){let n=[],s=z(e.domain);s&&n.push(s);let a=H(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 o=Z(e.chainId);o&&n.push(o);let r=J(e.nonce);r&&n.push(r);let c=O(e.issuedAt,"issuedAt");c&&n.push(c);let g=t?.policy?.clockSkewSeconds??60;if(e.expirationTime){let d=O(e.expirationTime,"expirationTime");if(d)n.push(d);else if(!t?.skipExpiration){let u=Q(e.expirationTime,new Date,g);u&&n.push(u);}}if(e.notBefore){let d=O(e.notBefore,"notBefore");d&&n.push(d);}return e.statement&&e.statement.includes(`
4
+ `)&&n.push("statement must not contain newline characters."),n.push(...X(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=parseCaip10AccountId(e.address);if(!s||s.namespace!=="eip155"&&s.namespace!=="solana")return false;let a=s.namespace==="eip155",i=t;if(t.includes(":")){let r=parseCaip10AccountId(t);if(r?.namespace!==s.namespace)return false;i=r.address;}else if(t.startsWith("0x")!==a)return false;if(!(a?s.address.toLowerCase()===i.toLowerCase():s.address===i))return false;if(n!=null&&e.chainId){let r=String(n),c=S(r.includes(":")?r:`${s.namespace}:${r}`);if(S(e.chainId)!==c&&e.chainId!==r)return false}return true}var ne=new RegExp(`^(?<domain>${L.source.slice(1,-1)}) wants you to sign in with your blockchain account:$`),V=/^(?<key>[A-Za-z ]+): (?<value>.+)$/,se=/^- (?<resource>.+)$/;function ie(e){let t=e.split(`
5
+ `);if(t.length<5)throw new m("Message is too short to be a valid CAIP-122 message.");let n=t[0]?.match(ne);if(!n?.groups?.domain)throw new m('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 m("Missing address on line 2.");if(t[2]!=="")throw new m("Expected blank line after address (line 3).");let i=3,o;if(t[i]&&!V.test(t[i])){if(o=t[i],i++,t[i]!=="")throw new m("Expected blank line after statement.");i++;}let r={},c=[],g=false;for(;i<t.length;){let u=t[i];if(u===void 0){i++;continue}if(u==="Resources:"){g=true,i++;continue}if(g){let w=u.match(se);if(w?.groups?.resource){c.push(w.groups.resource),i++;continue}g=false;}let x=u.match(V);x?.groups?.key&&x.groups.value&&(r[x.groups.key]=x.groups.value),i++;}let d=["URI","Version","Chain ID","Nonce","Issued At"];for(let u of d)if(!r[u])throw new m(`Missing required field in CAIP-122 message: "${u}"`);return {domain:s,address:a,statement:o,uri:r.URI,version:r.Version,chainId:r["Chain ID"],nonce:r.Nonce,issuedAt:r["Issued At"],expirationTime:r["Expiration Time"],notBefore:r["Not Before"],requestId:r["Request ID"],resources:c.length>0?c:void 0}}export{C as SiwxChainNotAllowedError,T as SiwxDomainMismatchError,l as SiwxError,R as SiwxExpiredSessionError,D as SiwxIssuedAtFutureError,_ as SiwxIssuedAtStaleError,y as SiwxNonceReplayError,N as SiwxNotBeforeError,m as SiwxParseError,f as SiwxPolicyViolationError,v as SiwxSessionLifetimeExceededError,b as SiwxUnsupportedNamespaceError,M as SiwxUriMismatchError,I as SiwxValidationError,$ as SiwxVerificationError,F as buildMessage,ee as generateNonce,U as isChainIdAllowed,te as isSessionMatchingTarget,S as normalizeSolanaChainId,ie as parseMessage,K as validateMessage,X as validatePolicy};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tuwaio/siwx-core",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "private": false,
5
5
  "author": "Oleksandr Tkach",
6
6
  "license": "Apache-2.0",