@ghostlytools/cli 1.9.0 → 1.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -27
- package/SKILL.md +7 -3
- package/dist/assets/api-BOWLZYXM.js +3 -0
- package/dist/assets/{api-DFCgr6RH.js → api-Bi6hCcwG.js} +100 -47
- package/dist/assets/api-Bi6hCcwG.js.map +1 -0
- package/dist/assets/{apiKit-CCavJJcl.js → apiKit-DzXHZojD.js} +26 -9
- package/dist/assets/apiKit-DzXHZojD.js.map +1 -0
- package/dist/assets/{apps-B7o2BPj6.js → apps-0Ks6KjqS.js} +1 -1
- package/dist/assets/{apps-DmxEG147.js → apps-DIQbzG08.js} +33 -10
- package/dist/assets/apps-DIQbzG08.js.map +1 -0
- package/dist/assets/{arkade-DtYR9H0c.js → arkade-zozCldAE.js} +2 -2
- package/dist/assets/{arkade-DtYR9H0c.js.map → arkade-zozCldAE.js.map} +1 -1
- package/dist/assets/{backup-YIB2XIES.js → backup-BL49Kt-T.js} +7 -6
- package/dist/assets/{backup-YIB2XIES.js.map → backup-BL49Kt-T.js.map} +1 -1
- package/dist/assets/{backup-BserdrNk.js → backup-BvIFcZM7.js} +1 -1
- package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js.map +1 -1
- package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js.map +1 -1
- package/dist/assets/{blobFiles-DOQDRdDI.js → blobFiles-BnjN_Vrz.js} +3 -3
- package/dist/assets/{blobFiles-DOQDRdDI.js.map → blobFiles-BnjN_Vrz.js.map} +1 -1
- package/dist/assets/buttons-CAW5v5EE.js +332 -0
- package/dist/assets/buttons-CAW5v5EE.js.map +1 -0
- package/dist/assets/buttons-oJI5mHSL.js +2 -0
- package/dist/assets/childEnv-BVOQK9EA.js +21 -0
- package/dist/assets/childEnv-BVOQK9EA.js.map +1 -0
- package/dist/assets/client-CyApKBEw.js +473 -0
- package/dist/assets/client-CyApKBEw.js.map +1 -0
- package/dist/assets/codec-DqFxxB_q.js +13 -0
- package/dist/assets/codec-DqFxxB_q.js.map +1 -0
- package/dist/assets/{endpoint-BdaeBw2L.js → endpoint-DWHkXWVM.js} +101 -16
- package/dist/assets/endpoint-DWHkXWVM.js.map +1 -0
- package/dist/assets/{envelope-Dt75vrmY.js → envelope-CMUgz31I.js} +3 -12
- package/dist/assets/envelope-CMUgz31I.js.map +1 -0
- package/dist/assets/fedimint_client_wasm_bg-BtHHlFpp.js.map +1 -1
- package/dist/assets/{fileBytes-BPDKufla.js → fileBytes-DMzrIdCu.js} +1 -1
- package/dist/assets/{fileBytes-DNgrRL0R.js → fileBytes-DjBYYyXT.js} +3 -3
- package/dist/assets/{fileBytes-DNgrRL0R.js.map → fileBytes-DjBYYyXT.js.map} +1 -1
- package/dist/assets/{fileBytes-Q3ehcEr8.js → fileBytes-Douk1yOp.js} +2 -2
- package/dist/assets/{fileBytes-Q3ehcEr8.js.map → fileBytes-Douk1yOp.js.map} +1 -1
- package/dist/assets/fileBytesIdb-CD5Uv490.js +2 -0
- package/dist/assets/{fileBytesIdb-Dm1EyEbT.js → fileBytesIdb-CkClu9YI.js} +3 -3
- package/dist/assets/{fileBytesIdb-Dm1EyEbT.js.map → fileBytesIdb-CkClu9YI.js.map} +1 -1
- package/dist/assets/{fileBytesOpfs-ZGD21c4Q.js → fileBytesOpfs-WryQuOgK.js} +3 -3
- package/dist/assets/{fileBytesOpfs-ZGD21c4Q.js.map → fileBytesOpfs-WryQuOgK.js.map} +1 -1
- package/dist/assets/{fixedHosts-B598JzbC.js → fixedHosts-C2hdCfzK.js} +4 -4
- package/dist/assets/{fixedHosts-B598JzbC.js.map → fixedHosts-C2hdCfzK.js.map} +1 -1
- package/dist/assets/{groupFiles-FXel6zIc.js → groupFiles-BAQIt_bJ.js} +404 -161
- package/dist/assets/groupFiles-BAQIt_bJ.js.map +1 -0
- package/dist/assets/{host-DIBeK_c_.js → host-CaRlDMTd.js} +206 -49
- package/dist/assets/host-CaRlDMTd.js.map +1 -0
- package/dist/assets/{hyperdhtRelay-D185dETu.js → hyperdhtRelay-BxADl3SG.js} +2 -2
- package/dist/assets/{hyperdhtRelay-D185dETu.js.map → hyperdhtRelay-BxADl3SG.js.map} +1 -1
- package/dist/assets/{idb-BkOJES5_.js → idb-BHsAqENE.js} +37 -6
- package/dist/assets/idb-BHsAqENE.js.map +1 -0
- package/dist/assets/{irohWeb-BSv_BWyG.js → irohWeb-D2sh6EWp.js} +65 -7
- package/dist/assets/irohWeb-D2sh6EWp.js.map +1 -0
- package/dist/assets/{main-BbhfMTt8.js → main-Bc4Ow56Z.js} +221 -287
- package/dist/assets/main-Bc4Ow56Z.js.map +1 -0
- package/dist/assets/{mainline-9Vc3c3SA.js → mainline-DWh4Ccri.js} +2 -2
- package/dist/assets/{mainline-9Vc3c3SA.js.map → mainline-DWh4Ccri.js.map} +1 -1
- package/dist/assets/networkReason-DT_D_Wpc.js +474 -0
- package/dist/assets/networkReason-DT_D_Wpc.js.map +1 -0
- package/dist/assets/{nwc-QX3Yt1Sb.js → nwc-DoSEhUKb.js} +3 -3
- package/dist/assets/{nwc-QX3Yt1Sb.js.map → nwc-DoSEhUKb.js.map} +1 -1
- package/dist/assets/{nwcProvider-CzX3xH47.js → nwcProvider-CGWqUjpB.js} +2 -2
- package/dist/assets/{nwcProvider-CzX3xH47.js.map → nwcProvider-CGWqUjpB.js.map} +1 -1
- package/dist/assets/{ownDid-D8z5gwGI.js → ownDid-CbGjRLBn.js} +3 -3
- package/dist/assets/ownDid-CbGjRLBn.js.map +1 -0
- package/dist/assets/{profiles-MFtCmJwK.js → profiles-DgIfvBeN.js} +47 -4
- package/dist/assets/profiles-DgIfvBeN.js.map +1 -0
- package/dist/assets/{registry-B2Dtnibo.js → registry-BSyxGjN6.js} +11 -9
- package/dist/assets/registry-BSyxGjN6.js.map +1 -0
- package/dist/assets/{registry-PTtBMaYZ.js → registry-C5cn80Rw.js} +1 -1
- package/dist/assets/{resolve-ZxVzwFNA.js → resolve-D-9YRFhl.js} +2 -2
- package/dist/assets/{resolve-ZxVzwFNA.js.map → resolve-D-9YRFhl.js.map} +1 -1
- package/dist/assets/{restoredRows-BCRCjhdF.js → restoredRows-CRYwIx3g.js} +2 -2
- package/dist/assets/{restoredRows-BCRCjhdF.js.map → restoredRows-CRYwIx3g.js.map} +1 -1
- package/dist/assets/{buttons-CuRfKnPI.js → secretGuard-CSVNxXVW.js} +80 -330
- package/dist/assets/secretGuard-CSVNxXVW.js.map +1 -0
- package/dist/assets/secretGuard-Q2BKq0q0.js +2 -0
- package/dist/assets/{server-Dw1o8z1o.js → server-BufntkX8.js} +1734 -369
- package/dist/assets/server-BufntkX8.js.map +1 -0
- package/dist/assets/{src-BD8RBVEp.js → src-CCt5s4DK.js} +3073 -1890
- package/dist/assets/src-CCt5s4DK.js.map +1 -0
- package/dist/assets/{sshForges-DWrESWkK.js → sshForges-D8CPaIbR.js} +16 -9
- package/dist/assets/{sshForges-DWrESWkK.js.map → sshForges-D8CPaIbR.js.map} +1 -1
- package/dist/assets/{translate-D1uP0q32.js → translate-Cb-6hMhD.js} +17 -12
- package/dist/assets/translate-Cb-6hMhD.js.map +1 -0
- package/dist/assets/{usdt-DhVN8geQ.js → usdt-ds461mzA.js} +3 -3
- package/dist/assets/{usdt-DhVN8geQ.js.map → usdt-ds461mzA.js.map} +1 -1
- package/dist/assets/{words-DdXPkB3n.js → words-B1ylON2h.js} +4 -2
- package/dist/assets/words-B1ylON2h.js.map +1 -0
- package/dist/ghostly.mjs +1 -1
- package/package.json +1 -1
- package/dist/assets/api-DFCgr6RH.js.map +0 -1
- package/dist/assets/api-raWw9j_m.js +0 -3
- package/dist/assets/apiKit-CCavJJcl.js.map +0 -1
- package/dist/assets/apps-DmxEG147.js.map +0 -1
- package/dist/assets/buttons-CuRfKnPI.js.map +0 -1
- package/dist/assets/buttons-De3LPdSG.js +0 -2
- package/dist/assets/daemonProof-DtrL5lE5.js +0 -236
- package/dist/assets/daemonProof-DtrL5lE5.js.map +0 -1
- package/dist/assets/endpoint-BdaeBw2L.js.map +0 -1
- package/dist/assets/envelope-Dt75vrmY.js.map +0 -1
- package/dist/assets/fileBytesIdb-DZcESfTt.js +0 -2
- package/dist/assets/groupFiles-FXel6zIc.js.map +0 -1
- package/dist/assets/host-DIBeK_c_.js.map +0 -1
- package/dist/assets/idb-BkOJES5_.js.map +0 -1
- package/dist/assets/irohWeb-BSv_BWyG.js.map +0 -1
- package/dist/assets/main-BbhfMTt8.js.map +0 -1
- package/dist/assets/networkReason-BncJ9KSM.js +0 -154
- package/dist/assets/networkReason-BncJ9KSM.js.map +0 -1
- package/dist/assets/ownDid-D8z5gwGI.js.map +0 -1
- package/dist/assets/profiles-MFtCmJwK.js.map +0 -1
- package/dist/assets/registry-B2Dtnibo.js.map +0 -1
- package/dist/assets/server-Dw1o8z1o.js.map +0 -1
- package/dist/assets/src-BD8RBVEp.js.map +0 -1
- package/dist/assets/translate-D1uP0q32.js.map +0 -1
- package/dist/assets/words-DdXPkB3n.js.map +0 -1
|
@@ -1,236 +0,0 @@
|
|
|
1
|
-
import { d as lockPath } from "./profiles-MFtCmJwK.js";
|
|
2
|
-
import { closeSync, lstatSync, openSync, readFileSync, rmSync, writeSync } from "node:fs";
|
|
3
|
-
import { join } from "node:path";
|
|
4
|
-
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
5
|
-
var CALL_RATES = [
|
|
6
|
-
8e3,
|
|
7
|
-
12e3,
|
|
8
|
-
16e3,
|
|
9
|
-
24e3,
|
|
10
|
-
48e3
|
|
11
|
-
];
|
|
12
|
-
var DEFAULT_RATE = 48e3;
|
|
13
|
-
var frameSamples = (rate) => rate * 20 / 1e3;
|
|
14
|
-
var frameBytes = (rate) => frameSamples(rate) * 2;
|
|
15
|
-
var bytesToMs = (rate, bytes) => Math.round(bytes / 2 / rate * 1e3);
|
|
16
|
-
function isCallRate(value) {
|
|
17
|
-
return CALL_RATES.includes(value);
|
|
18
|
-
}
|
|
19
|
-
/** The most a program may queue ahead of the call: five minutes of speech. What goes past it is dropped. */
|
|
20
|
-
var MAX_QUEUE_MS = 3e5;
|
|
21
|
-
/**
|
|
22
|
-
* What the program wrote, waiting to be sent: taken one 20 ms frame per tick, silence when there is nothing, and
|
|
23
|
-
* dropped whole by a flush (barge-in). The program may write any amount at any time, faster than real time too.
|
|
24
|
-
*/
|
|
25
|
-
var PlaybackQueue = class {
|
|
26
|
-
rate;
|
|
27
|
-
now;
|
|
28
|
-
chunks = [];
|
|
29
|
-
head = 0;
|
|
30
|
-
length = 0;
|
|
31
|
-
lastPush = 0;
|
|
32
|
-
frame;
|
|
33
|
-
max;
|
|
34
|
-
silence;
|
|
35
|
-
/** Bytes dropped because the queue was full, since the start. */
|
|
36
|
-
dropped = 0;
|
|
37
|
-
constructor(rate, now = Date.now, maxMs = MAX_QUEUE_MS) {
|
|
38
|
-
this.rate = rate;
|
|
39
|
-
this.now = now;
|
|
40
|
-
this.frame = frameBytes(rate);
|
|
41
|
-
this.max = Math.floor(rate * maxMs / 1e3) * 2;
|
|
42
|
-
this.silence = Buffer.alloc(this.frame);
|
|
43
|
-
}
|
|
44
|
-
/** Adds what the program wrote. Returns the bytes it could not keep (the queue was full). */
|
|
45
|
-
push(chunk) {
|
|
46
|
-
if (!chunk.length) return 0;
|
|
47
|
-
this.lastPush = this.now();
|
|
48
|
-
const room = this.max - this.length;
|
|
49
|
-
const kept = chunk.length <= room ? chunk : chunk.subarray(0, Math.max(0, room));
|
|
50
|
-
const lost = chunk.length - kept.length;
|
|
51
|
-
this.dropped += lost;
|
|
52
|
-
if (kept.length) {
|
|
53
|
-
this.chunks.push(Buffer.from(kept));
|
|
54
|
-
this.length += kept.length;
|
|
55
|
-
}
|
|
56
|
-
return lost;
|
|
57
|
-
}
|
|
58
|
-
/** Queued audio, in milliseconds (whole frames and a partial one). */
|
|
59
|
-
get queuedMs() {
|
|
60
|
-
return bytesToMs(this.rate, this.length - this.length % 2);
|
|
61
|
-
}
|
|
62
|
-
/** One frame to send now, and whether it is the program's audio or silence. */
|
|
63
|
-
next() {
|
|
64
|
-
if (this.length >= this.frame) return {
|
|
65
|
-
frame: this.take(this.frame),
|
|
66
|
-
silent: false
|
|
67
|
-
};
|
|
68
|
-
const whole = this.length - this.length % 2;
|
|
69
|
-
if (whole > 0 && this.now() - this.lastPush >= 60) {
|
|
70
|
-
const frame = Buffer.alloc(this.frame);
|
|
71
|
-
this.take(whole).copy(frame);
|
|
72
|
-
return {
|
|
73
|
-
frame,
|
|
74
|
-
silent: false
|
|
75
|
-
};
|
|
76
|
-
}
|
|
77
|
-
return {
|
|
78
|
-
frame: this.silence,
|
|
79
|
-
silent: true
|
|
80
|
-
};
|
|
81
|
-
}
|
|
82
|
-
/** Drops everything queued; returns how much, in milliseconds. */
|
|
83
|
-
flush() {
|
|
84
|
-
const ms = this.queuedMs;
|
|
85
|
-
this.chunks = [];
|
|
86
|
-
this.head = 0;
|
|
87
|
-
this.length = 0;
|
|
88
|
-
return ms;
|
|
89
|
-
}
|
|
90
|
-
/** Drops up to that much from the front, in whole frames (audio whose time went by); returns how much, in milliseconds. */
|
|
91
|
-
skip(ms) {
|
|
92
|
-
const frames = Math.min(Math.floor(ms / 20), Math.floor(this.length / this.frame));
|
|
93
|
-
if (frames > 0) this.take(frames * this.frame);
|
|
94
|
-
return Math.max(0, frames) * 20;
|
|
95
|
-
}
|
|
96
|
-
take(bytes) {
|
|
97
|
-
const out = Buffer.allocUnsafe(bytes);
|
|
98
|
-
let filled = 0;
|
|
99
|
-
while (filled < bytes) {
|
|
100
|
-
const chunk = this.chunks[0];
|
|
101
|
-
const n = Math.min(bytes - filled, chunk.length - this.head);
|
|
102
|
-
chunk.copy(out, filled, this.head, this.head + n);
|
|
103
|
-
filled += n;
|
|
104
|
-
this.head += n;
|
|
105
|
-
if (this.head === chunk.length) {
|
|
106
|
-
this.chunks.shift();
|
|
107
|
-
this.head = 0;
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
this.length -= bytes;
|
|
111
|
-
return out;
|
|
112
|
-
}
|
|
113
|
-
};
|
|
114
|
-
//#endregion
|
|
115
|
-
//#region src/daemonProof.ts
|
|
116
|
-
/**
|
|
117
|
-
* How a client knows the process on the profile's socket is the profile's daemon (WISP 1100 § Local control API).
|
|
118
|
-
* On Windows the socket is a named pipe whose name follows from the profile's path, and any account of the machine
|
|
119
|
-
* may open that name first; the pipe itself has no owner a client can check. So the daemon writes a fresh random
|
|
120
|
-
* secret in the profile's owner-only folder at every start, and the client sends nothing but a `daemon.hello` with a
|
|
121
|
-
* nonce of its own until the answer proves, over that nonce, that its sender read the secret. Same on every platform.
|
|
122
|
-
*
|
|
123
|
-
* Before even the hello, the daemon speaks first: a greeting that proves, with the same secret, its pid (the
|
|
124
|
-
* profile's lock holder) and the time. The client writes nothing at all until the greeting checks out. A process
|
|
125
|
-
* holding `SeImpersonatePrivilege` that opened the pipe's name first can impersonate the client from the first
|
|
126
|
-
* message it reads (Node's pipe client sets no security quality of service, so the level is SecurityImpersonation),
|
|
127
|
-
* and Windows refuses to impersonate a pipe's client until data has been read from it (ERROR_CANNOT_IMPERSONATE):
|
|
128
|
-
* a client that writes nothing to it cannot be impersonated.
|
|
129
|
-
*/
|
|
130
|
-
var HELLO = "daemon.hello";
|
|
131
|
-
function daemonSecretPath(dir) {
|
|
132
|
-
return join(dir, "daemon.secret");
|
|
133
|
-
}
|
|
134
|
-
/** HMAC-SHA256 over the role's domain and the nonce, hex: a daemon's proof is never a client's, nor one for another nonce. */
|
|
135
|
-
function proof(secret, role, nonce) {
|
|
136
|
-
return createHmac("sha256", secret).update(`ghostly-${role}:${nonce}`).digest("hex");
|
|
137
|
-
}
|
|
138
|
-
function newNonce() {
|
|
139
|
-
return randomBytes(16).toString("hex");
|
|
140
|
-
}
|
|
141
|
-
/**
|
|
142
|
-
* The daemon's: a new secret, 32 random bytes as hex, made 0600 (`wx`, so a file or link put there in the meantime is
|
|
143
|
-
* an error, not something written through). The one a daemon before it left is removed first: whoever could have
|
|
144
|
-
* read that one learns nothing about this one.
|
|
145
|
-
*/
|
|
146
|
-
function newDaemonSecret(dir) {
|
|
147
|
-
const file = daemonSecretPath(dir);
|
|
148
|
-
rmSync(file, { force: true });
|
|
149
|
-
const secret = randomBytes(32);
|
|
150
|
-
const fd = openSync(file, "wx", 384);
|
|
151
|
-
try {
|
|
152
|
-
writeSync(fd, secret.toString("hex") + "\n");
|
|
153
|
-
} finally {
|
|
154
|
-
closeSync(fd);
|
|
155
|
-
}
|
|
156
|
-
return secret;
|
|
157
|
-
}
|
|
158
|
-
/** The daemon's, when it stops: a greeting copied from it proves nothing once it is gone. */
|
|
159
|
-
function removeDaemonSecret(dir) {
|
|
160
|
-
rmSync(daemonSecretPath(dir), { force: true });
|
|
161
|
-
}
|
|
162
|
-
/** The daemon's first line on every connection, before it has read anything. */
|
|
163
|
-
function greeting(secret, pid = process.pid, at = Date.now()) {
|
|
164
|
-
return { greeting: {
|
|
165
|
-
pid,
|
|
166
|
-
at,
|
|
167
|
-
proof: proof(secret, "greeting", `${pid}:${at}`)
|
|
168
|
-
} };
|
|
169
|
-
}
|
|
170
|
-
/**
|
|
171
|
-
* Whether `message` (the first line the client read) is the profile's daemon's greeting: proved with the secret, made
|
|
172
|
-
* within `GREETING_WINDOW_MS` of `now`, by the process that holds the profile's lock, alive and one this user may
|
|
173
|
-
* signal (`process.kill(pid, 0)`: EPERM on Unix for another user's; on Windows libuv opens the process to terminate
|
|
174
|
-
* it, which another account's process normally denies). A greeting copied from a daemon that died fails on its pid,
|
|
175
|
-
* unless a process this user may signal took that pid within the window.
|
|
176
|
-
*/
|
|
177
|
-
function provesGreeting(secret, dir, message, now = Date.now()) {
|
|
178
|
-
const given = message?.greeting;
|
|
179
|
-
if (!given || !Number.isSafeInteger(given.pid) || given.pid <= 0 || !Number.isSafeInteger(given.at)) return false;
|
|
180
|
-
if (typeof given.proof !== "string" || !/^[0-9a-f]{64}$/.test(given.proof)) return false;
|
|
181
|
-
const { pid, at } = given;
|
|
182
|
-
if (Math.abs(now - at) > 1e4) return false;
|
|
183
|
-
if (!timingSafeEqual(Buffer.from(given.proof, "hex"), Buffer.from(proof(secret, "greeting", `${pid}:${at}`), "hex"))) return false;
|
|
184
|
-
return holdsProfile(dir, pid);
|
|
185
|
-
}
|
|
186
|
-
/**
|
|
187
|
-
* Whether a daemon of this release holds the profile: its secret is there (an older release's never writes one, and a
|
|
188
|
-
* daemon removes its own when it stops) and the lock's holder is alive and this user's. One whose greeting is late is
|
|
189
|
-
* busy (its event loop held by one long task), not something else on its socket: the client waits for it.
|
|
190
|
-
*/
|
|
191
|
-
function daemonOfThisRelease(dir) {
|
|
192
|
-
if (!readDaemonSecret(dir)) return false;
|
|
193
|
-
let pid;
|
|
194
|
-
try {
|
|
195
|
-
pid = Number(readFileSync(lockPath(dir), "utf8").trim());
|
|
196
|
-
} catch {
|
|
197
|
-
return false;
|
|
198
|
-
}
|
|
199
|
-
return Number.isSafeInteger(pid) && pid > 0 && holdsProfile(dir, pid);
|
|
200
|
-
}
|
|
201
|
-
function holdsProfile(dir, pid) {
|
|
202
|
-
try {
|
|
203
|
-
if (readFileSync(lockPath(dir), "utf8").trim() !== String(pid)) return false;
|
|
204
|
-
process.kill(pid, 0);
|
|
205
|
-
return true;
|
|
206
|
-
} catch {
|
|
207
|
-
return false;
|
|
208
|
-
}
|
|
209
|
-
}
|
|
210
|
-
/**
|
|
211
|
-
* The client's: the secret the profile's daemon wrote, or null when there is none, or it is not a file of this user's
|
|
212
|
-
* alone (a link, another user's file, one others may read): then it proves nothing. On Windows the file has the
|
|
213
|
-
* folder's ACL (owner-only in the user's home); Node can check no more than that it is a plain file.
|
|
214
|
-
*/
|
|
215
|
-
function readDaemonSecret(dir) {
|
|
216
|
-
const file = daemonSecretPath(dir);
|
|
217
|
-
try {
|
|
218
|
-
const info = lstatSync(file);
|
|
219
|
-
if (!info.isFile()) return null;
|
|
220
|
-
if (process.platform !== "win32" && (process.getuid && info.uid !== process.getuid() || (info.mode & 63) !== 0)) return null;
|
|
221
|
-
const text = readFileSync(file, "utf8").trim();
|
|
222
|
-
return /^[0-9a-f]{64}$/.test(text) ? Buffer.from(text, "hex") : null;
|
|
223
|
-
} catch {
|
|
224
|
-
return null;
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
/** Whether `answer` (the result of a `daemon.hello` with `nonce`) is the daemon's proof over it, in constant time. */
|
|
228
|
-
function provesDaemon(secret, nonce, answer) {
|
|
229
|
-
const given = answer?.proof;
|
|
230
|
-
if (typeof given !== "string" || !/^[0-9a-f]{64}$/.test(given)) return false;
|
|
231
|
-
return timingSafeEqual(Buffer.from(given, "hex"), Buffer.from(proof(secret, "daemon", nonce), "hex"));
|
|
232
|
-
}
|
|
233
|
-
//#endregion
|
|
234
|
-
export { isCallRate as _, newNonce as a, provesGreeting as c, CALL_RATES as d, DEFAULT_RATE as f, frameSamples as g, frameBytes as h, newDaemonSecret as i, readDaemonSecret as l, bytesToMs as m, daemonOfThisRelease as n, proof as o, PlaybackQueue as p, greeting as r, provesDaemon as s, HELLO as t, removeDaemonSecret as u };
|
|
235
|
-
|
|
236
|
-
//# sourceMappingURL=daemonProof-DtrL5lE5.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"daemonProof-DtrL5lE5.js","names":[],"sources":["../../src/calls/pcm.ts","../../src/daemonProof.ts"],"sourcesContent":["/**\n * The audio a call hands to an outside program, and takes from it (WISP 1100 § Calls): raw PCM, signed 16-bit\n * little-endian, mono, at the call's rate, in frames of 20 ms. Opus runs at every one of these rates itself, so\n * nothing is resampled.\n */\nexport const FRAME_MS = 20;\nexport const CALL_RATES = [8000, 12000, 16000, 24000, 48000] as const;\nexport type CallRate = (typeof CALL_RATES)[number];\nexport const DEFAULT_RATE: CallRate = 48000;\n\nexport const frameSamples = (rate: CallRate): number => (rate * FRAME_MS) / 1000;\nexport const frameBytes = (rate: CallRate): number => frameSamples(rate) * 2;\nexport const bytesToMs = (rate: CallRate, bytes: number): number => Math.round((bytes / 2 / rate) * 1000);\n\nexport function isCallRate(value: unknown): value is CallRate {\n return CALL_RATES.includes(value as CallRate);\n}\n\n/** The most a program may queue ahead of the call: five minutes of speech. What goes past it is dropped. */\nexport const MAX_QUEUE_MS = 5 * 60_000;\n\n/**\n * A partial frame waits this long for the rest of it before it is played padded with silence: a program writing at\n * real time, a little late, is not cut into gaps; a program that stopped mid-frame is still heard to its end.\n */\nexport const PARTIAL_WAIT_MS = 60;\n\n/**\n * What the program wrote, waiting to be sent: taken one 20 ms frame per tick, silence when there is nothing, and\n * dropped whole by a flush (barge-in). The program may write any amount at any time, faster than real time too.\n */\nexport class PlaybackQueue {\n private chunks: Buffer[] = [];\n private head = 0;\n private length = 0;\n private lastPush = 0;\n private readonly frame: number;\n private readonly max: number;\n private readonly silence: Buffer;\n /** Bytes dropped because the queue was full, since the start. */\n dropped = 0;\n\n constructor(readonly rate: CallRate, private readonly now: () => number = Date.now, maxMs = MAX_QUEUE_MS) {\n this.frame = frameBytes(rate);\n // Whole samples only: an odd byte waits for its other half.\n this.max = Math.floor((rate * maxMs) / 1000) * 2;\n this.silence = Buffer.alloc(this.frame);\n }\n\n /** Adds what the program wrote. Returns the bytes it could not keep (the queue was full). */\n push(chunk: Buffer): number {\n if (!chunk.length) return 0;\n this.lastPush = this.now();\n const room = this.max - this.length;\n const kept = chunk.length <= room ? chunk : chunk.subarray(0, Math.max(0, room));\n const lost = chunk.length - kept.length;\n this.dropped += lost;\n if (kept.length) { this.chunks.push(Buffer.from(kept)); this.length += kept.length; }\n return lost;\n }\n\n /** Queued audio, in milliseconds (whole frames and a partial one). */\n get queuedMs(): number {\n return bytesToMs(this.rate, this.length - (this.length % 2));\n }\n\n /** One frame to send now, and whether it is the program's audio or silence. */\n next(): { frame: Buffer; silent: boolean } {\n if (this.length >= this.frame) return { frame: this.take(this.frame), silent: false };\n const whole = this.length - (this.length % 2);\n if (whole > 0 && this.now() - this.lastPush >= PARTIAL_WAIT_MS) {\n const frame = Buffer.alloc(this.frame);\n this.take(whole).copy(frame);\n return { frame, silent: false };\n }\n return { frame: this.silence, silent: true };\n }\n\n /** Drops everything queued; returns how much, in milliseconds. */\n flush(): number {\n const ms = this.queuedMs;\n this.chunks = [];\n this.head = 0;\n this.length = 0;\n return ms;\n }\n\n /** Drops up to that much from the front, in whole frames (audio whose time went by); returns how much, in milliseconds. */\n skip(ms: number): number {\n const frames = Math.min(Math.floor(ms / FRAME_MS), Math.floor(this.length / this.frame));\n if (frames > 0) this.take(frames * this.frame);\n return Math.max(0, frames) * FRAME_MS;\n }\n\n private take(bytes: number): Buffer {\n const out = Buffer.allocUnsafe(bytes);\n let filled = 0;\n while (filled < bytes) {\n const chunk = this.chunks[0];\n const n = Math.min(bytes - filled, chunk.length - this.head);\n chunk.copy(out, filled, this.head, this.head + n);\n filled += n;\n this.head += n;\n if (this.head === chunk.length) { this.chunks.shift(); this.head = 0; }\n }\n this.length -= bytes;\n return out;\n }\n}\n","import { createHmac, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { closeSync, lstatSync, openSync, readFileSync, rmSync, writeSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { lockPath } from \"./profiles\";\n\n/**\n * How a client knows the process on the profile's socket is the profile's daemon (WISP 1100 § Local control API).\n * On Windows the socket is a named pipe whose name follows from the profile's path, and any account of the machine\n * may open that name first; the pipe itself has no owner a client can check. So the daemon writes a fresh random\n * secret in the profile's owner-only folder at every start, and the client sends nothing but a `daemon.hello` with a\n * nonce of its own until the answer proves, over that nonce, that its sender read the secret. Same on every platform.\n *\n * Before even the hello, the daemon speaks first: a greeting that proves, with the same secret, its pid (the\n * profile's lock holder) and the time. The client writes nothing at all until the greeting checks out. A process\n * holding `SeImpersonatePrivilege` that opened the pipe's name first can impersonate the client from the first\n * message it reads (Node's pipe client sets no security quality of service, so the level is SecurityImpersonation),\n * and Windows refuses to impersonate a pipe's client until data has been read from it (ERROR_CANNOT_IMPERSONATE):\n * a client that writes nothing to it cannot be impersonated.\n */\nexport const HELLO = \"daemon.hello\";\n\n/**\n * How far a greeting's time may be from the client's clock (the same machine's): a greeting is no fresh challenge, so\n * one copied from a daemon that has since died could otherwise stand in for it as long as its secret file is left.\n */\nexport const GREETING_WINDOW_MS = 10_000;\n\nexport interface Greeting { pid: number; at: number; proof: string }\n\nexport function daemonSecretPath(dir: string): string {\n return join(dir, \"daemon.secret\");\n}\n\n/** HMAC-SHA256 over the role's domain and the nonce, hex: a daemon's proof is never a client's, nor one for another nonce. */\nexport function proof(secret: Buffer, role: \"daemon\" | \"client\" | \"greeting\", nonce: string): string {\n return createHmac(\"sha256\", secret).update(`ghostly-${role}:${nonce}`).digest(\"hex\");\n}\n\nexport function newNonce(): string {\n return randomBytes(16).toString(\"hex\");\n}\n\n/**\n * The daemon's: a new secret, 32 random bytes as hex, made 0600 (`wx`, so a file or link put there in the meantime is\n * an error, not something written through). The one a daemon before it left is removed first: whoever could have\n * read that one learns nothing about this one.\n */\nexport function newDaemonSecret(dir: string): Buffer {\n const file = daemonSecretPath(dir);\n rmSync(file, { force: true });\n const secret = randomBytes(32);\n const fd = openSync(file, \"wx\", 0o600);\n try { writeSync(fd, secret.toString(\"hex\") + \"\\n\"); } finally { closeSync(fd); }\n return secret;\n}\n\n/** The daemon's, when it stops: a greeting copied from it proves nothing once it is gone. */\nexport function removeDaemonSecret(dir: string): void {\n rmSync(daemonSecretPath(dir), { force: true });\n}\n\n/** The daemon's first line on every connection, before it has read anything. */\nexport function greeting(secret: Buffer, pid = process.pid, at = Date.now()): { greeting: Greeting } {\n return { greeting: { pid, at, proof: proof(secret, \"greeting\", `${pid}:${at}`) } };\n}\n\n/**\n * Whether `message` (the first line the client read) is the profile's daemon's greeting: proved with the secret, made\n * within `GREETING_WINDOW_MS` of `now`, by the process that holds the profile's lock, alive and one this user may\n * signal (`process.kill(pid, 0)`: EPERM on Unix for another user's; on Windows libuv opens the process to terminate\n * it, which another account's process normally denies). A greeting copied from a daemon that died fails on its pid,\n * unless a process this user may signal took that pid within the window.\n */\nexport function provesGreeting(secret: Buffer, dir: string, message: unknown, now = Date.now()): boolean {\n const given = (message as { greeting?: Partial<Greeting> } | null)?.greeting;\n if (!given || !Number.isSafeInteger(given.pid) || (given.pid as number) <= 0 || !Number.isSafeInteger(given.at)) return false;\n if (typeof given.proof !== \"string\" || !/^[0-9a-f]{64}$/.test(given.proof)) return false;\n const { pid, at } = given as Greeting;\n if (Math.abs(now - at) > GREETING_WINDOW_MS) return false;\n if (!timingSafeEqual(Buffer.from(given.proof, \"hex\"), Buffer.from(proof(secret, \"greeting\", `${pid}:${at}`), \"hex\"))) return false;\n return holdsProfile(dir, pid);\n}\n\n/**\n * Whether a daemon of this release holds the profile: its secret is there (an older release's never writes one, and a\n * daemon removes its own when it stops) and the lock's holder is alive and this user's. One whose greeting is late is\n * busy (its event loop held by one long task), not something else on its socket: the client waits for it.\n */\nexport function daemonOfThisRelease(dir: string): boolean {\n if (!readDaemonSecret(dir)) return false;\n let pid: number;\n try { pid = Number(readFileSync(lockPath(dir), \"utf8\").trim()); } catch { return false; }\n return Number.isSafeInteger(pid) && pid > 0 && holdsProfile(dir, pid);\n}\n\nfunction holdsProfile(dir: string, pid: number): boolean {\n try {\n if (readFileSync(lockPath(dir), \"utf8\").trim() !== String(pid)) return false;\n process.kill(pid, 0);\n return true;\n } catch { return false; }\n}\n\n/**\n * The client's: the secret the profile's daemon wrote, or null when there is none, or it is not a file of this user's\n * alone (a link, another user's file, one others may read): then it proves nothing. On Windows the file has the\n * folder's ACL (owner-only in the user's home); Node can check no more than that it is a plain file.\n */\nexport function readDaemonSecret(dir: string): Buffer | null {\n const file = daemonSecretPath(dir);\n try {\n const info = lstatSync(file);\n if (!info.isFile()) return null;\n if (process.platform !== \"win32\" && ((process.getuid && info.uid !== process.getuid()) || (info.mode & 0o077) !== 0)) return null;\n const text = readFileSync(file, \"utf8\").trim();\n return /^[0-9a-f]{64}$/.test(text) ? Buffer.from(text, \"hex\") : null;\n } catch { return null; }\n}\n\n/** Whether `answer` (the result of a `daemon.hello` with `nonce`) is the daemon's proof over it, in constant time. */\nexport function provesDaemon(secret: Buffer, nonce: string, answer: unknown): boolean {\n const given = (answer as { proof?: unknown } | null)?.proof;\n if (typeof given !== \"string\" || !/^[0-9a-f]{64}$/.test(given)) return false;\n return timingSafeEqual(Buffer.from(given, \"hex\"), Buffer.from(proof(secret, \"daemon\", nonce), \"hex\"));\n}\n"],"mappings":";;;;AAMA,IAAa,aAAa;CAAC;CAAM;CAAO;CAAO;CAAO;AAAK;AAE3D,IAAa,eAAyB;AAEtC,IAAa,gBAAgB,SAA4B,OAAA,KAAmB;AAC5E,IAAa,cAAc,SAA2B,aAAa,IAAI,IAAI;AAC3E,IAAa,aAAa,MAAgB,UAA0B,KAAK,MAAO,QAAQ,IAAI,OAAQ,GAAI;AAExG,SAAgB,WAAW,OAAmC;CAC5D,OAAO,WAAW,SAAS,KAAiB;AAC9C;;AAGA,IAAa,eAAe;;;;;AAY5B,IAAa,gBAAb,MAA2B;CAWJ;CAAiC;CAVtD,SAA2B,CAAC;CAC5B,OAAe;CACf,SAAiB;CACjB,WAAmB;CACnB;CACA;CACA;;CAEA,UAAU;CAEV,YAAY,MAAyB,MAAqC,KAAK,KAAK,QAAQ,cAAc;EAArF,KAAA,OAAA;EAAiC,KAAA,MAAA;EACpD,KAAK,QAAQ,WAAW,IAAI;EAE5B,KAAK,MAAM,KAAK,MAAO,OAAO,QAAS,GAAI,IAAI;EAC/C,KAAK,UAAU,OAAO,MAAM,KAAK,KAAK;CACxC;;CAGA,KAAK,OAAuB;EAC1B,IAAI,CAAC,MAAM,QAAQ,OAAO;EAC1B,KAAK,WAAW,KAAK,IAAI;EACzB,MAAM,OAAO,KAAK,MAAM,KAAK;EAC7B,MAAM,OAAO,MAAM,UAAU,OAAO,QAAQ,MAAM,SAAS,GAAG,KAAK,IAAI,GAAG,IAAI,CAAC;EAC/E,MAAM,OAAO,MAAM,SAAS,KAAK;EACjC,K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AI,IAAI,OAAO,KAAK,MAAM,KAAK,IAAI;CAClE,QAAQ;EAAE,OAAO;CAAM;AACzB;;AAGA,SAAgB,aAAa,QAAgB,OAAe,QAA0B;CACpF,MAAM,QAAS,QAAuC;CACtD,IAAI,OAAO,UAAU,YAAY,CAAC,iBAAiB,KAAK,KAAK,GAAG,OAAO;CACvE,OAAO,gBAAgB,OAAO,KAAK,OAAO,KAAK,GAAG,OAAO,KAAK,MAAM,QAAQ,UAAU,KAAK,GAAG,KAAK,CAAC;AACtG"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"endpoint-BdaeBw2L.js","names":[],"sources":["../../../../native/transports/hyperdht/redial.mjs","../../../../native/transports/hyperdht/endpoint.mjs"],"sourcesContent":["/**\n * How long a HyperDHT dial whose stream opened may go without the contact's preface before it is dialled again.\n *\n * The first connection a freshly started process makes sometimes opens (the handshake went through the DHT and the\n * stream is connected to the right address) and then carries nothing: the contact never sees it, and UDX gives up\n * only after 13 s. A connection made again at once goes through in milliseconds. Found as a chat moved to HyperDHT\n * right after the contact's app restarted taking about 28 s in CI (the move's 8 s, then its 20 s retry), 1 run in 6;\n * reproduced with hyperdht alone under load (bug hunt r11h). On loopback the preface comes within milliseconds of\n * the stream opening, one round trip on the internet.\n */\nexport const PREFACE_WAIT_MS = 2000\n\n/**\n * The longest a stream that opened waits for the preface on a slow path: the 8 s a chat's move gives its dial. Past\n * it nobody is waiting for the dial made again, and UDX gives a silent stream up at 13 s anyway.\n */\nexport const PREFACE_MAX_WAIT_MS = 8000\n\n/**\n * How many of the stream's smoothed round trips the preface may take. A contact that waits for our first packet\n * before its side of the stream connects (we are behind a firewall) writes its preface one round trip after our\n * stream opened; a lost packet adds a retransmission timeout (at least one round trip more). Three keep a slow path's\n * preface from being dialled again for nothing (a fixed 2 s on a 3 s path made three dials) and leave every path\n * under 667 ms on the 2 s.\n */\nexport const RTT_FACTOR = 3\n\n/**\n * Before the stream has its first RTT sample, how many times the dial's own opening (from the dial to the stream\n * open) the preface may take. The opening is the DHT lookup plus the handshake through a DHT node, so it took at\n * least two round trips of the path, and the preface comes one round trip after the stream opened: once covers it\n * (on a 3 s path the first sample comes only 3 s after the stream opened, past the 2 s). It is not more because a\n * stalled stream never gets a sample, and its opening is mostly the lookup (1-3 s on the public DHT even for a near\n * contact): twice a 2.5 s opening would dial again only 7.5 s after the dial, past the move's 8 s once the second\n * dial's own opening is added. A dial that opened in milliseconds (loopback, a near contact) stays on the 2 s.\n */\nexport const OPENING_FACTOR = 1\n\n/**\n * The preface wait for a stream whose smoothed RTT is `rtt` ms and whose dial took `opening` ms to open: three round\n * trips once there is a sample, the opening itself before, between `floor` and `ceiling`.\n */\nexport function prefaceWait(rtt, opening = 0, floor = PREFACE_WAIT_MS, ceiling = PREFACE_MAX_WAIT_MS) {\n const wait = rtt > 0 ? RTT_FACTOR * rtt : OPENING_FACTOR * (opening || 0)\n return Math.min(ceiling, Math.max(floor, wait))\n}\n\n/**\n * At most this many dials for one `connect`: the first, and two more if they stalled, 2 s apart, all within the 8 s a\n * chat's move gives its dial. Under load a dial made again stalled too about once in 20 (bug hunt r11h).\n */\nexport const MAX_DIALS = 3\n\n/**\n * Dials with `dialOnce` until one brings the contact's preface. `dialOnce()` starts a connection and returns\n * `{ opened, ready, close }`: `opened` resolves true once the stream is open (the handshake is done), `ready` with the\n * bound channel once the contact's preface came, and `close()` drops it; `rtt()`, if given, is the stream's smoothed\n * RTT in ms so far, 0 before its first sample (UDX's `rawStream.rtt`). A dial that opened and brought no preface\n * within `waitMs`, or longer on a slow path (`prefaceWait`, at most `maxWaitMs`), is closed and made again, up to\n * `maxDials` in all. The RTT is read again whenever the wait would end, so a sample taken after the stream opened\n * counts. A dial that fails before it opened (the contact not found, refused) fails the whole connect at once, as\n * before: there is nothing to wait for.\n */\nexport function redial(dialOnce, { waitMs = PREFACE_WAIT_MS, maxWaitMs = PREFACE_MAX_WAIT_MS, maxDials = MAX_DIALS } = {}) {\n return new Promise((resolve, reject) => {\n let settled = false\n let dials = 0\n const attempt = () => {\n dials++\n const dialledAt = Date.now()\n const dial = dialOnce()\n let timer = null\n let stalled = false\n dial.opened.then(open => {\n if (!open || settled) return\n const openedAt = Date.now()\n const check = () => {\n if (settled) return\n const left = openedAt + prefaceWait(dial.rtt?.(), openedAt - dialledAt, waitMs, maxWaitMs) - Date.now()\n if (left > 0) { timer = setTimeout(check, left); return }\n if (dials >= maxDials) return\n stalled = true\n dial.close()\n attempt()\n }\n timer = setTimeout(check, waitMs)\n }, () => {})\n dial.ready.then(bound => {\n clearTimeout(timer)\n if (settled || stalled) { bound.channel.close(); return }\n settled = true\n resolve(bound)\n }, error => {\n clearTimeout(timer)\n // A dial closed here for stalling ends as closed: the next one carries the connect.\n if (settled || stalled) return\n settled = true\n reject(error)\n })\n }\n attempt()\n })\n}\n","import DHT from 'hyperdht'\nimport { redial } from './redial.mjs'\n\nexport const MAX_FRAME = 60 * 1024\n/** The top bit of a frame's length word: the frame is a binary message, not UTF-8 text (WISP 103). */\nconst BINARY = 0x80000000\nconst PREFACE = 'ghostly/paired-chat/1'\n/** How long a closing channel waits for what it sent last to go out before the stream is destroyed anyway. */\nconst CLOSE_FLUSH_MS = 300\n/**\n * Bytes a channel may hold before `send` throws: above what every sender here lets itself queue (the CLI's 1 MiB high\n * water mark and an app's quarter above it; the Desktop page, which stops a file once the sidecar says `full` past its\n * `SEND_ROOM`), so it trips only for one that ignores its own line.\n */\nconst MAX_BUFFERED = 2 * 1024 * 1024\n/**\n * `drained()` resolves once a channel holds no more than this: no more than the sidecar's `SEND_ROOM`, so its wait for\n * room never spins on a `drained()` that resolves at once.\n */\nconst DRAINED_AT = 64 * 1024\n/**\n * How often a wait in `drained()` looks again. Each stream says `drain` only once its own queue is empty, which on a fast\n * link comes first; on a slow one this finds the queue at `DRAINED_AT` before it runs dry.\n */\nconst DRAIN_POLL_MS = 10\n\n/**\n * What a connection's stream still holds: secret-stream's queue and the UDX stream's under it. Both are streamx\n * streams, which count it in `_writableState.buffered` (hyperdht is pinned; hyperdhtEndpointBuffered.test.ts reads it).\n * secret-stream has no `writableLength`: read from there, it was always 0.\n */\nfunction held(socket) {\n return (socket._writableState?.buffered ?? 0) + (socket.rawStream?._writableState?.buffered ?? 0)\n}\n\n/** Native UDP + NoiseSecretStream. The binding comes from the authenticated\n * stream itself, never from an application frame supplied by the other peer. */\nexport async function createHyperEndpoint(seed, options = {}) {\n if (!(seed instanceof Uint8Array) || seed.length !== 32) throw new Error('Invalid HyperDHT seed')\n const keyPair = DHT.keyPair(Buffer.from(seed))\n // A chat's listener is a DHT client for good: an adaptive node turns persistent after ~20 min wherever its UDP port is\n // reachable, and then joins the routing table and keeps strangers' records and values. Ephemeral, it still listens\n // (announced through other nodes) and holepunches.\n const node = new DHT({ ...options, keyPair, ephemeral: true })\n const channels = new Set()\n let stopped = false\n let incomingHandler = null\n const waiting = []\n const descriptor = { publicKey: keyPair.publicKey.toString('hex') }\n\n /** `onChannel`: hears the channel as soon as it counts against the limit (a dial that stalls is dropped from it). */\n async function attach(socket, onChannel) {\n if (stopped || channels.size >= 2) { socket.destroy(); throw new Error('Native connection limit reached') }\n let reader = null\n let closeHandler = null\n let closed = false\n let ending = null\n let pending = []\n let buffer = Buffer.alloc(0)\n let preface = false\n let resolveOpen, rejectOpen\n const ready = new Promise((resolve, reject) => { resolveOpen = resolve; rejectOpen = reject })\n const timer = setTimeout(() => { socket.destroy(new Error('HyperDHT handshake timed out')) }, 20000)\n const channel = {\n // It carries binary messages (WISP 100 § Text and binary messages): a capability that needs them may be offered.\n binary: true,\n get bufferedAmount() { return held(socket) },\n get onMessage() { return reader },\n set onMessage(value) { reader = value; if (value) for (const text of pending.splice(0)) value(text) },\n get onClose() { return closeHandler },\n set onClose(value) { closeHandler = value; if (closed) value?.() },\n send(data) {\n const binary = data instanceof Uint8Array\n if (closed || !(binary || typeof data === 'string') || !data.length || (binary ? data.length : Buffer.byteLength(data)) > MAX_FRAME || this.bufferedAmount > MAX_BUFFERED)\n throw new Error('Native channel is closed or exceeds its frame budget')\n const payload = binary ? Buffer.from(data.buffer, data.byteOffset, data.byteLength) : Buffer.from(data)\n const header = Buffer.alloc(4); header.writeUInt32BE((binary ? BINARY : 0) + payload.length)\n socket.write(Buffer.concat([header, payload]))\n },\n drained() {\n if (this.bufferedAmount <= DRAINED_AT) return Promise.resolve()\n if (closed) return Promise.reject(new Error('Native channel closed'))\n return new Promise((resolve, reject) => {\n const raw = socket.rawStream\n const check = () => { if (this.bufferedAmount <= DRAINED_AT) finish(resolve) }\n const gone = () => finish(() => reject(new Error('Native channel closed')))\n const poll = setInterval(check, DRAIN_POLL_MS)\n poll.unref?.()\n function finish(settle) {\n clearInterval(poll); socket.off('drain', check); raw?.off('drain', check); socket.off('close', gone); settle()\n }\n socket.on('drain', check); raw?.on('drain', check); socket.once('close', gone)\n })\n },\n // What was sent last (a goodbye, as an app stops) goes out before the stream ends: destroyed at once, it was\n // dropped unsent. A contact that never finishes the stream has CLOSE_FLUSH_MS.\n close() {\n if (closed || ending) return ending ?? Promise.resolve()\n ending = new Promise(resolve => { socket.once('close', resolve) })\n const timer = setTimeout(() => socket.destroy(), CLOSE_FLUSH_MS)\n timer.unref?.()\n socket.end()\n return ending\n },\n }\n channels.add(channel)\n onChannel?.(channel)\n socket.on('error', error => rejectOpen(error))\n // The contact ended its side (its channel closed): this one ends too, so the stream closes now, not on its timer.\n socket.on('end', () => socket.end())\n socket.on('close', () => {\n closed = true; pending = []; clearTimeout(timer); channels.delete(channel)\n rejectOpen(new Error('Native channel closed')); closeHandler?.()\n })\n const opened = () => {\n if (socket.handshakeHash?.length !== 64 || socket.publicKey?.length !== 32 || socket.remotePublicKey?.length !== 32) {\n socket.destroy(new Error('Noise session binding unavailable')); return\n }\n channel.send(PREFACE)\n }\n socket.on('data', chunk => {\n // Secretstream chunks are bounded by its record layer. Process all frames\n // before retaining a partial one; never allocate based on an unchecked size.\n buffer = Buffer.concat([buffer, chunk])\n while (buffer.length >= 4) {\n const word = buffer.readUInt32BE(0)\n const binary = word >= BINARY, length = word % BINARY\n // A binary frame before the preface is another protocol.\n if (length === 0 || length > MAX_FRAME || (binary && !preface)) { socket.destroy(new Error('Invalid frame length')); return }\n if (buffer.length < 4 + length) break\n let text\n if (binary) text = new Uint8Array(buffer.subarray(4, 4 + length))\n else {\n try { text = new TextDecoder('utf-8', { fatal: true }).decode(buffer.subarray(4, 4 + length)) }\n catch { socket.destroy(new Error('Invalid UTF-8 frame')); return }\n }\n buffer = buffer.subarray(4 + length)\n if (!preface) {\n if (text !== PREFACE) { socket.destroy(new Error('Unexpected application protocol')); return }\n preface = true; clearTimeout(timer)\n resolveOpen({ channel, binding: { transport: 'hyperdht/1', context: socket.handshakeHash.toString('hex'),\n identities: [socket.publicKey.toString('hex'), socket.remotePublicKey.toString('hex')].sort() } })\n } else if (reader) reader(text)\n else if (pending.length < 64) pending.push(text)\n else { socket.destroy(new Error('Receive queue exceeded')); return }\n }\n })\n void socket.opened.then(ok => { if (ok) opened(); else rejectOpen(new Error('Noise handshake failed')) })\n return ready\n }\n\n const server = node.createServer(socket => {\n void attach(socket).then(bound => {\n if (stopped) bound.channel.close()\n else if (incomingHandler) incomingHandler(bound)\n else waiting.push(bound)\n }).catch(() => {})\n })\n try { await server.listen(keyPair) }\n catch (error) { await node.destroy(); throw error }\n return {\n transport: 'hyperdht/1', descriptor, onDescriptor: null,\n get onConnection() { return incomingHandler },\n set onConnection(value) { incomingHandler = value; if (value) for (const bound of waiting.splice(0)) value(bound) },\n async connect(address) {\n if (stopped || !address || !/^[a-f0-9]{64}$/.test(address.publicKey)) throw new Error('Invalid HyperDHT endpoint')\n const remote = Buffer.from(address.publicKey, 'hex')\n // A dial whose stream opened and carried nothing is made again (`redial.mjs`): it is dropped from the limit at\n // once, so the next one has its place even while another channel is live. The wait follows the stream's RTT.\n return redial(() => {\n const socket = node.connect(remote, { keyPair })\n let counted = null\n const ready = attach(socket, channel => { counted = channel })\n return { opened: socket.opened, ready, rtt: () => socket.rawStream?.rtt ?? 0,\n close() { if (counted) channels.delete(counted); socket.destroy() } }\n })\n },\n // The channels end first (their last frames out, CLOSE_FLUSH_MS at most): the node's socket goes with it.\n async close() { stopped = true; const ended = [...channels].map(channel => channel.close()); waiting.length = 0; await Promise.all(ended); await server.close(); await node.destroy() },\n }\n}\n"],"mappings":";;;;;;;;;;;;AAUA,IAAa,kBAAkB;;;;;AAM/B,IAAa,sBAAsB;;;;;AA0BnC,SAAgB,YAAY,KAAK,UAAU,GAAG,QAAQ,iBAAiB,UAAU,qBAAqB;CACpG,MAAM,OAAO,MAAM,IAAA,IAAiB,MAAA,KAAwB,WAAW;CACvE,OAAO,KAAK,IAAI,SAAS,KAAK,IAAI,OAAO,IAAI,CAAC;AAChD;;;;;;;;;;;AAkBA,SAAgB,OAAO,UAAU,EAAE,SAAS,iBAAiB,YAAY,qBAAqB,WAAA,MAAyB,CAAC,GAAG;CACzH,OAAO,IAAI,SAAS,SAAS,WAAW;EACtC,IAAI,UAAU;EACd,IAAI,QAAQ;EACZ,MAAM,gBAAgB;GACpB;GACA,MAAM,YAAY,KAAK,IAAI;GAC3B,MAAM,OAAO,SAAS;GACtB,IAAI,QAAQ;GACZ,IAAI,UAAU;GACd,KAAK,OAAO,MAAK,SAAQ;IACvB,IAAI,CAAC,QAAQ,SAAS;IACtB,MAAM,WAAW,KAAK,IAAI;IAC1B,MAAM,cAAc;KAClB,IAAI,SAAS;KACb,MAAM,OAAO,WAAW,YAAY,KAAK,MAAM,GAAG,WAAW,WAAW,QAAQ,SAAS,IAAI,KAAK,IAAI;KACtG,IAAI,OAAO,GAAG;MAAE,QAAQ,WAAW,OAAO,IAAI;MAAG;KAAO;KACxD,IAAI,SAAS,UAAU;KACvB,UAAU;KACV,KAAK,MAAM;KACX,QAAQ;IACV;IACA,QAAQ,WAAW,OAAO,MAAM;GAClC,SAAS,CAAC,CAAC;GACX,KAAK,MAAM,MAAK,UAAS;IACvB,aAAa,KAAK;IAClB,IAAI,WAAW,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/backup/envelope.ts"],"sourcesContent":["import { toBase64Url } from \"@ghostly/core\";\n\n/**\n * Base64url without padding. Core's encoder, not `btoa`: every picture, voice note and kept file (up to 16 MiB each)\n * goes through it on the page's thread, where `btoa` spends over a second per 16 MiB.\n */\nexport { toBase64Url };\nexport function fromBase64Url(text: string): Uint8Array {\n if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error(\"Invalid base64url\");\n const binary = atob(text.replace(/-/g, \"+\").replace(/_/g, \"/\") + \"=\".repeat((4 - (text.length % 4)) % 4));\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\n\ntype Tagged = { $ghostly: \"bigint\" | \"bytes\" | \"blob\"; value: string; type?: string };\n/** Data that happens to look like a tag (a contact can send anything) travels as its entries instead. */\ntype Escaped = { $ghostly: \"object\"; entries: [string, unknown][] };\n\n/**\n * Blobs cannot be read synchronously: turn them into tagged values first, everywhere in the tree. An\n * object of the data's own with a `$ghostly` key is escaped, so it comes back as it was and not as a tag.\n */\nasync function inlineBlobs(value: unknown): Promise<unknown> {\n if (typeof Blob !== \"undefined\" && value instanceof Blob) return { $ghostly: \"blob\", type: value.type, value: toBase64Url(new Uint8Array(await value.arrayBuffer())) } satisfies Tagged;\n if (Array.isArray(value)) return Promise.all(value.map(inlineBlobs));\n if (value && typeof value === \"object\" && !(value instanceof Uint8Array) && !(value instanceof ArrayBuffer) && !ArrayBuffer.isView(value)) {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) out[k] = await inlineBlobs(v);\n return Object.prototype.hasOwnProperty.call(out, \"$ghostly\") ? ({ $ghostly: \"object\", entries: Object.entries(out) } satisfies Escaped) : out;\n }\n return value;\n}\n\n/** JSON that also carries what IndexedDB holds: bigints, bytes and blobs (WISP 05). */\nexport async function encode(value: unknown): Promise<string> {\n return JSON.stringify(await inlineBlobs(value), (_key, v) => {\n if (typeof v === \"bigint\") return { $ghostly: \"bigint\", value: String(v) } satisfies Tagged;\n if (v instanceof Uint8Array) return { $ghostly: \"bytes\", value: toBase64Url(v) } satisfies Tagged;\n if (v instanceof ArrayBuffer) return { $ghostly: \"bytes\", value: toBase64Url(new Uint8Array(v)) } satisfies Tagged;\n return v;\n });\n}\n/** Never throws on a tag it cannot read: that value stays as it is, and the rest of the backup restores. */\nexport function decode(text: string): unknown {\n return JSON.parse(text, (_key, v) => {\n const escaped = v as Partial<Escaped> | null;\n if (escaped && typeof escaped === \"object\" && escaped.$ghostly === \"object\" && Array.isArray(escaped.entries)) {\n const out: Record<string, unknown> = {};\n for (const entry of escaped.entries) if (Array.isArray(entry) && typeof entry[0] === \"string\") Object.defineProperty(out, entry[0], { value: entry[1], enumerable: true, writable: true, configurable: true });\n return out;\n }\n const tag = v as Partial<Tagged> | null;\n if (!tag || typeof tag !== \"object\" || typeof tag.$ghostly !== \"string\" || typeof tag.value !== \"string\") return v;\n if (tag.$ghostly === \"bigint\") return /^-?\\d+$/.test(tag.value) ? BigInt(tag.value) : v;\n if (!/^[A-Za-z0-9_-]*$/.test(tag.value)) return v;\n if (tag.$ghostly === \"bytes\") return fromBase64Url(tag.value);\n if (tag.$ghostly === \"blob\") return new Blob([fromBase64Url(tag.value) as BlobPart], { type: typeof tag.type === \"string\" ? tag.type : \"\" });\n return v;\n });\n}\n","import { fromBase64Url, toBase64Url } from \"./codec\";\n\n/** The clear part of a bundle (WISP 05): only what decryption needs. */\nexport interface Envelope {\n format: \"ghostly-backup\";\n version: 1;\n kdf: { name: \"PBKDF2-SHA256\"; iterations: number; salt: string };\n cipher: { name: \"AES-256-GCM\"; iv: string };\n compression: \"gzip\" | \"none\";\n ciphertext: string;\n}\nexport const BACKUP_MEDIA_TYPE = \"application/vnd.ghostly.backup+json\";\nconst ITERATIONS = 600_000;\n\nasync function keyFrom(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\"]);\n}\n/** A profile with years of files is large, but not this large: past it, a bundle is refused, not read. */\nexport const MAX_BACKUP_BYTES = 1024 * 1024 * 1024;\n\nasync function through(bytes: Uint8Array, stream: CompressionStream | DecompressionStream): Promise<Uint8Array> {\n const reader = new Blob([bytes as BlobPart]).stream().pipeThrough(stream).getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n for (let next = await reader.read(); !next.done; next = await reader.read()) {\n size += next.value.length;\n if (size > MAX_BACKUP_BYTES) { await reader.cancel(); throw new Error(\"This backup is too large to restore\"); }\n chunks.push(next.value);\n }\n const out = new Uint8Array(size);\n let at = 0;\n for (const chunk of chunks) { out.set(chunk, at); at += chunk.length; }\n return out;\n}\n\n/**\n * The clear header is authenticated with the ciphertext (AES-GCM associated data): changing any of it,\n * the compression included, makes the bundle fail to open instead of being read differently.\n */\nconst header = (e: Pick<Envelope, \"format\" | \"version\" | \"kdf\" | \"cipher\" | \"compression\">) =>\n new TextEncoder().encode([e.format, e.version, e.kdf.name, e.kdf.iterations, e.kdf.salt, e.cipher.name, e.cipher.iv, e.compression].join(\"\\n\"));\nconst canCompress = () => typeof CompressionStream !== \"undefined\";\n\n/** Compresses and encrypts a payload under a passphrase the person chose. */\nexport async function seal(payload: string, passphrase: string): Promise<string> {\n if (passphrase.length < 12) throw new Error(\"Use at least 12 characters for the backup passphrase\");\n const salt = crypto.getRandomValues(new Uint8Array(16)), iv = crypto.getRandomValues(new Uint8Array(12));\n const plain = new TextEncoder().encode(payload);\n const compression = canCompress() ? \"gzip\" : \"none\";\n const body = compression === \"gzip\" ? await through(plain, new CompressionStream(\"gzip\")) : plain;\n const clear = { format: \"ghostly-backup\", version: 1, kdf: { name: \"PBKDF2-SHA256\", iterations: ITERATIONS, salt: toBase64Url(salt) }, cipher: { name: \"AES-256-GCM\", iv: toBase64Url(iv) }, compression } as const;\n const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv, additionalData: header(clear) as BufferSource }, await keyFrom(passphrase, salt, ITERATIONS), body as BufferSource));\n const envelope: Envelope = { ...clear, ciphertext: toBase64Url(ciphertext) };\n return JSON.stringify(envelope);\n}\n\n/** Checks, decrypts and decompresses a bundle. Nothing from a bundle is used before this succeeds. */\nexport async function open(text: string, passphrase: string): Promise<string> {\n if (text.length > MAX_BACKUP_BYTES * 1.4) throw new Error(\"This backup is too large to restore\");\n let envelope: Envelope;\n try { envelope = JSON.parse(text) as Envelope; } catch { throw new Error(\"This is not a Ghostly backup\"); }\n if (envelope?.format !== \"ghostly-backup\") throw new Error(\"This is not a Ghostly backup\");\n if (envelope.version !== 1) throw new Error(\"This backup comes from a newer Ghostly; update to restore it\");\n if (envelope.kdf?.name !== \"PBKDF2-SHA256\" || !(envelope.kdf.iterations >= ITERATIONS) || envelope.kdf.iterations > 10_000_000 || envelope.cipher?.name !== \"AES-256-GCM\" || ![\"gzip\", \"none\"].includes(envelope.compression)) throw new Error(\"Unsupported backup encryption\");\n let body: Uint8Array;\n try {\n body = new Uint8Array(await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: fromBase64Url(envelope.cipher.iv) as BufferSource, additionalData: header(envelope) as BufferSource }, await keyFrom(passphrase, fromBase64Url(envelope.kdf.salt), envelope.kdf.iterations), fromBase64Url(envelope.ciphertext) as BufferSource));\n } catch { throw new Error(\"Wrong passphrase, or the backup was changed\"); }\n const plain = envelope.compression === \"gzip\" ? await through(body, new DecompressionStream(\"gzip\")) : body;\n return new TextDecoder().decode(plain);\n}\n"],"mappings":";;AAOA,SAAgB,cAAc,MAA0B;CACtD,IAAI,CAAC,mBAAmB,KAAK,IAAI,GAAG,MAAM,IAAI,MAAM,mBAAmB;CACvE,MAAM,SAAS,KAAK,KAAK,QAAQ,MAAM,GAAG,CAAC,CAAC,QAAQ,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