pinomad 0.0.0-stage → 0.1.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.
@@ -0,0 +1,430 @@
1
+ import {
2
+ commandHint,
3
+ hostEntry,
4
+ packagedVersion
5
+ } from "./chunk-v7yf5752.js";
6
+ import {
7
+ connectRemoteDurable
8
+ } from "./chunk-y73t2jmc.js";
9
+ import {
10
+ DEFAULT_DATA_DIR,
11
+ hostAddress
12
+ } from "./chunk-cjfmfyjb.js";
13
+
14
+ // apps/host/src/cli/service.ts
15
+ import { execFile as execFile2 } from "node:child_process";
16
+ import { homedir as homedir2 } from "node:os";
17
+ import { resolve as resolve2 } from "node:path";
18
+ import { fileURLToPath } from "node:url";
19
+ import { parseArgs, promisify as promisify2 } from "node:util";
20
+
21
+ // apps/host/src/service/definition.ts
22
+ import { join, resolve } from "node:path";
23
+ function sanitizePath(path) {
24
+ const seen = new Set;
25
+ const kept = [];
26
+ for (const entry of path.split(":")) {
27
+ if (entry === "" || entry.includes("/node_modules/.bin") || entry.includes("/bun-node-"))
28
+ continue;
29
+ if (seen.has(entry))
30
+ continue;
31
+ seen.add(entry);
32
+ kept.push(entry);
33
+ }
34
+ return kept.join(":");
35
+ }
36
+ function installSpec(argv, inputs) {
37
+ const hostArgs = [];
38
+ let dataDir;
39
+ for (let i = 0;i < argv.length; i++) {
40
+ const arg = argv[i];
41
+ if (arg === "--data-dir") {
42
+ dataDir = argv[++i];
43
+ if (dataDir === undefined)
44
+ throw new Error("--data-dir requires a value");
45
+ } else if (arg.startsWith("--data-dir=")) {
46
+ dataDir = arg.slice("--data-dir=".length);
47
+ } else {
48
+ hostArgs.push(arg);
49
+ }
50
+ }
51
+ const dir = resolve(inputs.cwd, dataDir ?? inputs.env.PINOMAD_DATA_DIR ?? join(inputs.home, ".pinomad"));
52
+ const { env } = inputs;
53
+ return {
54
+ nodePath: inputs.execPath,
55
+ mainPath: inputs.mainPath,
56
+ entryArgs: inputs.entryArgs ?? [],
57
+ dataDir: dir,
58
+ hostArgs,
59
+ env: {
60
+ PATH: sanitizePath(env.PATH ?? ""),
61
+ ...env.LANG === undefined ? {} : { LANG: env.LANG },
62
+ ...env.LC_ALL === undefined ? {} : { LC_ALL: env.LC_ALL }
63
+ },
64
+ home: inputs.home
65
+ };
66
+ }
67
+ var launchdPlistPath = (home) => join(home, "Library", "LaunchAgents", "pinomad.host.plist");
68
+ var systemdUnitPath = (home) => join(home, ".config", "systemd", "user", "pinomad.service");
69
+ var xmlEscape = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
70
+ function launchdPlist(spec) {
71
+ const program = [spec.nodePath, spec.mainPath, ...spec.entryArgs, "--data-dir", spec.dataDir, ...spec.hostArgs];
72
+ const log = join(spec.dataDir, "logs", "host.log");
73
+ const env = Object.entries(spec.env).map(([key, value]) => ` <key>${xmlEscape(key)}</key>
74
+ <string>${xmlEscape(value)}</string>`);
75
+ return `<?xml version="1.0" encoding="UTF-8"?>
76
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
77
+ <plist version="1.0">
78
+ <dict>
79
+ <key>Label</key>
80
+ <string>pinomad.host</string>
81
+ <key>ProgramArguments</key>
82
+ <array>
83
+ ${program.map((arg) => ` <string>${xmlEscape(arg)}</string>`).join(`
84
+ `)}
85
+ </array>
86
+ <key>WorkingDirectory</key>
87
+ <string>${xmlEscape(spec.home)}</string>
88
+ <key>EnvironmentVariables</key>
89
+ <dict>
90
+ ${env.join(`
91
+ `)}
92
+ </dict>
93
+ <key>RunAtLoad</key>
94
+ <true/>
95
+ <key>KeepAlive</key>
96
+ <true/>
97
+ <key>StandardOutPath</key>
98
+ <string>${xmlEscape(log)}</string>
99
+ <key>StandardErrorPath</key>
100
+ <string>${xmlEscape(log)}</string>
101
+ </dict>
102
+ </plist>
103
+ `;
104
+ }
105
+ var specifier = (value) => value.replace(/[%$]/g, (char) => char + char);
106
+ var execQuote = (value) => `"${specifier(value).replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
107
+ function systemdUnit(spec) {
108
+ const program = [spec.nodePath, spec.mainPath, ...spec.entryArgs, "--data-dir", spec.dataDir, ...spec.hostArgs];
109
+ const environment = Object.entries(spec.env).map(([key, value]) => `"${key}=${specifier(value)}"`);
110
+ return `[Unit]
111
+ Description=PiNomad host
112
+
113
+ [Service]
114
+ ExecStart=${program.map(execQuote).join(" ")}
115
+ WorkingDirectory=${specifier(spec.home)}
116
+ Environment=${environment.join(" ")}
117
+ Restart=on-failure
118
+ RestartSec=2
119
+
120
+ [Install]
121
+ WantedBy=default.target
122
+ `;
123
+ }
124
+
125
+ // apps/host/src/service/idle.ts
126
+ async function waitForIdle(remote, onBusy) {
127
+ if (remote.view.current().tasks === undefined)
128
+ await remote.controller.toggleTasks();
129
+ let announced = false;
130
+ await new Promise((resolve2) => {
131
+ const check = () => {
132
+ const view = remote.view.current();
133
+ if (view.connection !== "connected") {
134
+ unsubscribe();
135
+ resolve2();
136
+ return;
137
+ }
138
+ const tasks = view.tasks;
139
+ if (tasks === undefined)
140
+ return;
141
+ if (Object.keys(tasks.tasks).length === 0) {
142
+ unsubscribe();
143
+ resolve2();
144
+ return;
145
+ }
146
+ if (!announced) {
147
+ announced = true;
148
+ onBusy(tasks);
149
+ }
150
+ };
151
+ const unsubscribe = remote.view.subscribe(check);
152
+ check();
153
+ });
154
+ }
155
+
156
+ // apps/host/src/service/manager.ts
157
+ import { execFile, spawn } from "node:child_process";
158
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
159
+ import { homedir, userInfo } from "node:os";
160
+ import { dirname, join as join2 } from "node:path";
161
+ import { promisify } from "node:util";
162
+ var run = promisify(execFile);
163
+ var launchd = {
164
+ async install(spec) {
165
+ await mkdir(join2(spec.dataDir, "logs"), { recursive: true });
166
+ const path = launchdPlistPath(spec.home);
167
+ await mkdir(dirname(path), { recursive: true });
168
+ await writeFile(path, launchdPlist(spec));
169
+ const domain = `gui/${process.getuid()}/pinomad.host`;
170
+ await run("launchctl", ["bootout", domain]).catch(() => {});
171
+ await run("launchctl", ["bootstrap", `gui/${process.getuid()}`, path]);
172
+ return path;
173
+ },
174
+ async uninstall() {
175
+ await run("launchctl", ["bootout", `gui/${process.getuid()}/pinomad.host`]).catch(() => {});
176
+ await rm(launchdPlistPath(homedir()), { force: true });
177
+ },
178
+ async restart() {
179
+ await run("launchctl", ["kickstart", "-k", `gui/${process.getuid()}/pinomad.host`]);
180
+ },
181
+ async state() {
182
+ const printed = await run("launchctl", ["print", `gui/${process.getuid()}/pinomad.host`]).then(({ stdout }) => stdout, () => {
183
+ return;
184
+ });
185
+ if (printed === undefined)
186
+ return { installed: false, running: false, detail: "not installed" };
187
+ const field = (name) => printed.match(new RegExp(`^\\s*${name} = (.+)$`, "m"))?.[1];
188
+ const state = field("state") ?? "unknown";
189
+ const pid = field("pid");
190
+ const exit = field("last exit code");
191
+ return {
192
+ installed: true,
193
+ running: state === "running" && pid !== undefined,
194
+ ...pid === undefined ? {} : { pid: Number(pid) },
195
+ detail: [
196
+ state,
197
+ ...pid === undefined ? [] : [`pid ${pid}`],
198
+ ...exit === undefined || exit === "0" || exit === "(never exited)" ? [] : [`last exit ${exit}`]
199
+ ].join(", ")
200
+ };
201
+ },
202
+ async logs(dataDir, lines, follow) {
203
+ const file = join2(dataDir, "logs", "host.log");
204
+ if (follow) {
205
+ const tail = spawn("tail", ["-f", "-n", String(lines), file], { stdio: "inherit" });
206
+ await new Promise((resolve2) => tail.once("exit", () => resolve2()));
207
+ return;
208
+ }
209
+ const text = await readFile(file, "utf8");
210
+ const all = text.endsWith(`
211
+ `) ? text.slice(0, -1).split(`
212
+ `) : text.split(`
213
+ `);
214
+ process.stdout.write(`${all.slice(-lines).join(`
215
+ `)}
216
+ `);
217
+ }
218
+ };
219
+ var systemd = {
220
+ async install(spec) {
221
+ const path = systemdUnitPath(spec.home);
222
+ await mkdir(dirname(path), { recursive: true });
223
+ await writeFile(path, systemdUnit(spec));
224
+ await run("systemctl", ["--user", "daemon-reload"]);
225
+ await run("systemctl", ["--user", "enable", "pinomad.service"]);
226
+ await run("systemctl", ["--user", "restart", "pinomad.service"]);
227
+ const user = process.env.USER ?? userInfo().username;
228
+ const linger = await run("loginctl", ["show-user", user, "-p", "Linger"]).then(({ stdout }) => stdout.trim(), () => "");
229
+ if (linger === "Linger=no") {
230
+ console.log(`Note: run \`loginctl enable-linger ${user}\` to keep the host running while logged out.`);
231
+ }
232
+ return path;
233
+ },
234
+ async uninstall() {
235
+ await run("systemctl", ["--user", "disable", "--now", "pinomad.service"]).catch(() => {});
236
+ await rm(systemdUnitPath(homedir()), { force: true });
237
+ await run("systemctl", ["--user", "daemon-reload"]).catch(() => {});
238
+ },
239
+ async restart() {
240
+ await run("systemctl", ["--user", "restart", "pinomad.service"]);
241
+ },
242
+ async state() {
243
+ const shown = await run("systemctl", [
244
+ "--user",
245
+ "show",
246
+ "pinomad.service",
247
+ "-p",
248
+ "LoadState,ActiveState,SubState,MainPID,ExecMainStatus"
249
+ ]).then(({ stdout }) => stdout, () => {
250
+ return;
251
+ });
252
+ if (shown === undefined)
253
+ return { installed: false, running: false, detail: "not installed" };
254
+ const fields = Object.fromEntries(shown.trim().split(`
255
+ `).map((line) => line.split("=", 2)));
256
+ if (fields.LoadState === "not-found")
257
+ return { installed: false, running: false, detail: "not installed" };
258
+ const pid = Number(fields.MainPID ?? "0");
259
+ return {
260
+ installed: true,
261
+ running: fields.ActiveState === "active" && pid > 0,
262
+ ...pid > 0 ? { pid } : {},
263
+ detail: [
264
+ fields.ActiveState ?? "unknown",
265
+ fields.SubState ?? "",
266
+ ...pid > 0 ? [`pid ${pid}`] : [],
267
+ ...fields.ExecMainStatus === undefined || fields.ExecMainStatus === "0" ? [] : [`last exit ${fields.ExecMainStatus}`]
268
+ ].filter((part) => part !== "").join(", ")
269
+ };
270
+ },
271
+ async logs(_dataDir, lines, follow) {
272
+ const journal = spawn("journalctl", ["--user", "-u", "pinomad.service", "-n", String(lines), ...follow ? ["-f"] : []], {
273
+ stdio: "inherit"
274
+ });
275
+ await new Promise((resolve2) => journal.once("exit", () => resolve2()));
276
+ }
277
+ };
278
+ function serviceManager(platform = process.platform) {
279
+ if (platform === "darwin")
280
+ return launchd;
281
+ if (platform === "linux")
282
+ return systemd;
283
+ throw new Error(`service commands support macOS and Linux, not ${platform}`);
284
+ }
285
+
286
+ // apps/host/src/cli/service.ts
287
+ var run2 = promisify2(execFile2);
288
+ var repoRoot = fileURLToPath(new URL("../../../../", import.meta.url));
289
+ var message = (error) => error instanceof Error ? error.message : String(error);
290
+ function connect(url, token, timeoutMs = 3000) {
291
+ const connecting = connectRemoteDurable({ url, token, reconnectDelayMs: { min: 200, max: 2000 } });
292
+ const timedOut = Symbol("timedOut");
293
+ return Promise.race([
294
+ connecting,
295
+ new Promise((resolve3) => {
296
+ const timer = setTimeout(() => resolve3(timedOut), timeoutMs);
297
+ timer.unref();
298
+ })
299
+ ]).then((winner) => {
300
+ if (winner !== timedOut)
301
+ return winner;
302
+ connecting.then((remote) => remote.close(), () => {});
303
+ throw new Error("connect timed out");
304
+ });
305
+ }
306
+ async function install(argv) {
307
+ const spec = installSpec(argv, {
308
+ execPath: process.execPath,
309
+ env: process.env,
310
+ home: homedir2(),
311
+ cwd: process.cwd(),
312
+ mainPath: hostEntry.script,
313
+ entryArgs: hostEntry.args
314
+ });
315
+ const path = await serviceManager().install(spec);
316
+ console.log(`installed ${path}`);
317
+ console.log(`data dir: ${spec.dataDir}`);
318
+ console.log(`browser link: ${commandHint("link")} pairing QR: ${commandHint("pair")}`);
319
+ }
320
+ async function status(argv) {
321
+ const state = await serviceManager().state();
322
+ console.log(`service: ${state.installed ? state.detail : "not installed"}`);
323
+ if (packagedVersion === undefined) {
324
+ const head = await run2("git", ["rev-parse", "--short", "HEAD"], { cwd: repoRoot }).then(({ stdout }) => stdout.trim(), () => "unknown");
325
+ console.log(`checkout: ${head}`);
326
+ } else {
327
+ console.log(`version: ${packagedVersion}`);
328
+ }
329
+ try {
330
+ const { url, token } = await hostAddress(argv);
331
+ const remote = await connect(url, token);
332
+ if (remote.view.current().tasks === undefined)
333
+ await remote.controller.toggleTasks();
334
+ const tasks = remote.view.current().tasks;
335
+ const count = tasks === undefined ? 0 : Object.keys(tasks.tasks).length;
336
+ console.log(`host: reachable at ${url}, ${count} live task${count === 1 ? "" : "s"}`);
337
+ remote.close();
338
+ } catch (error) {
339
+ console.log(`host: unreachable (${message(error)})`);
340
+ }
341
+ }
342
+ async function restartService({ force, argv }) {
343
+ const manager = serviceManager();
344
+ if (!(await manager.state()).installed) {
345
+ console.log(`service not installed (${commandHint("service")} install)`);
346
+ return 1;
347
+ }
348
+ const address = await hostAddress(argv).catch(() => {
349
+ return;
350
+ });
351
+ if (!force && address !== undefined) {
352
+ try {
353
+ const remote = await connect(address.url, address.token);
354
+ await waitForIdle(remote, (tasks) => {
355
+ console.log("waiting for running tasks to finish (Ctrl-C to cancel)");
356
+ for (const task of Object.values(tasks.tasks)) {
357
+ console.log(` ${task.kind} in conversation ${task.conversationId}`);
358
+ }
359
+ });
360
+ remote.close();
361
+ } catch {}
362
+ }
363
+ await manager.restart();
364
+ if (address === undefined) {
365
+ console.log("restart requested (host address unknown; not polling)");
366
+ return 0;
367
+ }
368
+ const deadline = Date.now() + 30000;
369
+ for (;; ) {
370
+ try {
371
+ const remote = await connect(address.url, address.token, 2000);
372
+ remote.close();
373
+ console.log(`host restarted, reachable at ${address.url}`);
374
+ return 0;
375
+ } catch (error) {
376
+ if (Date.now() > deadline) {
377
+ console.error(`host did not answer within 30s after restart: ${message(error)}`);
378
+ return 1;
379
+ }
380
+ await new Promise((resolve3) => setTimeout(resolve3, 500));
381
+ }
382
+ }
383
+ }
384
+ async function logs(argv) {
385
+ const { values } = parseArgs({
386
+ args: [...argv],
387
+ options: {
388
+ follow: { type: "boolean", default: false },
389
+ lines: { type: "string", short: "n", default: "100" },
390
+ "data-dir": { type: "string" }
391
+ }
392
+ });
393
+ const dataDir = resolve2(values["data-dir"] ?? DEFAULT_DATA_DIR);
394
+ await serviceManager().logs(dataDir, Number(values.lines), values.follow);
395
+ }
396
+ async function main(argv) {
397
+ const [command, ...args] = argv;
398
+ try {
399
+ switch (command) {
400
+ case "install":
401
+ await install(args);
402
+ break;
403
+ case "uninstall":
404
+ await serviceManager().uninstall();
405
+ console.log("uninstalled");
406
+ break;
407
+ case "status":
408
+ await status(args);
409
+ break;
410
+ case "restart": {
411
+ const force = args.includes("--force");
412
+ process.exitCode = await restartService({ force, argv: args.filter((arg) => arg !== "--force") });
413
+ break;
414
+ }
415
+ case "logs":
416
+ await logs(args);
417
+ break;
418
+ default:
419
+ console.error(`usage: ${commandHint("service")} install|uninstall|status|restart|logs`);
420
+ process.exitCode = 1;
421
+ }
422
+ } catch (error) {
423
+ console.error(message(error));
424
+ process.exitCode = 1;
425
+ }
426
+ }
427
+ if (false)
428
+ ;
429
+
430
+ export { serviceManager, restartService, main };
@@ -0,0 +1,36 @@
1
+ import {
2
+ packagedVersion
3
+ } from "./chunk-v7yf5752.js";
4
+ import {
5
+ hostAddress
6
+ } from "./chunk-cjfmfyjb.js";
7
+ import"./chunk-df32avw6.js";
8
+
9
+ // apps/host/src/cli/web-link.ts
10
+ var DEV_WEB = "http://127.0.0.1:5199/";
11
+ function webLink(url, token, base = DEV_WEB) {
12
+ const web = new URL(base);
13
+ web.hash = new URLSearchParams({ token, url }).toString();
14
+ return web.href;
15
+ }
16
+ async function linkBase(url, answers200) {
17
+ const hostHttp = url.replace(/^ws/, "http");
18
+ if (await answers200(DEV_WEB))
19
+ return DEV_WEB;
20
+ if (await answers200(hostHttp))
21
+ return hostHttp;
22
+ return DEV_WEB;
23
+ }
24
+ async function main(argv) {
25
+ const { url, token } = await hostAddress(argv);
26
+ const base = packagedVersion !== undefined ? url.replace(/^ws/, "http") : await linkBase(url, (probe) => fetch(probe, { signal: AbortSignal.timeout(1000) }).then((response) => response.status === 200, () => false));
27
+ console.log(webLink(url, token, base));
28
+ }
29
+ if (false)
30
+ ;
31
+ export {
32
+ webLink,
33
+ main,
34
+ linkBase,
35
+ DEV_WEB
36
+ };
@@ -0,0 +1,21 @@
1
+ // apps/host/src/cli/host-address.ts
2
+ import { readFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { join, resolve } from "node:path";
5
+ import { parseArgs } from "node:util";
6
+ var DEFAULT_DATA_DIR = process.env.PINOMAD_DATA_DIR ?? join(homedir(), ".pinomad");
7
+ async function hostAddress(argv) {
8
+ const { values } = parseArgs({
9
+ args: [...argv],
10
+ options: {
11
+ "data-dir": { type: "string" },
12
+ url: { type: "string", default: "ws://127.0.0.1:7420" },
13
+ token: { type: "string" }
14
+ }
15
+ });
16
+ const dataDir = resolve(values["data-dir"] ?? DEFAULT_DATA_DIR);
17
+ const token = values.token ?? (await readFile(join(dataDir, "token"), "utf8")).trim();
18
+ return { url: values.url, token, dataDir };
19
+ }
20
+
21
+ export { DEFAULT_DATA_DIR, hostAddress };
@@ -0,0 +1,4 @@
1
+ import { createRequire } from "node:module";
2
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
3
+
4
+ export { __require };
@@ -0,0 +1,113 @@
1
+ import {
2
+ fromBase64Url,
3
+ generateKeyPair,
4
+ keyPairFromPrivate,
5
+ toBase64Url
6
+ } from "./chunk-z4x88s0q.js";
7
+
8
+ // apps/host/src/devices.ts
9
+ import { readFile, writeFile } from "node:fs/promises";
10
+ import { join } from "node:path";
11
+ import { randomBytes, timingSafeEqual } from "node:crypto";
12
+ import { ed25519 } from "@noble/curves/ed25519.js";
13
+ import { defineDoc } from "@earendil-works/pi-durable";
14
+ var DevicesDoc = defineDoc({
15
+ kind: "pinomad.devices",
16
+ version: 1,
17
+ scope: "session",
18
+ initial: () => ({ devices: [] })
19
+ });
20
+ async function ensureDevices(harness, context) {
21
+ await harness.commit(async (tx) => void await tx.doc(DevicesDoc), context);
22
+ }
23
+ async function isRegistered(harness, publicKey, context) {
24
+ return await harness.commit(async (tx) => (await tx.doc(DevicesDoc)).devices.some((entry) => entry.publicKey === publicKey), context);
25
+ }
26
+ async function registerDevice(harness, device, context) {
27
+ return await harness.commit(async (tx) => {
28
+ const doc = await tx.doc(DevicesDoc);
29
+ const existing = doc.devices.find((entry2) => entry2.publicKey === device.publicKey);
30
+ if (existing !== undefined)
31
+ return { ...existing };
32
+ const name = device.name.trim().slice(0, 64) || "Unknown device";
33
+ const entry = { publicKey: device.publicKey, name, pairedAt: Date.now() };
34
+ doc.devices.push(entry);
35
+ return entry;
36
+ }, context);
37
+ }
38
+ async function revokeDevice(harness, publicKey, context) {
39
+ await harness.commit(async (tx) => {
40
+ const doc = await tx.doc(DevicesDoc);
41
+ doc.devices = doc.devices.filter((entry) => entry.publicKey !== publicKey);
42
+ }, context);
43
+ }
44
+ async function loadHostKey(dataDir) {
45
+ const path = join(dataDir, "host-key");
46
+ try {
47
+ const text = (await readFile(path, "utf8")).trim();
48
+ return keyPairFromPrivate(fromBase64Url(text));
49
+ } catch (error) {
50
+ if (error.code !== "ENOENT")
51
+ throw error;
52
+ const pair = generateKeyPair();
53
+ await writeFile(path, `${toBase64Url(pair.privateKey)}
54
+ `, { mode: 384 });
55
+ return pair;
56
+ }
57
+ }
58
+ async function loadRelayKey(dataDir) {
59
+ const path = join(dataDir, "relay-key");
60
+ try {
61
+ const secretKey = fromBase64Url((await readFile(path, "utf8")).trim());
62
+ if (secretKey.length !== 32)
63
+ throw new Error(`bad relay key in ${path}`);
64
+ return { secretKey, publicKey: ed25519.getPublicKey(secretKey) };
65
+ } catch (error) {
66
+ if (error.code !== "ENOENT")
67
+ throw error;
68
+ const { secretKey, publicKey } = ed25519.keygen();
69
+ try {
70
+ await writeFile(path, `${toBase64Url(secretKey)}
71
+ `, { flag: "wx", mode: 384 });
72
+ } catch (race) {
73
+ if (race.code !== "EEXIST")
74
+ throw race;
75
+ return loadRelayKey(dataDir);
76
+ }
77
+ return { secretKey, publicKey };
78
+ }
79
+ }
80
+ function pairingOffers(ttlMs = 5 * 60 * 1000) {
81
+ const live = new Map;
82
+ const prune = () => {
83
+ const now = Date.now();
84
+ for (const [secret, expiresAt] of live)
85
+ if (expiresAt <= now)
86
+ live.delete(secret);
87
+ };
88
+ return {
89
+ create() {
90
+ prune();
91
+ const secret = toBase64Url(randomBytes(16));
92
+ const expiresAt = Date.now() + ttlMs;
93
+ live.set(secret, expiresAt);
94
+ return { secret, expiresAt };
95
+ },
96
+ consume(secret) {
97
+ prune();
98
+ const candidate = Buffer.from(secret);
99
+ for (const offer of live.keys()) {
100
+ const offerBytes = Buffer.from(offer);
101
+ if (offerBytes.length !== candidate.length)
102
+ continue;
103
+ if (timingSafeEqual(offerBytes, candidate)) {
104
+ live.delete(offer);
105
+ return true;
106
+ }
107
+ }
108
+ return false;
109
+ }
110
+ };
111
+ }
112
+
113
+ export { DevicesDoc, ensureDevices, isRegistered, registerDevice, revokeDevice, loadHostKey, loadRelayKey, pairingOffers };