@needmoretruth/nmts-cli 0.56.0 → 0.57.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.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,16 @@
3
3
  Each version's entry is what changed for the person or the program using `nmts`. The product's own
4
4
  update history, which covers the site and the server too, is at https://nmts.me/updates.
5
5
 
6
+ ## 0.57.0 — 2026-11-10
7
+
8
+ - A program can share a file the way `nmts share` does: `@needmoretruth/nmts-cli/share` exports
9
+ sending a share, listing what came in and what went out, receiving one and withdrawing one, and
10
+ runs in a browser as well as in Node. `nmts share`, `shares`, `receive` and `unshare` print what
11
+ they printed before.
12
+ - Delegation tokens have a sixth scope, `share`. With it, and the NMTS key's proof on the same
13
+ request, a token can share a file and make a public link. Listing shares and links needs
14
+ `files_read`; withdrawing a share or cutting a link needs `files_write`.
15
+
6
16
  ## 0.56.0 — 2026-11-10
7
17
 
8
18
  - With the account's storage copy of the recovery list switched on, `put --pay wallet` of a one-part
package/README.ko.md CHANGED
@@ -50,7 +50,7 @@ nmts --help
50
50
 
51
51
  ```sh
52
52
  npm install -g github:needmoretruth/nmts-cli # 기본 브랜치
53
- npm install -g github:needmoretruth/nmts-cli#v0.56.0 # 버전을 고정할 때
53
+ npm install -g github:needmoretruth/nmts-cli#v0.57.0 # 버전을 고정할 때
54
54
  npm install -g https://github.com/needmoretruth/nmts-cli/releases/latest/download/nmts.tgz
55
55
  ```
56
56
 
package/README.md CHANGED
@@ -51,7 +51,7 @@ default branch, from a pinned version, or from the tarball attached to the
51
51
 
52
52
  ```sh
53
53
  npm install -g github:needmoretruth/nmts-cli # the default branch
54
- npm install -g github:needmoretruth/nmts-cli#v0.56.0 # a pinned version
54
+ npm install -g github:needmoretruth/nmts-cli#v0.57.0 # a pinned version
55
55
  npm install -g https://github.com/needmoretruth/nmts-cli/releases/latest/download/nmts.tgz
56
56
  ```
57
57
 
@@ -11,7 +11,7 @@ export declare const CRYPTO_SPEC_URL = "https://github.com/needmoretruth/nmts-re
11
11
  * is the field's own contract — what the writer says about itself — and a person holding two
12
12
  * copies of one account's artefacts can then tell which program made each.
13
13
  */
14
- export declare const WRITTEN_BY = "nmts-cli 0.56.0";
14
+ export declare const WRITTEN_BY = "nmts-cli 0.57.0";
15
15
  /** Which of the three artefacts a wrapper is. A reader holding several can sort them. */
16
16
  export type ArtifactKind = "recovery-list" | "file-list" | "recovery-kit";
17
17
  /**
@@ -11,18 +11,15 @@
11
11
  // key and nothing else of the sender's, which is exactly why the check works at all: a storage
12
12
  // network that returned different bytes cannot produce a matching hash without the key.
13
13
  import { resolve } from "node:path";
14
- import { request } from "../api.js";
15
- import { loadCrypto } from "../crypto.js";
16
- import { fetchWithKey } from "../download.js";
17
14
  import { fileSink, stdoutSink } from "../download-sink-node.js";
18
15
  import { NmtsError } from "../errors.js";
19
16
  import { destinationFor } from "../safe-path.js";
20
17
  import { resolveNetwork } from "../network.js";
21
18
  import { BINARY_NAME } from "../product.js";
22
19
  import { openSession } from "../session.js";
23
- import { openReceived, openSharedDigest, receivedIndex } from "../share.js";
24
- import { shareKeyRing } from "../share-codes.js";
20
+ import { receiveShare } from "../sharing.js";
25
21
  import { processStdout, STDOUT_TARGET } from "../stdout.js";
22
+ import { shareAccountOf } from "./share.js";
26
23
  export async function receive(id, options = {}) {
27
24
  const toStdout = options.out === "-";
28
25
  const say = options.write ?? ((line) => (toStdout ? process.stderr : process.stdout).write(`${line}\n`));
@@ -33,99 +30,45 @@ export async function receive(id, options = {}) {
33
30
  });
34
31
  }
35
32
  const session = await openSession({ server: options.server, network: options.network });
36
- const chain = resolveNetwork(session.server, session.network);
37
- const crypt = await loadCrypto();
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);
40
- try {
41
- // ⛔ THE ROW IS FOUND IN THE LISTING, not asked for by id. The listing is what carries the
42
- // sender's published identity, and without that identity the envelope cannot be
43
- // authenticated — an unauthenticated open is not one worth doing.
44
- const answer = await request(session.server, "/v1/shares/received", {
45
- token: session.apiKey,
46
- });
47
- const rows = typeof answer === "object" && answer !== null ? Reflect.get(answer, "shares") : null;
48
- if (!Array.isArray(rows))
49
- throw new NmtsError("The server did not list any shares.");
50
- const row = rows.find((candidate) => typeof candidate === "object" && candidate !== null && Reflect.get(candidate, "id") === id);
51
- if (row === undefined) {
52
- throw new NmtsError(`Nothing shared with this account has the id "${id}".`, {
53
- exitCode: 4,
54
- nextStep: `Nothing was written. \`${BINARY_NAME} shares\` lists what is there.`,
55
- });
56
- }
57
- const opened = openReceived(crypt, ring.at(receivedIndex(row)), row);
58
- if (opened.dek === null || opened.name === null) {
59
- throw new NmtsError(`That share ${opened.problem ?? "did not open"}.`, {
60
- exitCode: 1,
61
- nextStep: "Nothing was written. The sender can withdraw it and share the file again.",
62
- });
63
- }
64
- if (opened.size === null) {
65
- // ⛔ NOT A GUESS. Without the sender's number there is nothing to trim the stored bytes back
66
- // to, and taking the stored length would write padding into the end of the file.
67
- opened.dek.fill(0);
68
- throw new NmtsError("The sender did not record this file's real length.", {
69
- exitCode: 1,
70
- nextStep: "Nothing was written. It was shared by an older client; ask them to share it again from " +
71
- "a current one, which seals the length beside the name.",
72
- });
73
- }
74
- const expected = openSharedDigest(crypt, opened.dek, opened.digestCt);
75
- if (expected === null) {
76
- opened.dek.fill(0);
77
- throw new NmtsError("This share's content hash did not open with the file's own key.", {
78
- exitCode: 1,
79
- nextStep: "Nothing was written. There would be nothing to check the bytes against.",
80
- });
81
- }
82
- const destination = toStdout
33
+ const account = shareAccountOf(session, resolveNetwork(session.server, session.network));
34
+ // ⛔ THE ROW IS FOUND IN THE LISTING, not asked for by id, and the length written is the one the
35
+ // sender sealed — both inside `receiveShare`, for the reasons at the top of this file.
36
+ let destination = null;
37
+ const got = await receiveShare(account, id, ({ name }) => {
38
+ destination = toStdout
83
39
  ? null
84
40
  : options.out !== undefined
85
41
  ? resolve(options.out)
86
42
  : // ⛔ The name is the SENDER'S choice, so it lands in a directory by its last segment only:
87
43
  // `../x` or an absolute path must not put a file outside where this tool was run.
88
- destinationFor(options.intoDir ?? ".", opened.name);
44
+ destinationFor(options.intoDir ?? ".", name);
89
45
  // ⛔ `--force` has nothing to overwrite on the stdout branch and is ignored there on purpose.
90
46
  // On the disk branch the file streams into a temporary name beside the destination and is
91
47
  // renamed into place only once the sender's digest matches, so a share that turns out to be
92
48
  // wrong — or a transfer that stops half way — leaves nothing under the name it was given.
93
- const sink = destination === null
49
+ return destination === null
94
50
  ? stdoutSink(options.stdout ?? processStdout())
95
51
  : fileSink(destination, { force: options.force === true });
96
- const fetched = await fetchWithKey({
97
- base: session.server,
98
- apiKey: session.apiKey,
99
- descriptorPath: `/v1/shares/${encodeURIComponent(id)}/parts?for=download`,
100
- size: opened.size,
101
- dek: opened.dek,
102
- expected,
103
- chain,
104
- sink,
105
- });
106
- if (!fetched.delivered)
107
- return 0;
108
- if (options.json) {
109
- say(JSON.stringify({
110
- id,
111
- name: opened.name,
112
- bytes: fetched.byteCount,
113
- from: opened.sender,
114
- senderRevoked: opened.senderRevoked,
115
- toIndex: opened.toIndex,
116
- parts: fetched.partCount,
117
- out: destination ?? STDOUT_TARGET,
118
- }));
119
- return 0;
120
- }
121
- say(`${opened.name} ${fetched.byteCount} bytes`);
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}`);
125
- say(` checked against the hash the sender sealed with it`);
52
+ });
53
+ if (!got.delivered)
54
+ return 0;
55
+ if (options.json) {
56
+ say(JSON.stringify({
57
+ id,
58
+ name: got.name,
59
+ bytes: got.bytes,
60
+ from: got.sender,
61
+ senderRevoked: got.senderRevoked,
62
+ toIndex: got.toIndex,
63
+ parts: got.parts,
64
+ out: destination ?? STDOUT_TARGET,
65
+ }));
126
66
  return 0;
127
67
  }
128
- finally {
129
- ring.wipe();
130
- }
68
+ say(`${got.name} ${got.bytes} bytes`);
69
+ say(` from ${got.sender ?? ""}${got.senderRevoked ? " · the sender has revoked this code" : ""}`);
70
+ if (got.toIndex !== 0)
71
+ say(` to #${got.toIndex} ${got.toCode}`);
72
+ say(` checked against the hash the sender sealed with it`);
73
+ return 0;
131
74
  }
@@ -1,3 +1,5 @@
1
+ import { type Session } from "../session.ts";
2
+ import { type ShareAccount } from "../sharing.ts";
1
3
  export interface ShareOptions {
2
4
  server?: string | undefined;
3
5
  network?: string | undefined;
@@ -9,6 +11,11 @@ export interface ShareOptions {
9
11
  write?: (line: string) => void;
10
12
  }
11
13
  export declare function out(options: ShareOptions): (line: string) => void;
14
+ /**
15
+ * The session as the share doors take it. ⛔ No account proof: an API key is asked for a live
16
+ * human check on the sending doors, and the commands send exactly what they sent before.
17
+ */
18
+ export declare function shareAccountOf(session: Session, network?: string): ShareAccount;
12
19
  /** `nmts share <path> <address>` — hand one file to one account. */
13
20
  export declare function share(target: string | undefined, typedAddress: string | undefined, options?: ShareOptions): Promise<number>;
14
21
  /** `nmts shares` — what was shared with this account, and what it shared. */
@@ -11,24 +11,24 @@
11
11
  // ⛔ THE CLAIMED SENDER IS PRINTED ONLY AFTER THE ENVELOPE OPENED. Opening it IS the proof of who
12
12
  // sent it, so a row that did not open is listed with no sender at all rather than with the name
13
13
  // it claims.
14
+ import { ServerError } from "../api.js";
14
15
  import { requireConsent } from "../consent.js";
15
16
  import { loadCrypto } from "../crypto.js";
16
- import { buildIndex, entryAt, fullPathOf, KIND_FILE, normalisePath } from "../drive-paths.js";
17
17
  import { NmtsError } from "../errors.js";
18
- import { readFileList } from "../manifest.js";
19
18
  import { BINARY_NAME } from "../product.js";
20
- import { request, ServerError } from "../api.js";
19
+ import { codeNumber, publicCodeRefusal } from "../public-code-refusals.js";
21
20
  import { openSession } from "../session.js";
22
- import { addressFromTyped, identityMatches, openReceived, receivedIndex, sealShare, } from "../share.js";
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";
21
+ import { addressFromTyped } from "../share.js";
22
+ import { receivedShares, removeShare, sendShare, shareableFileAt } from "../sharing.js";
27
23
  export function out(options) {
28
24
  return options.write ?? ((line) => process.stdout.write(`${line}\n`));
29
25
  }
30
- function b64(bytes) {
31
- return Buffer.from(bytes).toString("base64url");
26
+ /**
27
+ * The session as the share doors take it. ⛔ No account proof: an API key is asked for a live
28
+ * human check on the sending doors, and the commands send exactly what they sent before.
29
+ */
30
+ export function shareAccountOf(session, network = session.network) {
31
+ return { server: session.server, bearer: session.apiKey, code: session.code, accountId: session.accountId, network };
32
32
  }
33
33
  /** `nmts share <path> <address>` — hand one file to one account. */
34
34
  export async function share(target, typedAddress, options = {}) {
@@ -46,27 +46,8 @@ export async function share(target, typedAddress, options = {}) {
46
46
  // to the recipient lookup asks the server a question about an account that is not ours to ask.
47
47
  const recipientAddress = addressFromTyped(crypt, typedAddress);
48
48
  const session = await openSession({ server: options.server, network: options.network });
49
- const list = await readFileList(session.server, session.apiKey, session.code, session.accountId);
50
- if (list.manifest === null) {
51
- throw new NmtsError("This account has no file list, so there is nothing to share.", { exitCode: 4 });
52
- }
53
- const index = buildIndex(list.manifest.entries);
54
- const entry = entryAt(list.manifest.entries, normalisePath(target), {
55
- nothingHappened: "Nothing was shared.",
56
- });
57
- if (entry.kind !== KIND_FILE) {
58
- throw new NmtsError(`No file at "${fullPathOf(index, entry)}".`, {
59
- exitCode: 4,
60
- nextStep: "That is a folder. Nothing was shared — this version shares one file at a time.",
61
- });
62
- }
63
- if (entry.dekWrapped === undefined || entry.contentHashCt === undefined) {
64
- throw new NmtsError(`The file list holds no ${entry.dekWrapped === undefined ? "key" : "hash"} for "${entry.name}".`, {
65
- exitCode: 4,
66
- nextStep: "A share carries both — the key that opens the file and the hash the recipient checks the " +
67
- "bytes against. Nothing was shared.",
68
- });
69
- }
49
+ const account = shareAccountOf(session);
50
+ const file = await shareableFileAt(account, target);
70
51
  // ⛔ ASKED AFTER THE FILE IS KNOWN AND BEFORE ANYTHING LEAVES, so the question names a real file.
71
52
  requireConsent("share");
72
53
  // ⭐ AND ASKED EVERY TIME (2026-09-05): the once-per-machine unlock above says sharing is
@@ -74,7 +55,7 @@ export async function share(target, typedAddress, options = {}) {
74
55
  // takes the yes in every mode but skip-permissions, where it hands `--yes` in.
75
56
  if (options.yes !== true) {
76
57
  const from = sendAs === undefined ? "" : `, from public code #${sendAs}`;
77
- say(`Would share "${fullPathOf(index, entry)}" with ${typedAddress}${from}.`);
58
+ say(`Would share "${file.path}" with ${typedAddress}${from}.`);
78
59
  say(``);
79
60
  say(`⛔ Withdrawing later does not recall it — once the recipient has opened it, they have it.`);
80
61
  const as = sendAs === undefined ? "" : ` --as ${sendAs}`;
@@ -82,84 +63,22 @@ export async function share(target, typedAddress, options = {}) {
82
63
  say(`⛔ If a program is reading this on somebody's behalf: show it to them and let them decide.`);
83
64
  return 5;
84
65
  }
85
- let keys = null;
86
- const derived = crypt.kdf_derive(crypt.account_code_parse(session.code));
87
- const dataKey = derived.slice(DERIVED.dataKey[0], DERIVED.dataKey[1]);
88
- derived.fill(0);
89
- let dek = null;
90
- let digest = null;
91
66
  try {
92
- dek = crypt.envelope_open(dataKey, new TextEncoder().encode(AAD.dekWrap), new Uint8Array(Buffer.from(entry.dekWrapped, "base64url")));
93
- digest = crypt.envelope_open(dataKey, new TextEncoder().encode(AAD.contentHash), new Uint8Array(Buffer.from(entry.contentHashCt, "base64url")));
94
- dataKey.fill(0);
95
67
  // ⛔ A SHARE NEEDS A LIVE CODE TO COME FROM. The first one publishes the next number; a
96
68
  // later one sends from the lowest-numbered live code unless `--as` names another.
97
- const door = { server: session.server, token: session.apiKey };
98
69
  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);
70
+ const sent = await sendShare(account, file, recipientAddress, {
71
+ as: sendAs,
72
+ onFirstCode: () => {
73
+ if (!quiet)
74
+ say(` publishing this account's public code for the first time`);
75
+ },
104
76
  });
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
- const answer = await request(session.server, `/v1/share-recipients/${encodeURIComponent(b64(recipientAddress))}`, { token: session.apiKey });
113
- const identityB64 = typeof answer === "object" && answer !== null ? Reflect.get(answer, "share_public_key") : null;
114
- if (typeof identityB64 !== "string") {
115
- throw new NmtsError("That public code has never published an identity to share to.", {
116
- exitCode: 4,
117
- nextStep: "Nothing was shared. The code may be right and unused — somebody has to open " +
118
- "their account once before anything can be encrypted to them.",
119
- });
120
- }
121
- const recipientIdentity = new Uint8Array(Buffer.from(identityB64, "base64url"));
122
- // ⛔ CHECKED BEFORE ANYTHING IS ENCRYPTED TO IT. The engine checks it again inside the wrap;
123
- // this exists so the refusal names WHICH thing was wrong.
124
- if (!identityMatches(crypt, recipientIdentity, recipientAddress)) {
125
- throw new NmtsError("The identity the server returned is not the one that public code names.", {
126
- exitCode: 1,
127
- nextStep: "Nothing was shared. Encrypting to it would hand the file to somebody else.",
128
- });
129
- }
130
- const payload = sealShare(crypt, {
131
- keys,
132
- recipientIdentity,
133
- recipientAddress,
134
- dek,
135
- itemId: entry.id,
136
- name: entry.name,
137
- size: entry.size,
138
- digest,
139
- });
140
- const created = await request(session.server, "/v1/shares", {
141
- token: session.apiKey,
142
- method: "POST",
143
- body: { item_id: entry.id, recipient_address: b64(recipientAddress), ...payload },
144
- });
145
- // ⛔ READ BACK, NOT ECHOED. The server returns the address it actually STORED the share under.
146
- // Comparing it is the only way to notice a share that was filed against somebody else.
147
- const stored = typeof created === "object" && created !== null
148
- ? Reflect.get(created, "recipient_address")
149
- : null;
150
- if (typeof stored !== "string" || stored !== b64(recipientAddress)) {
151
- throw new NmtsError("The server filed this share against a different public code.", {
152
- exitCode: 1,
153
- nextStep: `Withdraw it now with \`${BINARY_NAME} unshare\` and share it again. The file's key was ` +
154
- `wrapped for the address you typed, so it is not readable by whoever it was filed under.`,
155
- });
156
- }
157
- const id = typeof created === "object" && created !== null ? Reflect.get(created, "id") : null;
158
77
  if (options.json) {
159
- say(JSON.stringify({ id, name: entry.name, recipient: crypt.share_address_display(recipientAddress), fromIndex: keys.index }));
78
+ say(JSON.stringify({ id: sent.id, name: sent.name, recipient: sent.recipient, fromIndex: sent.fromIndex }));
160
79
  return 0;
161
80
  }
162
- say(`${entry.name} → ${crypt.share_address_display(recipientAddress)}`);
81
+ say(`${sent.name} → ${sent.recipient}`);
163
82
  say(``);
164
83
  say(` They can download it from now on. Withdrawing the share stops further downloads`);
165
84
  say(` and cannot reach a copy they have already taken.`);
@@ -177,66 +96,50 @@ export async function share(target, typedAddress, options = {}) {
177
96
  }
178
97
  throw error;
179
98
  }
180
- finally {
181
- dataKey.fill(0);
182
- dek?.fill(0);
183
- digest?.fill(0);
184
- keys?.wipe();
185
- }
186
99
  }
187
100
  /** `nmts shares` — what was shared with this account, and what it shared. */
188
101
  export async function shares(options = {}) {
189
102
  const say = out(options);
190
103
  const session = await openSession({ server: options.server, network: options.network });
191
- const crypt = await loadCrypto();
192
- // Each row opens with the code it came to; each code's keys are derived once.
193
- const ring = shareKeyRing(crypt, session.code);
194
- try {
195
- const received = asReceived(await request(session.server, "/v1/shares/received", { token: session.apiKey }));
196
- const opened = received.rows.map((row) => openReceived(crypt, ring.at(receivedIndex(row)), row));
197
- for (const one of opened)
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;
202
- if (options.json) {
203
- say(JSON.stringify({
204
- received: opened.map((o) => ({
205
- id: o.id,
206
- name: o.name,
207
- size: o.size,
208
- sender: o.sender,
209
- senderRevoked: o.senderRevoked,
210
- toIndex: o.toIndex,
211
- createdAt: o.createdAt,
212
- problem: o.problem,
213
- })),
214
- total: received.total,
215
- }));
216
- return 0;
217
- }
218
- if (opened.length === 0) {
219
- say(`Nothing has been shared with this account.`);
220
- }
221
- else {
222
- say(`Shared with this account:`);
223
- for (const one of opened)
224
- printRow(say, one, toCode);
225
- // ⛔ SAID OUT LOUD. The listing is bounded, and a person who is not told cannot know that
226
- // what they are looking at is not everything.
227
- if (received.total > opened.length) {
228
- say(``);
229
- say(` ${received.total} in total; this shows ${opened.length}.`);
230
- }
231
- }
232
- say(``);
233
- say(` \`${BINARY_NAME} receive <id>\` downloads one. \`${BINARY_NAME} unshare <id>\` removes it`);
234
- say(` from this list, which does not touch the sender's own file.`);
104
+ const received = await receivedShares(shareAccountOf(session));
105
+ const opened = received.shares;
106
+ // ⚠ WHICH CODE IT CAME TO is said once any row came to a code other than 0: for an account
107
+ // that has only ever received with one, the line would say nothing.
108
+ const toCode = opened.some((o) => o.toIndex !== 0) ? (o) => `#${o.toIndex} ${o.toCode}` : null;
109
+ if (options.json) {
110
+ say(JSON.stringify({
111
+ received: opened.map((o) => ({
112
+ id: o.id,
113
+ name: o.name,
114
+ size: o.size,
115
+ sender: o.sender,
116
+ senderRevoked: o.senderRevoked,
117
+ toIndex: o.toIndex,
118
+ createdAt: o.createdAt,
119
+ problem: o.problem,
120
+ })),
121
+ total: received.total,
122
+ }));
235
123
  return 0;
236
124
  }
237
- finally {
238
- ring.wipe();
125
+ if (opened.length === 0) {
126
+ say(`Nothing has been shared with this account.`);
239
127
  }
128
+ else {
129
+ say(`Shared with this account:`);
130
+ for (const one of opened)
131
+ printRow(say, one, toCode);
132
+ // ⛔ SAID OUT LOUD. The listing is bounded, and a person who is not told cannot know that
133
+ // what they are looking at is not everything.
134
+ if (received.total > opened.length) {
135
+ say(``);
136
+ say(` ${received.total} in total; this shows ${opened.length}.`);
137
+ }
138
+ }
139
+ say(``);
140
+ say(` \`${BINARY_NAME} receive <id>\` downloads one. \`${BINARY_NAME} unshare <id>\` removes it`);
141
+ say(` from this list, which does not touch the sender's own file.`);
142
+ return 0;
240
143
  }
241
144
  function printRow(say, one, toCode) {
242
145
  if (one.problem !== null) {
@@ -258,10 +161,7 @@ export async function unshare(id, options = {}) {
258
161
  });
259
162
  }
260
163
  const session = await openSession({ server: options.server, network: options.network });
261
- await request(session.server, `/v1/shares/${encodeURIComponent(id)}`, {
262
- token: session.apiKey,
263
- method: "DELETE",
264
- });
164
+ await removeShare(shareAccountOf(session), id);
265
165
  if (options.json) {
266
166
  say(JSON.stringify({ id, removed: true }));
267
167
  return 0;
@@ -272,25 +172,3 @@ export async function unshare(id, options = {}) {
272
172
  say(` took is still theirs. If you received it, the sender's own file is untouched.`);
273
173
  return 0;
274
174
  }
275
- function asReceived(value) {
276
- if (typeof value !== "object" || value === null) {
277
- throw new NmtsError("The server's answer was not an object.");
278
- }
279
- const rows = Reflect.get(value, "shares");
280
- if (!Array.isArray(rows))
281
- throw new NmtsError("The server did not list any shares.");
282
- const total = Reflect.get(value, "total");
283
- return {
284
- rows: rows.filter(isRow),
285
- total: typeof total === "number" ? total : rows.length,
286
- };
287
- }
288
- function isRow(value) {
289
- if (typeof value !== "object" || value === null)
290
- return false;
291
- for (const name of ["id", "item_id", "dek_share_ct", "name_share_ct", "content_hash_share_ct"]) {
292
- if (typeof Reflect.get(value, name) !== "string")
293
- return false;
294
- }
295
- return true;
296
- }
@@ -1,12 +1,10 @@
1
1
  // `nmts shares --sent` — moved out of `share.ts` whole (that file is measured by `check:size`).
2
- import { request } from "../api.js";
3
- import { buildIndex, entryAt, fullPathOf, KIND_FILE, normalisePath } from "../drive-paths.js";
4
2
  import { NmtsError } from "../errors.js";
5
3
  import { isRecord } from "../guards.js";
6
- import { readFileList } from "../manifest.js";
7
4
  import { BINARY_NAME } from "../product.js";
8
5
  import { openSession } from "../session.js";
9
- import { out } from "./share.js";
6
+ import { sentShares } from "../sharing.js";
7
+ import { out, shareAccountOf } from "./share.js";
10
8
  /**
11
9
  * `nmts shares --sent <path>` — who ONE file was shared with.
12
10
  *
@@ -31,34 +29,11 @@ export async function sharesSent(target, options = {}) {
31
29
  });
32
30
  }
33
31
  const session = await openSession({ server: options.server, network: options.network });
34
- const list = await readFileList(session.server, session.apiKey, session.code, session.accountId);
35
- if (list.manifest === null) {
36
- throw new NmtsError("This account has no file list, so there is nothing to look up.", {
37
- exitCode: 4,
38
- });
39
- }
40
- const index = buildIndex(list.manifest.entries);
41
- const entry = entryAt(list.manifest.entries, normalisePath(target), {
42
- nothingHappened: "Nothing was changed.",
43
- });
44
- if (entry.kind !== KIND_FILE) {
45
- throw new NmtsError(`No file at "${fullPathOf(index, entry)}".`, {
46
- exitCode: 4,
47
- nextStep: "That is a folder, and a share is of one file.",
48
- });
49
- }
50
- const path = fullPathOf(index, entry);
51
- const answer = await request(session.server, `/v1/shares/sent?item_id=${encodeURIComponent(entry.id)}`, { token: session.apiKey });
52
- const rows = typeof answer === "object" && answer !== null ? Reflect.get(answer, "shares") : null;
53
- if (!Array.isArray(rows)) {
54
- throw new NmtsError("The server's answer did not carry a list of shares.", {
55
- nextStep: "Nothing was changed. Report it rather than retrying — the shape, not the network, is wrong.",
56
- });
57
- }
32
+ const { path, itemId, rows } = await sentShares(shareAccountOf(session), target);
58
33
  if (options.json) {
59
34
  // ⛔ THE SERVER'S ROWS, UNCHANGED. A reader of this arm is reading the route, and a shape
60
35
  // rewritten here would be a second wire to keep in step with the first.
61
- say(JSON.stringify({ path, item_id: entry.id, shares: rows }));
36
+ say(JSON.stringify({ path, item_id: itemId, shares: rows }));
62
37
  return 0;
63
38
  }
64
39
  if (rows.length === 0) {
package/dist/links.d.ts CHANGED
@@ -8,6 +8,11 @@ export interface LinkAccount {
8
8
  readonly bearer: string;
9
9
  /** The NMTS key, display form. Its dataKey opens the file key and seals the owner's copy of `S`. */
10
10
  readonly code: string;
11
+ /**
12
+ * ⛔ base64url of the code's proof, sent on making a link and nowhere else. A delegation token
13
+ * reaches that door only with its `share` bit and this proof; an API key does not need it.
14
+ */
15
+ readonly accountProof?: string | undefined;
11
16
  }
12
17
  export interface MadeLink {
13
18
  /** The whole link, secret included. */
package/dist/links.js CHANGED
@@ -67,7 +67,12 @@ export async function makeLink(account, entry, options) {
67
67
  digest.fill(0);
68
68
  }
69
69
  });
70
- const answer = await request(account.server, "/v1/share-links", { method: "POST", body, token: account.bearer });
70
+ const answer = await request(account.server, "/v1/share-links", {
71
+ method: "POST",
72
+ body,
73
+ token: account.bearer,
74
+ ...(account.accountProof === undefined ? {} : { accountProof: account.accountProof }),
75
+ });
71
76
  const id = isRecord(answer) ? text(answer["link_id"]) : null;
72
77
  const createdAt = isRecord(answer) ? text(answer["created_at"]) : null;
73
78
  if (id === null || createdAt === null) {
@@ -32,6 +32,11 @@ export declare const DELEGATION_MAX_TTL_SECS = 2592000;
32
32
  * an app can upload cannot destroy — and it does not stand alone: both doors also ask for the
33
33
  * account code's own proof on the same request, which is an act only whoever holds the code can
34
34
  * perform. The token is the business's permission; the proof is the key holder's.
35
+ *
36
+ * ⛔ `share` IS THE SIXTH, AND IT IS BUILT THE SAME WAY (spec 2026-09-20 unit C). It opens what sends
37
+ * a file's key out of the account: sharing it with another account and making a public link,
38
+ * and the lookup of the identity a share is sealed to. Those two sending doors also ask for the
39
+ * code's proof. Listing, receiving and cutting stay on `files_read` and `files_write`.
35
40
  */
36
41
  export declare const SCOPE_BITS: {
37
42
  readonly files_read: 1;
@@ -39,8 +44,9 @@ export declare const SCOPE_BITS: {
39
44
  readonly storage_spend: 4;
40
45
  readonly register: 8;
41
46
  readonly files_erase: 16;
47
+ readonly share: 32;
42
48
  };
43
- /** One of the five names above. */
49
+ /** One of the six names above. */
44
50
  export type ScopeName = keyof typeof SCOPE_BITS;
45
51
  /** Every bit a token may carry. */
46
52
  export declare const SCOPE_ALL: number;
@@ -60,6 +60,11 @@ export const DELEGATION_MAX_TTL_SECS = 2_592_000;
60
60
  * an app can upload cannot destroy — and it does not stand alone: both doors also ask for the
61
61
  * account code's own proof on the same request, which is an act only whoever holds the code can
62
62
  * perform. The token is the business's permission; the proof is the key holder's.
63
+ *
64
+ * ⛔ `share` IS THE SIXTH, AND IT IS BUILT THE SAME WAY (spec 2026-09-20 unit C). It opens what sends
65
+ * a file's key out of the account: sharing it with another account and making a public link,
66
+ * and the lookup of the identity a share is sealed to. Those two sending doors also ask for the
67
+ * code's proof. Listing, receiving and cutting stay on `files_read` and `files_write`.
63
68
  */
64
69
  export const SCOPE_BITS = {
65
70
  files_read: 1,
@@ -67,9 +72,15 @@ export const SCOPE_BITS = {
67
72
  storage_spend: 4,
68
73
  register: 8,
69
74
  files_erase: 16,
75
+ share: 32,
70
76
  };
71
77
  /** Every bit a token may carry. */
72
- export const SCOPE_ALL = SCOPE_BITS.files_read | SCOPE_BITS.files_write | SCOPE_BITS.storage_spend | SCOPE_BITS.register | SCOPE_BITS.files_erase;
78
+ export const SCOPE_ALL = SCOPE_BITS.files_read |
79
+ SCOPE_BITS.files_write |
80
+ SCOPE_BITS.storage_spend |
81
+ SCOPE_BITS.register |
82
+ SCOPE_BITS.files_erase |
83
+ SCOPE_BITS.share;
73
84
  /**
74
85
  * A new key pair, from the runtime's own random source.
75
86
  *
@@ -29,6 +29,8 @@ export { readFileList } from "./manifest.ts";
29
29
  export type { FileList } from "./manifest.ts";
30
30
  export { makeRecoveryList, nextRecoverySeq, readRecoveryCopy, recordRecoveryList, setRecoveryCopy } from "./recovery.ts";
31
31
  export type { MadeRecoveryList, RecoveryAccount, RecoveryCopyState } from "./recovery.ts";
32
+ export { addressFromTyped, receivedShares, receiveShare, removeShare, sendShare, sentShares, shareableFileAt } from "./sharing.ts";
33
+ export type { ReceivedFile, ReceivedShare, SentShare, ShareAccount, ShareableFile } from "./sharing.ts";
32
34
  export { addEntry, applyManyToList, applyToList, planAddition } from "./manifest-write.ts";
33
35
  export type { AddEntryInput, AddEntryResult, ListEditInput, ListEditResult } from "./manifest-write.ts";
34
36
  export type { Manifest, ManifestEntry } from "./shared/lib/drive/manifest-codec.ts";
package/dist/portable.js CHANGED
@@ -53,6 +53,8 @@ export { readFileList } from "./manifest.js";
53
53
  // The recovery list (spec 2026-09-20 unit B): the file `nmts recovery-list` writes, and its
54
54
  // storage-network copy's switch. Also its own entry, `./recovery`.
55
55
  export { makeRecoveryList, nextRecoverySeq, readRecoveryCopy, recordRecoveryList, setRecoveryCopy } from "./recovery.js";
56
+ // Sharing one file with another account (spec 2026-09-20 unit C). Also its own entry, `./share`.
57
+ export { addressFromTyped, receivedShares, receiveShare, removeShare, sendShare, sentShares, shareableFileAt } from "./sharing.js";
56
58
  export { addEntry, applyManyToList, applyToList, planAddition } from "./manifest-write.js";
57
59
  export { buildIndex, entryAt, folderIdFor, fullPathOf, isLive, KIND_FILE, KIND_FOLDER, namesIn, normalisePath, shown, trashedAt, } from "./drive-paths.js";
58
60
  export { setTrashed } from "./item-trash.js";
package/dist/product.d.ts CHANGED
@@ -9,7 +9,7 @@ export declare const BINARY_NAME = "nmts";
9
9
  * beside it. Here rather than in `main.ts` because the MCP server has to say it too, and a
10
10
  * command importing the entry point is a cycle waiting to bite.
11
11
  */
12
- export declare const VERSION = "0.56.0";
12
+ export declare const VERSION = "0.57.0";
13
13
  /** Where the product lives, for messages that need to send somebody somewhere real. */
14
14
  export declare const HOME_URL = "https://nmts.me";
15
15
  /** The source, so a person holding only the built program can find what it was built from. */
package/dist/product.js CHANGED
@@ -18,7 +18,7 @@ export const BINARY_NAME = "nmts";
18
18
  * beside it. Here rather than in `main.ts` because the MCP server has to say it too, and a
19
19
  * command importing the entry point is a cycle waiting to bite.
20
20
  */
21
- export const VERSION = "0.56.0";
21
+ export const VERSION = "0.57.0";
22
22
  /** Where the product lives, for messages that need to send somebody somewhere real. */
23
23
  export const HOME_URL = "https://nmts.me";
24
24
  /** The source, so a person holding only the built program can find what it was built from. */
@@ -0,0 +1,52 @@
1
+ import type { PlaintextSink } from "./download-sink.ts";
2
+ import type { ShareAccount } from "./sharing.ts";
3
+ import type { ReadOptions } from "./walrus.ts";
4
+ /** One received share, opened as far as it would open. Its key never leaves this module. */
5
+ export interface ReceivedShare {
6
+ id: string;
7
+ itemId: string;
8
+ /** The file's name and real length as the sender sealed them; null when the row would not open. */
9
+ name: string | null;
10
+ size: number | null;
11
+ /** The sender's public code — only ever set when the open SUCCEEDED. */
12
+ sender: string | null;
13
+ senderRevoked: boolean;
14
+ /** Which of this account's codes it came to, and that code readable. */
15
+ toIndex: number;
16
+ toCode: string;
17
+ createdAt: string;
18
+ /** Why it did not open, for a row that is still listed. */
19
+ problem: string | null;
20
+ }
21
+ /** A received file, written to the sink and checked against the sender's hash. */
22
+ export interface ReceivedFile {
23
+ id: string;
24
+ name: string;
25
+ bytes: number;
26
+ parts: number;
27
+ sender: string | null;
28
+ senderRevoked: boolean;
29
+ toIndex: number;
30
+ toCode: string;
31
+ /** False when the sink took the bytes but did not deliver them (it decides what that means). */
32
+ delivered: boolean;
33
+ }
34
+ /**
35
+ * Everything shared with this account, each row opened with the code it came to.
36
+ *
37
+ * ⛔ A ROW THAT WILL NOT OPEN IS STILL LISTED, with its reason and no sender. `total` can be larger
38
+ * than the list: the server's listing is bounded, and a caller that is not told cannot know.
39
+ */
40
+ export declare function receivedShares(account: ShareAccount): Promise<{
41
+ shares: ReceivedShare[];
42
+ total: number;
43
+ }>;
44
+ /**
45
+ * Receive one share into a sink: find its row in the list, open it, check what it says, then fetch.
46
+ * `sinkFor` is asked once the name and real length are known — the command picks a path from the
47
+ * sender's name there, and a program its own destination.
48
+ */
49
+ export declare function receiveShare(account: ShareAccount, id: string, sinkFor: (file: {
50
+ name: string;
51
+ size: number;
52
+ }) => PlaintextSink, read?: ReadOptions): Promise<ReceivedFile>;
@@ -0,0 +1,146 @@
1
+ // The inbox half of `sharing.ts`: what came in, and taking one of them. Its own file because
2
+ // `check:size` measures the sending half; `./share` re-exports both, so a caller sees one entry.
3
+ //
4
+ // ⛔ RECEIVING FINDS THE ROW IN THE LIST, not by id: the list is what carries the sender's published
5
+ // identity, and without it the envelope cannot be authenticated. The length written is the one
6
+ // the sender sealed, never the server's stored size (`commands/receive.ts` says why).
7
+ //
8
+ // ⛔ NO `node:`, NO `Buffer`, NO `process.` — `test/portable-closure.test.ts` walks this file.
9
+ import { request } from "./api.js";
10
+ import { loadCrypto } from "./crypto.js";
11
+ import { fetchWithKey } from "./download.js";
12
+ import { NmtsError } from "./errors.js";
13
+ import { BINARY_NAME } from "./product.js";
14
+ import { openReceived, openSharedDigest, receivedIndex } from "./share.js";
15
+ import { shareKeyRing } from "./share-codes.js";
16
+ /** The raw rows of `GET /v1/shares/received`, read field by field. */
17
+ async function receivedRows(account) {
18
+ const value = await request(account.server, "/v1/shares/received", { token: account.bearer });
19
+ if (typeof value !== "object" || value === null)
20
+ throw new NmtsError("The server's answer was not an object.");
21
+ const rows = Reflect.get(value, "shares");
22
+ if (!Array.isArray(rows))
23
+ throw new NmtsError("The server did not list any shares.");
24
+ const total = Reflect.get(value, "total");
25
+ return { rows: rows.filter(isRow), total: typeof total === "number" ? total : rows.length };
26
+ }
27
+ function isRow(value) {
28
+ if (typeof value !== "object" || value === null)
29
+ return false;
30
+ for (const name of ["id", "item_id", "dek_share_ct", "name_share_ct", "content_hash_share_ct"]) {
31
+ if (typeof Reflect.get(value, name) !== "string")
32
+ return false;
33
+ }
34
+ return true;
35
+ }
36
+ /**
37
+ * Everything shared with this account, each row opened with the code it came to.
38
+ *
39
+ * ⛔ A ROW THAT WILL NOT OPEN IS STILL LISTED, with its reason and no sender. `total` can be larger
40
+ * than the list: the server's listing is bounded, and a caller that is not told cannot know.
41
+ */
42
+ export async function receivedShares(account) {
43
+ const crypt = await loadCrypto();
44
+ const ring = shareKeyRing(crypt, account.code);
45
+ try {
46
+ const received = await receivedRows(account);
47
+ const shares = received.rows.map((row) => {
48
+ const o = openReceived(crypt, ring.at(receivedIndex(row)), row);
49
+ o.dek?.fill(0);
50
+ return {
51
+ id: o.id,
52
+ itemId: o.itemId,
53
+ name: o.name,
54
+ size: o.size,
55
+ sender: o.sender,
56
+ senderRevoked: o.senderRevoked,
57
+ toIndex: o.toIndex,
58
+ toCode: ring.at(o.toIndex).display,
59
+ createdAt: o.createdAt,
60
+ problem: o.problem,
61
+ };
62
+ });
63
+ return { shares, total: received.total };
64
+ }
65
+ finally {
66
+ ring.wipe();
67
+ }
68
+ }
69
+ /**
70
+ * Receive one share into a sink: find its row in the list, open it, check what it says, then fetch.
71
+ * `sinkFor` is asked once the name and real length are known — the command picks a path from the
72
+ * sender's name there, and a program its own destination.
73
+ */
74
+ export async function receiveShare(account, id, sinkFor, read) {
75
+ const crypt = await loadCrypto();
76
+ const ring = shareKeyRing(crypt, account.code);
77
+ try {
78
+ const answer = await request(account.server, "/v1/shares/received", { token: account.bearer });
79
+ const rows = typeof answer === "object" && answer !== null ? Reflect.get(answer, "shares") : null;
80
+ if (!Array.isArray(rows))
81
+ throw new NmtsError("The server did not list any shares.");
82
+ const row = rows.find((candidate) => typeof candidate === "object" && candidate !== null && Reflect.get(candidate, "id") === id);
83
+ if (row === undefined) {
84
+ throw new NmtsError(`Nothing shared with this account has the id "${id}".`, {
85
+ exitCode: 4,
86
+ nextStep: `Nothing was written. \`${BINARY_NAME} shares\` lists what is there.`,
87
+ });
88
+ }
89
+ const opened = openReceived(crypt, ring.at(receivedIndex(row)), row);
90
+ if (opened.dek === null || opened.name === null) {
91
+ throw new NmtsError(`That share ${opened.problem ?? "did not open"}.`, {
92
+ exitCode: 1,
93
+ nextStep: "Nothing was written. The sender can withdraw it and share the file again.",
94
+ });
95
+ }
96
+ if (opened.size === null) {
97
+ opened.dek.fill(0);
98
+ throw new NmtsError("The sender did not record this file's real length.", {
99
+ exitCode: 1,
100
+ nextStep: "Nothing was written. It was shared by an older client; ask them to share it again from " +
101
+ "a current one, which seals the length beside the name.",
102
+ });
103
+ }
104
+ const expected = openSharedDigest(crypt, opened.dek, opened.digestCt);
105
+ if (expected === null) {
106
+ opened.dek.fill(0);
107
+ throw new NmtsError("This share's content hash did not open with the file's own key.", {
108
+ exitCode: 1,
109
+ nextStep: "Nothing was written. There would be nothing to check the bytes against.",
110
+ });
111
+ }
112
+ let sink;
113
+ try {
114
+ sink = sinkFor({ name: opened.name, size: opened.size });
115
+ }
116
+ catch (error) {
117
+ opened.dek.fill(0);
118
+ throw error;
119
+ }
120
+ const fetched = await fetchWithKey({
121
+ base: account.server,
122
+ apiKey: account.bearer,
123
+ descriptorPath: `/v1/shares/${encodeURIComponent(id)}/parts?for=download`,
124
+ size: opened.size,
125
+ dek: opened.dek,
126
+ expected,
127
+ chain: account.network,
128
+ ...(read === undefined ? {} : { read }),
129
+ sink,
130
+ });
131
+ return {
132
+ id,
133
+ name: opened.name,
134
+ bytes: fetched.byteCount,
135
+ parts: fetched.partCount,
136
+ sender: opened.sender,
137
+ senderRevoked: opened.senderRevoked,
138
+ toIndex: opened.toIndex,
139
+ toCode: ring.at(opened.toIndex).display,
140
+ delivered: fetched.delivered,
141
+ };
142
+ }
143
+ finally {
144
+ ring.wipe();
145
+ }
146
+ }
@@ -0,0 +1,52 @@
1
+ import type { ManifestEntry } from "./shared/lib/drive/manifest-codec.ts";
2
+ export { addressFromTyped } from "./share.ts";
3
+ export { receivedShares, receiveShare } from "./sharing-inbox.ts";
4
+ export type { ReceivedFile, ReceivedShare } from "./sharing-inbox.ts";
5
+ /** An account as the share doors take it. */
6
+ export interface ShareAccount {
7
+ readonly server: string;
8
+ /** What the one auth header carries: an API key or a delegation token. */
9
+ readonly bearer: string;
10
+ readonly code: string;
11
+ readonly accountId: string;
12
+ /** The chain the stored parts are on, as `resolveNetwork` answers it. */
13
+ readonly network: string;
14
+ /** ⛔ base64url of the code's proof, for the two sending doors only. Absent: not sent. */
15
+ readonly accountProof?: string | undefined;
16
+ }
17
+ /** One file of the account's list that a share can carry, and its full path. */
18
+ export interface ShareableFile {
19
+ readonly entry: ManifestEntry & {
20
+ dekWrapped: string;
21
+ contentHashCt: string;
22
+ };
23
+ readonly path: string;
24
+ }
25
+ /** What a sent share is: its id, the file's name, who it went to and from which code. */
26
+ export interface SentShare {
27
+ id: string | null;
28
+ name: string;
29
+ /** The recipient's public code, readable form. */
30
+ recipient: string;
31
+ fromIndex: number;
32
+ }
33
+ /** The file at `target`, checked for the key and the hash a share carries. */
34
+ export declare function shareableFileAt(account: ShareAccount, target: string): Promise<ShareableFile>;
35
+ /**
36
+ * Seal one file for one public code and send it.
37
+ *
38
+ * ⛔ THE CALLER HAS ALREADY DECIDED. The command asks its person between `shareableFileAt` and this
39
+ * call; a program decides by calling. Nothing here asks anybody anything.
40
+ */
41
+ export declare function sendShare(account: ShareAccount, file: ShareableFile, recipientAddress: Uint8Array, options?: {
42
+ as?: number | undefined;
43
+ onFirstCode?: () => void;
44
+ }): Promise<SentShare>;
45
+ /** Who one file was shared with: the server's rows, unchanged, beside the file's path and id. */
46
+ export declare function sentShares(account: ShareAccount, target: string): Promise<{
47
+ path: string;
48
+ itemId: string;
49
+ rows: unknown[];
50
+ }>;
51
+ /** Withdraw a share this account sent, or remove one it was sent. A copy already taken stays taken. */
52
+ export declare function removeShare(account: ShareAccount, id: string): Promise<void>;
@@ -0,0 +1,218 @@
1
+ // Sharing as a library: send one file to another account, list what came in and what went out,
2
+ // receive one, and take one back — for the command line, the SDK and a page, with nothing in it
3
+ // that needs Node (spec 2026-09-20 unit C).
4
+ //
5
+ // ⛔ WHY IT IS ITS OWN ENTRY. An app built on NMTS could not share a person's file: the steps lived
6
+ // inside `nmts share` and `nmts receive`, with the terminal wound through them. The commands are
7
+ // now shells over these functions, so what an app sends is what the command sends, byte for
8
+ // byte — the sealing itself is `share.ts`, untouched, and its order is load-bearing.
9
+ //
10
+ // ⛔ THE SAME FOR EVERY KEY HOLDER. `ShareAccount.bearer` is an API key or a delegation token. A
11
+ // token reaches the two sending doors only with its `share` bit AND the code's proof
12
+ // (`accountProof`), so the proof is sent on those two requests and on no other. An API key is
13
+ // asked for a live human check there instead, and the proof is simply not needed.
14
+ //
15
+ // ⛔ RECEIVING IS `sharing-inbox.ts`, re-exported here so `./share` is one entry.
16
+ //
17
+ // ⛔ NO `node:`, NO `Buffer`, NO `process.` — `test/portable-closure.test.ts` walks this file.
18
+ import { request, ServerError } from "./api.js";
19
+ import { fromBase64Url, toBase64Url, utf8 } from "./bytes.js";
20
+ import { AAD, DERIVED, loadCrypto } from "./crypto.js";
21
+ import { buildIndex, entryAt, fullPathOf, KIND_FILE, normalisePath } from "./drive-paths.js";
22
+ import { NmtsError } from "./errors.js";
23
+ import { readFileList } from "./manifest.js";
24
+ import { BINARY_NAME } from "./product.js";
25
+ import { differentCode, notLiveCode, publicCodeRefusal } from "./public-code-refusals.js";
26
+ import { ensureLiveCode, liveCodes, PUBLISH_TRIES } from "./public-codes.js";
27
+ import { identityMatches, sealShare } from "./share.js";
28
+ import { shareKeyRing, shareKeysAt } from "./share-codes.js";
29
+ export { addressFromTyped } from "./share.js";
30
+ export { receivedShares, receiveShare } from "./sharing-inbox.js";
31
+ /** The file at `target`, checked for the key and the hash a share carries. */
32
+ export async function shareableFileAt(account, target) {
33
+ const list = await readFileList(account.server, account.bearer, account.code, account.accountId);
34
+ if (list.manifest === null) {
35
+ throw new NmtsError("This account has no file list, so there is nothing to share.", { exitCode: 4 });
36
+ }
37
+ const index = buildIndex(list.manifest.entries);
38
+ const entry = entryAt(list.manifest.entries, normalisePath(target), {
39
+ nothingHappened: "Nothing was shared.",
40
+ });
41
+ if (entry.kind !== KIND_FILE) {
42
+ throw new NmtsError(`No file at "${fullPathOf(index, entry)}".`, {
43
+ exitCode: 4,
44
+ nextStep: "That is a folder. Nothing was shared — this version shares one file at a time.",
45
+ });
46
+ }
47
+ const { dekWrapped, contentHashCt } = entry;
48
+ if (dekWrapped === undefined || contentHashCt === undefined) {
49
+ throw new NmtsError(`The file list holds no ${dekWrapped === undefined ? "key" : "hash"} for "${entry.name}".`, {
50
+ exitCode: 4,
51
+ nextStep: "A share carries both — the key that opens the file and the hash the recipient checks the " +
52
+ "bytes against. Nothing was shared.",
53
+ });
54
+ }
55
+ return { entry: { ...entry, dekWrapped, contentHashCt }, path: fullPathOf(index, entry) };
56
+ }
57
+ /**
58
+ * Which live code sends: `as` when named, else the lowest-numbered live one — published first when
59
+ * the account has none, as a first share does.
60
+ *
61
+ * ⚠ A DELEGATION TOKEN CANNOT READ THE CODE LIST (its business replaces a user's one code through
62
+ * its own signed batch, and that list stays closed to it). So for a token the codes are asked
63
+ * one number at a time at the public lookup, from 0: a revoked one answers 410, the live one 200,
64
+ * and the first number never published 404 — there is nothing after it.
65
+ */
66
+ async function senderKeys(crypt, account, as, onFirstCode) {
67
+ const door = { server: account.server, token: account.bearer };
68
+ let codes;
69
+ try {
70
+ ({ list: codes } = await ensureLiveCode(crypt, account.code, door, onFirstCode));
71
+ }
72
+ catch (error) {
73
+ if (!(error instanceof ServerError && error.code === "DELEGATION_SCOPE"))
74
+ throw publicCodeRefusal(error);
75
+ return as === undefined ? await walkToLiveCode(crypt, account) : shareKeysAt(crypt, account.code, as);
76
+ }
77
+ const live = liveCodes(codes);
78
+ const sender = as === undefined ? live[0] : live.find((c) => c.index === as);
79
+ if (sender === undefined)
80
+ throw notLiveCode(as ?? 0);
81
+ const keys = shareKeysAt(crypt, account.code, sender.index);
82
+ if (toBase64Url(keys.address) !== sender.address) {
83
+ keys.wipe();
84
+ throw differentCode();
85
+ }
86
+ return keys;
87
+ }
88
+ async function walkToLiveCode(crypt, account) {
89
+ const ring = shareKeyRing(crypt, account.code);
90
+ try {
91
+ for (let index = 0; index < PUBLISH_TRIES; index += 1) {
92
+ const address = toBase64Url(ring.at(index).address);
93
+ try {
94
+ await request(account.server, `/v1/share-recipients/${encodeURIComponent(address)}`, { token: account.bearer });
95
+ return shareKeysAt(crypt, account.code, index);
96
+ }
97
+ catch (error) {
98
+ if (error instanceof ServerError && error.status === 410)
99
+ continue;
100
+ if (error instanceof ServerError && error.status === 404)
101
+ break;
102
+ throw error;
103
+ }
104
+ }
105
+ }
106
+ finally {
107
+ ring.wipe();
108
+ }
109
+ throw new NmtsError("This account has no public code yet, so nothing can be shared from it.", {
110
+ exitCode: 4,
111
+ nextStep: "Nothing was shared. The business that issued this token publishes one with setPublicCodes; then share again.",
112
+ });
113
+ }
114
+ /**
115
+ * Seal one file for one public code and send it.
116
+ *
117
+ * ⛔ THE CALLER HAS ALREADY DECIDED. The command asks its person between `shareableFileAt` and this
118
+ * call; a program decides by calling. Nothing here asks anybody anything.
119
+ */
120
+ export async function sendShare(account, file, recipientAddress, options = {}) {
121
+ const crypt = await loadCrypto();
122
+ const { entry } = file;
123
+ let keys = null;
124
+ const derived = crypt.kdf_derive(crypt.account_code_parse(account.code));
125
+ const dataKey = derived.slice(DERIVED.dataKey[0], DERIVED.dataKey[1]);
126
+ derived.fill(0);
127
+ let dek = null;
128
+ let digest = null;
129
+ try {
130
+ dek = crypt.envelope_open(dataKey, utf8(AAD.dekWrap), fromBase64Url(entry.dekWrapped));
131
+ digest = crypt.envelope_open(dataKey, utf8(AAD.contentHash), fromBase64Url(entry.contentHashCt));
132
+ dataKey.fill(0);
133
+ keys = await senderKeys(crypt, account, options.as, options.onFirstCode);
134
+ const answer = await request(account.server, `/v1/share-recipients/${encodeURIComponent(toBase64Url(recipientAddress))}`, { token: account.bearer });
135
+ const identityB64 = typeof answer === "object" && answer !== null ? Reflect.get(answer, "share_public_key") : null;
136
+ if (typeof identityB64 !== "string") {
137
+ throw new NmtsError("That public code has never published an identity to share to.", {
138
+ exitCode: 4,
139
+ nextStep: "Nothing was shared. The code may be right and unused — somebody has to open " +
140
+ "their account once before anything can be encrypted to them.",
141
+ });
142
+ }
143
+ const recipientIdentity = fromBase64Url(identityB64);
144
+ // ⛔ CHECKED BEFORE ANYTHING IS ENCRYPTED TO IT. The engine checks it again inside the wrap;
145
+ // this exists so the refusal names WHICH thing was wrong.
146
+ if (!identityMatches(crypt, recipientIdentity, recipientAddress)) {
147
+ throw new NmtsError("The identity the server returned is not the one that public code names.", {
148
+ exitCode: 1,
149
+ nextStep: "Nothing was shared. Encrypting to it would hand the file to somebody else.",
150
+ });
151
+ }
152
+ const payload = sealShare(crypt, {
153
+ keys,
154
+ recipientIdentity,
155
+ recipientAddress,
156
+ dek,
157
+ itemId: entry.id,
158
+ name: entry.name,
159
+ size: entry.size,
160
+ digest,
161
+ });
162
+ const created = await request(account.server, "/v1/shares", {
163
+ token: account.bearer,
164
+ method: "POST",
165
+ body: { item_id: entry.id, recipient_address: toBase64Url(recipientAddress), ...payload },
166
+ ...(account.accountProof === undefined ? {} : { accountProof: account.accountProof }),
167
+ });
168
+ // ⛔ READ BACK, NOT ECHOED. The server returns the address it actually STORED the share under.
169
+ const stored = typeof created === "object" && created !== null ? Reflect.get(created, "recipient_address") : null;
170
+ if (typeof stored !== "string" || stored !== toBase64Url(recipientAddress)) {
171
+ throw new NmtsError("The server filed this share against a different public code.", {
172
+ exitCode: 1,
173
+ nextStep: `Withdraw it now with \`${BINARY_NAME} unshare\` and share it again. The file's key was ` +
174
+ `wrapped for the address you typed, so it is not readable by whoever it was filed under.`,
175
+ });
176
+ }
177
+ const id = typeof created === "object" && created !== null ? Reflect.get(created, "id") : null;
178
+ return {
179
+ id: typeof id === "string" ? id : null,
180
+ name: entry.name,
181
+ recipient: crypt.share_address_display(recipientAddress),
182
+ fromIndex: keys.index,
183
+ };
184
+ }
185
+ finally {
186
+ dataKey.fill(0);
187
+ dek?.fill(0);
188
+ digest?.fill(0);
189
+ keys?.wipe();
190
+ }
191
+ }
192
+ /** Who one file was shared with: the server's rows, unchanged, beside the file's path and id. */
193
+ export async function sentShares(account, target) {
194
+ const list = await readFileList(account.server, account.bearer, account.code, account.accountId);
195
+ if (list.manifest === null) {
196
+ throw new NmtsError("This account has no file list, so there is nothing to look up.", { exitCode: 4 });
197
+ }
198
+ const index = buildIndex(list.manifest.entries);
199
+ const entry = entryAt(list.manifest.entries, normalisePath(target), { nothingHappened: "Nothing was changed." });
200
+ if (entry.kind !== KIND_FILE) {
201
+ throw new NmtsError(`No file at "${fullPathOf(index, entry)}".`, {
202
+ exitCode: 4,
203
+ nextStep: "That is a folder, and a share is of one file.",
204
+ });
205
+ }
206
+ const answer = await request(account.server, `/v1/shares/sent?item_id=${encodeURIComponent(entry.id)}`, { token: account.bearer });
207
+ const rows = typeof answer === "object" && answer !== null ? Reflect.get(answer, "shares") : null;
208
+ if (!Array.isArray(rows)) {
209
+ throw new NmtsError("The server's answer did not carry a list of shares.", {
210
+ nextStep: "Nothing was changed. Report it rather than retrying — the shape, not the network, is wrong.",
211
+ });
212
+ }
213
+ return { path: fullPathOf(index, entry), itemId: entry.id, rows };
214
+ }
215
+ /** Withdraw a share this account sent, or remove one it was sent. A copy already taken stays taken. */
216
+ export async function removeShare(account, id) {
217
+ await request(account.server, `/v1/shares/${encodeURIComponent(id)}`, { token: account.bearer, method: "DELETE" });
218
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@needmoretruth/nmts-cli",
3
- "version": "0.56.0",
3
+ "version": "0.57.0",
4
4
  "description": "Command-line and MCP access to NMTS (NeedMoreTruthStorage, https://nmts.me): open-source, end-to-end encrypted storage on the Walrus network. No fee to NMTS; you pay the network from your own wallet. For people and for their agents.",
5
5
  "license": "Apache-2.0",
6
6
  "publishConfig": {
@@ -49,6 +49,10 @@
49
49
  "types": "./dist/recovery.d.ts",
50
50
  "default": "./dist/recovery.js"
51
51
  },
52
+ "./share": {
53
+ "types": "./dist/sharing.d.ts",
54
+ "default": "./dist/sharing.js"
55
+ },
52
56
  "./host": {
53
57
  "types": "./dist/host.d.ts",
54
58
  "default": "./dist/host.js"
package/server.json CHANGED
@@ -6,13 +6,13 @@
6
6
  "url": "https://github.com/needmoretruth/nmts-cli",
7
7
  "source": "github"
8
8
  },
9
- "version": "0.56.0",
9
+ "version": "0.57.0",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "registryBaseUrl": "https://registry.npmjs.org",
14
14
  "identifier": "@needmoretruth/nmts-cli",
15
- "version": "0.56.0",
15
+ "version": "0.57.0",
16
16
  "transport": {
17
17
  "type": "stdio"
18
18
  },