@ghostlytools/cli 1.11.2 → 1.11.3
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 +11 -10
- package/dist/assets/{api-BM3PsXbB.js → api-DBlaoz8i.js} +129 -37
- package/dist/assets/api-DBlaoz8i.js.map +1 -0
- package/dist/assets/{api-CtXgscmK.js → api-DgU4MZPD.js} +2 -2
- package/dist/assets/{apiKit-lCTQ0EBG.js → apiKit-DesObIDf.js} +4 -4
- package/dist/assets/{apiKit-lCTQ0EBG.js.map → apiKit-DesObIDf.js.map} +1 -1
- package/dist/assets/{appFetch-BKHy5H8J.js → appFetch-C8yZIq1e.js} +3 -3
- package/dist/assets/{appFetch-BKHy5H8J.js.map → appFetch-C8yZIq1e.js.map} +1 -1
- package/dist/assets/{apps-Do26w3c7.js → apps-DkMjDHML.js} +104 -33
- package/dist/assets/apps-DkMjDHML.js.map +1 -0
- package/dist/assets/{apps-DO_gAZgm.js → apps-rzxsjfBV.js} +1 -1
- package/dist/assets/{arkade-CZrLbz-M.js → arkade-CarKONmH.js} +2 -2
- package/dist/assets/{arkade-CZrLbz-M.js.map → arkade-CarKONmH.js.map} +1 -1
- package/dist/assets/{backup-j47AzDvG.js → backup-C0OJCJlM.js} +17 -25
- package/dist/assets/backup-C0OJCJlM.js.map +1 -0
- package/dist/assets/{backup-D21x1f5P.js → backup-CgWU7x0T.js} +1 -1
- package/dist/assets/buttons-Cco0Agfa.js +2 -0
- package/dist/assets/{buttons-CiGlBVBT.js → buttons-fZTEa_2i.js} +34 -5
- package/dist/assets/buttons-fZTEa_2i.js.map +1 -0
- package/dist/assets/{client-raIncVtF.js → client-Ibk3-e60.js} +2 -2
- package/dist/assets/{client-raIncVtF.js.map → client-Ibk3-e60.js.map} +1 -1
- package/dist/assets/{codec-DcG2AeyE.js → codec-DMpQqVSt.js} +2 -2
- package/dist/assets/{codec-DcG2AeyE.js.map → codec-DMpQqVSt.js.map} +1 -1
- package/dist/assets/{envelope-Dud6lntA.js → envelope-CvQVCGdf.js} +2 -2
- package/dist/assets/{envelope-Dud6lntA.js.map → envelope-CvQVCGdf.js.map} +1 -1
- package/dist/assets/{fedimintSdk-DRKRSw14.js → fedimintSdk-zV_5Qdqz.js} +2 -2
- package/dist/assets/{fedimintSdk-DRKRSw14.js.map → fedimintSdk-zV_5Qdqz.js.map} +1 -1
- package/dist/assets/{fixedHosts-CNX7QiUD.js → fixedHosts-6gKn8dp2.js} +3 -3
- package/dist/assets/{fixedHosts-CNX7QiUD.js.map → fixedHosts-6gKn8dp2.js.map} +1 -1
- package/dist/assets/{host-8RskzQgB.js → host-CYlIiY3r.js} +161 -32
- package/dist/assets/host-CYlIiY3r.js.map +1 -0
- package/dist/assets/{hyperdhtRelay-uAThbFub.js → hyperdhtRelay-CdsLcAhY.js} +2 -2
- package/dist/assets/{hyperdhtRelay-uAThbFub.js.map → hyperdhtRelay-CdsLcAhY.js.map} +1 -1
- package/dist/assets/{irohWeb-DGelfgDJ.js → irohWeb-D2IuloLL.js} +19 -12
- package/dist/assets/irohWeb-D2IuloLL.js.map +1 -0
- package/dist/assets/{main-BC33ooYg.js → main-C0PfjKTe.js} +109 -42
- package/dist/assets/main-C0PfjKTe.js.map +1 -0
- package/dist/assets/{mainline-DYrjsS1t.js → mainline-Cu61qcPS.js} +35 -18
- package/dist/assets/mainline-Cu61qcPS.js.map +1 -0
- package/dist/assets/{networkReason-n2oBs4by.js → networkReason-Dt7Yx_n4.js} +3 -3
- package/dist/assets/{networkReason-n2oBs4by.js.map → networkReason-Dt7Yx_n4.js.map} +1 -1
- package/dist/assets/{nwc-Do3VSlIS.js → nwc-CtZypDcv.js} +3 -3
- package/dist/assets/{nwc-Do3VSlIS.js.map → nwc-CtZypDcv.js.map} +1 -1
- package/dist/assets/{nwcProvider-Du5aWNIn.js → nwcProvider-DYHkd0iu.js} +2 -2
- package/dist/assets/{nwcProvider-Du5aWNIn.js.map → nwcProvider-DYHkd0iu.js.map} +1 -1
- package/dist/assets/{ownDid-CwwYu8s2.js → ownDid-CJ0ta8CL.js} +2 -2
- package/dist/assets/{ownDid-CwwYu8s2.js.map → ownDid-CJ0ta8CL.js.map} +1 -1
- package/dist/assets/{ownStatus-D7dB4zJB.js → ownStatus-D4HC6tNR.js} +11 -6
- package/dist/assets/{ownStatus-D7dB4zJB.js.map → ownStatus-D4HC6tNR.js.map} +1 -1
- package/dist/assets/{profiles-NyF5FnYF.js → profiles-Ccdq6Xf6.js} +3 -3
- package/dist/assets/{profiles-NyF5FnYF.js.map → profiles-Ccdq6Xf6.js.map} +1 -1
- package/dist/assets/{registry-C734VrO9.js → registry-CE0PpQAE.js} +1 -1
- package/dist/assets/{registry-DKDInr0A.js → registry-LvxsLJ5S.js} +18 -7
- package/dist/assets/registry-LvxsLJ5S.js.map +1 -0
- package/dist/assets/{resolve-3Tqh9AWQ.js → resolve-6kVu2DE5.js} +2 -2
- package/dist/assets/{resolve-3Tqh9AWQ.js.map → resolve-6kVu2DE5.js.map} +1 -1
- package/dist/assets/{server-B6PQ6iae.js → server-Q3VcNqGt.js} +245 -97
- package/dist/assets/server-Q3VcNqGt.js.map +1 -0
- package/dist/assets/{src-ChJijTlM.js → src-DjVj2ynY.js} +188 -42
- package/dist/assets/src-DjVj2ynY.js.map +1 -0
- package/dist/assets/{sshForges-Brf0fslM.js → sshForges-DeZ9cN9Q.js} +4 -3
- package/dist/assets/sshForges-DeZ9cN9Q.js.map +1 -0
- package/dist/assets/{translate-xLme9Rdh.js → translate-iQZq4TnY.js} +35 -14
- package/dist/assets/translate-iQZq4TnY.js.map +1 -0
- package/dist/assets/{usdt-CSU5KzTV.js → usdt-DnyTGdTX.js} +3 -3
- package/dist/assets/{usdt-CSU5KzTV.js.map → usdt-DnyTGdTX.js.map} +1 -1
- package/dist/ghostly.mjs +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/dist/assets/api-BM3PsXbB.js.map +0 -1
- package/dist/assets/apps-Do26w3c7.js.map +0 -1
- package/dist/assets/backup-j47AzDvG.js.map +0 -1
- package/dist/assets/buttons-CiGlBVBT.js.map +0 -1
- package/dist/assets/buttons-D2l2bVCG.js +0 -2
- package/dist/assets/host-8RskzQgB.js.map +0 -1
- package/dist/assets/irohWeb-DGelfgDJ.js.map +0 -1
- package/dist/assets/main-BC33ooYg.js.map +0 -1
- package/dist/assets/mainline-DYrjsS1t.js.map +0 -1
- package/dist/assets/registry-DKDInr0A.js.map +0 -1
- package/dist/assets/server-B6PQ6iae.js.map +0 -1
- package/dist/assets/src-ChJijTlM.js.map +0 -1
- package/dist/assets/sshForges-Brf0fslM.js.map +0 -1
- package/dist/assets/translate-xLme9Rdh.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { $u as isDiscoveryBudgetError, Gu as SLOW_MS, Hu as HEDGE_MS, Uu as RelayTransport, Vu as HEDGE_MISSING_MS, Wu as RelaysFailedError, Zu as DiscoveryBudgetError, id as newerPacket, od as parseRelayPayload, ud as publicKeyFromZ32 } from "./src-DjVj2ynY.js";
|
|
2
2
|
import { ed25519 } from "@noble/curves/ed25519.js";
|
|
3
3
|
import { createHash } from "node:crypto";
|
|
4
4
|
import DHT from "bittorrent-dht";
|
|
@@ -12,6 +12,13 @@ var verify$1 = (sig, message, key) => {
|
|
|
12
12
|
return false;
|
|
13
13
|
}
|
|
14
14
|
};
|
|
15
|
+
/**
|
|
16
|
+
* What a `get` takes from the nodes that answer: a record signed without salt (Pkarr has none). bittorrent-dht reads a
|
|
17
|
+
* reply's `salt` (`Buffer.concat` with the key) only once it is verified, and a number there threw in its socket handler:
|
|
18
|
+
* any node a lookup asked, signing with its own key, raised an error nobody caught. Signed data is `4:salt…` with a salt.
|
|
19
|
+
*/
|
|
20
|
+
var SALTED = Buffer.from("4:salt");
|
|
21
|
+
var verifyUnsalted = (sig, message, key) => !Buffer.from(message.buffer, message.byteOffset, Math.min(message.length, SALTED.length)).equals(SALTED) && verify$1(sig, message, key);
|
|
15
22
|
/** Queries the node answers, a second: from each address (as libtorrent's default), and from all of them together. */
|
|
16
23
|
var QUERY_LIMITS = {
|
|
17
24
|
perAddress: 5,
|
|
@@ -73,13 +80,17 @@ var DhtQueryLimit = class {
|
|
|
73
80
|
*/
|
|
74
81
|
var LOOPBACK = /^(127\.|::1$|::ffff:127\.)/;
|
|
75
82
|
var bytes = (value, length) => Buffer.isBuffer(value) && value.length === length;
|
|
83
|
+
/** BEP44's bound on an item's value, which bittorrent-dht checks only on what has a `length` (not a dictionary). */
|
|
84
|
+
var VALUE_MAX = 1e3;
|
|
76
85
|
/**
|
|
77
86
|
* What the node answers strangers: queries at `DhtQueryLimit`'s rate, ping, find_node and get/get_peers as BEP5/BEP44
|
|
78
87
|
* say, and puts of signed mutable items only, which is what Pkarr packets are (the testnet's nodes and the public DHT
|
|
79
88
|
* keep each other's that way). It refuses what the app has no use for and bittorrent-dht kept for anyone and served to
|
|
80
|
-
* anyone: immutable items and peers announced for torrents. A
|
|
81
|
-
*
|
|
82
|
-
*
|
|
89
|
+
* anyone: immutable items and peers announced for torrents. A put's value is a string of at most 1000 bytes and its seq
|
|
90
|
+
* a non-negative integer, as every Pkarr packet's: bittorrent-dht bounds only a value with a `length`, so a dictionary
|
|
91
|
+
* of 60 KB was kept and served whole to every get. A query whose hash, key, signature or salt is not the string
|
|
92
|
+
* BEP5/BEP44 say (a put signed without a key, a number for a target) threw out of the socket handler: an error nobody
|
|
93
|
+
* caught, one per datagram. It is refused before bittorrent-dht reads it.
|
|
83
94
|
*/
|
|
84
95
|
function answerBounded(dht, limit = new DhtQueryLimit()) {
|
|
85
96
|
const node = dht;
|
|
@@ -89,7 +100,8 @@ function answerBounded(dht, limit = new DhtQueryLimit()) {
|
|
|
89
100
|
const q = query.q?.toString(), a = query.a ?? {};
|
|
90
101
|
if (q === "announce_peer") return node._rpc.error(peer, query, [204, "announce_peer is not served here"]);
|
|
91
102
|
if (q === "put" && (!bytes(a.k, 32) || !bytes(a.sig, SIGNATURE))) return node._rpc.error(peer, query, [203, "only signed mutable items are stored here"]);
|
|
92
|
-
if (
|
|
103
|
+
if (q === "put" && !(Buffer.isBuffer(a.v) && a.v.length <= VALUE_MAX)) return node._rpc.error(peer, query, [205, "only values of at most 1000 bytes are stored here"]);
|
|
104
|
+
if ((q === "get" || q === "find_node") && !bytes(a.target, 20) || q === "get_peers" && !bytes(a.info_hash, 20) || q === "put" && !(Number.isSafeInteger(a.seq) && a.seq >= 0) || q === "put" && a.salt !== void 0 && !(Buffer.isBuffer(a.salt) && a.salt.length <= 64)) return node._rpc.error(peer, query, [203, "malformed query"]);
|
|
93
105
|
try {
|
|
94
106
|
answer(query, peer);
|
|
95
107
|
} catch {}
|
|
@@ -183,16 +195,19 @@ var Mainline = class {
|
|
|
183
195
|
const k = Buffer.from(publicKeyFromZ32(pubKeyZ32));
|
|
184
196
|
const target = createHash("sha1").update(k).digest();
|
|
185
197
|
return this.bounded(new Promise((resolve, reject) => {
|
|
186
|
-
this.dht.get(target, {
|
|
198
|
+
this.dht.get(target, {
|
|
199
|
+
cache: false,
|
|
200
|
+
verify: verifyUnsalted
|
|
201
|
+
}, (error, found) => {
|
|
187
202
|
if (error) return reject(error);
|
|
188
|
-
if (!found
|
|
189
|
-
const timestamp = new Uint8Array(TIMESTAMP);
|
|
190
|
-
new DataView(timestamp.buffer).setBigUint64(0, BigInt(found.seq));
|
|
191
|
-
const payload = new Uint8Array(72 + found.v.length);
|
|
192
|
-
payload.set(found.sig, 0);
|
|
193
|
-
payload.set(timestamp, SIGNATURE);
|
|
194
|
-
payload.set(found.v, 72);
|
|
203
|
+
if (!found || !Buffer.isBuffer(found.v) || !Buffer.isBuffer(found.sig) || !Number.isSafeInteger(found.seq) || found.seq < 0) return resolve(null);
|
|
195
204
|
try {
|
|
205
|
+
const timestamp = new Uint8Array(TIMESTAMP);
|
|
206
|
+
new DataView(timestamp.buffer).setBigUint64(0, BigInt(found.seq));
|
|
207
|
+
const payload = new Uint8Array(72 + found.v.length);
|
|
208
|
+
payload.set(found.sig, 0);
|
|
209
|
+
payload.set(timestamp, SIGNATURE);
|
|
210
|
+
payload.set(found.v, 72);
|
|
196
211
|
resolve(parseRelayPayload(pubKeyZ32, payload));
|
|
197
212
|
} catch {
|
|
198
213
|
resolve(null);
|
|
@@ -281,8 +296,9 @@ var waitable = (options) => !!options.background && !options.urgent && !options.
|
|
|
281
296
|
/**
|
|
282
297
|
* The relays first, as the web app reaches Pkarr (its contacts read only the relays), and the DHT beside them: every
|
|
283
298
|
* packet also goes to the DHT, and a read goes there when every relay is failing, the read failed, or this app's own
|
|
284
|
-
* request budget held it back (the DHT has no budget)
|
|
285
|
-
* the DHT answers in the relays' place keep to the relays'
|
|
299
|
+
* request budget held it back (the DHT has no budget), or every relay rate limits this address (429). A background read
|
|
300
|
+
* this app's budget holds waits for it. Background reads the DHT answers in the relays' place keep to the relays'
|
|
301
|
+
* background share (`DhtBackgroundBudget`).
|
|
286
302
|
*
|
|
287
303
|
* `pinned`: the relays given are the only ones (`GHOSTLY_PKARR_RELAYS`, a private network): the profile's `relays`
|
|
288
304
|
* setting does not replace them. With no DHT (`dht` null), the relays alone carry every packet.
|
|
@@ -374,10 +390,11 @@ var RelaysAndDht = class {
|
|
|
374
390
|
return found;
|
|
375
391
|
}
|
|
376
392
|
({packet: fromRelays, failed} = answered);
|
|
377
|
-
|
|
393
|
+
const refusing = this.relays.discovery().relays.every((relay) => relay.state !== "ok");
|
|
394
|
+
if (isDiscoveryBudgetError(failed) && !(refusing && options.background)) return this.heldBack(pubKeyZ32, failed, options);
|
|
378
395
|
if (failed instanceof RelaysFailedError) fromRelays = failed.kept;
|
|
379
396
|
if (!failed) this.lastVia = "relay";
|
|
380
|
-
if (!failed && !down()) return fromRelays;
|
|
397
|
+
if (!failed && !down() && !refusing) return fromRelays;
|
|
381
398
|
}
|
|
382
399
|
try {
|
|
383
400
|
if (waitable(options) && this.relays.describe().relays.length > 0) {
|
|
@@ -506,4 +523,4 @@ var RelaysAndDht = class {
|
|
|
506
523
|
//#endregion
|
|
507
524
|
export { Mainline, RelaysAndDht };
|
|
508
525
|
|
|
509
|
-
//# sourceMappingURL=mainline-
|
|
526
|
+
//# sourceMappingURL=mainline-Cu61qcPS.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mainline-Cu61qcPS.js","names":["verify"],"sources":["../../src/runtime/mainline.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport DHT from \"bittorrent-dht\";\nimport { ed25519 } from \"@noble/curves/ed25519.js\";\nimport {\n BACKGROUND_REQUESTS_PER_MINUTE, DiscoveryBudgetError, HEDGE_MISSING_MS, HEDGE_MS, RelayTransport, RelaysFailedError, SLOW_MS, isDiscoveryBudgetError, newerPacket, parseRelayPayload, publicKeyFromZ32,\n type DiscoveryStatus, type GhostRecord, type Identity, type PkarrRequestOptions, type PkarrTransport, type RelayTransportOptions, type SignedPacket,\n} from \"@ghostly/core\";\n\n/**\n * Pkarr over the Mainline DHT (BEP44), from Node, as the Desktop reaches it from Rust: the relays are HTTP bridges to\n * this same DHT, so a headless Ghostly that speaks it directly keeps finding its contacts while the relays fail (they\n * answered HTTP 500 for more than ten minutes on 2026-09-27, and a group's edges stayed down all that while).\n *\n * A Pkarr packet is a BEP44 mutable item: the key is the Ed25519 public key, the value the DNS packet, the sequence\n * number its timestamp in microseconds, and the signature the one the relay payload already carries (over\n * `3:seqi<seq>e1:v<len>:<v>`). So one signed payload goes to the relays and to the DHT unchanged.\n */\n\nexport interface MainlineOptions {\n /** `host:port` nodes to start from; the public routers when absent; none with `false` (a testnet's first node). */\n bootstrap?: string[] | false;\n /** Address to bind (a loopback testnet binds 127.0.0.1). */\n host?: string;\n /** How long a lookup may take before it is given up, in ms. */\n timeoutMs?: number;\n}\n\nconst SIGNATURE = 64, TIMESTAMP = 8;\nconst verify = (sig: Uint8Array, message: Uint8Array, key: Uint8Array) => { try { return ed25519.verify(sig, message, key); } catch { return false; } };\n/**\n * What a `get` takes from the nodes that answer: a record signed without salt (Pkarr has none). bittorrent-dht reads a\n * reply's `salt` (`Buffer.concat` with the key) only once it is verified, and a number there threw in its socket handler:\n * any node a lookup asked, signing with its own key, raised an error nobody caught. Signed data is `4:salt…` with a salt.\n */\nconst SALTED = Buffer.from(\"4:salt\");\nconst verifyUnsalted = (sig: Uint8Array, message: Uint8Array, key: Uint8Array) =>\n !Buffer.from(message.buffer, message.byteOffset, Math.min(message.length, SALTED.length)).equals(SALTED) && verify(sig, message, key);\n\n/** Queries the node answers, a second: from each address (as libtorrent's default), and from all of them together. */\nconst QUERY_LIMITS = { perAddress: 5, perAddressBurst: 20, total: 50, totalBurst: 200 };\n/** Addresses `DhtQueryLimit` remembers: forged source addresses must not grow it without end. */\nconst ADDRESSES_KEPT = 4_096;\n/** Mutable items others put on the node: as many as bittorrent-dht keeps, each for the two hours BEP44 suggests. */\nconst VALUES_KEPT = { max: 1_000, maxAge: 2 * 60 * 60_000 };\n\n/**\n * The queries a DHT node answers, as token buckets: a burst then a rate per source address, and a total for all. UDP\n * has no handshake, so a query's address can be someone else's: answered without a limit, a stranger who parked a\n * 1000-byte item on the node had it send ~12.5x the bytes of each forged `get` (5-6x with nothing parked) to that\n * address, as fast as they came. Queries past either limit go unanswered, as an overloaded node's do. This node's own\n * lookups (answers to its queries, not queries) are not counted.\n */\nexport class DhtQueryLimit {\n private readonly addresses = new Map<string, { tokens: number; at: number }>();\n private all: { tokens: number; at: number } | null = null;\n\n constructor(private readonly limits: typeof QUERY_LIMITS = QUERY_LIMITS) {}\n\n /** Addresses remembered (`ADDRESSES_KEPT` at most). */\n get size(): number { return this.addresses.size; }\n\n /** Whether a query from `host` is answered now (counted if so). */\n take(host: string, now = Date.now()): boolean {\n const refill = (bucket: { tokens: number; at: number } | null | undefined, rate: number, burst: number) => {\n if (!bucket) return { tokens: burst, at: now };\n // A clock that went back refills nothing, and counts from now on.\n bucket.tokens = Math.min(burst, bucket.tokens + Math.max(0, now - bucket.at) * rate / 1_000);\n bucket.at = now;\n return bucket;\n };\n const all = this.all = refill(this.all, this.limits.total, this.limits.totalBurst);\n const own = refill(this.addresses.get(host), this.limits.perAddress, this.limits.perAddressBurst);\n // Kept in the order last asked: the address not heard from the longest goes first.\n this.addresses.delete(host);\n this.addresses.set(host, own);\n if (this.addresses.size > ADDRESSES_KEPT) this.addresses.delete(this.addresses.keys().next().value!);\n if (own.tokens < 1 || all.tokens < 1) return false;\n own.tokens -= 1; all.tokens -= 1;\n return true;\n }\n}\n\ntype Query = { q?: Buffer | string; a?: { k?: unknown; v?: unknown; seq?: unknown; sig?: unknown; salt?: unknown; target?: unknown; info_hash?: unknown } };\ntype QueryPeer = { address: string; port: number };\n/** The parts of bittorrent-dht's node (no API for them) through which it answers queries. */\ninterface DhtInternals { _onquery(query: Query, peer: QueryPeer): void; _rpc: { error(peer: QueryPeer, query: Query, error: [number, string]): void } }\n\n/**\n * A source on loopback is this machine, never a forged address from outside (a packet from the network claiming one is\n * dropped before it gets here): each of its ports is a node of its own (a loopback testnet's nodes all share the host),\n * counted apart. Any other address is counted whatever its port, as a forged source's port is the sender's choice.\n */\nconst LOOPBACK = /^(127\\.|::1$|::ffff:127\\.)/;\nconst bytes = (value: unknown, length: number): boolean => Buffer.isBuffer(value) && value.length === length;\n/** BEP44's bound on an item's value, which bittorrent-dht checks only on what has a `length` (not a dictionary). */\nconst VALUE_MAX = 1_000;\n\n/**\n * What the node answers strangers: queries at `DhtQueryLimit`'s rate, ping, find_node and get/get_peers as BEP5/BEP44\n * say, and puts of signed mutable items only, which is what Pkarr packets are (the testnet's nodes and the public DHT\n * keep each other's that way). It refuses what the app has no use for and bittorrent-dht kept for anyone and served to\n * anyone: immutable items and peers announced for torrents. A put's value is a string of at most 1000 bytes and its seq\n * a non-negative integer, as every Pkarr packet's: bittorrent-dht bounds only a value with a `length`, so a dictionary\n * of 60 KB was kept and served whole to every get. A query whose hash, key, signature or salt is not the string\n * BEP5/BEP44 say (a put signed without a key, a number for a target) threw out of the socket handler: an error nobody\n * caught, one per datagram. It is refused before bittorrent-dht reads it.\n */\nfunction answerBounded(dht: DHT, limit = new DhtQueryLimit()): void {\n const node = dht as unknown as DhtInternals;\n const answer = node._onquery.bind(dht);\n node._onquery = (query, peer) => {\n if (!query || !peer || !limit.take(LOOPBACK.test(peer.address) ? `${peer.address}:${peer.port}` : peer.address)) return;\n const q = query.q?.toString(), a = query.a ?? {};\n if (q === \"announce_peer\") return node._rpc.error(peer, query, [204, \"announce_peer is not served here\"]);\n if (q === \"put\" && (!bytes(a.k, 32) || !bytes(a.sig, SIGNATURE))) return node._rpc.error(peer, query, [203, \"only signed mutable items are stored here\"]);\n if (q === \"put\" && !(Buffer.isBuffer(a.v) && a.v.length <= VALUE_MAX)) return node._rpc.error(peer, query, [205, \"only values of at most 1000 bytes are stored here\"]);\n const malformed = ((q === \"get\" || q === \"find_node\") && !bytes(a.target, 20)) || (q === \"get_peers\" && !bytes(a.info_hash, 20))\n || (q === \"put\" && !(Number.isSafeInteger(a.seq) && (a.seq as number) >= 0))\n || (q === \"put\" && a.salt !== undefined && !(Buffer.isBuffer(a.salt) && a.salt.length <= 64));\n if (malformed) return node._rpc.error(peer, query, [203, \"malformed query\"]);\n try { answer(query, peer); } catch { /* a query bittorrent-dht could not read goes unanswered */ }\n };\n}\n\n/**\n * Every DHT node asked refused a put for holding a later-dated packet of the key (BEP44 error 302, \"sequence number less\n * than current\"): one put by this key's earlier clock, ahead of this one, before a restart forgot its date.\n */\nexport class DhtRefusedError extends Error {\n constructor(reason: string) {\n super(`The DHT holds a later-dated packet of this key (${reason})`);\n this.name = \"DhtRefusedError\";\n }\n}\n\n/**\n * A DHT node of this process: puts and gets Pkarr packets. The node starts at the first thing asked of it: a command\n * that reads only the profile (`chat list`, `settings get`) or a profile set offline asks nothing, and before, every\n * command bound a UDP port and bootstrapped from the public routers all the same, sending them this machine's address.\n */\nexport class Mainline {\n private node: { dht: DHT; listening: Promise<void> } | null = null;\n private closed = false;\n private readonly timeoutMs: number;\n\n constructor(private readonly options: MainlineOptions = {}) {\n this.timeoutMs = options.timeoutMs ?? 20_000;\n }\n\n private get dht(): DHT { return this.started().dht; }\n\n private started(): { dht: DHT; listening: Promise<void> } {\n if (this.closed) throw new Error(\"The DHT node is closed\");\n if (this.node) return this.node;\n const { host } = this.options;\n const bootstrap = this.options.bootstrap === false ? false : this.options.bootstrap?.length ? this.options.bootstrap : undefined;\n // `maxValues` reaches the `lru` that holds others' items, which takes `{ max, maxAge }` as well as a number.\n const dht = new DHT({ verify, maxValues: VALUES_KEPT, ...(bootstrap !== undefined ? { bootstrap } : {}), ...(host ? { host } : {}) });\n // A node of the table that errors must not end the process.\n dht.on(\"error\", () => {});\n answerBounded(dht);\n this.node = { dht, listening: new Promise((resolve) => dht.listen(0, host, () => resolve())) };\n return this.node;\n }\n\n /** Whether the node started (something was put, got or added). */\n get running(): boolean { return this.node !== null; }\n /** Its UDP socket is bound (starts the node). */\n get listening(): Promise<void> { return this.started().listening; }\n\n /** Adds a node (a testnet's peers). */\n addNode(host: string, port: number): void { this.dht.addNode({ host, port }); }\n address(): { port: number } { return this.dht.address() as { port: number }; }\n\n /** Puts a relay payload (`<signature><timestamp><DNS packet>`) as the mutable item of `pubKeyZ32`; resolves with the nodes that took it. */\n put(pubKeyZ32: string, payload: Uint8Array): Promise<number> {\n const k = Buffer.from(publicKeyFromZ32(pubKeyZ32));\n const sig = Buffer.from(payload.subarray(0, SIGNATURE));\n const seq = Number(new DataView(payload.buffer, payload.byteOffset + SIGNATURE, TIMESTAMP).getBigUint64(0));\n const v = Buffer.from(payload.subarray(SIGNATURE + TIMESTAMP));\n return this.bounded(new Promise((resolve, reject) => {\n this.dht.put({ k, v, seq, sig }, (error, _hash, nodes) => {\n if (error) reject((error as Error & { code?: unknown }).code === 302 ? new DhtRefusedError(error.message) : error);\n else if (!nodes) reject(new Error(\"No DHT node took the packet\")); else resolve(nodes);\n });\n }));\n }\n\n /** The newest packet of `pubKeyZ32` the DHT holds, checked; null when nobody has one. */\n get(pubKeyZ32: string): Promise<SignedPacket | null> {\n const k = Buffer.from(publicKeyFromZ32(pubKeyZ32));\n // A mutable item without salt is found under the SHA-1 of its public key (BEP44).\n const target = createHash(\"sha1\").update(k).digest();\n return this.bounded(new Promise((resolve, reject) => {\n this.dht.get(target, { cache: false, verify: verifyUnsalted }, (error, found) => {\n if (error) return reject(error);\n // A record is what its node sent, checked only by its signature: one signed with no `seq` (bittorrent-dht signs\n // `seq || 0`) or with a dictionary for `v` threw here, out of the socket's handler.\n if (!found || !Buffer.isBuffer(found.v) || !Buffer.isBuffer(found.sig) || !Number.isSafeInteger(found.seq) || found.seq < 0) return resolve(null);\n try {\n const timestamp = new Uint8Array(TIMESTAMP);\n new DataView(timestamp.buffer).setBigUint64(0, BigInt(found.seq));\n const payload = new Uint8Array(SIGNATURE + TIMESTAMP + found.v.length);\n payload.set(found.sig, 0); payload.set(timestamp, SIGNATURE); payload.set(found.v, SIGNATURE + TIMESTAMP);\n resolve(parseRelayPayload(pubKeyZ32, payload));\n } catch { resolve(null); }\n });\n }));\n }\n\n private bounded<T>(work: Promise<T>): Promise<T> {\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => reject(new Error(\"DHT lookup timed out\")), this.timeoutMs);\n work.then((value) => { clearTimeout(timer); resolve(value); }, (error) => { clearTimeout(timer); reject(error); });\n });\n }\n\n /** Closes the node and its socket, if it started; the next thing asked of it starts it again. */\n stop(): Promise<void> {\n const node = this.node;\n this.node = null;\n return node ? new Promise((resolve) => node.dht.destroy(() => resolve())) : Promise.resolve();\n }\n\n destroy(): Promise<void> {\n this.closed = true;\n return this.stop();\n }\n}\n\n/** Keys a `RelaysAndDht` remembers as found nowhere (`missing`). */\nconst MISSING_KEPT = 256;\n\n/** How long a key that asked for a background DHT read counts among those that share the budget (`DhtBackgroundBudget`). */\nconst ASKERS_WINDOW_MS = 2 * 60_000;\nconst MINUTE_MS = 60_000;\n\n/**\n * Background reads that go to the DHT in the relays' place (every relay failing, or failing this read), within the share\n * the relays would have given them (`BACKGROUND_REQUESTS_PER_MINUTE` a minute on each relay): a minute's lookups at\n * most, and each key in its turn, no sooner than the keys asking share that minute (`n` keys at `perMinute` a minute:\n * once every `n / perMinute` minutes). Without it, a daemon looked up every contact away on the DHT four times a minute\n * for as long as the relays failed (200 lookups a minute at 50 contacts, 1,200 at 300), where with the relays up it\n * made 26-54 relay reads a minute in all; each lookup on the real DHT is dozens of UDP queries.\n * Reads someone waits on (not `background`, or `urgent`, `signal`, `door`, `resume`) never wait for it, nor count.\n */\nexport class DhtBackgroundBudget {\n private readonly spent: number[] = [];\n /** Per key, when it last asked (oldest first) and when its last lookup went. */\n private readonly askedAt = new Map<string, number>();\n private readonly lookedAt = new Map<string, number>();\n /** The time of the last `take`: none of the above is dated after it. */\n private latest = -Infinity;\n\n constructor(private readonly perMinute: () => number) {}\n\n /** 0: the lookup goes now (counted). Otherwise how long until this key's turn, in ms; nothing is counted. */\n take(pubKeyZ32: string, now = Date.now()): number {\n // The clock went back (an NTP step, a clock that ran ahead fixed by hand): what is dated after now counts as of now,\n // as just spent. Counted as it was, an hour's step back held every key's lookup for 56 minutes (bug hunt, 2026-11-07).\n if (now < this.latest) {\n this.spent.forEach((at, i) => { this.spent[i] = Math.min(at, now); });\n for (const times of [this.askedAt, this.lookedAt]) for (const [key, at] of times) if (at > now) times.set(key, now);\n }\n this.latest = now;\n this.askedAt.delete(pubKeyZ32);\n this.askedAt.set(pubKeyZ32, now);\n for (const [key, at] of this.askedAt) {\n if (now - at < ASKERS_WINDOW_MS) break;\n this.askedAt.delete(key);\n this.lookedAt.delete(key);\n }\n while (this.spent.length && now - this.spent[0]! >= MINUTE_MS) this.spent.shift();\n const limit = Math.max(1, this.perMinute());\n const turn = Math.ceil(this.askedAt.size * MINUTE_MS / limit);\n const last = this.lookedAt.get(pubKeyZ32);\n const ownTurn = last === undefined ? 0 : last + turn - now;\n // The minute's lookups are spent (keys new to it, all at once): this key's turn, or the minute's next free one if later.\n const minute = this.spent.length >= limit ? this.spent[0]! + MINUTE_MS - now : 0;\n if (ownTurn > 0 || minute > 0) return Math.max(ownTurn, minute, last === undefined ? turn : 0);\n this.spent.push(now);\n this.lookedAt.set(pubKeyZ32, now);\n return 0;\n }\n}\n\n/** A read nobody waits on: what the relays' budget calls background, and what the DHT's (`DhtBackgroundBudget`) holds. */\nconst waitable = (options: PkarrRequestOptions): boolean =>\n !!options.background && !options.urgent && !options.signal && !options.door && !options.resume;\n\n/**\n * The relays first, as the web app reaches Pkarr (its contacts read only the relays), and the DHT beside them: every\n * packet also goes to the DHT, and a read goes there when every relay is failing, the read failed, or this app's own\n * request budget held it back (the DHT has no budget), or every relay rate limits this address (429). A background read\n * this app's budget holds waits for it. Background reads the DHT answers in the relays' place keep to the relays'\n * background share (`DhtBackgroundBudget`).\n *\n * `pinned`: the relays given are the only ones (`GHOSTLY_PKARR_RELAYS`, a private network): the profile's `relays`\n * setting does not replace them. With no DHT (`dht` null), the relays alone carry every packet.\n */\nexport class RelaysAndDht implements PkarrTransport {\n readonly relays: RelayTransport;\n private lastVia: \"relay\" | \"dht\" = \"relay\";\n /**\n * Keys a hedged read found nowhere: the DHT said so before the relays' slow 404 came, so the next poll of the key\n * hedges late too (`HEDGE_MISSING_MS`), not only once that 404 lands. The newest `MISSING_KEPT`.\n */\n private readonly missing = new Set<string>();\n /** Background reads on the DHT in the relays' place, at their background share (`DhtBackgroundBudget`). */\n private readonly dhtBackground = new DhtBackgroundBudget(() => BACKGROUND_REQUESTS_PER_MINUTE * this.relays.describe().relays.length);\n\n /** Off while the profile keeps to the relays (Hide my IP from contacts, `configure`'s `dhtDirect: false`). */\n private direct = true;\n\n constructor(private readonly mainline: Mainline | null, relays: RelayTransportOptions = {}, private readonly pinned = false) {\n this.relays = new RelayTransport(relays);\n }\n\n /** The DHT this transport reaches now: none while the profile keeps to the relays. */\n private get dht(): Mainline | null { return this.direct ? this.mainline : null; }\n\n async publish(identity: Identity, records: GhostRecord[], options: PkarrRequestOptions = {}): Promise<void> {\n // BEP44 sequence numbers must strictly increase, on the relays and on the DHT alike: one payload for both, dated\n // past every packet put or read under the key (`RelayTransport.publishDated`), whichever clock dated those.\n // With the DHT, the packet goes there whatever the relays' budgets say: signed every time. Without it (a private\n // network's relays only), a publish none of them takes now is not signed at all.\n await this.relays.publishDated(identity, records, (key, payload, timestamp, conflict) => this.putBoth(key, payload, options, conflict, timestamp), options, false, this.dht !== null);\n }\n\n publishPayload(pubKeyZ32: string, payload: Uint8Array, options: PkarrRequestOptions = {}): Promise<void> {\n return this.putBoth(pubKeyZ32, payload, options);\n }\n\n /**\n * `timestamp`: the payload was just signed here (`publish`), dated so; its signature is not checked again on the way\n * to the relays. Without it (`publishPayload`, signed elsewhere) the relays' side checks it to read its date.\n */\n private async putBoth(pubKeyZ32: string, payload: Uint8Array, options: PkarrRequestOptions, conflict?: (relay: string, read?: () => Promise<bigint | null>) => void, timestamp?: bigint): Promise<void> {\n const toRelays = () => timestamp === undefined\n ? this.relays.publishPayload(pubKeyZ32, payload, options, conflict)\n : this.relays.putSigned(pubKeyZ32, payload, timestamp, options, conflict);\n if (!this.dht) return toRelays();\n const onDht = this.dht.put(pubKeyZ32, payload);\n onDht.catch(() => {});\n const onRelays = toRelays();\n onRelays.catch(() => {});\n // Out on the DHT is out (a Pkarr relay reads the DHT for a key it has not got): a relay that takes the request and\n // never answers held each publish for its 10 s timeout, an invite's first among them, while the DHT took it in\n // milliseconds. The relays' copy finishes in the background. A budget's hold is said before any request goes, so\n // it wins this race: once the DHT took the packet, that is out too, and the relays get it when their budget frees\n // (`putLater`; browser contacts read only them). Said held back, the link signed it and put it on the DHT again in\n // 0.25-4 s, at budget 1.5-2.2x the DHT puts of a DHT-only daemon.\n let refused: unknown;\n const tookIt = onDht.then(() => true, (error: unknown) => {\n refused = error;\n // The DHT holds a later-dated packet of this key, as a relay that answers 409 does: its date is read there, and\n // the records go again dated just past it (`publishDated`). After a clock that ran ahead was set right, a\n // restarted CLI had every put refused, tried again every 4 s until the clock caught up (15 a minute per chat), and\n // texts to a contact away stayed queued.\n if (error instanceof DhtRefusedError) conflict?.(\"dht\", () => this.fromDht(pubKeyZ32).then((packet) => packet?.timestampMicros ?? null));\n return false;\n });\n if (await Promise.race([onRelays.then(() => false, () => false), tookIt])) return;\n try {\n await onRelays;\n } catch (error) {\n if (isDiscoveryBudgetError(error)) {\n if (!(await tookIt)) throw error;\n this.relays.putLater(pubKeyZ32, payload, timestamp, options);\n return;\n }\n // The relays failed: the DHT's answer is the publish's, and its refusal is said with theirs.\n if (!(await tookIt)) throw refused instanceof Error ? new Error(`${error instanceof Error ? error.message : String(error)}; ${refused.message}`, { cause: error }) : error;\n }\n }\n\n async resolve(pubKeyZ32: string, options: PkarrRequestOptions = {}, keptOnFailure = true): Promise<SignedPacket | null> {\n if (!this.dht) return this.relays.resolve(pubKeyZ32, options, keptOnFailure);\n let fromRelays: SignedPacket | null = null, failed: unknown = null;\n // Every relay left alone for failing: the relays answer from what they last saw, if anything; the DHT is asked.\n const down = () => this.relays.discovery().relays.every((relay) => relay.state === \"failing\");\n if (!down()) {\n const started = Date.now();\n // A read the relays failed asks the DHT at once, their last copy kept to weigh against its packet. Handed back\n // as their answer, it stood for each 20 s cooldown until the breaker opened: about 40 s of a contact's old packet\n // with the newer one on the DHT (bug hunt, 2026-10-17).\n const relays = this.relays.resolve(pubKeyZ32, options, false).then((packet) => ({ packet, failed: null as unknown }), (error: unknown) => ({ packet: null, failed: error }));\n let timer: ReturnType<typeof setTimeout> | undefined;\n // A key whose last read found nothing: the relays take 3-5 s to say a key is not there\n // (they ask the DHT themselves), and a hedge at HEDGE_MS made every poll of an unused invite's key a DHT lookup\n // of its own (+47 in 10 min: agents#1595). Their own hedge waits as long (`RelayTransport`, `HEDGE_MISSING_MS`).\n const hedgeAfter = this.relays.lastReadMissing(pubKeyZ32) || this.missing.has(pubKeyZ32) ? HEDGE_MISSING_MS : HEDGE_MS;\n const answered = await Promise.race([relays, new Promise<null>((resolve) => { timer = setTimeout(() => resolve(null), hedgeAfter); })]);\n clearTimeout(timer);\n // The relays have not answered within a hedge's time (one that takes requests and never answers held each read\n // for its 10 s timeout): the DHT is asked too.\n if (!answered) {\n const found = await this.hedged(pubKeyZ32, relays, started);\n this.missing.delete(pubKeyZ32);\n if (!found) { this.missing.add(pubKeyZ32); if (this.missing.size > MISSING_KEPT) this.missing.delete(this.missing.values().next().value!); }\n return found;\n }\n ({ packet: fromRelays, failed } = answered);\n // No relay is asked now: each one rate limits this address (429) for as long as it said, or fails. Their answer is\n // what they last saw, or a wait, and the DHT is asked in their place, as when they all fail (a background read\n // at their share). Taken as their answer, a daemon whose relays answered 429 for 10 minutes read none of its 50\n // contacts in that time, and looked none up on the DHT (bug hunt, 2026-11-11).\n const refusing = this.relays.discovery().relays.every((relay) => relay.state !== \"ok\");\n // The relays' budget held the read back: the DHT, which has no budget and already has a contact's first\n // envelope, is asked instead. Waiting for the relays' minute made each pairing past ~10 chats on working relays\n // take 3-18 s (13-37 s on one relay), where DHT-only pairings take 0.1-2.8 s (agents#1715). Found nowhere there,\n // or a background read, it is still a wait.\n if (isDiscoveryBudgetError(failed) && !(refusing && options.background)) return this.heldBack(pubKeyZ32, failed, options);\n if (failed instanceof RelaysFailedError) fromRelays = failed.kept;\n if (!failed) this.lastVia = \"relay\";\n if (!failed && !down() && !refusing) return fromRelays;\n }\n try {\n // A background read the DHT answers instead of the relays waits its turn there (`DhtBackgroundBudget`), as it did\n // on them: held back, as their budget holds one. With no relay set at all the DHT is the only way, not a stand-in.\n if (waitable(options) && this.relays.describe().relays.length > 0) {\n const wait = this.dhtBackground.take(pubKeyZ32);\n if (wait > 0) throw new DiscoveryBudgetError(wait, \"Background DHT reads in the relays' place are at their share; retry shortly\");\n }\n const fromDht = await this.fromDht(pubKeyZ32);\n this.lastVia = \"dht\";\n return newerPacket(fromRelays, fromDht);\n } catch (error) {\n // Nothing answered, the DHT neither: the relays' last copy is the answer, or, for a caller that asks, the failure\n // that carries it (`keptOnFailure`).\n if (fromRelays && (keptOnFailure || !(failed instanceof RelaysFailedError))) return fromRelays;\n throw failed ?? error;\n }\n }\n\n private async heldBack(pubKeyZ32: string, held: unknown, options: PkarrRequestOptions): Promise<SignedPacket> {\n if (options.background) throw held;\n const fromDht = await this.fromDht(pubKeyZ32).catch(() => null);\n if (!fromDht) throw held;\n this.lastVia = \"dht\";\n return fromDht;\n }\n\n private async fromDht(pubKeyZ32: string): Promise<SignedPacket | null> {\n // The switch turned while a read was on its way to the DHT: it does not go.\n if (!this.dht) throw new Error(\"The DHT is not reached while the profile keeps to the relays\");\n const packet = await this.dht.get(pubKeyZ32);\n if (packet) this.relays.sawTimestamp(pubKeyZ32, packet.timestampMicros);\n return packet;\n }\n\n /**\n * A read the relays are slow to answer, the DHT asked beside them. The relays' packet first is the answer, as without\n * the hedge. The DHT's first waits for the relays until a slow relay would have had its say (`SLOW_MS`, a relay\n * fetching the packet from the DHT itself), or until they answer, and the newer of the two is the answer: taken at\n * once, the DHT's older copy won every read over a relay that took 2 s with the newer one (agents#1594). The DHT\n * finding none is the answer once that time is up too, or once the relays answered. Both failing: the relays' reason.\n */\n private async hedged(pubKeyZ32: string, relays: Promise<{ packet: SignedPacket | null; failed: unknown }>, started: number): Promise<SignedPacket | null> {\n const dht = this.fromDht(pubKeyZ32).then((packet) => ({ packet, failed: null as unknown, via: \"dht\" as const }), (error: unknown) => ({ packet: null, failed: error, via: \"dht\" as const }));\n const viaRelays = relays.then((r) => ({ ...r, via: \"relay\" as const }));\n const first = await Promise.race([viaRelays, dht]);\n if (first.packet && first.via === \"relay\") { this.lastVia = \"relay\"; return first.packet; }\n const fromDht = await dht;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const slowAfter = new Promise<null>((resolve) => { timer = setTimeout(() => resolve(null), Math.max(0, SLOW_MS - (Date.now() - started))); });\n const fromRelays = await Promise.race([viaRelays, slowAfter]);\n clearTimeout(timer);\n if (fromDht.packet) {\n const newer = newerPacket(fromRelays?.packet, fromDht.packet);\n this.lastVia = newer === fromDht.packet ? \"dht\" : \"relay\";\n return newer;\n }\n if (fromRelays?.packet) { this.lastVia = \"relay\"; return fromRelays.packet; }\n if (!fromDht.failed) { this.lastVia = \"dht\"; return null; }\n if (!fromRelays) throw fromDht.failed;\n if (!fromRelays.failed) return null;\n throw fromRelays.failed;\n }\n\n describe(): { protocol: string; relays: string[] } {\n return { protocol: this.dht ? \"Pkarr relays (HTTP), and the Mainline DHT (BEP44) directly\" : \"Pkarr relays (HTTP)\", relays: this.relays.describe().relays };\n }\n discovery(): DiscoveryStatus {\n const status = this.relays.discovery();\n return this.lastVia === \"dht\" ? { ...status, path: { via: \"dht\" } } : status;\n }\n subscribe(listener: Parameters<RelayTransport[\"subscribe\"]>[0]): () => void { return this.relays.subscribe(listener); }\n /** A relay's answer only: a packet the DHT hands back when the relays are down may be older than one already read. */\n readAnsweredAt(pubKeyZ32: string): number | undefined { return this.relays.readAnsweredAt(pubKeyZ32); }\n readHeldBackFor(pubKeyZ32: string): number | undefined { return this.relays.readHeldBackFor(pubKeyZ32); }\n /** With the DHT every packet goes there too, whatever the relays' budgets say: nothing is held. */\n publishHeld(pubKeyZ32: string, options?: PkarrRequestOptions): DiscoveryBudgetError | null { return this.dht ? null : this.relays.publishHeld(pubKeyZ32, options); }\n onServerTime(listener: Parameters<RelayTransport[\"onServerTime\"]>[0]): () => void { return this.relays.onServerTime(listener); }\n /**\n * `dhtDirect: false` (Hide my IP from contacts): no packet is put on or read from the DHT, and its node is closed, so\n * no UDP goes from this machine to a DHT node; true again starts it at the next put or read. Absent leaves it as it is.\n */\n configure({ relays, dhtDirect }: { relays: string[]; readRelays: boolean; dhtDirect?: boolean }): void {\n if (!this.pinned) this.relays.setRelays(relays);\n if (dhtDirect === undefined) return;\n this.direct = dhtDirect;\n if (!dhtDirect) this.mainline?.stop().catch(() => {});\n }\n /**\n * The relays' side only: the DHT side keeps nothing per key it puts. What it keeps per key it reads is bounded\n * (`missing`, `M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ynY.js";
|
|
2
2
|
import { _ as openDb, b as transact, s as STORES, x as wrap, y as store } from "./idb-CEuoNsTv.js";
|
|
3
|
-
import { t as fromBase64Url } from "./codec-
|
|
3
|
+
import { t as fromBase64Url } from "./codec-DMpQqVSt.js";
|
|
4
4
|
import { sha256 } from "@noble/hashes/sha2.js";
|
|
5
5
|
import { bytesToHex, utf8ToBytes } from "@noble/hashes/utils.js";
|
|
6
6
|
//#region ../browser/src/shared/profileKey.ts
|
|
@@ -471,4 +471,4 @@ function rpcHost(url) {
|
|
|
471
471
|
//#endregion
|
|
472
472
|
export { sealSeed as a, openRow as c, sealRow as d, sealedStore as f, whenDataKeyDropped as g, sealSecret as h, newDeviceKey as i, openRows as l, openSecret as m, rpcHost as n, unsealSeed as o, hasDataKey as p, intentRepository as r, RowSeals as s, networkReason as t, proofKey as u };
|
|
473
473
|
|
|
474
|
-
//# sourceMappingURL=networkReason-
|
|
474
|
+
//# sourceMappingURL=networkReason-Dt7Yx_n4.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"networkReason-n2oBs4by.js","names":[],"sources":["../../../browser/src/shared/profileKey.ts","../../../browser/src/engine/dataKey.ts","../../../browser/src/engine/sealedRows.ts","../../../browser/src/engine/paymentAdapters/persistence.ts","../../../browser/src/engine/paymentAdapters/networkReason.ts"],"sourcesContent":["import { fromBase64Url, toBase64Url } from \"../backup/codec\";\n\n/**\n * The encrypted profile's keys (WISP 04, Encrypted profile): a random data key (DK) per profile seals each secret\n * field, and is stored only wrapped under a key derived from the passphrase (KEK). The passphrase never encrypts\n * data directly, so changing it rewraps 32 bytes and rewrites nothing else.\n */\nexport interface ProfileKeyRecord {\n format: \"ghostly-profile-key\";\n version: 1;\n kdf: { name: \"PBKDF2-SHA256\"; iterations: number; salt: string };\n cipher: { name: \"AES-256-GCM\"; iv: string };\n /** The profile id, empty for the default: the record opens only in its own profile's slot. */\n profile: string;\n ciphertext: string;\n}\n/** A field sealed under DK. Version 1 is the `{version:1,salt,iv,ciphertext}` seed sealed with a device key. */\nexport interface SealedField { v: 2; iv: string; ct: string }\n/**\n * Where a sealed field lives: a ciphertext moved to another database, store, record or field fails to open instead\n * of being read as that one. `db` is `local` for local storage.\n */\nexport interface FieldBinding { db: string; store: string; key: string; field: string }\n\nconst ITERATIONS = 600_000;\nconst MAX_ITERATIONS = 10_000_000;\nconst DK_BYTES = 32;\nconst TAG_BYTES = 16;\n\nasync function kekFrom(passphrase: string, salt: Uint8Array, iterations: number): Promise<CryptoKey> {\n const material = await crypto.subtle.importKey(\"raw\", new TextEncoder().encode(passphrase), \"PBKDF2\", false, [\"deriveKey\"]);\n return crypto.subtle.deriveKey({ name: \"PBKDF2\", hash: \"SHA-256\", salt: salt as BufferSource, iterations }, material, { name: \"AES-GCM\", length: 256 }, false, [\"encrypt\", \"decrypt\", \"unwrapKey\"]);\n}\n\n/** The clear header is the wrap's associated data, `profile` included: changing any of it makes the record fail to open. */\nconst header = (r: Omit<ProfileKeyRecord, \"ciphertext\">) =>\n new TextEncoder().encode([r.format, r.version, r.kdf.name, r.kdf.iterations, r.kdf.salt, r.cipher.name, r.cipher.iv, r.profile].join(\"\\n\"));\n\nconst importDataKey = (raw: Uint8Array) => crypto.subtle.importKey(\"raw\", raw as BufferSource, { name: \"AES-GCM\" }, false, [\"encrypt\", \"decrypt\"]);\n\nfunction checkPassphrase(passphrase: string) {\n if (passphrase.length < 12) throw new Error(\"Use at least 12 characters for the profile passphrase\");\n}\n\nasync function wrap(raw: Uint8Array, passphrase: string, profile: string): Promise<ProfileKeyRecord> {\n const salt = crypto.getRandomValues(new Uint8Array(16)), iv = crypto.getRandomValues(new Uint8Array(12));\n const clear = { format: \"ghostly-profile-key\", version: 1, kdf: { name: \"PBKDF2-SHA256\", iterations: ITERATIONS, salt: toBase64Url(salt) }, cipher: { name: \"AES-256-GCM\", iv: toBase64Url(iv) }, profile } as const;\n const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv, additionalData: header(clear) as BufferSource }, await kekFrom(passphrase, salt, ITERATIONS), raw as BufferSource));\n return { ...clear, ciphertext: toBase64Url(ciphertext) };\n}\n\n/** Refuses what this version can't read before any KDF runs, as backups do. */\nfunction checked(record: ProfileKeyRecord, profile: string) {\n if (record?.format !== \"ghostly-profile-key\") throw new Error(\"This is not a Ghostly profile key\");\n if (record.version !== 1) throw new Error(\"This profile key comes from a newer Ghostly; update to open it\");\n if (record.kdf?.name !== \"PBKDF2-SHA256\" || !Number.isInteger(record.kdf.iterations) || record.kdf.iterations < ITERATIONS || record.kdf.iterations > MAX_ITERATIONS || record.cipher?.name !== \"AES-256-GCM\") throw new Error(\"Unsupported profile key encryption\");\n if (typeof record.profile !== \"string\" || record.profile !== profile) throw new Error(\"This profile key belongs to another profile\");\n const salt = fromBase64Url(record.kdf.salt), iv = fromBase64Url(record.cipher.iv), ciphertext = fromBase64Url(record.ciphertext);\n if (salt.length !== 16 || iv.length !== 12 || ciphertext.length !== DK_BYTES + TAG_BYTES) throw new Error(\"Unsupported profile key encryption\");\n return { salt, iv, ciphertext };\n}\n\n/** Turning encryption on: a fresh DK, wrapped under the passphrase, and the DK itself as a key that can't be read back. */\nexport async function createProfileKey(passphrase: string, profile: string): Promise<{ record: ProfileKeyRecord; key: CryptoKey }> {\n checkPassphrase(passphrase);\n const raw = crypto.getRandomValues(new Uint8Array(DK_BYTES));\n try { return { record: await wrap(raw, passphrase, profile), key: await importDataKey(raw) }; } finally { raw.fill(0); }\n}\n\n/** The start gate: the DK as a non-extractable key, or \"Wrong passphrase\" with nothing else read. */\nexport async function unlockProfileKey(record: ProfileKeyRecord, passphrase: string, profile: string): Promise<CryptoKey> {\n const { salt, iv, ciphertext } = checked(record, profile);\n const kek = await kekFrom(passphrase, salt, record.kdf.iterations);\n try {\n return await crypto.subtle.unwrapKey(\"raw\", ciphertext as BufferSource, kek, { name: \"AES-GCM\", iv: iv as BufferSource, additionalData: header(record) as BufferSource }, { name: \"AES-GCM\" }, false, [\"encrypt\", \"decrypt\"]);\n } catch { throw new Error(\"Wrong passphrase\"); }\n}\n\n/** Change passphrase: the same DK under a new KEK, salt and nonce. No sealed field changes. */\nexport async function rewrapProfileKey(record: ProfileKeyRecord, passphrase: string, next: string, profile: string): Promise<ProfileKeyRecord> {\n checkPassphrase(next);\n const { salt, iv, ciphertext } = checked(record, profile);\n let raw: Uint8Array;\n try {\n raw = new Uint8Array(await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: iv as BufferSource, additionalData: header(record) as BufferSource }, await kekFrom(passphrase, salt, record.kdf.iterations), ciphertext as BufferSource));\n } catch { throw new Error(\"Wrong passphrase\"); }\n try { return await wrap(raw, next, profile); } finally { raw.fill(0); }\n}\n\n/**\n * Only the record key can hold a newline: the other parts come from the code, so the joined binding still reads one\n * way (the first two lines, the last line, and the key between them).\n */\nfunction binding(b: FieldBinding): Uint8Array {\n for (const part of [b.db, b.store, b.field]) if (!part || part.includes(\"\\n\")) throw new Error(\"Invalid sealed field binding\");\n return new TextEncoder().encode([\"ghostly-field/2\", b.db, b.store, b.key, b.field].join(\"\\n\"));\n}\n\nexport function isSealedField(value: unknown): value is SealedField {\n const v = value as Partial<SealedField> | null;\n return !!v && typeof v === \"object\" && v.v === 2 && typeof v.iv === \"string\" && typeof v.ct === \"string\";\n}\n\n/** Seals one field under DK with a fresh random 96-bit nonce and no KDF per field. */\nexport async function sealField(key: CryptoKey, where: FieldBinding, value: string): Promise<SealedField> {\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const ct = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv, additionalData: binding(where) as BufferSource }, key, new TextEncoder().encode(value)));\n return { v: 2, iv: toBase64Url(iv), ct: toBase64Url(ct) };\n}\n\n/** Opens a field sealed for exactly this place under this DK; anything else fails instead of opening wrong. */\nexport async function openField(key: CryptoKey, where: FieldBinding, sealed: SealedField): Promise<string> {\n if (!isSealedField(sealed)) throw new Error(\"Unsupported sealed field version\");\n const aad = binding(where);\n try {\n const iv = fromBase64Url(sealed.iv);\n if (iv.length !== 12) throw new Error(\"nonce\");\n return new TextDecoder().decode(await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: iv as BufferSource, additionalData: aad as BufferSource }, key, fromBase64Url(sealed.ct) as BufferSource));\n } catch { throw new Error(\"A sealed field could not be opened: it was changed, or it belongs to another record\"); }\n}\n","import { isSealedField, openField, sealField, type FieldBinding, type SealedField } from \"../shared/profileKey\";\nimport { newDeviceKey, sealSeed, unsealSeed, type EncryptedSeed } from \"./paymentAdapters/persistence\";\n\n/** Version 1: sealed under a random key stored beside it. It keeps a secret from a log, not from a reader of the profile. */\nexport interface DeviceSealed { sealed: EncryptedSeed; deviceKey: string }\n/** A secret the engine keeps: version 1 while the profile is not encrypted, version 2 under its data key once it is. */\nexport type SealedSecret = DeviceSealed | SealedField;\n/**\n * Where a secret belongs, in the peer database (WISP 04, Encrypted profile): its store, its own id (stable when the\n * secret moves inside its record, as a proof key does into the revocations) and what it is.\n */\nexport type SecretPlace = Omit<FieldBinding, \"db\">;\n\nconst PEER_DB = \"ghostly\";\n\n/**\n * The profile's data key (DK), when the profile is encrypted and unlocked: the one slot the engine owns. A\n * non-extractable key; nothing writes it anywhere. Empty, every secret is sealed as today (version 1).\n */\nlet slot: CryptoKey | null = null;\n/**\n * The profile's migration is over (no `migrating` mark): a sealed place then takes version 2 only. A version 1 or plain\n * value there was put by someone who could write the profile's database but not read it, and is refused.\n */\nlet sealedOnly = false;\nconst onDrop = new Set<() => void>();\nconst LOCKED = \"This profile is locked. Enter its passphrase first.\";\n\nexport function setDataKey(key: CryptoKey): void { slot = key; }\nexport function hasDataKey(): boolean { return slot !== null; }\n/** Off until the migration that seals every place has ended; set by it. */\nexport function setSealedOnly(on: boolean): void { sealedOnly = on; }\n/** Whether a sealed place may still hold a version 1 or plain value. */\nexport function takesUnsealed(): boolean { return !(slot && sealedOnly); }\n/** \"Lock and stop\", or a profile switch: the key goes, and so does every secret opened with it and kept in memory. */\nexport function dropDataKey(): void {\n slot = null;\n sealedOnly = false;\n for (const drop of [...onDrop]) drop();\n}\n/** A cache of opened secrets empties itself when the key goes. Returns the way to stop listening. */\nexport function whenDataKeyDropped(drop: () => void): () => void {\n onDrop.add(drop);\n return () => { onDrop.delete(drop); };\n}\n\nexport async function sealSecret(value: string, at: SecretPlace): Promise<SealedSecret> {\n if (slot) return sealField(slot, { db: PEER_DB, ...at }, value);\n const deviceKey = newDeviceKey();\n return { sealed: await sealSeed(value, deviceKey), deviceKey };\n}\n\n/** Version 2 only, for a field the database layer seals: refused while the profile is locked, never version 1. */\nexport async function sealPlace(value: string, at: SecretPlace): Promise<SealedField> {\n if (!slot) throw new Error(LOCKED);\n return sealField(slot, { db: PEER_DB, ...at }, value);\n}\n\n/** Reads both versions: a profile being encrypted holds some of each until its migration ends. */\nexport async function openSecret(secret: SealedSecret, at: SecretPlace): Promise<string> {\n if (!isSealedField(secret)) {\n if (!takesUnsealed()) throw new Error(\"A secret of this profile was not sealed with its key\");\n return unsealSeed(secret.sealed, secret.deviceKey);\n }\n if (!slot) throw new Error(LOCKED);\n return openField(slot, { db: PEER_DB, ...at }, secret);\n}\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex, utf8ToBytes } from \"@noble/hashes/utils.js\";\nimport { STORES } from \"../shared/idb\";\nimport { isSealedField, type SealedField } from \"../shared/profileKey\";\nimport { hasDataKey, openSecret, sealPlace, takesUnsealed, type SecretPlace } from \"./dataKey\";\n\n/**\n * Phase 1 of the encrypted profile (WISP 04, What is encrypted): the fields of the peer database that let someone act\n * as the person or spend, by store, as paths into the row. With the data key set they are written sealed (version 2,\n * bound to the store, the row's key and the path) and opened as they are read; without it, rows are written and read\n * as they always were. A field is sealed as its JSON, so an object (transport seeds, epoch secrets) is one field.\n */\nconst FIELDS: Record<string, readonly string[]> = {\n [STORES.links]: [\"seedB64\", \"encKeyB64\", \"participationSeed\", \"transportSeeds\", \"inviteCode\", \"pairedPeerKey\", \"peerTrust.verifiedKey\", \"ratchetState\"],\n [STORES.groups]: [\"invitation.seedB64\", \"entry.seedB64\", \"joining.seedB64\", \"state.seedB64\", \"state.secrets\", \"community.seedB64\", \"community.secrets\", \"community.entry.seedB64\", \"community.rv\"],\n [STORES.swaps]: [\"swap\", \"token\"],\n [STORES.melts]: [\"secrets\", \"outputs\"],\n // A sent token kept for Take it back, the outputs of a paid invoice not minted yet, and a Cashu review's swap and token.\n [STORES.payments]: [\"token\"],\n [STORES.quotes]: [\"outputs\"],\n [STORES.intents]: [\"prepared.swap\", \"prepared.token\"],\n};\n/** A group removed and invited again keeps the group it was (`previous`), with secrets of its own. */\nconst NESTED: Record<string, string> = { [STORES.groups]: \"previous\" };\n\n/**\n * A proof's secret is its row's key (`keyPath: \"secret\"`), and a sealed value can't be one: a sealed proof is kept under\n * this hash of its secret, the secret itself sealed beside it. The hash, not the secret, can be found again inside a\n * transaction, where WebCrypto can't be waited for.\n */\nexport const proofKey = (secret: string): string => bytesToHex(sha256(utf8ToBytes(`ghostly-proof/1\\n${secret}`)));\nconst SEALED_SECRET = \"sealedSecret\";\n\ntype Row = Record<string, unknown>;\ntype Seal = (json: string, at: SecretPlace) => SealedField;\n\nconst keyOf = (store: string, row: Row) =>\n String(store === STORES.melts || store === STORES.quotes ? row.quote : store === STORES.intents ? read(row, \"review.id\") : row.id);\n\nfunction read(row: Row, path: string): unknown {\n return path.split(\".\").reduce<unknown>((at, part) => (at && typeof at === \"object\" ? (at as Row)[part] : undefined), row);\n}\n/** The row with `value` at `path`, copied along the way: the caller's row is never changed. */\nfunction written(row: Row, [part, ...rest]: string[], value: unknown): Row {\n return { ...row, [part]: rest.length ? written(row[part] as Row, rest, value) : value };\n}\n\n/** Every phase 1 value of a row that is there, with its path. */\nfunction places(store: string, row: Row, prefix = \"\"): { path: string; value: unknown }[] {\n const found = (FIELDS[store] ?? []).map((path) => ({ path: prefix + path, value: read(row, path) })).filter(({ value }) => value !== undefined);\n const nested = NESTED[store] && row[NESTED[store]];\n return nested && typeof nested === \"object\" ? [...found, ...places(store, nested as Row, `${prefix}${NESTED[store]}.`)] : found;\n}\n\nfunction sealWith<T>(store: string, value: T, seal: Seal): T {\n const row = value as Row;\n if (store === STORES.proofs) {\n if (row[SEALED_SECRET] !== undefined) return value;\n const secret = String(row.secret), key = proofKey(secret);\n return { ...row, secret: key, [SEALED_SECRET]: seal(JSON.stringify(secret), { store, key, field: \"secret\" }) } as T;\n }\n const key = keyOf(store, row);\n let out = row;\n for (const { path, value: at } of places(store, row)) {\n if (!isSealedField(at)) out = written(out, path.split(\".\"), seal(JSON.stringify(at), { store, key, field: path }));\n }\n return out as T;\n}\n\nconst slotOf = (json: string, at: SecretPlace) => [at.store, at.key, at.field, json].join(\"\\n\");\n\n/**\n * Seals made ahead of a transaction, for `row` to use inside it: IndexedDB commits a transaction that waits for\n * anything else, WebCrypto included. Whether rows are sealed is fixed when this is made, so a key dropped meanwhile\n * makes a write fail, never go out in the clear.\n */\nexport class RowSeals {\n /** Seals are made one batch after another, so writes that seal first are saved in the order they were asked for. */\n private static turn: Promise<unknown> = Promise.resolve();\n readonly on = hasDataKey();\n private ready = new Map<string, SealedField>();\n\n /** What these rows (or the proofs of these secrets) hold, sealed now. */\n async prepare(store: string, rows: readonly object[]): Promise<this> {\n if (!this.on) return this;\n const wanted = new Map<string, [string, SecretPlace]>();\n for (const row of rows) sealWith(store, row, (json, at) => { wanted.set(slotOf(json, at), [json, at]); return { v: 2, iv: \"\", ct: \"\" }; });\n const sealing = RowSeals.turn.then(async () => {\n for (const [slot, [json, at]] of wanted) if (!this.ready.has(slot)) this.ready.set(slot, await sealPlace(json, at));\n });\n RowSeals.turn = sealing.catch(() => {});\n await sealing;\n return this;\n }\n\n /** The row as it is written. Throws for a value not prepared: its transaction aborts, and nothing goes out in the clear. */\n row<T>(store: string, row: T): T {\n if (!this.on) return row;\n return sealWith(store, row, (json, at) => {\n const sealed = this.ready.get(slotOf(json, at));\n if (!sealed) throw new Error(\"A secret was not sealed before it was saved\");\n return sealed;\n });\n }\n}\n\nexport async function sealRow<T extends object>(store: string, row: T): Promise<T> {\n return (await new RowSeals().prepare(store, [row])).row(store, row);\n}\n\n/**\n * The store as a transaction's work sees it: what it puts is sealed from `seals`, and a proof is found by its secret.\n * Without the data key, the store itself.\n */\nexport function sealedStore(store: IDBObjectStore, seals: RowSeals): IDBObjectStore {\n if (!seals.on) return store;\n const proofs = store.name === STORES.proofs;\n return new Proxy(store, {\n get(target, name) {\n if (name === \"put\") return (row: object, ...key: [IDBValidKey?]) => target.put(seals.row(target.name, row), ...key);\n // A proof stored before the profile was encrypted is kept under its secret until the migration reseals it.\n if (proofs && name === \"delete\") return (secret: string) => { target.delete(secret); return target.delete(proofKey(secret)); };\n if (proofs && name === \"get\") return (secret: string) => target.get(proofKey(secret));\n const value: unknown = Reflect.get(target, name, target);\n return typeof value === \"function\" ? value.bind(target) : value;\n },\n });\n}\n\nfunction unsealed(): void {\n if (!takesUnsealed()) throw new Error(\"A secret of this profile was not sealed with its key\");\n}\n\n/** The row as the engine uses it: every sealed value opened, where it was. */\nexport async function openRow<T>(store: string, value: T): Promise<T> {\n if (!hasDataKey() || !value) return value;\n const row = value as Row;\n if (store === STORES.proofs) {\n const sealed = row[SEALED_SECRET];\n if (sealed === undefined) { unsealed(); return value; }\n const key = String(row.secret), secret = JSON.parse(await openSecret(sealed as SealedField, { store, key, field: \"secret\" })) as string;\n if (proofKey(secret) !== key) throw new Error(\"A sealed field could not be opened: it was changed, or it belongs to another record\");\n const { [SEALED_SECRET]: _sealed, ...rest } = row;\n return { ...rest, secret } as T;\n }\n const key = keyOf(store, row);\n let out = row;\n for (const { path, value: at } of places(store, row)) {\n if (!isSealedField(at)) { unsealed(); continue; }\n out = written(out, path.split(\".\"), JSON.parse(await openSecret(at, { store, key, field: path })));\n }\n return out as T;\n}\n\nexport function openRows<T>(store: string, rows: T[]): Promise<T[]> {\n return hasDataKey() ? Promise.all(rows.map((row) => openRow(store, row))) : Promise.resolve(rows);\n}\n","import { engineError, engineText } from \"@ghostly/core\";\nimport { STORES, openDb, store, transact, wrap } from \"../../shared/idb\";\nimport { openRow, openRows, sealRow } from \"../sealedRows\";\nimport type { IntentRepository, SavedIntent } from \"./coordinator\";\n/**\n * A USDT payment is one transaction at one account nonce. Another payment from the same account and chain that is\n * submitted or of unknown outcome holds its nonce until it confirms. A review made after it was sent took the next\n * nonce and may go at once. One made before (or read from an RPC that had not seen it yet) has the same or a lower\n * nonce: sent, it would replace the earlier transaction or be dropped, so it is refused. A row with no nonce refuses.\n */\nfunction nonceTaken(review:SavedIntent[\"review\"],intents:SavedIntent[]):boolean {\n if(review.method!==\"usdt\")return false;\n const from=review.evm?.from?.toLowerCase(), nonce=review.evm?.nonce;\n return intents.some(({review:other})=>other.id!==review.id && other.method===\"usdt\" && other.chainId===review.chainId && other.evm?.from?.toLowerCase()===from && [\"submitted\",\"unknown\"].includes(other.state)\n && !(typeof nonce===\"number\" && typeof other.evm?.nonce===\"number\" && nonce>other.evm.nonce));\n}\n/**\n * A Cashu review's swap and token are sealed when the profile is encrypted (sealedRows): they are read here opened.\n * `claim` and `cancel` change only the review, so they put back the row as it was read, sealed fields and all.\n */\nexport const intentRepository: IntentRepository = {\n async get(id) { return openRow(STORES.intents,await wrap<SavedIntent | undefined>((await store(STORES.intents,\"readonly\")).get(id))); },\n async list() { return openRows(STORES.intents,await wrap<SavedIntent[]>((await store(STORES.intents,\"readonly\")).getAll())); },\n async put(intent) { const row=await sealRow(STORES.intents,intent); await transact([STORES.intents],s=>{s[STORES.intents].put(row);}); },\n async claim(id) {\n const tx=(await openDb()).transaction(STORES.intents,\"readwrite\");\n return new Promise<SavedIntent>((resolve,reject)=>{\n let saved:SavedIntent;\n let reason=engineText(\"alreadySubmitted\");\n const request=tx.objectStore(STORES.intents).getAll();\n request.onsuccess=()=>{\n const intents:SavedIntent[]=request.result;\n saved=intents.find(item=>item.review.id===id)!;\n if(!saved || saved.review.state!==\"pending\") {tx.abort();return;}\n const duplicate=saved.review.requestId && intents.some(({review})=>review.id!==id && review.requestId===saved.review.requestId && review.linkId===saved.review.linkId && [\"submitted\",\"settled\",\"unknown\"].includes(review.state));\n if(duplicate){tx.abort();return;}\n if(nonceTaken(saved.review,intents)){reason=engineText(\"sentAfterReview\");tx.abort();return;}\n saved.review={...saved.review,state:\"submitted\",error:undefined,submittedAt:Date.now()};\n tx.objectStore(STORES.intents).put(saved);\n };\n tx.oncomplete=()=>resolve(openRow(STORES.intents,saved));\n tx.onabort=tx.onerror=()=>reject(new Error(reason));\n });\n },\n async cancel(id) {\n const tx=(await openDb()).transaction(STORES.intents,\"readwrite\");\n return new Promise<SavedIntent>((resolve,reject)=>{\n let saved:SavedIntent;\n const request=tx.objectStore(STORES.intents).get(id);\n request.onsuccess=()=>{\n saved=request.result;\n if(!saved || saved.review.state!==\"pending\"){tx.abort();return;}\n saved.review={...saved.review,state:\"cancelled\"};\n tx.objectStore(STORES.intents).put(saved);\n };\n tx.oncomplete=()=>resolve(openRow(STORES.intents,saved));\n tx.onabort=tx.onerror=()=>reject(engineError(\"cannotCancelSubmitted\"));\n });\n },\n};\n/** Key for a wallet that needs no password: its seed is protected like the Cashu proofs in the same database. */\nexport function newDeviceKey():string {return btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32)))).replace(/=+$/,\"\");}\nexport interface EncryptedSeed {version:1;salt:number[];iv:number[];ciphertext:number[]}\nasync function passwordKey(password:string,salt:Uint8Array<ArrayBuffer>) {\n const material=await crypto.subtle.importKey(\"raw\",new TextEncoder().encode(password),\"PBKDF2\",false,[\"deriveKey\"]);\n return crypto.subtle.deriveKey({name:\"PBKDF2\",hash:\"SHA-256\",salt,iterations:600000},material,{name:\"AES-GCM\",length:256},false,[\"encrypt\",\"decrypt\"]);\n}\nexport async function sealSeed(seed:string,password:string):Promise<EncryptedSeed> {\n if(password.length<12)throw new Error(\"Use at least 12 characters for the wallet password\");\n const salt=crypto.getRandomValues(new Uint8Array(16)),iv=crypto.getRandomValues(new Uint8Array(12));\n const ciphertext=await crypto.subtle.encrypt({name:\"AES-GCM\",iv},await passwordKey(password,salt),new TextEncoder().encode(seed));\n return {version:1,salt:[...salt],iv:[...iv],ciphertext:[...new Uint8Array(ciphertext)]};\n}\nexport async function unsealSeed(seed:EncryptedSeed,password:string):Promise<string> {\n if(seed.version!==1)throw new Error(\"Unsupported wallet backup version\");\n try {return new TextDecoder().decode(await crypto.subtle.decrypt({name:\"AES-GCM\",iv:new Uint8Array(seed.iv)},await passwordKey(password,new Uint8Array(seed.salt)),new Uint8Array(seed.ciphertext)));}\n catch {throw new Error(\"Could not unlock the wallet. Check the password and backup.\");}\n}\n","import { engineText } from \"@ghostly/core\";\n\n/**\n * A request's failure as a person says it, when the browser's own words say nothing: a request that timed out or was\n * given up (\"Fetch is aborted\" in Safari, \"signal timed out\" in Chromium) did not answer in time; one that never left\n * (\"Failed to fetch\", \"Load failed\") could not reach it. `host` names what was asked, when known. Anything else is\n * `null`: its own words are kept.\n */\nexport function networkReason(error: unknown, host?: string): string | null {\n const name = error instanceof Error ? error.name : \"\";\n const text = error instanceof Error ? error.message : String(error);\n if (name === \"AbortError\" || name === \"TimeoutError\" || /^(fetch is aborted|signal timed out|signal is aborted without reason|the (user|operation) (aborted a request|was aborted)\\.?|this operation was aborted|the operation timed out\\.?)$/i.test(text.trim()))\n return host ? engineText(\"hostTimedOut\", { host }) : engineText(\"networkTimedOut\");\n if (/^(failed to fetch|load failed|fetch failed|networkerror when attempting to fetch resource\\.?|network request failed)$/i.test(text.trim()))\n return host ? engineText(\"hostUnreachable\", { host }) : engineText(\"networkUnreachable\");\n return null;\n}\n\n/** A request URL's host, for a reason that names it; the URL itself when it does not parse. */\nexport function rpcHost(url: string): string {\n try { return new URL(url).host; } catch { return url; }\n}\n"],"mappings":";;;;;;;;;;AA6FA,SAAS,QAAQ,GAA6B;CAC5C,KAAK,MAAM,QAAQ;EAAC,EAAE;EAAI,EAAE;EAAO,EAAE;CAAK,GAAG,IAAI,C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WAAW,gBAAgB,EAAE,KAAK,CAAC,IAAI,WAAW,iBAAiB;CACnF,IAAI,yHAAyH,KAAK,KAAK,KAAK,CAAC,GAC3I,OAAO,OAAO,WAAW,mBAAmB,EAAE,KAAK,CAAC,IAAI,WAAW,oBAAoB;CACzF,OAAO;AACT;;AAGA,SAAgB,QAAQ,KAAqB;CAC3C,IAAI;EAAE,OAAO,IAAI,IAAI,GAAG,CAAC,CAAC;CAAM,QAAQ;EAAE,OAAO;CAAK;AACxD"}
|
|
1
|
+
{"version":3,"file":"networkReason-Dt7Yx_n4.js","names":[],"sources":["../../../browser/src/shared/profileKey.ts","../../../browser/src/engine/dataKey.ts","../../../browser/src/engine/sealedRows.ts","../../../browser/src/engine/paymentAdapters/persistence.ts","../../../browser/src/engine/paymentAdapters/networkReason.ts"],"sourcesContent":["import { fromBase64Url, toBase64Url } from \"../backup/codec\";\n\n/**\n * The encrypted profile's keys (WISP 04, Encrypted profile): a random data key (DK) per profile seals each secret\n * field, and is stored only wrapped under a key derived from the passphrase (KEK). The passphrase never encrypts\n * data directly, so changing it rewraps 32 bytes and rewrites nothing else.\n */\nexport interface ProfileKeyRecord {\n format: \"ghostly-profile-key\";\n version: 1;\n kdf: { name: \"PBKDF2-SHA256\"; iterations: number; salt: string };\n cipher: { name: \"AES-256-GCM\"; iv: string };\n /** The profile id, empty for the default: the record opens only in its own profile's slot. */\n profile: string;\n ciphertext: string;\n}\n/** A field sealed under DK. Version 1 is the `{version:1,salt,iv,ciphertext}` seed sealed with a device key. */\nexport interface SealedField { v: 2; iv: string; ct: string }\n/**\n * Where a sealed field lives: a ciphertext moved to another database, store, record or field fails to open instead\n * of being read as that one. `db` is `local` for local storage.\n */\nexport interface FieldBinding { db: string; store: string; key: string; field: string }\n\nconst ITERATIONS = 600_000;\nconst MAX_ITERATIONS = 10_000_000;\nconst DK_BYTES = 32;\nconst TAG_BYTES = 16;\n\nasync function kekFrom(passphrase: string, salt: Uint8Array, iterations: number): Promise<CryptoKey> {\n const material = await crypto.subtle.importKey(\"raw\", new TextEncoder().encode(passphrase), \"PBKDF2\", false, [\"deriveKey\"]);\n return crypto.subtle.deriveKey({ name: \"PBKDF2\", hash: \"SHA-256\", salt: salt as BufferSource, iterations }, material, { name: \"AES-GCM\", length: 256 }, false, [\"encrypt\", \"decrypt\", \"unwrapKey\"]);\n}\n\n/** The clear header is the wrap's associated data, `profile` included: changing any of it makes the record fail to open. */\nconst header = (r: Omit<ProfileKeyRecord, \"ciphertext\">) =>\n new TextEncoder().encode([r.format, r.version, r.kdf.name, r.kdf.iterations, r.kdf.salt, r.cipher.name, r.cipher.iv, r.profile].join(\"\\n\"));\n\nconst importDataKey = (raw: Uint8Array) => crypto.subtle.importKey(\"raw\", raw as BufferSource, { name: \"AES-GCM\" }, false, [\"encrypt\", \"decrypt\"]);\n\nfunction checkPassphrase(passphrase: string) {\n if (passphrase.length < 12) throw new Error(\"Use at least 12 characters for the profile passphrase\");\n}\n\nasync function wrap(raw: Uint8Array, passphrase: string, profile: string): Promise<ProfileKeyRecord> {\n const salt = crypto.getRandomValues(new Uint8Array(16)), iv = crypto.getRandomValues(new Uint8Array(12));\n const clear = { format: \"ghostly-profile-key\", version: 1, kdf: { name: \"PBKDF2-SHA256\", iterations: ITERATIONS, salt: toBase64Url(salt) }, cipher: { name: \"AES-256-GCM\", iv: toBase64Url(iv) }, profile } as const;\n const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv, additionalData: header(clear) as BufferSource }, await kekFrom(passphrase, salt, ITERATIONS), raw as BufferSource));\n return { ...clear, ciphertext: toBase64Url(ciphertext) };\n}\n\n/** Refuses what this version can't read before any KDF runs, as backups do. */\nfunction checked(record: ProfileKeyRecord, profile: string) {\n if (record?.format !== \"ghostly-profile-key\") throw new Error(\"This is not a Ghostly profile key\");\n if (record.version !== 1) throw new Error(\"This profile key comes from a newer Ghostly; update to open it\");\n if (record.kdf?.name !== \"PBKDF2-SHA256\" || !Number.isInteger(record.kdf.iterations) || record.kdf.iterations < ITERATIONS || record.kdf.iterations > MAX_ITERATIONS || record.cipher?.name !== \"AES-256-GCM\") throw new Error(\"Unsupported profile key encryption\");\n if (typeof record.profile !== \"string\" || record.profile !== profile) throw new Error(\"This profile key belongs to another profile\");\n const salt = fromBase64Url(record.kdf.salt), iv = fromBase64Url(record.cipher.iv), ciphertext = fromBase64Url(record.ciphertext);\n if (salt.length !== 16 || iv.length !== 12 || ciphertext.length !== DK_BYTES + TAG_BYTES) throw new Error(\"Unsupported profile key encryption\");\n return { salt, iv, ciphertext };\n}\n\n/** Turning encryption on: a fresh DK, wrapped under the passphrase, and the DK itself as a key that can't be read back. */\nexport async function createProfileKey(passphrase: string, profile: string): Promise<{ record: ProfileKeyRecord; key: CryptoKey }> {\n checkPassphrase(passphrase);\n const raw = crypto.getRandomValues(new Uint8Array(DK_BYTES));\n try { return { record: await wrap(raw, passphrase, profile), key: await importDataKey(raw) }; } finally { raw.fill(0); }\n}\n\n/** The start gate: the DK as a non-extractable key, or \"Wrong passphrase\" with nothing else read. */\nexport async function unlockProfileKey(record: ProfileKeyRecord, passphrase: string, profile: string): Promise<CryptoKey> {\n const { salt, iv, ciphertext } = checked(record, profile);\n const kek = await kekFrom(passphrase, salt, record.kdf.iterations);\n try {\n return await crypto.subtle.unwrapKey(\"raw\", ciphertext as BufferSource, kek, { name: \"AES-GCM\", iv: iv as BufferSource, additionalData: header(record) as BufferSource }, { name: \"AES-GCM\" }, false, [\"encrypt\", \"decrypt\"]);\n } catch { throw new Error(\"Wrong passphrase\"); }\n}\n\n/** Change passphrase: the same DK under a new KEK, salt and nonce. No sealed field changes. */\nexport async function rewrapProfileKey(record: ProfileKeyRecord, passphrase: string, next: string, profile: string): Promise<ProfileKeyRecord> {\n checkPassphrase(next);\n const { salt, iv, ciphertext } = checked(record, profile);\n let raw: Uint8Array;\n try {\n raw = new Uint8Array(await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: iv as BufferSource, additionalData: header(record) as BufferSource }, await kekFrom(passphrase, salt, record.kdf.iterations), ciphertext as BufferSource));\n } catch { throw new Error(\"Wrong passphrase\"); }\n try { return await wrap(raw, next, profile); } finally { raw.fill(0); }\n}\n\n/**\n * Only the record key can hold a newline: the other parts come from the code, so the joined binding still reads one\n * way (the first two lines, the last line, and the key between them).\n */\nfunction binding(b: FieldBinding): Uint8Array {\n for (const part of [b.db, b.store, b.field]) if (!part || part.includes(\"\\n\")) throw new Error(\"Invalid sealed field binding\");\n return new TextEncoder().encode([\"ghostly-field/2\", b.db, b.store, b.key, b.field].join(\"\\n\"));\n}\n\nexport function isSealedField(value: unknown): value is SealedField {\n const v = value as Partial<SealedField> | null;\n return !!v && typeof v === \"object\" && v.v === 2 && typeof v.iv === \"string\" && typeof v.ct === \"string\";\n}\n\n/** Seals one field under DK with a fresh random 96-bit nonce and no KDF per field. */\nexport async function sealField(key: CryptoKey, where: FieldBinding, value: string): Promise<SealedField> {\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const ct = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv, additionalData: binding(where) as BufferSource }, key, new TextEncoder().encode(value)));\n return { v: 2, iv: toBase64Url(iv), ct: toBase64Url(ct) };\n}\n\n/** Opens a field sealed for exactly this place under this DK; anything else fails instead of opening wrong. */\nexport async function openField(key: CryptoKey, where: FieldBinding, sealed: SealedField): Promise<string> {\n if (!isSealedField(sealed)) throw new Error(\"Unsupported sealed field version\");\n const aad = binding(where);\n try {\n const iv = fromBase64Url(sealed.iv);\n if (iv.length !== 12) throw new Error(\"nonce\");\n return new TextDecoder().decode(await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: iv as BufferSource, additionalData: aad as BufferSource }, key, fromBase64Url(sealed.ct) as BufferSource));\n } catch { throw new Error(\"A sealed field could not be opened: it was changed, or it belongs to another record\"); }\n}\n","import { isSealedField, openField, sealField, type FieldBinding, type SealedField } from \"../shared/profileKey\";\nimport { newDeviceKey, sealSeed, unsealSeed, type EncryptedSeed } from \"./paymentAdapters/persistence\";\n\n/** Version 1: sealed under a random key stored beside it. It keeps a secret from a log, not from a reader of the profile. */\nexport interface DeviceSealed { sealed: EncryptedSeed; deviceKey: string }\n/** A secret the engine keeps: version 1 while the profile is not encrypted, version 2 under its data key once it is. */\nexport type SealedSecret = DeviceSealed | SealedField;\n/**\n * Where a secret belongs, in the peer database (WISP 04, Encrypted profile): its store, its own id (stable when the\n * secret moves inside its record, as a proof key does into the revocations) and what it is.\n */\nexport type SecretPlace = Omit<FieldBinding, \"db\">;\n\nconst PEER_DB = \"ghostly\";\n\n/**\n * The profile's data key (DK), when the profile is encrypted and unlocked: the one slot the engine owns. A\n * non-extractable key; nothing writes it anywhere. Empty, every secret is sealed as today (version 1).\n */\nlet slot: CryptoKey | null = null;\n/**\n * The profile's migration is over (no `migrating` mark): a sealed place then takes version 2 only. A version 1 or plain\n * value there was put by someone who could write the profile's database but not read it, and is refused.\n */\nlet sealedOnly = false;\nconst onDrop = new Set<() => void>();\nconst LOCKED = \"This profile is locked. Enter its passphrase first.\";\n\nexport function setDataKey(key: CryptoKey): void { slot = key; }\nexport function hasDataKey(): boolean { return slot !== null; }\n/** Off until the migration that seals every place has ended; set by it. */\nexport function setSealedOnly(on: boolean): void { sealedOnly = on; }\n/** Whether a sealed place may still hold a version 1 or plain value. */\nexport function takesUnsealed(): boolean { return !(slot && sealedOnly); }\n/** \"Lock and stop\", or a profile switch: the key goes, and so does every secret opened with it and kept in memory. */\nexport function dropDataKey(): void {\n slot = null;\n sealedOnly = false;\n for (const drop of [...onDrop]) drop();\n}\n/** A cache of opened secrets empties itself when the key goes. Returns the way to stop listening. */\nexport function whenDataKeyDropped(drop: () => void): () => void {\n onDrop.add(drop);\n return () => { onDrop.delete(drop); };\n}\n\nexport async function sealSecret(value: string, at: SecretPlace): Promise<SealedSecret> {\n if (slot) return sealField(slot, { db: PEER_DB, ...at }, value);\n const deviceKey = newDeviceKey();\n return { sealed: await sealSeed(value, deviceKey), deviceKey };\n}\n\n/** Version 2 only, for a field the database layer seals: refused while the profile is locked, never version 1. */\nexport async function sealPlace(value: string, at: SecretPlace): Promise<SealedField> {\n if (!slot) throw new Error(LOCKED);\n return sealField(slot, { db: PEER_DB, ...at }, value);\n}\n\n/** Reads both versions: a profile being encrypted holds some of each until its migration ends. */\nexport async function openSecret(secret: SealedSecret, at: SecretPlace): Promise<string> {\n if (!isSealedField(secret)) {\n if (!takesUnsealed()) throw new Error(\"A secret of this profile was not sealed with its key\");\n return unsealSeed(secret.sealed, secret.deviceKey);\n }\n if (!slot) throw new Error(LOCKED);\n return openField(slot, { db: PEER_DB, ...at }, secret);\n}\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex, utf8ToBytes } from \"@noble/hashes/utils.js\";\nimport { STORES } from \"../shared/idb\";\nimport { isSealedField, type SealedField } from \"../shared/profileKey\";\nimport { hasDataKey, openSecret, sealPlace, takesUnsealed, type SecretPlace } from \"./dataKey\";\n\n/**\n * Phase 1 of the encrypted profile (WISP 04, What is encrypted): the fields of the peer database that let someone act\n * as the person or spend, by store, as paths into the row. With the data key set they are written sealed (version 2,\n * bound to the store, the row's key and the path) and opened as they are read; without it, rows are written and read\n * as they always were. A field is sealed as its JSON, so an object (transport seeds, epoch secrets) is one field.\n */\nconst FIELDS: Record<string, readonly string[]> = {\n [STORES.links]: [\"seedB64\", \"encKeyB64\", \"participationSeed\", \"transportSeeds\", \"inviteCode\", \"pairedPeerKey\", \"peerTrust.verifiedKey\", \"ratchetState\"],\n [STORES.groups]: [\"invitation.seedB64\", \"entry.seedB64\", \"joining.seedB64\", \"state.seedB64\", \"state.secrets\", \"community.seedB64\", \"community.secrets\", \"community.entry.seedB64\", \"community.rv\"],\n [STORES.swaps]: [\"swap\", \"token\"],\n [STORES.melts]: [\"secrets\", \"outputs\"],\n // A sent token kept for Take it back, the outputs of a paid invoice not minted yet, and a Cashu review's swap and token.\n [STORES.payments]: [\"token\"],\n [STORES.quotes]: [\"outputs\"],\n [STORES.intents]: [\"prepared.swap\", \"prepared.token\"],\n};\n/** A group removed and invited again keeps the group it was (`previous`), with secrets of its own. */\nconst NESTED: Record<string, string> = { [STORES.groups]: \"previous\" };\n\n/**\n * A proof's secret is its row's key (`keyPath: \"secret\"`), and a sealed value can't be one: a sealed proof is kept under\n * this hash of its secret, the secret itself sealed beside it. The hash, not the secret, can be found again inside a\n * transaction, where WebCrypto can't be waited for.\n */\nexport const proofKey = (secret: string): string => bytesToHex(sha256(utf8ToBytes(`ghostly-proof/1\\n${secret}`)));\nconst SEALED_SECRET = \"sealedSecret\";\n\ntype Row = Record<string, unknown>;\ntype Seal = (json: string, at: SecretPlace) => SealedField;\n\nconst keyOf = (store: string, row: Row) =>\n String(store === STORES.melts || store === STORES.quotes ? row.quote : store === STORES.intents ? read(row, \"review.id\") : row.id);\n\nfunction read(row: Row, path: string): unknown {\n return path.split(\".\").reduce<unknown>((at, part) => (at && typeof at === \"object\" ? (at as Row)[part] : undefined), row);\n}\n/** The row with `value` at `path`, copied along the way: the caller's row is never changed. */\nfunction written(row: Row, [part, ...rest]: string[], value: unknown): Row {\n return { ...row, [part]: rest.length ? written(row[part] as Row, rest, value) : value };\n}\n\n/** Every phase 1 value of a row that is there, with its path. */\nfunction places(store: string, row: Row, prefix = \"\"): { path: string; value: unknown }[] {\n const found = (FIELDS[store] ?? []).map((path) => ({ path: prefix + path, value: read(row, path) })).filter(({ value }) => value !== undefined);\n const nested = NESTED[store] && row[NESTED[store]];\n return nested && typeof nested === \"object\" ? [...found, ...places(store, nested as Row, `${prefix}${NESTED[store]}.`)] : found;\n}\n\nfunction sealWith<T>(store: string, value: T, seal: Seal): T {\n const row = value as Row;\n if (store === STORES.proofs) {\n if (row[SEALED_SECRET] !== undefined) return value;\n const secret = String(row.secret), key = proofKey(secret);\n return { ...row, secret: key, [SEALED_SECRET]: seal(JSON.stringify(secret), { store, key, field: \"secret\" }) } as T;\n }\n const key = keyOf(store, row);\n let out = row;\n for (const { path, value: at } of places(store, row)) {\n if (!isSealedField(at)) out = written(out, path.split(\".\"), seal(JSON.stringify(at), { store, key, field: path }));\n }\n return out as T;\n}\n\nconst slotOf = (json: string, at: SecretPlace) => [at.store, at.key, at.field, json].join(\"\\n\");\n\n/**\n * Seals made ahead of a transaction, for `row` to use inside it: IndexedDB commits a transaction that waits for\n * anything else, WebCrypto included. Whether rows are sealed is fixed when this is made, so a key dropped meanwhile\n * makes a write fail, never go out in the clear.\n */\nexport class RowSeals {\n /** Seals are made one batch after another, so writes that seal first are saved in the order they were asked for. */\n private static turn: Promise<unknown> = Promise.resolve();\n readonly on = hasDataKey();\n private ready = new Map<string, SealedField>();\n\n /** What these rows (or the proofs of these secrets) hold, sealed now. */\n async prepare(store: string, rows: readonly object[]): Promise<this> {\n if (!this.on) return this;\n const wanted = new Map<string, [string, SecretPlace]>();\n for (const row of rows) sealWith(store, row, (json, at) => { wanted.set(slotOf(json, at), [json, at]); return { v: 2, iv: \"\", ct: \"\" }; });\n const sealing = RowSeals.turn.then(async () => {\n for (const [slot, [json, at]] of wanted) if (!this.ready.has(slot)) this.ready.set(slot, await sealPlace(json, at));\n });\n RowSeals.turn = sealing.catch(() => {});\n await sealing;\n return this;\n }\n\n /** The row as it is written. Throws for a value not prepared: its transaction aborts, and nothing goes out in the clear. */\n row<T>(store: string, row: T): T {\n if (!this.on) return row;\n return sealWith(store, row, (json, at) => {\n const sealed = this.ready.get(slotOf(json, at));\n if (!sealed) throw new Error(\"A secret was not sealed before it was saved\");\n return sealed;\n });\n }\n}\n\nexport async function sealRow<T extends object>(store: string, row: T): Promise<T> {\n return (await new RowSeals().prepare(store, [row])).row(store, row);\n}\n\n/**\n * The store as a transaction's work sees it: what it puts is sealed from `seals`, and a proof is found by its secret.\n * Without the data key, the store itself.\n */\nexport function sealedStore(store: IDBObjectStore, seals: RowSeals): IDBObjectStore {\n if (!seals.on) return store;\n const proofs = store.name === STORES.proofs;\n return new Proxy(store, {\n get(target, name) {\n if (name === \"put\") return (row: object, ...key: [IDBValidKey?]) => target.put(seals.row(target.name, row), ...key);\n // A proof stored before the profile was encrypted is kept under its secret until the migration reseals it.\n if (proofs && name === \"delete\") return (secret: string) => { target.delete(secret); return target.delete(proofKey(secret)); };\n if (proofs && name === \"get\") return (secret: string) => target.get(proofKey(secret));\n const value: unknown = Reflect.get(target, name, target);\n return typeof value === \"function\" ? value.bind(target) : value;\n },\n });\n}\n\nfunction unsealed(): void {\n if (!takesUnsealed()) throw new Error(\"A secret of this profile was not sealed with its key\");\n}\n\n/** The row as the engine uses it: every sealed value opened, where it was. */\nexport async function openRow<T>(store: string, value: T): Promise<T> {\n if (!hasDataKey() || !value) return value;\n const row = value as Row;\n if (store === STORES.proofs) {\n const sealed = row[SEALED_SECRET];\n if (sealed === undefined) { unsealed(); return value; }\n const key = String(row.secret), secret = JSON.parse(await openSecret(sealed as SealedField, { store, key, field: \"secret\" })) as string;\n if (proofKey(secret) !== key) throw new Error(\"A sealed field could not be opened: it was changed, or it belongs to another record\");\n const { [SEALED_SECRET]: _sealed, ...rest } = row;\n return { ...rest, secret } as T;\n }\n const key = keyOf(store, row);\n let out = row;\n for (const { path, value: at } of places(store, row)) {\n if (!isSealedField(at)) { unsealed(); continue; }\n out = written(out, path.split(\".\"), JSON.parse(await openSecret(at, { store, key, field: path })));\n }\n return out as T;\n}\n\nexport function openRows<T>(store: string, rows: T[]): Promise<T[]> {\n return hasDataKey() ? Promise.all(rows.map((row) => openRow(store, row))) : Promise.resolve(rows);\n}\n","import { engineError, engineText } from \"@ghostly/core\";\nimport { STORES, openDb, store, transact, wrap } from \"../../shared/idb\";\nimport { openRow, openRows, sealRow } from \"../sealedRows\";\nimport type { IntentRepository, SavedIntent } from \"./coordinator\";\n/**\n * A USDT payment is one transaction at one account nonce. Another payment from the same account and chain that is\n * submitted or of unknown outcome holds its nonce until it confirms. A review made after it was sent took the next\n * nonce and may go at once. One made before (or read from an RPC that had not seen it yet) has the same or a lower\n * nonce: sent, it would replace the earlier transaction or be dropped, so it is refused. A row with no nonce refuses.\n */\nfunction nonceTaken(review:SavedIntent[\"review\"],intents:SavedIntent[]):boolean {\n if(review.method!==\"usdt\")return false;\n const from=review.evm?.from?.toLowerCase(), nonce=review.evm?.nonce;\n return intents.some(({review:other})=>other.id!==review.id && other.method===\"usdt\" && other.chainId===review.chainId && other.evm?.from?.toLowerCase()===from && [\"submitted\",\"unknown\"].includes(other.state)\n && !(typeof nonce===\"number\" && typeof other.evm?.nonce===\"number\" && nonce>other.evm.nonce));\n}\n/**\n * A Cashu review's swap and token are sealed when the profile is encrypted (sealedRows): they are read here opened.\n * `claim` and `cancel` change only the review, so they put back the row as it was read, sealed fields and all.\n */\nexport const intentRepository: IntentRepository = {\n async get(id) { return openRow(STORES.intents,await wrap<SavedIntent | undefined>((await store(STORES.intents,\"readonly\")).get(id))); },\n async list() { return openRows(STORES.intents,await wrap<SavedIntent[]>((await store(STORES.intents,\"readonly\")).getAll())); },\n async put(intent) { const row=await sealRow(STORES.intents,intent); await transact([STORES.intents],s=>{s[STORES.intents].put(row);}); },\n async claim(id) {\n const tx=(await openDb()).transaction(STORES.intents,\"readwrite\");\n return new Promise<SavedIntent>((resolve,reject)=>{\n let saved:SavedIntent;\n let reason=engineText(\"alreadySubmitted\");\n const request=tx.objectStore(STORES.intents).getAll();\n request.onsuccess=()=>{\n const intents:SavedIntent[]=request.result;\n saved=intents.find(item=>item.review.id===id)!;\n if(!saved || saved.review.state!==\"pending\") {tx.abort();return;}\n const duplicate=saved.review.requestId && intents.some(({review})=>review.id!==id && review.requestId===saved.review.requestId && review.linkId===saved.review.linkId && [\"submitted\",\"settled\",\"unknown\"].includes(review.state));\n if(duplicate){tx.abort();return;}\n if(nonceTaken(saved.review,intents)){reason=engineText(\"sentAfterReview\");tx.abort();return;}\n saved.review={...saved.review,state:\"submitted\",error:undefined,submittedAt:Date.now()};\n tx.objectStore(STORES.intents).put(saved);\n };\n tx.oncomplete=()=>resolve(openRow(STORES.intents,saved));\n tx.onabort=tx.onerror=()=>reject(new Error(reason));\n });\n },\n async cancel(id) {\n const tx=(await openDb()).transaction(STORES.intents,\"readwrite\");\n return new Promise<SavedIntent>((resolve,reject)=>{\n let saved:SavedIntent;\n const request=tx.objectStore(STORES.intents).get(id);\n request.onsuccess=()=>{\n saved=request.result;\n if(!saved || saved.review.state!==\"pending\"){tx.abort();return;}\n saved.review={...saved.review,state:\"cancelled\"};\n tx.objectStore(STORES.intents).put(saved);\n };\n tx.oncomplete=()=>resolve(openRow(STORES.intents,saved));\n tx.onabort=tx.onerror=()=>reject(engineError(\"cannotCancelSubmitted\"));\n });\n },\n};\n/** Key for a wallet that needs no password: its seed is protected like the Cashu proofs in the same database. */\nexport function newDeviceKey():string {return btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32)))).replace(/=+$/,\"\");}\nexport interface EncryptedSeed {version:1;salt:number[];iv:number[];ciphertext:number[]}\nasync function passwordKey(password:string,salt:Uint8Array<ArrayBuffer>) {\n const material=await crypto.subtle.importKey(\"raw\",new TextEncoder().encode(password),\"PBKDF2\",false,[\"deriveKey\"]);\n return crypto.subtle.deriveKey({name:\"PBKDF2\",hash:\"SHA-256\",salt,iterations:600000},material,{name:\"AES-GCM\",length:256},false,[\"encrypt\",\"decrypt\"]);\n}\nexport async function sealSeed(seed:string,password:string):Promise<EncryptedSeed> {\n if(password.length<12)throw new Error(\"Use at least 12 characters for the wallet password\");\n const salt=crypto.getRandomValues(new Uint8Array(16)),iv=crypto.getRandomValues(new Uint8Array(12));\n const ciphertext=await crypto.subtle.encrypt({name:\"AES-GCM\",iv},await passwordKey(password,salt),new TextEncoder().encode(seed));\n return {version:1,salt:[...salt],iv:[...iv],ciphertext:[...new Uint8Array(ciphertext)]};\n}\nexport async function unsealSeed(seed:EncryptedSeed,password:string):Promise<string> {\n if(seed.version!==1)throw new Error(\"Unsupported wallet backup version\");\n try {return new TextDecoder().decode(await crypto.subtle.decrypt({name:\"AES-GCM\",iv:new Uint8Array(seed.iv)},await passwordKey(password,new Uint8Array(seed.salt)),new Uint8Array(seed.ciphertext)));}\n catch {throw new Error(\"Could not unlock the wallet. Check the password and backup.\");}\n}\n","import { engineText } from \"@ghostly/core\";\n\n/**\n * A request's failure as a person says it, when the browser's own words say nothing: a request that timed out or was\n * given up (\"Fetch is aborted\" in Safari, \"signal timed out\" in Chromium) did not answer in time; one that never left\n * (\"Failed to fetch\", \"Load failed\") could not reach it. `host` names what was asked, when known. Anything else is\n * `null`: its own words are kept.\n */\nexport function networkReason(error: unknown, host?: string): string | null {\n const name = error instanceof Error ? error.name : \"\";\n const text = error instanceof Error ? error.message : String(error);\n if (name === \"AbortError\" || name === \"TimeoutError\" || /^(fetch is aborted|signal timed out|signal is aborted without reason|the (user|operation) (aborted a request|was aborted)\\.?|this operation was aborted|the operation timed out\\.?)$/i.test(text.trim()))\n return host ? engineText(\"hostTimedOut\", { host }) : engineText(\"networkTimedOut\");\n if (/^(failed to fetch|load failed|fetch failed|networkerror when attempting to fetch resource\\.?|network request failed)$/i.test(text.trim()))\n return host ? engineText(\"hostUnreachable\", { host }) : engineText(\"networkUnreachable\");\n return null;\n}\n\n/** A request URL's host, for a reason that names it; the URL itself when it does not parse. */\nexport function rpcHost(url: string): string {\n try { return new URL(url).host; } catch { return url; }\n}\n"],"mappings":";;;;;;;;;;AA6FA,SAAS,QAAQ,GAA6B;CAC5C,KAAK,MAAM,QAAQ;EAAC,EAAE;EAAI,EAAE;EAAO,EAAE;CAAK,GAAG,IAAI,CAAC,QAAQ,KAAK,SAAS,IAAI,GAAG,MAAM,IAAI,MAAM,8BAA8B;CAC7H,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO;EAAC;EAAmB,EAAE;EAAI,EAAE;EAAO,EAAE;EAAK,EAAE;CAAK,CAAC,CAAC,KAAK,IAAI,CAAC;AAC/F;AAEA,SAAgB,cAAc,OAAsC;CAClE,MAAM,IAAI;CACV,OAAO,CAAC,CAAC,KAAK,OAAO,MAAM,YAAY,EAAE,MAAM,KAAK,OAAO,EAA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 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { _d as sanitizeDisplayText, jn as decodeBolt11 } from "./src-DjVj2ynY.js";
|
|
2
2
|
import { t as NothingSpentError } from "./types-Clyb52K2.js";
|
|
3
|
-
import { i as parseNwcUri, n as nwcAlias } from "./nwcProvider-
|
|
3
|
+
import { i as parseNwcUri, n as nwcAlias } from "./nwcProvider-DYHkd0iu.js";
|
|
4
4
|
import { sha256 } from "@noble/hashes/sha2.js";
|
|
5
5
|
import * as nip04 from "nostr-tools/nip04";
|
|
6
6
|
import * as nip44 from "nostr-tools/nip44";
|
|
@@ -610,4 +610,4 @@ var NwcLightning = class NwcLightning {
|
|
|
610
610
|
//#endregion
|
|
611
611
|
export { NwcLightning };
|
|
612
612
|
|
|
613
|
-
//# sourceMappingURL=nwc-
|
|
613
|
+
//# sourceMappingURL=nwc-CtZypDcv.js.map
|