@needmoretruth/nmts-cli 0.46.0 → 0.48.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.
Files changed (68) hide show
  1. package/AGENTS.md +8 -8
  2. package/CHANGELOG.md +32 -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/links.d.ts +7 -0
  14. package/dist/commands/links.js +71 -0
  15. package/dist/commands/public-code-manage.d.ts +24 -0
  16. package/dist/commands/public-code-manage.js +217 -0
  17. package/dist/commands/public-code.d.ts +7 -2
  18. package/dist/commands/public-code.js +104 -55
  19. package/dist/commands/receive.js +11 -5
  20. package/dist/commands/share-dispatch.js +18 -1
  21. package/dist/commands/share.d.ts +2 -0
  22. package/dist/commands/share.js +45 -35
  23. package/dist/commands/shares-sent.js +8 -3
  24. package/dist/crypto-surface.d.ts +27 -0
  25. package/dist/crypto-surface.js +10 -0
  26. package/dist/crypto.d.ts +5 -0
  27. package/dist/crypto.js +5 -0
  28. package/dist/handover-codes.d.ts +25 -0
  29. package/dist/handover-codes.js +106 -0
  30. package/dist/handover.d.ts +21 -3
  31. package/dist/handover.js +47 -29
  32. package/dist/help-options.js +9 -2
  33. package/dist/help.js +11 -1
  34. package/dist/links.d.ts +67 -0
  35. package/dist/links.js +226 -0
  36. package/dist/main.js +6 -6
  37. package/dist/mcp-tools/reads.js +20 -6
  38. package/dist/mcp-tools/share.js +47 -1
  39. package/dist/mcp-tools/tiers.js +16 -1
  40. package/dist/portable.d.ts +8 -0
  41. package/dist/portable.js +8 -0
  42. package/dist/product.d.ts +1 -1
  43. package/dist/product.js +1 -1
  44. package/dist/public-code-activity.d.ts +35 -0
  45. package/dist/public-code-activity.js +88 -0
  46. package/dist/public-code-refusals.d.ts +25 -0
  47. package/dist/public-code-refusals.js +87 -0
  48. package/dist/public-codes.d.ts +76 -0
  49. package/dist/public-codes.js +182 -0
  50. package/dist/risk.d.ts +36 -1
  51. package/dist/risk.js +38 -1
  52. package/dist/share-codes.d.ts +40 -0
  53. package/dist/share-codes.js +151 -0
  54. package/dist/share.d.ts +34 -0
  55. package/dist/share.js +53 -12
  56. package/dist/shared/lib/share/public-link.d.ts +41 -0
  57. package/dist/shared/lib/share/public-link.js +107 -0
  58. package/docs/commands/handover.md +17 -1
  59. package/docs/commands/link.md +34 -0
  60. package/docs/commands/mcp.md +2 -1
  61. package/docs/commands/public-code.md +21 -9
  62. package/docs/commands/share.md +6 -3
  63. package/package.json +1 -1
  64. package/server.json +2 -2
  65. package/vendor/nmts-crypto/nmts_crypto_wasm.d.ts +91 -5
  66. package/vendor/nmts-crypto/nmts_crypto_wasm.js +259 -4
  67. package/vendor/nmts-crypto/nmts_crypto_wasm_bg.wasm +0 -0
  68. package/vendor/nmts-crypto/nmts_crypto_wasm_bg.wasm.d.ts +11 -1
@@ -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;
@@ -19,36 +19,17 @@ import { readFileList } from "../manifest.js";
19
19
  import { BINARY_NAME } from "../product.js";
20
20
  import { request, ServerError } from "../api.js";
21
21
  import { openSession } from "../session.js";
22
- import { addressFromTyped, identityMatches, openReceived, sealShare, shareKeysOf, } from "../share.js";
22
+ import { addressFromTyped, identityMatches, openReceived, receivedIndex, sealShare, } from "../share.js";
23
23
  import { AAD, DERIVED } from "../crypto.js";
24
+ import { codeNumber, differentCode, notLiveCode, publicCodeRefusal } from "../public-code-refusals.js";
25
+ import { ensureLiveCode, liveCodes } from "../public-codes.js";
26
+ import { shareKeyRing, shareKeysAt } from "../share-codes.js";
24
27
  export function out(options) {
25
28
  return options.write ?? ((line) => process.stdout.write(`${line}\n`));
26
29
  }
27
30
  function b64(bytes) {
28
31
  return Buffer.from(bytes).toString("base64url");
29
32
  }
30
- /**
31
- * Make sure this account has published the identity other people encrypt to.
32
- *
33
- * ⛔ IT IS THE SAME BYTES EVERY TIME. The identity is derived from the NMTS key, so a browser
34
- * and this tool publish something identical for one account — which is why publishing from here
35
- * cannot claim a different account's place or overwrite anything meaningful.
36
- */
37
- async function ensurePublished(session, identity, address, say, quiet) {
38
- const seen = await request(session.server, "/v1/account/share-identity", {
39
- token: session.apiKey,
40
- });
41
- const published = typeof seen === "object" && seen !== null && Reflect.get(seen, "published") === true;
42
- if (published)
43
- return;
44
- if (!quiet)
45
- say(` publishing this account's public code for the first time`);
46
- await request(session.server, "/v1/account/share-identity", {
47
- token: session.apiKey,
48
- method: "PUT",
49
- body: { share_public_key: b64(identity), share_address: b64(address) },
50
- });
51
- }
52
33
  /** `nmts share <path> <address>` — hand one file to one account. */
53
34
  export async function share(target, typedAddress, options = {}) {
54
35
  const say = out(options);
@@ -59,6 +40,7 @@ export async function share(target, typedAddress, options = {}) {
59
40
  + `and the code as their \`${BINARY_NAME} public-code\` or account screen prints it.`,
60
41
  });
61
42
  }
43
+ const sendAs = options.as === undefined ? undefined : codeNumber(options.as, "--as");
62
44
  const crypt = await loadCrypto();
63
45
  // ⛔ BEFORE ANYTHING ELSE, AND BEFORE THE NETWORK. A typo caught here costs nothing; a typo sent
64
46
  // to the recipient lookup asks the server a question about an account that is not ours to ask.
@@ -91,14 +73,16 @@ export async function share(target, typedAddress, options = {}) {
91
73
  // allowed at all; `--yes` says THIS file to THIS address. A high act, so the tier gate
92
74
  // takes the yes in every mode but skip-permissions, where it hands `--yes` in.
93
75
  if (options.yes !== true) {
94
- say(`Would share "${fullPathOf(index, entry)}" with ${typedAddress}.`);
76
+ const from = sendAs === undefined ? "" : `, from public code #${sendAs}`;
77
+ say(`Would share "${fullPathOf(index, entry)}" with ${typedAddress}${from}.`);
95
78
  say(``);
96
79
  say(`⛔ Withdrawing later does not recall it — once the recipient has opened it, they have it.`);
97
- say(`Nothing was shared. To go ahead: ${BINARY_NAME} share ${JSON.stringify(target)} ${typedAddress} --yes`);
80
+ const as = sendAs === undefined ? "" : ` --as ${sendAs}`;
81
+ say(`Nothing was shared. To go ahead: ${BINARY_NAME} share ${JSON.stringify(target)} ${typedAddress}${as} --yes`);
98
82
  say(`⛔ If a program is reading this on somebody's behalf: show it to them and let them decide.`);
99
83
  return 5;
100
84
  }
101
- const keys = shareKeysOf(crypt, session.code);
85
+ let keys = null;
102
86
  const derived = crypt.kdf_derive(crypt.account_code_parse(session.code));
103
87
  const dataKey = derived.slice(DERIVED.dataKey[0], DERIVED.dataKey[1]);
104
88
  derived.fill(0);
@@ -108,7 +92,23 @@ export async function share(target, typedAddress, options = {}) {
108
92
  dek = crypt.envelope_open(dataKey, new TextEncoder().encode(AAD.dekWrap), new Uint8Array(Buffer.from(entry.dekWrapped, "base64url")));
109
93
  digest = crypt.envelope_open(dataKey, new TextEncoder().encode(AAD.contentHash), new Uint8Array(Buffer.from(entry.contentHashCt, "base64url")));
110
94
  dataKey.fill(0);
111
- await ensurePublished(session, keys.identity, keys.address, say, options.json === true);
95
+ // ⛔ A SHARE NEEDS A LIVE CODE TO COME FROM. The first one publishes the next number; a
96
+ // later one sends from the lowest-numbered live code unless `--as` names another.
97
+ const door = { server: session.server, token: session.apiKey };
98
+ const quiet = options.json === true;
99
+ const { list: codes } = await ensureLiveCode(crypt, session.code, door, () => {
100
+ if (!quiet)
101
+ say(` publishing this account's public code for the first time`);
102
+ }).catch((error) => {
103
+ throw publicCodeRefusal(error);
104
+ });
105
+ const live = liveCodes(codes);
106
+ const sender = sendAs === undefined ? live[0] : live.find((c) => c.index === sendAs);
107
+ if (sender === undefined)
108
+ throw notLiveCode(sendAs ?? 0);
109
+ keys = shareKeysAt(crypt, session.code, sender.index);
110
+ if (b64(keys.address) !== sender.address)
111
+ throw differentCode();
112
112
  const answer = await request(session.server, `/v1/share-recipients/${encodeURIComponent(b64(recipientAddress))}`, { token: session.apiKey });
113
113
  const identityB64 = typeof answer === "object" && answer !== null ? Reflect.get(answer, "share_public_key") : null;
114
114
  if (typeof identityB64 !== "string") {
@@ -156,7 +156,7 @@ export async function share(target, typedAddress, options = {}) {
156
156
  }
157
157
  const id = typeof created === "object" && created !== null ? Reflect.get(created, "id") : null;
158
158
  if (options.json) {
159
- say(JSON.stringify({ id, name: entry.name, recipient: crypt.share_address_display(recipientAddress) }));
159
+ say(JSON.stringify({ id, name: entry.name, recipient: crypt.share_address_display(recipientAddress), fromIndex: keys.index }));
160
160
  return 0;
161
161
  }
162
162
  say(`${entry.name} → ${crypt.share_address_display(recipientAddress)}`);
@@ -166,6 +166,8 @@ export async function share(target, typedAddress, options = {}) {
166
166
  return 0;
167
167
  }
168
168
  catch (error) {
169
+ if (error instanceof ServerError && error.code === "PUBLIC_CODE_REVOKED")
170
+ throw publicCodeRefusal(error);
169
171
  if (error instanceof ServerError && error.status === 403) {
170
172
  throw new NmtsError(error.message, {
171
173
  exitCode: 3,
@@ -179,7 +181,7 @@ export async function share(target, typedAddress, options = {}) {
179
181
  dataKey.fill(0);
180
182
  dek?.fill(0);
181
183
  digest?.fill(0);
182
- keys.wipe();
184
+ keys?.wipe();
183
185
  }
184
186
  }
185
187
  /** `nmts shares` — what was shared with this account, and what it shared. */
@@ -187,12 +189,16 @@ export async function shares(options = {}) {
187
189
  const say = out(options);
188
190
  const session = await openSession({ server: options.server, network: options.network });
189
191
  const crypt = await loadCrypto();
190
- const keys = shareKeysOf(crypt, session.code);
192
+ // Each row opens with the code it came to; each code's keys are derived once.
193
+ const ring = shareKeyRing(crypt, session.code);
191
194
  try {
192
195
  const received = asReceived(await request(session.server, "/v1/shares/received", { token: session.apiKey }));
193
- const opened = received.rows.map((row) => openReceived(crypt, keys, row));
196
+ const opened = received.rows.map((row) => openReceived(crypt, ring.at(receivedIndex(row)), row));
194
197
  for (const one of opened)
195
198
  one.dek?.fill(0);
199
+ // ⚠ WHICH CODE IT CAME TO is said once any row came to a code other than 0: for an account
200
+ // that has only ever received with one, the line would say nothing.
201
+ const toCode = opened.some((o) => o.toIndex !== 0) ? (o) => `#${o.toIndex} ${ring.at(o.toIndex).display}` : null;
196
202
  if (options.json) {
197
203
  say(JSON.stringify({
198
204
  received: opened.map((o) => ({
@@ -200,6 +206,8 @@ export async function shares(options = {}) {
200
206
  name: o.name,
201
207
  size: o.size,
202
208
  sender: o.sender,
209
+ senderRevoked: o.senderRevoked,
210
+ toIndex: o.toIndex,
203
211
  createdAt: o.createdAt,
204
212
  problem: o.problem,
205
213
  })),
@@ -213,7 +221,7 @@ export async function shares(options = {}) {
213
221
  else {
214
222
  say(`Shared with this account:`);
215
223
  for (const one of opened)
216
- printRow(say, one);
224
+ printRow(say, one, toCode);
217
225
  // ⛔ SAID OUT LOUD. The listing is bounded, and a person who is not told cannot know that
218
226
  // what they are looking at is not everything.
219
227
  if (received.total > opened.length) {
@@ -227,17 +235,19 @@ export async function shares(options = {}) {
227
235
  return 0;
228
236
  }
229
237
  finally {
230
- keys.wipe();
238
+ ring.wipe();
231
239
  }
232
240
  }
233
- function printRow(say, one) {
241
+ function printRow(say, one, toCode) {
234
242
  if (one.problem !== null) {
235
243
  say(` ${one.id} (will not open: ${one.problem})`);
236
244
  return;
237
245
  }
238
246
  const size = one.size === null ? "" : ` ${one.size} bytes`;
239
247
  say(` ${one.id} ${one.name ?? ""}${size}`);
240
- say(` from ${one.sender ?? ""}`);
248
+ say(` from ${one.sender ?? ""}${one.senderRevoked ? " · the sender has revoked this code" : ""}`);
249
+ if (toCode !== null)
250
+ say(` to ${toCode(one)}`);
241
251
  }
242
252
  export async function unshare(id, options = {}) {
243
253
  const say = out(options);
@@ -2,6 +2,7 @@
2
2
  import { request } from "../api.js";
3
3
  import { buildIndex, entryAt, fullPathOf, KIND_FILE, normalisePath } from "../drive-paths.js";
4
4
  import { NmtsError } from "../errors.js";
5
+ import { isRecord } from "../guards.js";
5
6
  import { readFileList } from "../manifest.js";
6
7
  import { BINARY_NAME } from "../product.js";
7
8
  import { openSession } from "../session.js";
@@ -65,12 +66,14 @@ export async function sharesSent(target, options = {}) {
65
66
  return 0;
66
67
  }
67
68
  say(`${path} is shared with:`);
69
+ // ⚠ WHICH OF THIS ACCOUNT'S CODES SENT IT is said once any row went from a code other than 0.
70
+ const fromShown = rows.some((row) => isRecord(row) && typeof row["from_index"] === "number" && row["from_index"] !== 0);
68
71
  for (const row of rows)
69
- say(sentLine(row));
72
+ say(sentLine(row, fromShown));
70
73
  return 0;
71
74
  }
72
75
  /** One row of `GET /v1/shares/sent`, as a person reads it. */
73
- function sentLine(row) {
76
+ function sentLine(row, fromShown) {
74
77
  const at = (name) => {
75
78
  const value = typeof row === "object" && row !== null ? Reflect.get(row, name) : undefined;
76
79
  if (typeof value !== "string") {
@@ -80,7 +83,9 @@ function sentLine(row) {
80
83
  }
81
84
  return value;
82
85
  };
83
- return `${at("recipient_address")} since ${utcDay(at("created_at"))} share ${at("id")}`;
86
+ const from = fromShown && isRecord(row) && typeof row["from_index"] === "number" ? ` from #${row["from_index"]}` : "";
87
+ const gone = isRecord(row) && row["recipient_code_revoked"] === true ? " · the recipient has revoked this code" : "";
88
+ return `${at("recipient_address")} since ${utcDay(at("created_at"))}${from} share ${at("id")}${gone}`;
84
89
  }
85
90
  /** The UTC day of an RFC 3339 instant, `YYYY-MM-DD`. */
86
91
  function utcDay(instant) {
@@ -109,6 +109,23 @@ export interface CryptoGlue {
109
109
  * that opens this. That is why the claimed sender may only be printed AFTER this succeeds.
110
110
  */
111
111
  share_unwrap_dek(shareKemSeed: Uint8Array, shareAuthSecret: Uint8Array, shareSigSeed: Uint8Array, senderPublic: Uint8Array, envelope: Uint8Array, itemId: string, nameShareCt: Uint8Array, contentHashShareCt: Uint8Array): Uint8Array;
112
+ /**
113
+ * The three secrets of sharing identity `index` (1 and up), from the 32-byte `shareIdRoot` slice
114
+ * of the derivation (NCF-3 §5.9): `kem(32) || auth(32) || sig(32)`. Throws for 0 — identity 0's
115
+ * secrets are the three share slices of the derivation itself.
116
+ */
117
+ share_id_seeds(shareIdRoot: Uint8Array, index: number): Uint8Array;
118
+ /** Identity `index`'s published bundle. At 0 it is `share_public_key`, byte for byte. */
119
+ share_public_key_at(shareKemSeed: Uint8Array, shareAuthSecret: Uint8Array, shareSigSeed: Uint8Array, index: number): Uint8Array;
120
+ /** Identity `index`'s 16-byte public code, from its signing seed alone. */
121
+ share_address_at(shareSigSeed: Uint8Array, index: number): Uint8Array;
122
+ /** `share_wrap_dek` sending as identity `senderIndex`: the envelope carries that identity's code. */
123
+ share_wrap_dek_as(senderAuthSecret: Uint8Array, senderSigSeed: Uint8Array, senderIndex: number, recipientPublic: Uint8Array, recipientAddress: Uint8Array, dek: Uint8Array, itemId: string, nameShareCt: Uint8Array, contentHashShareCt: Uint8Array): Uint8Array;
124
+ /**
125
+ * `share_unwrap_dek` as identity `index`. An envelope does not say which of the account's
126
+ * identities it was sealed to; opened as the wrong one it throws exactly like anybody else's.
127
+ */
128
+ share_unwrap_dek_as(shareKemSeed: Uint8Array, shareAuthSecret: Uint8Array, shareSigSeed: Uint8Array, index: number, senderPublic: Uint8Array, envelope: Uint8Array, itemId: string, nameShareCt: Uint8Array, contentHashShareCt: Uint8Array): Uint8Array;
112
129
  /**
113
130
  * Open one NCF-3 envelope: key, the associated data it was sealed with, the envelope bytes.
114
131
  *
@@ -231,6 +248,16 @@ export interface CryptoGlue {
231
248
  * (`heavy-evm.ts`); the key is wiped by whoever asked for it.
232
249
  */
233
250
  evm_key_for(walletRoot: Uint8Array, index: number): Uint8Array;
251
+ /** A fresh 32-byte public-link secret `S` (NCF-3 §5.8), drawn inside the engine. */
252
+ link_generate_secret(): Uint8Array;
253
+ /** `E(S, "nmts/v3/link-wrap", DEK)`, 104 bytes. */
254
+ link_wrap_dek(linkSecret: Uint8Array, dek: Uint8Array): Uint8Array;
255
+ /** The file key back from a link's wrapped key; throws when `S` or the envelope was changed. */
256
+ link_unwrap_dek(linkSecret: Uint8Array, wrapped: Uint8Array): Uint8Array;
257
+ /** `E(dataKey, "nmts/v3/link-secret", S)` — the owner's copy, so the link can be printed again. */
258
+ link_seal_secret(dataKey: Uint8Array, linkSecret: Uint8Array): Uint8Array;
259
+ /** `S` back from the owner's copy. */
260
+ link_open_secret(dataKey: Uint8Array, sealed: Uint8Array): Uint8Array;
234
261
  }
235
262
  export declare function isCryptoGlue(value: unknown): value is CryptoGlue;
236
263
  /** Which of the required functions this object does not have. Empty means it is the engine. */
@@ -43,9 +43,19 @@ const REQUIRED = [
43
43
  // "this function is missing" said at load time is a different day's problem from
44
44
  // `undefined is not a function` in the middle of deriving somebody's second account.
45
45
  "derive_ai_account_code",
46
+ // Numbered sharing identities (NCF-3 §5.9). Required for the same reason: an engine without them
47
+ // cannot make, show or open with any public code but the first.
48
+ "share_id_seeds",
49
+ "share_public_key_at",
50
+ "share_address_at",
51
+ "share_wrap_dek_as",
52
+ "share_unwrap_dek_as",
46
53
  // The EVM wallets (NCF-3 §1.9), required for the same reason: `put --tier heavy --pay evm` and
47
54
  // `heavy wallet` cannot run on a build without it.
48
55
  "evm_key_for",
56
+ // Public links (NCF-3 §5.8): `link make`, `link list` and `link open` cannot run without them.
57
+ "link_generate_secret", "link_wrap_dek", "link_unwrap_dek",
58
+ "link_seal_secret", "link_open_secret",
49
59
  ];
50
60
  export function isCryptoGlue(value) {
51
61
  return missingExports(value).length === 0;
package/dist/crypto.d.ts CHANGED
@@ -76,6 +76,11 @@ export declare const DERIVED: {
76
76
  * directly — and what it expands to is 20 bytes that ARE an NMTS key, not a seed.
77
77
  */
78
78
  readonly aiAccountRoot: readonly [256, 288];
79
+ /**
80
+ * The parent of this account's numbered sharing identities, 1 and up (NCF-3 §5.9). Identity 0
81
+ * is the three share slices above. Appended at the TAIL on 2026-09-23, for the same reason.
82
+ */
83
+ readonly shareIdRoot: readonly [288, 320];
79
84
  };
80
85
  /**
81
86
  * The engine, loaded once by whichever host this program registered.
package/dist/crypto.js CHANGED
@@ -94,6 +94,11 @@ export const DERIVED = {
94
94
  * directly — and what it expands to is 20 bytes that ARE an NMTS key, not a seed.
95
95
  */
96
96
  aiAccountRoot: [256, 288],
97
+ /**
98
+ * The parent of this account's numbered sharing identities, 1 and up (NCF-3 §5.9). Identity 0
99
+ * is the three share slices above. Appended at the TAIL on 2026-09-23, for the same reason.
100
+ */
101
+ shareIdRoot: [288, 320],
97
102
  };
98
103
  /**
99
104
  * The engine, loaded once by whichever host this program registered.
@@ -0,0 +1,25 @@
1
+ import type { CryptoGlue } from "./crypto.ts";
2
+ import { type PublicCodeList } from "./public-codes.ts";
3
+ import type { ShareKeys, ShareSealed } from "./share.ts";
4
+ /** How many numbers after 0 opening tries when it cannot read the account's list. */
5
+ export declare const OFFLINE_WALK = 64;
6
+ /**
7
+ * The number a handover is sent from: `--as`, or the lowest-numbered live code. An account that has
8
+ * never published sends from code 0, the code its key has always had.
9
+ */
10
+ export declare function senderIndexOf(list: PublicCodeList, as: string | undefined): number;
11
+ /** The keys at `index`, refused by name when the server lists another code at that number. */
12
+ export declare function checkedKeys(crypt: CryptoGlue, code: string, list: PublicCodeList, index: number): ShareKeys;
13
+ /** Whether `address` is one of this account's codes — live, revoked, or the one it is sending from. */
14
+ export declare function isMine(list: PublicCodeList, keys: ShareKeys, address: Uint8Array): boolean;
15
+ /** What opening found: the file key, the code it opened with, and — when known — whether that code is revoked. */
16
+ export interface OpenedWith {
17
+ dek: Uint8Array;
18
+ index: number;
19
+ display: string;
20
+ address: Uint8Array;
21
+ /** From the account's list when it was read; null when it was not. */
22
+ revoked: boolean | null;
23
+ }
24
+ /** Open a handover envelope with whichever of this account's codes it was sealed to. */
25
+ export declare function openWithMyCodes(crypt: CryptoGlue, code: string, sealed: ShareSealed, server: string): Promise<OpenedWith>;
@@ -0,0 +1,106 @@
1
+ // Which of this account's public codes a handover is made from, and which one opens it.
2
+ //
3
+ // ⛔ A HANDOVER FILE NAMES NO RECIPIENT NUMBER. The envelope was sealed to one of this key's codes
4
+ // and does not say which, so opening tries them: code 0 first — the code every account starts
5
+ // with, and the one every file made before numbered codes was sealed to — then, when a credential
6
+ // on this machine can read the account's list, the live codes lowest first and the revoked ones
7
+ // newest first; with no credential, 1, 2, … up to `OFFLINE_WALK`. A wrong number fails exactly as
8
+ // any other refusal does, so trying several tells nobody anything.
9
+ //
10
+ // ⛔ MAKING ONE SENDS FROM A LIVE CODE. A revoked code that went on sending would leave its
11
+ // recipients unable to trust a revocation; the server refuses that for shares, and a handover has
12
+ // no server to refuse it, so this does.
13
+ import { toBase64Url } from "./bytes.js";
14
+ import { resolveApiKey } from "./credentials.js";
15
+ import { notForThisKey } from "./handover.js";
16
+ import { codeNumber, differentCode, notLiveCode } from "./public-code-refusals.js";
17
+ import { liveCodes, readPublicCodes } from "./public-codes.js";
18
+ import { openShareWithRing, shareKeyRing, shareKeysAt } from "./share-codes.js";
19
+ /** How many numbers after 0 opening tries when it cannot read the account's list. */
20
+ export const OFFLINE_WALK = 64;
21
+ /**
22
+ * The number a handover is sent from: `--as`, or the lowest-numbered live code. An account that has
23
+ * never published sends from code 0, the code its key has always had.
24
+ */
25
+ export function senderIndexOf(list, as) {
26
+ const wanted = as === undefined ? undefined : codeNumber(as, "--as");
27
+ if (list.codes.length === 0) {
28
+ if (wanted !== undefined && wanted !== 0)
29
+ throw notLiveCode(wanted);
30
+ return 0;
31
+ }
32
+ const live = liveCodes(list);
33
+ const row = wanted === undefined ? live[0] : live.find((c) => c.index === wanted);
34
+ if (row === undefined)
35
+ throw notLiveCode(wanted ?? 0);
36
+ return row.index;
37
+ }
38
+ /** The keys at `index`, refused by name when the server lists another code at that number. */
39
+ export function checkedKeys(crypt, code, list, index) {
40
+ const keys = shareKeysAt(crypt, code, index);
41
+ const row = list.codes.find((c) => c.index === index);
42
+ if (row !== undefined && toBase64Url(keys.address) !== row.address) {
43
+ keys.wipe();
44
+ throw differentCode();
45
+ }
46
+ return keys;
47
+ }
48
+ /** Whether `address` is one of this account's codes — live, revoked, or the one it is sending from. */
49
+ export function isMine(list, keys, address) {
50
+ const wire = toBase64Url(address);
51
+ return wire === toBase64Url(keys.address) || list.codes.some((c) => c.address === wire);
52
+ }
53
+ /** The numbers to try after 0: live ascending, then revoked newest first. */
54
+ function laterCodes(list) {
55
+ const live = liveCodes(list).map((c) => c.index);
56
+ const revoked = list.codes
57
+ .filter((c) => c.revokedAt !== null)
58
+ .sort((a, b) => (b.revokedAt ?? "").localeCompare(a.revokedAt ?? "") || b.index - a.index)
59
+ .map((c) => c.index);
60
+ return [...live, ...revoked].filter((i) => i !== 0);
61
+ }
62
+ /** The account's list, when a credential on this machine can read it; null otherwise. */
63
+ async function listIfHeld(server) {
64
+ const key = resolveApiKey();
65
+ if (key === null)
66
+ return null;
67
+ try {
68
+ return await readPublicCodes(server, key.key);
69
+ }
70
+ catch {
71
+ return null;
72
+ }
73
+ }
74
+ /** Open a handover envelope with whichever of this account's codes it was sealed to. */
75
+ export async function openWithMyCodes(crypt, code, sealed, server) {
76
+ // ⛔ ONE RING: the key's derivation runs once however many numbers are tried.
77
+ const ring = shareKeyRing(crypt, code);
78
+ try {
79
+ let found;
80
+ let list = null;
81
+ try {
82
+ found = openShareWithRing(crypt, ring, [0], sealed);
83
+ }
84
+ catch {
85
+ list = await listIfHeld(server);
86
+ const order = list === null ? Array.from({ length: OFFLINE_WALK }, (_, i) => i + 1) : laterCodes(list);
87
+ try {
88
+ found = openShareWithRing(crypt, ring, order, sealed);
89
+ }
90
+ catch {
91
+ throw notForThisKey();
92
+ }
93
+ }
94
+ const keys = ring.at(found.index);
95
+ const row = list?.codes.find((c) => c.index === found.index);
96
+ return {
97
+ ...found,
98
+ display: keys.display,
99
+ address: keys.address.slice(),
100
+ revoked: row === undefined ? null : row.revokedAt !== null,
101
+ };
102
+ }
103
+ finally {
104
+ ring.wipe();
105
+ }
106
+ }
@@ -1,6 +1,7 @@
1
1
  import { type CryptoGlue } from "./crypto.ts";
2
- import { type ShareKeys } from "./share.ts";
3
- import { type HandoverNetwork, type HandoverPart } from "./shared/lib/share/handover-format.ts";
2
+ import { NmtsError } from "./errors.ts";
3
+ import { type ShareKeys, type ShareSealed } from "./share.ts";
4
+ import { type HandoverFile, type HandoverNetwork, type HandoverPart } from "./shared/lib/share/handover-format.ts";
4
5
  export declare function isHandoverNetwork(value: string): value is HandoverNetwork;
5
6
  /** Refuse a name the handover file cannot carry, before any work is done. */
6
7
  export declare function checkHandoverName(name: string, size: number, network: HandoverNetwork): void;
@@ -23,13 +24,30 @@ export interface OpenedHandover {
23
24
  size: number;
24
25
  /** The sender's public code, readable form — set only because the envelope opened. */
25
26
  sender: string;
27
+ /** The same code, 16 bytes — what a revoked-list lookup takes. */
28
+ senderAddress: Uint8Array;
26
29
  parts: HandoverPart[];
27
30
  /** Earliest end epoch recorded when the file was made (exclusive); 0 when unknown. A hint. */
28
31
  expiryEpoch: number;
29
32
  dek: Uint8Array;
30
33
  digest: Uint8Array;
31
34
  }
32
- /** Open a handover file's text with this account's keys. */
35
+ /** A handover file read and checked up to its envelope: everything opening it needs. */
36
+ export interface SealedHandover {
37
+ file: HandoverFile;
38
+ /** What the envelope opens with — the sender's identity, the envelope and the two sealed fields. */
39
+ sealed: ShareSealed;
40
+ /** The sender's code as the envelope names it; agreed with the identity the file carries. */
41
+ claimed: Uint8Array;
42
+ partsCt: Uint8Array;
43
+ }
44
+ /** The one refusal for a file none of this account's codes opens. */
45
+ export declare function notForThisKey(): NmtsError;
46
+ /** Read a handover file's text and check what can be checked before opening it. */
47
+ export declare function readHandoverText(crypt: CryptoGlue, text: string, network: HandoverNetwork): SealedHandover;
48
+ /** Everything inside a handover whose envelope opened to `dek`. Wipes `dek` when it fails. */
49
+ export declare function finishHandover(crypt: CryptoGlue, h: SealedHandover, dek: Uint8Array): OpenedHandover;
50
+ /** Open a handover file's text with one of this account's codes. */
33
51
  export declare function openHandoverText(crypt: CryptoGlue, keys: ShareKeys, text: string, network: HandoverNetwork): OpenedHandover;
34
52
  /** This account's public code file. */
35
53
  export declare function publicCodeFileText(keys: ShareKeys): string;
package/dist/handover.js CHANGED
@@ -22,7 +22,7 @@
22
22
  import { createHash } from "node:crypto";
23
23
  import { AAD } from "./crypto.js";
24
24
  import { NmtsError } from "./errors.js";
25
- import { addressFromTyped, identityMatches, sealShare } from "./share.js";
25
+ import { addressFromTyped, identityMatches, sealShare, unwrapWith } from "./share.js";
26
26
  import { decodeHandover, decodeHandoverName, decodePartsList, decodePublicCodeFile, earliestExpiry, encodeHandover, encodeHandoverName, encodePartsList, encodePublicCodeFile, handoverNameFits, HandoverFormatError, } from "./shared/lib/share/handover-format.js";
27
27
  const encoder = new TextEncoder();
28
28
  const b64 = (bytes) => Buffer.from(bytes).toString("base64url");
@@ -84,8 +84,21 @@ export function makeHandoverText(crypt, input) {
84
84
  });
85
85
  }
86
86
  }
87
- /** Open a handover file's text with this account's keys. */
88
- export function openHandoverText(crypt, keys, text, network) {
87
+ function damagedFile() {
88
+ return new NmtsError("This handover file is damaged: its fields do not hold together.", {
89
+ exitCode: 1,
90
+ nextStep: "Nothing was written. Ask the sender to send it again.",
91
+ });
92
+ }
93
+ /** The one refusal for a file none of this account's codes opens. */
94
+ export function notForThisKey() {
95
+ return new NmtsError("This file does not open with your NMTS key.", {
96
+ exitCode: 4,
97
+ nextStep: "Nothing was written. It was made for another key, or it was changed after it was made.",
98
+ });
99
+ }
100
+ /** Read a handover file's text and check what can be checked before opening it. */
101
+ export function readHandoverText(crypt, text, network) {
89
102
  let file;
90
103
  try {
91
104
  file = decodeHandover(text, network);
@@ -93,10 +106,6 @@ export function openHandoverText(crypt, keys, text, network) {
93
106
  catch (error) {
94
107
  throw readRefusal(error, network);
95
108
  }
96
- const damaged = new NmtsError("This handover file is damaged: its fields do not hold together.", {
97
- exitCode: 1,
98
- nextStep: "Nothing was written. Ask the sender to send it again.",
99
- });
100
109
  const senderIdentity = bytesOf(file.sender);
101
110
  const envelope = bytesOf(file.envelope);
102
111
  let claimed;
@@ -104,33 +113,30 @@ export function openHandoverText(crypt, keys, text, network) {
104
113
  claimed = crypt.share_claimed_sender(envelope);
105
114
  }
106
115
  catch {
107
- throw damaged;
116
+ throw damagedFile();
108
117
  }
109
118
  if (!identityMatches(crypt, senderIdentity, claimed))
110
- throw damaged;
111
- const nameCt = bytesOf(file.name);
112
- const digestCt = bytesOf(file.hash);
113
- const partsCt = bytesOf(file.parts);
114
- let dek;
115
- try {
116
- dek = crypt.share_unwrap_dek(keys.kemSeed, keys.authSecret, keys.sigSeed, senderIdentity, envelope, file.item, nameCt, digestCt);
117
- }
118
- catch {
119
- throw new NmtsError("This file does not open with your NMTS key.", {
120
- exitCode: 4,
121
- nextStep: "Nothing was written. It was made for another key, or it was changed after it was made.",
122
- });
123
- }
119
+ throw damagedFile();
120
+ return {
121
+ file,
122
+ sealed: { senderPublic: senderIdentity, envelope, itemId: file.item, nameCt: bytesOf(file.name), digestCt: bytesOf(file.hash) },
123
+ claimed,
124
+ partsCt: bytesOf(file.parts),
125
+ };
126
+ }
127
+ /** Everything inside a handover whose envelope opened to `dek`. Wipes `dek` when it fails. */
128
+ export function finishHandover(crypt, h, dek) {
124
129
  try {
125
- const named = decodeHandoverName(new TextDecoder().decode(crypt.envelope_open(dek, encoder.encode(AAD.shareName), nameCt)));
126
- if (named.network !== file.network || named.partsSha256 !== sha256(partsCt))
127
- throw damaged;
128
- const parts = decodePartsList(new TextDecoder().decode(crypt.envelope_open(dek, encoder.encode(AAD.handoverParts), partsCt)));
129
- const digest = crypt.envelope_open(dek, encoder.encode(AAD.shareContentHash), digestCt);
130
+ const named = decodeHandoverName(new TextDecoder().decode(crypt.envelope_open(dek, encoder.encode(AAD.shareName), h.sealed.nameCt)));
131
+ if (named.network !== h.file.network || named.partsSha256 !== sha256(h.partsCt))
132
+ throw damagedFile();
133
+ const parts = decodePartsList(new TextDecoder().decode(crypt.envelope_open(dek, encoder.encode(AAD.handoverParts), h.partsCt)));
134
+ const digest = crypt.envelope_open(dek, encoder.encode(AAD.shareContentHash), h.sealed.digestCt);
130
135
  return {
131
136
  name: named.name,
132
137
  size: named.size,
133
- sender: crypt.share_address_display(claimed),
138
+ sender: crypt.share_address_display(h.claimed),
139
+ senderAddress: h.claimed,
134
140
  parts,
135
141
  expiryEpoch: earliestExpiry(parts),
136
142
  dek,
@@ -139,8 +145,20 @@ export function openHandoverText(crypt, keys, text, network) {
139
145
  }
140
146
  catch {
141
147
  dek.fill(0);
142
- throw damaged;
148
+ throw damagedFile();
149
+ }
150
+ }
151
+ /** Open a handover file's text with one of this account's codes. */
152
+ export function openHandoverText(crypt, keys, text, network) {
153
+ const h = readHandoverText(crypt, text, network);
154
+ let dek;
155
+ try {
156
+ dek = unwrapWith(crypt, keys, h.sealed);
157
+ }
158
+ catch {
159
+ throw notForThisKey();
143
160
  }
161
+ return finishHandover(crypt, h, dek);
144
162
  }
145
163
  /** This account's public code file. */
146
164
  export function publicCodeFileText(keys) {
@@ -25,6 +25,8 @@ export function optionLines() {
25
25
  ` --all Include what is in the trash (ls), or take one label off every`,
26
26
  ` file that carries it (unlabel)`,
27
27
  ` --sent <path> Who ONE file was shared with, instead of the inbox (shares)`,
28
+ ` --hide-name Leave the file's name out of the link; its size stays (link make)`,
29
+ ` --expires <n>d When the link stops working, 1d to 3650d. Default: when it is cut (link make)`,
28
30
  ` --rename <old> The label to rename; the new name follows it (label)`,
29
31
  ` --qr Draw the wallet address as a code to scan (wallet address)`,
30
32
  ` --remove Take your name off the gift hall of fame, leaving a shortened`,
@@ -119,8 +121,13 @@ export function optionLines() {
119
121
  ` --accept-privacy <v> The version of the Privacy Policy accepted in the same act (create)`,
120
122
  ` --no-wait Print the registration address and stop, instead of waiting for a`,
121
123
  ` person to open it (create, when there is no verified key)`,
122
- ` --publish Publish this account's public code (public-code). Permanent —`,
123
- ` it cannot be withdrawn or changed afterwards`,
124
+ ` --publish Publish this account's public code (public-code), so other accounts`,
125
+ ` can send files to it`,
126
+ ` --activity Each code's shares as well as its counts (public-code list)`,
127
+ ` --replace <n> Revoke that live code in the same request (public-code new)`,
128
+ ` --as <n> Send from that live public code (share, handover make), or write`,
129
+ ` that code's file (public-code --save). Default: the lowest-numbered`,
130
+ ` live one`,
124
131
  ` --category <c> What a report is about (support send). The categories are listed by`,
125
132
  ` \`${BINARY_NAME} support --help\``,
126
133
  ` --sub <s> Which part of that category (support send). Always optional`,