@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.
- package/README.md +10 -7
- package/dist/ancestry.d.ts +42 -2
- package/dist/ancestry.js +215 -32
- package/dist/app.d.ts +64 -2
- package/dist/app.js +188 -22
- package/dist/cli.d.ts +30 -3
- package/dist/cli.js +332 -8
- package/dist/config.d.ts +5 -0
- package/dist/doctor.d.ts +7 -0
- package/dist/doctor.js +102 -3
- package/dist/format.d.ts +5 -1
- package/dist/format.js +17 -1
- package/dist/identity.d.ts +6 -2
- package/dist/identity.js +36 -19
- package/dist/keystore.d.ts +223 -0
- package/dist/keystore.js +1021 -0
- package/dist/pretty.js +2 -1
- package/dist/procstart.js +11 -3
- package/dist/projects.d.ts +58 -12
- package/dist/projects.js +217 -49
- package/dist/rotation-lock.d.ts +17 -0
- package/dist/rotation-lock.js +188 -0
- package/dist/rotation.d.ts +46 -1
- package/dist/rotation.js +408 -16
- package/dist/sandbox.d.ts +195 -0
- package/dist/sandbox.js +763 -0
- package/dist/state.d.ts +8 -0
- package/dist/state.js +12 -2
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/watch.js +43 -13
- package/package.json +3 -3
package/dist/doctor.js
CHANGED
|
@@ -30,7 +30,7 @@ import { readdirSync, statSync } from "node:fs";
|
|
|
30
30
|
import { readFile, stat } from "node:fs/promises";
|
|
31
31
|
import { dirname, join } from "node:path";
|
|
32
32
|
import { fileURLToPath } from "node:url";
|
|
33
|
-
import { capAllowsKind, daysPastExp, decodeTyped, DEFAULT_SKEW_SEC, displayAddress, identityFreshness, isLive, isUserId, liveFriendshipsV3, nowSec, peekIdentityDoc, sanitizePeerText, TYP3, unfriendApplies, refreshIdentity as coreRefreshIdentity, } from "@peer2peer/core/v3";
|
|
33
|
+
import { capAllowsKind, daysPastExp, decodeTyped, DEFAULT_SKEW_SEC, displayAddress, identityFreshness, isLive, isUserId, liveFriendshipsV3, nowSec, peekIdentityDoc, sanitizePeerText, TYP3, unfriendApplies, pendingHeadSenders, refreshIdentity as coreRefreshIdentity, } from "@peer2peer/core/v3";
|
|
34
34
|
import { App, capPeek, joinCapOf, orderRelays, REPUBLISH_DOC_WITHIN_SEC } from "./app.js";
|
|
35
35
|
import { CAP_PROJECTS, CLI_CAPS, KNOWN_FEATURES, peerDevices, unavailableBetween } from "./features.js";
|
|
36
36
|
import { circleMembers, listCircles } from "./circle-ops.js";
|
|
@@ -41,7 +41,9 @@ import { rosterAudience, sessionRef } from "./sessions.js";
|
|
|
41
41
|
import { EVENT_RETENTION_MS } from "./state.js";
|
|
42
42
|
import { enabledNamespaces } from "./extensions.js";
|
|
43
43
|
import { extIxInstalled, ixBinary, ixDeclined, IX_INSTALL_URL, ixInstallLine, ixMemorySupport, ixVersion, runIx } from "./ix-local.js";
|
|
44
|
-
import { personHere } from "./projects.js";
|
|
44
|
+
import { identityHere, personHere } from "./projects.js";
|
|
45
|
+
import { keyStoreStatus } from "./keystore.js";
|
|
46
|
+
import { sandboxFix, sandboxReport } from "./sandbox.js";
|
|
45
47
|
import { graphMemoryReport } from "./graph-memory.js";
|
|
46
48
|
import { graphMemoryEnabled } from "./config.js";
|
|
47
49
|
import { historySettings } from "./history.js";
|
|
@@ -416,6 +418,33 @@ async function versionCheck(c, app, o, ms) {
|
|
|
416
418
|
async function circlesOf(app, ms) {
|
|
417
419
|
return (await bounded(listCircles(app), ms)).value ?? [];
|
|
418
420
|
}
|
|
421
|
+
/**
|
|
422
|
+
* #78: newer versions of our own identity this device holds as pending heads, with the listed relays that
|
|
423
|
+
* sent them. While one of those relays doesn't answer, edits and the key holder's renewal are refused
|
|
424
|
+
* (App.ownPendingGuard), so the document can lapse: name the relays this probe couldn't reach, and the fix.
|
|
425
|
+
* Local data only (no refresh).
|
|
426
|
+
*/
|
|
427
|
+
async function pendingHeadsCheck(c, app, view, reports, ms) {
|
|
428
|
+
const stored = (await bounded(app.store.getIdentity(app.userId), ms)).value;
|
|
429
|
+
if (!stored)
|
|
430
|
+
return;
|
|
431
|
+
const above = pendingHeadSenders(stored).filter((p) => p.ver > view.head.ver && p.relays.some((r) => view.relays.includes(r)));
|
|
432
|
+
if (above.length === 0)
|
|
433
|
+
return;
|
|
434
|
+
const newest = Math.max(...above.map((p) => p.ver));
|
|
435
|
+
const senders = [...new Set(above.flatMap((p) => p.relays.filter((r) => view.relays.includes(r))))];
|
|
436
|
+
const down = senders.filter((r) => reports.find((x) => x.relay === r)?.reachable === false);
|
|
437
|
+
const what = `this device holds version ${newest} of your identity, newer than its head (version ${view.head.ver}), from ${senders.join(", ")}`;
|
|
438
|
+
if (down.length === 0 && senders.some((r) => !reports.some((x) => x.relay === r))) {
|
|
439
|
+
c.add("pending-heads", "unknown", "newer versions of your identity", `${what}; not probed here`, "run `p2p doctor` again; if one of them stays unreachable, edits and renewals are refused until it answers or you remove it (`p2p relays remove <url>`)");
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
if (down.length === 0) {
|
|
443
|
+
c.add("pending-heads", "ok", "newer versions of your identity", `${what}; ${senders.length === 1 ? "it answers" : "they answer"}, so your next edit or renewal fetches it`);
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
c.add("pending-heads", "fail", "newer versions of your identity", `${what}; ${down.join(", ")} ${down.length === 1 ? "doesn't" : "don't"} answer, so edits and renewing your identity document are refused until ${down.length === 1 ? "it answers" : "they answer"}`, `wait for ${down.length === 1 ? "it" : "them"} to come back; if ${down.length === 1 ? "it is" : "they are"} gone for good, or no device of yours published that version: \`p2p relays remove ${down.join(" ")}\``);
|
|
447
|
+
}
|
|
419
448
|
async function deviceChecks(c, app, o, ms, reports) {
|
|
420
449
|
const view = (await bounded(app.view(app.userId), ms)).value;
|
|
421
450
|
const name = view?.head.name ?? app.self?.name ?? "?";
|
|
@@ -440,6 +469,7 @@ async function deviceChecks(c, app, o, ms, reports) {
|
|
|
440
469
|
c.add("document-fork", "fail", "identity document history", "forked (two versions claim the same place)", "run `p2p identity republish` on a key holder: it merges the branches");
|
|
441
470
|
if (view.rotations.length > 0)
|
|
442
471
|
c.add("document-rotated", "fail", "identity", "this identity moved to a new key", "follow it: `p2p held` shows the move (approve it there), or re-link with `p2p link join <code> --rotated`");
|
|
472
|
+
await pendingHeadsCheck(c, app, view, reports, ms);
|
|
443
473
|
}
|
|
444
474
|
relayChecks(c, app, reports, view ? { hash: view.head.hash, ver: view.head.ver } : undefined);
|
|
445
475
|
clockCheck(c, reports);
|
|
@@ -526,6 +556,7 @@ async function deviceChecks(c, app, o, ms, reports) {
|
|
|
526
556
|
if (dropped > 0) {
|
|
527
557
|
c.add("inbound", "unknown", "incoming envelopes", `${dropped} couldn't be applied and ${dropped === 1 ? "was" : "were"} dropped after failing for good (or every attempt)`, "if messages from someone seem missing, ask them to send again; P2P_DEBUG=1 on `p2p ls` shows why one fails");
|
|
528
558
|
}
|
|
559
|
+
sandboxChecks(c, app);
|
|
529
560
|
const ix = await ixChecks(c, app, ms);
|
|
530
561
|
await versionCheck(c, app, o, ms);
|
|
531
562
|
return dataFlowOf(app, ix);
|
|
@@ -541,6 +572,39 @@ export function dataFlowOf(app, ix) {
|
|
|
541
572
|
};
|
|
542
573
|
}
|
|
543
574
|
// ---------------------------------------------------------------------------
|
|
575
|
+
// The agents' sandboxes (sandbox.ts): whether Claude Code's and Codex's deny P2P_HOME
|
|
576
|
+
/**
|
|
577
|
+
* One line per installed front end: does its agent's sandbox deny its commands read and write
|
|
578
|
+
* access to P2P_HOME? That is the boundary the CLI's own gates rest on (an agent running as you can
|
|
579
|
+
* otherwise read the key files). Read from the person's config files; nothing is written, and
|
|
580
|
+
* nothing of their contents is shown.
|
|
581
|
+
*/
|
|
582
|
+
export function sandboxChecks(c, app) {
|
|
583
|
+
let r;
|
|
584
|
+
try {
|
|
585
|
+
r = sandboxReport(app.env);
|
|
586
|
+
}
|
|
587
|
+
catch {
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
const fix = sandboxFix(personHere(app));
|
|
591
|
+
const rows = [
|
|
592
|
+
["sandbox-claude", "Claude Code sandbox", r.claude],
|
|
593
|
+
["sandbox-codex", "Codex sandbox", r.codex],
|
|
594
|
+
];
|
|
595
|
+
for (const [id, title, s] of rows) {
|
|
596
|
+
if (!s.present && s.state !== "on")
|
|
597
|
+
continue;
|
|
598
|
+
const notes = s.notes.length > 0 ? ` (${s.notes.join("; ")})` : "";
|
|
599
|
+
if (s.state === "on")
|
|
600
|
+
c.add(id, s.notes.length > 0 ? "unknown" : "ok", title, `${s.detail}${notes}`, s.notes.length > 0 ? "see the note: it lets some commands past the deny" : undefined);
|
|
601
|
+
else if (s.state === "off")
|
|
602
|
+
c.add(id, "fail", title, `${s.detail}${notes}`, `${fix}${r.declined ? " (you said no when `p2p setup` offered it)" : ""}`);
|
|
603
|
+
else
|
|
604
|
+
c.add(id, "unknown", title, `${s.detail}${notes}`, s.state === "unavailable" ? "run your agent where its sandbox works (macOS, Linux, WSL2)" : `check ${s.settings}, then \`p2p sandbox\``);
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
// ---------------------------------------------------------------------------
|
|
544
608
|
// Ix (epic #41): the local CLI, its backend, this checkout's map, and each project's graph target
|
|
545
609
|
/** At most this many projects' graph targets are listed. */
|
|
546
610
|
const MAX_GRAPH_ROWS = 10;
|
|
@@ -868,6 +932,23 @@ async function userChecks(c, app, userId, ms, mine) {
|
|
|
868
932
|
}
|
|
869
933
|
}
|
|
870
934
|
// ---------------------------------------------------------------------------
|
|
935
|
+
/** Where this device's keys are kept (`p2p keys backend`), and whether they could be read. Never a secret. */
|
|
936
|
+
function keyStorageCheck(c, ks) {
|
|
937
|
+
const store = ks.keys === "keychain" ? `${ks.keychain.label} (item ${ks.item?.service})` : "files in P2P_HOME (cli/keys.json, 0600)";
|
|
938
|
+
if (ks.keys === "none") {
|
|
939
|
+
c.add("key-storage", "ok", "key storage", `no keys here yet; new ones go to ${ks.configured === "keychain" ? ks.keychain.label : "files in P2P_HOME"}`);
|
|
940
|
+
return;
|
|
941
|
+
}
|
|
942
|
+
if (!ks.readable) {
|
|
943
|
+
c.add("key-storage", "fail", "key storage", `${store}: the keys can't be read${ks.problem ? ` (${errText(ks.problem)})` : ""}`, ks.keys === "keychain" ? "unlock the keychain (or install its tool) and run the command again; nothing makes new keys in their place" : "check cli/keys.json in P2P_HOME");
|
|
944
|
+
return;
|
|
945
|
+
}
|
|
946
|
+
if (ks.problem) {
|
|
947
|
+
c.add("key-storage", "unknown", "key storage", `${store}, readable; ${errText(ks.problem)}`, ks.leftovers?.length && !/hasn't finished|stay in the keychain/.test(ks.problem) ? "run any p2p command that isn't read-only (`p2p whoami`): it removes them" : "run `p2p keys backend keychain` (or `p2p keys backend file`) in your own terminal");
|
|
948
|
+
return;
|
|
949
|
+
}
|
|
950
|
+
c.add("key-storage", "ok", "key storage", `${store}, readable${ks.keys === "file" && ks.keychain.available ? `; \`p2p keys backend keychain\` moves them into ${ks.keychain.label}` : ""}`);
|
|
951
|
+
}
|
|
871
952
|
export function summarize(checks) {
|
|
872
953
|
return {
|
|
873
954
|
ok: checks.filter((x) => x.status === "ok").length,
|
|
@@ -894,7 +975,23 @@ export async function doctor(app, o) {
|
|
|
894
975
|
app.tun.requestTimeoutMs = ms;
|
|
895
976
|
const c = new Checks();
|
|
896
977
|
const scope = o.user !== undefined ? "user" : "device";
|
|
897
|
-
|
|
978
|
+
let loadError;
|
|
979
|
+
const hasIdentity = await app.load(false).catch((e) => {
|
|
980
|
+
loadError = e;
|
|
981
|
+
return false;
|
|
982
|
+
});
|
|
983
|
+
// Where the keys are kept, and whether they could be read (keystore.ts): first, since nothing else works without them.
|
|
984
|
+
const ks = keyStoreStatus(app.home);
|
|
985
|
+
// About another user only when they can't be read (nothing about them can be checked then).
|
|
986
|
+
if (scope === "device" || (ks.keys !== "none" && !ks.readable))
|
|
987
|
+
keyStorageCheck(c, ks);
|
|
988
|
+
if (!hasIdentity && ks.keys !== "none" && identityHere(app.home)) {
|
|
989
|
+
c.add("identity", "fail", "identity", `this device holds an identity, but it couldn't be loaded: ${errText(loadError ?? ks.problem)}`, ks.keys === "keychain" ? "unlock the keychain (or install its tool), then run `p2p doctor` again; p2p never makes new keys in their place" : `check ${app.home}/cli/keys.json`);
|
|
990
|
+
await versionCheck(c, app, o, ms);
|
|
991
|
+
if (scope === "device")
|
|
992
|
+
sandboxChecks(c, app);
|
|
993
|
+
return { scope, version: o.version, ...(o.user !== undefined ? { user: { input: o.user } } : {}), checks: c.list, summary: summarize(c.list) };
|
|
994
|
+
}
|
|
898
995
|
if (!hasIdentity) {
|
|
899
996
|
c.add("identity", "fail", "identity", "this device has no Peer2Peer identity yet", "run `/peers setup` in Claude Code (or `p2p setup`), then `/peers join <code>` with a code from a friend");
|
|
900
997
|
let relays;
|
|
@@ -909,6 +1006,8 @@ export async function doctor(app, o) {
|
|
|
909
1006
|
else
|
|
910
1007
|
relayChecks(c, app, await probeRelays(app, relays, ms, false), undefined);
|
|
911
1008
|
await versionCheck(c, app, o, ms);
|
|
1009
|
+
if (scope === "device")
|
|
1010
|
+
sandboxChecks(c, app);
|
|
912
1011
|
return { scope, version: o.version, ...(o.user !== undefined ? { user: { input: o.user } } : {}), checks: c.list, summary: summarize(c.list) };
|
|
913
1012
|
}
|
|
914
1013
|
const reports = await probeRelays(app, app.relays, ms, true, app.userId);
|
package/dist/format.d.ts
CHANGED
|
@@ -4,11 +4,13 @@ import type { CodeRow } from "./codes.js";
|
|
|
4
4
|
import type { DeviceRow, WhoamiResult } from "./identity.js";
|
|
5
5
|
import type { PeerRow, RosterView } from "./sessions.js";
|
|
6
6
|
import type { FriendRow } from "./social.js";
|
|
7
|
-
import type { RotateResult, RotationPlan } from "./rotation.js";
|
|
7
|
+
import type { BranchSummary, RotateResult, RotationPlan } from "./rotation.js";
|
|
8
8
|
export declare function formatAge(sec: number): string;
|
|
9
9
|
export declare function formatDate(sec: number): string;
|
|
10
10
|
export declare function plural(n: number, one: string, many?: string): string;
|
|
11
11
|
export declare function formatCodes(rows: CodeRow[]): string;
|
|
12
|
+
/** A code cut to its first four characters (after any link prefix): what the listing shows of a code that no longer lets anyone in. */
|
|
13
|
+
export declare function shortCode(code: string): string;
|
|
12
14
|
/** "delivered via 2 relays (1 device)". */
|
|
13
15
|
export declare function formatDelivery(d: Pick<Delivery, "relays" | "devices">): string;
|
|
14
16
|
/** A terminal QR code of `text`; empty when it can't be rendered. */
|
|
@@ -37,6 +39,8 @@ export declare function formatMembers(r: {
|
|
|
37
39
|
}): string;
|
|
38
40
|
export declare function formatRoster(r: RosterView): string;
|
|
39
41
|
export declare function formatJoin(r: JoinResult): string;
|
|
42
|
+
/** One branch summary as text: `<hash> (ver N, published by ...; relays ...)`. */
|
|
43
|
+
export declare function branchLine(b: BranchSummary): string;
|
|
40
44
|
export declare function formatRotationPlan(p: RotationPlan): string;
|
|
41
45
|
export declare function formatRotation(r: RotateResult): string;
|
|
42
46
|
/**
|
package/dist/format.js
CHANGED
|
@@ -47,11 +47,15 @@ export function formatCodes(rows) {
|
|
|
47
47
|
default:
|
|
48
48
|
st = r.status;
|
|
49
49
|
}
|
|
50
|
-
const shown = r.status === "open" || r.status === "taken" ? r.code : r.code
|
|
50
|
+
const shown = (r.status === "open" || r.status === "taken") && !r.redacted ? r.code : shortCode(r.code);
|
|
51
51
|
return `${shown}${who}${circle}${to}: ${st}`;
|
|
52
52
|
})
|
|
53
53
|
.join("\n");
|
|
54
54
|
}
|
|
55
|
+
/** A code cut to its first four characters (after any link prefix): what the listing shows of a code that no longer lets anyone in. */
|
|
56
|
+
export function shortCode(code) {
|
|
57
|
+
return code.endsWith("…") ? code : code.replace(/[^/]*$/, (c) => `${c.slice(0, 4)}…`);
|
|
58
|
+
}
|
|
55
59
|
/** "delivered via 2 relays (1 device)". */
|
|
56
60
|
export function formatDelivery(d) {
|
|
57
61
|
return `delivered via ${plural(d.relays.length, "relay")} (${plural(d.devices, "device")})`;
|
|
@@ -183,12 +187,24 @@ export function formatJoin(r) {
|
|
|
183
187
|
return `Not joined "${r.name}" (${r.cid}): ${r.refused}.`;
|
|
184
188
|
}
|
|
185
189
|
}
|
|
190
|
+
/** One branch summary as text: `<hash> (ver N, published by ...; relays ...)`. */
|
|
191
|
+
export function branchLine(b) {
|
|
192
|
+
return `${b.hash} (ver ${b.ver}, published by ${b.by.join(", ") || "?"}; relays ${b.relays.join(", ") || "?"})`;
|
|
193
|
+
}
|
|
186
194
|
export function formatRotationPlan(p) {
|
|
187
195
|
// A label from a version this device didn't publish is shown as such (pre-release re-review N2), and so is why a device is dropped.
|
|
188
196
|
const dev = (d) => ` ${d.did}${d.label ? ` (${d.labelTrusted === false ? "unverified label: " : ""}${sanitizePeerText(d.label, 64)})` : ""}${d.keyholder ? ", key holder" : ""}${d.why ? `: DROPPED, ${d.why} (keep it with --keep ${d.did})` : ""}`;
|
|
189
197
|
return [
|
|
190
198
|
`${p.contest ? "Contesting a rotation you didn't publish: moving" : "Rotating"} ${p.address} to a new identity key ${p.newFingerprint} (§2.8).`,
|
|
191
199
|
...(p.backup ? [`Its backup phrase is in ${p.backup.file}.`] : []),
|
|
200
|
+
// #91: a branch picked by provenance among others that still list this device is never picked silently.
|
|
201
|
+
...(p.branch && p.otherBranches?.length
|
|
202
|
+
? [
|
|
203
|
+
`Your identity is forked: this plan builds on the branch ${p.branch} as yours (its versions come from your devices). Other branches still list this device:\n${p.otherBranches
|
|
204
|
+
.map((b) => ` ${branchLine(b)}`)
|
|
205
|
+
.join("\n")}\nIf ${p.branch} isn't yours, drop this plan (--cancel) and choose with --plan --branch <hash>.`,
|
|
206
|
+
]
|
|
207
|
+
: []),
|
|
192
208
|
p.follow.length ? `These devices get the rotation to follow (each follows only when you accept it there):\n${p.follow.map(dev).join("\n")}` : "No other device follows.",
|
|
193
209
|
...(p.excluded.length ? [`These devices do NOT follow (excluded):\n${p.excluded.map(dev).join("\n")}`] : []),
|
|
194
210
|
`${plural(p.friends, "friend")} get a fresh invite (they approve it); ${plural(p.owned, "circle")} you own move to the new key; in ${plural(p.memberOf, "other circle")} the owner swaps you in.`,
|
package/dist/identity.d.ts
CHANGED
|
@@ -89,8 +89,12 @@ export declare function reissueForRelays(app: App): Promise<{
|
|
|
89
89
|
}>;
|
|
90
90
|
/** Adds a relay to your identity document (the next version, published to old and new relays). */
|
|
91
91
|
export declare function relaysAdd(app: App, url: string): Promise<RelaysChange>;
|
|
92
|
-
/**
|
|
93
|
-
|
|
92
|
+
/**
|
|
93
|
+
* Removes relays (at least one must stay), in one new version. The removed relays get it too, so they stop
|
|
94
|
+
* admitting removed state. Several at once (#78 review): two relays that both went silent while holding a
|
|
95
|
+
* newer version each hold up removing the other one alone (App.ownPendingGuard).
|
|
96
|
+
*/
|
|
97
|
+
export declare function relaysRemove(app: App, urls: string | readonly string[]): Promise<RelaysChange>;
|
|
94
98
|
export interface DeviceRow {
|
|
95
99
|
did: string;
|
|
96
100
|
label: string;
|
package/dist/identity.js
CHANGED
|
@@ -16,6 +16,7 @@ import { receiving } from "./inbound.js";
|
|
|
16
16
|
import { recordJoin, resignJoin } from "./circle-ops.js";
|
|
17
17
|
import { setupIx } from "./ix-local.js";
|
|
18
18
|
import { renewPersonToken } from "./projects.js";
|
|
19
|
+
import { forgetKeychainItem } from "./keystore.js";
|
|
19
20
|
/** The `p2p` command as the person types it here (Windows PowerShell blocks npm's p2p.ps1 shim; p2p.cmd works everywhere on Windows). */
|
|
20
21
|
export function p2pCommand(platform = process.platform) {
|
|
21
22
|
return platform === "win32" ? "p2p.cmd" : "p2p";
|
|
@@ -47,7 +48,8 @@ export async function init(app, opts) {
|
|
|
47
48
|
const self = { name, relays, createdAt: Date.now() };
|
|
48
49
|
// A person.key from before this identity existed no longer counts (projects.ts renewPersonToken).
|
|
49
50
|
// Replaced before any key is written: if that fails, no identity is made here.
|
|
50
|
-
renewPersonToken(app.home);
|
|
51
|
+
renewPersonToken(app.home, keys.spk);
|
|
52
|
+
app.identityMadeHere = true;
|
|
51
53
|
await app.state.put("keys", keys);
|
|
52
54
|
await app.state.put("self", self);
|
|
53
55
|
app.setKeys(keys, self);
|
|
@@ -195,28 +197,39 @@ export async function relaysAdd(app, url) {
|
|
|
195
197
|
throw new CliError("bad_relay", `at most ${MAX_RELAYS} relays: remove one first`);
|
|
196
198
|
return changeRelays(app, (list) => [...list.filter((x) => x !== r), r]);
|
|
197
199
|
}
|
|
198
|
-
/**
|
|
199
|
-
|
|
200
|
-
|
|
200
|
+
/**
|
|
201
|
+
* Removes relays (at least one must stay), in one new version. The removed relays get it too, so they stop
|
|
202
|
+
* admitting removed state. Several at once (#78 review): two relays that both went silent while holding a
|
|
203
|
+
* newer version each hold up removing the other one alone (App.ownPendingGuard).
|
|
204
|
+
*/
|
|
205
|
+
export async function relaysRemove(app, urls) {
|
|
206
|
+
const rs = [...new Set(normalizeRelays(typeof urls === "string" ? [urls] : [...urls]))];
|
|
207
|
+
if (rs.length === 0)
|
|
208
|
+
throw new CliError("usage", "name the relay to remove");
|
|
201
209
|
const cur = (await app.ownView()).head.relays;
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
const
|
|
209
|
-
|
|
210
|
+
for (const r of rs)
|
|
211
|
+
if (!cur.includes(r))
|
|
212
|
+
throw new CliError("not_found", `${r} is not one of your relays`);
|
|
213
|
+
if (cur.every((r) => rs.includes(r)))
|
|
214
|
+
throw new CliError("usage", cur.length === 1 ? "that is your only relay: add another first" : "at least one relay must stay: add another first");
|
|
215
|
+
// Caps naming a dropped relay, captured before the re-issue adds new ones.
|
|
216
|
+
const old = (await app.store.listCapsIssued()).filter((c) => c.iss === app.userId && c.relays.some((r) => rs.includes(r)));
|
|
217
|
+
const out = await changeRelays(app, (list) => list.filter((x) => !rs.includes(x)), rs);
|
|
218
|
+
// review L2: revoke them at the dropped relays only (our devices are still in their allowlists). Other
|
|
210
219
|
// relays keep honouring them, so friends who haven't picked up the new caps stay covered.
|
|
211
220
|
// Best effort: the relay may be down.
|
|
212
221
|
let revokedAtRemoved = 0;
|
|
222
|
+
let tried = 0;
|
|
213
223
|
const pool = app.pool ?? (await app.connect({ allowNone: true }));
|
|
214
224
|
for (const c of old) {
|
|
215
|
-
|
|
216
|
-
|
|
225
|
+
for (const r of rs.filter((x) => c.relays.includes(x))) {
|
|
226
|
+
tried++;
|
|
227
|
+
if ((await pool.revoke(c.capid, [r]).catch(() => [])).length > 0)
|
|
228
|
+
revokedAtRemoved++;
|
|
229
|
+
}
|
|
217
230
|
}
|
|
218
|
-
if (revokedAtRemoved <
|
|
219
|
-
app.warn(`couldn't revoke ${
|
|
231
|
+
if (revokedAtRemoved < tried)
|
|
232
|
+
app.warn(`couldn't revoke ${tried - revokedAtRemoved} of your old caps at ${rs.join(", ")}; they expire on their own`);
|
|
220
233
|
return { ...out, revokedAtRemoved };
|
|
221
234
|
}
|
|
222
235
|
export async function devices(app) {
|
|
@@ -496,7 +509,8 @@ export async function linkJoin(app, code, opts = {}) {
|
|
|
496
509
|
}
|
|
497
510
|
const keys = newKeysDoc(userId, { ...device, userId }, opened.cert.jws, opened.ik);
|
|
498
511
|
const self = { name: opened.doc.name, relays: opened.doc.relays, createdAt: Date.now() };
|
|
499
|
-
renewPersonToken(app.home);
|
|
512
|
+
renewPersonToken(app.home, keys.spk);
|
|
513
|
+
app.identityMadeHere = true;
|
|
500
514
|
await app.state.put("keys", keys);
|
|
501
515
|
await app.state.put("self", self);
|
|
502
516
|
app.setKeys(keys, self);
|
|
@@ -547,6 +561,7 @@ export async function backupRestore(app, phrase, opts) {
|
|
|
547
561
|
// review N-H1: nothing is committed unless a relay took the new version. The home was fresh
|
|
548
562
|
// (checked above), and no relay can hold the new version (every publish was refused outright or
|
|
549
563
|
// never reached a relay), so its state directories go; config.json stays.
|
|
564
|
+
forgetKeychainItem(app.home, app.keys?.did);
|
|
550
565
|
await rm(join(app.home, "cli"), { recursive: true, force: true });
|
|
551
566
|
await rm(join(app.home, "v3"), { recursive: true, force: true });
|
|
552
567
|
throw e;
|
|
@@ -591,7 +606,8 @@ async function restoreInto(app, phrase, opts) {
|
|
|
591
606
|
if (found === 0) {
|
|
592
607
|
const name = opts.name ?? defaultName();
|
|
593
608
|
const doc = createIdentityDoc(ik, { ver: 1, prev: null, name, relays, devices: [device.did], keyholders: [device.did], by: device.did, certs: [cert] });
|
|
594
|
-
renewPersonToken(app.home);
|
|
609
|
+
renewPersonToken(app.home, keys.spk);
|
|
610
|
+
app.identityMadeHere = true;
|
|
595
611
|
await app.state.put("keys", keys);
|
|
596
612
|
await app.state.put("self", { ...self, name });
|
|
597
613
|
app.setKeys(keys, { ...self, name });
|
|
@@ -614,7 +630,8 @@ async function restoreInto(app, phrase, opts) {
|
|
|
614
630
|
const existing = await app.refreshIdentity(ik.userId, relays, { force: true, strict: true });
|
|
615
631
|
if (!existing)
|
|
616
632
|
throw new CliError("refresh_failed", "couldn't fit the relays' identity document");
|
|
617
|
-
renewPersonToken(app.home);
|
|
633
|
+
renewPersonToken(app.home, keys.spk);
|
|
634
|
+
app.identityMadeHere = true;
|
|
618
635
|
await app.state.put("keys", keys);
|
|
619
636
|
await app.store.putDeviceCert({ userId: ik.userId, did: device.did, exp: verifyDeviceCertV3(cert).exp, jws: cert });
|
|
620
637
|
await app.state.put("self", { ...self, name: existing.head.name, relays: existing.head.relays });
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
export type KeyBackend = "file" | "keychain";
|
|
2
|
+
/** One run of an OS tool: what came back. `error` is the spawn's own failure (ENOENT, ETIMEDOUT). */
|
|
3
|
+
export interface RunResult {
|
|
4
|
+
status: number | null;
|
|
5
|
+
stdout: string;
|
|
6
|
+
stderr: string;
|
|
7
|
+
error?: string;
|
|
8
|
+
}
|
|
9
|
+
/** Runs `file` with `args` (never through a shell), `input` on its stdin. Tests stand in their own. */
|
|
10
|
+
export type Runner = (file: string, args: readonly string[], input: string) => RunResult;
|
|
11
|
+
/** How long one keychain call may take: a locked keychain may be showing its unlock prompt. */
|
|
12
|
+
export declare const KEYCHAIN_TIMEOUT_MS = 20000;
|
|
13
|
+
export declare const realRunner: Runner;
|
|
14
|
+
/** A keychain call that failed: `reason` is safe to show (never the secret, never the tool's raw output with it). */
|
|
15
|
+
export declare class KeychainError extends Error {
|
|
16
|
+
readonly reason: string;
|
|
17
|
+
constructor(reason: string);
|
|
18
|
+
}
|
|
19
|
+
export interface Keychain {
|
|
20
|
+
readonly kind: "macos" | "linux" | "windows";
|
|
21
|
+
/** "the macOS Keychain", for messages. */
|
|
22
|
+
readonly label: string;
|
|
23
|
+
/** Why this keychain can't be used here (its tool is missing), or undefined. */
|
|
24
|
+
unavailable(): string | undefined;
|
|
25
|
+
/** The secret, or undefined when there is no such item. Throws KeychainError when the keychain can't be read. */
|
|
26
|
+
get(service: string, account: string): string | undefined;
|
|
27
|
+
/** Stores (or replaces) the item. Throws KeychainError. */
|
|
28
|
+
set(service: string, account: string, label: string, secret: string): void;
|
|
29
|
+
/** Deletes the item; false when there was none. Throws KeychainError. */
|
|
30
|
+
remove(service: string, account: string): boolean;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* The tool's message, safe to show: one line, short, with the secret (and anything shaped like one)
|
|
34
|
+
* taken out. The tools don't echo secrets, but this never relies on it.
|
|
35
|
+
*/
|
|
36
|
+
export declare function toolMessage(out: string, secret?: string): string;
|
|
37
|
+
export declare const SECURITY = "/usr/bin/security";
|
|
38
|
+
/**
|
|
39
|
+
* The macOS Keychain through `/usr/bin/security`. Writes go through `security -i`, which reads its
|
|
40
|
+
* commands from stdin, so the secret is never in a command line. The item's access list trusts
|
|
41
|
+
* `/usr/bin/security` only (`-T`): other apps get the system's prompt. `keychainFile` points at
|
|
42
|
+
* another keychain than the default one (the opt-in test uses a throwaway keychain).
|
|
43
|
+
*/
|
|
44
|
+
export declare function macosKeychain(run?: Runner, opts?: {
|
|
45
|
+
keychainFile?: string;
|
|
46
|
+
exists?: (p: string) => boolean;
|
|
47
|
+
}): Keychain;
|
|
48
|
+
/** Where secret-tool is looked for: system folders only (never PATH, never a user-writable folder). */
|
|
49
|
+
export declare const SECRET_TOOL_PATHS: string[];
|
|
50
|
+
/** The Secret Service (GNOME Keyring, KWallet) through libsecret's `secret-tool`; `store` reads the secret from stdin. */
|
|
51
|
+
export declare function libsecretKeychain(run?: Runner, opts?: {
|
|
52
|
+
exists?: (p: string) => boolean;
|
|
53
|
+
}): Keychain;
|
|
54
|
+
/**
|
|
55
|
+
* The C# that does the work on Windows. It reads the request from stdin itself and writes the answer
|
|
56
|
+
* to stdout itself, so the secret never passes through a PowerShell cmdlet, pipeline or variable
|
|
57
|
+
* (with PowerShell module or script block logging on, those are recorded in the event log). The
|
|
58
|
+
* request: one field per line, `op`, `target`, `account`, `label`, `secret` (each in the narrow
|
|
59
|
+
* alphabets above: no line breaks). Credentials are generic ones persisted on this machine only
|
|
60
|
+
* (CRED_PERSIST_LOCAL_MACHINE: never roamed). Exit 3: no such credential.
|
|
61
|
+
*/
|
|
62
|
+
export declare const WINDOWS_CSHARP: string;
|
|
63
|
+
/**
|
|
64
|
+
* The PowerShell that runs it (passed as -EncodedCommand: no secret in it): a static loader that
|
|
65
|
+
* compiles the C# above with the .NET compiler directly and calls it. No cmdlet runs (not even
|
|
66
|
+
* Add-Type), no module is loaded (autoloading off: nothing from a user-writable PSModulePath), and
|
|
67
|
+
* nothing reads stdin but the C#.
|
|
68
|
+
*/
|
|
69
|
+
export declare const WINDOWS_SCRIPT: string;
|
|
70
|
+
/** The fixed path of Windows PowerShell 5.1, which every supported Windows has. */
|
|
71
|
+
export declare const WINDOWS_POWERSHELL = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
|
|
72
|
+
/**
|
|
73
|
+
* Windows PowerShell by its absolute path: the fixed `C:\\Windows` one when it is there. Otherwise
|
|
74
|
+
* %SystemRoot% (or %windir%) only when it is a drive's own Windows folder (`D:\\Windows`, `D:\\WINNT`),
|
|
75
|
+
* never anything else the environment names (a folder in a user profile). Undefined: none to trust.
|
|
76
|
+
*/
|
|
77
|
+
export declare function powershellPath(env?: Record<string, string | undefined>, exists?: (p: string) => boolean): string | undefined;
|
|
78
|
+
export declare function windowsKeychain(run?: Runner, opts?: {
|
|
79
|
+
exists?: (p: string) => boolean;
|
|
80
|
+
env?: Record<string, string | undefined>;
|
|
81
|
+
}): Keychain;
|
|
82
|
+
/** Tests: use `k` instead of the platform's keychain (null: none on this platform); undefined restores it. */
|
|
83
|
+
export declare function useKeychainForTests(k: Keychain | null | undefined): void;
|
|
84
|
+
/** This platform's keychain, or undefined where p2p knows none. */
|
|
85
|
+
export declare function platformKeychain(platform?: NodeJS.Platform): Keychain | undefined;
|
|
86
|
+
export declare const SERVICE_PREFIX = "peer2peer-keys-";
|
|
87
|
+
/** Contains the service prefix, so a guard looking for p2p's items also sees a lookup by label. */
|
|
88
|
+
export declare const LABEL = "peer2peer-keys-device";
|
|
89
|
+
/** The home as the keychain item names it: its real path when it exists (a symlinked P2P_HOME is the same home). */
|
|
90
|
+
export declare function canonicalHome(home: string): string;
|
|
91
|
+
/** The keychain service for `home`: one per home, so two homes (two identities on one machine) never share an item. */
|
|
92
|
+
export declare function serviceFor(home: string): string;
|
|
93
|
+
export declare function markerFile(home: string): string;
|
|
94
|
+
/** The backend new keys are written to: keystore.json's, else files. Throws when the file is there but unreadable (fail closed). */
|
|
95
|
+
export declare function configuredBackend(home: string): KeyBackend;
|
|
96
|
+
/** The keys document as the CLI uses it (state.ts KeysDoc), with secrets. */
|
|
97
|
+
export interface FullKeys {
|
|
98
|
+
v: 1;
|
|
99
|
+
userId: string;
|
|
100
|
+
did: string;
|
|
101
|
+
spk: string;
|
|
102
|
+
kpk: string;
|
|
103
|
+
cert: string;
|
|
104
|
+
ik?: string;
|
|
105
|
+
[k: string]: unknown;
|
|
106
|
+
}
|
|
107
|
+
/** keys.json when the secrets are in the keychain. */
|
|
108
|
+
interface SealedKeys {
|
|
109
|
+
v: 1;
|
|
110
|
+
userId: string;
|
|
111
|
+
did: string;
|
|
112
|
+
cert: string;
|
|
113
|
+
store: "keychain";
|
|
114
|
+
service: string;
|
|
115
|
+
[k: string]: unknown;
|
|
116
|
+
}
|
|
117
|
+
/** Whether a raw keys.json holds the secrets itself. */
|
|
118
|
+
export declare function holdsSecrets(raw: unknown): boolean;
|
|
119
|
+
/** Whether a raw keys.json says its secrets are in the keychain. */
|
|
120
|
+
export declare function isSealed(raw: unknown): raw is SealedKeys;
|
|
121
|
+
/** The item's secret for keys `k` (exported for the tests). */
|
|
122
|
+
export declare function payloadOf(k: FullKeys): string;
|
|
123
|
+
/** The keys document as the CLI uses it from what keys.json holds: the secrets from the keychain when it says so. */
|
|
124
|
+
export declare function openKeys(home: string, raw: unknown): unknown;
|
|
125
|
+
/**
|
|
126
|
+
* The device signing seed for the person token (projects.ts), read synchronously: from keys.json,
|
|
127
|
+
* or from the keychain when keys.json says so. Undefined when it can't be read.
|
|
128
|
+
*/
|
|
129
|
+
export declare function signingSeedSync(home: string): string | undefined;
|
|
130
|
+
/** Throws the keychain's error when this home's keys are in a keychain that can't be read now; else nothing. */
|
|
131
|
+
export declare function assertKeysReadable(home: string): void;
|
|
132
|
+
/** Whether this home's keys are in a keychain that can't be read now. */
|
|
133
|
+
export declare function keysUnreadable(home: string): boolean;
|
|
134
|
+
/** What CliState's backend is (state.ts CliBackend), restated here to keep this module free of state.ts. */
|
|
135
|
+
export interface DocStore {
|
|
136
|
+
read(name: string): Promise<unknown>;
|
|
137
|
+
write(name: string, value: unknown): Promise<void>;
|
|
138
|
+
remove?(name: string): Promise<void>;
|
|
139
|
+
withLock<T>(fn: () => Promise<T>): Promise<T>;
|
|
140
|
+
}
|
|
141
|
+
/** Removes the wipe files a move left behind (zeroed where safe: zeroAndRemove). Returns how many there were. */
|
|
142
|
+
export declare function sweepWipeLeftovers(home: string): Promise<number>;
|
|
143
|
+
/**
|
|
144
|
+
* CliState's backend with the keys document routed: written to the keychain when the home chose it
|
|
145
|
+
* (keystore.json), read from wherever keys.json says. Every other document passes through.
|
|
146
|
+
*/
|
|
147
|
+
export declare class KeyStoreBackend implements DocStore {
|
|
148
|
+
readonly inner: DocStore;
|
|
149
|
+
readonly home: string;
|
|
150
|
+
/** A read-only run's overlay (readonly.ts): writes stay in memory, never reach the keychain. */
|
|
151
|
+
private readonly opts;
|
|
152
|
+
constructor(inner: DocStore, home: string,
|
|
153
|
+
/** A read-only run's overlay (readonly.ts): writes stay in memory, never reach the keychain. */
|
|
154
|
+
opts?: {
|
|
155
|
+
memoryOnly?: boolean;
|
|
156
|
+
});
|
|
157
|
+
read(name: string): Promise<unknown>;
|
|
158
|
+
/** keys.json as it is on disk (sealed or not). */
|
|
159
|
+
readRaw(): Promise<unknown>;
|
|
160
|
+
write(name: string, value: unknown): Promise<void>;
|
|
161
|
+
remove(name: string): Promise<void>;
|
|
162
|
+
withLock<T>(fn: () => Promise<T>): Promise<T>;
|
|
163
|
+
}
|
|
164
|
+
export interface KeyStoreStatus {
|
|
165
|
+
/** Where new keys are written (keystore.json). */
|
|
166
|
+
configured: KeyBackend;
|
|
167
|
+
/** Where this device's keys are now: none (no identity here yet), file or keychain. */
|
|
168
|
+
keys: "none" | "file" | "keychain";
|
|
169
|
+
/** Whether they could be read just now. */
|
|
170
|
+
readable: boolean;
|
|
171
|
+
/** What is wrong, in words, when something is. */
|
|
172
|
+
problem?: string;
|
|
173
|
+
/** The OS keychain p2p uses on this platform. */
|
|
174
|
+
keychain: {
|
|
175
|
+
kind?: Keychain["kind"];
|
|
176
|
+
label: string;
|
|
177
|
+
available: boolean;
|
|
178
|
+
why?: string;
|
|
179
|
+
};
|
|
180
|
+
/** keychain: the item's service name and account (not secret). */
|
|
181
|
+
item?: {
|
|
182
|
+
service: string;
|
|
183
|
+
account: string;
|
|
184
|
+
};
|
|
185
|
+
/** Wipe files an interrupted move left in `cli/` (they may hold the old keys.json's bytes). */
|
|
186
|
+
leftovers?: string[];
|
|
187
|
+
}
|
|
188
|
+
/** Where this home's keys are and whether they can be read (no secret in it). Read only. */
|
|
189
|
+
export declare function keyStoreStatus(home: string): KeyStoreStatus;
|
|
190
|
+
export interface MoveResult {
|
|
191
|
+
backend: KeyBackend;
|
|
192
|
+
/** Whether keys were moved (false: there were none yet, or they were there already). */
|
|
193
|
+
moved: boolean;
|
|
194
|
+
/** Where new keys go from now on, in words. */
|
|
195
|
+
where: string;
|
|
196
|
+
item?: {
|
|
197
|
+
service: string;
|
|
198
|
+
account: string;
|
|
199
|
+
};
|
|
200
|
+
warnings: string[];
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Moves this home's keys into the keychain: stored, read back and compared byte for byte, and only
|
|
204
|
+
* then keys.json loses its secrets (its old bytes overwritten). Each step can be repeated: an
|
|
205
|
+
* interrupted move is finished by running it again (or by the next command that loads the keys).
|
|
206
|
+
*/
|
|
207
|
+
export declare function moveKeysToKeychain(store: KeyStoreBackend): Promise<MoveResult>;
|
|
208
|
+
/**
|
|
209
|
+
* Moves this home's keys back into keys.json: written and read back first, then the keychain item
|
|
210
|
+
* is deleted. Fails closed: keys that can't be read from the keychain stay there.
|
|
211
|
+
*/
|
|
212
|
+
export declare function moveKeysToFiles(store: KeyStoreBackend): Promise<MoveResult>;
|
|
213
|
+
/**
|
|
214
|
+
* A home that chose the keychain whose keys.json holds secrets (a move that was interrupted, or a
|
|
215
|
+
* rotation or follow that swapped in a new identity's files): moves them now. Called on load by
|
|
216
|
+
* commands that may write; never by read-only ones. Returns a warning when it couldn't.
|
|
217
|
+
*/
|
|
218
|
+
export declare function finishPendingMove(store: KeyStoreBackend): Promise<string | undefined>;
|
|
219
|
+
/** Stores, reads back and deletes a throwaway item under `service`; throws when any of it fails. Its secret is random, never a key. */
|
|
220
|
+
export declare function probeKeychain(kc: Keychain, service: string): void;
|
|
221
|
+
/** Best effort: deletes this home's keychain item for device `did` (a half-made identity that was wiped). */
|
|
222
|
+
export declare function forgetKeychainItem(home: string, did: string | undefined): void;
|
|
223
|
+
export {};
|