@peer2peer/cli 0.1.2 → 0.1.4

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,1021 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // Where this device's secret keys live (issue #8): in `<home>/cli/keys.json` (0600, the default), or
4
+ // in the OS keychain (macOS Keychain, Windows Credential Manager, libsecret on Linux), chosen by the
5
+ // person with `p2p keys backend keychain|file`.
6
+ //
7
+ // With the keychain, keys.json keeps only the public part of the keys document (userId, did, the
8
+ // device certificate) and says where the secrets are (`store: "keychain"` and the item's service
9
+ // name). The secrets (the device signing seed `spk`, the agreement secret `kpk`, and on a key holder
10
+ // the identity seed `ik`) are one keychain item:
11
+ //
12
+ // service peer2peer-keys-<first 20 hex of SHA-256 of the home's real path> (two homes never share one)
13
+ // account the device id (`did`): a new device (init, restore, a rotation) is a new item
14
+ // secret `p2p1.` + base64url(JSON {v, userId, did, spk, kpk, ik?})
15
+ //
16
+ // The home records the chosen backend in `<home>/keystore.json` (not secret), so where new keys are
17
+ // written is decided by that file, and where existing keys are read from by keys.json itself: a load
18
+ // never guesses. A keys document that says "keychain" is read from the keychain or not at all: when
19
+ // the keychain can't be read (locked, its tool missing, the item gone) the command stops with a
20
+ // clear error. Nothing ever makes new keys in their place.
21
+ //
22
+ // The OS tools do the work (no native module: the CLI is a single bundled file), each called by its
23
+ // absolute path, never through a shell or PATH (a planted `secret-tool` earlier in PATH would be
24
+ // handed the secret). A secret is never in a command line (other processes can read those): it goes
25
+ // over the tool's stdin, and it never appears in an error or a log line. What this does and doesn't
26
+ // protect against is in docs/security/threat-model.md ("Keys in the OS keychain").
27
+ import { spawnSync } from "node:child_process";
28
+ import { createHash, randomBytes } from "node:crypto";
29
+ import { constants, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
30
+ import { link, lstat, open, readFile, rm, stat } from "node:fs/promises";
31
+ import { join, resolve } from "node:path";
32
+ import { b64uDecode, b64uEncode, decodeTyped, deviceKeysV3FromSecrets, identityKeyFromSeed, TYP3 } from "@peer2peer/core/v3";
33
+ import { CliError } from "./errors.js";
34
+ /** How long one keychain call may take: a locked keychain may be showing its unlock prompt. */
35
+ export const KEYCHAIN_TIMEOUT_MS = 20_000;
36
+ export const realRunner = (file, args, input) => {
37
+ const r = spawnSync(file, [...args], {
38
+ input,
39
+ encoding: "utf8",
40
+ timeout: KEYCHAIN_TIMEOUT_MS,
41
+ windowsHide: true,
42
+ shell: false,
43
+ maxBuffer: 1 << 20,
44
+ stdio: ["pipe", "pipe", "pipe"],
45
+ });
46
+ return { status: r.status, stdout: r.stdout ?? "", stderr: r.stderr ?? "", ...(r.error ? { error: r.error.code ?? "error" } : {}) };
47
+ };
48
+ /** A keychain call that failed: `reason` is safe to show (never the secret, never the tool's raw output with it). */
49
+ export class KeychainError extends Error {
50
+ reason;
51
+ constructor(reason) {
52
+ super(reason);
53
+ this.reason = reason;
54
+ }
55
+ }
56
+ /** Service names, accounts and labels go into command lines and the tools' own parsers: a narrow alphabet, never starting with `-` (never an option). */
57
+ const SAFE_ARG = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/;
58
+ /** Secrets are `p2p1.` + base64url: never an option (no leading `-`), nothing a parser splits. */
59
+ const SAFE_SECRET = /^p2p1\.[A-Za-z0-9_-]{1,4096}$/;
60
+ function checkArgs(...args) {
61
+ for (const a of args)
62
+ if (!SAFE_ARG.test(a))
63
+ throw new KeychainError("an item name with characters the keychain tools can't be given safely");
64
+ }
65
+ /**
66
+ * The tool's message, safe to show: one line, short, with the secret (and anything shaped like one)
67
+ * taken out. The tools don't echo secrets, but this never relies on it.
68
+ */
69
+ export function toolMessage(out, secret) {
70
+ let s = out;
71
+ if (secret)
72
+ s = s.split(secret).join("[secret]");
73
+ s = s.replace(/p2p1\.[A-Za-z0-9_-]*/g, "[secret]").replace(/[A-Za-z0-9_-]{40,}/g, "[…]");
74
+ s = s.replace(/[\u0000-\u001f\u007f]+/g, " ").trim();
75
+ return s.length > 160 ? `${s.slice(0, 160)}…` : s;
76
+ }
77
+ function spawnProblem(r, tool) {
78
+ if (!r.error)
79
+ return undefined;
80
+ if (r.error === "ETIMEDOUT")
81
+ return `${tool} didn't answer in ${KEYCHAIN_TIMEOUT_MS / 1000}s (is the keychain locked, with its unlock prompt waiting?)`;
82
+ if (r.error === "ENOENT")
83
+ return `${tool} isn't installed`;
84
+ return `${tool} couldn't be run (${r.error})`;
85
+ }
86
+ // ---------------------------------------------------------------------------
87
+ // macOS: /usr/bin/security
88
+ export const SECURITY = "/usr/bin/security";
89
+ /**
90
+ * The macOS Keychain through `/usr/bin/security`. Writes go through `security -i`, which reads its
91
+ * commands from stdin, so the secret is never in a command line. The item's access list trusts
92
+ * `/usr/bin/security` only (`-T`): other apps get the system's prompt. `keychainFile` points at
93
+ * another keychain than the default one (the opt-in test uses a throwaway keychain).
94
+ */
95
+ export function macosKeychain(run = realRunner, opts = {}) {
96
+ const kc = opts.keychainFile ? [opts.keychainFile] : [];
97
+ const exists = opts.exists ?? existsSync;
98
+ if (opts.keychainFile && /["\s\\]/.test(opts.keychainFile))
99
+ throw new KeychainError("a keychain path with spaces, quotes or backslashes");
100
+ return {
101
+ kind: "macos",
102
+ label: "the macOS Keychain",
103
+ unavailable: () => (exists(SECURITY) ? undefined : `${SECURITY} isn't there`),
104
+ get(service, account) {
105
+ checkArgs(service, account);
106
+ const r = run(SECURITY, ["find-generic-password", "-s", service, "-a", account, "-w", ...kc], "");
107
+ const p = spawnProblem(r, "security");
108
+ if (p)
109
+ throw new KeychainError(p);
110
+ // 44: errSecItemNotFound.
111
+ if (r.status === 44)
112
+ return undefined;
113
+ if (r.status !== 0)
114
+ throw new KeychainError(`security couldn't read the item (exit ${r.status}${r.stderr.trim() ? `: ${toolMessage(r.stderr)}` : ""}): is the keychain locked?`);
115
+ return r.stdout.replace(/\r?\n$/, "");
116
+ },
117
+ set(service, account, label, secret) {
118
+ checkArgs(service, account, label);
119
+ if (!SAFE_SECRET.test(secret))
120
+ throw new KeychainError("a secret in an unexpected form");
121
+ // A new item only (no -U: changing an existing item's access list asks the user in a dialog, so
122
+ // the caller deletes an item it replaces first). -T sets the access list to the security tool alone.
123
+ const line = ["add-generic-password", "-s", service, "-a", account, "-l", label, "-T", SECURITY, "-w", secret, ...kc].join(" ");
124
+ const r = run(SECURITY, ["-i"], `${line}\n`);
125
+ const p = spawnProblem(r, "security");
126
+ if (p)
127
+ throw new KeychainError(p);
128
+ // `security -i` exits 0 even when a command failed: whatever it said on stderr is a failure.
129
+ if (r.status !== 0 || r.stderr.trim() !== "")
130
+ throw new KeychainError(`security couldn't store the item${r.stderr.trim() ? ` (${toolMessage(r.stderr, secret)})` : ` (exit ${r.status})`}`);
131
+ },
132
+ remove(service, account) {
133
+ checkArgs(service, account);
134
+ const r = run(SECURITY, ["delete-generic-password", "-s", service, "-a", account, ...kc], "");
135
+ const p = spawnProblem(r, "security");
136
+ if (p)
137
+ throw new KeychainError(p);
138
+ if (r.status === 44)
139
+ return false;
140
+ if (r.status !== 0)
141
+ throw new KeychainError(`security couldn't delete the item (exit ${r.status}${r.stderr.trim() ? `: ${toolMessage(r.stderr)}` : ""})`);
142
+ return true;
143
+ },
144
+ };
145
+ }
146
+ // ---------------------------------------------------------------------------
147
+ // Linux (and other Unixes with libsecret): secret-tool
148
+ /** Where secret-tool is looked for: system folders only (never PATH, never a user-writable folder). */
149
+ export const SECRET_TOOL_PATHS = ["/usr/bin/secret-tool", "/bin/secret-tool", "/run/current-system/sw/bin/secret-tool"];
150
+ /** The Secret Service (GNOME Keyring, KWallet) through libsecret's `secret-tool`; `store` reads the secret from stdin. */
151
+ export function libsecretKeychain(run = realRunner, opts = {}) {
152
+ const exists = opts.exists ?? existsSync;
153
+ const tool = () => SECRET_TOOL_PATHS.find((p) => exists(p));
154
+ const need = () => {
155
+ const t = tool();
156
+ if (!t)
157
+ throw new KeychainError("secret-tool isn't installed (the libsecret tools package: libsecret-tools on Debian and Ubuntu, libsecret on Fedora and Arch)");
158
+ return t;
159
+ };
160
+ return {
161
+ kind: "linux",
162
+ label: "the Secret Service keyring (libsecret)",
163
+ unavailable: () => (tool() ? undefined : "secret-tool isn't installed (the libsecret tools package)"),
164
+ get(service, account) {
165
+ checkArgs(service, account);
166
+ const r = run(need(), ["lookup", "service", service, "account", account], "");
167
+ const p = spawnProblem(r, "secret-tool");
168
+ if (p)
169
+ throw new KeychainError(p);
170
+ if (r.status === 0)
171
+ return r.stdout.replace(/\r?\n$/, "");
172
+ // Not found: exit 1 and nothing said. Anything said is the service failing (no D-Bus session, locked).
173
+ if (r.status === 1 && r.stderr.trim() === "" && r.stdout === "")
174
+ return undefined;
175
+ throw new KeychainError(`secret-tool couldn't read the item (exit ${r.status}${r.stderr.trim() ? `: ${toolMessage(r.stderr)}` : ""}): is a Secret Service (GNOME Keyring, KWallet) running and unlocked in this session?`);
176
+ },
177
+ set(service, account, label, secret) {
178
+ checkArgs(service, account, label);
179
+ if (!SAFE_SECRET.test(secret))
180
+ throw new KeychainError("a secret in an unexpected form");
181
+ const r = run(need(), ["store", `--label=${label}`, "service", service, "account", account], secret);
182
+ const p = spawnProblem(r, "secret-tool");
183
+ if (p)
184
+ throw new KeychainError(p);
185
+ if (r.status !== 0)
186
+ throw new KeychainError(`secret-tool couldn't store the item (exit ${r.status}${r.stderr.trim() ? `: ${toolMessage(r.stderr, secret)}` : ""})`);
187
+ },
188
+ remove(service, account) {
189
+ checkArgs(service, account);
190
+ // `clear` says nothing either way: looked up first, to tell whether there was one.
191
+ const had = this.get(service, account) !== undefined;
192
+ const r = run(need(), ["clear", "service", service, "account", account], "");
193
+ const p = spawnProblem(r, "secret-tool");
194
+ if (p)
195
+ throw new KeychainError(p);
196
+ if (r.status !== 0 && had)
197
+ throw new KeychainError(`secret-tool couldn't delete the item (exit ${r.status}${r.stderr.trim() ? `: ${toolMessage(r.stderr)}` : ""})`);
198
+ return had;
199
+ },
200
+ };
201
+ }
202
+ // ---------------------------------------------------------------------------
203
+ // Windows: Credential Manager (CredWriteW / CredReadW / CredDeleteW) through Windows PowerShell
204
+ /**
205
+ * The C# that does the work on Windows. It reads the request from stdin itself and writes the answer
206
+ * to stdout itself, so the secret never passes through a PowerShell cmdlet, pipeline or variable
207
+ * (with PowerShell module or script block logging on, those are recorded in the event log). The
208
+ * request: one field per line, `op`, `target`, `account`, `label`, `secret` (each in the narrow
209
+ * alphabets above: no line breaks). Credentials are generic ones persisted on this machine only
210
+ * (CRED_PERSIST_LOCAL_MACHINE: never roamed). Exit 3: no such credential.
211
+ */
212
+ export const WINDOWS_CSHARP = String.raw `using System;
213
+ using System.Runtime.InteropServices;
214
+ using System.Text;
215
+ public static class P2PCred {
216
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
217
+ public struct CREDENTIAL {
218
+ public int Flags; public int Type; public string TargetName; public string Comment;
219
+ public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten;
220
+ public int CredentialBlobSize; public IntPtr CredentialBlob; public int Persist;
221
+ public int AttributeCount; public IntPtr Attributes; public string TargetAlias; public string UserName;
222
+ }
223
+ [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] static extern bool CredWriteW(ref CREDENTIAL c, int flags);
224
+ [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] static extern bool CredReadW(string target, int type, int flags, out IntPtr c);
225
+ [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] static extern bool CredDeleteW(string target, int type, int flags);
226
+ [DllImport("advapi32.dll")] static extern void CredFree(IntPtr p);
227
+ static int Write(string target, string user, string label, string secret) {
228
+ byte[] b = Encoding.UTF8.GetBytes(secret);
229
+ IntPtr p = Marshal.AllocHGlobal(b.Length);
230
+ try {
231
+ Marshal.Copy(b, 0, p, b.Length);
232
+ CREDENTIAL c = new CREDENTIAL();
233
+ c.Type = 1; c.TargetName = target; c.UserName = user; c.Comment = label;
234
+ c.CredentialBlobSize = b.Length; c.CredentialBlob = p; c.Persist = 2;
235
+ if (!CredWriteW(ref c, 0)) return Marshal.GetLastWin32Error();
236
+ return 0;
237
+ } finally {
238
+ for (int i = 0; i < b.Length; i++) Marshal.WriteByte(p, i, 0);
239
+ Marshal.FreeHGlobal(p);
240
+ Array.Clear(b, 0, b.Length);
241
+ }
242
+ }
243
+ static string Read(string target, out int err) {
244
+ IntPtr p;
245
+ err = 0;
246
+ if (!CredReadW(target, 1, 0, out p)) { err = Marshal.GetLastWin32Error(); return null; }
247
+ try {
248
+ CREDENTIAL c = (CREDENTIAL)Marshal.PtrToStructure(p, typeof(CREDENTIAL));
249
+ byte[] b = new byte[c.CredentialBlobSize];
250
+ Marshal.Copy(c.CredentialBlob, b, 0, c.CredentialBlobSize);
251
+ return Encoding.UTF8.GetString(b);
252
+ } finally { CredFree(p); }
253
+ }
254
+ static string Field(string[] f, int i) { return i < f.Length ? f[i].Trim() : ""; }
255
+ public static int Run() {
256
+ string[] f = Console.In.ReadToEnd().Split((char)10);
257
+ string op = Field(f, 0), target = Field(f, 1);
258
+ if (target.Length == 0) return 4;
259
+ int e;
260
+ if (op == "set") {
261
+ e = Write(target, Field(f, 2), Field(f, 3), Field(f, 4));
262
+ if (e != 0) { Console.Error.WriteLine("CredWrite failed: Win32 error " + e); return 2; }
263
+ return 0;
264
+ }
265
+ if (op == "get") {
266
+ string s = Read(target, out e);
267
+ if (e == 1168) return 3;
268
+ if (e != 0) { Console.Error.WriteLine("CredRead failed: Win32 error " + e); return 2; }
269
+ Console.Out.Write(s);
270
+ Console.Out.Flush();
271
+ return 0;
272
+ }
273
+ if (op == "delete") {
274
+ if (CredDeleteW(target, 1, 0)) return 0;
275
+ e = Marshal.GetLastWin32Error();
276
+ if (e == 1168) return 3;
277
+ Console.Error.WriteLine("CredDelete failed: Win32 error " + e);
278
+ return 2;
279
+ }
280
+ return 4;
281
+ }
282
+ }
283
+ `;
284
+ /**
285
+ * The PowerShell that runs it (passed as -EncodedCommand: no secret in it): a static loader that
286
+ * compiles the C# above with the .NET compiler directly and calls it. No cmdlet runs (not even
287
+ * Add-Type), no module is loaded (autoloading off: nothing from a user-writable PSModulePath), and
288
+ * nothing reads stdin but the C#.
289
+ */
290
+ export const WINDOWS_SCRIPT = `$ErrorActionPreference = 'Stop'
291
+ $PSModuleAutoloadingPreference = 'None'
292
+ $src = @'
293
+ ${WINDOWS_CSHARP}'@
294
+ $cp = [System.CodeDom.Compiler.CompilerParameters]::new()
295
+ $cp.GenerateInMemory = $true
296
+ [void]$cp.ReferencedAssemblies.Add('System.dll')
297
+ $res = [Microsoft.CSharp.CSharpCodeProvider]::new().CompileAssemblyFromSource($cp, $src)
298
+ if ($res.Errors.HasErrors) { [Console]::Error.WriteLine('the credential helper did not compile'); exit 5 }
299
+ exit [int]$res.CompiledAssembly.GetType('P2PCred').GetMethod('Run').Invoke($null, $null)
300
+ `;
301
+ /** The fixed path of Windows PowerShell 5.1, which every supported Windows has. */
302
+ export const WINDOWS_POWERSHELL = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
303
+ /**
304
+ * Windows PowerShell by its absolute path: the fixed `C:\\Windows` one when it is there. Otherwise
305
+ * %SystemRoot% (or %windir%) only when it is a drive's own Windows folder (`D:\\Windows`, `D:\\WINNT`),
306
+ * never anything else the environment names (a folder in a user profile). Undefined: none to trust.
307
+ */
308
+ export function powershellPath(env = process.env, exists = existsSync) {
309
+ if (exists(WINDOWS_POWERSHELL))
310
+ return WINDOWS_POWERSHELL;
311
+ for (const root of [env.SystemRoot, env.windir]) {
312
+ const r = (root ?? "").replace(/\\+$/, "");
313
+ if (/^[A-Za-z]:\\(?:Windows|WINNT)$/i.test(r)) {
314
+ const exe = `${r}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
315
+ if (exists(exe))
316
+ return exe;
317
+ }
318
+ }
319
+ return undefined;
320
+ }
321
+ export function windowsKeychain(run = realRunner, opts = {}) {
322
+ const exists = opts.exists ?? existsSync;
323
+ const encoded = Buffer.from(WINDOWS_SCRIPT, "utf16le").toString("base64");
324
+ const call = (req) => {
325
+ const exe = powershellPath(opts.env, exists);
326
+ if (!exe)
327
+ throw new KeychainError("Windows PowerShell isn't in the Windows folder");
328
+ // One field per line; every field is in a narrow alphabet (checked by the callers), so none holds a line break.
329
+ const input = [req.op, req.target, req.account ?? "", req.label ?? "", req.secret ?? ""].join("\n") + "\n";
330
+ const r = run(exe, ["-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encoded], input);
331
+ const p = spawnProblem(r, "PowerShell");
332
+ if (p)
333
+ throw new KeychainError(p);
334
+ return { ...r, stderr: toolMessage(r.stderr, req.secret) };
335
+ };
336
+ const target = (service, account) => `${service}/${account}`;
337
+ return {
338
+ kind: "windows",
339
+ label: "the Windows Credential Manager",
340
+ unavailable: () => (powershellPath(opts.env, exists) ? undefined : `Windows PowerShell isn't at ${WINDOWS_POWERSHELL}`),
341
+ get(service, account) {
342
+ checkArgs(service, account);
343
+ const r = call({ op: "get", target: target(service, account) });
344
+ if (r.status === 3)
345
+ return undefined;
346
+ if (r.status !== 0)
347
+ throw new KeychainError(`the Credential Manager couldn't be read (exit ${r.status}${r.stderr ? `: ${r.stderr}` : ""})`);
348
+ return r.stdout.replace(/\r?\n$/, "");
349
+ },
350
+ set(service, account, label, secret) {
351
+ checkArgs(service, account, label);
352
+ if (!SAFE_SECRET.test(secret))
353
+ throw new KeychainError("a secret in an unexpected form");
354
+ const r = call({ op: "set", target: target(service, account), account, label, secret });
355
+ if (r.status !== 0)
356
+ throw new KeychainError(`the Credential Manager couldn't store the item (exit ${r.status}${r.stderr ? `: ${r.stderr}` : ""})`);
357
+ },
358
+ remove(service, account) {
359
+ checkArgs(service, account);
360
+ const r = call({ op: "delete", target: target(service, account) });
361
+ if (r.status === 3)
362
+ return false;
363
+ if (r.status !== 0)
364
+ throw new KeychainError(`the Credential Manager couldn't delete the item (exit ${r.status}${r.stderr ? `: ${r.stderr}` : ""})`);
365
+ return true;
366
+ },
367
+ };
368
+ }
369
+ // ---------------------------------------------------------------------------
370
+ // The keychain of this platform (tests stand one in)
371
+ let override;
372
+ /** Tests: use `k` instead of the platform's keychain (null: none on this platform); undefined restores it. */
373
+ export function useKeychainForTests(k) {
374
+ override = k;
375
+ cache.clear();
376
+ }
377
+ /** This platform's keychain, or undefined where p2p knows none. */
378
+ export function platformKeychain(platform = process.platform) {
379
+ if (override !== undefined)
380
+ return override ?? undefined;
381
+ if (platform === "darwin")
382
+ return macosKeychain();
383
+ if (platform === "win32")
384
+ return windowsKeychain();
385
+ if (platform === "linux" || platform === "freebsd" || platform === "openbsd")
386
+ return libsecretKeychain();
387
+ return undefined;
388
+ }
389
+ // ---------------------------------------------------------------------------
390
+ // The home's choice and the item's name
391
+ export const SERVICE_PREFIX = "peer2peer-keys-";
392
+ /** Contains the service prefix, so a guard looking for p2p's items also sees a lookup by label. */
393
+ export const LABEL = "peer2peer-keys-device";
394
+ /** The home as the keychain item names it: its real path when it exists (a symlinked P2P_HOME is the same home). */
395
+ export function canonicalHome(home) {
396
+ try {
397
+ return realpathSync.native(home);
398
+ }
399
+ catch {
400
+ return resolve(home);
401
+ }
402
+ }
403
+ /** The keychain service for `home`: one per home, so two homes (two identities on one machine) never share an item. */
404
+ export function serviceFor(home) {
405
+ return `${SERVICE_PREFIX}${createHash("sha256").update(canonicalHome(home)).digest("hex").slice(0, 20)}`;
406
+ }
407
+ export function markerFile(home) {
408
+ return join(home, "keystore.json");
409
+ }
410
+ /** The backend new keys are written to: keystore.json's, else files. Throws when the file is there but unreadable (fail closed). */
411
+ export function configuredBackend(home) {
412
+ let raw;
413
+ try {
414
+ raw = readFileSync(markerFile(home), "utf8");
415
+ }
416
+ catch (e) {
417
+ if (e.code === "ENOENT")
418
+ return "file";
419
+ throw new CliError("keystore_unreadable", `${markerFile(home)} can't be read (${e.code ?? "error"}): it says where this device's keys go. Fix or remove it`);
420
+ }
421
+ let m;
422
+ try {
423
+ m = JSON.parse(raw);
424
+ }
425
+ catch {
426
+ throw new CliError("keystore_unreadable", `${markerFile(home)} isn't valid JSON: it says where this device's keys go. Set it again: \`p2p keys backend keychain\` or \`p2p keys backend file\``);
427
+ }
428
+ if (m.backend === "file" || m.backend === "keychain")
429
+ return m.backend;
430
+ throw new CliError("keystore_unreadable", `${markerFile(home)} names no backend p2p knows: set it again with \`p2p keys backend keychain\` or \`p2p keys backend file\``);
431
+ }
432
+ function writeMarker(home, backend) {
433
+ mkdirSync(home, { recursive: true, mode: 0o700 });
434
+ const m = { v: 1, backend, ...(backend === "keychain" ? { service: serviceFor(home), home: canonicalHome(home) } : {}), at: Date.now() };
435
+ const f = markerFile(home);
436
+ const tmp = `${f}.${randomBytes(6).toString("hex")}.tmp`;
437
+ try {
438
+ writeFileSync(tmp, JSON.stringify(m, null, 2) + "\n", { mode: 0o600, flag: "wx" });
439
+ renameSync(tmp, f);
440
+ }
441
+ catch (e) {
442
+ rmSync(tmp, { force: true });
443
+ throw e;
444
+ }
445
+ }
446
+ const SECRET_FIELDS = ["spk", "kpk", "ik"];
447
+ const SEAL_FIELDS = ["store", "service"];
448
+ const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
449
+ /** Whether a raw keys.json holds the secrets itself. */
450
+ export function holdsSecrets(raw) {
451
+ return isObj(raw) && typeof raw.spk === "string" && raw.spk !== "";
452
+ }
453
+ /** Whether a raw keys.json says its secrets are in the keychain. */
454
+ export function isSealed(raw) {
455
+ return isObj(raw) && raw.store === "keychain" && !holdsSecrets(raw);
456
+ }
457
+ function without(o, keys) {
458
+ const out = {};
459
+ for (const [k, v] of Object.entries(o))
460
+ if (!keys.includes(k))
461
+ out[k] = v;
462
+ return out;
463
+ }
464
+ /** The item's secret for keys `k` (exported for the tests). */
465
+ export function payloadOf(k) {
466
+ const body = { v: 1, userId: k.userId, did: k.did, spk: k.spk, kpk: k.kpk, ...(typeof k.ik === "string" ? { ik: k.ik } : {}) };
467
+ return `p2p1.${Buffer.from(JSON.stringify(body), "utf8").toString("base64url")}`;
468
+ }
469
+ /** The secrets in an item, checked against the public part they belong to: the device id from the signing seed, the userId from the identity seed. */
470
+ function openPayload(secret, pub, where) {
471
+ const bad = (why) => new CliError("keychain_mismatch", `the keychain item for this device (${where}) ${why}: this device's keys can't be loaded. Nothing was changed, and no new keys were made`);
472
+ if (!SAFE_SECRET.test(secret))
473
+ throw bad("isn't one p2p wrote");
474
+ let body;
475
+ try {
476
+ body = JSON.parse(Buffer.from(secret.slice(5), "base64url").toString("utf8"));
477
+ }
478
+ catch {
479
+ throw bad("isn't one p2p wrote");
480
+ }
481
+ const { spk, kpk, ik } = body;
482
+ if (typeof spk !== "string" || typeof kpk !== "string" || (ik !== undefined && typeof ik !== "string"))
483
+ throw bad("isn't one p2p wrote");
484
+ try {
485
+ const dk = deviceKeysV3FromSecrets(pub.userId, b64uDecode(spk, 32), b64uDecode(kpk, 32));
486
+ if (dk.did !== pub.did)
487
+ throw bad("holds another device's keys");
488
+ // The agreement key too: the certificate in keys.json names its public half.
489
+ const cert = decodeTyped(pub.cert, TYP3.device).payload;
490
+ if (cert.did !== pub.did || cert.spk !== b64uEncode(dk.signingPublicKey) || cert.kpk !== b64uEncode(dk.agreementPublicKey))
491
+ throw bad("holds keys this device's certificate doesn't name");
492
+ if (typeof ik === "string" && identityKeyFromSeed(b64uDecode(ik, 32)).userId !== pub.userId)
493
+ throw bad("holds another identity's key");
494
+ }
495
+ catch (e) {
496
+ if (e instanceof CliError)
497
+ throw e;
498
+ throw bad("isn't one p2p wrote");
499
+ }
500
+ return { spk, kpk, ...(typeof ik === "string" ? { ik } : {}) };
501
+ }
502
+ /** Items read in this process, by service and device id (a device's secrets never change: a new device is a new item). */
503
+ const cache = new Map();
504
+ function keychainOrThrow() {
505
+ const kc = platformKeychain();
506
+ if (!kc)
507
+ throw new CliError("keychain_unavailable", `this device's keys are kept in an OS keychain, and p2p knows none on ${process.platform}. Nothing was changed, and no new keys were made`);
508
+ const why = kc.unavailable();
509
+ if (why)
510
+ throw new CliError("keychain_unavailable", `this device's keys are in ${kc.label}, which can't be used here: ${why}. Nothing was changed, and no new keys were made`);
511
+ return kc;
512
+ }
513
+ /** The secrets of a sealed keys.json from the keychain, or a clear error (never a guess, never new keys). */
514
+ function unseal(home, raw) {
515
+ const service = serviceFor(home);
516
+ if (raw.service !== service) {
517
+ throw new CliError("keychain_moved", `this device's keys are in the keychain under another home's name (${String(raw.service).slice(0, 64)}, not ${service}): was ${home} moved or copied from elsewhere? Move it back, or run p2p with P2P_HOME set to the folder it was made in. Nothing was changed, and no new keys were made`);
518
+ }
519
+ if (typeof raw.did !== "string" || typeof raw.userId !== "string")
520
+ throw new CliError("keychain_mismatch", `${join(home, "cli", "keys.json")} is damaged: no device id. Nothing was changed`);
521
+ const kc = keychainOrThrow();
522
+ const key = `${service}|${raw.did}`;
523
+ let secret = cache.get(key);
524
+ if (secret === undefined) {
525
+ try {
526
+ secret = kc.get(service, raw.did);
527
+ }
528
+ catch (e) {
529
+ const why = e instanceof KeychainError ? e.reason : "an unexpected error";
530
+ throw new CliError("keychain_unreadable", `this device's keys are in ${kc.label} (item ${service}, account ${raw.did}), which couldn't be read: ${why}. Unlock it and run the command again. Nothing was changed, and no new keys were made`);
531
+ }
532
+ if (secret === undefined) {
533
+ throw new CliError("keychain_missing", `this device's keys should be in ${kc.label} (item ${service}, account ${raw.did}), and it has no such item: was it deleted, or is this another user account? Restore it from a keychain backup, or \`p2p backup restore\` on a fresh home. Nothing was changed, and no new keys were made`);
534
+ }
535
+ }
536
+ const secrets = openPayload(secret, raw, `${service}, account ${raw.did}`);
537
+ // An identity seed in keys.json itself (p2p never writes one there when sealed) counts only if it is this identity's.
538
+ if (secrets.ik === undefined && raw.ik !== undefined) {
539
+ let ok;
540
+ try {
541
+ ok = typeof raw.ik === "string" && identityKeyFromSeed(b64uDecode(raw.ik, 32)).userId === raw.userId;
542
+ }
543
+ catch {
544
+ ok = false;
545
+ }
546
+ if (!ok)
547
+ throw new CliError("keychain_mismatch", `${join(home, "cli", "keys.json")} holds an identity key that isn't this identity's: this device's keys can't be loaded. Nothing was changed, and no new keys were made`);
548
+ }
549
+ cache.set(key, secret);
550
+ return { ...without(raw, SEAL_FIELDS), ...secrets };
551
+ }
552
+ /** The keys document as the CLI uses it from what keys.json holds: the secrets from the keychain when it says so. */
553
+ export function openKeys(home, raw) {
554
+ if (raw === undefined || raw === null)
555
+ return raw;
556
+ if (isSealed(raw))
557
+ return unseal(home, raw);
558
+ // The secrets are in the file (the default, or a move that hasn't finished): those are the keys.
559
+ return isObj(raw) ? without(raw, SEAL_FIELDS) : raw;
560
+ }
561
+ /**
562
+ * The device signing seed for the person token (projects.ts), read synchronously: from keys.json,
563
+ * or from the keychain when keys.json says so. Undefined when it can't be read.
564
+ */
565
+ export function signingSeedSync(home) {
566
+ let raw;
567
+ try {
568
+ raw = JSON.parse(readFileSync(join(home, "cli", "keys.json"), "utf8"));
569
+ }
570
+ catch {
571
+ return undefined;
572
+ }
573
+ try {
574
+ const k = openKeys(home, raw);
575
+ return isObj(k) && typeof k.spk === "string" && k.spk !== "" ? k.spk : undefined;
576
+ }
577
+ catch {
578
+ return undefined;
579
+ }
580
+ }
581
+ /** Throws the keychain's error when this home's keys are in a keychain that can't be read now; else nothing. */
582
+ export function assertKeysReadable(home) {
583
+ let raw;
584
+ try {
585
+ raw = JSON.parse(readFileSync(join(home, "cli", "keys.json"), "utf8"));
586
+ }
587
+ catch {
588
+ return;
589
+ }
590
+ if (isSealed(raw))
591
+ unseal(home, raw);
592
+ }
593
+ /** Whether this home's keys are in a keychain that can't be read now. */
594
+ export function keysUnreadable(home) {
595
+ try {
596
+ assertKeysReadable(home);
597
+ return false;
598
+ }
599
+ catch {
600
+ return true;
601
+ }
602
+ }
603
+ /**
604
+ * Removes the wipe file at `path`, first overwriting its bytes with zeros only when that is safe: a
605
+ * regular file (never a symbolic link, which is removed without following it), with no other name
606
+ * (nlink 1, so no other file loses its content), and not keys.json itself (the same inode is only
607
+ * unlinked: a run that made the link may not have renamed the new file in yet). Best effort.
608
+ */
609
+ async function zeroAndRemove(path, keysPath) {
610
+ try {
611
+ const st = await lstat(path);
612
+ const keys = await stat(keysPath).catch(() => undefined);
613
+ const sameAsKeys = keys !== undefined && keys.ino === st.ino && keys.dev === st.dev;
614
+ if (st.isFile() && st.nlink === 1 && !sameAsKeys) {
615
+ const fh = await open(path, constants.O_RDWR | constants.O_NOFOLLOW);
616
+ try {
617
+ const now = await fh.stat();
618
+ // Still the file that was checked (nothing swapped in between).
619
+ if (now.ino === st.ino && now.dev === st.dev && now.nlink === 1 && now.size > 0) {
620
+ await fh.write(Buffer.alloc(now.size, 0), 0, now.size, 0);
621
+ await fh.sync();
622
+ }
623
+ }
624
+ finally {
625
+ await fh.close().catch(() => { });
626
+ }
627
+ }
628
+ }
629
+ catch {
630
+ // gone already, or not ours to open
631
+ }
632
+ await rm(path, { force: true }).catch(() => { });
633
+ }
634
+ const WIPE_PREFIX = ".keys.json.wipe-";
635
+ /** Wipe files a move left in `<home>/cli` (one interrupted between linking and removing). */
636
+ function wipeLeftovers(home) {
637
+ try {
638
+ return readdirSync(join(home, "cli")).filter((f) => f.startsWith(WIPE_PREFIX));
639
+ }
640
+ catch {
641
+ return [];
642
+ }
643
+ }
644
+ /** Removes the wipe files a move left behind (zeroed where safe: zeroAndRemove). Returns how many there were. */
645
+ export async function sweepWipeLeftovers(home) {
646
+ const found = wipeLeftovers(home);
647
+ for (const f of found)
648
+ await zeroAndRemove(join(home, "cli", f), join(home, "cli", "keys.json"));
649
+ return found.length;
650
+ }
651
+ /**
652
+ * Writes `doc` to keys.json, and when the file it replaces held secrets, overwrites that file's old
653
+ * bytes before they are gone (best effort: on an SSD or a copy-on-write file system the old blocks may
654
+ * still be somewhere; the keychain is the place the keys are kept now). On POSIX the old file stays
655
+ * open across the rename and is zeroed through that handle. Windows refuses to rename over a file that
656
+ * is open, so there a second name for the old file (a hard link, `.keys.json.wipe-…`) keeps it while the
657
+ * new one is renamed in, and is zeroed and removed after (only when it has no other name: a backup's
658
+ * hard link to the old file keeps its bytes there); one left by an interrupted run is finished by the next.
659
+ */
660
+ async function replaceKeysFile(inner, home, doc) {
661
+ const dir = join(home, "cli");
662
+ const path = join(dir, "keys.json");
663
+ let old;
664
+ try {
665
+ old = JSON.parse(await readFile(path, "utf8"));
666
+ }
667
+ catch {
668
+ old = undefined;
669
+ }
670
+ if (process.platform === "win32") {
671
+ await sweepWipeLeftovers(home);
672
+ let wipe;
673
+ if (holdsSecrets(old)) {
674
+ wipe = join(dir, `${WIPE_PREFIX}${randomBytes(6).toString("hex")}`);
675
+ try {
676
+ await link(path, wipe);
677
+ }
678
+ catch {
679
+ wipe = undefined;
680
+ }
681
+ }
682
+ await inner.write("keys", doc);
683
+ if (wipe)
684
+ await zeroAndRemove(wipe, path);
685
+ return;
686
+ }
687
+ let fh;
688
+ try {
689
+ fh = holdsSecrets(old) ? await open(path, "r+") : undefined;
690
+ }
691
+ catch {
692
+ fh = undefined;
693
+ }
694
+ try {
695
+ const before = fh ? await fh.stat() : undefined;
696
+ await inner.write("keys", doc);
697
+ if (fh && before && before.size > 0) {
698
+ const now = await stat(path).catch(() => undefined);
699
+ // Only the file the write replaced (renamed over): never the one just written.
700
+ if (!now || now.ino !== before.ino || now.dev !== before.dev) {
701
+ await fh.write(Buffer.alloc(before.size, 0), 0, before.size, 0);
702
+ await fh.sync();
703
+ }
704
+ }
705
+ }
706
+ finally {
707
+ await fh?.close().catch(() => { });
708
+ }
709
+ }
710
+ /**
711
+ * Stores `k`'s secrets in the keychain and reads them back; throws unless the item reads back byte
712
+ * for byte. An item that already holds them is left as it is (a renewed certificate changes only
713
+ * keys.json). One that holds something else is replaced only with `replace` (the keys are still in
714
+ * keys.json, or are new); otherwise it may be the only copy of this device's keys, and it stays.
715
+ */
716
+ function storeAndVerify(kc, home, k, replace) {
717
+ const service = serviceFor(home);
718
+ const secret = payloadOf(k);
719
+ const key = `${service}|${k.did}`;
720
+ if (cache.get(key) === secret)
721
+ return;
722
+ try {
723
+ const have = kc.get(service, k.did);
724
+ if (have === secret) {
725
+ cache.set(key, secret);
726
+ return;
727
+ }
728
+ if (have !== undefined) {
729
+ if (!replace)
730
+ throw new CliError("keychain_mismatch", `${kc.label} holds other keys for this device (item ${service}, account ${k.did}) than the ones being written: nothing was changed`);
731
+ kc.remove(service, k.did);
732
+ cache.delete(key);
733
+ }
734
+ kc.set(service, k.did, LABEL, secret);
735
+ }
736
+ catch (e) {
737
+ if (e instanceof CliError)
738
+ throw e;
739
+ throw new CliError("keychain_write_failed", `couldn't store this device's keys in ${kc.label}: ${e instanceof KeychainError ? e.reason : "an unexpected error"}. Nothing was changed: the keys are where they were`);
740
+ }
741
+ let back;
742
+ try {
743
+ back = kc.get(service, k.did);
744
+ }
745
+ catch (e) {
746
+ throw new CliError("keychain_write_failed", `stored this device's keys in ${kc.label}, but couldn't read them back: ${e instanceof KeychainError ? e.reason : "an unexpected error"}. Nothing was changed: the keys are where they were`);
747
+ }
748
+ if (back !== secret)
749
+ throw new CliError("keychain_write_failed", `the keys read back from ${kc.label} weren't the ones stored. Nothing was changed: the keys are where they were`);
750
+ cache.set(`${service}|${k.did}`, secret);
751
+ }
752
+ function sealedOf(home, k) {
753
+ return { ...without(k, [...SECRET_FIELDS, ...SEAL_FIELDS]), store: "keychain", service: serviceFor(home) };
754
+ }
755
+ function asFull(v) {
756
+ if (!isObj(v) || typeof v.spk !== "string" || typeof v.kpk !== "string" || typeof v.did !== "string" || typeof v.userId !== "string") {
757
+ throw new CliError("internal", "a keys document without its keys");
758
+ }
759
+ return without(v, SEAL_FIELDS);
760
+ }
761
+ /**
762
+ * CliState's backend with the keys document routed: written to the keychain when the home chose it
763
+ * (keystore.json), read from wherever keys.json says. Every other document passes through.
764
+ */
765
+ export class KeyStoreBackend {
766
+ inner;
767
+ home;
768
+ opts;
769
+ constructor(inner, home,
770
+ /** A read-only run's overlay (readonly.ts): writes stay in memory, never reach the keychain. */
771
+ opts = {}) {
772
+ this.inner = inner;
773
+ this.home = home;
774
+ this.opts = opts;
775
+ }
776
+ async read(name) {
777
+ const raw = await this.inner.read(name);
778
+ return name === "keys" ? openKeys(this.home, raw) : raw;
779
+ }
780
+ /** keys.json as it is on disk (sealed or not). */
781
+ readRaw() {
782
+ return this.inner.read("keys");
783
+ }
784
+ async write(name, value) {
785
+ if (name !== "keys" || value === null || value === undefined || this.opts.memoryOnly)
786
+ return this.inner.write(name, value);
787
+ const k = asFull(value);
788
+ const sealed = isSealed(await this.inner.read("keys"));
789
+ // Keys sealed in the keychain stay there whatever keystore.json says (missing, or "file"): only
790
+ // `p2p keys backend file` moves them out, never an ordinary write (a renewed certificate).
791
+ if (sealed || configuredBackend(this.home) === "keychain") {
792
+ // Replacing an item is only for keys that aren't sealed already (then the item may be their only copy).
793
+ storeAndVerify(keychainOrThrow(), this.home, k, !sealed);
794
+ return replaceKeysFile(this.inner, this.home, sealedOf(this.home, k));
795
+ }
796
+ return this.inner.write(name, k);
797
+ }
798
+ remove(name) {
799
+ return this.inner.remove ? this.inner.remove(name) : this.inner.write(name, null);
800
+ }
801
+ withLock(fn) {
802
+ return this.inner.withLock(fn);
803
+ }
804
+ }
805
+ /** Where this home's keys are and whether they can be read (no secret in it). Read only. */
806
+ export function keyStoreStatus(home) {
807
+ const st = keyStoreStatusOf(home);
808
+ const left = wipeLeftovers(home);
809
+ if (left.length === 0)
810
+ return st;
811
+ const say = `${left.length === 1 ? "a wipe file" : `${left.length} wipe files`} from an interrupted move ${left.length === 1 ? "is" : "are"} still in ${join(home, "cli")} (${left.join(", ")}), and may hold the old keys file's bytes: the next p2p command that isn't read-only removes ${left.length === 1 ? "it" : "them"}`;
812
+ return { ...st, leftovers: left, problem: st.problem ? `${st.problem}; ${say}` : say };
813
+ }
814
+ function keyStoreStatusOf(home) {
815
+ const kc = platformKeychain();
816
+ const why = kc ? kc.unavailable() : `p2p knows no OS keychain on ${process.platform}`;
817
+ const keychain = { ...(kc ? { kind: kc.kind } : {}), label: kc?.label ?? "an OS keychain", available: why === undefined, ...(why !== undefined ? { why } : {}) };
818
+ let configured = "file";
819
+ let problem;
820
+ try {
821
+ configured = configuredBackend(home);
822
+ }
823
+ catch (e) {
824
+ problem = e.message;
825
+ }
826
+ let raw;
827
+ try {
828
+ raw = JSON.parse(readFileSync(join(home, "cli", "keys.json"), "utf8"));
829
+ }
830
+ catch (e) {
831
+ if (e.code === "ENOENT")
832
+ return { configured, keys: "none", readable: false, ...(problem ? { problem } : {}), keychain };
833
+ return { configured, keys: "file", readable: false, problem: `${join(home, "cli", "keys.json")} can't be read`, keychain };
834
+ }
835
+ if (isSealed(raw)) {
836
+ const item = { service: String(raw.service), account: String(raw.did) };
837
+ if (configured !== "keychain" && !problem)
838
+ problem = `the keys are in the keychain, but ${markerFile(home)} is missing or says files: they stay in the keychain (\`p2p keys backend keychain\` records it again; \`p2p keys backend file\` moves them out)`;
839
+ try {
840
+ unseal(home, raw);
841
+ return { configured, keys: "keychain", readable: true, ...(problem ? { problem } : {}), keychain, item };
842
+ }
843
+ catch (e) {
844
+ return { configured, keys: "keychain", readable: false, problem: e.message, keychain, item };
845
+ }
846
+ }
847
+ if (!holdsSecrets(raw))
848
+ return { configured, keys: "file", readable: false, problem: `${join(home, "cli", "keys.json")} holds no keys`, keychain };
849
+ if (configured === "keychain" && !problem)
850
+ problem = `the keys are still in ${join(home, "cli", "keys.json")}: the move into the keychain hasn't finished (\`p2p keys backend keychain\` finishes it)`;
851
+ return { configured, keys: "file", readable: true, ...(problem ? { problem } : {}), keychain };
852
+ }
853
+ /**
854
+ * Moves this home's keys into the keychain: stored, read back and compared byte for byte, and only
855
+ * then keys.json loses its secrets (its old bytes overwritten). Each step can be repeated: an
856
+ * interrupted move is finished by running it again (or by the next command that loads the keys).
857
+ */
858
+ export async function moveKeysToKeychain(store) {
859
+ const home = store.home;
860
+ const kc = platformKeychain();
861
+ if (!kc)
862
+ throw new CliError("keychain_unavailable", `p2p knows no OS keychain on ${process.platform}: the keys stay in files`);
863
+ const why = kc.unavailable();
864
+ if (why)
865
+ throw new CliError("keychain_unavailable", `${kc.label} can't be used here: ${why}. Nothing was changed: the keys stay in files`);
866
+ return store.withLock(async () => {
867
+ const raw = await store.readRaw();
868
+ const service = serviceFor(home);
869
+ if (raw === undefined) {
870
+ // No keys yet: the keychain must work before this home counts on it (a probe item, stored, read back, deleted).
871
+ probeKeychain(kc, service);
872
+ writeMarker(home, "keychain");
873
+ return { backend: "keychain", moved: false, where: `${kc.label}: no keys here yet, the ones this device makes will be kept there`, warnings: [] };
874
+ }
875
+ if (isSealed(raw)) {
876
+ unseal(home, raw);
877
+ writeMarker(home, "keychain");
878
+ return { backend: "keychain", moved: false, where: `${kc.label} (they were there already)`, item: { service, account: String(raw.did) }, warnings: [] };
879
+ }
880
+ const k = asFull(raw);
881
+ storeAndVerify(kc, home, k, true);
882
+ writeMarker(home, "keychain");
883
+ await replaceKeysFile(store.inner, home, sealedOf(home, k));
884
+ return { backend: "keychain", moved: true, where: kc.label, item: { service, account: k.did }, warnings: [] };
885
+ });
886
+ }
887
+ /**
888
+ * Moves this home's keys back into keys.json: written and read back first, then the keychain item
889
+ * is deleted. Fails closed: keys that can't be read from the keychain stay there.
890
+ */
891
+ export async function moveKeysToFiles(store) {
892
+ const home = store.home;
893
+ const where = `${join(home, "cli", "keys.json")} (0600)`;
894
+ return store.withLock(async () => {
895
+ await sweepWipeLeftovers(home);
896
+ const raw = await store.readRaw();
897
+ const warnings = [];
898
+ if (raw === undefined || !isSealed(raw)) {
899
+ writeMarker(home, "file");
900
+ // A move into the keychain that stopped before keys.json was sealed leaves a copy there: deleted,
901
+ // once keys.json is known to hold this device's keys.
902
+ if (raw !== undefined && holdsSecrets(raw))
903
+ forgetLeftover(home, asFull(raw), warnings);
904
+ return { backend: "file", moved: false, where: raw === undefined ? `${where}: no keys here yet` : `${where} (they were there already)`, warnings };
905
+ }
906
+ const k = unseal(home, raw);
907
+ await store.inner.write("keys", k);
908
+ const back = await store.inner.read("keys");
909
+ if (!isObj(back) || payloadOf(asFull(back)) !== payloadOf(k)) {
910
+ throw new CliError("keys_write_failed", `the keys read back from ${where} weren't the ones written: the keychain item was kept`);
911
+ }
912
+ writeMarker(home, "file");
913
+ const kc = platformKeychain();
914
+ const service = String(raw.service);
915
+ try {
916
+ kc?.remove(service, k.did);
917
+ cache.delete(`${service}|${k.did}`);
918
+ }
919
+ catch (e) {
920
+ warnings.push(`the keys are in ${where} now, but the keychain item ${service} (account ${k.did}) couldn't be deleted (${e instanceof KeychainError ? e.reason : "error"}): delete it yourself`);
921
+ }
922
+ return { backend: "file", moved: true, where, warnings };
923
+ });
924
+ }
925
+ /**
926
+ * A home that chose the keychain whose keys.json holds secrets (a move that was interrupted, or a
927
+ * rotation or follow that swapped in a new identity's files): moves them now. Called on load by
928
+ * commands that may write; never by read-only ones. Returns a warning when it couldn't.
929
+ */
930
+ export async function finishPendingMove(store) {
931
+ // Wipe files an interrupted move left (Windows' way of overwriting the old keys.json): finished now.
932
+ await sweepWipeLeftovers(store.home);
933
+ let backend;
934
+ try {
935
+ backend = configuredBackend(store.home);
936
+ }
937
+ catch (e) {
938
+ return e.message;
939
+ }
940
+ if (backend !== "keychain")
941
+ return undefined;
942
+ if (!holdsSecrets(await store.readRaw()))
943
+ return undefined;
944
+ try {
945
+ await moveKeysToKeychain(store);
946
+ return undefined;
947
+ }
948
+ catch (e) {
949
+ return `this device's keys are still in ${join(store.home, "cli", "keys.json")}, not in the keychain this home chose: ${e.message}`;
950
+ }
951
+ }
952
+ /** Stores, reads back and deletes a throwaway item under `service`; throws when any of it fails. Its secret is random, never a key. */
953
+ export function probeKeychain(kc, service) {
954
+ const account = `probe-${randomBytes(8).toString("hex")}`;
955
+ const secret = `p2p1.${randomBytes(24).toString("base64url")}`;
956
+ try {
957
+ kc.set(service, account, LABEL, secret);
958
+ const back = kc.get(service, account);
959
+ if (back !== secret)
960
+ throw new KeychainError("what it read back wasn't what it stored");
961
+ }
962
+ catch (e) {
963
+ try {
964
+ kc.remove(service, account);
965
+ }
966
+ catch {
967
+ // nothing more to do
968
+ }
969
+ throw new CliError("keychain_write_failed", `${kc.label} can't be used here: ${e instanceof KeychainError ? e.reason : "an unexpected error"}. Nothing was changed: new keys stay in files`);
970
+ }
971
+ try {
972
+ kc.remove(service, account);
973
+ }
974
+ catch (e) {
975
+ throw new CliError("keychain_write_failed", `${kc.label} stored a test item but couldn't delete it (${e instanceof KeychainError ? e.reason : "error"}): nothing was changed. Delete the item ${service} (account ${account}) yourself`);
976
+ }
977
+ }
978
+ /** Deletes this home's keychain item for the keys `k` (which keys.json holds) when there is one; a warning when it can't. */
979
+ function forgetLeftover(home, k, warnings) {
980
+ try {
981
+ if (deviceKeysV3FromSecrets(k.userId, b64uDecode(k.spk, 32), b64uDecode(k.kpk, 32)).did !== k.did)
982
+ return;
983
+ }
984
+ catch {
985
+ return;
986
+ }
987
+ const kc = platformKeychain();
988
+ if (!kc || kc.unavailable())
989
+ return;
990
+ const service = serviceFor(home);
991
+ try {
992
+ // Only an item that holds exactly these keys (a move's copy): anything else under this name is left alone.
993
+ const have = kc.get(service, k.did);
994
+ if (have === undefined)
995
+ return;
996
+ if (have !== payloadOf(k)) {
997
+ warnings.push(`${kc.label} holds an item for this device (${service}, account ${k.did}) that isn't a copy of the keys in keys.json: it was left alone`);
998
+ return;
999
+ }
1000
+ kc.remove(service, k.did);
1001
+ cache.delete(`${service}|${k.did}`);
1002
+ }
1003
+ catch (e) {
1004
+ warnings.push(`a copy of the keys may still be in ${kc.label} (item ${service}, account ${k.did}) from a move that didn't finish, and it couldn't be deleted (${e instanceof KeychainError ? e.reason : "error"}): delete it yourself`);
1005
+ }
1006
+ }
1007
+ /** Best effort: deletes this home's keychain item for device `did` (a half-made identity that was wiped). */
1008
+ export function forgetKeychainItem(home, did) {
1009
+ if (!did)
1010
+ return;
1011
+ try {
1012
+ if (configuredBackend(home) !== "keychain")
1013
+ return;
1014
+ const service = serviceFor(home);
1015
+ platformKeychain()?.remove(service, did);
1016
+ cache.delete(`${service}|${did}`);
1017
+ }
1018
+ catch {
1019
+ // the item stays; nothing else depends on it
1020
+ }
1021
+ }