@tuwaio/siwx-core 0.7.3 → 0.7.4
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 +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +5 -5
- package/dist/index.mjs +5 -5
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -12,7 +12,7 @@ Its only dependency is the peer [`@tuwaio/orbit-core`](https://orbit.docs.tuwa.i
|
|
|
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) 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
|
|
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, and the account must be on the chain of `Chain ID`.
|
|
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.
|
package/dist/index.d.mts
CHANGED
|
@@ -526,8 +526,8 @@ declare function validatePolicy(fields: SiwxMessageFields, policy?: SiwxVerifica
|
|
|
526
526
|
* Validates the format of CAIP-122 message fields and, optionally, a verification policy. Collects every failure
|
|
527
527
|
* instead of stopping at the first one.
|
|
528
528
|
*
|
|
529
|
-
* Checks: non-empty single-line `domain`, CAIP-10 `address`, `http(s)://` `uri`, `version` `"1"`, CAIP-2 `chainId`,
|
|
530
|
-
* alphanumeric `nonce` of at least 8 characters, ISO 8601 `issuedAt` / `expirationTime` / `notBefore`, single-line
|
|
529
|
+
* Checks: non-empty single-line `domain`, CAIP-10 `address`, `http(s)://` `uri`, `version` `"1"`, CAIP-2 `chainId`, an
|
|
530
|
+
* `address` on the chain of `chainId` (a Solana cluster is one chain under its name and its genesis hash), alphanumeric `nonce` of at least 8 characters, ISO 8601 `issuedAt` / `expirationTime` / `notBefore`, single-line
|
|
531
531
|
* `statement`, and that `expirationTime` (plus the policy clock skew, 60 seconds by default) has not passed.
|
|
532
532
|
* Then it runs {@link validatePolicy} with `options.policy`, or with an empty policy: so `issuedAt` in the future
|
|
533
533
|
* and a `notBefore` that has not been reached are always rejected (unless `enforceNotBefore` is `false`), and the
|
package/dist/index.d.ts
CHANGED
|
@@ -526,8 +526,8 @@ declare function validatePolicy(fields: SiwxMessageFields, policy?: SiwxVerifica
|
|
|
526
526
|
* Validates the format of CAIP-122 message fields and, optionally, a verification policy. Collects every failure
|
|
527
527
|
* instead of stopping at the first one.
|
|
528
528
|
*
|
|
529
|
-
* Checks: non-empty single-line `domain`, CAIP-10 `address`, `http(s)://` `uri`, `version` `"1"`, CAIP-2 `chainId`,
|
|
530
|
-
* alphanumeric `nonce` of at least 8 characters, ISO 8601 `issuedAt` / `expirationTime` / `notBefore`, single-line
|
|
529
|
+
* Checks: non-empty single-line `domain`, CAIP-10 `address`, `http(s)://` `uri`, `version` `"1"`, CAIP-2 `chainId`, an
|
|
530
|
+
* `address` on the chain of `chainId` (a Solana cluster is one chain under its name and its genesis hash), alphanumeric `nonce` of at least 8 characters, ISO 8601 `issuedAt` / `expirationTime` / `notBefore`, single-line
|
|
531
531
|
* `statement`, and that `expirationTime` (plus the policy clock skew, 60 seconds by default) has not passed.
|
|
532
532
|
* Then it runs {@link validatePolicy} with `options.policy`, or with an empty policy: so `issuedAt` in the future
|
|
533
533
|
* and a `notBefore` that has not been reached are always rejected (unless `enforceNotBefore` is `false`), and the
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
'use strict';var orbitCore=require('@tuwaio/orbit-core');var
|
|
2
|
-
`)}function
|
|
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 Y(e){if(!orbitCore.parseCaip10AccountId(e))return `address must be CAIP-10 compliant (namespace:chainRef:address). Got: "${e}"`}function Z(e){if(!q.test(e))return `uri must be a valid RFC 3986 URI starting with http(s)://. Got: "${e}"`}function J(e){if(!orbitCore.parseCaip2ChainId(e))return `chainId must be a valid CAIP-2 identifier (namespace:reference). Got: "${e}"`}function Q(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
|
|
4
|
-
`)&&n.push("statement must not contain newline characters."),n.push(...
|
|
5
|
-
`);if(t.length<5)throw new
|
|
1
|
+
'use strict';var orbitCore=require('@tuwaio/orbit-core');var l=class extends Error{constructor(n,i="SIWX_ERROR"){super(n);this.code=i;this.name="SiwxError",Object.setPrototypeOf(this,new.target.prototype);}code},f=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},R=class extends l{constructor(t){super(t,"SIWX_VERIFICATION_ERROR"),this.name="SiwxVerificationError";}},y=class extends l{constructor(n){super(`SIWX session expired at ${n}`,"SIWX_EXPIRED_SESSION");this.expirationTime=n;this.name="SiwxExpiredSessionError";}expirationTime},b=class extends l{constructor(n){super(`Nonce has already been used: ${n}`,"SIWX_NONCE_REPLAY");this.nonce=n;this.name="SiwxNonceReplayError";}nonce},T=class extends l{constructor(n){super(`Unsupported CAIP-2 namespace: "${n}". Supported: eip155, solana`,"SIWX_UNSUPPORTED_NAMESPACE");this.namespace=n;this.name="SiwxUnsupportedNamespaceError";}namespace},g=class extends l{constructor(t,n="SIWX_POLICY_VIOLATION"){super(t,n),this.name="SiwxPolicyViolationError";}},M=class extends g{constructor(n,i){let a=Array.isArray(n)?n.join(", "):n;super(`Domain mismatch. Expected: [${a}], Received: "${i}"`,"SIWX_DOMAIN_MISMATCH");this.expected=n;this.received=i;this.name="SiwxDomainMismatchError";}expected;received},C=class extends g{constructor(n,i){let a=Array.isArray(n)?n.join(", "):n;super(`URI mismatch. Expected: [${a}], Received: "${i}"`,"SIWX_URI_MISMATCH");this.expected=n;this.received=i;this.name="SiwxUriMismatchError";}expected;received},_=class extends g{constructor(n,i){super(`Chain ID "${i}" is not allowed. Allowed: [${n.join(", ")}]`,"SIWX_CHAIN_NOT_ALLOWED");this.allowedChainIds=n;this.received=i;this.name="SiwxChainNotAllowedError";}allowedChainIds;received},D=class extends g{constructor(n,i){super(`Message issuedAt "${n}" is older than the allowed max age of ${i} seconds`,"SIWX_ISSUED_AT_STALE");this.issuedAt=n;this.maxAgeSeconds=i;this.name="SiwxIssuedAtStaleError";}issuedAt;maxAgeSeconds},N=class extends g{constructor(n,i){super(`Message issuedAt "${n}" is in the future beyond allowed clock skew of ${i} seconds`,"SIWX_ISSUED_AT_FUTURE");this.issuedAt=n;this.clockSkewSeconds=i;this.name="SiwxIssuedAtFutureError";}issuedAt;clockSkewSeconds},v=class extends g{constructor(n){super(`Message not valid before ${n}`,"SIWX_NOT_BEFORE");this.notBefore=n;this.name="SiwxNotBeforeError";}notBefore},U=class extends g{constructor(n,i){super(`Session lifetime of ${n} seconds exceeds maximum allowed lifetime of ${i} seconds`,"SIWX_SESSION_LIFETIME_EXCEEDED");this.lifetimeSeconds=n;this.maxLifetimeSeconds=i;this.name="SiwxSessionLifetimeExceededError";}lifetimeSeconds;maxLifetimeSeconds};var P=["domain","address","uri","version","chainId","nonce","issuedAt"],F=[...P,"statement","expirationTime","notBefore","requestId"];function B(e){let t=[];for(let m of P){let $=e[m];(typeof $!="string"||$.trim().length===0)&&t.push(`${m} is required. Got: ${JSON.stringify($)??"undefined"}`);}let n=m=>typeof m=="string"&&/[\r\n]/.test(m);for(let m of F)n(e[m])&&t.push(`${m} 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:i,address:a,statement:r,uri:s,version:o,chainId:u,nonce:d,issuedAt:S,expirationTime:c,notBefore:p,requestId:w,resources:A}=e,h=[`${i} wants you to sign in with your blockchain account:`,a,""];if(r&&h.push(r,""),h.push(`URI: ${s}`,`Version: ${o}`,`Chain ID: ${u}`,`Nonce: ${d}`,`Issued At: ${S}`),c&&h.push(`Expiration Time: ${c}`),p&&h.push(`Not Before: ${p}`),w&&h.push(`Request ID: ${w}`),A&&A.length>0){h.push("Resources:");for(let m of A)h.push(`- ${m}`);}return h.join(`
|
|
2
|
+
`)}function x(e){return e.startsWith("solana:")?orbitCore.getSolanaChainId(e)??e:e}function O(e,t){if(!t||t.length===0)return true;let n=x(e);return t.some(i=>x(i)===n)}var L=/^[A-Za-z0-9\-._~%!$&'()*+,;=:@[\]]+$/,q=/^https?:\/\/.+/,z=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;function H(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 Y(e){if(!orbitCore.parseCaip10AccountId(e))return `address must be CAIP-10 compliant (namespace:chainRef:address). Got: "${e}"`}function Z(e){if(!q.test(e))return `uri must be a valid RFC 3986 URI starting with http(s)://. Got: "${e}"`}function J(e){if(!orbitCore.parseCaip2ChainId(e))return `chainId must be a valid CAIP-2 identifier (namespace:reference). Got: "${e}"`}function Q(e,t){let n=orbitCore.parseCaip10AccountId(e);if(!(!n||!orbitCore.parseCaip2ChainId(t))&&x(n.chainId)!==x(t))return `address is an account of "${n.chainId}", and chainId is "${t}": a sign-in is of one chain.`}function K(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 k(e,t){if(!z.test(e))return `${t} must be a valid ISO 8601 datetime string. Got: "${e}"`}function ee(e,t=new Date,n=0){let i=new Date(e);if(isNaN(i.getTime()))return `expirationTime is not a valid date: "${e}"`;if(i.getTime()+n*1e3<t.getTime())return `Message has expired. expirationTime was: ${e}`}function V(e,t,n=new Date){if(!t)return [];let i=[];if(t.expectedDomain!==void 0){let s=Array.isArray(t.expectedDomain)?t.expectedDomain:[t.expectedDomain];s.some(u=>u.toLowerCase()===e.domain.toLowerCase())||i.push(`Domain mismatch. Expected: [${s.join(", ")}], Received: "${e.domain}"`);}if(t.expectedUri!==void 0){let s=Array.isArray(t.expectedUri)?t.expectedUri:[t.expectedUri];s.some(u=>{if(e.uri===u)return true;let d=u.endsWith("/")?u.slice(0,-1):u;if(e.uri.startsWith(`${d}/`))return true;try{let S=new URL(e.uri),c=new URL(u);return S.origin.toLowerCase()===c.origin.toLowerCase()}catch{return false}})||i.push(`URI mismatch. Expected: [${s.join(", ")}], Received: "${e.uri}"`);}O(e.chainId,t.allowedChainIds)||i.push(`Chain ID "${e.chainId}" is not allowed. Allowed: [${t.allowedChainIds?.join(", ")}]`),t.requireExpirationTime&&!e.expirationTime&&i.push("expirationTime is required by verification policy.");let a=t.clockSkewSeconds??60,r=new Date(e.issuedAt);if(isNaN(r.getTime())||(t.maxIssuedAtAgeSeconds!==void 0&&(n.getTime()-r.getTime())/1e3>t.maxIssuedAtAgeSeconds+a&&i.push(`Message issuedAt "${e.issuedAt}" is older than the allowed max age of ${t.maxIssuedAtAgeSeconds} seconds`),r.getTime()-n.getTime()>a*1e3&&i.push(`Message issuedAt "${e.issuedAt}" is in the future beyond allowed clock skew of ${a} seconds`)),e.notBefore&&t.enforceNotBefore!==false){let s=new Date(e.notBefore);isNaN(s.getTime())||s.getTime()-n.getTime()>a*1e3&&i.push(`Message not valid before ${e.notBefore}`);}if(t.maxSessionLifetimeSeconds!==void 0&&e.expirationTime){let s=new Date(e.expirationTime);if(!isNaN(s.getTime())&&!isNaN(r.getTime())){let o=(s.getTime()-r.getTime())/1e3;o>t.maxSessionLifetimeSeconds&&i.push(`Session lifetime of ${o} seconds exceeds maximum allowed lifetime of ${t.maxSessionLifetimeSeconds} seconds`);}}return i}function te(e,t){let n=[],i=H(e.domain);i&&n.push(i);let a=Y(e.address);a&&n.push(a);let r=Z(e.uri);r&&n.push(r),e.version!=="1"&&n.push(`version must be "1". Got: "${e.version}"`);let s=J(e.chainId);s&&n.push(s);let o=Q(e.address,e.chainId);o&&n.push(o);let u=K(e.nonce);u&&n.push(u);let d=k(e.issuedAt,"issuedAt");d&&n.push(d);let S=t?.policy?.clockSkewSeconds??60;if(e.expirationTime){let c=k(e.expirationTime,"expirationTime");if(c)n.push(c);else if(!t?.skipExpiration){let p=ee(e.expirationTime,new Date,S);p&&n.push(p);}}if(e.notBefore){let c=k(e.notBefore,"notBefore");c&&n.push(c);}return e.statement&&e.statement.includes(`
|
|
4
|
+
`)&&n.push("statement must not contain newline characters."),n.push(...V(e,t?.policy??{})),{valid:n.length===0,errors:n}}function ne(){let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function ie(e,t,n){if(!e||!e.address||!t)return false;let i=orbitCore.parseCaip10AccountId(e.address);if(!i||i.namespace!=="eip155"&&i.namespace!=="solana")return false;let a=i.namespace==="eip155",r=t;if(t.includes(":")){let s=orbitCore.parseCaip10AccountId(t);if(s?.namespace!==i.namespace)return false;r=s.address;}else if(t.startsWith("0x")!==a)return false;if(!orbitCore.isSameAddress(i.namespace,i.address,r))return false;if(n!=null&&e.chainId){let s=String(n),o=x(s.includes(":")?s:`${i.namespace}:${s}`);if(x(e.chainId)!==o&&e.chainId!==s)return false}return true}var se=new RegExp(`^(?<domain>${L.source.slice(1,-1)}) wants you to sign in with your blockchain account:$`),W=/^(?<key>[A-Za-z ]+): (?<value>.+)$/,re=/^- (?<resource>.+)$/;function oe(e){let t=e.split(`
|
|
5
|
+
`);if(t.length<5)throw new f("Message is too short to be a valid CAIP-122 message.");let n=t[0]?.match(se);if(!n?.groups?.domain)throw new f('Invalid CAIP-122 header line. Expected: "{domain} wants you to sign in with your blockchain account:"');let i=n.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,s;if(t[r]&&!W.test(t[r])){if(s=t[r],r++,t[r]!=="")throw new f("Expected blank line after statement.");r++;}let o={},u=[],d=false;for(;r<t.length;){let c=t[r];if(c===void 0){r++;continue}if(c==="Resources:"){d=true,r++;continue}if(d){let w=c.match(re);if(w?.groups?.resource){u.push(w.groups.resource),r++;continue}d=false;}let p=c.match(W);p?.groups?.key&&p.groups.value&&(o[p.groups.key]=p.groups.value),r++;}let S=["URI","Version","Chain ID","Nonce","Issued At"];for(let c of S)if(!o[c])throw new f(`Missing required field in CAIP-122 message: "${c}"`);return {domain:i,address:a,statement:s,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}}exports.SiwxChainNotAllowedError=_;exports.SiwxDomainMismatchError=M;exports.SiwxError=l;exports.SiwxExpiredSessionError=y;exports.SiwxIssuedAtFutureError=N;exports.SiwxIssuedAtStaleError=D;exports.SiwxNonceReplayError=b;exports.SiwxNotBeforeError=v;exports.SiwxParseError=f;exports.SiwxPolicyViolationError=g;exports.SiwxSessionLifetimeExceededError=U;exports.SiwxUnsupportedNamespaceError=T;exports.SiwxUriMismatchError=C;exports.SiwxValidationError=I;exports.SiwxVerificationError=R;exports.buildMessage=B;exports.generateNonce=ne;exports.isChainIdAllowed=O;exports.isSessionMatchingTarget=ie;exports.normalizeSolanaChainId=x;exports.parseMessage=oe;exports.validateMessage=te;exports.validatePolicy=V;
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {getSolanaChainId,parseCaip10AccountId,isSameAddress,parseCaip2ChainId}from'@tuwaio/orbit-core';var
|
|
2
|
-
`)}function
|
|
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 Y(e){if(!parseCaip10AccountId(e))return `address must be CAIP-10 compliant (namespace:chainRef:address). Got: "${e}"`}function Z(e){if(!q.test(e))return `uri must be a valid RFC 3986 URI starting with http(s)://. Got: "${e}"`}function J(e){if(!parseCaip2ChainId(e))return `chainId must be a valid CAIP-2 identifier (namespace:reference). Got: "${e}"`}function Q(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
|
|
4
|
-
`)&&n.push("statement must not contain newline characters."),n.push(...
|
|
5
|
-
`);if(t.length<5)throw new
|
|
1
|
+
import {getSolanaChainId,parseCaip10AccountId,isSameAddress,parseCaip2ChainId}from'@tuwaio/orbit-core';var l=class extends Error{constructor(n,i="SIWX_ERROR"){super(n);this.code=i;this.name="SiwxError",Object.setPrototypeOf(this,new.target.prototype);}code},f=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},R=class extends l{constructor(t){super(t,"SIWX_VERIFICATION_ERROR"),this.name="SiwxVerificationError";}},y=class extends l{constructor(n){super(`SIWX session expired at ${n}`,"SIWX_EXPIRED_SESSION");this.expirationTime=n;this.name="SiwxExpiredSessionError";}expirationTime},b=class extends l{constructor(n){super(`Nonce has already been used: ${n}`,"SIWX_NONCE_REPLAY");this.nonce=n;this.name="SiwxNonceReplayError";}nonce},T=class extends l{constructor(n){super(`Unsupported CAIP-2 namespace: "${n}". Supported: eip155, solana`,"SIWX_UNSUPPORTED_NAMESPACE");this.namespace=n;this.name="SiwxUnsupportedNamespaceError";}namespace},g=class extends l{constructor(t,n="SIWX_POLICY_VIOLATION"){super(t,n),this.name="SiwxPolicyViolationError";}},M=class extends g{constructor(n,i){let a=Array.isArray(n)?n.join(", "):n;super(`Domain mismatch. Expected: [${a}], Received: "${i}"`,"SIWX_DOMAIN_MISMATCH");this.expected=n;this.received=i;this.name="SiwxDomainMismatchError";}expected;received},C=class extends g{constructor(n,i){let a=Array.isArray(n)?n.join(", "):n;super(`URI mismatch. Expected: [${a}], Received: "${i}"`,"SIWX_URI_MISMATCH");this.expected=n;this.received=i;this.name="SiwxUriMismatchError";}expected;received},_=class extends g{constructor(n,i){super(`Chain ID "${i}" is not allowed. Allowed: [${n.join(", ")}]`,"SIWX_CHAIN_NOT_ALLOWED");this.allowedChainIds=n;this.received=i;this.name="SiwxChainNotAllowedError";}allowedChainIds;received},D=class extends g{constructor(n,i){super(`Message issuedAt "${n}" is older than the allowed max age of ${i} seconds`,"SIWX_ISSUED_AT_STALE");this.issuedAt=n;this.maxAgeSeconds=i;this.name="SiwxIssuedAtStaleError";}issuedAt;maxAgeSeconds},N=class extends g{constructor(n,i){super(`Message issuedAt "${n}" is in the future beyond allowed clock skew of ${i} seconds`,"SIWX_ISSUED_AT_FUTURE");this.issuedAt=n;this.clockSkewSeconds=i;this.name="SiwxIssuedAtFutureError";}issuedAt;clockSkewSeconds},v=class extends g{constructor(n){super(`Message not valid before ${n}`,"SIWX_NOT_BEFORE");this.notBefore=n;this.name="SiwxNotBeforeError";}notBefore},U=class extends g{constructor(n,i){super(`Session lifetime of ${n} seconds exceeds maximum allowed lifetime of ${i} seconds`,"SIWX_SESSION_LIFETIME_EXCEEDED");this.lifetimeSeconds=n;this.maxLifetimeSeconds=i;this.name="SiwxSessionLifetimeExceededError";}lifetimeSeconds;maxLifetimeSeconds};var P=["domain","address","uri","version","chainId","nonce","issuedAt"],F=[...P,"statement","expirationTime","notBefore","requestId"];function B(e){let t=[];for(let m of P){let $=e[m];(typeof $!="string"||$.trim().length===0)&&t.push(`${m} is required. Got: ${JSON.stringify($)??"undefined"}`);}let n=m=>typeof m=="string"&&/[\r\n]/.test(m);for(let m of F)n(e[m])&&t.push(`${m} 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:i,address:a,statement:r,uri:s,version:o,chainId:u,nonce:d,issuedAt:S,expirationTime:c,notBefore:p,requestId:w,resources:A}=e,h=[`${i} wants you to sign in with your blockchain account:`,a,""];if(r&&h.push(r,""),h.push(`URI: ${s}`,`Version: ${o}`,`Chain ID: ${u}`,`Nonce: ${d}`,`Issued At: ${S}`),c&&h.push(`Expiration Time: ${c}`),p&&h.push(`Not Before: ${p}`),w&&h.push(`Request ID: ${w}`),A&&A.length>0){h.push("Resources:");for(let m of A)h.push(`- ${m}`);}return h.join(`
|
|
2
|
+
`)}function x(e){return e.startsWith("solana:")?getSolanaChainId(e)??e:e}function O(e,t){if(!t||t.length===0)return true;let n=x(e);return t.some(i=>x(i)===n)}var L=/^[A-Za-z0-9\-._~%!$&'()*+,;=:@[\]]+$/,q=/^https?:\/\/.+/,z=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;function H(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 Y(e){if(!parseCaip10AccountId(e))return `address must be CAIP-10 compliant (namespace:chainRef:address). Got: "${e}"`}function Z(e){if(!q.test(e))return `uri must be a valid RFC 3986 URI starting with http(s)://. Got: "${e}"`}function J(e){if(!parseCaip2ChainId(e))return `chainId must be a valid CAIP-2 identifier (namespace:reference). Got: "${e}"`}function Q(e,t){let n=parseCaip10AccountId(e);if(!(!n||!parseCaip2ChainId(t))&&x(n.chainId)!==x(t))return `address is an account of "${n.chainId}", and chainId is "${t}": a sign-in is of one chain.`}function K(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 k(e,t){if(!z.test(e))return `${t} must be a valid ISO 8601 datetime string. Got: "${e}"`}function ee(e,t=new Date,n=0){let i=new Date(e);if(isNaN(i.getTime()))return `expirationTime is not a valid date: "${e}"`;if(i.getTime()+n*1e3<t.getTime())return `Message has expired. expirationTime was: ${e}`}function V(e,t,n=new Date){if(!t)return [];let i=[];if(t.expectedDomain!==void 0){let s=Array.isArray(t.expectedDomain)?t.expectedDomain:[t.expectedDomain];s.some(u=>u.toLowerCase()===e.domain.toLowerCase())||i.push(`Domain mismatch. Expected: [${s.join(", ")}], Received: "${e.domain}"`);}if(t.expectedUri!==void 0){let s=Array.isArray(t.expectedUri)?t.expectedUri:[t.expectedUri];s.some(u=>{if(e.uri===u)return true;let d=u.endsWith("/")?u.slice(0,-1):u;if(e.uri.startsWith(`${d}/`))return true;try{let S=new URL(e.uri),c=new URL(u);return S.origin.toLowerCase()===c.origin.toLowerCase()}catch{return false}})||i.push(`URI mismatch. Expected: [${s.join(", ")}], Received: "${e.uri}"`);}O(e.chainId,t.allowedChainIds)||i.push(`Chain ID "${e.chainId}" is not allowed. Allowed: [${t.allowedChainIds?.join(", ")}]`),t.requireExpirationTime&&!e.expirationTime&&i.push("expirationTime is required by verification policy.");let a=t.clockSkewSeconds??60,r=new Date(e.issuedAt);if(isNaN(r.getTime())||(t.maxIssuedAtAgeSeconds!==void 0&&(n.getTime()-r.getTime())/1e3>t.maxIssuedAtAgeSeconds+a&&i.push(`Message issuedAt "${e.issuedAt}" is older than the allowed max age of ${t.maxIssuedAtAgeSeconds} seconds`),r.getTime()-n.getTime()>a*1e3&&i.push(`Message issuedAt "${e.issuedAt}" is in the future beyond allowed clock skew of ${a} seconds`)),e.notBefore&&t.enforceNotBefore!==false){let s=new Date(e.notBefore);isNaN(s.getTime())||s.getTime()-n.getTime()>a*1e3&&i.push(`Message not valid before ${e.notBefore}`);}if(t.maxSessionLifetimeSeconds!==void 0&&e.expirationTime){let s=new Date(e.expirationTime);if(!isNaN(s.getTime())&&!isNaN(r.getTime())){let o=(s.getTime()-r.getTime())/1e3;o>t.maxSessionLifetimeSeconds&&i.push(`Session lifetime of ${o} seconds exceeds maximum allowed lifetime of ${t.maxSessionLifetimeSeconds} seconds`);}}return i}function te(e,t){let n=[],i=H(e.domain);i&&n.push(i);let a=Y(e.address);a&&n.push(a);let r=Z(e.uri);r&&n.push(r),e.version!=="1"&&n.push(`version must be "1". Got: "${e.version}"`);let s=J(e.chainId);s&&n.push(s);let o=Q(e.address,e.chainId);o&&n.push(o);let u=K(e.nonce);u&&n.push(u);let d=k(e.issuedAt,"issuedAt");d&&n.push(d);let S=t?.policy?.clockSkewSeconds??60;if(e.expirationTime){let c=k(e.expirationTime,"expirationTime");if(c)n.push(c);else if(!t?.skipExpiration){let p=ee(e.expirationTime,new Date,S);p&&n.push(p);}}if(e.notBefore){let c=k(e.notBefore,"notBefore");c&&n.push(c);}return e.statement&&e.statement.includes(`
|
|
4
|
+
`)&&n.push("statement must not contain newline characters."),n.push(...V(e,t?.policy??{})),{valid:n.length===0,errors:n}}function ne(){let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function ie(e,t,n){if(!e||!e.address||!t)return false;let i=parseCaip10AccountId(e.address);if(!i||i.namespace!=="eip155"&&i.namespace!=="solana")return false;let a=i.namespace==="eip155",r=t;if(t.includes(":")){let s=parseCaip10AccountId(t);if(s?.namespace!==i.namespace)return false;r=s.address;}else if(t.startsWith("0x")!==a)return false;if(!isSameAddress(i.namespace,i.address,r))return false;if(n!=null&&e.chainId){let s=String(n),o=x(s.includes(":")?s:`${i.namespace}:${s}`);if(x(e.chainId)!==o&&e.chainId!==s)return false}return true}var se=new RegExp(`^(?<domain>${L.source.slice(1,-1)}) wants you to sign in with your blockchain account:$`),W=/^(?<key>[A-Za-z ]+): (?<value>.+)$/,re=/^- (?<resource>.+)$/;function oe(e){let t=e.split(`
|
|
5
|
+
`);if(t.length<5)throw new f("Message is too short to be a valid CAIP-122 message.");let n=t[0]?.match(se);if(!n?.groups?.domain)throw new f('Invalid CAIP-122 header line. Expected: "{domain} wants you to sign in with your blockchain account:"');let i=n.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,s;if(t[r]&&!W.test(t[r])){if(s=t[r],r++,t[r]!=="")throw new f("Expected blank line after statement.");r++;}let o={},u=[],d=false;for(;r<t.length;){let c=t[r];if(c===void 0){r++;continue}if(c==="Resources:"){d=true,r++;continue}if(d){let w=c.match(re);if(w?.groups?.resource){u.push(w.groups.resource),r++;continue}d=false;}let p=c.match(W);p?.groups?.key&&p.groups.value&&(o[p.groups.key]=p.groups.value),r++;}let S=["URI","Version","Chain ID","Nonce","Issued At"];for(let c of S)if(!o[c])throw new f(`Missing required field in CAIP-122 message: "${c}"`);return {domain:i,address:a,statement:s,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}}export{_ as SiwxChainNotAllowedError,M as SiwxDomainMismatchError,l as SiwxError,y as SiwxExpiredSessionError,N as SiwxIssuedAtFutureError,D as SiwxIssuedAtStaleError,b as SiwxNonceReplayError,v as SiwxNotBeforeError,f as SiwxParseError,g as SiwxPolicyViolationError,U as SiwxSessionLifetimeExceededError,T as SiwxUnsupportedNamespaceError,C as SiwxUriMismatchError,I as SiwxValidationError,R as SiwxVerificationError,B as buildMessage,ne as generateNonce,O as isChainIdAllowed,ie as isSessionMatchingTarget,x as normalizeSolanaChainId,oe as parseMessage,te as validateMessage,V as validatePolicy};
|