@ghostlytools/cli 1.11.4 → 1.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -11
- package/dist/assets/{api-MYc6QNRs.js → api-DLzCtePC.js} +363 -125
- package/dist/assets/api-DLzCtePC.js.map +1 -0
- package/dist/assets/{api-BwyFq4lA.js → api-DYMKyb1k.js} +2 -2
- package/dist/assets/{apiKit-CfsNx9ZR.js → apiKit-CVaEzKWQ.js} +48 -11
- package/dist/assets/apiKit-CVaEzKWQ.js.map +1 -0
- package/dist/assets/appFetch-D56GsYuq.js +602 -0
- package/dist/assets/appFetch-D56GsYuq.js.map +1 -0
- package/dist/assets/apps-BPFW19Wc.js +1 -0
- package/dist/assets/{apps-h12II1us.js → apps-XnZ8VEuj.js} +20 -14
- package/dist/assets/apps-XnZ8VEuj.js.map +1 -0
- package/dist/assets/{argon2id-088uQfnH.js → argon2id-B9wFdSj6.js} +2 -3
- package/dist/assets/{argon2id-088uQfnH.js.map → argon2id-B9wFdSj6.js.map} +1 -1
- package/dist/assets/{arkade-Bw_4PZRG.js → arkade-DryM-q5n.js} +6 -7
- package/dist/assets/arkade-DryM-q5n.js.map +1 -0
- package/dist/assets/backup-COX6j1_W.js +1 -0
- package/dist/assets/{backup-Chvy79SN.js → backup-DpyvT9Z6.js} +66 -21
- package/dist/assets/backup-DpyvT9Z6.js.map +1 -0
- package/dist/assets/bark_ffi_wasm_bg-CcafsJla.js +5 -0
- package/dist/assets/bark_ffi_wasm_bg-CcafsJla.js.map +1 -0
- package/dist/assets/{bark_ffi_wasm_bg-Bxru_BVW.wasm → bark_ffi_wasm_bg-VNmaJsc9.wasm} +0 -0
- package/dist/assets/{bitcoind-CdSmvy2y.js → bitcoind-DTsrd7TF.js} +4 -5
- package/dist/assets/{bitcoind-CdSmvy2y.js.map → bitcoind-DTsrd7TF.js.map} +1 -1
- package/dist/assets/bitcoindevkit_bg-BWQHx7vd.js +5 -0
- package/dist/assets/bitcoindevkit_bg-BWQHx7vd.js.map +1 -0
- package/dist/assets/bitcoindevkit_bg-DXil67yS.wasm +0 -0
- package/dist/assets/{blobFiles-BmsrvZc3.js → blobFiles-DDs34n0r.js} +4 -5
- package/dist/assets/{blobFiles-BmsrvZc3.js.map → blobFiles-DDs34n0r.js.map} +1 -1
- package/dist/assets/breez_sdk_spark_wasm_bg.wasm +0 -0
- package/dist/assets/buttons-Bq7pTXqF.js +1 -0
- package/dist/assets/{buttons-BgoExb4E.js → buttons-BvWqHJeh.js} +45 -23
- package/dist/assets/buttons-BvWqHJeh.js.map +1 -0
- package/dist/assets/bytes-C1DNGY18.js +132 -0
- package/dist/assets/bytes-C1DNGY18.js.map +1 -0
- package/dist/assets/{childEnv-K_IzUqQx.js → childEnv-C-99hdbL.js} +2 -3
- package/dist/assets/{childEnv-K_IzUqQx.js.map → childEnv-C-99hdbL.js.map} +1 -1
- package/dist/assets/{client-DY8tZZWi.js → client-kGZ3ZdUW.js} +5 -8
- package/dist/assets/{client-DY8tZZWi.js.map → client-kGZ3ZdUW.js.map} +1 -1
- package/dist/assets/{codec-BnMg-Grj.js → codec-B2rH1mfx.js} +2 -4
- package/dist/assets/{codec-BnMg-Grj.js.map → codec-B2rH1mfx.js.map} +1 -1
- package/dist/assets/domainProofs-BDNP1dIy.js +280 -0
- package/dist/assets/domainProofs-BDNP1dIy.js.map +1 -0
- package/dist/assets/{endpoint-DarqblYE.js → endpoint-B0vE5ojY.js} +421 -420
- package/dist/assets/endpoint-B0vE5ojY.js.map +1 -0
- package/dist/assets/engineErrors--9hfgKlK.js +150 -0
- package/dist/assets/engineErrors--9hfgKlK.js.map +1 -0
- package/dist/assets/{envelope-CdV7vHVZ.js → envelope-Bi2kMqbp.js} +3 -4
- package/dist/assets/{envelope-CdV7vHVZ.js.map → envelope-Bi2kMqbp.js.map} +1 -1
- package/dist/assets/{errors-CAh6GLJZ.js → errors-DDLFO4Gf.js} +5 -4
- package/dist/assets/errors-DDLFO4Gf.js.map +1 -0
- package/dist/assets/{fedimintSdk-CPFfVK-G.js → fedimintSdk-D-6H9Pe7.js} +4 -5
- package/dist/assets/{fedimintSdk-CPFfVK-G.js.map → fedimintSdk-D-6H9Pe7.js.map} +1 -1
- package/dist/assets/fedimint_client_wasm_bg-Cr5xGD-w.js +5 -0
- package/dist/assets/{fedimint_client_wasm_bg-BtHHlFpp.js.map → fedimint_client_wasm_bg-Cr5xGD-w.js.map} +1 -1
- package/dist/assets/fileBytes-CCKbwqG_.js +1 -0
- package/dist/assets/{fileBytes-BLPZq9YU.js → fileBytes-CfvUXdSy.js} +5 -7
- package/dist/assets/fileBytes-CfvUXdSy.js.map +1 -0
- package/dist/assets/{fileBytes-B0z9A6Le.js → fileBytes-tj6-VZcB.js} +3 -4
- package/dist/assets/{fileBytes-B0z9A6Le.js.map → fileBytes-tj6-VZcB.js.map} +1 -1
- package/dist/assets/fileBytesIdb-B0zzJ6p7.js +1 -0
- package/dist/assets/{fileBytesIdb-Bmlrl9EO.js → fileBytesIdb-BJirUAjI.js} +4 -5
- package/dist/assets/{fileBytesIdb-Bmlrl9EO.js.map → fileBytesIdb-BJirUAjI.js.map} +1 -1
- package/dist/assets/{fileBytesOpfs-DBS0kbPT.js → fileBytesOpfs-DRUYLER4.js} +4 -5
- package/dist/assets/{fileBytesOpfs-DBS0kbPT.js.map → fileBytesOpfs-DRUYLER4.js.map} +1 -1
- package/dist/assets/{fixedHosts-CbgqrIKs.js → fixedHosts-CPSsGOI2.js} +4 -5
- package/dist/assets/{fixedHosts-CbgqrIKs.js.map → fixedHosts-CPSsGOI2.js.map} +1 -1
- package/dist/assets/{ghostly_iroh_web-BzAXJUYH.js → ghostly_iroh_web-DIj5xGmR.js} +2 -3
- package/dist/assets/{ghostly_iroh_web-BzAXJUYH.js.map → ghostly_iroh_web-DIj5xGmR.js.map} +1 -1
- package/dist/assets/{src-DJe-OYxd.js → groupMeta-DTQAJG50.js} +4693 -24241
- package/dist/assets/groupMeta-DTQAJG50.js.map +1 -0
- package/dist/assets/{host-C0NMNQLl.js → host-z0FAHP9Z.js} +209 -134
- package/dist/assets/host-z0FAHP9Z.js.map +1 -0
- package/dist/assets/{hyperdhtRelay-Dz7pvcBA.js → hyperdhtRelay-CvsAfQRQ.js} +5 -6
- package/dist/assets/hyperdhtRelay-CvsAfQRQ.js.map +1 -0
- package/dist/assets/hyperdhtRelay-bjNGacf5.js +32 -0
- package/dist/assets/hyperdhtRelay-bjNGacf5.js.map +1 -0
- package/dist/assets/{idb-CEuoNsTv.js → idb-ewvbqyDI.js} +2 -3
- package/dist/assets/{idb-CEuoNsTv.js.map → idb-ewvbqyDI.js.map} +1 -1
- package/dist/assets/identityProofs-Cksc_K7_.js +940 -0
- package/dist/assets/identityProofs-Cksc_K7_.js.map +1 -0
- package/dist/assets/{irohWeb-caAj4Dms.js → irohWeb-CLBx5MIv.js} +3061 -86
- package/dist/assets/irohWeb-CLBx5MIv.js.map +1 -0
- package/dist/assets/joinTrace-CBr1jbch.js +1 -0
- package/dist/assets/{joinTrace-CjRDFy85.js → joinTrace-xKBe73j9.js} +2 -3
- package/dist/assets/{joinTrace-CjRDFy85.js.map → joinTrace-xKBe73j9.js.map} +1 -1
- package/dist/assets/{legacy_ciphers-JJOu0JXL.js → legacy_ciphers-BnYATjxo.js} +2 -3
- package/dist/assets/{legacy_ciphers-JJOu0JXL.js.map → legacy_ciphers-BnYATjxo.js.map} +1 -1
- package/dist/assets/linkPreview-DdMf-YAc.js +252 -0
- package/dist/assets/linkPreview-DdMf-YAc.js.map +1 -0
- package/dist/assets/{main-C6t5zrD5.js → main-CVqkvuIo.js} +268 -111
- package/dist/assets/main-CVqkvuIo.js.map +1 -0
- package/dist/assets/{mainline-DCuGUSZF.js → mainline-CVrd0C1n.js} +72 -18
- package/dist/assets/mainline-CVrd0C1n.js.map +1 -0
- package/dist/assets/mints-BcBODVVW.js +1 -0
- package/dist/assets/{mints-j5XAOk4f.js → mints-CMDLbMeH.js} +8 -6
- package/dist/assets/mints-CMDLbMeH.js.map +1 -0
- package/dist/assets/{nacl-fast-CDhNCYHs.js → nacl-fast-B1ThWvuM.js} +2 -3
- package/dist/assets/{nacl-fast-CDhNCYHs.js.map → nacl-fast-B1ThWvuM.js.map} +1 -1
- package/dist/assets/{networkReason-BbQW1Xpc.js → networkReason-Be-hMghr.js} +10 -14
- package/dist/assets/{networkReason-BbQW1Xpc.js.map → networkReason-Be-hMghr.js.map} +1 -1
- package/dist/assets/{noble_curves-DDWn5AH0.js → noble_curves-DqpNlhAU.js} +3 -4
- package/dist/assets/{noble_curves-DDWn5AH0.js.map → noble_curves-DqpNlhAU.js.map} +1 -1
- package/dist/assets/{noble_hashes-B7AZyFyS.js → noble_hashes-LFe1N2xt.js} +3 -4
- package/dist/assets/{noble_hashes-B7AZyFyS.js.map → noble_hashes-LFe1N2xt.js.map} +1 -1
- package/dist/assets/{nwc-CSDRMZ0e.js → nwc-DKE2FXr6.js} +5 -6
- package/dist/assets/{nwc-CSDRMZ0e.js.map → nwc-DKE2FXr6.js.map} +1 -1
- package/dist/assets/nwcProvider-pL2XqSbW.js +208 -0
- package/dist/assets/nwcProvider-pL2XqSbW.js.map +1 -0
- package/dist/assets/{openpgp-BBFr-zHQ.js → openpgp-LkR_Zof0.js} +14 -15
- package/dist/assets/{openpgp-BBFr-zHQ.js.map → openpgp-LkR_Zof0.js.map} +1 -1
- package/dist/assets/ownDid-DY3rYqDI.js +862 -0
- package/dist/assets/ownDid-DY3rYqDI.js.map +1 -0
- package/dist/assets/{ownStatus-BoTf5WqQ.js → ownStatus-DMEhrpkd.js} +69 -20
- package/dist/assets/ownStatus-DMEhrpkd.js.map +1 -0
- package/dist/assets/pairedTransports-BKmvlKz1.js +581 -0
- package/dist/assets/pairedTransports-BKmvlKz1.js.map +1 -0
- package/dist/assets/paymentIntent-DySU3Ajm.js +349 -0
- package/dist/assets/paymentIntent-DySU3Ajm.js.map +1 -0
- package/dist/assets/pkarr-BQo4PcCg.js +367 -0
- package/dist/assets/pkarr-BQo4PcCg.js.map +1 -0
- package/dist/assets/{profiles-DszHjEJi.js → profiles-BFSGqDFC.js} +9 -10
- package/dist/assets/profiles-BFSGqDFC.js.map +1 -0
- package/dist/assets/registry-B15Yg_1C.js +1 -0
- package/dist/assets/{registry-Da-r6eC3.js → registry-rXgaZeNn.js} +1261 -53
- package/dist/assets/registry-rXgaZeNn.js.map +1 -0
- package/dist/assets/relay-Cjfmdec0.js +2219 -0
- package/dist/assets/relay-Cjfmdec0.js.map +1 -0
- package/dist/assets/resolve-CIc3KZMV.js +970 -0
- package/dist/assets/resolve-CIc3KZMV.js.map +1 -0
- package/dist/assets/{restoredRows-C3LcxmOw.js → restoredRows-D_WSHE7H.js} +3 -4
- package/dist/assets/{restoredRows-C3LcxmOw.js.map → restoredRows-D_WSHE7H.js.map} +1 -1
- package/dist/assets/{secretGuard-CsVHDdYk.js → secretGuard-B4-LlMjv.js} +11 -14
- package/dist/assets/{secretGuard-CsVHDdYk.js.map → secretGuard-B4-LlMjv.js.map} +1 -1
- package/dist/assets/secretGuard-BmmnEbYf.js +1 -0
- package/dist/assets/{server-C1jZZ61O.js → server-CQR7NLCz.js} +9565 -461
- package/dist/assets/server-CQR7NLCz.js.map +1 -0
- package/dist/assets/{sha512-BYId-G-T.js → sha512-DST9fbWH.js} +2 -3
- package/dist/assets/{sha512-BYId-G-T.js.map → sha512-DST9fbWH.js.map} +1 -1
- package/dist/assets/sshForges-BnvwmNj-.js +539 -0
- package/dist/assets/sshForges-BnvwmNj-.js.map +1 -0
- package/dist/assets/{storage-Bya5b2Xt.js → storage-BpjdxvO2.js} +243 -34
- package/dist/assets/storage-BpjdxvO2.js.map +1 -0
- package/dist/assets/text-li76pThX.js +106 -0
- package/dist/assets/text-li76pThX.js.map +1 -0
- package/dist/assets/{translate-CUuC5szR.js → translate-BcbSWkuq.js} +21 -26
- package/dist/assets/{translate-CUuC5szR.js.map → translate-BcbSWkuq.js.map} +1 -1
- package/dist/assets/{tree-store-N362nuzZ.js → tree-store-CAchkO_l.js} +22 -6
- package/dist/assets/tree-store-CAchkO_l.js.map +1 -0
- package/dist/assets/{types-Clyb52K2.js → types-CdWwgvyt.js} +2 -3
- package/dist/assets/{types-Clyb52K2.js.map → types-CdWwgvyt.js.map} +1 -1
- package/dist/assets/{unbzip2-stream-B1C-JX9L.js → unbzip2-stream-BtkYGpC5.js} +2 -3
- package/dist/assets/{unbzip2-stream-B1C-JX9L.js.map → unbzip2-stream-BtkYGpC5.js.map} +1 -1
- package/dist/assets/{usdt-DI51znt-.js → usdt-CBJ4Q5Ji.js} +7 -7
- package/dist/assets/usdt-CBJ4Q5Ji.js.map +1 -0
- package/dist/assets/{waitNotice-Cn0WJ-He.js → waitNotice-BGM0QOS2.js} +27 -4
- package/dist/assets/waitNotice-BGM0QOS2.js.map +1 -0
- package/dist/assets/{web-DwgdhfcY.js → web-68CYFCl9.js} +314 -91
- package/dist/assets/web-68CYFCl9.js.map +1 -0
- package/dist/ghostly.mjs +3 -5
- package/dist/ghostly.mjs.map +1 -1
- package/npm-shrinkwrap.json +225 -200
- package/package.json +16 -16
- package/dist/assets/api-MYc6QNRs.js.map +0 -1
- package/dist/assets/apiKit-CfsNx9ZR.js.map +0 -1
- package/dist/assets/appFetch-DVYZOZFw.js +0 -194
- package/dist/assets/appFetch-DVYZOZFw.js.map +0 -1
- package/dist/assets/apps-Dbw2Hcko.js +0 -2
- package/dist/assets/apps-h12II1us.js.map +0 -1
- package/dist/assets/arkade-Bw_4PZRG.js.map +0 -1
- package/dist/assets/backup-CdEzTq5C.js +0 -2
- package/dist/assets/backup-Chvy79SN.js.map +0 -1
- package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js +0 -6
- package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js.map +0 -1
- package/dist/assets/bitcoindProvider-BvoRh0D5.js +0 -97
- package/dist/assets/bitcoindProvider-BvoRh0D5.js.map +0 -1
- package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js +0 -6
- package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js.map +0 -1
- package/dist/assets/bitcoindevkit_bg-CRkZTSbO.wasm +0 -0
- package/dist/assets/buttons-BgoExb4E.js.map +0 -1
- package/dist/assets/buttons-DK2aAGat.js +0 -2
- package/dist/assets/endpoint-DarqblYE.js.map +0 -1
- package/dist/assets/errors-CAh6GLJZ.js.map +0 -1
- package/dist/assets/fedimint_client_wasm_bg-BtHHlFpp.js +0 -6
- package/dist/assets/fileBytes-BLPZq9YU.js.map +0 -1
- package/dist/assets/fileBytes-BtIyoDF2.js +0 -2
- package/dist/assets/fileBytesIdb-D8mAK4pF.js +0 -2
- package/dist/assets/host-C0NMNQLl.js.map +0 -1
- package/dist/assets/hyperdhtRelay-1wzya_0L.js +0 -25
- package/dist/assets/hyperdhtRelay-1wzya_0L.js.map +0 -1
- package/dist/assets/hyperdhtRelay-Dz7pvcBA.js.map +0 -1
- package/dist/assets/irohWeb-caAj4Dms.js.map +0 -1
- package/dist/assets/joinTrace-D-fnt2p3.js +0 -2
- package/dist/assets/jsonOut-POtMBS_V.js +0 -16
- package/dist/assets/jsonOut-POtMBS_V.js.map +0 -1
- package/dist/assets/main-C6t5zrD5.js.map +0 -1
- package/dist/assets/mainline-DCuGUSZF.js.map +0 -1
- package/dist/assets/mints-BaOmx517.js +0 -2
- package/dist/assets/mints-j5XAOk4f.js.map +0 -1
- package/dist/assets/nwcProvider-PE0wli8n.js +0 -88
- package/dist/assets/nwcProvider-PE0wli8n.js.map +0 -1
- package/dist/assets/ownDid-C1R5Kd8q.js +0 -282
- package/dist/assets/ownDid-C1R5Kd8q.js.map +0 -1
- package/dist/assets/ownStatus-BoTf5WqQ.js.map +0 -1
- package/dist/assets/profiles-DszHjEJi.js.map +0 -1
- package/dist/assets/registry-Da-r6eC3.js.map +0 -1
- package/dist/assets/registry-zUZBSHYv.js +0 -2
- package/dist/assets/resolve-tUzh4lHh.js +0 -400
- package/dist/assets/resolve-tUzh4lHh.js.map +0 -1
- package/dist/assets/secretGuard-DCb1I0_B.js +0 -2
- package/dist/assets/server-C1jZZ61O.js.map +0 -1
- package/dist/assets/src-DJe-OYxd.js.map +0 -1
- package/dist/assets/sshForges-C9zTO72R.js +0 -261
- package/dist/assets/sshForges-C9zTO72R.js.map +0 -1
- package/dist/assets/storage-Bya5b2Xt.js.map +0 -1
- package/dist/assets/tree-store-N362nuzZ.js.map +0 -1
- package/dist/assets/usdt-DI51znt-.js.map +0 -1
- package/dist/assets/waitNotice-Cn0WJ-He.js.map +0 -1
- package/dist/assets/web-DwgdhfcY.js.map +0 -1
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
// ../core/src/bytes.ts
|
|
2
|
+
var textEncoder = new TextEncoder();
|
|
3
|
+
var textDecoder = new TextDecoder("utf-8", { fatal: true });
|
|
4
|
+
function utf8Encode(str) {
|
|
5
|
+
return textEncoder.encode(str);
|
|
6
|
+
}
|
|
7
|
+
function utf8Decode(bytes) {
|
|
8
|
+
return textDecoder.decode(bytes);
|
|
9
|
+
}
|
|
10
|
+
function concatBytes(...parts) {
|
|
11
|
+
let length = 0;
|
|
12
|
+
for (const p of parts) length += p.length;
|
|
13
|
+
const out = new Uint8Array(length);
|
|
14
|
+
let offset = 0;
|
|
15
|
+
for (const p of parts) {
|
|
16
|
+
out.set(p, offset);
|
|
17
|
+
offset += p.length;
|
|
18
|
+
}
|
|
19
|
+
return out;
|
|
20
|
+
}
|
|
21
|
+
function bytesEqual(a, b) {
|
|
22
|
+
if (a.length !== b.length) return false;
|
|
23
|
+
let diff = 0;
|
|
24
|
+
for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
|
|
25
|
+
return diff === 0;
|
|
26
|
+
}
|
|
27
|
+
/** `Uint8Array.prototype.toBase64` (Node 25+, Chrome 140+, Firefox 133+, Safari 18.2+): ~200x the JS below. */
|
|
28
|
+
var nativeToBase64 = Uint8Array.prototype.toBase64;
|
|
29
|
+
var tableOf = (chars) => Uint8Array.from(chars, (c) => c.charCodeAt(0));
|
|
30
|
+
var BASE64_TABLE = tableOf("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
|
|
31
|
+
var BASE64URL_TABLE = tableOf("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");
|
|
32
|
+
/**
|
|
33
|
+
* Base64 where the runtime has no native encoder (Node 22 and 24, older WebViews): the characters go into bytes and
|
|
34
|
+
* become one string at the end. Every file chunk is encoded (files/3 `pf-data`), so this is on a transfer's path.
|
|
35
|
+
*/
|
|
36
|
+
function encodeBase64(bytes, table, pad) {
|
|
37
|
+
const out = new Uint8Array(Math.ceil(bytes.length / 3) * 4);
|
|
38
|
+
let o = 0, i = 0;
|
|
39
|
+
for (; i + 2 < bytes.length; i += 3) {
|
|
40
|
+
const n = bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2];
|
|
41
|
+
out[o++] = table[n >>> 18];
|
|
42
|
+
out[o++] = table[n >>> 12 & 63];
|
|
43
|
+
out[o++] = table[n >>> 6 & 63];
|
|
44
|
+
out[o++] = table[n & 63];
|
|
45
|
+
}
|
|
46
|
+
const rest = bytes.length - i;
|
|
47
|
+
if (rest) {
|
|
48
|
+
const n = bytes[i] << 16 | (rest === 2 ? bytes[i + 1] << 8 : 0);
|
|
49
|
+
out[o++] = table[n >>> 18];
|
|
50
|
+
out[o++] = table[n >>> 12 & 63];
|
|
51
|
+
if (rest === 2) out[o++] = table[n >>> 6 & 63];
|
|
52
|
+
else if (pad) out[o++] = 61;
|
|
53
|
+
if (pad) out[o++] = 61;
|
|
54
|
+
}
|
|
55
|
+
return textDecoder.decode(out.subarray(0, o));
|
|
56
|
+
}
|
|
57
|
+
function toBase64(bytes) {
|
|
58
|
+
return nativeToBase64 ? nativeToBase64.call(bytes) : encodeBase64(bytes, BASE64_TABLE, true);
|
|
59
|
+
}
|
|
60
|
+
function fromBase64(str) {
|
|
61
|
+
const binary = atob(str);
|
|
62
|
+
const bytes = new Uint8Array(binary.length);
|
|
63
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
64
|
+
return bytes;
|
|
65
|
+
}
|
|
66
|
+
function toBase64Url(bytes) {
|
|
67
|
+
return nativeToBase64 ? nativeToBase64.call(bytes, {
|
|
68
|
+
alphabet: "base64url",
|
|
69
|
+
omitPadding: true
|
|
70
|
+
}) : encodeBase64(bytes, BASE64URL_TABLE, false);
|
|
71
|
+
}
|
|
72
|
+
function fromBase64Url(str) {
|
|
73
|
+
let b = str.replace(/-/g, "+").replace(/_/g, "/");
|
|
74
|
+
while (b.length % 4) b += "=";
|
|
75
|
+
return fromBase64(b);
|
|
76
|
+
}
|
|
77
|
+
var Z32_ALPHABET = "ybndrfg8ejkmcpqxot1uwisza345h769";
|
|
78
|
+
function toZ32(bytes) {
|
|
79
|
+
let out = "";
|
|
80
|
+
let bits = 0;
|
|
81
|
+
let value = 0;
|
|
82
|
+
for (const byte of bytes) {
|
|
83
|
+
value = value << 8 | byte;
|
|
84
|
+
bits += 8;
|
|
85
|
+
while (bits >= 5) {
|
|
86
|
+
out += Z32_ALPHABET[value >>> bits - 5 & 31];
|
|
87
|
+
bits -= 5;
|
|
88
|
+
}
|
|
89
|
+
value &= (1 << bits) - 1;
|
|
90
|
+
}
|
|
91
|
+
if (bits > 0) out += Z32_ALPHABET[value << 5 - bits & 31];
|
|
92
|
+
return out;
|
|
93
|
+
}
|
|
94
|
+
function fromZ32(str) {
|
|
95
|
+
const out = new Uint8Array(Math.floor(str.length * 5 / 8));
|
|
96
|
+
let bits = 0;
|
|
97
|
+
let value = 0;
|
|
98
|
+
let index = 0;
|
|
99
|
+
for (const char of str) {
|
|
100
|
+
const v = Z32_ALPHABET.indexOf(char);
|
|
101
|
+
if (v < 0) throw new Error(`Invalid z-base-32 character: ${char}`);
|
|
102
|
+
value = value << 5 | v;
|
|
103
|
+
bits += 5;
|
|
104
|
+
if (bits >= 8) {
|
|
105
|
+
out[index++] = value >>> bits - 8 & 255;
|
|
106
|
+
bits -= 8;
|
|
107
|
+
}
|
|
108
|
+
value &= (1 << bits) - 1;
|
|
109
|
+
}
|
|
110
|
+
return out;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* A 32-byte key written as the one z-base-32 spelling `toZ32` produces: 52 characters that decode to 32 bytes and
|
|
114
|
+
* encode back to the same string. The last character carries four zero padding bits, so each key has exactly one
|
|
115
|
+
* spelling and keys may be compared as strings (WISP 02). Any other spelling is not a key here.
|
|
116
|
+
*/
|
|
117
|
+
function isZ32Key(value) {
|
|
118
|
+
if (typeof value !== "string" || value.length !== 52) return false;
|
|
119
|
+
try {
|
|
120
|
+
return toZ32(fromZ32(value)) === value;
|
|
121
|
+
} catch {
|
|
122
|
+
return false;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
function randomBytes(length) {
|
|
126
|
+
const bytes = new Uint8Array(length);
|
|
127
|
+
crypto.getRandomValues(bytes);
|
|
128
|
+
return bytes;
|
|
129
|
+
}
|
|
130
|
+
export { fromZ32 as a, toBase64 as c, utf8Decode as d, utf8Encode as f, fromBase64Url as i, toBase64Url as l, concatBytes as n, isZ32Key as o, fromBase64 as r, randomBytes as s, bytesEqual as t, toZ32 as u };
|
|
131
|
+
|
|
132
|
+
//# sourceMappingURL=bytes-C1DNGY18.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bytes-C1DNGY18.js","names":[],"sources":["../../../core/src/bytes.ts"],"sourcesContent":["const textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder(\"utf-8\", { fatal: true });\n\nexport function utf8Encode(str: string): Uint8Array {\n return textEncoder.encode(str);\n}\n\nexport function utf8Decode(bytes: Uint8Array): string {\n return textDecoder.decode(bytes);\n}\n\nexport function concatBytes(...parts: Uint8Array[]): Uint8Array {\n let length = 0;\n for (const p of parts) length += p.length;\n const out = new Uint8Array(length);\n let offset = 0;\n for (const p of parts) {\n out.set(p, offset);\n offset += p.length;\n }\n return out;\n}\n\nexport function bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\ntype NativeToBase64 = (this: Uint8Array, options?: { alphabet?: \"base64\" | \"base64url\"; omitPadding?: boolean }) => string;\n/** `Uint8Array.prototype.toBase64` (Node 25+, Chrome 140+, Firefox 133+, Safari 18.2+): ~200x the JS below. */\nconst nativeToBase64 = (Uint8Array.prototype as { toBase64?: NativeToBase64 }).toBase64;\n\nconst tableOf = (chars: string) => Uint8Array.from(chars, (c) => c.charCodeAt(0));\nconst BASE64_TABLE = tableOf(\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\");\nconst BASE64URL_TABLE = tableOf(\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\");\n\n/**\n * Base64 where the runtime has no native encoder (Node 22 and 24, older WebViews): the characters go into bytes and\n * become one string at the end. Every file chunk is encoded (files/3 `pf-data`), so this is on a transfer's path.\n */\nfunction encodeBase64(bytes: Uint8Array, table: Uint8Array, pad: boolean): string {\n const out = new Uint8Array(Math.ceil(bytes.length / 3) * 4);\n let o = 0, i = 0;\n for (; i + 2 < bytes.length; i += 3) {\n const n = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];\n out[o++] = table[n >>> 18];\n out[o++] = table[(n >>> 12) & 63];\n out[o++] = table[(n >>> 6) & 63];\n out[o++] = table[n & 63];\n }\n const rest = bytes.length - i;\n if (rest) {\n const n = (bytes[i] << 16) | (rest === 2 ? bytes[i + 1] << 8 : 0);\n out[o++] = table[n >>> 18];\n out[o++] = table[(n >>> 12) & 63];\n if (rest === 2) out[o++] = table[(n >>> 6) & 63];\n else if (pad) out[o++] = 61; // \"=\"\n if (pad) out[o++] = 61;\n }\n return textDecoder.decode(out.subarray(0, o));\n}\n\nexport function toBase64(bytes: Uint8Array): string {\n return nativeToBase64 ? nativeToBase64.call(bytes) : encodeBase64(bytes, BASE64_TABLE, true);\n}\n\nexport function fromBase64(str: string): Uint8Array {\n const binary = atob(str);\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\nexport function toBase64Url(bytes: Uint8Array): string {\n return nativeToBase64 ? nativeToBase64.call(bytes, { alphabet: \"base64url\", omitPadding: true }) : encodeBase64(bytes, BASE64URL_TABLE, false);\n}\n\nexport function fromBase64Url(str: string): Uint8Array {\n let b = str.replace(/-/g, \"+\").replace(/_/g, \"/\");\n while (b.length % 4) b += \"=\";\n return fromBase64(b);\n}\n\nconst Z32_ALPHABET = \"ybndrfg8ejkmcpqxot1uwisza345h769\";\n\nexport function toZ32(bytes: Uint8Array): string {\n let out = \"\";\n let bits = 0;\n let value = 0;\n for (const byte of bytes) {\n value = (value << 8) | byte;\n bits += 8;\n while (bits >= 5) {\n out += Z32_ALPHABET[(value >>> (bits - 5)) & 31];\n bits -= 5;\n }\n value &= (1 << bits) - 1;\n }\n if (bits > 0) out += Z32_ALPHABET[(value << (5 - bits)) & 31];\n return out;\n}\n\nexport function fromZ32(str: string): Uint8Array {\n const out = new Uint8Array(Math.floor((str.length * 5) / 8));\n let bits = 0;\n let value = 0;\n let index = 0;\n for (const char of str) {\n const v = Z32_ALPHABET.indexOf(char);\n if (v < 0) throw new Error(`Invalid z-base-32 character: ${char}`);\n value = (value << 5) | v;\n bits += 5;\n if (bits >= 8) {\n out[index++] = (value >>> (bits - 8)) & 0xff;\n bits -= 8;\n }\n value &= (1 << bits) - 1;\n }\n return out;\n}\n\n/**\n * A 32-byte key written as the one z-base-32 spelling `toZ32` produces: 52 characters that decode to 32 bytes and\n * encode back to the same string. The last character carries four zero padding bits, so each key has exactly one\n * spelling and keys may be compared as strings (WISP 02). Any other spelling is not a key here.\n */\nexport function isZ32Key(value: unknown): value is string {\n if (typeof value !== \"string\" || value.length !== 52) return false;\n try { return toZ32(fromZ32(value)) === value; } catch { return false; }\n}\n\nexport function randomBytes(length: number): Uint8Array {\n const bytes = new Uint8Array(length);\n crypto.getRandomValues(bytes);\n return bytes;\n}\n"],"mappings":";AAAA,IAAM,cAAc,IAAI,YAAY;AACpC,IAAM,cAAc,IAAI,YAAY,SAAS,EAAE,OAAO,KAAK,CAAC;AAE5D,SAAgB,WAAW,KAAyB;CAClD,OAAO,YAAY,OAAO,GAAG;AAC/B;AAEA,SAAgB,WAAW,OAA2B;CACpD,OAAO,YAAY,OAAO,KAAK;AACjC;AAEA,SAAgB,YAAY,GAAG,OAAiC;CAC9D,IAAI,SAAS;CACb,KAAK,MAAM,KAAK,OAAO,UAAU,EAAE;CACnC,MAAM,MAAM,IAAI,WAAW,MAAM;CACjC,IAAI,SAAS;CACb,KAAK,MAAM,KAAK,OAAO;EACrB,IAAI,IAAI,GAAG,MAAM;EACjB,UAAU,EAAE;CACd;CACA,OAAO;AACT;AAEA,SAAgB,WAAW,GAAe,GAAwB;CAChE,IAAI,EAAE,WAAW,EAAE,QAAQ,OAAO;CAClC,IAAI,OAAO;CACX,KAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK,QAAQ,EAAE,KAAK,EAAE;CACpD,OAAO,SAAS;AAClB;;AAIA,IAAM,iBAAkB,WAAW,UAA4C;AAE/E,IAAM,WAAW,UAAkB,WAAW,KAAK,QAAQ,MAAM,EAAE,WAAW,CAAC,CAAC;AAChF,IAAM,eAAe,QAAQ,kEAAkE;AAC/F,IAAM,kBAAkB,QAAQ,kEAAkE;;;;;AAMlG,SAAS,aAAa,OAAmB,OAAmB,KAAsB;CAChF,MAAM,MAAM,IAAI,WAAW,KAAK,KAAK,MAAM,SAAS,CAAC,IAAI,CAAC;CAC1D,IAAI,IAAI,GAAG,IAAI;CACf,OAAO,IAAI,IAAI,MAAM,QAAQ,KAAK,GAAG;EACnC,MAAM,IAAK,MAAM,MAAM,K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V,IAAI,OAAO;CACX,IAAI,QAAQ;CACZ,KAAK,MAAM,QAAQ,OAAO;EACxB,QAAS,SAAS,IAAK;EACvB,QAAQ;EACR,OAAO,QAAQ,GAAG;GAChB,OAAO,aAAc,UAAW,OAAO,IAAM;GAC7C,QAAQ;EACV;EACA,UAAU,KAAK,QAAQ;CACzB;CACA,IAAI,OAAO,GAAG,OAAO,aAAc,SAAU,IAAI,OAAS;CAC1D,OAAO;AACT;AAEA,SAAgB,QAAQ,KAAyB;CAC/C,MAAM,MAAM,IAAI,WAAW,KAAK,MAAO,IAAI,SAAS,IAAK,CAAC,CAAC;CAC3D,IAAI,OAAO;CACX,IAAI,QAAQ;CACZ,IAAI,QAAQ;CACZ,KAAK,MAAM,QAAQ,KAAK;EACtB,MAAM,IAAI,aAAa,QAAQ,IAAI;EACnC,IAAI,IAAI,GAAG,MAAM,IAAI,MAAM,gCAAgC,MAAM;EACjE,QAAS,SAAS,IAAK;EACvB,QAAQ;EACR,IAAI,QAAQ,GAAG;GACb,IAAI,WAAY,UAAW,OAAO,IAAM;GACxC,QAAQ;EACV;EACA,UAAU,KAAK,QAAQ;CACzB;CACA,OAAO;AACT;;;;;;AAOA,SAAgB,SAAS,OAAiC;CACxD,IAAI,OAAO,UAAU,YAAY,MAAM,WAAW,IAAI,OAAO;CAC7D,IAAI;EAAE,OAAO,MAAM,QAAQ,KAAK,CAAC,MAAM;CAAO,QAAQ;EAAE,OAAO;CAAO;AACxE;AAEA,SAAgB,YAAY,QAA4B;CACtD,MAAM,QAAQ,IAAI,WAAW,MAAM;CACnC,OAAO,gBAAgB,KAAK;CAC5B,OAAO;AACT"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/childEnv.ts
|
|
2
2
|
/**
|
|
3
3
|
* Environment variables only the command that reads them needs: the backup passphrase is read by a one-shot
|
|
4
4
|
* `profile backup`/`profile restore` and sent as a call parameter, so no other process (the daemon, a hook, ffmpeg,
|
|
@@ -16,7 +16,6 @@ function childEnv(env = process.env) {
|
|
|
16
16
|
function dropSecretEnv(env = process.env) {
|
|
17
17
|
for (const name of SECRET_ENV) delete env[name];
|
|
18
18
|
}
|
|
19
|
-
//#endregion
|
|
20
19
|
export { dropSecretEnv as n, childEnv as t };
|
|
21
20
|
|
|
22
|
-
//# sourceMappingURL=childEnv-
|
|
21
|
+
//# sourceMappingURL=childEnv-C-99hdbL.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"childEnv-
|
|
1
|
+
{"version":3,"file":"childEnv-C-99hdbL.js","names":[],"sources":["../../src/childEnv.ts"],"sourcesContent":["/**\n * Environment variables only the command that reads them needs: the backup passphrase is read by a one-shot\n * `profile backup`/`profile restore` and sent as a call parameter, so no other process (the daemon, a hook, ffmpeg,\n * the translator, `ps`, `xattr`) ever needs it; `listen` reads its webhook's URL (a bridge's token in it) once, at the\n * start, and a hook it runs never needs it. The one list every child's environment is cleaned with.\n */\nexport const SECRET_ENV = [\"GHOSTLY_BACKUP_PASSPHRASE\", \"GHOSTLY_WEBHOOK\"] as const;\n\n/** `env` less the secrets in `SECRET_ENV`: what a process this one starts gets. */\nexport function childEnv(env: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {\n const rest = { ...env };\n for (const name of SECRET_ENV) delete rest[name];\n return rest;\n}\n\n/** Removes the secrets in `SECRET_ENV` from this process's own environment (the daemon, which never reads them). */\nexport function dropSecretEnv(env: NodeJS.ProcessEnv = process.env): void {\n for (const name of SECRET_ENV) delete env[name];\n}\n"],"mappings":";;;;;;;AAMA,IAAa,aAAa,CAAC,6BAA6B,iBAAiB;;AAGzE,SAAgB,SAAS,MAAyB,QAAQ,KAAwB;CAChF,MAAM,OAAO,EAAE,GAAG,IAAI;CACtB,KAAK,MAAM,QAAQ,YAAY,OAAO,KAAK;CAC3C,OAAO;AACT;;AAGA,SAAgB,cAAc,MAAyB,QAAQ,KAAW;CACxE,KAAK,MAAM,QAAQ,YAAY,OAAO,IAAI;AAC5C"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as CliError } from "./errors-
|
|
2
|
-
import { T as ownSocket, h as lockPath } from "./profiles-
|
|
1
|
+
import { t as CliError } from "./errors-DDLFO4Gf.js";
|
|
2
|
+
import { T as ownSocket, h as lockPath } from "./profiles-BFSGqDFC.js";
|
|
3
3
|
import { closeSync, lstatSync, openSync, readFileSync, rmSync, writeSync } from "node:fs";
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
@@ -141,8 +141,7 @@ var PlaybackQueue = class {
|
|
|
141
141
|
return out;
|
|
142
142
|
}
|
|
143
143
|
};
|
|
144
|
-
|
|
145
|
-
//#region src/daemonProof.ts
|
|
144
|
+
// src/daemonProof.ts
|
|
146
145
|
/**
|
|
147
146
|
* How a client knows the process on the profile's socket is the profile's daemon (WISP 1100 § Local control API).
|
|
148
147
|
* On Windows the socket is a named pipe whose name follows from the profile's path, and any account of the machine
|
|
@@ -260,8 +259,7 @@ function provesDaemon(secret, nonce, answer) {
|
|
|
260
259
|
if (typeof given !== "string" || !/^[0-9a-f]{64}$/.test(given)) return false;
|
|
261
260
|
return timingSafeEqual(Buffer.from(given, "hex"), Buffer.from(proof(secret, "daemon", nonce), "hex"));
|
|
262
261
|
}
|
|
263
|
-
|
|
264
|
-
//#region src/client.ts
|
|
262
|
+
// src/client.ts
|
|
265
263
|
/** The id of the hello on every connection: a string, so it is never one of the calls' numbers. */
|
|
266
264
|
var HELLO_ID = "hello";
|
|
267
265
|
/**
|
|
@@ -566,7 +564,6 @@ function connectDaemon(address, timeoutMs = 2e3, { greetingMs = GREETING_MS } =
|
|
|
566
564
|
});
|
|
567
565
|
});
|
|
568
566
|
}
|
|
569
|
-
//#endregion
|
|
570
567
|
export { frameBytes as _, endedUnsent as a, monotonic as b, HELLO as c, proof as d, removeDaemonSecret as f, bytesToMs as g, PlaybackQueue as h, endedUnanswered as i, greeting as l, DEFAULT_RATE as m, MAX_LINE as n, isNotTheDaemon as o, CALL_RATES as p, connectDaemon as r, notTheDaemon as s, DaemonClient as t, newDaemonSecret as u, frameSamples as v, isCallRate as y };
|
|
571
568
|
|
|
572
|
-
//# sourceMappingURL=client-
|
|
569
|
+
//# sourceMappingURL=client-kGZ3ZdUW.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client-DY8tZZWi.js","names":[],"sources":["../../src/calls/pcm.ts","../../src/daemonProof.ts","../../src/client.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 * The call's own clock, in ms: monotonic, so the device's clock set back or ahead mid-call (a phone or a VM fixing its\n * time) moves the time of day, not the audio. On `Date.now()`, a clock set back held the next frame for as long as the\n * jump, and one set ahead read as that long without a packet from the contact.\n */\nexport const monotonic = (): number => performance.now();\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 /** Half a sample was dropped (a flush, a full queue): the program's next byte is its other half, dropped too. */\n private owed = false;\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 = monotonic, 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 if (this.owed) {\n this.owed = false;\n chunk = chunk.subarray(1);\n }\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 // The queue ends on a whole sample here, so an odd number lost ends on half of one.\n if (lost % 2) this.owed = true;\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 // Half a sample queued: its other half is the program's next byte.\n if (this.length % 2) this.owed = true;\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 /**\n * Another program writes from now on (it replaced the last one on the call's socket): what the last one left is\n * dropped, half a sample included, so the new one starts on a whole sample and is heard at once. Returns how much\n * was dropped, in milliseconds.\n */\n newWriter(): number {\n const ms = this.queuedMs;\n this.chunks = [];\n this.head = 0;\n this.length = 0;\n // A flush that cut the last program's half sample owes nothing to the next program: it starts on a whole sample.\n this.owed = false;\n return 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","import { readFileSync } from \"node:fs\";\nimport { connect, type Socket } from \"node:net\";\nimport { createInterface } from \"node:readline\";\nimport { CliError, type ErrorCode } from \"./errors\";\nimport type { GhostlyEvent } from \"./events\";\nimport { daemonOfThisRelease, HELLO, newNonce, provesDaemon, provesGreeting, readDaemonSecret } from \"./daemonProof\";\nimport { ownSocket } from \"./privateFolder\";\nimport { lockPath } from \"./profiles\";\n\n/** The id of the hello on every connection: a string, so it is never one of the calls' numbers. */\nconst HELLO_ID = \"hello\";\n\n/**\n * How long a client waits for the daemon's greeting before it asks who holds the profile: a daemon greets as it\n * accepts the connection, and one of an older release (before the greeting) never does. A daemon of this release\n * holding the profile (`daemonOfThisRelease`) is busy and is waited for, under each call's own deadline; anything\n * else is refused then. It used to refuse every late greeting, after 10 s: a daemon busy that long on one task (an\n * outbox backlog, 14 to 29 s) had every command and `listen` refused as an older release's, to be restarted.\n */\nexport const GREETING_MS = 2_000;\n\n/** The longest request line the daemon reads (WISP 1100 § Framing): it cuts the connection on a longer one. */\nexport const MAX_LINE = 16 * 1024 * 1024;\n\n/** What a client needs of a profile to reach its daemon: the socket, and the folder the daemon's secret is in. */\nexport interface DaemonAddress { socket: string; dir: string }\n\n/**\n * The refusal of a listener that did not prove it is the profile's daemon (`isNotTheDaemon` tells it apart). With nobody\n * holding the profile it is no daemon of any release, and no restart moves it: the answer pointed at `daemon restart`,\n * which answered the same, and a start said a daemon ran. What listens there has to stop, or its file go. `held`: whether\n * a process holds the profile, as the caller knows it (`lockOwner`); read here as a greeting's proof reads it otherwise.\n */\nexport function notTheDaemon(address: DaemonAddress, held = profileHeld(address.dir)): CliError {\n if (!held) {\n return new CliError(\"refused\", `Something that is not this profile's daemon listens on ${address.socket}, and no ghostly process holds the profile: nothing was sent to it. Stop the program that listens there, or remove that file, then start the daemon with ghostly daemon --detach`, { reason: \"not-the-daemon\", socket: address.socket });\n }\n return new CliError(\"refused\", `What answers on ${address.socket} did not prove it is this profile's daemon, so nothing was sent to it. A daemon of an older release cannot: \\`ghostly daemon restart\\` starts this one's`, { reason: \"not-the-daemon\" });\n}\n\n/** Whether a live process of this user's is in the profile's lock (`daemonProof.ts` reads it the same way). */\nfunction profileHeld(dir: string): boolean {\n try {\n const pid = Number(readFileSync(lockPath(dir), \"utf8\").trim());\n if (!Number.isSafeInteger(pid) || pid <= 0) return false;\n process.kill(pid, 0);\n return true;\n } catch { return false; }\n}\n\n/** The failures of calls whose connection ended unanswered (`endedUnanswered`), not answers the daemon gave. */\nconst unanswered = new WeakSet<CliError>();\n\n/**\n * A call the daemon read and never answered, because it stopped (a restart, a crash): what was asked may be done, so\n * it is no plain failure a bot tries again (a send went twice). A daemon that stops answers its waits first (`serve`);\n * this is for the calls it could not.\n */\nfunction stoppedUnanswered(method: string): CliError {\n const error = new CliError(\"timeout\", `The daemon stopped before it answered ${method}, which may be done: check (\\`ghostly chat history\\` for a message) before you try again`, { method, reason: \"daemon-stopped\" });\n unanswered.add(error);\n return error;\n}\n\n/**\n * A call whose connection ended before the daemon read it, or before it proved itself: nothing was done. `leaving`: this\n * client ended it (a deadline, Ctrl-C), so it is no daemon that stopped under the call.\n */\nfunction wentAway(leaving: boolean): CliError {\n const error = new CliError(\"unavailable\", \"The daemon went away\");\n if (!leaving) unanswered.add(error);\n return error;\n}\n\n/**\n * Whether a call failed because its connection ended unanswered (the daemon stopped, restarted or crashed under it),\n * not because the daemon answered it with an error. A read that did can be asked again: it changed nothing. So may one\n * refused because the daemon's secret was gone when its greeting or its hello's answer came: a daemon that stops removes\n * it first, and the greeting it wrote just before is read after. Nothing but the hello was written to it, and a listener\n * that never proves itself is refused again on the new connection.\n */\nexport function endedUnanswered(error: unknown): boolean {\n return error instanceof CliError && unanswered.has(error);\n}\n\n/**\n * Whether a call ended unanswered before it was written (`endedUnanswered`, and not a call the daemon read: those are\n * `daemon-stopped`): nothing reached the daemon, so the call may go to the daemon that runs next, whatever it does.\n */\nexport function endedUnsent(error: unknown): boolean {\n return endedUnanswered(error) && (error as CliError).details?.reason !== \"daemon-stopped\";\n}\n\nexport function isNotTheDaemon(error: unknown): boolean {\n return error instanceof CliError && error.code === \"refused\" && error.details?.reason === \"not-the-daemon\";\n}\n\n/**\n * A connection to a profile's daemon over its socket (WISP 1100 § Local control API). `null` from `connectDaemon`\n * means no daemon answers there: a one-shot command runs the profile itself.\n *\n * The client writes nothing on it until the daemon's greeting, its first line, proves the other end read the\n * profile's daemon secret and holds the profile's lock (`provesGreeting`): a listener that cannot prove it has read\n * nothing from this client, so it cannot impersonate it either (`daemonProof.ts`). Then the first line written is a\n * `daemon.hello`, and no call is written until its answer proves the same over the client's own nonce. Until then\n * every call waits, under its own deadline, and a listener that does not prove both gets every call refused\n * (`refused`, `isNotTheDaemon`). Nothing it writes before that is read either.\n */\nexport class DaemonClient {\n private nextId = 1;\n /** `written`: the call is on the socket, so the daemon may have acted on it. */\n private readonly pending = new Map<number, { method: string; written: boolean; resolve: (value: unknown) => void; reject: (error: Error) => void }>();\n /** This client closed the connection: what was still unanswered is its own doing, not a daemon that stopped. */\n private leaving = false;\n private eventListener: ((event: GhostlyEvent) => void) | null = null;\n private closedListener: (() => void) | null = null;\n /** While paused: the events of the chunk already read, given to the listener on resume. */\n private held: GhostlyEvent[] | null = null;\n private greeted = false;\n private verified = false;\n private refusal: CliError | null = null;\n private readonly ready: Promise<void>;\n private settle!: { resolve: () => void; reject: (error: CliError) => void };\n\n constructor(private readonly socket: Socket, private readonly address: DaemonAddress, greetingMs = GREETING_MS) {\n this.ready = new Promise<void>((resolve, reject) => { this.settle = { resolve, reject }; });\n this.ready.catch(() => {});\n const nonce = newNonce();\n // Nothing is written until the greeting either way: a busy daemon only keeps the calls waiting.\n const waitedTooLong = setTimeout(() => { if (!this.greeted && !this.refusal && !daemonOfThisRelease(this.address.dir)) this.refuse(); }, greetingMs);\n waitedTooLong.unref?.();\n const lines = createInterface({ input: socket, crlfDelay: Infinity });\n // readline passes on its input's errors: a daemon that went away with this client's lines unread (ECONNRESET) ended\n // the command on an unhandled 'error' instead of the close below (unavailable).\n lines.on(\"error\", () => {});\n lines.on(\"line\", (line) => {\n let message: { id?: number | string; result?: unknown; error?: { code: ErrorCode; message: string; details?: Record<string, unknown> }; event?: GhostlyEvent };\n // A first line that is not even JSON is no greeting: refused as one that does not prove itself.\n try { message = JSON.parse(line); } catch { if (!this.greeted && !this.refusal) this.refuse(); return; }\n if (this.refusal) return;\n if (!this.greeted) {\n clearTimeout(waitedTooLong);\n // The secret is read once a listener spoke: the daemon wrote it before it listened.\n const secret = readDaemonSecret(this.address.dir);\n if (!secret || !provesGreeting(secret, this.address.dir, message)) { this.refuse(!secret); return; }\n this.greeted = true;\n // A client closed before the greeting came (a start's readiness probe) has nothing to say.\n if (socket.writableEnded || socket.destroyed) return;\n socket.write(JSON.stringify({ id: HELLO_ID, method: HELLO, params: { nonce } }) + \"\\n\");\n return;\n }\n if (!this.verified) {\n if (message?.id !== HELLO_ID) return;\n // The secret is read once a listener answered: the daemon wrote it before it listened.\n const secret = readDaemonSecret(this.address.dir);\n if (!message.error && secret && provesDaemon(secret, nonce, message.result)) { this.verified = true; this.settle.resolve(); return; }\n this.refuse(!secret);\n return;\n }\n if (message.event) { if (this.held) this.held.push(message.event); else this.eventListener?.(message.event); return; }\n const waiting = typeof message.id === \"number\" ? this.pending.get(message.id) : undefined;\n if (!waiting) return;\n this.pending.delete(message.id as number);\n if (message.error) waiting.reject(new CliError(message.error.code, message.error.message, message.error.details));\n else waiting.resolve(message.result);\n });\n socket.on(\"close\", () => {\n clearTimeout(waitedTooLong);\n const why = this.refusal ?? wentAway(this.leaving);\n if (!this.verified) this.settle.reject(why);\n for (const waiting of this.pending.values()) waiting.reject(waiting.written && !this.refusal && !this.leaving ? stoppedUnanswered(waiting.method) : why);\n this.pending.clear();\n this.closedListener?.();\n });\n socket.on(\"error\", () => {});\n }\n\n /** `secretGone`: the daemon's secret was not there to check against, as when it stops (`endedUnanswered`). */\n private refuse(secretGone = false): void {\n this.refusal = notTheDaemon(this.address);\n if (secretGone) unanswered.add(this.refusal);\n this.settle.reject(this.refusal);\n this.socket.destroy();\n }\n\n /**\n * `timeoutMs`: give up (code `timeout`, exit 4) when the daemon has not answered by then; without it the call waits\n * for as long as the connection holds. A call that timed out closes the connection: its answer, if one ever comes,\n * is of no use, and the process leaves once nothing else keeps it (not every caller reaches `exit`).\n *\n * A call whose line is longer than `MAX_LINE` is refused here, never written: the daemon cut the connection on it,\n * and the command answered \"The daemon went away\" (`unavailable`, read as try later) while the daemon ran on.\n */\n call(method: string, params: unknown = {}, { timeoutMs }: { timeoutMs?: number } = {}): Promise<unknown> {\n if (this.socket.destroyed) return Promise.reject(this.refusal ?? wentAway(this.leaving));\n const id = this.nextId++;\n const line = JSON.stringify({ id, method, params }) + \"\\n\";\n const bytes = Buffer.byteLength(line);\n if (bytes > MAX_LINE) return Promise.reject(new CliError(\"bad_request\", `${method} came to ${(bytes / 1024 / 1024).toFixed(1)} MiB as JSON, more than a daemon reads in one request (16 MiB): nothing was sent (a long text goes as a file: ghostly file send <chat|group> <path>)`));\n return new Promise((resolve, reject) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n if (timeoutMs !== undefined) {\n timer = setTimeout(() => {\n if (!this.pending.delete(id)) return;\n reject(new CliError(\"timeout\", `The daemon did not answer ${method} in ${timeoutMs / 1000} s: \\`ghostly daemon restart\\` starts a fresh one`, { method }));\n this.destroy();\n }, timeoutMs);\n timer.unref?.();\n }\n const settle = {\n method, written: false,\n resolve: (value: unknown) => { if (timer) clearTimeout(timer); resolve(value); },\n reject: (error: Error) => { if (timer) clearTimeout(timer); reject(error); },\n };\n this.pending.set(id, settle);\n // Written once the daemon proved itself, in the order the calls were made; a refusal ends each instead.\n this.ready.then(\n () => {\n if (!this.pending.has(id) || this.socket.destroyed) return;\n this.socket.write(line);\n settle.written = true;\n },\n (error: CliError) => { if (this.pending.delete(id)) settle.reject(error); },\n );\n });\n }\n\n /** Events after `since` (replayed from the journal), then every new one, until the connection closes. */\n async subscribe(since: number | undefined, listener: (event: GhostlyEvent) => void, onClosed?: () => void): Promise<{ lastSeq: number }> {\n this.eventListener = listener;\n this.closedListener = onClosed ?? null;\n return this.call(\"events.subscribe\", since === undefined ? {} : { since }) as Promise<{ lastSeq: number }>;\n }\n\n /**\n * Stops reading: what the daemon sends waits in the connection (and past its bound the daemon ends it), and no\n * event reaches the listener until `resume`.\n */\n pause(): void {\n if (this.held) return;\n this.held = [];\n this.socket.pause();\n }\n\n /** Gives the listener the events held, then reads again; a listener that pauses again keeps the rest held. */\n resume(): void {\n const held = this.held;\n if (!held) return;\n this.held = null;\n for (let i = 0; i < held.length; i++) {\n this.eventListener?.(held[i]);\n if (this.held) { (this.held as GhostlyEvent[]).unshift(...held.slice(i + 1)); return; }\n }\n this.socket.resume();\n }\n\n close(): void {\n this.leaving = true;\n this.socket.end();\n }\n\n /** Closes at once: what the daemon still sends is not read. */\n destroy(): void {\n this.leaving = true;\n this.socket.destroy();\n }\n}\n\n/**\n * `timeoutMs` bounds the connect only; `greetingMs`, the wait for the daemon's greeting (above). The client it gives\n * has written nothing yet; whether the listener is the daemon is known at the first call.\n */\nexport function connectDaemon(address: DaemonAddress, timeoutMs = 2_000, { greetingMs = GREETING_MS }: { greetingMs?: number } = {}): Promise<DaemonClient | null> {\n const path = address.socket;\n // Someone else's socket (or a link) where the daemon's should be is no daemon of this profile's.\n if (!ownSocket(path)) return Promise.resolve(null);\n return new Promise((resolve) => {\n const socket = connect(path);\n const timer = setTimeout(() => { socket.destroy(); resolve(null); }, timeoutMs);\n socket.once(\"connect\", () => { clearTimeout(timer); resolve(new DaemonClient(socket, address, greetingMs)); });\n socket.once(\"error\", () => { clearTimeout(timer); resolve(null); });\n });\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;;;;;;AAa5B,IAAa,kBAA0B,YAAY,IAAI;;;;;AAMvD,IAAa,gBAAb,MAA2B;CAaJ;CAAiC;CAZtD,SAA2B,CAAC;CAC5B,OAAe;CACf,SAAiB;CACjB,WAAmB;;CAEnB,OAAe;CACf;CACA;CACA;;CAEA,UAAU;CAEV,YAAY,MAAyB,MAAqC,WAAW,QAAQ,cAAc;EAAtF,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,IAAI,KAAK,MAAM;GACb,KAAK,OAAO;GACZ,QAAQ,MAAM,SAAS,CAAC;EAC1B;EACA,MAAM,OAAO,KAAK,MAAM,KAAK;EAC7B,MAAM,OAAO,MAAM,UAAU,OAAO,QAAQ,MAAM,SAAS,GAAG,KAAK,IAAI,GAAG,IAAI,CAAC;EAC/E,MAAM,OA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CAEA,QAAc;EACZ,KAAK,UAAU;EACf,KAAK,OAAO,IAAI;CAClB;;CAGA,UAAgB;EACd,KAAK,UAAU;EACf,KAAK,OAAO,QAAQ;CACtB;AACF;;;;;AAMA,SAAgB,cAAc,SAAwB,YAAY,KAAO,EAAE,aAAa,gBAAyC,CAAC,GAAiC;CACjK,MAAM,OAAO,QAAQ;CAErB,IAAI,CAAC,UAAU,IAAI,GAAG,OAAO,QAAQ,QAAQ,IAAI;CACjD,OAAO,IAAI,SAAS,YAAY;EAC9B,MAAM,SAAS,QAAQ,IAAI;EAC3B,MAAM,QAAQ,iBAAiB;GAAE,OAAO,QAAQ;GAAG,QAAQ,IAAI;EAAG,GAAG,SAAS;EAC9E,OAAO,KAAK,iBAAiB;GAAE,aAAa,KAAK;GAAG,QAAQ,IAAI,aAAa,QAAQ,SAAS,UAAU,CAAC;EAAG,CAAC;EAC7G,OAAO,KAAK,eAAe;GAAE,aAAa,KAAK;GAAG,QAAQ,IAAI;EAAG,CAAC;CACpE,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"client-kGZ3ZdUW.js","names":[],"sources":["../../src/calls/pcm.ts","../../src/daemonProof.ts","../../src/client.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 * The call's own clock, in ms: monotonic, so the device's clock set back or ahead mid-call (a phone or a VM fixing its\n * time) moves the time of day, not the audio. On `Date.now()`, a clock set back held the next frame for as long as the\n * jump, and one set ahead read as that long without a packet from the contact.\n */\nexport const monotonic = (): number => performance.now();\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 /** Half a sample was dropped (a flush, a full queue): the program's next byte is its other half, dropped too. */\n private owed = false;\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 = monotonic, 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 if (this.owed) {\n this.owed = false;\n chunk = chunk.subarray(1);\n }\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 // The queue ends on a whole sample here, so an odd number lost ends on half of one.\n if (lost % 2) this.owed = true;\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 // Half a sample queued: its other half is the program's next byte.\n if (this.length % 2) this.owed = true;\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 /**\n * Another program writes from now on (it replaced the last one on the call's socket): what the last one left is\n * dropped, half a sample included, so the new one starts on a whole sample and is heard at once. Returns how much\n * was dropped, in milliseconds.\n */\n newWriter(): number {\n const ms = this.queuedMs;\n this.chunks = [];\n this.head = 0;\n this.length = 0;\n // A flush that cut the last program's half sample owes nothing to the next program: it starts on a whole sample.\n this.owed = false;\n return 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","import { readFileSync } from \"node:fs\";\nimport { connect, type Socket } from \"node:net\";\nimport { createInterface } from \"node:readline\";\nimport { CliError, type ErrorCode } from \"./errors\";\nimport type { GhostlyEvent } from \"./events\";\nimport { daemonOfThisRelease, HELLO, newNonce, provesDaemon, provesGreeting, readDaemonSecret } from \"./daemonProof\";\nimport { ownSocket } from \"./privateFolder\";\nimport { lockPath } from \"./profiles\";\n\n/** The id of the hello on every connection: a string, so it is never one of the calls' numbers. */\nconst HELLO_ID = \"hello\";\n\n/**\n * How long a client waits for the daemon's greeting before it asks who holds the profile: a daemon greets as it\n * accepts the connection, and one of an older release (before the greeting) never does. A daemon of this release\n * holding the profile (`daemonOfThisRelease`) is busy and is waited for, under each call's own deadline; anything\n * else is refused then. It used to refuse every late greeting, after 10 s: a daemon busy that long on one task (an\n * outbox backlog, 14 to 29 s) had every command and `listen` refused as an older release's, to be restarted.\n */\nexport const GREETING_MS = 2_000;\n\n/** The longest request line the daemon reads (WISP 1100 § Framing): it cuts the connection on a longer one. */\nexport const MAX_LINE = 16 * 1024 * 1024;\n\n/** What a client needs of a profile to reach its daemon: the socket, and the folder the daemon's secret is in. */\nexport interface DaemonAddress { socket: string; dir: string }\n\n/**\n * The refusal of a listener that did not prove it is the profile's daemon (`isNotTheDaemon` tells it apart). With nobody\n * holding the profile it is no daemon of any release, and no restart moves it: the answer pointed at `daemon restart`,\n * which answered the same, and a start said a daemon ran. What listens there has to stop, or its file go. `held`: whether\n * a process holds the profile, as the caller knows it (`lockOwner`); read here as a greeting's proof reads it otherwise.\n */\nexport function notTheDaemon(address: DaemonAddress, held = profileHeld(address.dir)): CliError {\n if (!held) {\n return new CliError(\"refused\", `Something that is not this profile's daemon listens on ${address.socket}, and no ghostly process holds the profile: nothing was sent to it. Stop the program that listens there, or remove that file, then start the daemon with ghostly daemon --detach`, { reason: \"not-the-daemon\", socket: address.socket });\n }\n return new CliError(\"refused\", `What answers on ${address.socket} did not prove it is this profile's daemon, so nothing was sent to it. A daemon of an older release cannot: \\`ghostly daemon restart\\` starts this one's`, { reason: \"not-the-daemon\" });\n}\n\n/** Whether a live process of this user's is in the profile's lock (`daemonProof.ts` reads it the same way). */\nfunction profileHeld(dir: string): boolean {\n try {\n const pid = Number(readFileSync(lockPath(dir), \"utf8\").trim());\n if (!Number.isSafeInteger(pid) || pid <= 0) return false;\n process.kill(pid, 0);\n return true;\n } catch { return false; }\n}\n\n/** The failures of calls whose connection ended unanswered (`endedUnanswered`), not answers the daemon gave. */\nconst unanswered = new WeakSet<CliError>();\n\n/**\n * A call the daemon read and never answered, because it stopped (a restart, a crash): what was asked may be done, so\n * it is no plain failure a bot tries again (a send went twice). A daemon that stops answers its waits first (`serve`);\n * this is for the calls it could not.\n */\nfunction stoppedUnanswered(method: string): CliError {\n const error = new CliError(\"timeout\", `The daemon stopped before it answered ${method}, which may be done: check (\\`ghostly chat history\\` for a message) before you try again`, { method, reason: \"daemon-stopped\" });\n unanswered.add(error);\n return error;\n}\n\n/**\n * A call whose connection ended before the daemon read it, or before it proved itself: nothing was done. `leaving`: this\n * client ended it (a deadline, Ctrl-C), so it is no daemon that stopped under the call.\n */\nfunction wentAway(leaving: boolean): CliError {\n const error = new CliError(\"unavailable\", \"The daemon went away\");\n if (!leaving) unanswered.add(error);\n return error;\n}\n\n/**\n * Whether a call failed because its connection ended unanswered (the daemon stopped, restarted or crashed under it),\n * not because the daemon answered it with an error. A read that did can be asked again: it changed nothing. So may one\n * refused because the daemon's secret was gone when its greeting or its hello's answer came: a daemon that stops removes\n * it first, and the greeting it wrote just before is read after. Nothing but the hello was written to it, and a listener\n * that never proves itself is refused again on the new connection.\n */\nexport function endedUnanswered(error: unknown): boolean {\n return error instanceof CliError && unanswered.has(error);\n}\n\n/**\n * Whether a call ended unanswered before it was written (`endedUnanswered`, and not a call the daemon read: those are\n * `daemon-stopped`): nothing reached the daemon, so the call may go to the daemon that runs next, whatever it does.\n */\nexport function endedUnsent(error: unknown): boolean {\n return endedUnanswered(error) && (error as CliError).details?.reason !== \"daemon-stopped\";\n}\n\nexport function isNotTheDaemon(error: unknown): boolean {\n return error instanceof CliError && error.code === \"refused\" && error.details?.reason === \"not-the-daemon\";\n}\n\n/**\n * A connection to a profile's daemon over its socket (WISP 1100 § Local control API). `null` from `connectDaemon`\n * means no daemon answers there: a one-shot command runs the profile itself.\n *\n * The client writes nothing on it until the daemon's greeting, its first line, proves the other end read the\n * profile's daemon secret and holds the profile's lock (`provesGreeting`): a listener that cannot prove it has read\n * nothing from this client, so it cannot impersonate it either (`daemonProof.ts`). Then the first line written is a\n * `daemon.hello`, and no call is written until its answer proves the same over the client's own nonce. Until then\n * every call waits, under its own deadline, and a listener that does not prove both gets every call refused\n * (`refused`, `isNotTheDaemon`). Nothing it writes before that is read either.\n */\nexport class DaemonClient {\n private nextId = 1;\n /** `written`: the call is on the socket, so the daemon may have acted on it. */\n private readonly pending = new Map<number, { method: string; written: boolean; resolve: (value: unknown) => void; reject: (error: Error) => void }>();\n /** This client closed the connection: what was still unanswered is its own doing, not a daemon that stopped. */\n private leaving = false;\n private eventListener: ((event: GhostlyEvent) => void) | null = null;\n private closedListener: (() => void) | null = null;\n /** While paused: the events of the chunk already read, given to the listener on resume. */\n private held: GhostlyEvent[] | null = null;\n private greeted = false;\n private verified = false;\n private refusal: CliError | null = null;\n private readonly ready: Promise<void>;\n private settle!: { resolve: () => void; reject: (error: CliError) => void };\n\n constructor(private readonly socket: Socket, private readonly address: DaemonAddress, greetingMs = GREETING_MS) {\n this.ready = new Promise<void>((resolve, reject) => { this.settle = { resolve, reject }; });\n this.ready.catch(() => {});\n const nonce = newNonce();\n // Nothing is written until the greeting either way: a busy daemon only keeps the calls waiting.\n const waitedTooLong = setTimeout(() => { if (!this.greeted && !this.refusal && !daemonOfThisRelease(this.address.dir)) this.refuse(); }, greetingMs);\n waitedTooLong.unref?.();\n const lines = createInterface({ input: socket, crlfDelay: Infinity });\n // readline passes on its input's errors: a daemon that went away with this client's lines unread (ECONNRESET) ended\n // the command on an unhandled 'error' instead of the close below (unavailable).\n lines.on(\"error\", () => {});\n lines.on(\"line\", (line) => {\n let message: { id?: number | string; result?: unknown; error?: { code: ErrorCode; message: string; details?: Record<string, unknown> }; event?: GhostlyEvent };\n // A first line that is not even JSON is no greeting: refused as one that does not prove itself.\n try { message = JSON.parse(line); } catch { if (!this.greeted && !this.refusal) this.refuse(); return; }\n if (this.refusal) return;\n if (!this.greeted) {\n clearTimeout(waitedTooLong);\n // The secret is read once a listener spoke: the daemon wrote it before it listened.\n const secret = readDaemonSecret(this.address.dir);\n if (!secret || !provesGreeting(secret, this.address.dir, message)) { this.refuse(!secret); return; }\n this.greeted = true;\n // A client closed before the greeting came (a start's readiness probe) has nothing to say.\n if (socket.writableEnded || socket.destroyed) return;\n socket.write(JSON.stringify({ id: HELLO_ID, method: HELLO, params: { nonce } }) + \"\\n\");\n return;\n }\n if (!this.verified) {\n if (message?.id !== HELLO_ID) return;\n // The secret is read once a listener answered: the daemon wrote it before it listened.\n const secret = readDaemonSecret(this.address.dir);\n if (!message.error && secret && provesDaemon(secret, nonce, message.result)) { this.verified = true; this.settle.resolve(); return; }\n this.refuse(!secret);\n return;\n }\n if (message.event) { if (this.held) this.held.push(message.event); else this.eventListener?.(message.event); return; }\n const waiting = typeof message.id === \"number\" ? this.pending.get(message.id) : undefined;\n if (!waiting) return;\n this.pending.delete(message.id as number);\n if (message.error) waiting.reject(new CliError(message.error.code, message.error.message, message.error.details));\n else waiting.resolve(message.result);\n });\n socket.on(\"close\", () => {\n clearTimeout(waitedTooLong);\n const why = this.refusal ?? wentAway(this.leaving);\n if (!this.verified) this.settle.reject(why);\n for (const waiting of this.pending.values()) waiting.reject(waiting.written && !this.refusal && !this.leaving ? stoppedUnanswered(waiting.method) : why);\n this.pending.clear();\n this.closedListener?.();\n });\n socket.on(\"error\", () => {});\n }\n\n /** `secretGone`: the daemon's secret was not there to check against, as when it stops (`endedUnanswered`). */\n private refuse(secretGone = false): void {\n this.refusal = notTheDaemon(this.address);\n if (secretGone) unanswered.add(this.refusal);\n this.settle.reject(this.refusal);\n this.socket.destroy();\n }\n\n /**\n * `timeoutMs`: give up (code `timeout`, exit 4) when the daemon has not answered by then; without it the call waits\n * for as long as the connection holds. A call that timed out closes the connection: its answer, if one ever comes,\n * is of no use, and the process leaves once nothing else keeps it (not every caller reaches `exit`).\n *\n * A call whose line is longer than `MAX_LINE` is refused here, never written: the daemon cut the connection on it,\n * and the command answered \"The daemon went away\" (`unavailable`, read as try later) while the daemon ran on.\n */\n call(method: string, params: unknown = {}, { timeoutMs }: { timeoutMs?: number } = {}): Promise<unknown> {\n if (this.socket.destroyed) return Promise.reject(this.refusal ?? wentAway(this.leaving));\n const id = this.nextId++;\n const line = JSON.stringify({ id, method, params }) + \"\\n\";\n const bytes = Buffer.byteLength(line);\n if (bytes > MAX_LINE) return Promise.reject(new CliError(\"bad_request\", `${method} came to ${(bytes / 1024 / 1024).toFixed(1)} MiB as JSON, more than a daemon reads in one request (16 MiB): nothing was sent (a long text goes as a file: ghostly file send <chat|group> <path>)`));\n return new Promise((resolve, reject) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n if (timeoutMs !== undefined) {\n timer = setTimeout(() => {\n if (!this.pending.delete(id)) return;\n reject(new CliError(\"timeout\", `The daemon did not answer ${method} in ${timeoutMs / 1000} s: \\`ghostly daemon restart\\` starts a fresh one`, { method }));\n this.destroy();\n }, timeoutMs);\n timer.unref?.();\n }\n const settle = {\n method, written: false,\n resolve: (value: unknown) => { if (timer) clearTimeout(timer); resolve(value); },\n reject: (error: Error) => { if (timer) clearTimeout(timer); reject(error); },\n };\n this.pending.set(id, settle);\n // Written once the daemon proved itself, in the order the calls were made; a refusal ends each instead.\n this.ready.then(\n () => {\n if (!this.pending.has(id) || this.socket.destroyed) return;\n this.socket.write(line);\n settle.written = true;\n },\n (error: CliError) => { if (this.pending.delete(id)) settle.reject(error); },\n );\n });\n }\n\n /** Events after `since` (replayed from the journal), then every new one, until the connection closes. */\n async subscribe(since: number | undefined, listener: (event: GhostlyEvent) => void, onClosed?: () => void): Promise<{ lastSeq: number }> {\n this.eventListener = listener;\n this.closedListener = onClosed ?? null;\n return this.call(\"events.subscribe\", since === undefined ? {} : { since }) as Promise<{ lastSeq: number }>;\n }\n\n /**\n * Stops reading: what the daemon sends waits in the connection (and past its bound the daemon ends it), and no\n * event reaches the listener until `resume`.\n */\n pause(): void {\n if (this.held) return;\n this.held = [];\n this.socket.pause();\n }\n\n /** Gives the listener the events held, then reads again; a listener that pauses again keeps the rest held. */\n resume(): void {\n const held = this.held;\n if (!held) return;\n this.held = null;\n for (let i = 0; i < held.length; i++) {\n this.eventListener?.(held[i]);\n if (this.held) { (this.held as GhostlyEvent[]).unshift(...held.slice(i + 1)); return; }\n }\n this.socket.resume();\n }\n\n close(): void {\n this.leaving = true;\n this.socket.end();\n }\n\n /** Closes at once: what the daemon still sends is not read. */\n destroy(): void {\n this.leaving = true;\n this.socket.destroy();\n }\n}\n\n/**\n * `timeoutMs` bounds the connect only; `greetingMs`, the wait for the daemon's greeting (above). The client it gives\n * has written nothing yet; whether the listener is the daemon is known at the first call.\n */\nexport function connectDaemon(address: DaemonAddress, timeoutMs = 2_000, { greetingMs = GREETING_MS }: { greetingMs?: number } = {}): Promise<DaemonClient | null> {\n const path = address.socket;\n // Someone else's socket (or a link) where the daemon's should be is no daemon of this profile's.\n if (!ownSocket(path)) return Promise.resolve(null);\n return new Promise((resolve) => {\n const socket = connect(path);\n const timer = setTimeout(() => { socket.destroy(); resolve(null); }, timeoutMs);\n socket.once(\"connect\", () => { clearTimeout(timer); resolve(new DaemonClient(socket, address, greetingMs)); });\n socket.once(\"error\", () => { clearTimeout(timer); resolve(null); });\n });\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;;;;;;AAa5B,IAAa,kBAA0B,YAAY,IAAI;;;;;AAMvD,IAAa,gBAAb,MAA2B;CAaJ;CAAiC;CAZtD,SAA2B,CAAC;CAC5B,OAAe;CACf,SAAiB;CACjB,WAAmB;;CAEnB,OAAe;CACf;CACA;CACA;;CAEA,UAAU;CAEV,YAAY,MAAyB,MAAqC,WAAW,QAAQ,cAAc;EAAtF,KAAA,OAAA;EAAiC,KAAA,MAAA;EACpD,KAAK,QAAQ,WAAW,IA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(text)) throw new Error("Invalid base64url");
|
|
5
4
|
const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - text.length % 4) % 4));
|
|
@@ -7,7 +6,6 @@ function fromBase64Url(text) {
|
|
|
7
6
|
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
8
7
|
return bytes;
|
|
9
8
|
}
|
|
10
|
-
//#endregion
|
|
11
9
|
export { fromBase64Url as t };
|
|
12
10
|
|
|
13
|
-
//# sourceMappingURL=codec-
|
|
11
|
+
//# sourceMappingURL=codec-B2rH1mfx.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codec-
|
|
1
|
+
{"version":3,"file":"codec-B2rH1mfx.js","names":[],"sources":["../../../browser/src/backup/codec.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"],"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,MAAM,GAAG,IAAI,IAAI,QAAQ,IAAK,KAAK,SAAS,KAAM,CAAC,CAAC;CACxG,MAAM,QAAQ,IAAI,WAAW,OAAO,MAAM;CAC1C,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK,MAAM,KAAK,OAAO,WAAW,CAAC;CACtE,OAAO;AACT"}
|