@qntx/wallet-engine 0.8.1 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/connect.d.mts +3 -2
- package/dist/connect.mjs +16 -5
- package/dist/connect.mjs.map +1 -1
- package/dist/{errors-CW_XXGL9.d.mts → errors-Bglz0VYn.d.mts} +617 -235
- package/dist/gateway-contract.d.mts +79 -2
- package/dist/gateway-contract.mjs +213 -2
- package/dist/gateway-contract.mjs.map +1 -1
- package/dist/idb.d.mts +14 -1
- package/dist/idb.mjs +43 -12
- package/dist/idb.mjs.map +1 -1
- package/dist/index.d.mts +57 -5
- package/dist/index.mjs +3267 -3454
- package/dist/index.mjs.map +1 -1
- package/dist/{registry-LcFSPrE1.d.mts → registry-Deo5WQe1.d.mts} +3 -1
- package/dist/{registry-CHiAn88k.mjs → registry-wYrcuFNc.mjs} +8 -7
- package/dist/registry-wYrcuFNc.mjs.map +1 -0
- package/dist/webln-BGKm12wd.mjs +3638 -0
- package/dist/webln-BGKm12wd.mjs.map +1 -0
- package/package.json +12 -7
- package/dist/registry-CHiAn88k.mjs.map +0 -1
- package/dist/webln-CHjBMRcv.mjs +0 -1247
- package/dist/webln-CHjBMRcv.mjs.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as networkById, i as SOLANA_NETWORKS, n as NETWORKS, r as NetworkInfo, t as BITCOIN_NETWORKS } from "./registry-
|
|
1
|
+
import { a as networkById, i as SOLANA_NETWORKS, n as NETWORKS, r as NetworkInfo, t as BITCOIN_NETWORKS } from "./registry-Deo5WQe1.mjs";
|
|
2
2
|
import * as z from "zod/mini";
|
|
3
3
|
export declare const INSTALL_ID_HEADER = "x-install-id";
|
|
4
4
|
export declare const PROVIDERS_HEADER = "x-gateway-providers";
|
|
@@ -43,7 +43,7 @@ export declare const health: Endpoint<z.ZodMiniUndefined, z.ZodMiniObject<{
|
|
|
43
43
|
/** One JSON-RPC call plus nothing else: batches may carry at most this many entries. */
|
|
44
44
|
export declare const RPC_BATCH_MAX = 20;
|
|
45
45
|
/** Read-only EVM methods plus `eth_sendRawTransaction`. Anything not listed is rejected. */
|
|
46
|
-
export declare const EVM_RPC_METHODS: readonly ["eth_blobBaseFee", "eth_blockNumber", "eth_call", "eth_chainId", "eth_createAccessList", "eth_estimateGas", "eth_feeHistory", "eth_gasPrice", "eth_getBalance", "eth_getBlockByHash", "eth_getBlockByNumber", "eth_getBlockReceipts", "eth_getBlockTransactionCountByHash", "eth_getBlockTransactionCountByNumber", "eth_getCode", "eth_getProof", "eth_getStorageAt", "eth_getTransactionByBlockHashAndIndex", "eth_getTransactionByBlockNumberAndIndex", "eth_getTransactionByHash", "eth_getTransactionCount", "eth_getTransactionReceipt", "eth_maxPriorityFeePerGas", "eth_sendRawTransaction", "net_version", "web3_clientVersion"];
|
|
46
|
+
export declare const EVM_RPC_METHODS: readonly ["eth_blobBaseFee", "eth_blockNumber", "eth_call", "eth_chainId", "eth_createAccessList", "eth_estimateGas", "eth_feeHistory", "eth_gasPrice", "eth_getBalance", "eth_getBlockByHash", "eth_getBlockByNumber", "eth_getBlockReceipts", "eth_getBlockTransactionCountByHash", "eth_getBlockTransactionCountByNumber", "eth_getCode", "eth_getProof", "eth_getStorageAt", "eth_getTransactionByBlockHashAndIndex", "eth_getTransactionByBlockNumberAndIndex", "eth_getTransactionByHash", "eth_getTransactionCount", "eth_getTransactionReceipt", "eth_maxPriorityFeePerGas", "eth_sendRawTransaction", "eth_simulateV1", "net_version", "web3_clientVersion"];
|
|
47
47
|
/** Read-only Solana methods plus `sendTransaction`. Anything not listed is rejected. */
|
|
48
48
|
export declare const SOLANA_RPC_METHODS: readonly ["getAccountInfo", "getBalance", "getBlock", "getBlockHeight", "getBlockTime", "getEpochInfo", "getFeeForMessage", "getGenesisHash", "getLatestBlockhash", "getMinimumBalanceForRentExemption", "getMultipleAccounts", "getRecentPrioritizationFees", "getSignatureStatuses", "getSignaturesForAddress", "getSlot", "getTokenAccountBalance", "getTokenAccountsByOwner", "getTokenSupply", "getTransaction", "getVersion", "isBlockhashValid", "sendTransaction", "simulateTransaction"];
|
|
49
49
|
export type EvmRpcMethod = (typeof EVM_RPC_METHODS)[number];
|
|
@@ -89,6 +89,7 @@ export declare const evmRpcRequest: z.ZodMiniUnion<readonly [z.ZodMiniObject<{
|
|
|
89
89
|
eth_getTransactionReceipt: "eth_getTransactionReceipt";
|
|
90
90
|
eth_maxPriorityFeePerGas: "eth_maxPriorityFeePerGas";
|
|
91
91
|
eth_sendRawTransaction: "eth_sendRawTransaction";
|
|
92
|
+
eth_simulateV1: "eth_simulateV1";
|
|
92
93
|
net_version: "net_version";
|
|
93
94
|
web3_clientVersion: "web3_clientVersion";
|
|
94
95
|
}>;
|
|
@@ -121,6 +122,7 @@ export declare const evmRpcRequest: z.ZodMiniUnion<readonly [z.ZodMiniObject<{
|
|
|
121
122
|
eth_getTransactionReceipt: "eth_getTransactionReceipt";
|
|
122
123
|
eth_maxPriorityFeePerGas: "eth_maxPriorityFeePerGas";
|
|
123
124
|
eth_sendRawTransaction: "eth_sendRawTransaction";
|
|
125
|
+
eth_simulateV1: "eth_simulateV1";
|
|
124
126
|
net_version: "net_version";
|
|
125
127
|
web3_clientVersion: "web3_clientVersion";
|
|
126
128
|
}>;
|
|
@@ -281,5 +283,80 @@ export declare const servedNetworks: Endpoint<z.ZodMiniUndefined, z.ZodMiniObjec
|
|
|
281
283
|
networks: z.ZodMiniArray<z.ZodMiniString<string>>;
|
|
282
284
|
}, z.core.$strip>>;
|
|
283
285
|
export declare const networksPath: string;
|
|
286
|
+
export declare const PHISHING_HASH_BYTES = 8;
|
|
287
|
+
export declare const PHISHING_MAX_PATH_SEGMENTS = 8;
|
|
288
|
+
/** One list entry as its lookup key, or `undefined` when the entry is not a usable host or path. */
|
|
289
|
+
export declare function phishingKey(entry: string): string | undefined;
|
|
290
|
+
/** The first 8 bytes of SHA-256 over the UTF-8 key. */
|
|
291
|
+
export declare function phishingHash(key: string): Uint8Array;
|
|
292
|
+
/** Lookup keys for a page URL, most specific first; empty for anything but http(s). */
|
|
293
|
+
export declare function phishingCandidates(url: string): ReadonlyArray<string>;
|
|
294
|
+
export declare const phishingListRequest: z.ZodMiniObject<{
|
|
295
|
+
since: z.ZodMiniOptional<z.ZodMiniString<string>>;
|
|
296
|
+
}, z.core.$strip>;
|
|
297
|
+
export declare const phishingListResponse: z.ZodMiniDiscriminatedUnion<[z.ZodMiniObject<{
|
|
298
|
+
kind: z.ZodMiniLiteral<"current">;
|
|
299
|
+
version: z.ZodMiniNumber<number>;
|
|
300
|
+
}, z.core.$strip>, z.ZodMiniObject<{
|
|
301
|
+
kind: z.ZodMiniLiteral<"diff">;
|
|
302
|
+
from: z.ZodMiniNumber<number>;
|
|
303
|
+
version: z.ZodMiniNumber<number>;
|
|
304
|
+
deny: z.ZodMiniObject<{
|
|
305
|
+
add: z.ZodMiniString<string>;
|
|
306
|
+
remove: z.ZodMiniString<string>;
|
|
307
|
+
}, z.core.$strip>;
|
|
308
|
+
allow: z.ZodMiniObject<{
|
|
309
|
+
add: z.ZodMiniString<string>;
|
|
310
|
+
remove: z.ZodMiniString<string>;
|
|
311
|
+
}, z.core.$strip>;
|
|
312
|
+
}, z.core.$strip>, z.ZodMiniObject<{
|
|
313
|
+
kind: z.ZodMiniLiteral<"snapshot">;
|
|
314
|
+
version: z.ZodMiniNumber<number>;
|
|
315
|
+
deny: z.ZodMiniString<string>;
|
|
316
|
+
allow: z.ZodMiniString<string>;
|
|
317
|
+
}, z.core.$strip>], "kind">;
|
|
318
|
+
export type PhishingListResponse = z.infer<typeof phishingListResponse>;
|
|
319
|
+
export declare const phishingList: Endpoint<z.ZodMiniObject<{
|
|
320
|
+
since: z.ZodMiniOptional<z.ZodMiniString<string>>;
|
|
321
|
+
}, z.core.$strip>, z.ZodMiniDiscriminatedUnion<[z.ZodMiniObject<{
|
|
322
|
+
kind: z.ZodMiniLiteral<"current">;
|
|
323
|
+
version: z.ZodMiniNumber<number>;
|
|
324
|
+
}, z.core.$strip>, z.ZodMiniObject<{
|
|
325
|
+
kind: z.ZodMiniLiteral<"diff">;
|
|
326
|
+
from: z.ZodMiniNumber<number>;
|
|
327
|
+
version: z.ZodMiniNumber<number>;
|
|
328
|
+
deny: z.ZodMiniObject<{
|
|
329
|
+
add: z.ZodMiniString<string>;
|
|
330
|
+
remove: z.ZodMiniString<string>;
|
|
331
|
+
}, z.core.$strip>;
|
|
332
|
+
allow: z.ZodMiniObject<{
|
|
333
|
+
add: z.ZodMiniString<string>;
|
|
334
|
+
remove: z.ZodMiniString<string>;
|
|
335
|
+
}, z.core.$strip>;
|
|
336
|
+
}, z.core.$strip>, z.ZodMiniObject<{
|
|
337
|
+
kind: z.ZodMiniLiteral<"snapshot">;
|
|
338
|
+
version: z.ZodMiniNumber<number>;
|
|
339
|
+
deny: z.ZodMiniString<string>;
|
|
340
|
+
allow: z.ZodMiniString<string>;
|
|
341
|
+
}, z.core.$strip>], "kind">>;
|
|
342
|
+
export declare const phishingListPath: string;
|
|
343
|
+
/** Strictly ascending 8-byte hashes, concatenated: a sorted set. */
|
|
344
|
+
export type HashList = Uint8Array;
|
|
345
|
+
declare const size: (list: HashList) => number;
|
|
346
|
+
export declare const hashCount: typeof size;
|
|
347
|
+
/**
|
|
348
|
+
* A base64 hash list, or `undefined` when it is not whole 8-byte hashes in strictly ascending
|
|
349
|
+
* order.
|
|
350
|
+
*/
|
|
351
|
+
export declare function decodeHashList(encoded: string): HashList | undefined;
|
|
352
|
+
/** The sorted set of `hashes`, duplicates removed. */
|
|
353
|
+
export declare function hashList(hashes: Iterable<Uint8Array>): HashList;
|
|
354
|
+
export declare const encodeHashList: (list: HashList) => string;
|
|
355
|
+
export declare function contains(list: HashList, hash: Uint8Array): boolean;
|
|
356
|
+
export declare const union: (a: HashList, b: HashList) => HashList;
|
|
357
|
+
/** The hashes of `a` that are not in `b`. */
|
|
358
|
+
export declare const difference: (a: HashList, b: HashList) => HashList;
|
|
359
|
+
/** `(list − remove) ∪ add`. */
|
|
360
|
+
export declare const applyDiff: (list: HashList, add: HashList, remove: HashList) => HashList;
|
|
284
361
|
export { BITCOIN_NETWORKS, NETWORKS, type NetworkInfo, SOLANA_NETWORKS, networkById };
|
|
285
362
|
//# sourceMappingURL=gateway-contract.d.mts.map
|
|
@@ -1,5 +1,8 @@
|
|
|
1
|
-
import { i as networkById, n as NETWORKS, r as SOLANA_NETWORKS, t as BITCOIN_NETWORKS } from "./registry-
|
|
1
|
+
import { i as networkById, n as NETWORKS, r as SOLANA_NETWORKS, t as BITCOIN_NETWORKS } from "./registry-wYrcuFNc.mjs";
|
|
2
|
+
import { utf8ToBytes } from "@noble/hashes/utils.js";
|
|
2
3
|
import * as z from "zod/mini";
|
|
4
|
+
import { base64 } from "@scure/base";
|
|
5
|
+
import { sha256 } from "@noble/hashes/sha2.js";
|
|
3
6
|
// src/gateway/contract/endpoint.ts
|
|
4
7
|
/** One gateway route: its verb, versioned path template, and request/response schemas. */
|
|
5
8
|
function endpoint(method, path, request, response) {
|
|
@@ -48,6 +51,7 @@ const EVM_RPC_METHODS = [
|
|
|
48
51
|
"eth_getTransactionReceipt",
|
|
49
52
|
"eth_maxPriorityFeePerGas",
|
|
50
53
|
"eth_sendRawTransaction",
|
|
54
|
+
"eth_simulateV1",
|
|
51
55
|
"net_version",
|
|
52
56
|
"web3_clientVersion"
|
|
53
57
|
];
|
|
@@ -178,6 +182,213 @@ const servedNetworksRequest = z.undefined();
|
|
|
178
182
|
const servedNetworksResponse = z.object({ networks: z.array(caip2) });
|
|
179
183
|
const servedNetworks = endpoint("GET", "/v1/networks", servedNetworksRequest, servedNetworksResponse);
|
|
180
184
|
const networksPath = servedNetworks.path;
|
|
181
|
-
|
|
185
|
+
// src/gateway/contract/risk.ts
|
|
186
|
+
const PHISHING_HASH_BYTES = 8;
|
|
187
|
+
const PHISHING_MAX_PATH_SEGMENTS = 8;
|
|
188
|
+
const MAX_HOST_LENGTH = 253;
|
|
189
|
+
const MIN_HOST_LABELS = 2;
|
|
190
|
+
const FORBIDDEN_ENTRY = /:\/\/|[?#@\\\s]/;
|
|
191
|
+
const IPV4 = /^\d{1,3}(?:\.\d{1,3}){3}$/;
|
|
192
|
+
/** Lowercase ASCII labels ending in a non-numeric label: `new URL` returns such a host unchanged. */
|
|
193
|
+
const PLAIN_HOST = /^(?:[a-z0-9_-]+\.)+[a-z][a-z0-9_-]*\.?$/;
|
|
194
|
+
const trimTrailingDot = (host) => host.endsWith(".") ? host.slice(0, -1) : host;
|
|
195
|
+
const pathSegments = (pathname) => pathname.split("/").filter((segment) => segment !== "");
|
|
196
|
+
/** One list entry as its lookup key, or `undefined` when the entry is not a usable host or path. */
|
|
197
|
+
function phishingKey(entry) {
|
|
198
|
+
if (PLAIN_HOST.test(entry) && !entry.includes("xn--")) {
|
|
199
|
+
const host = trimTrailingDot(entry);
|
|
200
|
+
return host.length > MAX_HOST_LENGTH ? void 0 : host;
|
|
201
|
+
}
|
|
202
|
+
let raw = entry.trim();
|
|
203
|
+
if (raw.startsWith("*.")) raw = raw.slice(2);
|
|
204
|
+
if (raw === "" || FORBIDDEN_ENTRY.test(raw)) return;
|
|
205
|
+
let url;
|
|
206
|
+
try {
|
|
207
|
+
url = new URL(`https://${raw}`);
|
|
208
|
+
} catch {
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
if ((raw.split("/")[0] ?? "").includes(":")) return;
|
|
212
|
+
const host = trimTrailingDot(url.hostname.toLowerCase());
|
|
213
|
+
const labels = host.split(".");
|
|
214
|
+
if (host.length > MAX_HOST_LENGTH || labels.length < MIN_HOST_LABELS || labels.some((label) => label === "")) return;
|
|
215
|
+
const segments = pathSegments(url.pathname);
|
|
216
|
+
if (segments.length === 0) return host;
|
|
217
|
+
if (segments.length > 8) return;
|
|
218
|
+
return `${host}/${segments.join("/")}`;
|
|
219
|
+
}
|
|
220
|
+
/** The first 8 bytes of SHA-256 over the UTF-8 key. */
|
|
221
|
+
function phishingHash(key) {
|
|
222
|
+
return sha256(utf8ToBytes(key)).slice(0, 8);
|
|
223
|
+
}
|
|
224
|
+
/** Lookup keys for a page URL, most specific first; empty for anything but http(s). */
|
|
225
|
+
function phishingCandidates(url) {
|
|
226
|
+
let parsed;
|
|
227
|
+
try {
|
|
228
|
+
parsed = new URL(url);
|
|
229
|
+
} catch {
|
|
230
|
+
return [];
|
|
231
|
+
}
|
|
232
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return [];
|
|
233
|
+
const host = trimTrailingDot(parsed.hostname);
|
|
234
|
+
if (host === "") return [];
|
|
235
|
+
if (host.startsWith("[") || IPV4.test(host)) return [host];
|
|
236
|
+
const segments = pathSegments(parsed.pathname).slice(0, 8);
|
|
237
|
+
const candidates = [];
|
|
238
|
+
for (let depth = segments.length; depth > 0; depth -= 1) candidates.push(`${host}/${segments.slice(0, depth).join("/")}`);
|
|
239
|
+
const labels = host.split(".");
|
|
240
|
+
for (let start = 0; labels.length - start >= MIN_HOST_LABELS; start += 1) candidates.push(labels.slice(start).join("."));
|
|
241
|
+
return candidates;
|
|
242
|
+
}
|
|
243
|
+
const version = z.number().check(z.int(), z.nonnegative());
|
|
244
|
+
/** Concatenated sorted 8-byte hashes, standard-alphabet base64; the empty string is an empty set. */
|
|
245
|
+
const hashes = z.string().check(z.regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/));
|
|
246
|
+
const delta = z.object({
|
|
247
|
+
add: hashes,
|
|
248
|
+
remove: hashes
|
|
249
|
+
});
|
|
250
|
+
const phishingListRequest = z.object({ since: z.optional(z.string().check(z.regex(/^\d{1,15}$/))) });
|
|
251
|
+
const phishingListResponse = z.discriminatedUnion("kind", [
|
|
252
|
+
z.object({
|
|
253
|
+
kind: z.literal("current"),
|
|
254
|
+
version
|
|
255
|
+
}),
|
|
256
|
+
z.object({
|
|
257
|
+
kind: z.literal("diff"),
|
|
258
|
+
from: version,
|
|
259
|
+
version,
|
|
260
|
+
deny: delta,
|
|
261
|
+
allow: delta
|
|
262
|
+
}),
|
|
263
|
+
z.object({
|
|
264
|
+
kind: z.literal("snapshot"),
|
|
265
|
+
version,
|
|
266
|
+
deny: hashes,
|
|
267
|
+
allow: hashes
|
|
268
|
+
})
|
|
269
|
+
]);
|
|
270
|
+
const phishingList = endpoint("GET", "/v1/risk/lists/phishing", phishingListRequest, phishingListResponse);
|
|
271
|
+
const phishingListPath = phishingList.path;
|
|
272
|
+
// src/gateway/contract/hash-list.ts
|
|
273
|
+
const WIDTH = 8;
|
|
274
|
+
function compareAt(a, ai, b, bi) {
|
|
275
|
+
for (let k = 0; k < WIDTH; k += 1) {
|
|
276
|
+
const delta = (a[ai * WIDTH + k] ?? 0) - (b[bi * WIDTH + k] ?? 0);
|
|
277
|
+
if (delta !== 0) return delta;
|
|
278
|
+
}
|
|
279
|
+
return 0;
|
|
280
|
+
}
|
|
281
|
+
const size = (list) => list.length / WIDTH;
|
|
282
|
+
const hashCount = size;
|
|
283
|
+
const isStrictlyAscending = (list) => {
|
|
284
|
+
for (let i = 1; i < size(list); i += 1) if (compareAt(list, i - 1, list, i) >= 0) return false;
|
|
285
|
+
return true;
|
|
286
|
+
};
|
|
287
|
+
/**
|
|
288
|
+
* A base64 hash list, or `undefined` when it is not whole 8-byte hashes in strictly ascending
|
|
289
|
+
* order.
|
|
290
|
+
*/
|
|
291
|
+
function decodeHashList(encoded) {
|
|
292
|
+
let bytes;
|
|
293
|
+
try {
|
|
294
|
+
bytes = base64.decode(encoded);
|
|
295
|
+
} catch {
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
return bytes.length % WIDTH === 0 && isStrictlyAscending(bytes) ? bytes : void 0;
|
|
299
|
+
}
|
|
300
|
+
const RADIX = 256;
|
|
301
|
+
/** Indices of the `count` hashes in `flat`, ascending: an LSD radix sort, one pass per byte. */
|
|
302
|
+
function sortedOrder(flat, count) {
|
|
303
|
+
let order = new Uint32Array(count);
|
|
304
|
+
let scratch = new Uint32Array(count);
|
|
305
|
+
for (let i = 0; i < count; i += 1) order[i] = i;
|
|
306
|
+
const offsets = /* @__PURE__ */ new Uint32Array(257);
|
|
307
|
+
for (let byte = 7; byte >= 0; byte -= 1) {
|
|
308
|
+
offsets.fill(0);
|
|
309
|
+
for (let i = 0; i < count; i += 1) {
|
|
310
|
+
const slot = (flat[i * WIDTH + byte] ?? 0) + 1;
|
|
311
|
+
offsets[slot] = (offsets[slot] ?? 0) + 1;
|
|
312
|
+
}
|
|
313
|
+
for (let bucket = 0; bucket < RADIX; bucket += 1) offsets[bucket + 1] = (offsets[bucket + 1] ?? 0) + (offsets[bucket] ?? 0);
|
|
314
|
+
for (let i = 0; i < count; i += 1) {
|
|
315
|
+
const index = order[i] ?? 0;
|
|
316
|
+
const bucket = flat[index * WIDTH + byte] ?? 0;
|
|
317
|
+
scratch[offsets[bucket] ?? 0] = index;
|
|
318
|
+
offsets[bucket] = (offsets[bucket] ?? 0) + 1;
|
|
319
|
+
}
|
|
320
|
+
[order, scratch] = [scratch, order];
|
|
321
|
+
}
|
|
322
|
+
return order;
|
|
323
|
+
}
|
|
324
|
+
/** The sorted set of `hashes`, duplicates removed. */
|
|
325
|
+
function hashList(hashes) {
|
|
326
|
+
let flat = new Uint8Array(1024 * WIDTH);
|
|
327
|
+
let count = 0;
|
|
328
|
+
for (const hash of hashes) {
|
|
329
|
+
if ((count + 1) * WIDTH > flat.length) {
|
|
330
|
+
const grown = new Uint8Array(flat.length * 2);
|
|
331
|
+
grown.set(flat);
|
|
332
|
+
flat = grown;
|
|
333
|
+
}
|
|
334
|
+
flat.set(hash.subarray(0, WIDTH), count * WIDTH);
|
|
335
|
+
count += 1;
|
|
336
|
+
}
|
|
337
|
+
const order = sortedOrder(flat, count);
|
|
338
|
+
const out = new Uint8Array(count * WIDTH);
|
|
339
|
+
let written = 0;
|
|
340
|
+
for (let i = 0; i < count; i += 1) {
|
|
341
|
+
const at = (order[i] ?? 0) * WIDTH;
|
|
342
|
+
if (written === 0 || compareAt(out, written / WIDTH - 1, flat, at / WIDTH) !== 0) {
|
|
343
|
+
out.set(flat.subarray(at, at + WIDTH), written);
|
|
344
|
+
written += WIDTH;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
return out.slice(0, written);
|
|
348
|
+
}
|
|
349
|
+
const encodeHashList = (list) => base64.encode(list);
|
|
350
|
+
function contains(list, hash) {
|
|
351
|
+
let low = 0;
|
|
352
|
+
let high = size(list) - 1;
|
|
353
|
+
while (low <= high) {
|
|
354
|
+
const middle = Math.floor((low + high) / 2);
|
|
355
|
+
const order = compareAt(list, middle, hash, 0);
|
|
356
|
+
if (order === 0) return true;
|
|
357
|
+
if (order < 0) low = middle + 1;
|
|
358
|
+
else high = middle - 1;
|
|
359
|
+
}
|
|
360
|
+
return false;
|
|
361
|
+
}
|
|
362
|
+
function merge(a, b, keep) {
|
|
363
|
+
const out = new Uint8Array(a.length + b.length);
|
|
364
|
+
let written = 0;
|
|
365
|
+
const take = (source, index) => {
|
|
366
|
+
out.set(source.subarray(index * WIDTH, (index + 1) * WIDTH), written);
|
|
367
|
+
written += WIDTH;
|
|
368
|
+
};
|
|
369
|
+
let i = 0;
|
|
370
|
+
let j = 0;
|
|
371
|
+
while (i < size(a) || j < size(b)) {
|
|
372
|
+
const order = i >= size(a) ? 1 : j >= size(b) ? -1 : compareAt(a, i, b, j);
|
|
373
|
+
if (order < 0) {
|
|
374
|
+
if (keep(true, false)) take(a, i);
|
|
375
|
+
i += 1;
|
|
376
|
+
} else if (order > 0) {
|
|
377
|
+
if (keep(false, true)) take(b, j);
|
|
378
|
+
j += 1;
|
|
379
|
+
} else {
|
|
380
|
+
if (keep(true, true)) take(a, i);
|
|
381
|
+
i += 1;
|
|
382
|
+
j += 1;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
return out.slice(0, written);
|
|
386
|
+
}
|
|
387
|
+
const union = (a, b) => merge(a, b, () => true);
|
|
388
|
+
/** The hashes of `a` that are not in `b`. */
|
|
389
|
+
const difference = (a, b) => merge(a, b, (inA, inB) => inA && !inB);
|
|
390
|
+
/** `(list − remove) ∪ add`. */
|
|
391
|
+
const applyDiff = (list, add, remove) => union(difference(list, remove), add);
|
|
392
|
+
export { BITCOIN_NETWORKS, ESPLORA_ROUTES, EVM_RPC_METHODS, GATEWAY_ERRORS, INSTALL_ID_HEADER, NETWORKS, PHISHING_HASH_BYTES, PHISHING_MAX_PATH_SEGMENTS, PROVIDERS_HEADER, RPC_BATCH_MAX, SOLANA_NETWORKS, SOLANA_RPC_METHODS, accepts, applyDiff, caip2, contains, decodeHashList, difference, encodeHashList, endpoint, esploraBasePath, esploraGet, esploraPathAllowed, esploraPost, evmRpcRequest, gatewayError, hashCount, hashList, health, healthRequest, healthResponse, installId, jsonRpcId, jsonRpcResponse, networkById, networksPath, parseWith, phishingCandidates, phishingHash, phishingKey, phishingList, phishingListPath, phishingListRequest, phishingListResponse, rpc, rpcPath, rpcRequest, rpcResponse, servedNetworks, servedNetworksRequest, servedNetworksResponse, solanaRpcRequest, union };
|
|
182
393
|
|
|
183
394
|
//# sourceMappingURL=gateway-contract.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gateway-contract.mjs","names":[],"sources":["../src/gateway/contract/endpoint.ts","../src/gateway/contract/rpc.ts","../src/gateway/contract/primitives.ts","../src/gateway/contract/health.ts","../src/gateway/contract/esplora.ts","../src/gateway/contract/served.ts"],"sourcesContent":["import * as z from \"zod/mini\";\n\nexport type HttpMethod = \"GET\" | \"POST\" | \"DELETE\";\n\nexport type Endpoint<Req extends z.ZodMiniType, Res extends z.ZodMiniType> = {\n readonly method: HttpMethod;\n readonly path: string;\n readonly request: Req;\n readonly response: Res;\n};\n\n/** One gateway route: its verb, versioned path template, and request/response schemas. */\nexport function endpoint<Req extends z.ZodMiniType, Res extends z.ZodMiniType>(\n method: HttpMethod,\n path: `/v1/${string}`,\n request: Req,\n response: Res,\n): Endpoint<Req, Res> {\n return { method, path, request, response };\n}\n\n/** `value` typed by `schema`, or `undefined` when it does not satisfy it. */\nexport function parseWith<S extends z.ZodMiniType>(\n schema: S,\n value: unknown,\n): z.output<S> | undefined {\n const result = z.safeParse(schema, value);\n return result.success ? result.data : undefined;\n}\n\n/** Whether `value` satisfies `schema` — lets consumers validate without importing zod. */\nexport function accepts(schema: z.ZodMiniType, value: unknown): boolean {\n return z.safeParse(schema, value).success;\n}\n","import * as z from \"zod/mini\";\n\nimport { endpoint } from \"./endpoint.ts\";\n\n/** One JSON-RPC call plus nothing else: batches may carry at most this many entries. */\nexport const RPC_BATCH_MAX = 20;\n\n/** Read-only EVM methods plus `eth_sendRawTransaction`. Anything not listed is rejected. */\nexport const EVM_RPC_METHODS = [\n \"eth_blobBaseFee\",\n \"eth_blockNumber\",\n \"eth_call\",\n \"eth_chainId\",\n \"eth_createAccessList\",\n \"eth_estimateGas\",\n \"eth_feeHistory\",\n \"eth_gasPrice\",\n \"eth_getBalance\",\n \"eth_getBlockByHash\",\n \"eth_getBlockByNumber\",\n \"eth_getBlockReceipts\",\n \"eth_getBlockTransactionCountByHash\",\n \"eth_getBlockTransactionCountByNumber\",\n \"eth_getCode\",\n \"eth_getProof\",\n \"eth_getStorageAt\",\n \"eth_getTransactionByBlockHashAndIndex\",\n \"eth_getTransactionByBlockNumberAndIndex\",\n \"eth_getTransactionByHash\",\n \"eth_getTransactionCount\",\n \"eth_getTransactionReceipt\",\n \"eth_maxPriorityFeePerGas\",\n \"eth_sendRawTransaction\",\n \"net_version\",\n \"web3_clientVersion\",\n] as const;\n\n/** Read-only Solana methods plus `sendTransaction`. Anything not listed is rejected. */\nexport const SOLANA_RPC_METHODS = [\n \"getAccountInfo\",\n \"getBalance\",\n \"getBlock\",\n \"getBlockHeight\",\n \"getBlockTime\",\n \"getEpochInfo\",\n \"getFeeForMessage\",\n \"getGenesisHash\",\n \"getLatestBlockhash\",\n \"getMinimumBalanceForRentExemption\",\n \"getMultipleAccounts\",\n \"getRecentPrioritizationFees\",\n \"getSignatureStatuses\",\n \"getSignaturesForAddress\",\n \"getSlot\",\n \"getTokenAccountBalance\",\n \"getTokenAccountsByOwner\",\n \"getTokenSupply\",\n \"getTransaction\",\n \"getVersion\",\n \"isBlockhashValid\",\n \"sendTransaction\",\n \"simulateTransaction\",\n] as const;\n\nexport type EvmRpcMethod = (typeof EVM_RPC_METHODS)[number];\nexport type SolanaRpcMethod = (typeof SOLANA_RPC_METHODS)[number];\n\nexport const jsonRpcId = z.union([z.string(), z.number(), z.null()]);\n\nconst jsonRpcParams = z.optional(\n z.union([z.array(z.unknown()), z.record(z.string(), z.unknown())]),\n);\n\nconst callSchema = <M extends z.ZodMiniType<string>>(method: M) =>\n z.object({ jsonrpc: z.literal(\"2.0\"), id: jsonRpcId, method, params: jsonRpcParams });\n\nconst bodySchema = <C extends z.ZodMiniType>(call: C) =>\n z.union([call, z.array(call).check(z.minLength(1), z.maxLength(RPC_BATCH_MAX))]);\n\n/** Method-agnostic wire shape of a call or batch (the gateway narrows by family). */\nexport const rpcRequest = bodySchema(callSchema(z.string()));\n\nexport const evmRpcRequest = bodySchema(callSchema(z.enum(EVM_RPC_METHODS)));\nexport const solanaRpcRequest = bodySchema(callSchema(z.enum(SOLANA_RPC_METHODS)));\n\nconst successResponse = z.object({\n jsonrpc: z.literal(\"2.0\"),\n id: jsonRpcId,\n result: z.unknown(),\n});\nconst errorResponse = z.object({\n jsonrpc: z.literal(\"2.0\"),\n id: jsonRpcId,\n error: z.object({ code: z.int(), message: z.string(), data: z.optional(z.unknown()) }),\n});\n\nexport const jsonRpcResponse = z.union([successResponse, errorResponse]);\nexport const rpcResponse = z.union([jsonRpcResponse, z.array(jsonRpcResponse)]);\n\nexport const rpc = endpoint(\"POST\", \"/v1/rpc/:caip2\", rpcRequest, rpcResponse);\n\n/** The JSON-RPC URL path for one network. */\nexport const rpcPath = (caip2: string): string => rpc.path.replace(\":caip2\", caip2);\n","import * as z from \"zod/mini\";\n\nexport const INSTALL_ID_HEADER = \"x-install-id\";\nexport const PROVIDERS_HEADER = \"x-gateway-providers\";\n\n/** 128 random bits as lowercase hex — generated once per install, unrelated to wallet secrets. */\nexport const installId = z.string().check(z.regex(/^[0-9a-f]{32}$/));\n\n/** CAIP-2 chain id: `namespace:reference`. */\nexport const caip2 = z.string().check(z.regex(/^[-a-z0-9]{3,8}:[-_a-zA-Z0-9]{1,32}$/));\n\nexport type Caip2 = z.infer<typeof caip2>;\nexport type InstallId = z.infer<typeof installId>;\n\nexport const GATEWAY_ERRORS = [\n \"invalid-request\",\n \"unknown-network\",\n \"not-found\",\n \"rate-limited\",\n \"unavailable\",\n \"internal\",\n] as const;\n\nexport const gatewayError = z.object({ error: z.enum(GATEWAY_ERRORS) });\n\nexport type GatewayErrorCode = (typeof GATEWAY_ERRORS)[number];\n","import * as z from \"zod/mini\";\n\nimport { endpoint } from \"./endpoint.ts\";\n\nexport const healthRequest = z.undefined();\nexport const healthResponse = z.object({ status: z.literal(\"ok\") });\n\nexport const health = endpoint(\"GET\", \"/v1/health\", healthRequest, healthResponse);\n","import * as z from \"zod/mini\";\n\nimport { endpoint } from \"./endpoint.ts\";\n\nconst HEX64 = \"[0-9a-f]{64}\";\n\ntype EsploraRoute = { readonly method: \"GET\" | \"POST\"; readonly pattern: RegExp };\n\n/** The Esplora surface the engine uses; every other path is rejected. */\nexport const ESPLORA_ROUTES: ReadonlyArray<EsploraRoute> = [\n { method: \"GET\", pattern: /^\\/block-height\\/\\d{1,10}$/ },\n { method: \"GET\", pattern: /^\\/fee-estimates$/ },\n { method: \"GET\", pattern: new RegExp(`^/scripthash/${HEX64}/txs$`) },\n { method: \"GET\", pattern: new RegExp(`^/scripthash/${HEX64}/utxo$`) },\n { method: \"GET\", pattern: new RegExp(`^/tx/${HEX64}/hex$`) },\n { method: \"GET\", pattern: new RegExp(`^/tx/${HEX64}/status$`) },\n { method: \"POST\", pattern: /^\\/tx$/ },\n];\n\n/** `path` is the Esplora path after `/v1/esplora/:caip2`, with a leading slash and no query. */\nexport const esploraPathAllowed = (method: string, path: string): boolean =>\n ESPLORA_ROUTES.some((route) => route.method === method && route.pattern.test(path));\n\nexport const esploraGet = endpoint(\"GET\", \"/v1/esplora/:caip2/*\", z.undefined(), z.unknown());\n\n/** The Esplora base path for one network; allow-listed paths are appended to it. */\nexport const esploraBasePath = (caip2: string): string =>\n esploraGet.path.replace(\":caip2\", caip2).replace(/\\/\\*$/, \"\");\nexport const esploraPost = endpoint(\"POST\", \"/v1/esplora/:caip2/tx\", z.string(), z.string());\n","import * as z from \"zod/mini\";\n\nimport { endpoint } from \"./endpoint.ts\";\nimport { caip2 } from \"./primitives.ts\";\n\nexport const servedNetworksRequest = z.undefined();\n/** The networks the gateway actually serves, in its configured order. */\nexport const servedNetworksResponse = z.object({ networks: z.array(caip2) });\n\nexport const servedNetworks = endpoint(\n \"GET\",\n \"/v1/networks\",\n servedNetworksRequest,\n servedNetworksResponse,\n);\n\nexport const networksPath: string = servedNetworks.path;\n"],"mappings":";;;;AAYA,SAAgB,SACd,QACA,MACA,SACA,UACoB;CACpB,OAAO;EAAE;EAAQ;EAAM;EAAS;CAAS;AAC3C;;AAGA,SAAgB,UACd,QACA,OACyB;CACzB,MAAM,SAAS,EAAE,UAAU,QAAQ,KAAK;CACxC,OAAO,OAAO,UAAU,OAAO,OAAO,KAAA;AACxC;;AAGA,SAAgB,QAAQ,QAAuB,OAAyB;CACtE,OAAO,EAAE,UAAU,QAAQ,KAAK,CAAC,CAAC;AACpC;;;AC5BA,MAAa,gBAAgB;;AAG7B,MAAa,kBAAkB;CAC7B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAa,qBAAqB;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;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AU,KAAK,CAAC,CAAC,QAAQ,SAAS,EAAE;AAC9D,MAAa,cAAc,SAAS,QAAQ,yBAAyB,EAAE,OAAO,GAAG,EAAE,OAAO,CAAC;;ACvB3F,MAAa,wBAAwB,EAAE,UAAU;;AAEjD,MAAa,yBAAyB,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,KAAK,EAAE,CAAC;AAE3E,MAAa,iBAAiB,SAC5B,OACA,gBACA,uBACA,sBACF;AAEA,MAAa,eAAuB,eAAe"}
|
|
1
|
+
{"version":3,"file":"gateway-contract.mjs","names":[],"sources":["../src/gateway/contract/endpoint.ts","../src/gateway/contract/rpc.ts","../src/gateway/contract/primitives.ts","../src/gateway/contract/health.ts","../src/gateway/contract/esplora.ts","../src/gateway/contract/served.ts","../src/gateway/contract/risk.ts","../src/gateway/contract/hash-list.ts"],"sourcesContent":["import * as z from \"zod/mini\";\n\nexport type HttpMethod = \"GET\" | \"POST\" | \"DELETE\";\n\nexport type Endpoint<Req extends z.ZodMiniType, Res extends z.ZodMiniType> = {\n readonly method: HttpMethod;\n readonly path: string;\n readonly request: Req;\n readonly response: Res;\n};\n\n/** One gateway route: its verb, versioned path template, and request/response schemas. */\nexport function endpoint<Req extends z.ZodMiniType, Res extends z.ZodMiniType>(\n method: HttpMethod,\n path: `/v1/${string}`,\n request: Req,\n response: Res,\n): Endpoint<Req, Res> {\n return { method, path, request, response };\n}\n\n/** `value` typed by `schema`, or `undefined` when it does not satisfy it. */\nexport function parseWith<S extends z.ZodMiniType>(\n schema: S,\n value: unknown,\n): z.output<S> | undefined {\n const result = z.safeParse(schema, value);\n return result.success ? result.data : undefined;\n}\n\n/** Whether `value` satisfies `schema` — lets consumers validate without importing zod. */\nexport function accepts(schema: z.ZodMiniType, value: unknown): boolean {\n return z.safeParse(schema, value).success;\n}\n","import * as z from \"zod/mini\";\n\nimport { endpoint } from \"./endpoint.ts\";\n\n/** One JSON-RPC call plus nothing else: batches may carry at most this many entries. */\nexport const RPC_BATCH_MAX = 20;\n\n/** Read-only EVM methods plus `eth_sendRawTransaction`. Anything not listed is rejected. */\nexport const EVM_RPC_METHODS = [\n \"eth_blobBaseFee\",\n \"eth_blockNumber\",\n \"eth_call\",\n \"eth_chainId\",\n \"eth_createAccessList\",\n \"eth_estimateGas\",\n \"eth_feeHistory\",\n \"eth_gasPrice\",\n \"eth_getBalance\",\n \"eth_getBlockByHash\",\n \"eth_getBlockByNumber\",\n \"eth_getBlockReceipts\",\n \"eth_getBlockTransactionCountByHash\",\n \"eth_getBlockTransactionCountByNumber\",\n \"eth_getCode\",\n \"eth_getProof\",\n \"eth_getStorageAt\",\n \"eth_getTransactionByBlockHashAndIndex\",\n \"eth_getTransactionByBlockNumberAndIndex\",\n \"eth_getTransactionByHash\",\n \"eth_getTransactionCount\",\n \"eth_getTransactionReceipt\",\n \"eth_maxPriorityFeePerGas\",\n \"eth_sendRawTransaction\",\n \"eth_simulateV1\",\n \"net_version\",\n \"web3_clientVersion\",\n] as const;\n\n/** Read-only Solana methods plus `sendTransaction`. Anything not listed is rejected. */\nexport const SOLANA_RPC_METHODS = [\n \"getAccountInfo\",\n \"getBalance\",\n \"getBlock\",\n \"getBlockHeight\",\n \"getBlockTime\",\n \"getEpochInfo\",\n \"getFeeForMessage\",\n \"getGenesisHash\",\n \"getLatestBlockhash\",\n \"getMinimumBalanceForRentExemption\",\n \"getMultipleAccounts\",\n \"getRecentPrioritizationFees\",\n \"getSignatureStatuses\",\n \"getSignaturesForAddress\",\n \"getSlot\",\n \"getTokenAccountBalance\",\n \"getTokenAccountsByOwner\",\n \"getTokenSupply\",\n \"getTransaction\",\n \"getVersion\",\n \"isBlockhashValid\",\n \"sendTransaction\",\n \"simulateTransaction\",\n] as const;\n\nexport type EvmRpcMethod = (typeof EVM_RPC_METHODS)[number];\nexport type SolanaRpcMethod = (typeof SOLANA_RPC_METHODS)[number];\n\nexport const jsonRpcId = z.union([z.string(), z.number(), z.null()]);\n\nconst jsonRpcParams = z.optional(\n z.union([z.array(z.unknown()), z.record(z.string(), z.unknown())]),\n);\n\nconst callSchema = <M extends z.ZodMiniType<string>>(method: M) =>\n z.object({ jsonrpc: z.literal(\"2.0\"), id: jsonRpcId, method, params: jsonRpcParams });\n\nconst bodySchema = <C extends z.ZodMiniType>(call: C) =>\n z.union([call, z.array(call).check(z.minLength(1), z.maxLength(RPC_BATCH_MAX))]);\n\n/** Method-agnostic wire shape of a call or batch (the gateway narrows by family). */\nexport const rpcRequest = bodySchema(callSchema(z.string()));\n\nexport const evmRpcRequest = bodySchema(callSchema(z.enum(EVM_RPC_METHODS)));\nexport const solanaRpcRequest = bodySchema(callSchema(z.enum(SOLANA_RPC_METHODS)));\n\nconst successResponse = z.object({\n jsonrpc: z.literal(\"2.0\"),\n id: jsonRpcId,\n result: z.unknown(),\n});\nconst errorResponse = z.object({\n jsonrpc: z.literal(\"2.0\"),\n id: jsonRpcId,\n error: z.object({ code: z.int(), message: z.string(), data: z.optional(z.unknown()) }),\n});\n\nexport const jsonRpcResponse = z.union([successResponse, errorResponse]);\nexport const rpcResponse = z.union([jsonRpcResponse, z.array(jsonRpcResponse)]);\n\nexport const rpc = endpoint(\"POST\", \"/v1/rpc/:caip2\", rpcRequest, rpcResponse);\n\n/** The JSON-RPC URL path for one network. */\nexport const rpcPath = (caip2: string): string => rpc.path.replace(\":caip2\", caip2);\n","import * as z from \"zod/mini\";\n\nexport const INSTALL_ID_HEADER = \"x-install-id\";\nexport const PROVIDERS_HEADER = \"x-gateway-providers\";\n\n/** 128 random bits as lowercase hex — generated once per install, unrelated to wallet secrets. */\nexport const installId = z.string().check(z.regex(/^[0-9a-f]{32}$/));\n\n/** CAIP-2 chain id: `namespace:reference`. */\nexport const caip2 = z.string().check(z.regex(/^[-a-z0-9]{3,8}:[-_a-zA-Z0-9]{1,32}$/));\n\nexport type Caip2 = z.infer<typeof caip2>;\nexport type InstallId = z.infer<typeof installId>;\n\nexport const GATEWAY_ERRORS = [\n \"invalid-request\",\n \"unknown-network\",\n \"not-found\",\n \"rate-limited\",\n \"unavailable\",\n \"internal\",\n] as const;\n\nexport const gatewayError = z.object({ error: z.enum(GATEWAY_ERRORS) });\n\nexport type GatewayErrorCode = (typeof GATEWAY_ERRORS)[number];\n","import * as z from \"zod/mini\";\n\nimport { endpoint } from \"./endpoint.ts\";\n\nexport const healthRequest = z.undefined();\nexport const healthResponse = z.object({ status: z.literal(\"ok\") });\n\nexport const health = endpoint(\"GET\", \"/v1/health\", healthRequest, healthResponse);\n","import * as z from \"zod/mini\";\n\nimport { endpoint } from \"./endpoint.ts\";\n\nconst HEX64 = \"[0-9a-f]{64}\";\n\ntype EsploraRoute = { readonly method: \"GET\" | \"POST\"; readonly pattern: RegExp };\n\n/** The Esplora surface the engine uses; every other path is rejected. */\nexport const ESPLORA_ROUTES: ReadonlyArray<EsploraRoute> = [\n { method: \"GET\", pattern: /^\\/block-height\\/\\d{1,10}$/ },\n { method: \"GET\", pattern: /^\\/fee-estimates$/ },\n { method: \"GET\", pattern: new RegExp(`^/scripthash/${HEX64}/txs$`) },\n { method: \"GET\", pattern: new RegExp(`^/scripthash/${HEX64}/utxo$`) },\n { method: \"GET\", pattern: new RegExp(`^/tx/${HEX64}/hex$`) },\n { method: \"GET\", pattern: new RegExp(`^/tx/${HEX64}/status$`) },\n { method: \"POST\", pattern: /^\\/tx$/ },\n];\n\n/** `path` is the Esplora path after `/v1/esplora/:caip2`, with a leading slash and no query. */\nexport const esploraPathAllowed = (method: string, path: string): boolean =>\n ESPLORA_ROUTES.some((route) => route.method === method && route.pattern.test(path));\n\nexport const esploraGet = endpoint(\"GET\", \"/v1/esplora/:caip2/*\", z.undefined(), z.unknown());\n\n/** The Esplora base path for one network; allow-listed paths are appended to it. */\nexport const esploraBasePath = (caip2: string): string =>\n esploraGet.path.replace(\":caip2\", caip2).replace(/\\/\\*$/, \"\");\nexport const esploraPost = endpoint(\"POST\", \"/v1/esplora/:caip2/tx\", z.string(), z.string());\n","import * as z from \"zod/mini\";\n\nimport { endpoint } from \"./endpoint.ts\";\nimport { caip2 } from \"./primitives.ts\";\n\nexport const servedNetworksRequest = z.undefined();\n/** The networks the gateway actually serves, in its configured order. */\nexport const servedNetworksResponse = z.object({ networks: z.array(caip2) });\n\nexport const servedNetworks = endpoint(\n \"GET\",\n \"/v1/networks\",\n servedNetworksRequest,\n servedNetworksResponse,\n);\n\nexport const networksPath: string = servedNetworks.path;\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { utf8ToBytes } from \"@noble/hashes/utils.js\";\nimport * as z from \"zod/mini\";\n\nimport { endpoint } from \"./endpoint.ts\";\n\nexport const PHISHING_HASH_BYTES = 8;\nexport const PHISHING_MAX_PATH_SEGMENTS = 8;\n\nconst MAX_HOST_LENGTH = 253;\nconst MIN_HOST_LABELS = 2;\nconst FORBIDDEN_ENTRY = /:\\/\\/|[?#@\\\\\\s]/;\nconst IPV4 = /^\\d{1,3}(?:\\.\\d{1,3}){3}$/;\n/** Lowercase ASCII labels ending in a non-numeric label: `new URL` returns such a host unchanged. */\nconst PLAIN_HOST = /^(?:[a-z0-9_-]+\\.)+[a-z][a-z0-9_-]*\\.?$/;\n\nconst trimTrailingDot = (host: string): string => (host.endsWith(\".\") ? host.slice(0, -1) : host);\n\nconst pathSegments = (pathname: string): ReadonlyArray<string> =>\n pathname.split(\"/\").filter((segment) => segment !== \"\");\n\n/** One list entry as its lookup key, or `undefined` when the entry is not a usable host or path. */\nexport function phishingKey(entry: string): string | undefined {\n if (PLAIN_HOST.test(entry) && !entry.includes(\"xn--\")) {\n const host = trimTrailingDot(entry);\n return host.length > MAX_HOST_LENGTH ? undefined : host;\n }\n let raw = entry.trim();\n if (raw.startsWith(\"*.\")) {\n raw = raw.slice(2);\n }\n if (raw === \"\" || FORBIDDEN_ENTRY.test(raw)) {\n return undefined;\n }\n let url: URL;\n try {\n url = new URL(`https://${raw}`);\n } catch {\n return undefined;\n }\n if ((raw.split(\"/\")[0] ?? \"\").includes(\":\")) {\n return undefined;\n }\n const host = trimTrailingDot(url.hostname.toLowerCase());\n const labels = host.split(\".\");\n if (\n host.length > MAX_HOST_LENGTH ||\n labels.length < MIN_HOST_LABELS ||\n labels.some((label) => label === \"\")\n ) {\n return undefined;\n }\n const segments = pathSegments(url.pathname);\n if (segments.length === 0) {\n return host;\n }\n if (segments.length > PHISHING_MAX_PATH_SEGMENTS) {\n return undefined;\n }\n return `${host}/${segments.join(\"/\")}`;\n}\n\n/** The first 8 bytes of SHA-256 over the UTF-8 key. */\nexport function phishingHash(key: string): Uint8Array {\n return sha256(utf8ToBytes(key)).slice(0, PHISHING_HASH_BYTES);\n}\n\n/** Lookup keys for a page URL, most specific first; empty for anything but http(s). */\nexport function phishingCandidates(url: string): ReadonlyArray<string> {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return [];\n }\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n return [];\n }\n const host = trimTrailingDot(parsed.hostname);\n if (host === \"\") {\n return [];\n }\n if (host.startsWith(\"[\") || IPV4.test(host)) {\n return [host];\n }\n const segments = pathSegments(parsed.pathname).slice(0, PHISHING_MAX_PATH_SEGMENTS);\n const candidates: string[] = [];\n for (let depth = segments.length; depth > 0; depth -= 1) {\n candidates.push(`${host}/${segments.slice(0, depth).join(\"/\")}`);\n }\n const labels = host.split(\".\");\n for (let start = 0; labels.length - start >= MIN_HOST_LABELS; start += 1) {\n candidates.push(labels.slice(start).join(\".\"));\n }\n return candidates;\n}\n\nconst version = z.number().check(z.int(), z.nonnegative());\n\n/** Concatenated sorted 8-byte hashes, standard-alphabet base64; the empty string is an empty set. */\nconst hashes = z\n .string()\n .check(z.regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/));\n\nconst delta = z.object({ add: hashes, remove: hashes });\n\nexport const phishingListRequest = z.object({\n since: z.optional(z.string().check(z.regex(/^\\d{1,15}$/))),\n});\n\nexport const phishingListResponse = z.discriminatedUnion(\"kind\", [\n z.object({ kind: z.literal(\"current\"), version }),\n z.object({\n kind: z.literal(\"diff\"),\n from: version,\n version,\n deny: delta,\n allow: delta,\n }),\n z.object({ kind: z.literal(\"snapshot\"), version, deny: hashes, allow: hashes }),\n]);\n\nexport type PhishingListResponse = z.infer<typeof phishingListResponse>;\n\nexport const phishingList = endpoint(\n \"GET\",\n \"/v1/risk/lists/phishing\",\n phishingListRequest,\n phishingListResponse,\n);\n\nexport const phishingListPath: string = phishingList.path;\n","import { base64 } from \"@scure/base\";\n\nimport { PHISHING_HASH_BYTES } from \"./risk.ts\";\n\n/** Strictly ascending 8-byte hashes, concatenated: a sorted set. */\nexport type HashList = Uint8Array;\n\nconst WIDTH = PHISHING_HASH_BYTES;\n\nfunction compareAt(a: Uint8Array, ai: number, b: Uint8Array, bi: number): number {\n for (let k = 0; k < WIDTH; k += 1) {\n const delta = (a[ai * WIDTH + k] ?? 0) - (b[bi * WIDTH + k] ?? 0);\n if (delta !== 0) {\n return delta;\n }\n }\n return 0;\n}\n\nconst size = (list: HashList): number => list.length / WIDTH;\n\nexport const hashCount = size;\n\nconst isStrictlyAscending = (list: HashList): boolean => {\n for (let i = 1; i < size(list); i += 1) {\n if (compareAt(list, i - 1, list, i) >= 0) {\n return false;\n }\n }\n return true;\n};\n\n/**\n * A base64 hash list, or `undefined` when it is not whole 8-byte hashes in strictly ascending\n * order.\n */\nexport function decodeHashList(encoded: string): HashList | undefined {\n let bytes: Uint8Array;\n try {\n bytes = base64.decode(encoded);\n } catch {\n return undefined;\n }\n return bytes.length % WIDTH === 0 && isStrictlyAscending(bytes) ? bytes : undefined;\n}\n\nconst RADIX = 256;\n\n/** Indices of the `count` hashes in `flat`, ascending: an LSD radix sort, one pass per byte. */\nfunction sortedOrder(flat: Uint8Array, count: number): Uint32Array {\n let order = new Uint32Array(count);\n let scratch = new Uint32Array(count);\n for (let i = 0; i < count; i += 1) {\n order[i] = i;\n }\n const offsets = new Uint32Array(RADIX + 1);\n for (let byte = WIDTH - 1; byte >= 0; byte -= 1) {\n offsets.fill(0);\n for (let i = 0; i < count; i += 1) {\n const slot = (flat[i * WIDTH + byte] ?? 0) + 1;\n offsets[slot] = (offsets[slot] ?? 0) + 1;\n }\n for (let bucket = 0; bucket < RADIX; bucket += 1) {\n offsets[bucket + 1] = (offsets[bucket + 1] ?? 0) + (offsets[bucket] ?? 0);\n }\n for (let i = 0; i < count; i += 1) {\n const index = order[i] ?? 0;\n const bucket = flat[index * WIDTH + byte] ?? 0;\n scratch[offsets[bucket] ?? 0] = index;\n offsets[bucket] = (offsets[bucket] ?? 0) + 1;\n }\n [order, scratch] = [scratch, order];\n }\n return order;\n}\n\n/** The sorted set of `hashes`, duplicates removed. */\nexport function hashList(hashes: Iterable<Uint8Array>): HashList {\n let flat = new Uint8Array(1024 * WIDTH);\n let count = 0;\n for (const hash of hashes) {\n if ((count + 1) * WIDTH > flat.length) {\n const grown = new Uint8Array(flat.length * 2);\n grown.set(flat);\n flat = grown;\n }\n flat.set(hash.subarray(0, WIDTH), count * WIDTH);\n count += 1;\n }\n const order = sortedOrder(flat, count);\n const out = new Uint8Array(count * WIDTH);\n let written = 0;\n for (let i = 0; i < count; i += 1) {\n const at = (order[i] ?? 0) * WIDTH;\n if (written === 0 || compareAt(out, written / WIDTH - 1, flat, at / WIDTH) !== 0) {\n out.set(flat.subarray(at, at + WIDTH), written);\n written += WIDTH;\n }\n }\n return out.slice(0, written);\n}\n\nexport const encodeHashList = (list: HashList): string => base64.encode(list);\n\nexport function contains(list: HashList, hash: Uint8Array): boolean {\n let low = 0;\n let high = size(list) - 1;\n while (low <= high) {\n const middle = Math.floor((low + high) / 2);\n const order = compareAt(list, middle, hash, 0);\n if (order === 0) {\n return true;\n }\n if (order < 0) {\n low = middle + 1;\n } else {\n high = middle - 1;\n }\n }\n return false;\n}\n\nfunction merge(a: HashList, b: HashList, keep: (inA: boolean, inB: boolean) => boolean): HashList {\n const out = new Uint8Array(a.length + b.length);\n let written = 0;\n const take = (source: Uint8Array, index: number): void => {\n out.set(source.subarray(index * WIDTH, (index + 1) * WIDTH), written);\n written += WIDTH;\n };\n let i = 0;\n let j = 0;\n while (i < size(a) || j < size(b)) {\n const order = i >= size(a) ? 1 : j >= size(b) ? -1 : compareAt(a, i, b, j);\n if (order < 0) {\n if (keep(true, false)) {\n take(a, i);\n }\n i += 1;\n } else if (order > 0) {\n if (keep(false, true)) {\n take(b, j);\n }\n j += 1;\n } else {\n if (keep(true, true)) {\n take(a, i);\n }\n i += 1;\n j += 1;\n }\n }\n return out.slice(0, written);\n}\n\nexport const union = (a: HashList, b: HashList): HashList => merge(a, b, () => true);\n\n/** The hashes of `a` that are not in `b`. */\nexport const difference = (a: HashList, b: HashList): HashList =>\n merge(a, b, (inA, inB) => inA && !inB);\n\n/** `(list − remove) ∪ add`. */\nexport const applyDiff = (list: HashList, add: HashList, remove: HashList): HashList =>\n union(difference(list, remove), add);\n"],"mappings":";;;;;;;AAYA,SAAgB,SACd,QACA,MACA,SACA,UACoB;CACpB,OAAO;EAAE;EAAQ;EAAM;EAAS;CAAS;AAC3C;;AAGA,SAAgB,UACd,QACA,OACyB;CACzB,MAAM,SAAS,EAAE,UAAU,QAAQ,KAAK;CACxC,OAAO,OAAO,UAAU,OAAO,OAAO,KAAA;AACxC;;AAGA,SAAgB,QAAQ,QAAuB,OAAyB;CACtE,OAAO,EAAE,UAAU,QAAQ,KAAK,CAAC,CAAC;AACpC;;;AC5BA,MAAa,gBAAgB;;AAG7B,MAAa,kBAAkB;CAC7B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAa,qBAAqB;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAKA,MAAa,YAAY,EAAE,MAAM;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GACpB,IAAI,KAAK,OAAO,IAAI,GAClB,KAAK,GAAG,CAAC;GAEX,KAAK;EACP,OAAO;GACL,IAAI,KAAK,MAAM,IAAI,GACjB,KAAK,GAAG,CAAC;GAEX,KAAK;GACL,KAAK;EACP;CACF;CACA,OAAO,IAAI,MAAM,GAAG,OAAO;AAC7B;AAEA,MAAa,SAAS,GAAa,MAA0B,MAAM,GAAG,SAAS,IAAI;;AAGnF,MAAa,cAAc,GAAa,MACtC,MAAM,GAAG,IAAI,KAAK,QAAQ,OAAO,CAAC,GAAG;;AAGvC,MAAa,aAAa,MAAgB,KAAe,WACvD,MAAM,WAAW,MAAM,MAAM,GAAG,GAAG"}
|
package/dist/idb.d.mts
CHANGED
|
@@ -13,6 +13,19 @@ type EngineStore = {
|
|
|
13
13
|
readonly collection: (name: string) => EngineCollection;
|
|
14
14
|
readonly close: () => Promise<void>;
|
|
15
15
|
};
|
|
16
|
+
/**
|
|
17
|
+
* Non-secret device data (the phishing list, the origins the user trusts): available while the
|
|
18
|
+
* wallet is locked, and the host may keep it unencrypted. Never put anything secret in it.
|
|
19
|
+
*/
|
|
20
|
+
type PublicStore = {
|
|
21
|
+
readonly get: (key: string) => Promise<Uint8Array | undefined>;
|
|
22
|
+
readonly put: (key: string, bytes: Uint8Array) => Promise<void>;
|
|
23
|
+
};
|
|
24
|
+
type IndexedDbPublicStoreOptions = {
|
|
25
|
+
readonly name: string;
|
|
26
|
+
};
|
|
27
|
+
/** An unencrypted IndexedDB PublicStore: one database, one `records` object store. */
|
|
28
|
+
export declare function openIndexedDbPublicStore(options: IndexedDbPublicStoreOptions): Promise<PublicStore>;
|
|
16
29
|
export type Random = (length: number) => Uint8Array;
|
|
17
30
|
export type IndexedDbEngineStoreOptions = {
|
|
18
31
|
readonly name: string;
|
|
@@ -20,5 +33,5 @@ export type IndexedDbEngineStoreOptions = {
|
|
|
20
33
|
readonly random: Random;
|
|
21
34
|
};
|
|
22
35
|
export declare function openIndexedDbEngineStore(options: IndexedDbEngineStoreOptions): Promise<EngineStore>;
|
|
23
|
-
export {};
|
|
36
|
+
export type { IndexedDbPublicStoreOptions };
|
|
24
37
|
//# sourceMappingURL=idb.d.mts.map
|
package/dist/idb.mjs
CHANGED
|
@@ -14,17 +14,7 @@ var EngineStoreError = class extends Error {
|
|
|
14
14
|
function checkName(kind, value) {
|
|
15
15
|
if (value.includes("\0")) throw new EngineStoreError("invalid-input", `${kind} must not contain NUL`);
|
|
16
16
|
}
|
|
17
|
-
// src/idb/
|
|
18
|
-
/**
|
|
19
|
-
* The Web EngineStore: one IndexedDB database, one `records` object store, values encrypted per
|
|
20
|
-
* record with XChaCha20-Poly1305. Key = the injected 32-byte data key; nonce = 24 random bytes
|
|
21
|
-
* stored as nonce‖ciphertext; AAD = UTF-8 `<collection>\0<key>` — moving a record to another key or
|
|
22
|
-
* collection fails the MAC, same as a tampered payload. `close()` drops the connection, wipes the
|
|
23
|
-
* module-held key copy and latches every call to `closed`.
|
|
24
|
-
*/
|
|
25
|
-
const STORE = "records";
|
|
26
|
-
const id = (collection, recordKey) => `${collection}\u0000${recordKey}`;
|
|
27
|
-
const aad = (collection, recordKey) => new TextEncoder().encode(`${collection}\u0000${recordKey}`);
|
|
17
|
+
// src/idb/requests.ts
|
|
28
18
|
async function request(req) {
|
|
29
19
|
return new Promise((resolve, reject) => {
|
|
30
20
|
req.addEventListener("success", () => {
|
|
@@ -48,6 +38,47 @@ async function done(tx) {
|
|
|
48
38
|
});
|
|
49
39
|
});
|
|
50
40
|
}
|
|
41
|
+
// src/idb/public-store.ts
|
|
42
|
+
const STORE$1 = "records";
|
|
43
|
+
/** An unencrypted IndexedDB PublicStore: one database, one `records` object store. */
|
|
44
|
+
async function openIndexedDbPublicStore(options) {
|
|
45
|
+
const db = await new Promise((resolve, reject) => {
|
|
46
|
+
const open = indexedDB.open(options.name, 1);
|
|
47
|
+
open.addEventListener("upgradeneeded", () => {
|
|
48
|
+
open.result.createObjectStore(STORE$1);
|
|
49
|
+
});
|
|
50
|
+
open.addEventListener("success", () => {
|
|
51
|
+
resolve(open.result);
|
|
52
|
+
});
|
|
53
|
+
open.addEventListener("error", () => {
|
|
54
|
+
reject(new Error("indexeddb open failed", { cause: open.error }));
|
|
55
|
+
});
|
|
56
|
+
});
|
|
57
|
+
return {
|
|
58
|
+
get: async (key) => {
|
|
59
|
+
checkName("key", key);
|
|
60
|
+
const value = await request(db.transaction(STORE$1, "readonly").objectStore(STORE$1).get(key));
|
|
61
|
+
return value === void 0 ? void 0 : new Uint8Array(value);
|
|
62
|
+
},
|
|
63
|
+
put: async (key, bytes) => {
|
|
64
|
+
checkName("key", key);
|
|
65
|
+
const tx = db.transaction(STORE$1, "readwrite");
|
|
66
|
+
tx.objectStore(STORE$1).put(new Uint8Array(bytes), key);
|
|
67
|
+
await done(tx);
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
// src/idb/indexeddb.ts
|
|
72
|
+
/**
|
|
73
|
+
* The Web EngineStore: one IndexedDB database, one `records` object store, values encrypted per
|
|
74
|
+
* record with XChaCha20-Poly1305. Key = the injected 32-byte data key; nonce = 24 random bytes
|
|
75
|
+
* stored as nonce‖ciphertext; AAD = UTF-8 `<collection>\0<key>` — moving a record to another key or
|
|
76
|
+
* collection fails the MAC, same as a tampered payload. `close()` drops the connection, wipes the
|
|
77
|
+
* module-held key copy and latches every call to `closed`.
|
|
78
|
+
*/
|
|
79
|
+
const STORE = "records";
|
|
80
|
+
const id = (collection, recordKey) => `${collection}\u0000${recordKey}`;
|
|
81
|
+
const aad = (collection, recordKey) => new TextEncoder().encode(`${collection}\u0000${recordKey}`);
|
|
51
82
|
async function openIndexedDbEngineStore(options) {
|
|
52
83
|
const key = new Uint8Array(options.dataKey);
|
|
53
84
|
return new Promise((resolve, reject) => {
|
|
@@ -126,6 +157,6 @@ function makeStore(db, key, random) {
|
|
|
126
157
|
}
|
|
127
158
|
};
|
|
128
159
|
}
|
|
129
|
-
export { openIndexedDbEngineStore };
|
|
160
|
+
export { openIndexedDbEngineStore, openIndexedDbPublicStore };
|
|
130
161
|
|
|
131
162
|
//# sourceMappingURL=idb.mjs.map
|
package/dist/idb.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"idb.mjs","names":[],"sources":["../src/errors.ts","../src/store/guard.ts","../src/idb/indexeddb.ts"],"sourcesContent":["export type EngineErrorCode = \"closed\" | \"integrity\" | \"invalid-input\";\n\n/** Typed engine errors: store codes are `closed` and `integrity` (decrypt or bind failure). */\nexport class EngineStoreError extends Error {\n readonly code: EngineErrorCode;\n\n constructor(code: EngineErrorCode, message: string) {\n super(message);\n this.name = \"EngineStoreError\";\n this.code = code;\n }\n}\n","import { EngineStoreError } from \"../errors.ts\";\n\n/** NUL is the composite-key/AAD separator — a name or key containing it collides. */\nexport function checkName(kind: \"collection\" | \"key\", value: string): void {\n if (value.includes(\"\\u0000\")) {\n throw new EngineStoreError(\"invalid-input\", `${kind} must not contain NUL`);\n }\n}\n","/**\n * The Web EngineStore: one IndexedDB database, one `records` object store, values encrypted per\n * record with XChaCha20-Poly1305. Key = the injected 32-byte data key; nonce = 24 random bytes\n * stored as nonce‖ciphertext; AAD = UTF-8 `<collection>\\0<key>` — moving a record to another key or\n * collection fails the MAC, same as a tampered payload. `close()` drops the connection, wipes the\n * module-held key copy and latches every call to `closed`.\n */\nimport { xchacha20poly1305 } from \"@noble/ciphers/chacha.js\";\n\nimport { EngineStoreError } from \"../errors.ts\";\nimport { checkName } from \"../store/guard.ts\";\nimport type { EngineCollection, EngineStore } from \"../store/port.ts\";\n\nexport type Random = (length: number) => Uint8Array;\n\nexport type IndexedDbEngineStoreOptions = {\n readonly name: string;\n readonly dataKey: Uint8Array;\n readonly random: Random;\n};\n\nconst STORE = \"records\";\n\nconst id = (collection: string, recordKey: string): string => `${collection}\\u0000${recordKey}`;\nconst aad = (collection: string, recordKey: string): Uint8Array =>\n new TextEncoder().encode(`${collection}\\u0000${recordKey}`);\n\nasync function request<T>(req: IDBRequest<T>): Promise<T> {\n return new Promise((resolve, reject) => {\n req.addEventListener(\"success\", () => {\n resolve(req.result);\n });\n req.addEventListener(\"error\", () => {\n reject(new Error(\"indexeddb request failed\", { cause: req.error }));\n });\n });\n}\n\nasync function done(tx: IDBTransaction): Promise<void> {\n return new Promise((resolve, reject) => {\n tx.addEventListener(\"complete\", () => {\n resolve();\n });\n tx.addEventListener(\"error\", () => {\n reject(new Error(\"indexeddb transaction failed\", { cause: tx.error }));\n });\n tx.addEventListener(\"abort\", () => {\n reject(new Error(\"indexeddb transaction aborted\", { cause: tx.error }));\n });\n });\n}\n\nexport async function openIndexedDbEngineStore(\n options: IndexedDbEngineStoreOptions,\n): Promise<EngineStore> {\n const key = new Uint8Array(options.dataKey);\n return new Promise<EngineStore>((resolve, reject) => {\n const open = indexedDB.open(options.name, 1);\n open.addEventListener(\"upgradeneeded\", () => {\n open.result.createObjectStore(STORE);\n });\n open.addEventListener(\"success\", () => {\n resolve(makeStore(open.result, key, options.random));\n });\n open.addEventListener(\"error\", () => {\n key.fill(0);\n reject(new Error(\"indexeddb open failed\", { cause: open.error }));\n });\n });\n}\n\nfunction makeStore(db: IDBDatabase, key: Uint8Array, random: Random): EngineStore {\n let closed = false;\n\n const guard = (): IDBDatabase => {\n if (closed) {\n throw new EngineStoreError(\"closed\", \"engine store is closed\");\n }\n return db;\n };\n\n const seal = (collection: string, recordKey: string, bytes: Uint8Array): Uint8Array => {\n const nonce = random(24);\n const ciphertext = xchacha20poly1305(key, nonce, aad(collection, recordKey)).encrypt(bytes);\n const record = new Uint8Array(24 + ciphertext.length);\n record.set(nonce, 0);\n record.set(ciphertext, 24);\n return record;\n };\n\n const open = (collection: string, recordKey: string, record: Uint8Array): Uint8Array => {\n if (record.length < 24) {\n throw new EngineStoreError(\"integrity\", \"engine record too short\");\n }\n try {\n return xchacha20poly1305(key, record.slice(0, 24), aad(collection, recordKey)).decrypt(\n record.slice(24),\n );\n } catch {\n throw new EngineStoreError(\"integrity\", \"engine record failed integrity\");\n }\n };\n\n const make = (name: string): EngineCollection => ({\n get: async (recordKey) => {\n const database = guard();\n checkName(\"key\", recordKey);\n const tx = database.transaction(STORE, \"readonly\");\n const raw = tx.objectStore(STORE).get(id(name, recordKey));\n // oxlint-disable-next-line typescript/no-unsafe-argument -- IDB get() is any-typed by spec\n const record = await request<Uint8Array | undefined>(raw);\n return record === undefined ? undefined : open(name, recordKey, record);\n },\n put: async (recordKey, bytes) => {\n const database = guard();\n checkName(\"key\", recordKey);\n const tx = database.transaction(STORE, \"readwrite\");\n tx.objectStore(STORE).put(seal(name, recordKey, bytes), id(name, recordKey));\n await done(tx);\n },\n delete: async (recordKey) => {\n const database = guard();\n checkName(\"key\", recordKey);\n const tx = database.transaction(STORE, \"readwrite\");\n tx.objectStore(STORE).delete(id(name, recordKey));\n await done(tx);\n },\n list: async () => {\n const database = guard();\n const tx = database.transaction(STORE, \"readonly\");\n const all = tx.objectStore(STORE).getAllKeys();\n const keys = await request<IDBValidKey[]>(all);\n const prefix = `${name}\\u0000`;\n return keys\n .filter((k): k is string => typeof k === \"string\" && k.startsWith(prefix))\n .map((k) => k.slice(prefix.length));\n },\n });\n\n return {\n collection: (name) => {\n checkName(\"collection\", name);\n return make(name);\n },\n close: async () => {\n closed = true;\n db.close();\n key.fill(0);\n await Promise.resolve();\n },\n };\n}\n"],"mappings":";;;AAGA,IAAa,mBAAb,cAAsC,MAAM;CAC1C;CAEA,YAAY,MAAuB,SAAiB;EAClD,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF;;;ACRA,SAAgB,UAAU,MAA4B,OAAqB;CACzE,IAAI,MAAM,SAAS,IAAQ,GACzB,MAAM,IAAI,iBAAiB,iBAAiB,GAAG,KAAK,sBAAsB;AAE9E;;;;;;;;;ACcA,MAAM,QAAQ;AAEd,MAAM,MAAM,YAAoB,cAA8B,GAAG,WAAW,QAAQ;AACpF,MAAM,OAAO,YAAoB,cAC/B,IAAI,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OAAO,SAAS;GAC1B,MAAM,KAAK,SAAS,YAAY,OAAO,WAAW;GAClD,GAAG,YAAY,KAAK,CAAC,CAAC,OAAO,GAAG,MAAM,SAAS,CAAC;GAChD,MAAM,KAAK,EAAE;EACf;EACA,MAAM,YAAY;GAIhB,MAAM,OAAO,MAAM,QAHF,MACC,CAAC,CAAC,YAAY,OAAO,UAC1B,CAAC,CAAC,YAAY,KAAK,CAAC,CAAC,WACU,CAAC;GAC7C,MAAM,SAAS,GAAG,KAAK;GACvB,OAAO,KACJ,QAAQ,MAAmB,OAAO,MAAM,YAAY,EAAE,WAAW,MAAM,CAAC,CAAC,CACzE,KAAK,MAAM,EAAE,MAAM,OAAO,MAAM,CAAC;EACtC;CACF;CAEA,OAAO;EACL,aAAa,SAAS;GACpB,UAAU,cAAc,IAAI;GAC5B,OAAO,KAAK,IAAI;EAClB;EACA,OAAO,YAAY;GACjB,SAAS;GACT,GAAG,MAAM;GACT,IAAI,KAAK,CAAC;GACV,MAAM,QAAQ,QAAQ;EACxB;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"idb.mjs","names":["STORE"],"sources":["../src/errors.ts","../src/store/guard.ts","../src/idb/requests.ts","../src/idb/public-store.ts","../src/idb/indexeddb.ts"],"sourcesContent":["export type EngineErrorCode = \"closed\" | \"integrity\" | \"invalid-input\";\n\n/** Typed engine errors: store codes are `closed` and `integrity` (decrypt or bind failure). */\nexport class EngineStoreError extends Error {\n readonly code: EngineErrorCode;\n\n constructor(code: EngineErrorCode, message: string) {\n super(message);\n this.name = \"EngineStoreError\";\n this.code = code;\n }\n}\n\nexport const errorMessage = (error: unknown): string =>\n error instanceof Error ? error.message : String(error);\n","import { EngineStoreError } from \"../errors.ts\";\n\n/** NUL is the composite-key/AAD separator — a name or key containing it collides. */\nexport function checkName(kind: \"collection\" | \"key\", value: string): void {\n if (value.includes(\"\\u0000\")) {\n throw new EngineStoreError(\"invalid-input\", `${kind} must not contain NUL`);\n }\n}\n","export async function request<T>(req: IDBRequest<T>): Promise<T> {\n return new Promise((resolve, reject) => {\n req.addEventListener(\"success\", () => {\n resolve(req.result);\n });\n req.addEventListener(\"error\", () => {\n reject(new Error(\"indexeddb request failed\", { cause: req.error }));\n });\n });\n}\n\nexport async function done(tx: IDBTransaction): Promise<void> {\n return new Promise((resolve, reject) => {\n tx.addEventListener(\"complete\", () => {\n resolve();\n });\n tx.addEventListener(\"error\", () => {\n reject(new Error(\"indexeddb transaction failed\", { cause: tx.error }));\n });\n tx.addEventListener(\"abort\", () => {\n reject(new Error(\"indexeddb transaction aborted\", { cause: tx.error }));\n });\n });\n}\n","import { checkName } from \"../store/guard.ts\";\nimport type { PublicStore } from \"../store/port.ts\";\nimport { done, request } from \"./requests.ts\";\n\nexport type IndexedDbPublicStoreOptions = { readonly name: string };\n\nconst STORE = \"records\";\n\n/** An unencrypted IndexedDB PublicStore: one database, one `records` object store. */\nexport async function openIndexedDbPublicStore(\n options: IndexedDbPublicStoreOptions,\n): Promise<PublicStore> {\n const db = await new Promise<IDBDatabase>((resolve, reject) => {\n const open = indexedDB.open(options.name, 1);\n open.addEventListener(\"upgradeneeded\", () => {\n open.result.createObjectStore(STORE);\n });\n open.addEventListener(\"success\", () => {\n resolve(open.result);\n });\n open.addEventListener(\"error\", () => {\n reject(new Error(\"indexeddb open failed\", { cause: open.error }));\n });\n });\n return {\n get: async (key) => {\n checkName(\"key\", key);\n const tx = db.transaction(STORE, \"readonly\");\n // oxlint-disable-next-line typescript/no-unsafe-argument -- IDB get() is any-typed by spec\n const value = await request<Uint8Array | undefined>(tx.objectStore(STORE).get(key));\n return value === undefined ? undefined : new Uint8Array(value);\n },\n put: async (key, bytes) => {\n checkName(\"key\", key);\n const tx = db.transaction(STORE, \"readwrite\");\n tx.objectStore(STORE).put(new Uint8Array(bytes), key);\n await done(tx);\n },\n };\n}\n","/**\n * The Web EngineStore: one IndexedDB database, one `records` object store, values encrypted per\n * record with XChaCha20-Poly1305. Key = the injected 32-byte data key; nonce = 24 random bytes\n * stored as nonce‖ciphertext; AAD = UTF-8 `<collection>\\0<key>` — moving a record to another key or\n * collection fails the MAC, same as a tampered payload. `close()` drops the connection, wipes the\n * module-held key copy and latches every call to `closed`.\n */\nimport { xchacha20poly1305 } from \"@noble/ciphers/chacha.js\";\n\nimport { EngineStoreError } from \"../errors.ts\";\nimport { checkName } from \"../store/guard.ts\";\nimport type { EngineCollection, EngineStore } from \"../store/port.ts\";\nimport { done, request } from \"./requests.ts\";\n\nexport { openIndexedDbPublicStore } from \"./public-store.ts\";\nexport type { IndexedDbPublicStoreOptions } from \"./public-store.ts\";\n\nexport type Random = (length: number) => Uint8Array;\n\nexport type IndexedDbEngineStoreOptions = {\n readonly name: string;\n readonly dataKey: Uint8Array;\n readonly random: Random;\n};\n\nconst STORE = \"records\";\n\nconst id = (collection: string, recordKey: string): string => `${collection}\\u0000${recordKey}`;\nconst aad = (collection: string, recordKey: string): Uint8Array =>\n new TextEncoder().encode(`${collection}\\u0000${recordKey}`);\n\nexport async function openIndexedDbEngineStore(\n options: IndexedDbEngineStoreOptions,\n): Promise<EngineStore> {\n const key = new Uint8Array(options.dataKey);\n return new Promise<EngineStore>((resolve, reject) => {\n const open = indexedDB.open(options.name, 1);\n open.addEventListener(\"upgradeneeded\", () => {\n open.result.createObjectStore(STORE);\n });\n open.addEventListener(\"success\", () => {\n resolve(makeStore(open.result, key, options.random));\n });\n open.addEventListener(\"error\", () => {\n key.fill(0);\n reject(new Error(\"indexeddb open failed\", { cause: open.error }));\n });\n });\n}\n\nfunction makeStore(db: IDBDatabase, key: Uint8Array, random: Random): EngineStore {\n let closed = false;\n\n const guard = (): IDBDatabase => {\n if (closed) {\n throw new EngineStoreError(\"closed\", \"engine store is closed\");\n }\n return db;\n };\n\n const seal = (collection: string, recordKey: string, bytes: Uint8Array): Uint8Array => {\n const nonce = random(24);\n const ciphertext = xchacha20poly1305(key, nonce, aad(collection, recordKey)).encrypt(bytes);\n const record = new Uint8Array(24 + ciphertext.length);\n record.set(nonce, 0);\n record.set(ciphertext, 24);\n return record;\n };\n\n const open = (collection: string, recordKey: string, record: Uint8Array): Uint8Array => {\n if (record.length < 24) {\n throw new EngineStoreError(\"integrity\", \"engine record too short\");\n }\n try {\n return xchacha20poly1305(key, record.slice(0, 24), aad(collection, recordKey)).decrypt(\n record.slice(24),\n );\n } catch {\n throw new EngineStoreError(\"integrity\", \"engine record failed integrity\");\n }\n };\n\n const make = (name: string): EngineCollection => ({\n get: async (recordKey) => {\n const database = guard();\n checkName(\"key\", recordKey);\n const tx = database.transaction(STORE, \"readonly\");\n const raw = tx.objectStore(STORE).get(id(name, recordKey));\n // oxlint-disable-next-line typescript/no-unsafe-argument -- IDB get() is any-typed by spec\n const record = await request<Uint8Array | undefined>(raw);\n return record === undefined ? undefined : open(name, recordKey, record);\n },\n put: async (recordKey, bytes) => {\n const database = guard();\n checkName(\"key\", recordKey);\n const tx = database.transaction(STORE, \"readwrite\");\n tx.objectStore(STORE).put(seal(name, recordKey, bytes), id(name, recordKey));\n await done(tx);\n },\n delete: async (recordKey) => {\n const database = guard();\n checkName(\"key\", recordKey);\n const tx = database.transaction(STORE, \"readwrite\");\n tx.objectStore(STORE).delete(id(name, recordKey));\n await done(tx);\n },\n list: async () => {\n const database = guard();\n const tx = database.transaction(STORE, \"readonly\");\n const all = tx.objectStore(STORE).getAllKeys();\n const keys = await request<IDBValidKey[]>(all);\n const prefix = `${name}\\u0000`;\n return keys\n .filter((k): k is string => typeof k === \"string\" && k.startsWith(prefix))\n .map((k) => k.slice(prefix.length));\n },\n });\n\n return {\n collection: (name) => {\n checkName(\"collection\", name);\n return make(name);\n },\n close: async () => {\n closed = true;\n db.close();\n key.fill(0);\n await Promise.resolve();\n },\n };\n}\n"],"mappings":";;;AAGA,IAAa,mBAAb,cAAsC,MAAM;CAC1C;CAEA,YAAY,MAAuB,SAAiB;EAClD,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF;;;ACRA,SAAgB,UAAU,M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