@slicekit/erc8128 0.0.1
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 +169 -0
- package/dist/esm/index.d.ts +143 -0
- package/dist/esm/index.js +7 -0
- package/dist/esm/index.js.map +25 -0
- package/package.json +46 -0
package/README.md
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
# @slicekit/eip8128
|
|
2
|
+
|
|
3
|
+
Sign and verify HTTP requests with Ethereum wallets using [ERC-8128](https://eips.ethereum.org/EIPS/eip-8128).
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- **Fetch-native** — Works in browsers, workers, Node.js 18+, Bun, Deno
|
|
8
|
+
- **Full RFC 9421 compliance** — HTTP Message Signatures with Ethereum extension
|
|
9
|
+
- **Request binding** — Sign URL, method, headers, and body
|
|
10
|
+
- **Replay protection** — Built-in nonce handling
|
|
11
|
+
|
|
12
|
+
## Installation
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npm install @slicekit/eip8128
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Quick Start
|
|
19
|
+
|
|
20
|
+
### Sign a Request
|
|
21
|
+
|
|
22
|
+
```typescript
|
|
23
|
+
import { createClient } from '@slicekit/eip8128'
|
|
24
|
+
import { privateKeyToAccount } from 'viem/accounts'
|
|
25
|
+
|
|
26
|
+
const account = privateKeyToAccount('0x...')
|
|
27
|
+
|
|
28
|
+
const signer = {
|
|
29
|
+
chainId: 1,
|
|
30
|
+
address: account.address,
|
|
31
|
+
signMessage: (message) => account.signMessage({ message: { raw: message } }),
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const client = createClient(signer)
|
|
35
|
+
|
|
36
|
+
const response = await client.fetch(
|
|
37
|
+
'https://api.example.com/orders',
|
|
38
|
+
{
|
|
39
|
+
method: 'POST',
|
|
40
|
+
headers: { 'Content-Type': 'application/json' },
|
|
41
|
+
body: JSON.stringify({ amount: '100' }),
|
|
42
|
+
}
|
|
43
|
+
)
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
### Verify a Request
|
|
47
|
+
|
|
48
|
+
```typescript
|
|
49
|
+
import { verifyRequest } from '@slicekit/eip8128'
|
|
50
|
+
import { createPublicClient, http } from 'viem'
|
|
51
|
+
import { mainnet } from 'viem/chains'
|
|
52
|
+
|
|
53
|
+
const client = createPublicClient({ chain: mainnet, transport: http() })
|
|
54
|
+
|
|
55
|
+
const result = await verifyRequest(request, {
|
|
56
|
+
nonceStore,
|
|
57
|
+
verifyMessage: client.verifyMessage,
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
if (result.ok) {
|
|
61
|
+
console.log(`Authenticated: ${result.address}`)
|
|
62
|
+
}
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## API
|
|
66
|
+
|
|
67
|
+
### `createClient(signer, options?)`
|
|
68
|
+
|
|
69
|
+
Creates a client with pre-configured signer.
|
|
70
|
+
|
|
71
|
+
```typescript
|
|
72
|
+
const client = createClient(signer)
|
|
73
|
+
|
|
74
|
+
client.fetch(input, init?) // Sign and send
|
|
75
|
+
client.signRequest(input, init?) // Sign only
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### `verifyRequest(input, init?, policy?)`
|
|
79
|
+
|
|
80
|
+
Verifies a signed request.
|
|
81
|
+
|
|
82
|
+
**Returns:** `Promise<VerifyResult>`
|
|
83
|
+
|
|
84
|
+
```typescript
|
|
85
|
+
type VerifyResult =
|
|
86
|
+
| { ok: true; address: Address; chainId: number; label: string }
|
|
87
|
+
| { ok: false; reason: VerifyFailReason }
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### `signRequest(input, init?, signer, options?)`
|
|
91
|
+
|
|
92
|
+
Signs a fetch Request and returns a new Request with signature headers.
|
|
93
|
+
|
|
94
|
+
**Returns:** `Promise<Request>`
|
|
95
|
+
|
|
96
|
+
### `signedFetch(input, init?, signer, options?)`
|
|
97
|
+
|
|
98
|
+
Signs and sends a request in one call.
|
|
99
|
+
|
|
100
|
+
**Returns:** `Promise<Response>`
|
|
101
|
+
|
|
102
|
+
## Sign Options
|
|
103
|
+
|
|
104
|
+
| Option | Type | Default | Description |
|
|
105
|
+
|--------|------|---------|-------------|
|
|
106
|
+
| `binding` | `"request-bound"` \| `"minimal"` | `"request-bound"` | Components to sign |
|
|
107
|
+
| `replay` | `"non-replayable"` \| `"replayable"` | `"non-replayable"` | Include nonce |
|
|
108
|
+
| `ttlSeconds` | `number` | `60` | Signature validity window |
|
|
109
|
+
| `label` | `string` | `"eth"` | Signature label |
|
|
110
|
+
| `components` | `string[]` | — | Override signed components |
|
|
111
|
+
|
|
112
|
+
## Verify Policy
|
|
113
|
+
|
|
114
|
+
| Option | Type | Default | Description |
|
|
115
|
+
|--------|------|---------|-------------|
|
|
116
|
+
| `nonceStore` | `NonceStore` | — | Required for replay protection |
|
|
117
|
+
| `verifyMessage` | `function` | — | Signature verification function |
|
|
118
|
+
| `maxValiditySec` | `number` | `300` | Max allowed validity window |
|
|
119
|
+
| `clockSkewSec` | `number` | `0` | Allowed clock drift |
|
|
120
|
+
| `label` | `string` | — | Preferred signature label |
|
|
121
|
+
| `strictLabel` | `boolean` | `false` | Require exact label match |
|
|
122
|
+
| `requiredComponents` | `string[]` | — | Components that must be signed |
|
|
123
|
+
| `enforceContentDigest` | `boolean` | `false` | Require body digest |
|
|
124
|
+
|
|
125
|
+
## Nonce Store
|
|
126
|
+
|
|
127
|
+
For replay protection, implement `NonceStore`:
|
|
128
|
+
|
|
129
|
+
```typescript
|
|
130
|
+
interface NonceStore {
|
|
131
|
+
consume(key: string, ttlSeconds: number): Promise<boolean>
|
|
132
|
+
}
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
**In-memory (development):**
|
|
136
|
+
|
|
137
|
+
```typescript
|
|
138
|
+
const nonceStore = {
|
|
139
|
+
seen: new Map(),
|
|
140
|
+
async consume(key, ttl) {
|
|
141
|
+
if (this.seen.has(key)) return false
|
|
142
|
+
this.seen.set(key, Date.now() + ttl * 1000)
|
|
143
|
+
return true
|
|
144
|
+
},
|
|
145
|
+
}
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
**Redis (production):**
|
|
149
|
+
|
|
150
|
+
```typescript
|
|
151
|
+
const nonceStore = {
|
|
152
|
+
async consume(key, ttl) {
|
|
153
|
+
return (await redis.set(`nonce:${key}`, '1', 'EX', ttl, 'NX')) === 'OK'
|
|
154
|
+
},
|
|
155
|
+
}
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
## Documentation
|
|
159
|
+
|
|
160
|
+
Full documentation: [erc8128.slice.so](https://erc8128.slice.so)
|
|
161
|
+
|
|
162
|
+
- [Quick Start](https://erc8128.slice.so/getting-started/quick-start)
|
|
163
|
+
- [Signing Requests](https://erc8128.slice.so/guides/signing-requests)
|
|
164
|
+
- [Verifying Requests](https://erc8128.slice.so/guides/verifying-requests)
|
|
165
|
+
- [API Reference](https://erc8128.slice.so/api)
|
|
166
|
+
|
|
167
|
+
## License
|
|
168
|
+
|
|
169
|
+
MIT
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// Generated by dts-bundle-generator v9.5.1
|
|
2
|
+
|
|
3
|
+
export type Hex = `0x${string}`;
|
|
4
|
+
export type Address = `0x${string}`;
|
|
5
|
+
export type VerifyMessageArgs = {
|
|
6
|
+
address: Address;
|
|
7
|
+
message: {
|
|
8
|
+
raw: Hex;
|
|
9
|
+
};
|
|
10
|
+
signature: Hex;
|
|
11
|
+
};
|
|
12
|
+
export type VerifyMessageFn = (args: VerifyMessageArgs) => boolean | Promise<boolean>;
|
|
13
|
+
export type BindingMode = "request-bound" | "class-bound";
|
|
14
|
+
export type ReplayMode = "non-replayable" | "replayable";
|
|
15
|
+
export type ContentDigestMode = "auto" | "recompute" | "require" | "off";
|
|
16
|
+
export type HeaderMode = "replace" | "append";
|
|
17
|
+
export type SignOptions = {
|
|
18
|
+
label?: string;
|
|
19
|
+
binding?: BindingMode;
|
|
20
|
+
replay?: ReplayMode;
|
|
21
|
+
created?: number;
|
|
22
|
+
expires?: number;
|
|
23
|
+
ttlSeconds?: number;
|
|
24
|
+
nonce?: string | (() => Promise<string>);
|
|
25
|
+
contentDigest?: ContentDigestMode;
|
|
26
|
+
headerMode?: HeaderMode;
|
|
27
|
+
components?: string[];
|
|
28
|
+
};
|
|
29
|
+
export interface EthHttpSigner {
|
|
30
|
+
/** Address to put in keyid and to authenticate as (EOA or SCA). */
|
|
31
|
+
address: Address;
|
|
32
|
+
chainId: number;
|
|
33
|
+
/**
|
|
34
|
+
* Sign RFC9421 signature base bytes as an Ethereum message (EIP-191).
|
|
35
|
+
* Return signature bytes as hex (may be 65 bytes for EOA, arbitrary length for SCA-style signatures).
|
|
36
|
+
*/
|
|
37
|
+
signMessage: (message: Uint8Array) => Promise<Hex>;
|
|
38
|
+
}
|
|
39
|
+
export interface NonceStore {
|
|
40
|
+
/**
|
|
41
|
+
* Atomic consume: returns true if newly stored (i.e. not seen), false if already exists.
|
|
42
|
+
* ttlSeconds: how long the nonce should remain reserved.
|
|
43
|
+
*/
|
|
44
|
+
consume(key: string, ttlSeconds: number): Promise<boolean>;
|
|
45
|
+
}
|
|
46
|
+
export type VerifyPolicy = {
|
|
47
|
+
/** Preferred label to verify (default "eth"). If not found, verifier can fall back to first label unless strictLabel=true. */
|
|
48
|
+
label?: string;
|
|
49
|
+
strictLabel?: boolean;
|
|
50
|
+
/** Optional override. If omitted => default Request-Bound set derived from request shape. */
|
|
51
|
+
requiredComponents?: string[];
|
|
52
|
+
/** Params policy */
|
|
53
|
+
nonce?: "required" | "optional" | "forbidden";
|
|
54
|
+
/** Time policy */
|
|
55
|
+
now?: () => number;
|
|
56
|
+
clockSkewSec?: number;
|
|
57
|
+
maxValiditySec?: number;
|
|
58
|
+
maxNonceWindowSec?: number;
|
|
59
|
+
/** Replay protection */
|
|
60
|
+
nonceStore?: NonceStore;
|
|
61
|
+
nonceKey?: (keyid: string, nonce: string) => string;
|
|
62
|
+
/** If true: if content-digest is covered, recompute and compare (default true) */
|
|
63
|
+
enforceContentDigest?: boolean;
|
|
64
|
+
/** Message signature verifier (viem-compatible). */
|
|
65
|
+
verifyMessage?: VerifyMessageFn;
|
|
66
|
+
};
|
|
67
|
+
export type SignatureParams = {
|
|
68
|
+
created: number;
|
|
69
|
+
expires: number;
|
|
70
|
+
keyid: string;
|
|
71
|
+
nonce?: string;
|
|
72
|
+
tag?: string;
|
|
73
|
+
};
|
|
74
|
+
export type VerifyResult = {
|
|
75
|
+
ok: true;
|
|
76
|
+
kind: "eoa" | "sca";
|
|
77
|
+
address: Address;
|
|
78
|
+
chainId: number;
|
|
79
|
+
label: string;
|
|
80
|
+
components: string[];
|
|
81
|
+
params: SignatureParams;
|
|
82
|
+
} | {
|
|
83
|
+
ok: false;
|
|
84
|
+
reason: VerifyFailReason;
|
|
85
|
+
detail?: string;
|
|
86
|
+
};
|
|
87
|
+
export type VerifyFailReason = "missing_headers" | "label_not_found" | "bad_signature_input" | "bad_signature" | "bad_keyid" | "bad_time" | "not_yet_valid" | "expired" | "validity_too_long" | "nonce_required" | "replayable_not_allowed" | "class_bound_not_allowed" | "not_request_bound" | "nonce_window_too_long" | "replay" | "digest_mismatch" | "digest_required" | "alg_not_allowed" | "bad_signature_bytes" | "bad_signature_check";
|
|
88
|
+
export declare class Eip8128Error extends Error {
|
|
89
|
+
code: "CRYPTO_UNAVAILABLE" | "INVALID_OPTIONS" | "UNSUPPORTED_REQUEST" | "BODY_READ_FAILED" | "DIGEST_REQUIRED" | "BAD_DERIVED_VALUE" | "BAD_HEADER_VALUE" | "PARSE_ERROR";
|
|
90
|
+
constructor(code: "CRYPTO_UNAVAILABLE" | "INVALID_OPTIONS" | "UNSUPPORTED_REQUEST" | "BODY_READ_FAILED" | "DIGEST_REQUIRED" | "BAD_DERIVED_VALUE" | "BAD_HEADER_VALUE" | "PARSE_ERROR", message: string);
|
|
91
|
+
}
|
|
92
|
+
export type ClientOptions = SignOptions & {
|
|
93
|
+
fetch?: typeof fetch;
|
|
94
|
+
};
|
|
95
|
+
export type Client = {
|
|
96
|
+
signRequest: {
|
|
97
|
+
(input: RequestInfo, opts?: SignOptions): Promise<Request>;
|
|
98
|
+
(input: RequestInfo, init: RequestInit | undefined, opts?: SignOptions): Promise<Request>;
|
|
99
|
+
};
|
|
100
|
+
signedFetch: {
|
|
101
|
+
(input: RequestInfo, opts?: ClientOptions): Promise<Response>;
|
|
102
|
+
(input: RequestInfo, init: RequestInit | undefined, opts?: ClientOptions): Promise<Response>;
|
|
103
|
+
};
|
|
104
|
+
fetch: {
|
|
105
|
+
(input: RequestInfo, opts?: ClientOptions): Promise<Response>;
|
|
106
|
+
(input: RequestInfo, init: RequestInit | undefined, opts?: ClientOptions): Promise<Response>;
|
|
107
|
+
};
|
|
108
|
+
};
|
|
109
|
+
export declare function createClient(signer: EthHttpSigner, defaults?: ClientOptions): Client;
|
|
110
|
+
export declare function formatKeyId(chainId: number, address: Address): string;
|
|
111
|
+
export declare function parseKeyId(keyid: string): {
|
|
112
|
+
chainId: number;
|
|
113
|
+
address: Address;
|
|
114
|
+
} | null;
|
|
115
|
+
/**
|
|
116
|
+
* Minimal EIP-8128 signing
|
|
117
|
+
* - Fetch-first: works in browsers, workers, Node 18+.
|
|
118
|
+
* - Minimal RFC 9421 engine: message to sign is an ERFC9421 compliant signature base.
|
|
119
|
+
* - Minimal Structured Fields serialization: enough to serialize Signature-Input + Signature for one label.
|
|
120
|
+
*
|
|
121
|
+
* IMPORTANT:
|
|
122
|
+
* - This is "signing side" only. Verification is not included here.
|
|
123
|
+
* - For Request-Bound with body: we compute Content-Digest using SHA-256 and include it when required.
|
|
124
|
+
* - SHA-256 requires WebCrypto (crypto.subtle) or Node 'node:crypto'. The library will throw CRYPTO_UNAVAILABLE if neither is available.
|
|
125
|
+
*/
|
|
126
|
+
/**
|
|
127
|
+
* Sign a fetch Request (or RequestInfo+RequestInit) and return a NEW Request with:
|
|
128
|
+
* - Signature-Input
|
|
129
|
+
* - Signature
|
|
130
|
+
* - Content-Digest (if required)
|
|
131
|
+
*/
|
|
132
|
+
export declare function signRequest(input: RequestInfo, signer: EthHttpSigner, opts?: SignOptions): Promise<Request>;
|
|
133
|
+
export declare function signRequest(input: RequestInfo, init: RequestInit | undefined, signer: EthHttpSigner, opts?: SignOptions): Promise<Request>;
|
|
134
|
+
export declare function signedFetch(input: RequestInfo, signer: EthHttpSigner, opts?: SignOptions & {
|
|
135
|
+
fetch?: typeof fetch;
|
|
136
|
+
}): Promise<Response>;
|
|
137
|
+
export declare function signedFetch(input: RequestInfo, init: RequestInit | undefined, signer: EthHttpSigner, opts?: SignOptions & {
|
|
138
|
+
fetch?: typeof fetch;
|
|
139
|
+
}): Promise<Response>;
|
|
140
|
+
export declare function verifyRequest(input: RequestInfo, policy?: VerifyPolicy): Promise<VerifyResult>;
|
|
141
|
+
export declare function verifyRequest(input: RequestInfo, init: RequestInit | undefined, policy?: VerifyPolicy): Promise<VerifyResult>;
|
|
142
|
+
|
|
143
|
+
export {};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
class U extends Error{code;constructor(R,$){super($);this.code=R;this.name="Eip8128Error"}}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function nR(R){return R instanceof Uint8Array||ArrayBuffer.isView(R)&&R.constructor.name==="Uint8Array"}function p(R,...$){if(!nR(R))throw Error("Uint8Array expected");if($.length>0&&!$.includes(R.length))throw Error("Uint8Array expected of length "+$+", got length="+R.length)}function RR(R,$=!0){if(R.destroyed)throw Error("Hash instance has been destroyed");if($&&R.finished)throw Error("Hash#digest() has already been called")}function qR(R,$){p(R);let Y=$.outputLen;if(R.length<Y)throw Error("digestInto() expects output buffer of length at least "+Y)}function _(...R){for(let $=0;$<R.length;$++)R[$].fill(0)}function n(R){return new DataView(R.buffer,R.byteOffset,R.byteLength)}function x(R,$){return R<<32-$|R>>>$}function hR(R){if(typeof R!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(R))}function $R(R){if(typeof R==="string")R=hR(R);return p(R),R}class YR{}function OR(R){let $=(Z)=>R().update($R(Z)).digest(),Y=R();return $.outputLen=Y.outputLen,$.blockLen=Y.blockLen,$.create=()=>R(),$}function lR(R,$,Y,Z){if(typeof R.setBigUint64==="function")return R.setBigUint64($,Y,Z);let X=BigInt(32),J=BigInt(4294967295),K=Number(Y>>X&J),N=Number(Y&J),Q=Z?4:0,j=Z?0:4;R.setUint32($+Q,K,Z),R.setUint32($+j,N,Z)}function PR(R,$,Y){return R&$^~R&Y}function xR(R,$,Y){return R&$^R&Y^$&Y}class ZR extends YR{constructor(R,$,Y,Z){super();this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=R,this.outputLen=$,this.padOffset=Y,this.isLE=Z,this.buffer=new Uint8Array(R),this.view=n(this.buffer)}update(R){RR(this),R=$R(R),p(R);let{view:$,buffer:Y,blockLen:Z}=this,X=R.length;for(let J=0;J<X;){let K=Math.min(Z-this.pos,X-J);if(K===Z){let N=n(R);for(;Z<=X-J;J+=Z)this.process(N,J);continue}if(Y.set(R.subarray(J,J+K),this.pos),this.pos+=K,J+=K,this.pos===Z)this.process($,0),this.pos=0}return this.length+=R.length,this.roundClean(),this}digestInto(R){RR(this),qR(R,this),this.finished=!0;let{buffer:$,view:Y,blockLen:Z,isLE:X}=this,{pos:J}=this;if($[J++]=128,_(this.buffer.subarray(J)),this.padOffset>Z-J)this.process(Y,0),J=0;for(let z=J;z<Z;z++)$[z]=0;lR(Y,Z-8,BigInt(this.length*8),X),this.process(Y,0);let K=n(R),N=this.outputLen;if(N%4)throw Error("_sha2: outputLen should be aligned to 32bit");let Q=N/4,j=this.get();if(Q>j.length)throw Error("_sha2: outputLen bigger than state");for(let z=0;z<Q;z++)K.setUint32(4*z,j[z],X)}digest(){let{buffer:R,outputLen:$}=this;this.digestInto(R);let Y=R.slice(0,$);return this.destroy(),Y}_cloneInto(R){R||(R=new this.constructor),R.set(...this.get());let{blockLen:$,buffer:Y,length:Z,finished:X,destroyed:J,pos:K}=this;if(R.destroyed=J,R.finished=X,R.length=Z,R.pos=K,Z%$)R.buffer.set(Y);return R}clone(){return this._cloneInto()}}var C=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var oR=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),W=new Uint32Array(64);class kR extends ZR{constructor(R=32){super(64,R,8,!1);this.A=C[0]|0,this.B=C[1]|0,this.C=C[2]|0,this.D=C[3]|0,this.E=C[4]|0,this.F=C[5]|0,this.G=C[6]|0,this.H=C[7]|0}get(){let{A:R,B:$,C:Y,D:Z,E:X,F:J,G:K,H:N}=this;return[R,$,Y,Z,X,J,K,N]}set(R,$,Y,Z,X,J,K,N){this.A=R|0,this.B=$|0,this.C=Y|0,this.D=Z|0,this.E=X|0,this.F=J|0,this.G=K|0,this.H=N|0}process(R,$){for(let z=0;z<16;z++,$+=4)W[z]=R.getUint32($,!1);for(let z=16;z<64;z++){let M=W[z-15],F=W[z-2],G=x(M,7)^x(M,18)^M>>>3,O=x(F,17)^x(F,19)^F>>>10;W[z]=O+W[z-7]+G+W[z-16]|0}let{A:Y,B:Z,C:X,D:J,E:K,F:N,G:Q,H:j}=this;for(let z=0;z<64;z++){let M=x(K,6)^x(K,11)^x(K,25),F=j+M+PR(K,N,Q)+oR[z]+W[z]|0,O=(x(Y,2)^x(Y,13)^x(Y,22))+xR(Y,Z,X)|0;j=Q,Q=N,N=K,K=J+F|0,J=X,X=Z,Z=Y,Y=F+O|0}Y=Y+this.A|0,Z=Z+this.B|0,X=X+this.C|0,J=J+this.D|0,K=K+this.E|0,N=N+this.F|0,Q=Q+this.G|0,j=j+this.H|0,this.set(Y,Z,X,J,K,N,Q,j)}roundClean(){_(W)}destroy(){this.set(0,0,0,0,0,0,0,0),_(this.buffer)}}var wR=OR(()=>new kR);var k="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",tR=(()=>{let R=new Uint8Array(256);R.fill(255);for(let $=0;$<k.length;$++)R[k.charCodeAt($)]=$;return R[45]=62,R[95]=63,R})();function h(R,$){if(R instanceof Request)return $?new Request(R,$):R;return new Request(R,$)}function XR(R){return typeof R==="object"&&R!==null&&typeof R.signMessage==="function"}function g(R){try{return new URL(R)}catch{throw new U("UNSUPPORTED_REQUEST",`Request.url must be absolute (got: ${R}).`)}}function l(){return Math.floor(Date.now()/1000)}function TR(R){return new TextEncoder().encode(R)}function CR(R){let $=globalThis.crypto;if(!$?.getRandomValues)throw new U("CRYPTO_UNAVAILABLE","crypto.getRandomValues required.");let Y=new Uint8Array(R);return $.getRandomValues(Y),Y}async function JR(R){try{let Y=await R.clone().arrayBuffer();return new Uint8Array(Y)}catch{throw new U("BODY_READ_FAILED","Failed to read request body (stream locked/disturbed).")}}async function KR(R){return wR(R)}function y(R){let $="",Y=0;for(;Y+2<R.length;Y+=3){let X=R[Y]<<16|R[Y+1]<<8|R[Y+2];$+=k[X>>18&63]+k[X>>12&63]+k[X>>6&63]+k[X&63]}if(Y===R.length)return $;let Z=R[Y]<<16;if(Y+1<R.length){let X=Z|R[Y+1]<<8;$+=k[X>>18&63]+k[X>>12&63]+k[X>>6&63]+"="}else $+=k[Z>>18&63]+k[Z>>12&63]+"==";return $}function WR(R){try{let $=R.trim().replace(/=+$/g,"");if($.length===0)return new Uint8Array(0);if($.length%4===1)return null;let Y=new Uint8Array(Math.floor($.length*3/4)),Z=0,X=0,J=0;for(let K=0;K<$.length;K++){let N=tR[$.charCodeAt(K)];if(N===255)return null;if(Z=Z<<6|N,X+=6,X>=8)X-=8,Y[J++]=Z>>X&255}return J===Y.length?Y:Y.slice(0,J)}catch{return null}}function fR(R){return y(R).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function IR(R){let $=R.slice(2);if($.length%2!==0)throw new U("UNSUPPORTED_REQUEST","Invalid hex length.");let Y=new Uint8Array($.length/2);for(let Z=0;Z<Y.length;Z++)Y[Z]=parseInt($.slice(Z*2,Z*2+2),16);return Y}function NR(R){let $="0x";for(let Y of R)$+=Y.toString(16).padStart(2,"0");return $}async function QR(R,$){let Y=new Headers(R.headers),Z=Y.get("content-digest");if($==="off")throw new U("DIGEST_REQUIRED","content-digest is required by covered components, but contentDigest='off'.");if($==="require"&&!Z)throw new U("DIGEST_REQUIRED","content-digest is required but missing.");if(Z&&$==="auto")return R;let X=await JR(R),J=await KR(X),K=y(J);return Y.set("content-digest",`sha-256=:${K}:`),new Request(R,{headers:Y})}async function LR(R){let $=R.headers.get("content-digest");if(!$)return!1;let Y=iR($);if(!Y)return!1;if(Y.alg!=="sha-256")return!1;let Z=await JR(R),X=await KR(Z),J=y(X);return rR(Y.b64,J)}function iR(R){let $=R.trim(),Y=/^([A-Za-z0-9_-]+)=:([A-Za-z0-9+/]+={0,2}):$/.exec($);if(!Y)return null;return{alg:Y[1].toLowerCase(),b64:Y[2]}}function rR(R,$){if(R.length!==$.length)return!1;let Y=0;for(let Z=0;Z<R.length;Z++)Y|=R.charCodeAt(Z)^$.charCodeAt(Z);return Y===0}function BR(R){let $=[];for(let Y of vR(R)){let Z=Y.trim();if(!Z)continue;let X=Z.indexOf("=");if(X<=0)throw new U("PARSE_ERROR","Invalid Signature-Input member (missing '=').");let J=Z.slice(0,X).trim();S(J);let K=Z.slice(X+1).trim(),N=K,Q=aR(K);$.push({label:J,components:Q.items,params:Q.params,signatureParamsValue:N})}return $}function VR(R){let $=new Map;for(let Y of vR(R)){let Z=Y.trim();if(!Z)continue;let X=Z.indexOf("=");if(X<=0)throw new U("PARSE_ERROR","Invalid Signature member (missing '=').");let J=Z.slice(0,X).trim();S(J);let K=Z.slice(X+1).trim(),N=sR(K);$.set(J,N)}return $}function sR(R){let $=R.trim();if(!$.startsWith(":")||!$.endsWith(":")||$.length<3)throw new U("PARSE_ERROR","Invalid sf-binary.");let Y=$.slice(1,-1);if(!/^[A-Za-z0-9+/]+={0,2}$/.test(Y))throw new U("PARSE_ERROR","Invalid base64 in sf-binary.");return Y}function aR(R){let $=0,Y=R.trim();if(Y[$]!=="(")throw new U("PARSE_ERROR","Inner list must start with '('.");$++;let Z=[];while($<Y.length){if(M(),Y[$]===")"){$++;break}let D=F();Z.push(D),M()}if(Z.length===0)throw new U("PARSE_ERROR","Inner list has no items.");let X={};while($<Y.length){if(M(),Y[$]!==";")break;$++,M();let D=G();if(M(),Y[$]!=="=")throw new U("PARSE_ERROR",`Param ${D} missing '='.`);$++,M();let q=O();X[D]=q}let{created:J,expires:K,keyid:N,nonce:Q,tag:j}=X;if(!Number.isInteger(J)||!Number.isInteger(K)||typeof N!=="string")throw new U("PARSE_ERROR","Missing or invalid created/expires/keyid in Signature-Input.");let z={created:J,expires:K,keyid:N,...typeof Q==="string"?{nonce:Q}:{},...typeof j==="string"?{tag:j}:{}};return{items:Z,params:z};function M(){while($<Y.length&&(Y[$]===" "||Y[$]==="\t"))$++}function F(){if(Y[$]!=='"')throw new U("PARSE_ERROR","Expected sf-string.");$++;let D="";while($<Y.length){let q=Y[$];if(q==='"'){$++;break}if(q==="\\"){if($++,$>=Y.length)throw new U("PARSE_ERROR","Bad escape in sf-string.");D+=Y[$],$++;continue}let f=q.charCodeAt(0);if(f<32||f===127)throw new U("PARSE_ERROR","Control char in sf-string.");D+=q,$++}return D}function G(){let D=$;while($<Y.length&&/[A-Za-z0-9_\-*.]/.test(Y[$]))$++;if($===D)throw new U("PARSE_ERROR","Expected token.");return Y.slice(D,$)}function O(){if(Y[$]==='"')return F();let D=$;if(Y[$]==="-")$++;while($<Y.length&&/[0-9]/.test(Y[$]))$++;if($===D)throw new U("PARSE_ERROR","Expected param value.");let q=Number(Y.slice(D,$));if(!Number.isFinite(q))throw new U("PARSE_ERROR","Bad integer param value.");return q}}function vR(R){let $=[],Y="",Z=!1,X=!1;for(let J=0;J<R.length;J++){let K=R[J];if(X){Y+=K,X=!1;continue}if(K==="\\"&&Z){Y+=K,X=!0;continue}if(K==='"'){Y+=K,Z=!Z;continue}if(K===","&&!Z){$.push(Y),Y="";continue}Y+=K}if(Y)$.push(Y);return $}function S(R){if(!/^[a-z][a-z0-9_.-]*$/.test(R))throw new U("PARSE_ERROR",`Invalid signature label: ${R}`)}function yR(R,$){let X=`(${R.map((J)=>L(J)).join(" ")})`;if(X+=`;created=${$.created}`,X+=`;expires=${$.expires}`,$.nonce!=null)X+=`;nonce=${L($.nonce)}`;if($.tag!=null)X+=`;tag=${L($.tag)}`;return X+=`;keyid=${L($.keyid)}`,X}function ER(R){if(!Number.isInteger(R.created)||!Number.isInteger(R.expires))throw new U("INVALID_OPTIONS","created/expires must be integers.");if(R.expires<=R.created)throw new U("INVALID_OPTIONS","expires must be > created.");if(!R.keyid)throw new U("INVALID_OPTIONS","keyid is required.")}function _R(R,$){return S(R),`${R}=${$}`}function SR(R,$){if(S(R),!/^[A-Za-z0-9+/]+={0,2}$/.test($))throw new U("BAD_HEADER_VALUE","Signature must be base64.");return`${R}=:${$}:`}function zR(R,$){if(!R)return $;return`${R}, ${$}`}function L(R){for(let Y=0;Y<R.length;Y++){let Z=R.charCodeAt(Y);if(Z>=0&&Z<=31||Z===127)throw new U("BAD_HEADER_VALUE","sf-string cannot contain control characters.")}return`"${R.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function gR(R){return R.map(($)=>$.trim()).filter(Boolean)}function eR(R){let{binding:$,hasQuery:Y,hasBody:Z}=R;if($==="class-bound")return["@authority"];let X=["@authority","@method","@path"];if(Y)X.push("@query");if(Z)X.push("content-digest");return X}function HR(R){let{binding:$,hasQuery:Y,hasBody:Z,providedComponents:X}=R;if($==="request-bound"){let K=eR({binding:$,hasQuery:Y,hasBody:Z});if(!X)return K;let N=gR(X).filter((Q)=>!K.includes(Q));return K.concat(N)}if(!X)throw new U("INVALID_OPTIONS","components are required for class-bound signatures.");let J=gR(X);if(!J.includes("@authority"))J.unshift("@authority");return J}function o(R){let{request:$,components:Y,signatureParamsValue:Z}=R,X=g($.url),J=[];for(let Q of Y){let j=R8({request:$,url:X,component:Q});if(/[^\x20-\x7E]/.test(j)||j.includes("\r")||j.includes(`
|
|
2
|
+
`))throw new U("BAD_DERIVED_VALUE",`Component ${Q} produced invalid characters.`);J.push(`${L(Q)}: ${j}`)}let K=`${L("@signature-params")}: ${Z}`,N=J.length?`${J.join(`
|
|
3
|
+
`)}
|
|
4
|
+
${K}`:K;return TR(N)}function R8(R){let{request:$,url:Y,component:Z}=R;switch(Z){case"@method":{let X=($.method||"GET").toUpperCase();return H(X,"@method"),X}case"@authority":{let X=Y.protocol.replace(":","").toLowerCase(),J=Y.hostname.toLowerCase(),K=Y.port,N=J;if(K){let Q=Number(K);if(!(X==="http"&&Q===80||X==="https"&&Q===443))N=`${J}:${K}`}return H(N,"@authority"),N}case"@path":{let X=Y.pathname||"/";return H(X,"@path"),X}case"@query":{let X=Y.search||"";return H(X,"@query"),X}default:{let X=$.headers.get(Z);if(X==null)throw new U("BAD_HEADER_VALUE",`Required header "${Z}" is missing.`);let J=$8(X);return H(J,Z),J}}}function $8(R){return R.trim().replace(/[ \t]+/g," ")}function H(R,$){if(R.includes("\r")||R.includes(`
|
|
5
|
+
`))throw new U("BAD_DERIVED_VALUE",`${$} contains CR/LF.`)}function UR(R,$){if(!Number.isInteger(R))throw new U("INVALID_OPTIONS","chainId must be positive integer.");return`eip8128:${R}:${$.toLowerCase()}`}function m(R){let $=/^eip8128:(\d+):(0x[a-fA-F0-9]{40})$/.exec(R);if(!$)return null;let Y=Number($[1]);if(!Number.isInteger(Y))return null;return{chainId:Y,address:$[2].toLowerCase()}}async function mR(R){if(typeof R.nonce==="string")return R.nonce;if(typeof R.nonce==="function")return R.nonce();let $=CR(16);return fR($)}async function t(R,$,Y,Z){let X,J,K;if(XR($))J=$,K=Y;else X=$,J=Y,K=Z;let N=K??{},Q=h(R,X),j=N.label??"eth",z=N.binding??"request-bound",M=N.replay??"non-replayable",F=N.headerMode??"replace",G=N.contentDigest??"auto",O=l(),D=N.created??O,q=N.ttlSeconds??60,f=N.expires??D+q,b=M==="non-replayable"?await mR(N):void 0,A=UR(J.chainId,J.address),u=g(Q.url).search.length>0,B=Q.body!=null,I=HR({binding:z,hasQuery:u,hasBody:B,providedComponents:N.components}),P=Q;if(I.includes("content-digest"))P=await QR(P,G);else if(z==="request-bound"&&B)I=[...I,"content-digest"],P=await QR(P,G);let E={created:D,expires:f,keyid:A,...b?{nonce:b}:{}};ER(E);let r=yR(I,E),c=_R(j,r),s=o({request:P,components:I,signatureParamsValue:r}),V=await J.signMessage(s),a=IR(V);if(a.length===0)throw new U("UNSUPPORTED_REQUEST","Signer returned empty signature.");let e=y(a),v=SR(j,e),T=new Headers(P.headers);if(F==="replace")T.set("Signature-Input",c),T.set("Signature",v);else T.set("Signature-Input",zR(T.get("Signature-Input"),c)),T.set("Signature",zR(T.get("Signature"),v));return new Request(P,{headers:T})}async function i(R,$,Y,Z){let X,J,K;if(XR($))J=$,K=Y;else X=$,J=Y,K=Z;let N=await t(R,X,J,K),Q=K?.fetch??globalThis.fetch;if(typeof Q!=="function")throw new U("UNSUPPORTED_REQUEST","No fetch implementation available. Provide opts.fetch.");return Q(N)}var Y8=new Set(["method","headers","body","signal","credentials","mode","cache","redirect","referrer","integrity","keepalive","window"]);function Z8(R){if(!R||typeof R!=="object")return!1;for(let $ of Y8)if($ in R)return!0;return!1}function jR(R,$){if($!==void 0)return{init:R,opts:$};if(Z8(R))return{init:R};return{opts:R}}function X8(R,$){let Y=$??{};return{signRequest:async(K,N,Q)=>{let{init:j,opts:z}=jR(N,Q),M={...Y,...z};return t(K,j,R,M)},signedFetch:async(K,N,Q)=>{let{init:j,opts:z}=jR(N,Q),M={...Y,...z};return i(K,j,R,M)},fetch:async(K,N,Q)=>{let{init:j,opts:z}=jR(N,Q),M={...Y,...z};return i(K,j,R,M)}}}function bR(R){let{signatureInputHeader:$,signatureHeader:Y,policy:Z}=R,X=Z.label,J=Z.strictLabel??!1;try{let K=BR($),N=VR(Y),Q,j,z,M=!1;for(let F of K){if(X!=null&&F.label===X){let D=N.get(F.label);if(!D)return{ok:!1,result:{ok:!1,reason:"label_not_found"}};Q=F,j=D;break}if(!m(F.params.keyid))continue;if(M=!0,z)continue;let O=N.get(F.label);if(!O)continue;z={member:F,sigB64:O}}if(!Q){if(X!=null&&J)return{ok:!1,result:{ok:!1,reason:"label_not_found"}};if(z)Q=z.member,j=z.sigB64;else return{ok:!1,result:M?{ok:!1,reason:"label_not_found"}:{ok:!1,reason:"bad_keyid"}}}if(!j)return{ok:!1,result:{ok:!1,reason:"label_not_found"}};return{ok:!0,selected:{label:Q.label,components:Q.components,params:Q.params,signatureParamsValue:Q.signatureParamsValue,sigB64:j}}}catch(K){let N=K instanceof Error?K.message:"Failed to parse signature headers.";if(K instanceof U&&K.code==="PARSE_ERROR")return{ok:!1,result:{ok:!1,reason:"bad_signature_input",detail:N}};return{ok:!1,result:{ok:!1,reason:"bad_signature_input",detail:N}}}}function AR(R,$){let Y=["@authority","@method","@path"];if($.hasQuery)Y.push("@query");if($.hasBody)Y.push("content-digest");return MR(Y,R)}function MR(R,$){let Y=0;for(let Z=0;Z<$.length&&Y<R.length;Z++)if($[Z]===R[Y])Y++;return Y===R.length}var J8=300;async function K8(R,$,Y){let Z=Y!==void 0,X=Z?$:void 0,J=Z?Y:$??{},K=h(R,X),N=J.label,Q=J.strictLabel??!1,j=K.headers.get("Signature-Input"),z=K.headers.get("Signature");if(!j||!z)return{ok:!1,reason:"missing_headers"};let M=bR({signatureInputHeader:j,signatureHeader:z,policy:{label:N,strictLabel:Q}});if(!M.ok)return M.result;let{components:F,params:G,signatureParamsValue:O,sigB64:D,label:q}=M.selected,f=m(G.keyid);if(!f)return{ok:!1,reason:"bad_keyid"};let{chainId:b,address:A}=f,d=J.now?.()??l(),u=J.clockSkewSec??0;if(!Number.isInteger(G.created)||!Number.isInteger(G.expires)||G.expires<=G.created)return{ok:!1,reason:"bad_time"};if(d+u<G.created)return{ok:!1,reason:"not_yet_valid"};if(d-u>G.expires)return{ok:!1,reason:"expired"};let B=J.maxValiditySec,I=typeof B==="number"&&Number.isFinite(B)?B:J8;if(G.expires-G.created>I)return{ok:!1,reason:"validity_too_long"};let P=typeof G.nonce==="string"&&G.nonce.length>0,E=J.nonce??"required";if(E==="required"&&!P)return{ok:!1,reason:"nonce_required"};if(E==="forbidden"&&P)return{ok:!1,reason:"bad_signature_input",detail:"nonce is forbidden by policy"};if(P){let w=J.maxNonceWindowSec;if(w!=null&&G.expires-G.created>w)return{ok:!1,reason:"nonce_window_too_long"}}let c=g(K.url).search.length>0,s=K.body!=null,V=J.requiredComponents?.map((w)=>w.trim()).filter(Boolean);if(V&&V.length>0){if(!MR(V,F))return{ok:!1,reason:"not_request_bound",detail:`requiredComponents not satisfied (need ordered subsequence: ${V.join(",")})`}}else if(!AR(F,{hasQuery:c,hasBody:s}))return{ok:!1,reason:"not_request_bound"};if((J.enforceContentDigest??!0)&&F.includes("content-digest")){if(!K.headers.get("content-digest"))return{ok:!1,reason:"digest_required"};if(!await LR(K))return{ok:!1,reason:"digest_mismatch"}}if(P){let w=J.nonceStore;if(!w)return{ok:!1,reason:"nonce_required",detail:"nonceStore missing"};let FR=J.nonceKey??((cR,pR)=>`${cR}:${pR}`),DR=G.nonce;if(!DR)return{ok:!1,reason:"nonce_required",detail:"nonce missing"};let dR=FR(G.keyid,DR),uR=Math.max(0,G.expires-d);if(!await w.consume(dR,uR))return{ok:!1,reason:"replay"}}let e=o({request:K,components:F,signatureParamsValue:O}),v=WR(D);if(!v||v.length===0)return{ok:!1,reason:"bad_signature_bytes"};let T=NR(v),GR=J.verifyMessage;if(!GR)return{ok:!1,reason:"bad_signature_check",detail:"verifyMessage missing in policy"};try{if(await GR({address:A,message:{raw:NR(e)},signature:T}))return{ok:!0,kind:"eoa",address:A,chainId:b,label:q,components:F,params:G}}catch{return{ok:!1,reason:"bad_signature_check"}}return{ok:!1,reason:"bad_signature"}}export{K8 as verifyRequest,i as signedFetch,t as signRequest,m as parseKeyId,UR as formatKeyId,X8 as createClient,U as Eip8128Error};
|
|
6
|
+
|
|
7
|
+
//# debugId=E4409D75420E658764756E2164756E21
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/lib/types.ts", "../../../../node_modules/.bun/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/utils.js", "../../../../node_modules/.bun/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_md.js", "../../../../node_modules/.bun/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha2.js", "../../src/lib/utilities.ts", "../../src/lib/engine/contentDigest.ts", "../../src/lib/engine/createSignatureInput.ts", "../../src/lib/engine/serializations.ts", "../../src/lib/engine/createSignatureBase.ts", "../../src/lib/keyId.ts", "../../src/lib/nonce.ts", "../../src/sign.ts", "../../src/client.ts", "../../src/lib/engine/signatureHeaders.ts", "../../src/lib/policies/isRequestBound.ts", "../../src/verify.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"//////////////////////////////\n// Types\n//////////////////////////////\n\nexport type Hex = `0x${string}`\nexport type Address = `0x${string}`\n\nexport type VerifyMessageArgs = {\n address: Address\n message: { raw: Hex }\n signature: Hex\n}\n\nexport type VerifyMessageFn = (\n args: VerifyMessageArgs\n) => boolean | Promise<boolean>\n\nexport type BindingMode = \"request-bound\" | \"class-bound\"\nexport type ReplayMode = \"non-replayable\" | \"replayable\"\nexport type ContentDigestMode = \"auto\" | \"recompute\" | \"require\" | \"off\"\nexport type HeaderMode = \"replace\" | \"append\"\n\nexport type SignOptions = {\n label?: string // default: \"eth\"\n binding?: BindingMode // default: \"request-bound\"\n replay?: ReplayMode // default: \"non-replayable\"\n\n created?: number // unix seconds; default now\n expires?: number // unix seconds; default created + ttlSeconds\n ttlSeconds?: number // default 60\n\n nonce?: string | (() => Promise<string>)\n\n contentDigest?: ContentDigestMode\n headerMode?: HeaderMode\n components?: string[]\n}\n\nexport interface EthHttpSigner {\n /** Address to put in keyid and to authenticate as (EOA or SCA). */\n address: Address\n chainId: number\n /**\n * Sign RFC9421 signature base bytes as an Ethereum message (EIP-191).\n * Return signature bytes as hex (may be 65 bytes for EOA, arbitrary length for SCA-style signatures).\n */\n signMessage: (message: Uint8Array) => Promise<Hex>\n}\n\nexport interface NonceStore {\n /**\n * Atomic consume: returns true if newly stored (i.e. not seen), false if already exists.\n * ttlSeconds: how long the nonce should remain reserved.\n */\n consume(key: string, ttlSeconds: number): Promise<boolean>\n}\n\nexport type VerifyPolicy = {\n /** Preferred label to verify (default \"eth\"). If not found, verifier can fall back to first label unless strictLabel=true. */\n label?: string\n strictLabel?: boolean // default false\n\n /** Optional override. If omitted => default Request-Bound set derived from request shape. */\n requiredComponents?: string[]\n\n /** Params policy */\n nonce?: \"required\" | \"optional\" | \"forbidden\" // default \"required\"\n\n /** Time policy */\n now?: () => number // unix seconds; default unixNow()\n clockSkewSec?: number // default 0; allow +/- drift when checking created/expires\n maxValiditySec?: number // default 300; cap (expires - created)\n maxNonceWindowSec?: number // optional; cap (expires - created) for non-replayable (nonce) requests\n\n /** Replay protection */\n nonceStore?: NonceStore // required when verifying non-replayable (nonce) requests\n nonceKey?: (keyid: string, nonce: string) => string // default `${keyid}:${nonce}`\n\n /** If true: if content-digest is covered, recompute and compare (default true) */\n enforceContentDigest?: boolean\n\n /** Message signature verifier (viem-compatible). */\n verifyMessage?: VerifyMessageFn\n}\n\nexport type SignatureParams = {\n created: number\n expires: number\n keyid: string\n nonce?: string\n tag?: string\n}\n\nexport type VerifyResult =\n | {\n ok: true\n kind: \"eoa\" | \"sca\"\n address: Address\n chainId: number\n label: string\n components: string[]\n params: SignatureParams\n }\n | { ok: false; reason: VerifyFailReason; detail?: string }\n\nexport type VerifyFailReason =\n | \"missing_headers\"\n | \"label_not_found\"\n | \"bad_signature_input\"\n | \"bad_signature\"\n | \"bad_keyid\"\n | \"bad_time\"\n | \"not_yet_valid\"\n | \"expired\"\n | \"validity_too_long\"\n | \"nonce_required\"\n | \"replayable_not_allowed\"\n | \"class_bound_not_allowed\"\n | \"not_request_bound\"\n | \"nonce_window_too_long\"\n | \"replay\"\n | \"digest_mismatch\"\n | \"digest_required\"\n | \"alg_not_allowed\"\n | \"bad_signature_bytes\"\n | \"bad_signature_check\"\n\nexport class Eip8128Error extends Error {\n constructor(\n public code:\n | \"CRYPTO_UNAVAILABLE\"\n | \"INVALID_OPTIONS\"\n | \"UNSUPPORTED_REQUEST\"\n | \"BODY_READ_FAILED\"\n | \"DIGEST_REQUIRED\"\n | \"BAD_DERIVED_VALUE\"\n | \"BAD_HEADER_VALUE\"\n | \"PARSE_ERROR\",\n message: string\n ) {\n super(message)\n this.name = \"Eip8128Error\"\n }\n}\n",
|
|
6
|
+
"/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is positive integer. */\nexport function anumber(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error('positive integer expected, got ' + n);\n}\n/** Asserts something is Uint8Array. */\nexport function abytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n/** Asserts something is hash */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out, instance) {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/** The byte swap operation for uint32 */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n);\n/** @deprecated */\nexport const byteSwapIfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin)\n return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async () => { };\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/** For runtime check if class implements interface */\nexport class Hash {\n}\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function createOptHasher(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function createXOFer(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor = createHasher;\nexport const wrapConstructorWithOpts = createOptHasher;\nexport const wrapXOFConstructorWithOpts = createXOFer;\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map",
|
|
7
|
+
"/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from \"./utils.js\";\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n/** Choice: a ? b : c */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n//# sourceMappingURL=_md.js.map",
|
|
8
|
+
"/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, rotr } from \"./utils.js\";\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n constructor(outputLen = 32) {\n super(64, outputLen, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = SHA256_IV[0] | 0;\n this.B = SHA256_IV[1] | 0;\n this.C = SHA256_IV[2] | 0;\n this.D = SHA256_IV[3] | 0;\n this.E = SHA256_IV[4] | 0;\n this.F = SHA256_IV[5] | 0;\n this.G = SHA256_IV[6] | 0;\n this.H = SHA256_IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\nexport class SHA224 extends SHA256 {\n constructor() {\n super(28);\n this.A = SHA224_IV[0] | 0;\n this.B = SHA224_IV[1] | 0;\n this.C = SHA224_IV[2] | 0;\n this.D = SHA224_IV[3] | 0;\n this.E = SHA224_IV[4] | 0;\n this.F = SHA224_IV[5] | 0;\n this.G = SHA224_IV[6] | 0;\n this.H = SHA224_IV[7] | 0;\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD {\n constructor(outputLen = 64) {\n super(128, outputLen, 16, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = SHA512_IV[0] | 0;\n this.Al = SHA512_IV[1] | 0;\n this.Bh = SHA512_IV[2] | 0;\n this.Bl = SHA512_IV[3] | 0;\n this.Ch = SHA512_IV[4] | 0;\n this.Cl = SHA512_IV[5] | 0;\n this.Dh = SHA512_IV[6] | 0;\n this.Dl = SHA512_IV[7] | 0;\n this.Eh = SHA512_IV[8] | 0;\n this.El = SHA512_IV[9] | 0;\n this.Fh = SHA512_IV[10] | 0;\n this.Fl = SHA512_IV[11] | 0;\n this.Gh = SHA512_IV[12] | 0;\n this.Gl = SHA512_IV[13] | 0;\n this.Hh = SHA512_IV[14] | 0;\n this.Hl = SHA512_IV[15] | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nexport class SHA384 extends SHA512 {\n constructor() {\n super(48);\n this.Ah = SHA384_IV[0] | 0;\n this.Al = SHA384_IV[1] | 0;\n this.Bh = SHA384_IV[2] | 0;\n this.Bl = SHA384_IV[3] | 0;\n this.Ch = SHA384_IV[4] | 0;\n this.Cl = SHA384_IV[5] | 0;\n this.Dh = SHA384_IV[6] | 0;\n this.Dl = SHA384_IV[7] | 0;\n this.Eh = SHA384_IV[8] | 0;\n this.El = SHA384_IV[9] | 0;\n this.Fh = SHA384_IV[10] | 0;\n this.Fl = SHA384_IV[11] | 0;\n this.Gh = SHA384_IV[12] | 0;\n this.Gl = SHA384_IV[13] | 0;\n this.Hh = SHA384_IV[14] | 0;\n this.Hl = SHA384_IV[15] | 0;\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\nexport class SHA512_224 extends SHA512 {\n constructor() {\n super(28);\n this.Ah = T224_IV[0] | 0;\n this.Al = T224_IV[1] | 0;\n this.Bh = T224_IV[2] | 0;\n this.Bl = T224_IV[3] | 0;\n this.Ch = T224_IV[4] | 0;\n this.Cl = T224_IV[5] | 0;\n this.Dh = T224_IV[6] | 0;\n this.Dl = T224_IV[7] | 0;\n this.Eh = T224_IV[8] | 0;\n this.El = T224_IV[9] | 0;\n this.Fh = T224_IV[10] | 0;\n this.Fl = T224_IV[11] | 0;\n this.Gh = T224_IV[12] | 0;\n this.Gl = T224_IV[13] | 0;\n this.Hh = T224_IV[14] | 0;\n this.Hl = T224_IV[15] | 0;\n }\n}\nexport class SHA512_256 extends SHA512 {\n constructor() {\n super(32);\n this.Ah = T256_IV[0] | 0;\n this.Al = T256_IV[1] | 0;\n this.Bh = T256_IV[2] | 0;\n this.Bl = T256_IV[3] | 0;\n this.Ch = T256_IV[4] | 0;\n this.Cl = T256_IV[5] | 0;\n this.Dh = T256_IV[6] | 0;\n this.Dl = T256_IV[7] | 0;\n this.Eh = T256_IV[8] | 0;\n this.El = T256_IV[9] | 0;\n this.Fh = T256_IV[10] | 0;\n this.Fl = T256_IV[11] | 0;\n this.Gh = T256_IV[12] | 0;\n this.Gl = T256_IV[13] | 0;\n this.Hh = T256_IV[14] | 0;\n this.Hl = T256_IV[15] | 0;\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new SHA224());\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new SHA512_224());\n//# sourceMappingURL=sha2.js.map",
|
|
9
|
+
"import { sha256 as nobleSha256 } from \"@noble/hashes/sha2\"\nimport type { EthHttpSigner, Hex } from \"./types.ts\"\nimport { Eip8128Error } from \"./types.ts\"\n\nconst BASE64_ALPHABET =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\"\nconst BASE64_CODES = (() => {\n const codes = new Uint8Array(256)\n codes.fill(255)\n for (let i = 0; i < BASE64_ALPHABET.length; i++)\n codes[BASE64_ALPHABET.charCodeAt(i)] = i\n // URL-safe base64 variants.\n codes[\"-\".charCodeAt(0)] = 62\n codes[\"_\".charCodeAt(0)] = 63\n return codes\n})()\n\nexport function toRequest(input: RequestInfo, init?: RequestInit): Request {\n if (input instanceof Request) return init ? new Request(input, init) : input\n return new Request(input, init)\n}\n\nexport function isEthHttpSigner(value: unknown): value is EthHttpSigner {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as EthHttpSigner).signMessage === \"function\"\n )\n}\n\nexport function sanitizeUrl(url: string): URL {\n try {\n return new URL(url)\n } catch {\n throw new Eip8128Error(\n \"UNSUPPORTED_REQUEST\",\n `Request.url must be absolute (got: ${url}).`\n )\n }\n}\n\nexport function unixNow(): number {\n return Math.floor(Date.now() / 1000)\n}\n\nexport function utf8Encode(s: string): Uint8Array {\n return new TextEncoder().encode(s)\n}\n\nexport function randomBytes(n: number): Uint8Array {\n const cryptoObj = globalThis.crypto\n if (!cryptoObj?.getRandomValues)\n throw new Eip8128Error(\n \"CRYPTO_UNAVAILABLE\",\n \"crypto.getRandomValues required.\"\n )\n const out = new Uint8Array(n)\n cryptoObj.getRandomValues(out)\n return out\n}\n\nexport async function readBodyBytes(request: Request): Promise<Uint8Array> {\n try {\n const clone = request.clone()\n const ab = await clone.arrayBuffer()\n return new Uint8Array(ab)\n } catch {\n throw new Eip8128Error(\n \"BODY_READ_FAILED\",\n \"Failed to read request body (stream locked/disturbed).\"\n )\n }\n}\n\nexport async function sha256(bytes: Uint8Array): Promise<Uint8Array> {\n // Pure JS hash to avoid node:crypto/Buffer polyfills in browser bundles.\n return nobleSha256(bytes)\n}\n\n// Bytes-only base64 encoder; callers should UTF-8 encode text first.\nexport function base64Encode(bytes: Uint8Array): string {\n let out = \"\"\n let i = 0\n for (; i + 2 < bytes.length; i += 3) {\n const n = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]\n out +=\n BASE64_ALPHABET[(n >> 18) & 63] +\n BASE64_ALPHABET[(n >> 12) & 63] +\n BASE64_ALPHABET[(n >> 6) & 63] +\n BASE64_ALPHABET[n & 63]\n }\n if (i === bytes.length) return out\n const n = bytes[i] << 16\n if (i + 1 < bytes.length) {\n const n2 = n | (bytes[i + 1] << 8)\n out +=\n BASE64_ALPHABET[(n2 >> 18) & 63] +\n BASE64_ALPHABET[(n2 >> 12) & 63] +\n BASE64_ALPHABET[(n2 >> 6) & 63] +\n \"=\"\n } else {\n out +=\n BASE64_ALPHABET[(n >> 18) & 63] + BASE64_ALPHABET[(n >> 12) & 63] + \"==\"\n }\n return out\n}\n\nexport function base64Decode(b64: string): Uint8Array | null {\n try {\n const cleaned = b64.trim().replace(/=+$/g, \"\")\n if (cleaned.length === 0) return new Uint8Array(0)\n if (cleaned.length % 4 === 1) return null\n const out = new Uint8Array(Math.floor((cleaned.length * 3) / 4))\n let buffer = 0\n let bits = 0\n let outIndex = 0\n for (let i = 0; i < cleaned.length; i++) {\n const code = BASE64_CODES[cleaned.charCodeAt(i)]\n if (code === 255) return null\n buffer = (buffer << 6) | code\n bits += 6\n if (bits >= 8) {\n bits -= 8\n out[outIndex++] = (buffer >> bits) & 255\n }\n }\n return outIndex === out.length ? out : out.slice(0, outIndex)\n } catch {\n return null\n }\n}\n\nexport function base64UrlEncode(bytes: Uint8Array): string {\n return base64Encode(bytes)\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/=+$/g, \"\")\n}\n\nexport function hexToBytes(hex: Hex): Uint8Array {\n const h = hex.slice(2)\n if (h.length % 2 !== 0)\n throw new Eip8128Error(\"UNSUPPORTED_REQUEST\", \"Invalid hex length.\")\n const out = new Uint8Array(h.length / 2)\n for (let i = 0; i < out.length; i++)\n out[i] = parseInt(h.slice(i * 2, i * 2 + 2), 16)\n return out\n}\n\nexport function bytesToHex(bytes: Uint8Array): Hex {\n let out = \"0x\"\n for (const b of bytes) out += b.toString(16).padStart(2, \"0\")\n return out as Hex\n}\n",
|
|
10
|
+
"import { type ContentDigestMode, Eip8128Error } from \"../types.ts\"\nimport { base64Encode, readBodyBytes, sha256 } from \"../utilities.ts\"\n\n/**\n * Sets or validates the Content-Digest header on the request.\n *\n * @param mode - How to handle the Content-Digest header:\n * - \"auto\": Use existing header if present, otherwise compute from body (default)\n * - \"recompute\": Always recompute and overwrite existing header\n * - \"require\": Require header to exist, throw if missing (does not compute)\n * - \"off\": Disabled (throws if content-digest is in components)\n */\nexport async function setContentDigestHeader(\n request: Request,\n mode: ContentDigestMode\n): Promise<Request> {\n const headers = new Headers(request.headers)\n const existing = headers.get(\"content-digest\")\n\n if (mode === \"off\") {\n throw new Eip8128Error(\n \"DIGEST_REQUIRED\",\n \"content-digest is required by covered components, but contentDigest='off'.\"\n )\n }\n if (mode === \"require\" && !existing) {\n throw new Eip8128Error(\n \"DIGEST_REQUIRED\",\n \"content-digest is required but missing.\"\n )\n }\n if (existing && mode === \"auto\") return request\n\n const bodyBytes = await readBodyBytes(request)\n const digest = await sha256(bodyBytes)\n const digestB64 = base64Encode(digest)\n headers.set(\"content-digest\", `sha-256=:${digestB64}:`)\n return new Request(request, { headers })\n}\n\nexport async function verifyContentDigest(request: Request): Promise<boolean> {\n const v = request.headers.get(\"content-digest\")\n if (!v) return false\n\n const parsed = parseContentDigest(v)\n if (!parsed) return false\n if (parsed.alg !== \"sha-256\") return false // minimal support\n\n const bodyBytes = await readBodyBytes(request)\n const digest = await sha256(bodyBytes)\n const digestB64 = base64Encode(digest)\n return timingSafeEqualAscii(parsed.b64, digestB64)\n}\n\nexport function parseContentDigest(\n v: string\n): { alg: string; b64: string } | null {\n // Very small parser for `sha-256=:<base64>:` (ignore surrounding whitespace)\n const s = v.trim()\n const m = /^([A-Za-z0-9_-]+)=:([A-Za-z0-9+/]+={0,2}):$/.exec(s)\n if (!m) return null\n return { alg: m[1].toLowerCase(), b64: m[2] }\n}\n\nfunction timingSafeEqualAscii(a: string, b: string): boolean {\n // Not truly constant-time across JS engines, but avoids early return.\n if (a.length !== b.length) return false\n let x = 0\n for (let i = 0; i < a.length; i++) x |= a.charCodeAt(i) ^ b.charCodeAt(i)\n return x === 0\n}\n",
|
|
11
|
+
"//////////////////////////////\n// Parsing: Signature-Input / Signature\n//////////////////////////////\n\nimport { Eip8128Error, type SignatureParams } from \"../types.ts\"\n\ntype ParsedSignatureInputMember = {\n label: string\n components: string[]\n params: SignatureParams\n signatureParamsValue: string // raw member value after \"label=\" (trimmed)\n}\n\nexport function parseSignatureInputDictionary(\n headerValue: string\n): ParsedSignatureInputMember[] {\n const out: ParsedSignatureInputMember[] = []\n\n for (const raw of splitTopLevelCommas(headerValue)) {\n const m = raw.trim()\n if (!m) continue\n const eq = m.indexOf(\"=\")\n if (eq <= 0)\n throw new Eip8128Error(\n \"PARSE_ERROR\",\n \"Invalid Signature-Input member (missing '=').\"\n )\n const label = m.slice(0, eq).trim()\n assertLabel(label)\n\n const value = m.slice(eq + 1).trim() // inner-list + params\n // Keep raw value to use for @signature-params line\n const signatureParamsValue = value\n\n const parsed = parseInnerListWithParams(value)\n out.push({\n label,\n components: parsed.items,\n params: parsed.params,\n signatureParamsValue\n })\n }\n return out\n}\n\nexport function parseSignatureDictionary(\n headerValue: string\n): Map<string, string> {\n const out = new Map<string, string>()\n\n for (const raw of splitTopLevelCommas(headerValue)) {\n const m = raw.trim()\n if (!m) continue\n const eq = m.indexOf(\"=\")\n if (eq <= 0)\n throw new Eip8128Error(\n \"PARSE_ERROR\",\n \"Invalid Signature member (missing '=').\"\n )\n const label = m.slice(0, eq).trim()\n assertLabel(label)\n\n const value = m.slice(eq + 1).trim()\n const b64 = parseBinaryItem(value)\n out.set(label, b64)\n }\n return out\n}\n\nfunction parseBinaryItem(v: string): string {\n // sf-binary: :base64:\n const s = v.trim()\n if (!s.startsWith(\":\") || !s.endsWith(\":\") || s.length < 3)\n throw new Eip8128Error(\"PARSE_ERROR\", \"Invalid sf-binary.\")\n const inner = s.slice(1, -1)\n if (!/^[A-Za-z0-9+/]+={0,2}$/.test(inner))\n throw new Eip8128Error(\"PARSE_ERROR\", \"Invalid base64 in sf-binary.\")\n return inner\n}\n\nfunction parseInnerListWithParams(value: string): {\n items: string[]\n params: SignatureParams\n} {\n // value like: (\"@authority\" \"@method\" \"@path\");created=...;expires=...;nonce=\"...\";keyid=\"...\"\n let i = 0\n const s = value.trim()\n if (s[i] !== \"(\")\n throw new Eip8128Error(\"PARSE_ERROR\", \"Inner list must start with '('.\")\n\n i++ // skip '('\n const items: string[] = []\n while (i < s.length) {\n skipWs()\n if (s[i] === \")\") {\n i++\n break\n }\n const str = parseSfString()\n items.push(str)\n skipWs()\n }\n if (items.length === 0)\n throw new Eip8128Error(\"PARSE_ERROR\", \"Inner list has no items.\")\n\n const params: Record<string, string | number> = {}\n while (i < s.length) {\n skipWs()\n if (s[i] !== \";\") break\n i++ // skip ';'\n skipWs()\n const key = parseToken()\n skipWs()\n if (s[i] !== \"=\")\n throw new Eip8128Error(\"PARSE_ERROR\", `Param ${key} missing '='.`)\n i++\n skipWs()\n const val = parseParamValue()\n params[key] = val\n }\n\n const created = params.created\n const expires = params.expires\n const keyid = params.keyid\n const nonce = params.nonce\n const tag = params.tag\n\n if (\n !Number.isInteger(created) ||\n !Number.isInteger(expires) ||\n typeof keyid !== \"string\"\n ) {\n throw new Eip8128Error(\n \"PARSE_ERROR\",\n \"Missing or invalid created/expires/keyid in Signature-Input.\"\n )\n }\n\n const outParams: SignatureParams = {\n created: created as number,\n expires: expires as number,\n keyid: keyid as string,\n ...(typeof nonce === \"string\" ? { nonce } : {}),\n ...(typeof tag === \"string\" ? { tag } : {})\n }\n\n return { items, params: outParams as SignatureParams }\n\n function skipWs() {\n while (i < s.length && (s[i] === \" \" || s[i] === \"\\t\")) i++\n }\n\n function parseSfString(): string {\n if (s[i] !== '\"')\n throw new Eip8128Error(\"PARSE_ERROR\", \"Expected sf-string.\")\n i++ // skip \"\n let out = \"\"\n while (i < s.length) {\n const ch = s[i]\n if (ch === '\"') {\n i++\n break\n }\n if (ch === \"\\\\\") {\n i++\n if (i >= s.length)\n throw new Eip8128Error(\"PARSE_ERROR\", \"Bad escape in sf-string.\")\n out += s[i]\n i++\n continue\n }\n // disallow controls\n const code = ch.charCodeAt(0)\n if (code < 0x20 || code === 0x7f)\n throw new Eip8128Error(\"PARSE_ERROR\", \"Control char in sf-string.\")\n out += ch\n i++\n }\n return out\n }\n\n function parseToken(): string {\n const start = i\n while (i < s.length && /[A-Za-z0-9_\\-*.]/.test(s[i])) i++\n if (i === start) throw new Eip8128Error(\"PARSE_ERROR\", \"Expected token.\")\n return s.slice(start, i)\n }\n\n function parseParamValue(): string | number {\n if (s[i] === '\"') return parseSfString()\n // integer\n const start = i\n if (s[i] === \"-\") i++\n while (i < s.length && /[0-9]/.test(s[i])) i++\n if (i === start)\n throw new Eip8128Error(\"PARSE_ERROR\", \"Expected param value.\")\n const num = Number(s.slice(start, i))\n if (!Number.isFinite(num))\n throw new Eip8128Error(\"PARSE_ERROR\", \"Bad integer param value.\")\n return num\n }\n}\n\nfunction splitTopLevelCommas(s: string): string[] {\n // Split on commas not inside quotes.\n const out: string[] = []\n let cur = \"\"\n let inQuotes = false\n let isEscaped = false\n\n for (let i = 0; i < s.length; i++) {\n const ch = s[i]\n if (isEscaped) {\n cur += ch\n isEscaped = false\n continue\n }\n if (ch === \"\\\\\" && inQuotes) {\n cur += ch\n isEscaped = true\n continue\n }\n if (ch === '\"') {\n cur += ch\n inQuotes = !inQuotes\n continue\n }\n if (ch === \",\" && !inQuotes) {\n out.push(cur)\n cur = \"\"\n continue\n }\n cur += ch\n }\n if (cur) out.push(cur)\n return out\n}\n\nexport function assertLabel(label: string) {\n // Minimal signature label: lowercase token\n if (!/^[a-z][a-z0-9_.-]*$/.test(label))\n throw new Eip8128Error(\"PARSE_ERROR\", `Invalid signature label: ${label}`)\n}\n",
|
|
12
|
+
"import {\n type BindingMode,\n Eip8128Error,\n type SignatureParams\n} from \"../types.ts\"\nimport { assertLabel } from \"./createSignatureInput.ts\"\n\nexport function serializeSignatureParamsInnerList(\n components: string[],\n params: SignatureParams\n): string {\n const items = components.map((c) => quoteSfString(c)).join(\" \")\n const inner = `(${items})`\n\n let out = inner\n out += `;created=${params.created}`\n out += `;expires=${params.expires}`\n if (params.nonce != null) out += `;nonce=${quoteSfString(params.nonce)}`\n if (params.tag != null) out += `;tag=${quoteSfString(params.tag)}`\n out += `;keyid=${quoteSfString(params.keyid)}`\n\n return out\n}\n\n/**\n * Validation helper kept separate from formatting so other call-sites can reuse it.\n * (Still throws the same error codes/messages as before.)\n */\nexport function assertSignatureParamsForSerialization(\n params: SignatureParams\n): void {\n if (!Number.isInteger(params.created) || !Number.isInteger(params.expires))\n throw new Eip8128Error(\n \"INVALID_OPTIONS\",\n \"created/expires must be integers.\"\n )\n if (params.expires <= params.created)\n throw new Eip8128Error(\"INVALID_OPTIONS\", \"expires must be > created.\")\n if (!params.keyid)\n throw new Eip8128Error(\"INVALID_OPTIONS\", \"keyid is required.\")\n}\n\nexport function serializeSignatureInputHeader(\n label: string,\n signatureParamsValue: string\n): string {\n assertLabel(label)\n return `${label}=${signatureParamsValue}`\n}\n\nexport function serializeSignatureHeader(\n label: string,\n signatureB64: string\n): string {\n assertLabel(label)\n if (!/^[A-Za-z0-9+/]+={0,2}$/.test(signatureB64))\n throw new Eip8128Error(\"BAD_HEADER_VALUE\", \"Signature must be base64.\")\n return `${label}=:${signatureB64}:`\n}\n\nexport function appendDictionaryMember(\n existing: string | null,\n member: string\n): string {\n if (!existing) return member\n return `${existing}, ${member}`\n}\n\nexport function quoteSfString(value: string): string {\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i)\n if ((code >= 0 && code <= 0x1f) || code === 0x7f)\n throw new Eip8128Error(\n \"BAD_HEADER_VALUE\",\n \"sf-string cannot contain control characters.\"\n )\n }\n const escaped = value.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')\n return `\"${escaped}\"`\n}\n\nexport function normalizeComponents(components: string[]): string[] {\n return components.map((c) => c.trim()).filter(Boolean)\n}\n\nexport function defaultComponents(args: {\n binding: BindingMode\n hasQuery: boolean\n hasBody: boolean\n}): string[] {\n const { binding, hasQuery, hasBody } = args\n\n if (binding === \"class-bound\") return [\"@authority\"]\n\n const c = [\"@authority\", \"@method\", \"@path\"]\n if (hasQuery) c.push(\"@query\")\n if (hasBody) c.push(\"content-digest\")\n return c\n}\n\nexport function resolveComponents(args: {\n binding: BindingMode\n hasQuery: boolean\n hasBody: boolean\n providedComponents?: string[]\n}): string[] {\n const { binding, hasQuery, hasBody, providedComponents } = args\n\n if (binding === \"request-bound\") {\n // Derive the minimal required set from the request and append extras if provided.\n const base = defaultComponents({ binding, hasQuery, hasBody })\n if (!providedComponents) return base\n const extra = normalizeComponents(providedComponents).filter(\n (c) => !base.includes(c)\n )\n return base.concat(extra)\n }\n\n // Class-bound: components are required\n if (!providedComponents) {\n throw new Eip8128Error(\n \"INVALID_OPTIONS\",\n \"components are required for class-bound signatures.\"\n )\n }\n\n const components = normalizeComponents(providedComponents)\n // always include @authority\n if (!components.includes(\"@authority\")) components.unshift(\"@authority\")\n\n return components\n}\n",
|
|
13
|
+
"import { Eip8128Error } from \"../types.ts\"\nimport { sanitizeUrl, utf8Encode } from \"../utilities.ts\"\nimport { quoteSfString } from \"./serializations.ts\"\n\nexport function createSignatureBaseMinimal(args: {\n request: Request\n components: string[]\n signatureParamsValue: string // the inner-list+params string, e.g. (\"@authority\"...);created=...;...\n}): Uint8Array {\n const { request, components, signatureParamsValue } = args\n const url = sanitizeUrl(request.url)\n\n const lines: string[] = []\n for (const comp of components) {\n const value = componentValueMinimal({ request, url, component: comp })\n\n // strict: no CR/LF and only visible ASCII + SP\n if (\n /[^\\x20-\\x7E]/.test(value) ||\n value.includes(\"\\r\") ||\n value.includes(\"\\n\")\n ) {\n throw new Eip8128Error(\n \"BAD_DERIVED_VALUE\",\n `Component ${comp} produced invalid characters.`\n )\n }\n lines.push(`${quoteSfString(comp)}: ${value}`)\n }\n\n const sigParamsLine = `${quoteSfString(\"@signature-params\")}: ${signatureParamsValue}`\n const base = lines.length\n ? `${lines.join(\"\\n\")}\\n${sigParamsLine}`\n : sigParamsLine\n return utf8Encode(base)\n}\n\nfunction componentValueMinimal(args: {\n request: Request\n url: URL\n component: string\n}): string {\n const { request, url, component } = args\n\n switch (component) {\n case \"@method\": {\n const m = (request.method || \"GET\").toUpperCase()\n ensureNoCrlf(m, \"@method\")\n return m\n }\n case \"@authority\": {\n const scheme = url.protocol.replace(\":\", \"\").toLowerCase()\n const hostname = url.hostname.toLowerCase()\n const port = url.port\n\n let authority = hostname\n if (port) {\n const p = Number(port)\n const isDefault =\n (scheme === \"http\" && p === 80) || (scheme === \"https\" && p === 443)\n if (!isDefault) authority = `${hostname}:${port}`\n }\n ensureNoCrlf(authority, \"@authority\")\n return authority\n }\n case \"@path\": {\n const path = url.pathname || \"/\"\n ensureNoCrlf(path, \"@path\")\n return path\n }\n case \"@query\": {\n const q = url.search || \"\"\n ensureNoCrlf(q, \"@query\")\n return q\n }\n default: {\n // header field component (e.g. content-digest)\n const v = request.headers.get(component)\n if (v == null)\n throw new Eip8128Error(\n \"BAD_HEADER_VALUE\",\n `Required header \"${component}\" is missing.`\n )\n const canon = canonicalizeFieldValue(v)\n ensureNoCrlf(canon, component)\n return canon\n }\n }\n}\n\nfunction canonicalizeFieldValue(v: string): string {\n return v.trim().replace(/[ \\t]+/g, \" \")\n}\n\nfunction ensureNoCrlf(value: string, name: string) {\n if (value.includes(\"\\r\") || value.includes(\"\\n\")) {\n throw new Eip8128Error(\"BAD_DERIVED_VALUE\", `${name} contains CR/LF.`)\n }\n}\n",
|
|
14
|
+
"//////////////////////////////\n// keyid\n//////////////////////////////\n\nimport type { Address } from \"./types.ts\"\nimport { Eip8128Error } from \"./types.ts\"\n\nexport function formatKeyId(chainId: number, address: Address): string {\n if (!Number.isInteger(chainId))\n throw new Eip8128Error(\n \"INVALID_OPTIONS\",\n \"chainId must be positive integer.\"\n )\n return `eip8128:${chainId}:${address.toLowerCase()}`\n}\n\nexport function parseKeyId(\n keyid: string\n): { chainId: number; address: Address } | null {\n const m = /^eip8128:(\\d+):(0x[a-fA-F0-9]{40})$/.exec(keyid)\n if (!m) return null\n const chainId = Number(m[1])\n if (!Number.isInteger(chainId)) return null\n return { chainId, address: m[2].toLowerCase() as Address }\n}\n",
|
|
15
|
+
"//////////////////////////////\n// Nonce\n//////////////////////////////\n\nimport type { SignOptions } from \"./types.ts\"\nimport { base64UrlEncode, randomBytes } from \"./utilities.ts\"\n\nexport async function resolveNonce(opts: SignOptions): Promise<string> {\n if (typeof opts.nonce === \"string\") return opts.nonce\n if (typeof opts.nonce === \"function\") return opts.nonce()\n\n // Auto-generate nonce if not provided (required for non-replayable signatures)\n const rnd = randomBytes(16)\n return base64UrlEncode(rnd)\n}\n",
|
|
16
|
+
"/* eslint-disable no-control-regex */\nimport { setContentDigestHeader } from \"./lib/engine/contentDigest.ts\"\nimport { createSignatureBaseMinimal } from \"./lib/engine/createSignatureBase.ts\"\nimport {\n appendDictionaryMember,\n assertSignatureParamsForSerialization,\n resolveComponents,\n serializeSignatureHeader,\n serializeSignatureInputHeader,\n serializeSignatureParamsInnerList\n} from \"./lib/engine/serializations.ts\"\nimport { formatKeyId } from \"./lib/keyId.ts\"\nimport { resolveNonce } from \"./lib/nonce.ts\"\nimport {\n Eip8128Error,\n type EthHttpSigner,\n type SignatureParams,\n type SignOptions\n} from \"./lib/types.ts\"\nimport {\n base64Encode,\n hexToBytes,\n isEthHttpSigner,\n sanitizeUrl,\n toRequest,\n unixNow\n} from \"./lib/utilities.ts\"\n\n/**\n * Minimal EIP-8128 signing\n * - Fetch-first: works in browsers, workers, Node 18+.\n * - Minimal RFC 9421 engine: message to sign is an ERFC9421 compliant signature base.\n * - Minimal Structured Fields serialization: enough to serialize Signature-Input + Signature for one label.\n *\n * IMPORTANT:\n * - This is \"signing side\" only. Verification is not included here.\n * - For Request-Bound with body: we compute Content-Digest using SHA-256 and include it when required.\n * - SHA-256 requires WebCrypto (crypto.subtle) or Node 'node:crypto'. The library will throw CRYPTO_UNAVAILABLE if neither is available.\n */\n\n/**\n * Sign a fetch Request (or RequestInfo+RequestInit) and return a NEW Request with:\n * - Signature-Input\n * - Signature\n * - Content-Digest (if required)\n */\nexport async function signRequest(\n input: RequestInfo,\n signer: EthHttpSigner,\n opts?: SignOptions\n): Promise<Request>\nexport async function signRequest(\n input: RequestInfo,\n init: RequestInit | undefined,\n signer: EthHttpSigner,\n opts?: SignOptions\n): Promise<Request>\nexport async function signRequest(\n input: RequestInfo,\n initOrSigner: RequestInit | EthHttpSigner | undefined,\n signerOrOpts?: EthHttpSigner | SignOptions,\n opts?: SignOptions\n): Promise<Request> {\n let init: RequestInit | undefined\n let signer: EthHttpSigner\n let signOpts: SignOptions | undefined\n\n if (isEthHttpSigner(initOrSigner)) {\n signer = initOrSigner\n signOpts = signerOrOpts as SignOptions | undefined\n } else {\n init = initOrSigner\n signer = signerOrOpts as EthHttpSigner\n signOpts = opts\n }\n\n const resolvedOpts = signOpts ?? {}\n const request = toRequest(input, init)\n\n const label = resolvedOpts.label ?? \"eth\"\n const binding = resolvedOpts.binding ?? \"request-bound\"\n const replay = resolvedOpts.replay ?? \"non-replayable\"\n const headerMode = resolvedOpts.headerMode ?? \"replace\"\n const digestMode = resolvedOpts.contentDigest ?? \"auto\"\n\n const now = unixNow()\n const created = resolvedOpts.created ?? now\n const ttl = resolvedOpts.ttlSeconds ?? 60\n const expires = resolvedOpts.expires ?? created + ttl\n\n const nonce =\n replay === \"non-replayable\" ? await resolveNonce(resolvedOpts) : undefined\n\n const keyid = formatKeyId(signer.chainId, signer.address)\n\n const url = sanitizeUrl(request.url)\n const hasQuery = url.search.length > 0\n const hasBody = request.body != null\n\n let components = resolveComponents({\n binding,\n hasQuery,\n hasBody,\n providedComponents: resolvedOpts.components\n })\n\n let signedRequest = request\n\n // Set content-digest header if required by components\n if (components.includes(\"content-digest\")) {\n signedRequest = await setContentDigestHeader(signedRequest, digestMode)\n } else if (binding === \"request-bound\" && hasBody) {\n // Auto-add content-digest for request-bound with body\n components = [...components, \"content-digest\"]\n signedRequest = await setContentDigestHeader(signedRequest, digestMode)\n }\n\n const params: SignatureParams = {\n created,\n expires,\n keyid,\n ...(nonce ? { nonce } : {})\n }\n\n assertSignatureParamsForSerialization(params)\n\n const signatureParamsValue = serializeSignatureParamsInnerList(\n components,\n params\n )\n const signatureInputHeader = serializeSignatureInputHeader(\n label,\n signatureParamsValue\n )\n\n const M = createSignatureBaseMinimal({\n request: signedRequest,\n components,\n signatureParamsValue\n })\n\n const sigHex = await signer.signMessage(M)\n const sigBytes = hexToBytes(sigHex)\n if (sigBytes.length === 0)\n throw new Eip8128Error(\n \"UNSUPPORTED_REQUEST\",\n \"Signer returned empty signature.\"\n )\n\n const sigB64 = base64Encode(sigBytes)\n const signatureHeader = serializeSignatureHeader(label, sigB64)\n\n const headers = new Headers(signedRequest.headers)\n if (headerMode === \"replace\") {\n headers.set(\"Signature-Input\", signatureInputHeader)\n headers.set(\"Signature\", signatureHeader)\n } else {\n headers.set(\n \"Signature-Input\",\n appendDictionaryMember(\n headers.get(\"Signature-Input\"),\n signatureInputHeader\n )\n )\n headers.set(\n \"Signature\",\n appendDictionaryMember(headers.get(\"Signature\"), signatureHeader)\n )\n }\n\n return new Request(signedRequest, { headers })\n}\n\nexport async function signedFetch(\n input: RequestInfo,\n signer: EthHttpSigner,\n opts?: SignOptions & { fetch?: typeof fetch }\n): Promise<Response>\nexport async function signedFetch(\n input: RequestInfo,\n init: RequestInit | undefined,\n signer: EthHttpSigner,\n opts?: SignOptions & { fetch?: typeof fetch }\n): Promise<Response>\nexport async function signedFetch(\n input: RequestInfo,\n initOrSigner: RequestInit | EthHttpSigner | undefined,\n signerOrOpts?: EthHttpSigner | (SignOptions & { fetch?: typeof fetch }),\n opts?: SignOptions & { fetch?: typeof fetch }\n): Promise<Response> {\n let init: RequestInit | undefined\n let signer: EthHttpSigner\n let resolvedOpts: (SignOptions & { fetch?: typeof fetch }) | undefined\n\n if (isEthHttpSigner(initOrSigner)) {\n signer = initOrSigner\n resolvedOpts = signerOrOpts as\n | (SignOptions & { fetch?: typeof fetch })\n | undefined\n } else {\n init = initOrSigner\n signer = signerOrOpts as EthHttpSigner\n resolvedOpts = opts\n }\n\n const req = await signRequest(input, init, signer, resolvedOpts)\n const f = resolvedOpts?.fetch ?? globalThis.fetch\n if (typeof f !== \"function\")\n throw new Eip8128Error(\n \"UNSUPPORTED_REQUEST\",\n \"No fetch implementation available. Provide opts.fetch.\"\n )\n return f(req)\n}\n",
|
|
17
|
+
"import type { EthHttpSigner, SignOptions } from \"./lib/types.ts\"\nimport { signedFetch, signRequest } from \"./sign.ts\"\n\nexport type ClientOptions = SignOptions & { fetch?: typeof fetch }\n\nexport type Client = {\n signRequest: {\n (input: RequestInfo, opts?: SignOptions): Promise<Request>\n (\n input: RequestInfo,\n init: RequestInit | undefined,\n opts?: SignOptions\n ): Promise<Request>\n }\n signedFetch: {\n (input: RequestInfo, opts?: ClientOptions): Promise<Response>\n (\n input: RequestInfo,\n init: RequestInit | undefined,\n opts?: ClientOptions\n ): Promise<Response>\n }\n fetch: {\n (input: RequestInfo, opts?: ClientOptions): Promise<Response>\n (\n input: RequestInfo,\n init: RequestInit | undefined,\n opts?: ClientOptions\n ): Promise<Response>\n }\n}\n\nconst REQUEST_INIT_KEYS = new Set([\n \"method\",\n \"headers\",\n \"body\",\n \"signal\",\n \"credentials\",\n \"mode\",\n \"cache\",\n \"redirect\",\n \"referrer\",\n \"integrity\",\n \"keepalive\",\n \"window\"\n])\n\nfunction isRequestInit(value: unknown): value is RequestInit {\n if (!value || typeof value !== \"object\") return false\n for (const key of REQUEST_INIT_KEYS) {\n if (key in (value as Record<string, unknown>)) return true\n }\n return false\n}\n\nfunction splitInitAndOpts<TOpts extends SignOptions>(\n initOrOpts?: RequestInit | TOpts,\n opts?: TOpts\n): { init?: RequestInit; opts?: TOpts } {\n if (opts !== undefined)\n return { init: initOrOpts as RequestInit | undefined, opts }\n if (isRequestInit(initOrOpts)) return { init: initOrOpts }\n return { opts: initOrOpts as TOpts | undefined }\n}\n\nexport function createClient(\n signer: EthHttpSigner,\n defaults?: ClientOptions\n): Client {\n const base = defaults ?? {}\n\n const signRequestBound: Client[\"signRequest\"] = async (\n input: RequestInfo,\n initOrOpts?: RequestInit | SignOptions,\n opts?: SignOptions\n ) => {\n const { init, opts: callOpts } = splitInitAndOpts(initOrOpts, opts)\n const merged = { ...base, ...callOpts }\n return signRequest(input, init, signer, merged)\n }\n\n const signedFetchBound: Client[\"signedFetch\"] = async (\n input: RequestInfo,\n initOrOpts?: RequestInit | ClientOptions,\n opts?: ClientOptions\n ) => {\n const { init, opts: callOpts } = splitInitAndOpts(initOrOpts, opts)\n const merged = { ...base, ...callOpts }\n return signedFetch(input, init, signer, merged)\n }\n\n const fetchBound: Client[\"fetch\"] = async (\n input: RequestInfo,\n initOrOpts?: RequestInit | ClientOptions,\n opts?: ClientOptions\n ) => {\n const { init, opts: callOpts } = splitInitAndOpts<ClientOptions>(\n initOrOpts,\n opts\n )\n const merged = { ...base, ...callOpts }\n return signedFetch(input, init, signer, merged)\n }\n\n return {\n signRequest: signRequestBound,\n signedFetch: signedFetchBound,\n fetch: fetchBound\n }\n}\n",
|
|
18
|
+
"import { parseKeyId } from \"../keyId.ts\"\nimport { Eip8128Error, type VerifyPolicy, type VerifyResult } from \"../types.ts\"\nimport {\n parseSignatureDictionary,\n parseSignatureInputDictionary\n} from \"./createSignatureInput.ts\"\n\nexport type SelectedSignature = {\n label: string\n components: string[]\n params: {\n keyid: string\n created: number\n expires: number\n nonce?: string\n tag?: string\n }\n signatureParamsValue: string\n sigB64: string\n}\n\n/**\n * Parse `Signature-Input` + `Signature` headers and select which signature member to verify.\n *\n * Selection rules:\n * - If `policy.label` is provided: prefer that label (fail if `strictLabel=true` and missing).\n * - Otherwise: pick the first `Signature-Input` member whose `keyid` is EIP-8128 compliant\n * and which has a matching `Signature` entry.\n *\n * Never throws for parse errors; returns `{ ok: false, reason: \"bad_signature_input\" }` instead.\n */\nexport function selectSignatureFromHeaders(args: {\n signatureInputHeader: string\n signatureHeader: string\n policy: Pick<VerifyPolicy, \"label\" | \"strictLabel\">\n}):\n | { ok: true; selected: SelectedSignature }\n | { ok: false; result: VerifyResult } {\n const { signatureInputHeader, signatureHeader, policy } = args\n const labelPref = policy.label\n const strictLabel = policy.strictLabel ?? false\n\n try {\n const parsedInputs = parseSignatureInputDictionary(signatureInputHeader)\n const parsedSigs = parseSignatureDictionary(signatureHeader)\n\n let chosen: (typeof parsedInputs)[number] | undefined\n let sigB64: string | undefined\n let fallback:\n | { member: (typeof parsedInputs)[number]; sigB64: string }\n | undefined\n let sawCompliantKeyid = false\n\n for (const cand of parsedInputs) {\n if (labelPref != null && cand.label === labelPref) {\n const s = parsedSigs.get(cand.label)\n if (!s)\n return { ok: false, result: { ok: false, reason: \"label_not_found\" } }\n chosen = cand\n sigB64 = s\n break\n }\n\n const key = parseKeyId(cand.params.keyid)\n if (!key) continue\n sawCompliantKeyid = true\n if (fallback) continue\n const s = parsedSigs.get(cand.label)\n if (!s) continue\n fallback = { member: cand, sigB64: s }\n }\n\n if (!chosen) {\n if (labelPref != null && strictLabel)\n return { ok: false, result: { ok: false, reason: \"label_not_found\" } }\n\n if (fallback) {\n chosen = fallback.member\n sigB64 = fallback.sigB64\n } else {\n return {\n ok: false,\n result: sawCompliantKeyid\n ? { ok: false, reason: \"label_not_found\" }\n : { ok: false, reason: \"bad_keyid\" }\n }\n }\n }\n\n if (!sigB64)\n return { ok: false, result: { ok: false, reason: \"label_not_found\" } }\n\n return {\n ok: true,\n selected: {\n label: chosen.label,\n components: chosen.components,\n params: chosen.params,\n signatureParamsValue: chosen.signatureParamsValue,\n sigB64\n }\n }\n } catch (err) {\n const detail =\n err instanceof Error ? err.message : \"Failed to parse signature headers.\"\n if (err instanceof Eip8128Error && err.code === \"PARSE_ERROR\")\n return {\n ok: false,\n result: { ok: false, reason: \"bad_signature_input\", detail }\n }\n return {\n ok: false,\n result: { ok: false, reason: \"bad_signature_input\", detail }\n }\n }\n}\n",
|
|
19
|
+
"export function isRequestBoundForThisRequest(\n components: string[],\n reqShape: { hasQuery: boolean; hasBody: boolean }\n): boolean {\n // Must include @authority, @method, @path\n const needed = [\"@authority\", \"@method\", \"@path\"]\n // If query present, must include @query\n if (reqShape.hasQuery) needed.push(\"@query\")\n // If body present, must include content-digest\n if (reqShape.hasBody) needed.push(\"content-digest\")\n\n // Must appear as an ordered subsequence (allows extra covered components too)\n return isOrderedSubsequence(needed, components)\n}\n\nexport function isOrderedSubsequence(need: string[], have: string[]): boolean {\n let j = 0\n for (let i = 0; i < have.length && j < need.length; i++) {\n if (have[i] === need[j]) j++\n }\n return j === need.length\n}\n",
|
|
20
|
+
"import { verifyContentDigest } from \"./lib/engine/contentDigest.ts\"\nimport { createSignatureBaseMinimal } from \"./lib/engine/createSignatureBase.ts\"\nimport { selectSignatureFromHeaders } from \"./lib/engine/signatureHeaders.ts\"\nimport { parseKeyId } from \"./lib/keyId.ts\"\nimport {\n isOrderedSubsequence,\n isRequestBoundForThisRequest\n} from \"./lib/policies/isRequestBound.ts\"\nimport type { Address, VerifyPolicy, VerifyResult } from \"./lib/types.ts\"\nimport {\n base64Decode,\n bytesToHex,\n sanitizeUrl,\n toRequest,\n unixNow\n} from \"./lib/utilities.ts\"\n\nconst DEFAULT_MAX_VALIDITY_SEC = 300\n\nexport async function verifyRequest(\n input: RequestInfo,\n policy?: VerifyPolicy\n): Promise<VerifyResult>\nexport async function verifyRequest(\n input: RequestInfo,\n init: RequestInit | undefined,\n policy?: VerifyPolicy\n): Promise<VerifyResult>\nexport async function verifyRequest(\n input: RequestInfo,\n initOrPolicy?: RequestInit | VerifyPolicy,\n policy?: VerifyPolicy\n): Promise<VerifyResult> {\n const hasPolicyArg = policy !== undefined\n const init = hasPolicyArg\n ? (initOrPolicy as RequestInit | undefined)\n : undefined\n const resolvedPolicy = hasPolicyArg\n ? (policy as VerifyPolicy)\n : ((initOrPolicy as VerifyPolicy | undefined) ?? {})\n\n const request = toRequest(input, init)\n const labelPref = resolvedPolicy.label\n const strictLabel = resolvedPolicy.strictLabel ?? false\n\n const sigInputHeader = request.headers.get(\"Signature-Input\")\n const sigHeader = request.headers.get(\"Signature\")\n if (!sigInputHeader || !sigHeader)\n return { ok: false, reason: \"missing_headers\" }\n\n const selected = selectSignatureFromHeaders({\n signatureInputHeader: sigInputHeader,\n signatureHeader: sigHeader,\n policy: { label: labelPref, strictLabel }\n })\n if (!selected.ok) return selected.result\n\n const { components, params, signatureParamsValue, sigB64, label } =\n selected.selected\n\n // Keyid parse\n const key = parseKeyId(params.keyid)\n if (!key) return { ok: false, reason: \"bad_keyid\" }\n const { chainId, address } = key\n\n // Time checks\n const now = resolvedPolicy.now?.() ?? unixNow()\n const skew = resolvedPolicy.clockSkewSec ?? 0\n\n if (\n !Number.isInteger(params.created) ||\n !Number.isInteger(params.expires) ||\n params.expires <= params.created\n ) {\n return { ok: false, reason: \"bad_time\" }\n }\n if (now + skew < params.created) return { ok: false, reason: \"not_yet_valid\" }\n if (now - skew > params.expires) return { ok: false, reason: \"expired\" }\n\n // Enforce a bounded validity window by default.\n // Note: treat null/undefined/NaN as \"use default\" (no bypass).\n const maxValiditySec = resolvedPolicy.maxValiditySec\n const maxValidity =\n typeof maxValiditySec === \"number\" && Number.isFinite(maxValiditySec)\n ? maxValiditySec\n : DEFAULT_MAX_VALIDITY_SEC\n if (params.expires - params.created > maxValidity) {\n return { ok: false, reason: \"validity_too_long\" }\n }\n\n // Nonce policy (replay vs non-replayable)\n const hasNonce = typeof params.nonce === \"string\" && params.nonce.length > 0\n const noncePolicy = resolvedPolicy.nonce ?? \"required\"\n\n if (noncePolicy === \"required\" && !hasNonce)\n return { ok: false, reason: \"nonce_required\" }\n if (noncePolicy === \"forbidden\" && hasNonce)\n return {\n ok: false,\n reason: \"bad_signature_input\",\n detail: \"nonce is forbidden by policy\"\n }\n\n // Nonce window enforcement (optional)\n if (hasNonce) {\n const maxNonceWin = resolvedPolicy.maxNonceWindowSec\n if (maxNonceWin != null && params.expires - params.created > maxNonceWin) {\n return { ok: false, reason: \"nonce_window_too_long\" }\n }\n }\n\n // Components checks (request-bound by default, unless overridden)\n const url = sanitizeUrl(request.url)\n const hasQuery = url.search.length > 0\n const hasBody = request.body != null\n\n const required = resolvedPolicy.requiredComponents\n ?.map((c) => c.trim())\n .filter(Boolean)\n if (required && required.length > 0) {\n if (!isOrderedSubsequence(required, components)) {\n return {\n ok: false,\n reason: \"not_request_bound\",\n detail: `requiredComponents not satisfied (need ordered subsequence: ${required.join(\n \",\"\n )})`\n }\n }\n } else {\n const requestBound = isRequestBoundForThisRequest(components, {\n hasQuery,\n hasBody\n })\n if (!requestBound) return { ok: false, reason: \"not_request_bound\" }\n }\n\n // If content-digest is covered, enforce header exists and matches body bytes (default true)\n const enforceDigest = resolvedPolicy.enforceContentDigest ?? true\n if (enforceDigest && components.includes(\"content-digest\")) {\n const v = request.headers.get(\"content-digest\")\n if (!v) return { ok: false, reason: \"digest_required\" }\n const ok = await verifyContentDigest(request)\n if (!ok) return { ok: false, reason: \"digest_mismatch\" }\n }\n\n // Nonce replay protection\n if (hasNonce) {\n const store = resolvedPolicy.nonceStore\n if (!store)\n return {\n ok: false,\n reason: \"nonce_required\",\n detail: \"nonceStore missing\"\n }\n\n const keyFn = resolvedPolicy.nonceKey ?? ((k, n) => `${k}:${n}`)\n const nonce = params.nonce\n if (!nonce)\n return {\n ok: false,\n reason: \"nonce_required\",\n detail: \"nonce missing\"\n }\n const replayKey = keyFn(params.keyid, nonce)\n const ttlSeconds = Math.max(0, params.expires - now)\n const consumed = await store.consume(replayKey, ttlSeconds)\n if (!consumed) return { ok: false, reason: \"replay\" }\n }\n\n // Build signature base M using the (raw) signatureParamsValue from header\n const M = createSignatureBaseMinimal({\n request,\n components,\n signatureParamsValue // use exactly the member value to keep parity\n })\n\n // Decode signature bytes\n const sigBytes = base64Decode(sigB64)\n if (!sigBytes || sigBytes.length === 0)\n return { ok: false, reason: \"bad_signature_bytes\" }\n const sigHex = bytesToHex(sigBytes)\n\n const verifyFn = resolvedPolicy.verifyMessage\n if (!verifyFn)\n return {\n ok: false,\n reason: \"bad_signature_check\",\n detail: \"verifyMessage missing in policy\"\n }\n\n // Verify signature (EOA / ERC-1271 / ERC-6492 / ERC-8010 depending on implementation)\n try {\n const ok = await verifyFn({\n address,\n message: { raw: bytesToHex(M) },\n signature: sigHex\n })\n if (ok) {\n return {\n ok: true,\n kind: \"eoa\",\n address: address as Address,\n chainId,\n label,\n components,\n params\n }\n }\n }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ACA,QACA,aACA,QACF,EAEF,KAAM,CACN,MAAO,CAAE,GAAI,GAAO,OAAQ,qBAAsB,EAGpD,MAAO,CAAE,GAAI,GAAO,OAAQ,eAAgB",
|
|
23
|
+
"debugId": "E4409D75420E658764756E2164756E21",
|
|
24
|
+
"names": []
|
|
25
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@slicekit/erc8128",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "EIP-8128 implementation",
|
|
5
|
+
"scripts": {
|
|
6
|
+
"format": "biome format --write",
|
|
7
|
+
"lint": "biome lint --write",
|
|
8
|
+
"check": "biome check --write",
|
|
9
|
+
"build": "bun run build.ts",
|
|
10
|
+
"test": "bun test"
|
|
11
|
+
},
|
|
12
|
+
"publishConfig": {
|
|
13
|
+
"access": "public"
|
|
14
|
+
},
|
|
15
|
+
"author": "slice-so",
|
|
16
|
+
"license": "MIT",
|
|
17
|
+
"type": "module",
|
|
18
|
+
"main": "./dist/esm/index.js",
|
|
19
|
+
"module": "./dist/esm/index.js",
|
|
20
|
+
"types": "./dist/index.d.ts",
|
|
21
|
+
"exports": {
|
|
22
|
+
".": {
|
|
23
|
+
"types": "./dist/index.d.ts",
|
|
24
|
+
"import": "./dist/esm/index.js",
|
|
25
|
+
"default": "./dist/esm/index.js"
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
"files": ["./dist"],
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@noble/hashes": "^1.8.0"
|
|
31
|
+
},
|
|
32
|
+
"peerDependencies": {},
|
|
33
|
+
"repository": {
|
|
34
|
+
"type": "git",
|
|
35
|
+
"url": "https://github.com/slice-so/slicekit"
|
|
36
|
+
},
|
|
37
|
+
"homepage": "https://slice.so",
|
|
38
|
+
"keywords": [
|
|
39
|
+
"http",
|
|
40
|
+
"ethereum",
|
|
41
|
+
"wallet",
|
|
42
|
+
"web3",
|
|
43
|
+
"dapp",
|
|
44
|
+
"dappkit"
|
|
45
|
+
]
|
|
46
|
+
}
|