@needmoretruth/nmts-cli 0.46.0 → 0.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/AGENTS.md +8 -8
  2. package/CHANGELOG.md +18 -1
  3. package/README.ko.md +1 -1
  4. package/README.md +19 -11
  5. package/dist/arg-options.d.ts +11 -1
  6. package/dist/args.js +7 -1
  7. package/dist/artifact-about.d.ts +1 -1
  8. package/dist/autonomy.js +3 -3
  9. package/dist/commands/handover.d.ts +2 -0
  10. package/dist/commands/handover.js +65 -17
  11. package/dist/commands/link.d.ts +12 -0
  12. package/dist/commands/link.js +121 -0
  13. package/dist/commands/public-code-manage.d.ts +24 -0
  14. package/dist/commands/public-code-manage.js +217 -0
  15. package/dist/commands/public-code.d.ts +7 -2
  16. package/dist/commands/public-code.js +104 -55
  17. package/dist/commands/receive.js +11 -5
  18. package/dist/commands/share-dispatch.js +14 -1
  19. package/dist/commands/share.d.ts +2 -0
  20. package/dist/commands/share.js +45 -35
  21. package/dist/commands/shares-sent.js +8 -3
  22. package/dist/crypto-surface.d.ts +27 -0
  23. package/dist/crypto-surface.js +10 -0
  24. package/dist/crypto.d.ts +5 -0
  25. package/dist/crypto.js +5 -0
  26. package/dist/handover-codes.d.ts +25 -0
  27. package/dist/handover-codes.js +106 -0
  28. package/dist/handover.d.ts +21 -3
  29. package/dist/handover.js +47 -29
  30. package/dist/help-options.js +9 -2
  31. package/dist/help.js +9 -1
  32. package/dist/links.d.ts +58 -0
  33. package/dist/links.js +206 -0
  34. package/dist/main.js +3 -2
  35. package/dist/mcp-tools/reads.js +20 -6
  36. package/dist/mcp-tools/share.js +47 -1
  37. package/dist/mcp-tools/tiers.js +16 -1
  38. package/dist/portable.d.ts +8 -0
  39. package/dist/portable.js +8 -0
  40. package/dist/product.d.ts +1 -1
  41. package/dist/product.js +1 -1
  42. package/dist/public-code-activity.d.ts +35 -0
  43. package/dist/public-code-activity.js +88 -0
  44. package/dist/public-code-refusals.d.ts +25 -0
  45. package/dist/public-code-refusals.js +87 -0
  46. package/dist/public-codes.d.ts +76 -0
  47. package/dist/public-codes.js +182 -0
  48. package/dist/risk.d.ts +25 -1
  49. package/dist/risk.js +32 -1
  50. package/dist/share-codes.d.ts +40 -0
  51. package/dist/share-codes.js +151 -0
  52. package/dist/share.d.ts +34 -0
  53. package/dist/share.js +53 -12
  54. package/dist/shared/lib/share/public-link.d.ts +41 -0
  55. package/dist/shared/lib/share/public-link.js +107 -0
  56. package/docs/commands/handover.md +17 -1
  57. package/docs/commands/link.md +27 -0
  58. package/docs/commands/mcp.md +2 -1
  59. package/docs/commands/public-code.md +21 -9
  60. package/docs/commands/share.md +6 -3
  61. package/package.json +1 -1
  62. package/server.json +2 -2
  63. package/vendor/nmts-crypto/nmts_crypto_wasm.d.ts +91 -5
  64. package/vendor/nmts-crypto/nmts_crypto_wasm.js +259 -4
  65. package/vendor/nmts-crypto/nmts_crypto_wasm_bg.wasm +0 -0
  66. package/vendor/nmts-crypto/nmts_crypto_wasm_bg.wasm.d.ts +11 -1
@@ -0,0 +1,217 @@
1
+ // `nmts public-code list · new · revoke` — the account's numbered public codes.
2
+ //
3
+ // ⛔ WHAT IS PRINTED IS WHAT THIS KEY DERIVES, CHECKED AGAINST WHAT THE SERVER HOLDS. Each code is
4
+ // derived here at its number and compared with the server's address; a difference stops the
5
+ // command with the bigger fact (`differentCode`), because a person gives these out and a code the
6
+ // key does not make is somebody else's.
7
+ //
8
+ // ⛔ REVOKING NEVER HAPPENS WITHOUT A YES. `revoke` and `new --replace` are the one high act here
9
+ // (`risk.ts` "public-code.revoke"); the question names the code, and without a terminal it is
10
+ // `--yes` or nothing.
11
+ //
12
+ // ⚠ THE CEILINGS ARE THE SERVER'S. Three live codes, one for a Platform user, and a daily number
13
+ // that is smaller for an agent: this prints what the server answered and does not keep a copy.
14
+ import { toBase64Url } from "../bytes.js";
15
+ import { loadCrypto } from "../crypto.js";
16
+ import { NmtsError } from "../errors.js";
17
+ import { BINARY_NAME } from "../product.js";
18
+ import { promptLine, stdinIsATerminal } from "../prompt.js";
19
+ import { codeActivity } from "../public-code-activity.js";
20
+ import { codeNumber, differentCode, lastLiveCode, notLiveCode, publicCodeRefusal } from "../public-code-refusals.js";
21
+ import { defaultCode, liveCodes, nextCodeIndex, publishCode, readPublicCodes, revokeCode, } from "../public-codes.js";
22
+ import { openSession } from "../session.js";
23
+ import { shareKeyRing, shareKeysAt } from "../share-codes.js";
24
+ /** The code this key derives at `row`'s number, as a person reads it — or `differentCode` when the server's differs. */
25
+ export function checkedDisplay(crypt, code, row) {
26
+ const keys = shareKeysAt(crypt, code, row.index);
27
+ try {
28
+ if (toBase64Url(keys.address) !== row.address)
29
+ throw differentCode();
30
+ return keys.display;
31
+ }
32
+ finally {
33
+ keys.wipe();
34
+ }
35
+ }
36
+ /** `checkedDisplay` for every row, from one ring — the key's derivation runs once, not once per row. */
37
+ function checkedDisplays(ring, rows) {
38
+ return new Map(rows.map((row) => {
39
+ const keys = ring.at(row.index);
40
+ if (toBase64Url(keys.address) !== row.address)
41
+ throw differentCode();
42
+ return [row.index, keys.display];
43
+ }));
44
+ }
45
+ /** The UTC day of an instant, `YYYY-MM-DD`; the text as sent when it is not one. */
46
+ function day(instant) {
47
+ const at = new Date(instant);
48
+ return Number.isNaN(at.getTime()) ? instant : at.toISOString().slice(0, 10);
49
+ }
50
+ function rowLine(row, display, isDefault) {
51
+ const counts = `sent ${row.sent} · received ${row.received} · messages ${row.support}`;
52
+ if (row.revokedAt !== null)
53
+ return `#${row.index} ${display} revoked ${day(row.revokedAt)} ${counts}`;
54
+ return `#${row.index} ${display}${isDefault ? " default" : ""} made ${day(row.createdAt)} ${counts}`;
55
+ }
56
+ function activityLines(activity) {
57
+ const out = [];
58
+ for (const s of activity?.sent ?? []) {
59
+ const what = s.path ?? `${s.itemId} (no longer in the file list)`;
60
+ const gone = s.recipientRevoked ? " · the recipient has revoked this code" : "";
61
+ out.push(` sent ${what} to ${s.recipient} ${day(s.createdAt)} share ${s.id}${gone}`);
62
+ }
63
+ for (const r of activity?.received ?? []) {
64
+ if (r.problem !== null) {
65
+ out.push(` received share ${r.id} (will not open: ${r.problem})`);
66
+ continue;
67
+ }
68
+ const gone = r.senderRevoked ? " · the sender has revoked this code" : "";
69
+ out.push(` received ${r.name ?? ""} from ${r.sender ?? ""} ${day(r.createdAt)} share ${r.id}${gone}`);
70
+ }
71
+ return out;
72
+ }
73
+ function sayer(options) {
74
+ return options.write ?? ((line) => process.stdout.write(`${line}\n`));
75
+ }
76
+ /** `nmts public-code list [--activity]` — every code, live ones first, and the two ceilings. */
77
+ export async function listCodes(options = {}) {
78
+ const say = sayer(options);
79
+ const session = await openSession({ server: options.server, network: options.network });
80
+ const crypt = await loadCrypto();
81
+ const door = { server: session.server, token: session.apiKey };
82
+ const list = await readPublicCodes(door.server, door.token);
83
+ const live = liveCodes(list);
84
+ const ordered = [...live, ...list.codes.filter((c) => c.revokedAt !== null)];
85
+ const ring = shareKeyRing(crypt, session.code);
86
+ let shown;
87
+ try {
88
+ shown = checkedDisplays(ring, ordered);
89
+ }
90
+ finally {
91
+ ring.wipe();
92
+ }
93
+ const def = defaultCode(list)?.index ?? null;
94
+ const activity = options.activity === true
95
+ ? await codeActivity(crypt, session.code, { ...door, accountId: session.accountId }, list)
96
+ : null;
97
+ if (options.json === true) {
98
+ const codes = ordered.map((r) => ({
99
+ index: r.index,
100
+ code: shown.get(r.index) ?? "",
101
+ raw: r.address,
102
+ default: r.index === def,
103
+ createdAt: r.createdAt,
104
+ revokedAt: r.revokedAt,
105
+ sent: r.sent,
106
+ received: r.received,
107
+ messages: r.support,
108
+ ...(activity === null ? {} : { activity: activity.get(r.index) ?? { sent: [], received: [] } }),
109
+ }));
110
+ say(JSON.stringify({ codes, live: live.length, liveMax: list.liveMax, madeToday: list.madeToday, dayCap: list.dayCap }));
111
+ return 0;
112
+ }
113
+ if (ordered.length === 0) {
114
+ say(`This account has no published public code yet.`);
115
+ say(``);
116
+ say(` ${BINARY_NAME} public-code --publish`);
117
+ return 0;
118
+ }
119
+ for (const r of ordered) {
120
+ say(rowLine(r, shown.get(r.index) ?? "", r.index === def));
121
+ if (activity !== null)
122
+ for (const line of activityLines(activity.get(r.index)))
123
+ say(line);
124
+ }
125
+ say(``);
126
+ say(`${live.length} of ${list.liveMax} live · ${list.madeToday} of ${list.dayCap} made today (UTC)`);
127
+ return 0;
128
+ }
129
+ /**
130
+ * The revoke question, put to a person — or, with nobody to put it to, the refusal that carries it.
131
+ * True when the answer is yes.
132
+ */
133
+ async function confirmRevoke(index, display, options, say) {
134
+ if (options.yes === true)
135
+ return true;
136
+ const question = `Revoke public code #${index} (${display})? Nobody can send to it again, and nobody can bring it ` +
137
+ `back. Files already received with it stay.`;
138
+ if (options.readLine === undefined && !stdinIsATerminal()) {
139
+ throw new NmtsError(question, {
140
+ exitCode: 5,
141
+ nextStep: "This needs the person's yes. If they say yes, run the same command with --yes. Nothing was done.",
142
+ });
143
+ }
144
+ const answer = (await (options.readLine ?? promptLine)(`${question} [y/N] `)).trim();
145
+ if (answer === "y" || answer === "Y")
146
+ return true;
147
+ say(`Nothing was revoked.`);
148
+ return false;
149
+ }
150
+ /** `nmts public-code new [--replace <n>]` — the next number, published; with --replace, that code revoked in the same request. */
151
+ export async function newCode(options = {}) {
152
+ const say = sayer(options);
153
+ const replace = options.replace === undefined ? undefined : codeNumber(options.replace, "--replace");
154
+ const session = await openSession({ server: options.server, network: options.network });
155
+ const crypt = await loadCrypto();
156
+ const door = { server: session.server, token: session.apiKey };
157
+ const list = await readPublicCodes(door.server, door.token);
158
+ let replaced = null;
159
+ if (replace !== undefined) {
160
+ const row = liveCodes(list).find((c) => c.index === replace);
161
+ if (row === undefined)
162
+ throw notLiveCode(replace);
163
+ replaced = checkedDisplay(crypt, session.code, row);
164
+ if (!(await confirmRevoke(replace, replaced, options, say)))
165
+ return 1;
166
+ }
167
+ let made;
168
+ try {
169
+ made = await publishCode(crypt, session.code, door, nextCodeIndex(list), replace);
170
+ }
171
+ catch (error) {
172
+ throw publicCodeRefusal(error, { liveMax: list.liveMax, dayCap: list.dayCap, replace: defaultCode(list)?.index });
173
+ }
174
+ if (options.json === true) {
175
+ say(JSON.stringify({ index: made.index, code: made.code, raw: made.address, revoked: replace ?? null }));
176
+ return 0;
177
+ }
178
+ say(`made public code #${made.index} ${made.code}`);
179
+ if (replace !== undefined)
180
+ say(`revoked #${replace} ${replaced ?? ""}`);
181
+ return 0;
182
+ }
183
+ /** `nmts public-code revoke <n>` — one way, and never the last live code. */
184
+ export async function revokeCodeCommand(operand, options = {}) {
185
+ const say = sayer(options);
186
+ const index = codeNumber(operand, "`public-code revoke`");
187
+ const session = await openSession({ server: options.server, network: options.network });
188
+ const crypt = await loadCrypto();
189
+ const door = { server: session.server, token: session.apiKey };
190
+ const list = await readPublicCodes(door.server, door.token);
191
+ const row = list.codes.find((c) => c.index === index);
192
+ if (row === undefined) {
193
+ throw new NmtsError(`This account has no public code #${index}.`, {
194
+ exitCode: 4,
195
+ nextStep: `\`${BINARY_NAME} public-code list\` shows its codes.`,
196
+ });
197
+ }
198
+ const display = checkedDisplay(crypt, session.code, row);
199
+ if (row.revokedAt === null) {
200
+ if (liveCodes(list).length <= 1)
201
+ throw lastLiveCode(index);
202
+ if (!(await confirmRevoke(index, display, options, say)))
203
+ return 1;
204
+ try {
205
+ await revokeCode(door, index);
206
+ }
207
+ catch (error) {
208
+ throw publicCodeRefusal(error, { replace: index });
209
+ }
210
+ }
211
+ if (options.json === true) {
212
+ say(JSON.stringify({ index, code: display, raw: row.address, revoked: true }));
213
+ return 0;
214
+ }
215
+ say(row.revokedAt === null ? `revoked public code #${index} ${display}` : `public code #${index} was already revoked on ${day(row.revokedAt)}`);
216
+ return 0;
217
+ }
@@ -1,10 +1,13 @@
1
+ import type { ParsedArgs } from "../args.ts";
1
2
  export interface PublicCodeOptions {
2
3
  server?: string | undefined;
3
4
  network?: string | undefined;
4
- /** Publish it, so other accounts can send to it. Permanent. */
5
+ /** Publish it, so other accounts can send to it. */
5
6
  publish?: boolean;
6
- /** `--save [file]`: write this account's public code file (NCF-3 §5.7). Asks the server nothing. */
7
+ /** `--save [file]`: write this account's public code file (NCF-3 §5.7) — the default code's. */
7
8
  save?: boolean;
9
+ /** `--save --as <n>`: the file for code number n instead, made on this machine alone. */
10
+ as?: string | undefined;
8
11
  /** The file `--save` writes; by default `nmts-public-code-<code>.nmtscode` here. */
9
12
  file?: string | undefined;
10
13
  /** Replace that file if it exists. */
@@ -12,4 +15,6 @@ export interface PublicCodeOptions {
12
15
  json?: boolean;
13
16
  write?: (line: string) => void;
14
17
  }
18
+ /** `nmts public-code [list|new|revoke]` and `nmts public-code --save [file]`, from the parsed command line. */
19
+ export declare function runPublicCode(args: ParsedArgs): Promise<number>;
15
20
  export declare function publicCode(options?: PublicCodeOptions): Promise<number>;
@@ -7,35 +7,61 @@
7
7
  // pasting into the other had two ways to be wrong about one value. Both are fixed here: one
8
8
  // name, and the same grouped form a person sees on the screen.
9
9
  //
10
+ // ⛔ ONE KEY, SEVERAL CODES. An account holds one to three live public codes,
11
+ // numbered from the one NMTS key; the bare command shows the DEFAULT — the lowest-numbered live
12
+ // one — and `list · new · revoke` (`public-code-manage.ts`) handle the rest. A published code
13
+ // never changes; what changes is which codes are live, and revoking one is one way.
14
+ //
10
15
  // ⛔ WHY PUBLISHING IS A SEPARATE STEP AND NOT SOMETHING THIS COMMAND JUST DOES. Sending a file
11
16
  // already publishes the sender's code as a side effect, because a share cannot exist without
12
17
  // one and the person has already decided to hand something over. RECEIVING is the other way
13
- // round: nothing has been decided yet, and the record is permanent. So the plain command reads,
14
- // says whether it can be sent to, and names the flag; `--publish` is the deliberate act.
18
+ // round: nothing has been decided yet. So the plain command reads, says whether it can be sent
19
+ // to, and names the flag; `--publish` is the deliberate act.
15
20
  //
16
- // ⛔ WHAT "PERMANENT" DOES AND DOES NOT MEAN HERE. The record cannot be withdrawn or replaced. It
17
- // is also not a choice: the code and the identity behind it are derived from the NMTS key,
18
- // so the same NMTS key produces the same bytes on any device, and the server refuses a
19
- // bundle whose claimed value is not the fingerprint of its own root. The only way to publish a
20
- // wrong one is to be holding a different NMTS key. That is worth saying plainly rather than
21
- // warning vaguely — a warning that cannot be acted on just teaches people to click through.
21
+ // ⛔ IT IS NOT A CHOICE. The code and the identity behind it are derived from the NMTS key, so the
22
+ // same key produces the same bytes at the same number on any device, and the server refuses a
23
+ // bundle whose claimed value is not the fingerprint of its own root.
22
24
  //
23
25
  // ⚠ IT IS NOT THE NMTS KEY. That one opens every file in the account and must never be given
24
26
  // to anybody; this one is meant to be given away, and on its own it opens nothing.
25
27
  import { writeFileSync } from "node:fs";
26
28
  import { resolve } from "node:path";
27
- import { request } from "../api.js";
28
29
  import { requireAccountCode } from "../code-access.js";
30
+ import { readCredentialsFile, resolveApiKey } from "../credentials.js";
29
31
  import { publicCodeFileText } from "../handover.js";
32
+ import { checkedKeys } from "../handover-codes.js";
30
33
  import { publicCodeFileName } from "../shared/lib/share/handover-format.js";
31
- import { NmtsError } from "../errors.js";
32
- import { isRecord } from "../guards.js";
33
34
  import { loadCrypto } from "../crypto.js";
35
+ import { NmtsError } from "../errors.js";
34
36
  import { BINARY_NAME } from "../product.js";
37
+ import { codeNumber, publicCodeRefusal } from "../public-code-refusals.js";
38
+ import { defaultCode, liveCodes, nextCodeIndex, publishCode, readPublicCodes } from "../public-codes.js";
39
+ import { resolveServer } from "../server.js";
35
40
  import { openSession } from "../session.js";
36
- import { shareKeysOf } from "../share.js";
37
- function b64(bytes) {
38
- return Buffer.from(bytes).toString("base64url");
41
+ import { shareKeysAt } from "../share-codes.js";
42
+ import { checkedDisplay } from "./public-code-manage.js";
43
+ /** `nmts public-code [list|new|revoke]` and `nmts public-code --save [file]`, from the parsed command line. */
44
+ export async function runPublicCode(args) {
45
+ const sub = args.operands[0] ?? "";
46
+ const common = { server: args.server, network: args.network, json: args.json };
47
+ // ⚠ WITH --save THE OPERAND IS THE FILE, not a verb — the same reading `risk.ts` gives it.
48
+ if (sub === "" || args.save) {
49
+ return await publicCode({ ...common, publish: args.publish, save: args.save, as: args.as, file: args.operands[0], force: args.force });
50
+ }
51
+ const manage = await import("./public-code-manage.js");
52
+ switch (sub) {
53
+ case "list":
54
+ return await manage.listCodes({ ...common, activity: args.activity });
55
+ case "new":
56
+ return await manage.newCode({ ...common, replace: args.replace, yes: args.yes });
57
+ case "revoke":
58
+ return await manage.revokeCodeCommand(args.operands[1], { ...common, yes: args.yes });
59
+ default:
60
+ throw new NmtsError(`"${sub}" is not a public-code command.`, {
61
+ exitCode: 2,
62
+ nextStep: `\`${BINARY_NAME} public-code\`, \`public-code list\`, \`public-code new\` or \`public-code revoke <number>\`.`,
63
+ });
64
+ }
39
65
  }
40
66
  export async function publicCode(options = {}) {
41
67
  const say = options.write ?? ((line) => process.stdout.write(`${line}\n`));
@@ -43,57 +69,55 @@ export async function publicCode(options = {}) {
43
69
  if (options.publish === true) {
44
70
  throw new NmtsError("--save and --publish are two different things; run them one at a time.", { exitCode: 2 });
45
71
  }
46
- return await savePublicCodeFile(options.file, options.force === true, say, options.json === true);
72
+ return await savePublicCodeFile(options, say);
47
73
  }
48
74
  const session = await openSession({ server: options.server, network: options.network });
49
75
  const crypt = await loadCrypto();
50
- const keys = shareKeysOf(crypt, session.code);
51
- const mine = b64(keys.address);
52
- const shown = keys.display;
53
- const seen = await request(session.server, "/v1/account/share-identity", {
54
- token: session.apiKey,
55
- });
56
- let published = isRecord(seen) && seen["published"] === true;
57
- // ⛔ IF THE SERVER ALREADY HOLDS A DIFFERENT ONE, STOP. Publishing is first-writer-wins and the
58
- // server would refuse the write anyway, but the useful thing to report is not "the write
59
- // failed" — it is that the NMTS key this machine is holding is not the one this account
60
- // was made with, which is a much bigger fact than a failed request.
61
- const held = isRecord(seen) ? seen["share_address"] : null;
62
- if (typeof held === "string" && held !== mine) {
63
- throw new NmtsError("This account already publishes a different public code.", {
64
- exitCode: 4,
65
- nextStep: "The public code is derived from the NMTS key, so a different one means this machine " +
66
- "is holding a different account's code than the key beside it. Check which account you meant.",
67
- });
76
+ const door = { server: session.server, token: session.apiKey };
77
+ const list = await readPublicCodes(door.server, door.token);
78
+ const held = defaultCode(list);
79
+ let shown;
80
+ let live = liveCodes(list).length;
81
+ if (held !== null) {
82
+ // ⛔ IF THE SERVER HOLDS A CODE THIS KEY DOES NOT MAKE AT THAT NUMBER, STOP (`differentCode`).
83
+ shown = { index: held.index, code: checkedDisplay(crypt, session.code, held), raw: held.address };
68
84
  }
69
- if (options.publish === true && !published) {
70
- await request(session.server, "/v1/account/share-identity", {
71
- token: session.apiKey,
72
- method: "PUT",
73
- body: { share_public_key: b64(keys.identity), share_address: mine },
74
- });
75
- published = true;
85
+ else if (options.publish === true) {
86
+ try {
87
+ const made = await publishCode(crypt, session.code, door, nextCodeIndex(list));
88
+ shown = { index: made.index, code: made.code, raw: made.address };
89
+ live = 1;
90
+ }
91
+ catch (error) {
92
+ throw publicCodeRefusal(error, { liveMax: list.liveMax, dayCap: list.dayCap });
93
+ }
76
94
  }
95
+ else {
96
+ const keys = shareKeysAt(crypt, session.code, nextCodeIndex(list));
97
+ shown = { index: keys.index, code: keys.display, raw: Buffer.from(keys.address).toString("base64url") };
98
+ keys.wipe();
99
+ }
100
+ const published = live > 0;
77
101
  if (options.json === true) {
78
102
  // ⚠ BOTH FORMS. `code` is what a person reads and types; `raw` is what the wire carries.
79
103
  // A reader that has only one of them ends up converting, and that is a second place to be wrong.
80
- say(JSON.stringify({ code: shown, raw: mine, published }));
104
+ say(JSON.stringify({ code: shown.code, raw: shown.raw, published, index: shown.index, live }));
81
105
  return 0;
82
106
  }
83
- say(`public code ${shown}`);
84
107
  if (published) {
85
- say(` published — another account can send files to it`);
108
+ say(`public code ${shown.code} (default · ${live} of ${list.liveMax} live)`);
86
109
  say(``);
87
110
  say(`Give it to whoever is sending. ⛔ It is NOT your NMTS key — that one opens`);
88
111
  say(`every file you have and is never given to anybody. This one opens nothing.`);
89
112
  return 0;
90
113
  }
114
+ say(`public code ${shown.code}`);
91
115
  say(` NOT published — nobody can send to it yet`);
92
116
  say(``);
93
117
  say(`Publishing writes it on the server so a sender can find the key to seal to.`);
94
- say(`It is permanent: it cannot be withdrawn or changed afterwards. It is also not a`);
95
- say(`choice — it comes from your NMTS key, so the same NMTS key always gives`);
96
- say(`the same public code, on this machine or any other.`);
118
+ say(`A published code cannot be changed. You can revoke it and make a new one with`);
119
+ say(` ${BINARY_NAME} public-code new`);
120
+ say(`The code comes from your NMTS key, so the same key always gives the same code.`);
97
121
  say(``);
98
122
  say(` ${BINARY_NAME} public-code --publish`);
99
123
  return 0;
@@ -101,15 +125,21 @@ export async function publicCode(options = {}) {
101
125
  /**
102
126
  * `nmts public-code --save [file]` — this account's public code file (NCF-3 §5.7).
103
127
  *
104
- * ⛔ NOTHING IN IT IS SECRET and nothing is asked of the server: the identity is derived from the
105
- * NMTS key on this machine, exactly the bytes `--publish` would put on the server. Whoever holds
106
- * the file can seal a handover to this account without looking the code up — which is the point:
107
- * that lookup is the one thing that tells NMTS who is sending to whom.
128
+ * ⛔ NOTHING IN IT IS SECRET: the identity is derived from the NMTS key on this machine, exactly the
129
+ * bytes `--publish` would put on the server. Whoever holds the file can seal a handover to this
130
+ * account without looking the code up — which is the point: that lookup is the one thing that
131
+ * tells NMTS who is sending to whom.
132
+ *
133
+ * ⚠ WHICH CODE: `--as <n>` names it and nothing is asked of the server. Without it, the default —
134
+ * read off the account's list when a key on this machine can read it, and code 0, the code every
135
+ * key starts with, when none can.
108
136
  */
109
- async function savePublicCodeFile(file, force, say, json) {
137
+ async function savePublicCodeFile(options, say) {
110
138
  const { code } = await requireAccountCode();
111
139
  const crypt = await loadCrypto();
112
- const keys = shareKeysOf(crypt, code);
140
+ const keys = await savedCodeKeys(crypt, code, options);
141
+ const force = options.force === true;
142
+ const file = options.file;
113
143
  const out = resolve(file === undefined || file === "" ? publicCodeFileName(keys.display) : file);
114
144
  try {
115
145
  writeFileSync(out, publicCodeFileText(keys), { flag: force ? "w" : "wx" });
@@ -123,13 +153,32 @@ async function savePublicCodeFile(file, force, say, json) {
123
153
  finally {
124
154
  keys.wipe();
125
155
  }
126
- if (json) {
127
- say(JSON.stringify({ code: keys.display, out }));
156
+ if (options.json === true) {
157
+ say(JSON.stringify({ code: keys.display, index: keys.index, out }));
128
158
  return 0;
129
159
  }
130
160
  say(`public code file ${out}`);
131
- say(` for public code ${keys.display}`);
161
+ say(` for public code #${keys.index} ${keys.display}`);
132
162
  say(``);
133
163
  say(`Whoever has this file can hand files over to you without asking NMTS.`);
134
164
  return 0;
135
165
  }
166
+ /** The keys the file is written from: `--as`, else the default code, else code 0. */
167
+ async function savedCodeKeys(crypt, code, options) {
168
+ if (options.as !== undefined)
169
+ return shareKeysAt(crypt, code, codeNumber(options.as, "--as"));
170
+ const key = resolveApiKey();
171
+ if (key === null)
172
+ return shareKeysAt(crypt, code, 0);
173
+ let list;
174
+ try {
175
+ list = await readPublicCodes(resolveServer(options.server ?? readCredentialsFile()?.server), key.key);
176
+ }
177
+ catch {
178
+ throw new NmtsError("Could not read which public code is your default.", {
179
+ exitCode: 4,
180
+ nextStep: "Nothing was written. Pass --as <number> to write the file for that code without asking the server.",
181
+ });
182
+ }
183
+ return checkedKeys(crypt, code, list, defaultCode(list)?.index ?? 0);
184
+ }
@@ -20,7 +20,8 @@ import { destinationFor } from "../safe-path.js";
20
20
  import { resolveNetwork } from "../network.js";
21
21
  import { BINARY_NAME } from "../product.js";
22
22
  import { openSession } from "../session.js";
23
- import { openReceived, openSharedDigest, shareKeysOf } from "../share.js";
23
+ import { openReceived, openSharedDigest, receivedIndex } from "../share.js";
24
+ import { shareKeyRing } from "../share-codes.js";
24
25
  import { processStdout, STDOUT_TARGET } from "../stdout.js";
25
26
  export async function receive(id, options = {}) {
26
27
  const toStdout = options.out === "-";
@@ -34,7 +35,8 @@ export async function receive(id, options = {}) {
34
35
  const session = await openSession({ server: options.server, network: options.network });
35
36
  const chain = resolveNetwork(session.server, session.network);
36
37
  const crypt = await loadCrypto();
37
- const keys = shareKeysOf(crypt, session.code);
38
+ // The row names which of this account's codes it came to; that code's keys open it.
39
+ const ring = shareKeyRing(crypt, session.code);
38
40
  try {
39
41
  // ⛔ THE ROW IS FOUND IN THE LISTING, not asked for by id. The listing is what carries the
40
42
  // sender's published identity, and without that identity the envelope cannot be
@@ -52,7 +54,7 @@ export async function receive(id, options = {}) {
52
54
  nextStep: `Nothing was written. \`${BINARY_NAME} shares\` lists what is there.`,
53
55
  });
54
56
  }
55
- const opened = openReceived(crypt, keys, row);
57
+ const opened = openReceived(crypt, ring.at(receivedIndex(row)), row);
56
58
  if (opened.dek === null || opened.name === null) {
57
59
  throw new NmtsError(`That share ${opened.problem ?? "did not open"}.`, {
58
60
  exitCode: 1,
@@ -109,17 +111,21 @@ export async function receive(id, options = {}) {
109
111
  name: opened.name,
110
112
  bytes: fetched.byteCount,
111
113
  from: opened.sender,
114
+ senderRevoked: opened.senderRevoked,
115
+ toIndex: opened.toIndex,
112
116
  parts: fetched.partCount,
113
117
  out: destination ?? STDOUT_TARGET,
114
118
  }));
115
119
  return 0;
116
120
  }
117
121
  say(`${opened.name} ${fetched.byteCount} bytes`);
118
- say(` from ${opened.sender ?? ""}`);
122
+ say(` from ${opened.sender ?? ""}${opened.senderRevoked ? " · the sender has revoked this code" : ""}`);
123
+ if (opened.toIndex !== 0)
124
+ say(` to #${opened.toIndex} ${ring.at(opened.toIndex).display}`);
119
125
  say(` checked against the hash the sender sealed with it`);
120
126
  return 0;
121
127
  }
122
128
  finally {
123
- keys.wipe();
129
+ ring.wipe();
124
130
  }
125
131
  }
@@ -1,4 +1,4 @@
1
- // The share verbs (share · shares · unshare · receive), dispatched here rather than in `main.ts`.
1
+ // The share verbs (share · shares · unshare · receive · link), dispatched here rather than in `main.ts`.
2
2
  //
3
3
  // ⛔ WHY A SECOND SWITCH. `main.ts` is measured (`check:size`) and had no room for `nmts support`;
4
4
  // this block shares a file and an option shape, so it moved as one piece with its comments.
@@ -11,6 +11,7 @@ export async function runShare(command, args) {
11
11
  network: args.network,
12
12
  json: args.json,
13
13
  yes: args.yes,
14
+ as: args.as,
14
15
  });
15
16
  }
16
17
  case "shares": {
@@ -40,6 +41,18 @@ export async function runShare(command, args) {
40
41
  json: args.json,
41
42
  });
42
43
  }
44
+ case "link": {
45
+ const { link } = await import("./link.js");
46
+ return await link(args.operands[0], args.operands[1], {
47
+ server: args.server,
48
+ network: args.network,
49
+ hideName: args.hideName,
50
+ expires: args.expires,
51
+ out: args.out,
52
+ force: args.force,
53
+ json: args.json,
54
+ });
55
+ }
43
56
  default:
44
57
  throw new Error(`not a share verb: ${command}`);
45
58
  }
@@ -4,6 +4,8 @@ export interface ShareOptions {
4
4
  json?: boolean;
5
5
  /** `--yes`: the per-attempt answer `share` needs in normal mode (see `share`). */
6
6
  yes?: boolean;
7
+ /** `--as <n>`: which live public code sends. Absent = the lowest-numbered live one. */
8
+ as?: string | undefined;
7
9
  write?: (line: string) => void;
8
10
  }
9
11
  export declare function out(options: ShareOptions): (line: string) => void;