@peer2peer/cli 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +370 -2
- package/dist/ancestry.d.ts +13 -0
- package/dist/ancestry.js +71 -0
- package/dist/app.d.ts +368 -0
- package/dist/app.js +1181 -0
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +56 -0
- package/dist/circle-ops.d.ts +402 -0
- package/dist/circle-ops.js +1725 -0
- package/dist/cli.d.ts +660 -0
- package/dist/cli.js +1787 -0
- package/dist/codes.d.ts +231 -0
- package/dist/codes.js +998 -0
- package/dist/config.d.ts +159 -0
- package/dist/config.js +294 -0
- package/dist/doctor.d.ts +113 -0
- package/dist/doctor.js +930 -0
- package/dist/errors.d.ts +8 -0
- package/dist/errors.js +29 -0
- package/dist/ext-host.d.ts +38 -0
- package/dist/ext-host.js +293 -0
- package/dist/extensions.d.ts +487 -0
- package/dist/extensions.js +406 -0
- package/dist/features.d.ts +91 -0
- package/dist/features.js +164 -0
- package/dist/format.d.ts +57 -0
- package/dist/format.js +248 -0
- package/dist/graph-memory.d.ts +107 -0
- package/dist/graph-memory.js +393 -0
- package/dist/history.d.ts +155 -0
- package/dist/history.js +697 -0
- package/dist/identity.d.ts +239 -0
- package/dist/identity.js +759 -0
- package/dist/inbound.d.ts +32 -0
- package/dist/inbound.js +261 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +14 -0
- package/dist/ix-local.d.ts +76 -0
- package/dist/ix-local.js +203 -0
- package/dist/join-answers.d.ts +49 -0
- package/dist/join-answers.js +149 -0
- package/dist/outbox.d.ts +109 -0
- package/dist/outbox.js +337 -0
- package/dist/pretty.d.ts +100 -0
- package/dist/pretty.js +256 -0
- package/dist/procstart.d.ts +1 -0
- package/dist/procstart.js +66 -0
- package/dist/progress.d.ts +30 -0
- package/dist/progress.js +78 -0
- package/dist/projects.d.ts +491 -0
- package/dist/projects.js +1383 -0
- package/dist/prompt/picker.d.ts +64 -0
- package/dist/prompt/picker.js +152 -0
- package/dist/prompt/tty.d.ts +29 -0
- package/dist/prompt/tty.js +122 -0
- package/dist/readonly.d.ts +20 -0
- package/dist/readonly.js +50 -0
- package/dist/receipts.d.ts +99 -0
- package/dist/receipts.js +182 -0
- package/dist/relay-client.d.ts +277 -0
- package/dist/relay-client.js +873 -0
- package/dist/relay-info.d.ts +24 -0
- package/dist/relay-info.js +53 -0
- package/dist/rotation.d.ts +402 -0
- package/dist/rotation.js +2054 -0
- package/dist/running.d.ts +5 -0
- package/dist/running.js +74 -0
- package/dist/sessions.d.ts +355 -0
- package/dist/sessions.js +1247 -0
- package/dist/shortcode.d.ts +149 -0
- package/dist/shortcode.js +465 -0
- package/dist/social.d.ts +139 -0
- package/dist/social.js +485 -0
- package/dist/state.d.ts +509 -0
- package/dist/state.js +220 -0
- package/dist/stdin.d.ts +17 -0
- package/dist/stdin.js +46 -0
- package/dist/sync.d.ts +77 -0
- package/dist/sync.js +375 -0
- package/dist/transient.d.ts +1 -0
- package/dist/transient.js +28 -0
- package/dist/trust.d.ts +37 -0
- package/dist/trust.js +134 -0
- package/dist/tty-confirm.d.ts +2 -0
- package/dist/tty-confirm.js +53 -0
- package/dist/tui/command.d.ts +20 -0
- package/dist/tui/command.js +70 -0
- package/dist/tui/frame.d.ts +43 -0
- package/dist/tui/frame.js +111 -0
- package/dist/tui/model.d.ts +221 -0
- package/dist/tui/model.js +259 -0
- package/dist/tui/sanitize.d.ts +13 -0
- package/dist/tui/sanitize.js +151 -0
- package/dist/tui/terminal.d.ts +88 -0
- package/dist/tui/terminal.js +354 -0
- package/dist/tui/tui.d.ts +78 -0
- package/dist/tui/tui.js +612 -0
- package/dist/tui/view.d.ts +4 -0
- package/dist/tui/view.js +358 -0
- package/dist/unknown-kinds.d.ts +12 -0
- package/dist/unknown-kinds.js +66 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +5 -0
- package/dist/want-pow.d.ts +12 -0
- package/dist/want-pow.js +46 -0
- package/dist/watch.d.ts +35 -0
- package/dist/watch.js +331 -0
- package/dist/xstate.d.ts +125 -0
- package/dist/xstate.js +422 -0
- package/package.json +60 -4
package/dist/social.d.ts
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { type AcceptedMessageV3 } from "@peer2peer/core/v3";
|
|
2
|
+
import type { App, Delivery } from "./app.js";
|
|
3
|
+
import { type NewEvent } from "./inbound.js";
|
|
4
|
+
import { type SyncBody } from "./sync.js";
|
|
5
|
+
import type { HeldItem } from "./state.js";
|
|
6
|
+
export interface InviteResult {
|
|
7
|
+
invite: {
|
|
8
|
+
inv: string;
|
|
9
|
+
aud: string;
|
|
10
|
+
exp: number;
|
|
11
|
+
uses: number;
|
|
12
|
+
};
|
|
13
|
+
link: string;
|
|
14
|
+
web: string;
|
|
15
|
+
delivered?: Delivery;
|
|
16
|
+
}
|
|
17
|
+
/** A minted invite (§3.1): recorded as outgoing, its contact cap as issued, both synced. */
|
|
18
|
+
export interface MintedInvite {
|
|
19
|
+
jws: string;
|
|
20
|
+
inv: string;
|
|
21
|
+
aud: string;
|
|
22
|
+
exp: number;
|
|
23
|
+
uses: number;
|
|
24
|
+
cap: string;
|
|
25
|
+
}
|
|
26
|
+
export declare function mintInvite(app: App, opts: {
|
|
27
|
+
aud: string;
|
|
28
|
+
uses: number;
|
|
29
|
+
ttlSec: number;
|
|
30
|
+
extraSync?: Partial<SyncBody>;
|
|
31
|
+
}): Promise<MintedInvite>;
|
|
32
|
+
export declare function invite(app: App, opts: {
|
|
33
|
+
to?: string;
|
|
34
|
+
uses?: number;
|
|
35
|
+
ttlDays?: number;
|
|
36
|
+
}): Promise<InviteResult>;
|
|
37
|
+
export interface AcceptResult {
|
|
38
|
+
friend: {
|
|
39
|
+
userId: string;
|
|
40
|
+
address: string;
|
|
41
|
+
};
|
|
42
|
+
delivered: Delivery;
|
|
43
|
+
}
|
|
44
|
+
/** Accepts an invite (a link, or the JWS of a held invite). */
|
|
45
|
+
/** The relays an invite names, unverified (a parse-time look): its `relays`, its bundled document's, its cap's. */
|
|
46
|
+
export declare function inviteRelays(jws: string): string[];
|
|
47
|
+
/**
|
|
48
|
+
* `p2p accept <link>`, before accept(): a link the person pasted, from anyone. The relays it names (its own list, its
|
|
49
|
+
* bundled document's, its cap's) are dialed to check it, so one on a loopback, link-local or private
|
|
50
|
+
* address is refused unless opted in, literally and where its name resolves (App.guardRelays).
|
|
51
|
+
* Invites that arrived otherwise (held, a rotation, the TUI) go to accept() as they are.
|
|
52
|
+
*/
|
|
53
|
+
export declare function guardInviteLink(app: App, input: string, opts?: {
|
|
54
|
+
allowPrivateRelay?: boolean;
|
|
55
|
+
}): Promise<void>;
|
|
56
|
+
/** Refuses private relays someone else named (literal hosts, and names resolving to private addresses), then guards their connections. */
|
|
57
|
+
export declare function guardForeignRelays(app: App, input: readonly string[], what: string, allow: boolean, opts?: {
|
|
58
|
+
code?: boolean;
|
|
59
|
+
}): Promise<void>;
|
|
60
|
+
export declare function accept(app: App, input: string): Promise<AcceptResult>;
|
|
61
|
+
/**
|
|
62
|
+
* Refuses, before anything is accepted or sent, an invite issued at or before an unfriend
|
|
63
|
+
* between its issuer and us: the friendship it makes would be ended at once, on every client
|
|
64
|
+
* (core unfriendApplies). That happens when we re-friend within the unfriend's second, or when
|
|
65
|
+
* the unfriender's clock is ahead of the inviter's and the inviter didn't yet hold the unfriend.
|
|
66
|
+
*/
|
|
67
|
+
export declare function refuseIfUnfriendedAfter(app: App, invite: {
|
|
68
|
+
iss: string;
|
|
69
|
+
iat: number;
|
|
70
|
+
}): Promise<void>;
|
|
71
|
+
/** `contact` envelopes (§4.3): invites are held; accepts, unfriends and cap grants are applied. */
|
|
72
|
+
export declare function onContact(app: App, env: string, r: AcceptedMessageV3): Promise<NewEvent[]>;
|
|
73
|
+
/** The `unfriend` kind (§4.3): the core already stored it; take back our caps. */
|
|
74
|
+
export declare function onUnfriendKind(app: App, env: string, r: AcceptedMessageV3): Promise<NewEvent[]>;
|
|
75
|
+
export declare function unfriend(app: App, who: string): Promise<{
|
|
76
|
+
unfriended: string;
|
|
77
|
+
address: string;
|
|
78
|
+
delivered: Delivery[];
|
|
79
|
+
revoked: number;
|
|
80
|
+
}>;
|
|
81
|
+
export declare function block(app: App, who: string): Promise<{
|
|
82
|
+
blocked: string;
|
|
83
|
+
address: string;
|
|
84
|
+
revoked: number;
|
|
85
|
+
rekeyedCircles: string[];
|
|
86
|
+
}>;
|
|
87
|
+
export declare function unblock(app: App, who: string): Promise<{
|
|
88
|
+
unblocked: string;
|
|
89
|
+
address: string;
|
|
90
|
+
}>;
|
|
91
|
+
export declare function petname(app: App, who: string, name: string | undefined): Promise<{
|
|
92
|
+
userId: string;
|
|
93
|
+
petname: string | null;
|
|
94
|
+
address: string;
|
|
95
|
+
}>;
|
|
96
|
+
export interface FriendRow {
|
|
97
|
+
userId: string;
|
|
98
|
+
address: string;
|
|
99
|
+
since: number;
|
|
100
|
+
direction: "outgoing" | "incoming";
|
|
101
|
+
canMessage: boolean;
|
|
102
|
+
}
|
|
103
|
+
export declare function friends(app: App): Promise<{
|
|
104
|
+
friends: FriendRow[];
|
|
105
|
+
invites: {
|
|
106
|
+
outgoing: {
|
|
107
|
+
inv: string;
|
|
108
|
+
aud: string;
|
|
109
|
+
exp: number;
|
|
110
|
+
}[];
|
|
111
|
+
held: number;
|
|
112
|
+
};
|
|
113
|
+
blocked: {
|
|
114
|
+
userId: string;
|
|
115
|
+
address: string;
|
|
116
|
+
}[];
|
|
117
|
+
}>;
|
|
118
|
+
/** Minimum length of an id prefix `held approve|decline` accepts. */
|
|
119
|
+
export declare const HELD_ID_MIN_PREFIX = 8;
|
|
120
|
+
/**
|
|
121
|
+
* A held item's id: a type letter and 16 b32 characters (80 bits) of
|
|
122
|
+
* SHA-256 over the whole held object (everything but when it arrived), so no
|
|
123
|
+
* peer can grind an item that collides with another.
|
|
124
|
+
*/
|
|
125
|
+
export declare function withHeldId(item: Omit<HeldItem, "id">): HeldItem;
|
|
126
|
+
export declare function hold(app: App, item: HeldItem): Promise<void>;
|
|
127
|
+
export declare function dropHeld(app: App, pred: (h: HeldItem) => boolean): Promise<HeldItem[]>;
|
|
128
|
+
export declare function listHeld(app: App): Promise<(HeldItem & {
|
|
129
|
+
address: string;
|
|
130
|
+
summary: string;
|
|
131
|
+
oldAddress?: string;
|
|
132
|
+
confirmedByDocument?: boolean;
|
|
133
|
+
choices?: {
|
|
134
|
+
userId: string;
|
|
135
|
+
address: string;
|
|
136
|
+
}[];
|
|
137
|
+
})[]>;
|
|
138
|
+
/** An exact id, or a unique prefix of at least 8 characters; ambiguous prefixes are refused. */
|
|
139
|
+
export declare function getHeld(app: App, id: string): Promise<HeldItem>;
|
package/dist/social.js
ADDED
|
@@ -0,0 +1,485 @@
|
|
|
1
|
+
// Copyright 2026 Ix Infrastructure Inc.
|
|
2
|
+
//
|
|
3
|
+
// Friends, blocks, petnames and held first contacts (docs/protocol.md §3.1,
|
|
4
|
+
// §3.2, §5.3).
|
|
5
|
+
//
|
|
6
|
+
// - `invite` mints a contact-only cap (§5.3) and an invite carrying our
|
|
7
|
+
// ik, relays and identity document, so the invitee needs no lookup.
|
|
8
|
+
// - `accept` records the friendship, then sends the accept (with our friend
|
|
9
|
+
// cap and document) as a `contact` envelope using the invite's cap.
|
|
10
|
+
// - The inviter, on the accept, records the friendship and grants its own
|
|
11
|
+
// friend cap back in a `contact` envelope (§5.3: caps in both directions).
|
|
12
|
+
// - Invites from anyone are held for the user (§3.1); nothing is acted on
|
|
13
|
+
// automatically.
|
|
14
|
+
// - Unfriend and block revoke the caps issued to that user at every relay
|
|
15
|
+
// they name.
|
|
16
|
+
//
|
|
17
|
+
// Reading of `--uses N`: the cap's per-relay use count (§5.3 SHOULD for
|
|
18
|
+
// shareable codes). An invite still binds to the first person who accepts it
|
|
19
|
+
// (v2 "invite-already-bound").
|
|
20
|
+
import { b32Encode, blockUser, sha256, capsToRevokeOnUnfriend, createAcceptV3, createCap, createInviteV3, createUnfriendV3, DEFAULT_SKEW_SEC, INVITE_MAX_TTL_SEC, inviteIatAfterUnfriends, inviteHashV3, inviteLink, liveFriendshipsV3, nowSec, P2PError, parseInviteLink, recordFriendshipV3, verifyInviteV3, reverifyInviteForApproval, reverifyFriendshipForApproval, verifyFriendshipV3, parseCircleVersion, unfriendApplies, unfriendEndingInvite, circleDisplayName, verifyUnfriendV3, peekIdentityDoc, } from "@peer2peer/core/v3";
|
|
21
|
+
import { isOwnRelay, refusePrivateRelays, refusePrivateResolved } from "./shortcode.js";
|
|
22
|
+
import { CliError } from "./errors.js";
|
|
23
|
+
import { isTransient } from "./transient.js";
|
|
24
|
+
import { fromOf, makeEvent } from "./inbound.js";
|
|
25
|
+
import { recordJoinAnswer, rekeyJoinsExcluding } from "./circle-ops.js";
|
|
26
|
+
import { listOutgoing, sendSync } from "./sync.js";
|
|
27
|
+
import { codeByInv, codeHint, onCodeRedeemed } from "./codes.js";
|
|
28
|
+
import { onRotationContact } from "./rotation.js";
|
|
29
|
+
export async function mintInvite(app, opts) {
|
|
30
|
+
const { aud, uses } = opts;
|
|
31
|
+
const ttl = Math.min(INVITE_MAX_TTL_SEC, opts.ttlSec);
|
|
32
|
+
const head = (await app.ownView()).head;
|
|
33
|
+
// An unfriend ends every friendship of the pair whose invite was issued at or before it (whole
|
|
34
|
+
// seconds, by the unfriender's clock): date the invite after every unfriend we know of, so a
|
|
35
|
+
// re-friend in the same second, or with the other side's clock ahead, isn't refused.
|
|
36
|
+
const now = nowSec();
|
|
37
|
+
const iat = inviteIatAfterUnfriends(app.userId, aud, await app.store.listUnfriends(), now);
|
|
38
|
+
if (iat - now > DEFAULT_SKEW_SEC) {
|
|
39
|
+
throw new CliError("clock_skew", `an unfriend between you is dated ${iat - 1 - now}s ahead of this device's clock, more than the ${DEFAULT_SKEW_SEC}s tolerated: check this clock (\`p2p doctor\`), or wait ${iat - now - DEFAULT_SKEW_SEC}s and invite again`);
|
|
40
|
+
}
|
|
41
|
+
const cap = createCap(app.device, app.keys.cert, { purpose: "contact", sub: aud, relays: app.relays, uses, ttlSec: ttl });
|
|
42
|
+
let jws;
|
|
43
|
+
try {
|
|
44
|
+
jws = createInviteV3(app.signer(), { aud, ik: head.ik, relays: app.relays, doc: head.jws, cap, ttlSec: ttl, iat });
|
|
45
|
+
}
|
|
46
|
+
catch (e) {
|
|
47
|
+
if (e instanceof P2PError && e.reason === "malformed") {
|
|
48
|
+
throw new CliError("too_large", `the invite doesn't fit 16 KiB with your identity document (${e.message}); a smaller avatar helps`);
|
|
49
|
+
}
|
|
50
|
+
throw e;
|
|
51
|
+
}
|
|
52
|
+
const inv = inviteHashV3(jws);
|
|
53
|
+
const exp = iat + ttl;
|
|
54
|
+
await app.store.addOutgoingInvite({ inv, aud, exp, jws });
|
|
55
|
+
const issued = await app.recordIssued(cap);
|
|
56
|
+
await sendSync(app, { outgoing: [{ inv, aud, exp, jws }], capsIssued: [issued], ...(opts.extraSync ?? {}) });
|
|
57
|
+
return { jws, inv, aud, exp, uses, cap };
|
|
58
|
+
}
|
|
59
|
+
export async function invite(app, opts) {
|
|
60
|
+
const aud = opts.to ? await app.resolveUser(opts.to) : "*";
|
|
61
|
+
if (aud === app.userId)
|
|
62
|
+
throw new CliError("usage", "you can't invite yourself (link a device with `p2p link start`)");
|
|
63
|
+
const uses = opts.uses ?? (aud === "*" ? 5 : 3);
|
|
64
|
+
if (!Number.isSafeInteger(uses) || uses < 1 || uses > 1000)
|
|
65
|
+
throw new CliError("usage", "--uses must be 1..1000");
|
|
66
|
+
// An unfriend queued for us must be known before the invite is dated (mintInvite), or a
|
|
67
|
+
// re-friend right after it would be refused. Best effort: an invite works offline too.
|
|
68
|
+
await app.connectAndDrain().catch(() => undefined);
|
|
69
|
+
const m = await mintInvite(app, { aud, uses, ttlSec: Math.round((opts.ttlDays ?? 14) * 86_400) });
|
|
70
|
+
const out = { invite: { inv: m.inv, aud, exp: m.exp, uses }, link: inviteLink(m.jws), web: inviteLink(m.jws, { web: true }) };
|
|
71
|
+
if (aud !== "*" && (await app.view(aud))) {
|
|
72
|
+
try {
|
|
73
|
+
out.delivered = await app.deliver(aud, "contact", { own: app.userId, sid: "~contact" }, { text: m.jws });
|
|
74
|
+
}
|
|
75
|
+
catch (e) {
|
|
76
|
+
app.warn(`couldn't deliver the invite directly: ${e.message}`);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
81
|
+
/** Accepts an invite (a link, or the JWS of a held invite). */
|
|
82
|
+
/** The relays an invite names, unverified (a parse-time look): its `relays`, its bundled document's, its cap's. */
|
|
83
|
+
export function inviteRelays(jws) {
|
|
84
|
+
const payload = (j) => {
|
|
85
|
+
try {
|
|
86
|
+
const v = JSON.parse(Buffer.from(j.split(".")[1] ?? "", "base64url").toString("utf8"));
|
|
87
|
+
return typeof v === "object" && v !== null ? v : {};
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
return {};
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
const strs = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === "string") : []);
|
|
94
|
+
const p = payload(jws);
|
|
95
|
+
const out = strs(p.relays);
|
|
96
|
+
if (typeof p.doc === "string") {
|
|
97
|
+
try {
|
|
98
|
+
out.push(...peekIdentityDoc(p.doc).relays);
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
// checked properly later
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (typeof p.cap === "string")
|
|
105
|
+
out.push(...strs(payload(p.cap).relays));
|
|
106
|
+
return out;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* `p2p accept <link>`, before accept(): a link the person pasted, from anyone. The relays it names (its own list, its
|
|
110
|
+
* bundled document's, its cap's) are dialed to check it, so one on a loopback, link-local or private
|
|
111
|
+
* address is refused unless opted in, literally and where its name resolves (App.guardRelays).
|
|
112
|
+
* Invites that arrived otherwise (held, a rotation, the TUI) go to accept() as they are.
|
|
113
|
+
*/
|
|
114
|
+
export async function guardInviteLink(app, input, opts = {}) {
|
|
115
|
+
let jws;
|
|
116
|
+
try {
|
|
117
|
+
jws = input.includes("://") ? parseInviteLink(input) : input.trim();
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
return; // not a link: accept() says so
|
|
121
|
+
}
|
|
122
|
+
await guardForeignRelays(app, inviteRelays(jws), "invite", opts.allowPrivateRelay || app.env.P2P_ALLOW_PRIVATE_RELAY === "1");
|
|
123
|
+
}
|
|
124
|
+
/** Refuses private relays someone else named (literal hosts, and names resolving to private addresses), then guards their connections. */
|
|
125
|
+
export async function guardForeignRelays(app, input, what, allow, opts = {}) {
|
|
126
|
+
if (allow)
|
|
127
|
+
return;
|
|
128
|
+
// The user's own relays are theirs to choose (a team relay on Tailscale or a LAN): left out, as guardedLookup leaves them.
|
|
129
|
+
const relays = input.filter((r) => !isOwnRelay(r, app.self?.relays ?? []));
|
|
130
|
+
refusePrivateRelays(relays, what, false, opts);
|
|
131
|
+
await refusePrivateResolved(relays.map((r) => {
|
|
132
|
+
try {
|
|
133
|
+
return { relay: r, dial: app.transport(r).ws };
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
return { relay: r, dial: r };
|
|
137
|
+
}
|
|
138
|
+
}), what, opts);
|
|
139
|
+
app.guardRelays(relays);
|
|
140
|
+
}
|
|
141
|
+
export async function accept(app, input) {
|
|
142
|
+
let jws;
|
|
143
|
+
try {
|
|
144
|
+
jws = input.includes("://") ? parseInviteLink(input) : input.trim();
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
throw new CliError("usage", "that is not an invite link (p2p://invite/… or https://ix-infra.com/p2p/i#…)");
|
|
148
|
+
}
|
|
149
|
+
await app.connectAndDrain();
|
|
150
|
+
// Structure and signature with whatever we know (the bundled document may stand in), to fail fast...
|
|
151
|
+
const first = await verifyInviteV3(jws, app.signerCtx());
|
|
152
|
+
if (first.iss === app.userId)
|
|
153
|
+
throw new CliError("usage", "that is your own invite");
|
|
154
|
+
if (await app.store.isBlocked(first.iss))
|
|
155
|
+
throw new CliError("blocked", "you blocked the inviter; `p2p unblock` first");
|
|
156
|
+
await refuseIfUnfriendedAfter(app, first);
|
|
157
|
+
// ...then, before acting on it (pre-release review M1), the inviter's head from its relays, and the invite against that alone.
|
|
158
|
+
let inv;
|
|
159
|
+
try {
|
|
160
|
+
inv = await reverifyInviteForApproval(app.store, jws, app.fetcher());
|
|
161
|
+
}
|
|
162
|
+
catch (e) {
|
|
163
|
+
if (e instanceof P2PError && (e.reason === "identity-unknown" || e.reason === "chain-broken")) {
|
|
164
|
+
throw new CliError("unknown_user", `couldn't confirm the inviter's identity document on the relays the invite names (${e.message})`);
|
|
165
|
+
}
|
|
166
|
+
throw e;
|
|
167
|
+
}
|
|
168
|
+
const head = (await app.ownView()).head;
|
|
169
|
+
const friendCap = createCap(app.device, app.keys.cert, { purpose: "friend", sub: inv.iss, relays: app.relays });
|
|
170
|
+
const acc = createAcceptV3(app.signer(), jws, { cap: friendCap, doc: head.jws });
|
|
171
|
+
const f = await verifyFriendshipV3({ invite: jws, accept: acc }, app.signerCtx());
|
|
172
|
+
await recordFriendshipV3(app.store, f);
|
|
173
|
+
const issued = await app.recordIssued(friendCap);
|
|
174
|
+
if (inv.contactCap) {
|
|
175
|
+
const c = inv.contactCap;
|
|
176
|
+
await app.store.addCapHeld({ capid: c.capid, iss: c.iss, sub: c.sub, relays: c.relays, kinds: c.kinds, exp: c.exp, jws: c.jws });
|
|
177
|
+
}
|
|
178
|
+
const delivered = await app.deliver(inv.iss, "contact", { own: app.userId, sid: "~contact" }, { text: acc }, { extraCaps: inv.cap ? [inv.cap] : [] });
|
|
179
|
+
await dropHeld(app, (h) => h.invite === jws);
|
|
180
|
+
await sendSync(app, { friendships: [{ invite: jws, accept: acc }], capsIssued: [issued], ...(inv.contactCap ? { capsHeld: [inv.contactCap.jws] } : {}) });
|
|
181
|
+
const friend = { userId: inv.iss, address: await app.addressOf(inv.iss) };
|
|
182
|
+
if (delivered.relays.length === 0) {
|
|
183
|
+
throw new CliError("undelivered", `friendship recorded, but the accept was delivered via 0 relays: ${inv.iss} won't know yet (run accept again later)`, {
|
|
184
|
+
friend,
|
|
185
|
+
delivered,
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
return { friend, delivered };
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Refuses, before anything is accepted or sent, an invite issued at or before an unfriend
|
|
192
|
+
* between its issuer and us: the friendship it makes would be ended at once, on every client
|
|
193
|
+
* (core unfriendApplies). That happens when we re-friend within the unfriend's second, or when
|
|
194
|
+
* the unfriender's clock is ahead of the inviter's and the inviter didn't yet hold the unfriend.
|
|
195
|
+
*/
|
|
196
|
+
export async function refuseIfUnfriendedAfter(app, invite) {
|
|
197
|
+
const u = unfriendEndingInvite(invite, app.userId, await app.store.listUnfriends());
|
|
198
|
+
if (!u)
|
|
199
|
+
return;
|
|
200
|
+
const who = await app.addressOf(invite.iss);
|
|
201
|
+
const skew = u.iat - invite.iat;
|
|
202
|
+
throw new CliError("invite_predates_unfriend", `this invite from ${who} is dated ${skew === 0 ? "in the same second as" : `${skew}s before`} the unfriend between you, so it can't re-friend you (one of your clocks may be off: \`p2p doctor\`). Nothing was accepted: ask ${who} for a new invite`, { inviter: invite.iss, unfriendIat: u.iat, inviteIat: invite.iat });
|
|
203
|
+
}
|
|
204
|
+
/** `contact` envelopes (§4.3): invites are held; accepts, unfriends and cap grants are applied. */
|
|
205
|
+
export async function onContact(app, env, r) {
|
|
206
|
+
const c = r.contact;
|
|
207
|
+
const from = await fromOf(app, r);
|
|
208
|
+
const at = r.envelope.ts;
|
|
209
|
+
switch (c.type) {
|
|
210
|
+
case "invite": {
|
|
211
|
+
const item = withHeldId({ type: "invite", from: c.invite.iss, at, invite: c.invite.jws });
|
|
212
|
+
await hold(app, item);
|
|
213
|
+
return [makeEvent(env, "p2p.held", at, { from, held: { id: item.id, type: item.type, exp: c.invite.exp } })];
|
|
214
|
+
}
|
|
215
|
+
case "accept": {
|
|
216
|
+
let f = c.friendship;
|
|
217
|
+
// P4: a revoked code's invite is refused, even when someone took the code before the revoke.
|
|
218
|
+
const code = await codeByInv(app, f.inv);
|
|
219
|
+
if (code?.status === "revoked") {
|
|
220
|
+
app.io.err(`refused ${from.address}: they used your revoked code ${codeHint(code.code)}`);
|
|
221
|
+
return [makeEvent(env, "p2p.invite-taken", at, { from, invite: { inv: f.inv }, revoked: true })];
|
|
222
|
+
}
|
|
223
|
+
try {
|
|
224
|
+
// A first-time invitee's document is only provisional: refresh it from the relays and re-verify (review N1).
|
|
225
|
+
if (f.provisional)
|
|
226
|
+
f = await reverifyFriendshipForApproval(app.store, f.proof, app.fetcher(), { self: app.userId });
|
|
227
|
+
await recordFriendshipV3(app.store, f);
|
|
228
|
+
}
|
|
229
|
+
catch (e) {
|
|
230
|
+
if (e instanceof P2PError && e.reason === "invite-already-bound") {
|
|
231
|
+
return [makeEvent(env, "p2p.invite-taken", at, { from, invite: { inv: f.inv } })];
|
|
232
|
+
}
|
|
233
|
+
if (e instanceof P2PError && e.reason === "unfriended") {
|
|
234
|
+
// Their client refuses this too (refuseIfUnfriendedAfter): a newer invite works.
|
|
235
|
+
app.io.err(`refused ${from.address}'s accept: your invite is dated at or before an unfriend between you (a clock may be off); send a new invite`);
|
|
236
|
+
return [makeEvent(env, "p2p.invite-taken", at, { from, invite: { inv: f.inv }, unfriended: true })];
|
|
237
|
+
}
|
|
238
|
+
throw e;
|
|
239
|
+
}
|
|
240
|
+
if (f.inviteeCap) {
|
|
241
|
+
const k = f.inviteeCap;
|
|
242
|
+
await app.store.addCapHeld({ capid: k.capid, iss: k.iss, sub: k.sub, relays: k.relays, kinds: k.kinds, exp: k.exp, jws: k.jws });
|
|
243
|
+
}
|
|
244
|
+
// §5.3: our friend cap goes back as a contact grant now the accept is recorded.
|
|
245
|
+
const mine = createCap(app.device, app.keys.cert, { purpose: "friend", sub: f.invitee, relays: app.relays });
|
|
246
|
+
const issued = await app.recordIssued(mine);
|
|
247
|
+
try {
|
|
248
|
+
await app.deliver(f.invitee, "contact", { own: app.userId, sid: "~contact" }, { text: mine });
|
|
249
|
+
}
|
|
250
|
+
catch (e) {
|
|
251
|
+
// A short network drop must not lose the grant (they could never message us): the accept
|
|
252
|
+
// is handled again on its redelivery, within the attempt limit (inbound.ts, review M-A).
|
|
253
|
+
if (isTransient(e))
|
|
254
|
+
throw e;
|
|
255
|
+
app.io.err(`couldn't send your cap to ${from.address}: ${e.message}`);
|
|
256
|
+
}
|
|
257
|
+
await sendSync(app, { friendships: [f.proof], capsIssued: [issued], ...(f.inviteeCap ? { capsHeld: [f.inviteeCap.jws] } : {}) });
|
|
258
|
+
const events = [makeEvent(env, "p2p.friend", at, { from, friend: { userId: f.invitee, address: from.address, inv: f.inv } })];
|
|
259
|
+
// P4: one of our short codes. Issuing it was our consent: finish our side (the circle), and tell the user.
|
|
260
|
+
if (code?.status === "open" && f.inviter === app.userId)
|
|
261
|
+
events.push(...(await onCodeRedeemed(app, env, at, from, code, f.invitee)));
|
|
262
|
+
return events;
|
|
263
|
+
}
|
|
264
|
+
case "unfriend": {
|
|
265
|
+
const u = c.unfriend;
|
|
266
|
+
await app.store.addUnfriend({ iss: u.iss, peer: u.peer, inv: u.inv, iat: u.iat, jws: u.jws });
|
|
267
|
+
await afterUnfriend(app, u.iss);
|
|
268
|
+
return [makeEvent(env, "p2p.unfriend", at, { from, peer: u.iss })];
|
|
269
|
+
}
|
|
270
|
+
case "cap": {
|
|
271
|
+
const k = c.cap;
|
|
272
|
+
await app.store.addCapHeld({ capid: k.capid, iss: k.iss, sub: k.sub, relays: k.relays, kinds: k.kinds, exp: k.exp, jws: k.jws });
|
|
273
|
+
await sendSync(app, { capsHeld: [k.jws] });
|
|
274
|
+
return [makeEvent(env, "p2p.contact", at, { from, what: "cap", relays: k.relays, exp: k.exp })];
|
|
275
|
+
}
|
|
276
|
+
case "rotation":
|
|
277
|
+
// §2.8: "<friend> moved to a new key", held for the user's approval.
|
|
278
|
+
return onRotationContact(app, env, at, from, c.rotation, c.invite);
|
|
279
|
+
case "circle-invite": {
|
|
280
|
+
const chain = c.chain ? c.chain.versions.map((v) => v.jws) : [c.head];
|
|
281
|
+
if (await recordJoinAnswer(app, r.envelope.from, chain, [])) {
|
|
282
|
+
return [makeEvent(env, "p2p.circle", at, { from, event: "join-answer", cid: c.chain?.cid })];
|
|
283
|
+
}
|
|
284
|
+
const head = parseCircleVersion(c.head);
|
|
285
|
+
const item = withHeldId({ type: "circle-invite", from: r.envelope.from, at, head: c.head, chain, cid: head.cid });
|
|
286
|
+
await hold(app, item);
|
|
287
|
+
return [makeEvent(env, "p2p.held", at, { from, held: { id: item.id, type: item.type, cid: head.cid } })];
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
/** The `unfriend` kind (§4.3): the core already stored it; take back our caps. */
|
|
292
|
+
export async function onUnfriendKind(app, env, r) {
|
|
293
|
+
await afterUnfriend(app, r.envelope.from);
|
|
294
|
+
return [makeEvent(env, "p2p.unfriend", r.envelope.ts, { from: await fromOf(app, r), peer: r.envelope.from })];
|
|
295
|
+
}
|
|
296
|
+
async function afterUnfriend(app, peer) {
|
|
297
|
+
const caps = await capsToRevokeOnUnfriend(app.store, peer);
|
|
298
|
+
await app.revokeCaps(caps).catch(() => 0);
|
|
299
|
+
await app.store.removeCapsHeld((c) => c.iss === peer);
|
|
300
|
+
}
|
|
301
|
+
export async function unfriend(app, who) {
|
|
302
|
+
const peer = await app.resolveUser(who);
|
|
303
|
+
// Handle what's queued first: it was sent while we were still friends.
|
|
304
|
+
await app.connectAndDrain();
|
|
305
|
+
const fs = (await app.store.listFriendships()).filter((f) => (f.inviter === peer && f.invitee === app.userId) || (f.invitee === peer && f.inviter === app.userId));
|
|
306
|
+
if (fs.length === 0)
|
|
307
|
+
throw new CliError("not_friends", `${await app.addressOf(peer)} is not a friend`);
|
|
308
|
+
const ctx = app.signerCtx();
|
|
309
|
+
const delivered = [];
|
|
310
|
+
const jwsList = [];
|
|
311
|
+
for (const inv of new Set(fs.map((f) => f.inv))) {
|
|
312
|
+
const j = createUnfriendV3(app.signer(), { peer, inv });
|
|
313
|
+
const u = await verifyUnfriendV3(j, ctx);
|
|
314
|
+
await app.store.addUnfriend({ iss: u.iss, peer: u.peer, inv: u.inv, iat: u.iat, jws: j });
|
|
315
|
+
jwsList.push(j);
|
|
316
|
+
try {
|
|
317
|
+
delivered.push(await app.deliver(peer, "contact", { own: app.userId, sid: "~contact" }, { text: j }));
|
|
318
|
+
}
|
|
319
|
+
catch (e) {
|
|
320
|
+
app.warn(`couldn't tell ${await app.addressOf(peer)}: ${e.message}`);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
const caps = await capsToRevokeOnUnfriend(app.store, peer);
|
|
324
|
+
const revoked = await app.revokeCaps(caps);
|
|
325
|
+
await app.store.removeCapsHeld((c) => c.iss === peer);
|
|
326
|
+
await sendSync(app, { unfriends: jwsList });
|
|
327
|
+
return { unfriended: peer, address: await app.addressOf(peer), delivered, revoked };
|
|
328
|
+
}
|
|
329
|
+
export async function block(app, who) {
|
|
330
|
+
const u = await app.resolveUser(who);
|
|
331
|
+
if (u === app.userId)
|
|
332
|
+
throw new CliError("usage", "you can't block yourself");
|
|
333
|
+
const pool = await app.connect({ allowNone: true });
|
|
334
|
+
await pool.drain(app.tun.drainQuietMs, app.tun.drainMaxMs);
|
|
335
|
+
const caps = await blockUser(app.store, u);
|
|
336
|
+
// Their copy of our circle join cap must stop working too: re-key our joins (a pre-release live test).
|
|
337
|
+
const rekeyed = await rekeyJoinsExcluding(app, u);
|
|
338
|
+
const revoked = await app.revokeCaps(caps);
|
|
339
|
+
await dropHeld(app, (h) => h.from === u);
|
|
340
|
+
await sendSync(app, { blocks: [u] });
|
|
341
|
+
return { blocked: u, address: await app.addressOf(u), revoked: revoked + rekeyed.length, rekeyedCircles: rekeyed };
|
|
342
|
+
}
|
|
343
|
+
export async function unblock(app, who) {
|
|
344
|
+
const u = await app.resolveUser(who);
|
|
345
|
+
await app.store.removeBlock(u);
|
|
346
|
+
await sendSync(app, { unblocks: [u] }).catch(() => 0);
|
|
347
|
+
return { unblocked: u, address: await app.addressOf(u) };
|
|
348
|
+
}
|
|
349
|
+
export async function petname(app, who, name) {
|
|
350
|
+
const u = await app.resolveUser(who);
|
|
351
|
+
try {
|
|
352
|
+
await app.store.setPetname(u, name);
|
|
353
|
+
}
|
|
354
|
+
catch (e) {
|
|
355
|
+
throw new CliError("usage", e.message);
|
|
356
|
+
}
|
|
357
|
+
await sendSync(app, { petnames: { [u]: name ?? null } }).catch(() => 0);
|
|
358
|
+
return { userId: u, petname: (await app.store.getPetname(u)) ?? null, address: await app.addressOf(u) };
|
|
359
|
+
}
|
|
360
|
+
export async function friends(app) {
|
|
361
|
+
const live = await liveFriendshipsV3(app.store, app.signerCtx());
|
|
362
|
+
const unfriends = await app.store.listUnfriends();
|
|
363
|
+
const rows = new Map();
|
|
364
|
+
for (const f of live) {
|
|
365
|
+
if (unfriends.some((u) => unfriendApplies(f, u)))
|
|
366
|
+
continue;
|
|
367
|
+
const other = f.inviter === app.userId ? f.invitee : f.inviter;
|
|
368
|
+
if (rows.has(other))
|
|
369
|
+
continue;
|
|
370
|
+
const caps = await app.capsFor(other, "msg");
|
|
371
|
+
rows.set(other, { userId: other, address: await app.addressOf(other), since: f.iat, direction: f.inviter === app.userId ? "outgoing" : "incoming", canMessage: caps.size > 0 });
|
|
372
|
+
}
|
|
373
|
+
const bound = new Set((await app.store.listFriendships()).map((f) => f.inv));
|
|
374
|
+
const now = nowSec();
|
|
375
|
+
const outgoing = (await listOutgoing(app)).filter((o) => o.exp > now && !bound.has(o.inv)).map((o) => ({ inv: o.inv, aud: o.aud, exp: o.exp }));
|
|
376
|
+
const held = ((await app.state.get("held")) ?? []).length;
|
|
377
|
+
const blocked = await Promise.all((await app.store.listBlocks()).map(async (b) => ({ userId: b.userId, address: await app.addressOf(b.userId) })));
|
|
378
|
+
return { friends: [...rows.values()], invites: { outgoing, held }, blocked };
|
|
379
|
+
}
|
|
380
|
+
// ---------------------------------------------------------------------------
|
|
381
|
+
// Held items (§3.1, §3.3)
|
|
382
|
+
const HELD_PREFIX = { invite: "i", "circle-invite": "c", "circle-join": "j", rotation: "r", "rotation-join": "s", "rotation-follow": "f", "rotation-dispute": "d" };
|
|
383
|
+
/** Why a held item waits, in words (rotation items carry these, §2.8). */
|
|
384
|
+
const REASON_TEXT = {
|
|
385
|
+
conflict: "conflict: more than one rotation from this identity",
|
|
386
|
+
"previously-removed": "previously removed from this circle",
|
|
387
|
+
"not-final-yet": "their old identity hasn't published this move yet",
|
|
388
|
+
"held-by-policy": "you hold changes to this circle for approval",
|
|
389
|
+
"not-member": "their old identity isn't a member now",
|
|
390
|
+
blocked: "blocked",
|
|
391
|
+
};
|
|
392
|
+
/** Minimum length of an id prefix `held approve|decline` accepts. */
|
|
393
|
+
export const HELD_ID_MIN_PREFIX = 8;
|
|
394
|
+
/**
|
|
395
|
+
* A held item's id: a type letter and 16 b32 characters (80 bits) of
|
|
396
|
+
* SHA-256 over the whole held object (everything but when it arrived), so no
|
|
397
|
+
* peer can grind an item that collides with another.
|
|
398
|
+
*/
|
|
399
|
+
export function withHeldId(item) {
|
|
400
|
+
const { at: _at, ...rest } = item;
|
|
401
|
+
const canonical = JSON.stringify(Object.keys(rest).sort().map((k) => [k, rest[k]]));
|
|
402
|
+
return { ...item, id: `${HELD_PREFIX[item.type]}${b32Encode(sha256(new TextEncoder().encode(canonical))).slice(0, 16)}` };
|
|
403
|
+
}
|
|
404
|
+
export async function hold(app, item) {
|
|
405
|
+
await app.state.update("held", (cur = []) => (cur.some((h) => h.id === item.id) ? { result: undefined } : { next: [...cur, item], result: undefined }));
|
|
406
|
+
}
|
|
407
|
+
export async function dropHeld(app, pred) {
|
|
408
|
+
const gone = await app.state.update("held", (cur = []) => {
|
|
409
|
+
const out = cur.filter(pred);
|
|
410
|
+
return out.length === 0 ? { result: [] } : { next: cur.filter((h) => !pred(h)), result: out };
|
|
411
|
+
});
|
|
412
|
+
// A dropped rotation of our own identity takes its (secret) link code with it.
|
|
413
|
+
const follows = gone.filter((h) => h.type === "rotation-follow").map((h) => h.id);
|
|
414
|
+
if (follows.length > 0) {
|
|
415
|
+
await app.state.update("follows", (cur = {}) => {
|
|
416
|
+
const next = { ...cur };
|
|
417
|
+
for (const id of follows)
|
|
418
|
+
delete next[id];
|
|
419
|
+
return { next, result: undefined };
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
return gone;
|
|
423
|
+
}
|
|
424
|
+
export async function listHeld(app) {
|
|
425
|
+
const list = (await app.state.get("held")) ?? [];
|
|
426
|
+
return Promise.all(list.map(async (h) => {
|
|
427
|
+
let summary = "";
|
|
428
|
+
let extra = {};
|
|
429
|
+
if (h.type === "rotation-dispute") {
|
|
430
|
+
// pre-release re-review N1: an approved move, now contested. Keep one, or neither.
|
|
431
|
+
const oldAddress = h.old ? await app.addressOf(h.old) : "?";
|
|
432
|
+
const choices = await Promise.all((h.candidates ?? []).map(async (u) => ({ userId: u, address: await app.addressOf(u) })));
|
|
433
|
+
extra = { oldAddress, choices };
|
|
434
|
+
summary = `CONTESTED: more than one new key claims to be ${oldAddress} (${choices.map((c) => c.address).join(", ")}); the one you approved is suspended. Confirm out of band which is really them, then \`p2p identity dispute ${h.id} --keep <userId>\` or \`--neither\``;
|
|
435
|
+
}
|
|
436
|
+
else if (h.type === "rotation-follow") {
|
|
437
|
+
// Never followed by itself (pre-release review H2): the user says so, on this device.
|
|
438
|
+
const by = h.deviceLabel ? `your device "${h.deviceLabel}" (${h.device})` : `your device ${h.device ?? "?"}`;
|
|
439
|
+
summary = `your identity is moving to a new key (${h.newFingerprint ?? "?"}), started by ${by}: follow it with \`p2p identity follow ${h.id}\` only if you started it; if not, contest it from a key-holding device`;
|
|
440
|
+
}
|
|
441
|
+
else if (h.type === "rotation" || h.type === "rotation-join") {
|
|
442
|
+
// §2.8: the old address is shown (petname first), and whether its own document names this move.
|
|
443
|
+
const oldAddress = h.old ? await app.addressOf(h.old) : "?";
|
|
444
|
+
// The old identity's own (relay-served, self-certifying) final version names this same move.
|
|
445
|
+
const inDoc = h.old && h.rotation ? ((await app.view(h.old))?.rotations ?? []).some((s) => s.old === h.rotation.old && s.new === h.rotation.new) : false;
|
|
446
|
+
extra = { oldAddress, confirmedByDocument: inDoc };
|
|
447
|
+
if (h.type === "rotation")
|
|
448
|
+
summary = `${oldAddress} moved to a new key`;
|
|
449
|
+
else {
|
|
450
|
+
const name = h.head ? circleDisplayName(parseCircleVersion(h.head)) : h.cid;
|
|
451
|
+
summary =
|
|
452
|
+
h.reason === "admin"
|
|
453
|
+
? `${oldAddress} moved to a new key and was an admin of circle "${name}" (${h.cid}): approve to make the new key an admin too`
|
|
454
|
+
: `${oldAddress} moved to a new key and asks to take their place in circle "${name}" (${h.cid})`;
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
else if (h.type === "invite")
|
|
458
|
+
summary = "friend invite";
|
|
459
|
+
else if (h.head) {
|
|
460
|
+
const v = parseCircleVersion(h.head);
|
|
461
|
+
summary = `${h.type === "circle-join" ? "join request for" : "invite to"} circle "${circleDisplayName(v)}" (${v.cid})`;
|
|
462
|
+
}
|
|
463
|
+
else if (h.cid)
|
|
464
|
+
summary = `join request for circle ${h.cid}`;
|
|
465
|
+
if (h.reason && h.reason !== "admin")
|
|
466
|
+
summary += ` [${REASON_TEXT[h.reason] ?? h.reason}]`;
|
|
467
|
+
// Held objects carry signed statements and invites, never secrets; the list shows them as data.
|
|
468
|
+
return { ...h, address: await app.addressOf(h.from), summary, ...extra };
|
|
469
|
+
}));
|
|
470
|
+
}
|
|
471
|
+
/** An exact id, or a unique prefix of at least 8 characters; ambiguous prefixes are refused. */
|
|
472
|
+
export async function getHeld(app, id) {
|
|
473
|
+
const list = (await app.state.get("held")) ?? [];
|
|
474
|
+
const exact = list.find((x) => x.id === id);
|
|
475
|
+
if (exact)
|
|
476
|
+
return exact;
|
|
477
|
+
if (id.length < HELD_ID_MIN_PREFIX)
|
|
478
|
+
throw new CliError("not_found", `no held item ${id} (give the full id, or at least ${HELD_ID_MIN_PREFIX} characters of it; see \`p2p held\`)`);
|
|
479
|
+
const hits = list.filter((x) => x.id.startsWith(id));
|
|
480
|
+
if (hits.length > 1)
|
|
481
|
+
throw new CliError("ambiguous", `${id} matches ${hits.length} held items: give more of the id`, { candidates: hits.map((h) => h.id) });
|
|
482
|
+
if (hits.length === 0)
|
|
483
|
+
throw new CliError("not_found", `no held item ${id} (see \`p2p held\`)`);
|
|
484
|
+
return hits[0];
|
|
485
|
+
}
|