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