@needmoretruth/nmts-cli 0.45.0 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (224) hide show
  1. package/AGENTS.md +2 -2
  2. package/CHANGELOG.md +61 -0
  3. package/README.ko.md +6 -3
  4. package/README.md +15 -3
  5. package/dist/api-advice.js +17 -2
  6. package/dist/api.d.ts +22 -0
  7. package/dist/api.js +49 -1
  8. package/dist/arg-options.d.ts +8 -0
  9. package/dist/args.js +7 -1
  10. package/dist/artifact-about.d.ts +1 -1
  11. package/dist/collision.d.ts +20 -3
  12. package/dist/collision.js +21 -3
  13. package/dist/commands/erase.js +1 -0
  14. package/dist/commands/handover.d.ts +13 -0
  15. package/dist/commands/handover.js +328 -0
  16. package/dist/commands/heavy-run.d.ts +59 -0
  17. package/dist/commands/heavy-run.js +247 -0
  18. package/dist/commands/heavy.d.ts +7 -0
  19. package/dist/commands/heavy.js +123 -0
  20. package/dist/commands/ls.d.ts +5 -0
  21. package/dist/commands/ls.js +9 -1
  22. package/dist/commands/public-code.d.ts +6 -0
  23. package/dist/commands/public-code.js +46 -0
  24. package/dist/commands/push-heavy.d.ts +6 -0
  25. package/dist/commands/push-heavy.js +128 -0
  26. package/dist/commands/push-tree.d.ts +24 -0
  27. package/dist/commands/push-tree.js +91 -0
  28. package/dist/commands/push.d.ts +4 -13
  29. package/dist/commands/push.js +7 -77
  30. package/dist/commands/put-heavy.d.ts +9 -0
  31. package/dist/commands/put-heavy.js +120 -0
  32. package/dist/commands/put-payer.d.ts +21 -0
  33. package/dist/commands/put-payer.js +24 -0
  34. package/dist/commands/put.d.ts +2 -2
  35. package/dist/commands/put.js +8 -7
  36. package/dist/commands/receive.js +3 -3
  37. package/dist/commands/s3.js +44 -10
  38. package/dist/crypto-surface.d.ts +8 -0
  39. package/dist/crypto-surface.js +3 -0
  40. package/dist/crypto.d.ts +3 -0
  41. package/dist/crypto.js +3 -0
  42. package/dist/download-part.d.ts +32 -1
  43. package/dist/download-part.js +95 -6
  44. package/dist/download-range.d.ts +19 -0
  45. package/dist/download-range.js +108 -0
  46. package/dist/download-sink.d.ts +15 -0
  47. package/dist/download.d.ts +14 -0
  48. package/dist/download.js +19 -4
  49. package/dist/handover.d.ts +44 -0
  50. package/dist/handover.js +199 -0
  51. package/dist/heavy-api.d.ts +36 -0
  52. package/dist/heavy-api.js +107 -0
  53. package/dist/heavy-copy.d.ts +72 -0
  54. package/dist/heavy-copy.js +108 -0
  55. package/dist/heavy-evm.d.ts +20 -0
  56. package/dist/heavy-evm.js +106 -0
  57. package/dist/heavy-self-pay.d.ts +92 -0
  58. package/dist/heavy-self-pay.js +167 -0
  59. package/dist/heavy-upload.d.ts +87 -0
  60. package/dist/heavy-upload.js +154 -0
  61. package/dist/heavy-wallet-pay.d.ts +39 -0
  62. package/dist/heavy-wallet-pay.js +73 -0
  63. package/dist/help-options.js +4 -2
  64. package/dist/help.js +16 -3
  65. package/dist/list-tier.d.ts +7 -0
  66. package/dist/list-tier.js +47 -0
  67. package/dist/main.js +12 -10
  68. package/dist/manifest-write.d.ts +4 -3
  69. package/dist/platform-sign.d.ts +4 -4
  70. package/dist/platform-sign.js +3 -3
  71. package/dist/portable.d.ts +15 -0
  72. package/dist/portable.js +11 -0
  73. package/dist/product.d.ts +1 -1
  74. package/dist/product.js +1 -1
  75. package/dist/recovery-build.js +16 -0
  76. package/dist/recovery-map-part.d.ts +82 -0
  77. package/dist/recovery-map-part.js +83 -0
  78. package/dist/recovery-map.d.ts +5 -40
  79. package/dist/recovery-map.js +18 -1
  80. package/dist/recovery-source.d.ts +3 -0
  81. package/dist/recovery-source.js +9 -0
  82. package/dist/risk.d.ts +30 -0
  83. package/dist/risk.js +23 -2
  84. package/dist/run-log.d.ts +1 -1
  85. package/dist/run-log.js +7 -1
  86. package/dist/s3/address.d.ts +20 -0
  87. package/dist/s3/address.js +97 -0
  88. package/dist/s3/answer.d.ts +48 -0
  89. package/dist/s3/answer.js +330 -0
  90. package/dist/s3/body-deframe.d.ts +49 -0
  91. package/dist/s3/body-deframe.js +264 -0
  92. package/dist/s3/body-measure.d.ts +13 -0
  93. package/dist/s3/body-measure.js +48 -0
  94. package/dist/s3/body-plan.d.ts +31 -0
  95. package/dist/s3/body-plan.js +159 -0
  96. package/dist/s3/body.d.ts +46 -0
  97. package/dist/s3/body.js +117 -0
  98. package/dist/s3/call.d.ts +36 -0
  99. package/dist/s3/call.js +42 -0
  100. package/dist/s3/checksum.d.ts +26 -0
  101. package/dist/s3/checksum.js +176 -0
  102. package/dist/s3/content-type.d.ts +3 -0
  103. package/dist/s3/content-type.js +49 -0
  104. package/dist/s3/contract.d.ts +91 -14
  105. package/dist/s3/drive-conditions.d.ts +47 -0
  106. package/dist/s3/drive-conditions.js +134 -0
  107. package/dist/s3/drive-key.d.ts +11 -0
  108. package/dist/s3/drive-key.js +58 -0
  109. package/dist/s3/drive-limits.d.ts +33 -0
  110. package/dist/s3/drive-limits.js +53 -0
  111. package/dist/s3/drive-lock.d.ts +11 -0
  112. package/dist/s3/drive-lock.js +47 -0
  113. package/dist/s3/drive-trashed-name.d.ts +13 -0
  114. package/dist/s3/drive-trashed-name.js +59 -0
  115. package/dist/s3/drive-write.d.ts +38 -0
  116. package/dist/s3/drive-write.js +258 -0
  117. package/dist/s3/drive.d.ts +59 -25
  118. package/dist/s3/drive.js +46 -77
  119. package/dist/s3/listing.d.ts +27 -1
  120. package/dist/s3/listing.js +62 -20
  121. package/dist/s3/long-answer.d.ts +12 -0
  122. package/dist/s3/long-answer.js +104 -0
  123. package/dist/s3/multipart-assemble.d.ts +17 -0
  124. package/dist/s3/multipart-assemble.js +68 -0
  125. package/dist/s3/multipart-sweep.d.ts +15 -0
  126. package/dist/s3/multipart-sweep.js +87 -0
  127. package/dist/s3/multipart-view.d.ts +45 -0
  128. package/dist/s3/multipart-view.js +232 -0
  129. package/dist/s3/multipart.d.ts +26 -19
  130. package/dist/s3/multipart.js +193 -78
  131. package/dist/s3/object-read.d.ts +17 -0
  132. package/dist/s3/object-read.js +127 -0
  133. package/dist/s3/object-write.d.ts +35 -0
  134. package/dist/s3/object-write.js +198 -0
  135. package/dist/s3/range.d.ts +14 -0
  136. package/dist/s3/range.js +80 -0
  137. package/dist/s3/response-sink.d.ts +12 -2
  138. package/dist/s3/response-sink.js +71 -7
  139. package/dist/s3/routes.d.ts +0 -1
  140. package/dist/s3/routes.js +242 -217
  141. package/dist/s3/same-file.d.ts +4 -1
  142. package/dist/s3/same-file.js +12 -3
  143. package/dist/s3/server.d.ts +54 -4
  144. package/dist/s3/server.js +174 -14
  145. package/dist/s3/sigv4-canonical.d.ts +91 -0
  146. package/dist/s3/sigv4-canonical.js +148 -0
  147. package/dist/s3/sigv4-presigned.d.ts +13 -0
  148. package/dist/s3/sigv4-presigned.js +82 -0
  149. package/dist/s3/sigv4.d.ts +26 -27
  150. package/dist/s3/sigv4.js +137 -102
  151. package/dist/s3/spool.d.ts +37 -0
  152. package/dist/s3/spool.js +104 -0
  153. package/dist/s3/staging.d.ts +90 -7
  154. package/dist/s3/staging.js +97 -66
  155. package/dist/s3/xml-multipart.d.ts +38 -0
  156. package/dist/s3/xml-multipart.js +47 -0
  157. package/dist/s3/xml-read.d.ts +28 -0
  158. package/dist/s3/xml-read.js +235 -0
  159. package/dist/s3/xml.d.ts +45 -2
  160. package/dist/s3/xml.js +72 -13
  161. package/dist/s3-gateway.d.ts +11 -5
  162. package/dist/s3-gateway.js +5 -2
  163. package/dist/seal.d.ts +1 -1
  164. package/dist/share.d.ts +5 -0
  165. package/dist/share.js +1 -1
  166. package/dist/shared/lib/api/types-heavy.d.ts +167 -0
  167. package/dist/shared/lib/api/types-heavy.js +60 -0
  168. package/dist/shared/lib/drive/rebuild-verify.js +1 -0
  169. package/dist/shared/lib/filecoin/providers.d.ts +25 -0
  170. package/dist/shared/lib/filecoin/providers.js +58 -0
  171. package/dist/shared/lib/heavy/download.d.ts +48 -0
  172. package/dist/shared/lib/heavy/download.js +116 -0
  173. package/dist/shared/lib/heavy/order-plan.d.ts +77 -0
  174. package/dist/shared/lib/heavy/order-plan.js +83 -0
  175. package/dist/shared/lib/heavy/order-runner.d.ts +9 -0
  176. package/dist/shared/lib/heavy/order-runner.js +300 -0
  177. package/dist/shared/lib/heavy/order-types.d.ts +90 -0
  178. package/dist/shared/lib/heavy/order-types.js +6 -0
  179. package/dist/shared/lib/heavy/order-wire.d.ts +55 -0
  180. package/dist/shared/lib/heavy/order-wire.js +113 -0
  181. package/dist/shared/lib/heavy/piece-cid.d.ts +24 -0
  182. package/dist/shared/lib/heavy/piece-cid.js +55 -0
  183. package/dist/shared/lib/heavy/sp-upload.d.ts +37 -0
  184. package/dist/shared/lib/heavy/sp-upload.js +112 -0
  185. package/dist/shared/lib/heavy/synapse-piece.d.ts +1 -0
  186. package/dist/shared/lib/heavy/synapse-piece.js +8 -0
  187. package/dist/shared/lib/share/handover-format.d.ts +129 -0
  188. package/dist/shared/lib/share/handover-format.js +323 -0
  189. package/dist/shared/lib/share/shared-file-info.js +1 -0
  190. package/dist/shared/lib/storage-network.d.ts +4 -4
  191. package/dist/shared/lib/storage-network.js +7 -7
  192. package/dist/shared/lib/storage-tier.d.ts +28 -0
  193. package/dist/shared/lib/storage-tier.js +63 -0
  194. package/dist/shared/lib/wallet/send-rules.js +1 -0
  195. package/dist/upload-file.d.ts +8 -0
  196. package/dist/upload-file.js +57 -25
  197. package/dist/upload-price-node.d.ts +3 -0
  198. package/dist/upload-price-node.js +3 -6
  199. package/dist/upload-price.d.ts +10 -0
  200. package/dist/upload-price.js +13 -1
  201. package/dist/upload-run.d.ts +80 -0
  202. package/dist/upload-run.js +173 -0
  203. package/dist/upload-steps.js +15 -4
  204. package/dist/upload-store.d.ts +15 -6
  205. package/dist/upload-store.js +6 -0
  206. package/dist/upload-wallet-put.d.ts +9 -4
  207. package/dist/upload-wallet-put.js +16 -6
  208. package/dist/upload-wallet.js +4 -0
  209. package/dist/upload-wire.d.ts +25 -0
  210. package/dist/upload-wire.js +20 -1
  211. package/dist/upload.js +28 -13
  212. package/dist/wallet-sign.js +2 -2
  213. package/docs/commands/handover.md +38 -0
  214. package/docs/commands/heavy.md +35 -0
  215. package/docs/commands/public-code.md +7 -0
  216. package/docs/commands/push.md +4 -1
  217. package/docs/commands/put.md +15 -1
  218. package/docs/commands/share.md +3 -1
  219. package/package.json +5 -2
  220. package/server.json +2 -2
  221. package/vendor/nmts-crypto/nmts_crypto_wasm.d.ts +17 -1
  222. package/vendor/nmts-crypto/nmts_crypto_wasm.js +28 -0
  223. package/vendor/nmts-crypto/nmts_crypto_wasm_bg.wasm +0 -0
  224. package/vendor/nmts-crypto/nmts_crypto_wasm_bg.wasm.d.ts +2 -1
@@ -0,0 +1,19 @@
1
+ import type { CryptoGlue } from "./crypto.ts";
2
+ import { type PartView } from "./download-part.ts";
3
+ import type { FetchedFile } from "./download.ts";
4
+ import type { PlaintextSink } from "./download-sink.ts";
5
+ import type { ReadOptions } from "./walrus.ts";
6
+ /** The bytes a sink keeps, when it keeps only some of the file and can be told what was left out. */
7
+ export declare function windowOf(sink: PlaintextSink): {
8
+ start: number;
9
+ end: number;
10
+ } | null;
11
+ /**
12
+ * Deliver `window` of the file to `sink`, reading only the parts it falls in.
13
+ *
14
+ * ⛔ THE SINK IS COMMITTED IN ONE PLACE AND ABANDONED ON EVERY OTHER WAY OUT, as in `download.ts`.
15
+ */
16
+ export declare function collectWindow(crypt: CryptoGlue, ordered: readonly PartView[], dek: Uint8Array, expected: Uint8Array | null, size: number, chain: string, read: ReadOptions | undefined, sink: PlaintextSink, window: {
17
+ start: number;
18
+ end: number;
19
+ }): Promise<FetchedFile>;
@@ -0,0 +1,108 @@
1
+ // Reading part of a file: from the stored part a range starts in, not from the file's first byte.
2
+ //
3
+ // ⛔ WHY THIS EXISTS. An S3 client fetches a large object as many ranges at once — eight MiB each,
4
+ // ten at a time — and a reader that decrypted every range from the file's first byte made a 1 GB
5
+ // file cost about 64 GB of reads, with the late ranges timing out. Every part of a file is its own
6
+ // sealed stream, so the parts wholly before a range can be left out: their headers (72 bytes
7
+ // each) say how long they are, and the range begins in the part where those lengths run out.
8
+ // Inside that part the read starts at the part's first chunk and stops at the chunk the range
9
+ // ends in, because the sequential opener is the one this tool's engine surface offers.
10
+ //
11
+ // ⛔ WHAT A RANGE IS CHECKED AGAINST. Every chunk it keeps is authenticated under the file's key.
12
+ // Every part it touches — the ones it leaves out included — has its header's key commitment
13
+ // checked and its sealed position compared with the position it is used in, so authentic bytes
14
+ // cannot be answered from the wrong place. The whole-file digest needs every byte from the first,
15
+ // so it is checked only when nothing was left out and the range runs to the file's end; that is
16
+ // the one range the whole-file path checked before, and it still is.
17
+ //
18
+ // ⚠ ONLY FOR A SINK THAT NAMES A WINDOW AND CAN BE TOLD WHAT WAS LEFT OUT (`PlaintextSink.window`
19
+ // with `skip`). Every other sink goes through `download.ts` exactly as before.
20
+ import { sha256 } from "@noble/hashes/sha2.js";
21
+ import { checkedHeader, fetchPart, openPart } from "./download-part.js";
22
+ import { NmtsError } from "./errors.js";
23
+ import { NCF3_SHAPE } from "./seal.js";
24
+ /** The bytes a sink keeps, when it keeps only some of the file and can be told what was left out. */
25
+ export function windowOf(sink) {
26
+ const window = sink.window ?? null;
27
+ return window !== null && sink.skip !== undefined ? window : null;
28
+ }
29
+ /**
30
+ * Where a read of one part may stop: just past the chunk holding its last wanted byte, or null for
31
+ * the whole part.
32
+ */
33
+ function prefixEnd(header, lastWanted) {
34
+ const step = header.chunkSize + NCF3_SHAPE.tagLen;
35
+ const chunks = header.declared === 0 ? 1 : Math.ceil(header.declared / header.chunkSize);
36
+ const lastChunk = Math.floor(lastWanted / header.chunkSize);
37
+ return lastChunk >= chunks - 1 ? null : NCF3_SHAPE.headerLen + (lastChunk + 1) * step;
38
+ }
39
+ function disagree(what) {
40
+ return new NmtsError(what, {
41
+ nextStep: "The file list and the stored parts do not agree. Nothing more was written.",
42
+ });
43
+ }
44
+ /**
45
+ * Deliver `window` of the file to `sink`, reading only the parts it falls in.
46
+ *
47
+ * ⛔ THE SINK IS COMMITTED IN ONE PLACE AND ABANDONED ON EVERY OTHER WAY OUT, as in `download.ts`.
48
+ */
49
+ export async function collectWindow(crypt, ordered, dek, expected, size, chain, read, sink, window) {
50
+ const hasher = sha256.create();
51
+ // ⚠ True until a part is left out: the digest is of every byte, and then it can no longer be had.
52
+ let whole = true;
53
+ let at = 0;
54
+ const total = ordered.length;
55
+ try {
56
+ sink.expect(size);
57
+ for (let index = 0; index < total && at <= window.end; index += 1) {
58
+ const part = ordered[index];
59
+ if (part === undefined)
60
+ continue;
61
+ const isLast = index === total - 1;
62
+ const headerBytes = await fetchPart(part, chain, { ...(read ?? {}), range: { start: 0, end: NCF3_SHAPE.headerLen } });
63
+ const header = checkedHeader(crypt, dek, part, headerBytes, { index, total });
64
+ // Every part but the last contributes all it declares; the last is what the file has left.
65
+ const contributes = isLast ? size - at : header.declared;
66
+ if (contributes < 0 || contributes > header.declared) {
67
+ throw disagree(`Part ${part.part_index} holds ${header.declared} bytes and would have to give ${contributes}.`);
68
+ }
69
+ if (!isLast && at + contributes <= window.start) {
70
+ sink.skip?.(contributes);
71
+ whole = false;
72
+ at += contributes;
73
+ continue;
74
+ }
75
+ const lastWanted = Math.min(window.end, at + contributes - 1) - at;
76
+ const end = contributes === 0 ? null : prefixEnd(header, lastWanted);
77
+ const sealed = await fetchPart(part, chain, end === null ? read : { ...(read ?? {}), range: { start: 0, end } });
78
+ at += await openPart(crypt, dek, part, sealed, { index, total }, size - at, async (body) => {
79
+ if (whole)
80
+ hasher.update(body);
81
+ await sink.write(body);
82
+ }, end !== null);
83
+ if (end !== null)
84
+ break;
85
+ }
86
+ if (at <= window.end)
87
+ throw disagree(`The stored parts end at byte ${at}, before the range does.`);
88
+ const checked = whole && at === size && expected !== null;
89
+ if (checked) {
90
+ const got = hasher.digest();
91
+ if (expected.length !== got.length || !expected.every((b, i) => b === got[i])) {
92
+ throw new NmtsError("The file came back whole but does not match the hash this account recorded for it.", {
93
+ nextStep: "The bytes themselves are not the ones that were uploaded.",
94
+ });
95
+ }
96
+ }
97
+ const delivered = await sink.commit();
98
+ return { byteCount: size, partCount: total, contentHashChecked: checked, delivered };
99
+ }
100
+ catch (failure) {
101
+ await sink.abandon();
102
+ throw failure;
103
+ }
104
+ finally {
105
+ dek.fill(0);
106
+ expected?.fill(0);
107
+ }
108
+ }
@@ -25,4 +25,19 @@ export interface PlaintextSink {
25
25
  commit(): Promise<boolean>;
26
26
  /** Something did not check out: leave nothing behind. Never throws. */
27
27
  abandon(): Promise<void>;
28
+ /**
29
+ * A destination that keeps only SOME of the file — an HTTP range — says which bytes, inclusive.
30
+ * Absent (or null) is the whole file, which is every sink but one.
31
+ *
32
+ * ⚠ WITH `skip`, AND ONLY WITH IT, a reader may leave out whole stored parts that end before
33
+ * `start`, and stop reading once `end` is written: a late range then costs the parts it falls
34
+ * in rather than every part before it. A sink that names a window must still cut what it is
35
+ * given, because a reader is free to hand it everything.
36
+ */
37
+ readonly window?: {
38
+ readonly start: number;
39
+ readonly end: number;
40
+ } | null | undefined;
41
+ /** Told, before the next write, that the reader left out this many bytes of the file. */
42
+ skip?(bytes: number): void;
28
43
  }
@@ -1,3 +1,4 @@
1
+ import { type PartView } from "./download-part.ts";
1
2
  import type { PlaintextSink } from "./download-sink.ts";
2
3
  import type { ReadOptions } from "./walrus.ts";
3
4
  export interface FetchedFile {
@@ -76,4 +77,17 @@ export declare function fetchWithKey(input: {
76
77
  /** Where the plaintext goes as it is decrypted. Committed only after the whole file checks out. */
77
78
  sink: PlaintextSink;
78
79
  }): Promise<FetchedFile>;
80
+ /**
81
+ * Fetch, decrypt and verify a file whose key is open AND whose pieces are already known — a
82
+ * handover file carries them sealed, so the NMTS server is asked nothing at all.
83
+ */
84
+ export declare function fetchKnownParts(input: {
85
+ parts: readonly PartView[];
86
+ size: number;
87
+ dek: Uint8Array;
88
+ expected: Uint8Array;
89
+ chain: string;
90
+ read?: ReadOptions;
91
+ sink: PlaintextSink;
92
+ }): Promise<FetchedFile>;
79
93
  export declare function fetchFile(input: FetchInput): Promise<FetchedFile>;
package/dist/download.js CHANGED
@@ -31,6 +31,7 @@ import { fromBase64Url, utf8 } from "./bytes.js";
31
31
  import { request } from "./api.js";
32
32
  import { AAD, DERIVED, loadCrypto } from "./crypto.js";
33
33
  import { asParts, fetchPart, openPart } from "./download-part.js";
34
+ import { collectWindow, windowOf } from "./download-range.js";
34
35
  import { NmtsError } from "./errors.js";
35
36
  /**
36
37
  * Fetch, decrypt and verify one file.
@@ -60,8 +61,22 @@ export async function fetchWithKey(input) {
60
61
  const crypt = await loadCrypto();
61
62
  const dek = input.dek;
62
63
  const expected = input.expected;
64
+ // ⚠ A sink that keeps only a window of the file is read from the part the window starts in
65
+ // (`download-range.ts`); every other sink takes the whole-file path below, unchanged.
66
+ const window = windowOf(input.sink);
67
+ if (window !== null) {
68
+ return collectWindow(crypt, ordered, dek, expected, input.size, input.chain, input.read, input.sink, window);
69
+ }
63
70
  return collect(crypt, ordered, dek, expected, input.size, input.chain, input.read, input.sink);
64
71
  }
72
+ /**
73
+ * Fetch, decrypt and verify a file whose key is open AND whose pieces are already known — a
74
+ * handover file carries them sealed, so the NMTS server is asked nothing at all.
75
+ */
76
+ export async function fetchKnownParts(input) {
77
+ const crypt = await loadCrypto();
78
+ return collect(crypt, input.parts, input.dek, input.expected, input.size, input.chain, input.read, input.sink);
79
+ }
65
80
  export async function fetchFile(input) {
66
81
  const crypt = await loadCrypto();
67
82
  const [from, to] = DERIVED.dataKey;
@@ -127,14 +142,14 @@ async function collect(crypt, ordered, dek, expected, size, chain, read, sink) {
127
142
  if (part === undefined)
128
143
  continue;
129
144
  const sealed = await fetchPart(part, chain, read);
130
- remaining -= await openPart(crypt, dek, part, sealed, i === ordered.length - 1, remaining, async (body) => {
145
+ remaining -= await openPart(crypt, dek, part, sealed, { index: i, total: ordered.length }, remaining, async (body) => {
131
146
  hasher.update(body);
132
147
  await sink.write(body);
133
148
  });
134
149
  }
135
150
  if (remaining !== 0) {
136
- throw new NmtsError(`The stored parts are ${remaining} bytes short of the file this list describes.`, {
137
- nextStep: "Nothing was written. Open the account in a browser and compare before uploading anything again.",
151
+ throw new NmtsError(`The stored parts are ${remaining} bytes short of the file's recorded length.`, {
152
+ nextStep: "Nothing was written. The stored bytes and the recorded length describe different files.",
138
153
  });
139
154
  }
140
155
  if (expected !== null) {
@@ -142,7 +157,7 @@ async function collect(crypt, ordered, dek, expected, size, chain, read, sink) {
142
157
  const same = expected.length === got.length && expected.every((b, i) => b === got[i]);
143
158
  expected.fill(0);
144
159
  if (!same) {
145
- throw new NmtsError("The file came back whole but does not match the hash this account recorded for it.", {
160
+ throw new NmtsError("The file came back whole but does not match the hash recorded for it.", {
146
161
  nextStep: "Nothing was written. Every part decrypted, so this is not a wrong key — the bytes " +
147
162
  "themselves are not the ones that were uploaded.",
148
163
  });
@@ -0,0 +1,44 @@
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";
4
+ export declare function isHandoverNetwork(value: string): value is HandoverNetwork;
5
+ /** Refuse a name the handover file cannot carry, before any work is done. */
6
+ export declare function checkHandoverName(name: string, size: number, network: HandoverNetwork): void;
7
+ /** Build a handover file's text. The caller holds the file key and the digest, and wipes them. */
8
+ export declare function makeHandoverText(crypt: CryptoGlue, input: {
9
+ keys: ShareKeys;
10
+ recipientIdentity: Uint8Array;
11
+ recipientAddress: Uint8Array;
12
+ dek: Uint8Array;
13
+ itemId: string;
14
+ name: string;
15
+ size: number;
16
+ digest: Uint8Array;
17
+ parts: readonly HandoverPart[];
18
+ network: HandoverNetwork;
19
+ }): string;
20
+ /** What an opened handover file says. `dek` and `digest` are the caller's to wipe. */
21
+ export interface OpenedHandover {
22
+ name: string;
23
+ size: number;
24
+ /** The sender's public code, readable form — set only because the envelope opened. */
25
+ sender: string;
26
+ parts: HandoverPart[];
27
+ /** Earliest end epoch recorded when the file was made (exclusive); 0 when unknown. A hint. */
28
+ expiryEpoch: number;
29
+ dek: Uint8Array;
30
+ digest: Uint8Array;
31
+ }
32
+ /** Open a handover file's text with this account's keys. */
33
+ export declare function openHandoverText(crypt: CryptoGlue, keys: ShareKeys, text: string, network: HandoverNetwork): OpenedHandover;
34
+ /** This account's public code file. */
35
+ export declare function publicCodeFileText(keys: ShareKeys): string;
36
+ /**
37
+ * Read a recipient's public code file. Returns only when the identity inside really fingerprints to
38
+ * the code the file names, so what is sealed to is what the person was told.
39
+ */
40
+ export declare function readPublicCodeFileText(crypt: CryptoGlue, text: string): {
41
+ identity: Uint8Array;
42
+ address: Uint8Array;
43
+ display: string;
44
+ };
@@ -0,0 +1,199 @@
1
+ // Handing one file to one account OUTSIDE NMTS: a share that travels as a file instead of a server
2
+ // row (NCF-3 §5.6), and the public code file that lets a sender make one without asking the server
3
+ // for the recipient's identity (§5.7).
4
+ //
5
+ // ⛔ NOTHING NEW IS BUILT HERE. The envelope and the sealed digest come from `sealShare` — the same
6
+ // bytes a built-in share posts. The name document is the share's, extended by two values, and the
7
+ // only extra sealed value is the list of stored pieces, under the file's own key with its own
8
+ // label. The text around them is the shared format module, byte for byte the one the browser
9
+ // uses, so both programs accept and refuse the same files.
10
+ //
11
+ // ⛔ THE PARTS LIST AND THE NETWORK ARE BOUND THROUGH THE NAME. The parts are sealed first, and
12
+ // their SHA-256 and the network go into the name document, which the envelope covers. A reader
13
+ // compares both after opening the name; without that, anyone holding the file key could hand the
14
+ // recipient a list of their own choosing under the real sender's name.
15
+ //
16
+ // ⛔ OPENING ONE ASKS THE NMTS SERVER NOTHING. Everything the recipient needs is in the file; the
17
+ // pieces come from Walrus aggregators.
18
+ //
19
+ // ⛔ THE SENDER IS NAMED ONLY AFTER THE ENVELOPE OPENED, as for a received share: the file names
20
+ // its sender twice (the identity it carries and the envelope's first 16 bytes), the two must
21
+ // agree, and the unwrap then proves that sender made it.
22
+ import { createHash } from "node:crypto";
23
+ import { AAD } from "./crypto.js";
24
+ import { NmtsError } from "./errors.js";
25
+ import { addressFromTyped, identityMatches, sealShare } from "./share.js";
26
+ import { decodeHandover, decodeHandoverName, decodePartsList, decodePublicCodeFile, earliestExpiry, encodeHandover, encodeHandoverName, encodePartsList, encodePublicCodeFile, handoverNameFits, HandoverFormatError, } from "./shared/lib/share/handover-format.js";
27
+ const encoder = new TextEncoder();
28
+ const b64 = (bytes) => Buffer.from(bytes).toString("base64url");
29
+ const bytesOf = (text) => new Uint8Array(Buffer.from(text, "base64url"));
30
+ const sha256 = (bytes) => createHash("sha256").update(bytes).digest("base64url");
31
+ /** A stand-in digest of the right length, to ask whether a name fits before anything is sealed. */
32
+ const DIGEST_PLACEHOLDER = "A".repeat(43);
33
+ export function isHandoverNetwork(value) {
34
+ return value === "mainnet" || value === "testnet";
35
+ }
36
+ /** Refuse a name the handover file cannot carry, before any work is done. */
37
+ export function checkHandoverName(name, size, network) {
38
+ let fits = false;
39
+ try {
40
+ fits = handoverNameFits(encodeHandoverName({ name, size, network, partsSha256: DIGEST_PLACEHOLDER }));
41
+ }
42
+ catch {
43
+ fits = false;
44
+ }
45
+ if (!fits) {
46
+ throw new NmtsError("This file's name is too long to hand over.", {
47
+ exitCode: 2,
48
+ nextStep: "Nothing was written. Rename it with `nmts mv`, then try again.",
49
+ });
50
+ }
51
+ }
52
+ /** Build a handover file's text. The caller holds the file key and the digest, and wipes them. */
53
+ export function makeHandoverText(crypt, input) {
54
+ checkHandoverName(input.name, input.size, input.network);
55
+ try {
56
+ // The engine lowercases the id before binding it; the file carries that same spelling.
57
+ const item = input.itemId.toLowerCase();
58
+ // ⚠ ORDER: parts first — their digest goes into the name, and the name into the envelope.
59
+ const parts = crypt.envelope_seal(input.dek, encoder.encode(AAD.handoverParts), encoder.encode(encodePartsList(input.parts)));
60
+ const nameDocument = encodeHandoverName({
61
+ name: input.name,
62
+ size: input.size,
63
+ network: input.network,
64
+ partsSha256: sha256(parts),
65
+ });
66
+ const sealed = sealShare(crypt, { ...input, itemId: item, nameDocument });
67
+ return encodeHandover({
68
+ network: input.network,
69
+ item,
70
+ sender: b64(input.keys.identity),
71
+ envelope: sealed.dek_share_ct,
72
+ name: sealed.name_share_ct,
73
+ hash: sealed.content_hash_share_ct,
74
+ parts: b64(parts),
75
+ });
76
+ }
77
+ catch (error) {
78
+ if (error instanceof NmtsError)
79
+ throw error;
80
+ const field = error instanceof HandoverFormatError && error.field !== null ? ` (${error.field})` : "";
81
+ throw new NmtsError(`Could not make the handover file${field}.`, {
82
+ exitCode: 1,
83
+ nextStep: "Nothing was written. The file's stored pieces are not in a form a handover can carry.",
84
+ });
85
+ }
86
+ }
87
+ /** Open a handover file's text with this account's keys. */
88
+ export function openHandoverText(crypt, keys, text, network) {
89
+ let file;
90
+ try {
91
+ file = decodeHandover(text, network);
92
+ }
93
+ catch (error) {
94
+ throw readRefusal(error, network);
95
+ }
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
+ const senderIdentity = bytesOf(file.sender);
101
+ const envelope = bytesOf(file.envelope);
102
+ let claimed;
103
+ try {
104
+ claimed = crypt.share_claimed_sender(envelope);
105
+ }
106
+ catch {
107
+ throw damaged;
108
+ }
109
+ 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
+ }
124
+ 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
+ return {
131
+ name: named.name,
132
+ size: named.size,
133
+ sender: crypt.share_address_display(claimed),
134
+ parts,
135
+ expiryEpoch: earliestExpiry(parts),
136
+ dek,
137
+ digest,
138
+ };
139
+ }
140
+ catch {
141
+ dek.fill(0);
142
+ throw damaged;
143
+ }
144
+ }
145
+ /** This account's public code file. */
146
+ export function publicCodeFileText(keys) {
147
+ return encodePublicCodeFile({ code: keys.display, identity: b64(keys.identity) });
148
+ }
149
+ /**
150
+ * Read a recipient's public code file. Returns only when the identity inside really fingerprints to
151
+ * the code the file names, so what is sealed to is what the person was told.
152
+ */
153
+ export function readPublicCodeFileText(crypt, text) {
154
+ let file;
155
+ try {
156
+ file = decodePublicCodeFile(text);
157
+ }
158
+ catch (error) {
159
+ if (error instanceof HandoverFormatError && error.problem === "unknown-version") {
160
+ throw new NmtsError("This public code file is from a newer version of NMTS.", {
161
+ exitCode: 4,
162
+ nextStep: "Nothing was written. Update this tool and try again.",
163
+ });
164
+ }
165
+ throw new NmtsError("This is not a valid public code file.", { exitCode: 2, nextStep: "Nothing was written." });
166
+ }
167
+ const address = addressFromTyped(crypt, file.code);
168
+ const identity = bytesOf(file.identity);
169
+ if (!identityMatches(crypt, identity, address)) {
170
+ throw new NmtsError("The identity in this public code file does not belong to the public code it names.", {
171
+ exitCode: 1,
172
+ nextStep: "Nothing was written. Sealing to it would hand the file to somebody else; ask the recipient for their file again.",
173
+ });
174
+ }
175
+ return { identity, address, display: crypt.share_address_display(address) };
176
+ }
177
+ /** A handover file the format module refused, said the way §5.6 sorts it. */
178
+ function readRefusal(error, network) {
179
+ const problem = error instanceof HandoverFormatError ? error.problem : "not-json";
180
+ switch (problem) {
181
+ case "unknown-version":
182
+ return new NmtsError("This handover file is from a newer version of NMTS.", {
183
+ exitCode: 4,
184
+ nextStep: "Nothing was written. Update this tool and try again.",
185
+ });
186
+ case "other-network":
187
+ return new NmtsError(`This handover file was made on the other network; this tool is on ${network}.`, {
188
+ exitCode: 4,
189
+ nextStep: "Nothing was written. Open it with --network set to the network it was made on.",
190
+ });
191
+ case "bad-field":
192
+ return new NmtsError("This handover file is damaged: a field was cut or changed.", {
193
+ exitCode: 1,
194
+ nextStep: "Nothing was written. Ask the sender to send it again.",
195
+ });
196
+ default:
197
+ return new NmtsError("This is not a handover file.", { exitCode: 2, nextStep: "Nothing was written." });
198
+ }
199
+ }
@@ -0,0 +1,36 @@
1
+ import { NmtsError } from "./errors.ts";
2
+ import type { HeavyCopy, HeavyOrderApi, HeavyPartCommit } from "./shared/lib/api/types-heavy.ts";
3
+ /** A line that dropped, in the shape the order runner retries. */
4
+ export declare class HeavyTransportError extends NmtsError {
5
+ readonly code = "NETWORK";
6
+ constructor(cause: NmtsError);
7
+ }
8
+ /** The order routes, bound to one server and one credential. */
9
+ export declare function createHeavyApi(server: string, bearer: string): HeavyOrderApi;
10
+ /** A self-paid Heavy part: no order, the person's own EVM wallet paid (`owner_kind` 0). */
11
+ export interface HeavySelfPaidPart {
12
+ part_index: number;
13
+ storage_kind: 0;
14
+ network: 1;
15
+ blob_id: string;
16
+ sealed_len: number;
17
+ owner_kind: 0;
18
+ expiry_epoch: number;
19
+ copies: HeavyCopy[];
20
+ }
21
+ /**
22
+ * `POST /v1/items` for one Heavy file.
23
+ *
24
+ * ⛔ SAFE TO ASK AGAIN: the idempotency key names this file of this upload, so a commit whose answer
25
+ * was lost is recognised rather than making a second file out of the same stored pieces.
26
+ */
27
+ export declare function commitHeavyItem(input: {
28
+ server: string;
29
+ bearer: string;
30
+ idempotencyKey: string;
31
+ dekWrapped: string;
32
+ contentHashCt: string;
33
+ parts: readonly (HeavyPartCommit | HeavySelfPaidPart)[];
34
+ /** Self-paid only: the `0x` EVM address that paid. */
35
+ paidBy?: string | undefined;
36
+ }): Promise<string>;
@@ -0,0 +1,107 @@
1
+ // NMTS Heavy's order routes over this package's one request function — the `HeavyOrderApi` the
2
+ // shared order runner (`shared/lib/heavy/order-runner.ts`) drives — and the commit of a finished
3
+ // Heavy file.
4
+ //
5
+ // ⛔ THE RUNNER READS ERRORS BY SHAPE: a string `code` and a number `status`. A server refusal
6
+ // already carries both (`ServerError`). A line that dropped does not — `request` throws a plain
7
+ // `NmtsError` for it — so it is handed on here with the transport word `NETWORK`, which is the
8
+ // one the runner asks again on. Everything else passes through untouched, so a refusal the
9
+ // server explained still prints the way every other refusal does.
10
+ //
11
+ // ⛔ NO `node:` IMPORT. The SDK's browser entry reaches this file through `portable.ts`.
12
+ import { HttpError, request, ServerError } from "./api.js";
13
+ import { NmtsError } from "./errors.js";
14
+ import { isRecord } from "./guards.js";
15
+ import { HEAVY_COPY } from "./heavy-copy.js";
16
+ /** How long a route that reaches the chain service gets. The same as the credit rail's. */
17
+ const CHAIN_TIMEOUT_MS = 120_000;
18
+ /** A line that dropped, in the shape the order runner retries. */
19
+ export class HeavyTransportError extends NmtsError {
20
+ code = "NETWORK";
21
+ constructor(cause) {
22
+ super(cause.message, { exitCode: cause.exitCode, nextStep: cause.nextStep });
23
+ this.name = "HeavyTransportError";
24
+ }
25
+ }
26
+ async function call(fn, read) {
27
+ let value;
28
+ try {
29
+ value = await fn();
30
+ }
31
+ catch (error) {
32
+ if (error instanceof ServerError || error instanceof HttpError || !(error instanceof NmtsError))
33
+ throw error;
34
+ throw new HeavyTransportError(error);
35
+ }
36
+ return read(value);
37
+ }
38
+ /**
39
+ * The answer as the contract types it.
40
+ *
41
+ * ⚠ CHECKED FOR BEING AN OBJECT AND NOTHING MORE HERE: the runner checks every field it acts on
42
+ * (the slots it opened, the https address it uploads to, each copy) before it acts on it, and
43
+ * says `bad_answer` when one is missing. Two checks of one answer would be two answers to what a
44
+ * well-formed one is.
45
+ */
46
+ function answer(value) {
47
+ if (!isRecord(value))
48
+ throw new NmtsError("The server's answer about the Heavy order was not an object.");
49
+ // ⚠ The one assertion in this file, for the reason above: the runner reads each field by shape.
50
+ return value;
51
+ }
52
+ /** The order routes, bound to one server and one credential. */
53
+ export function createHeavyApi(server, bearer) {
54
+ const order = (id) => encodeURIComponent(id);
55
+ return {
56
+ createOrder: (body, options) => call(() => request(server, "/v1/heavy/orders", { method: "POST", token: bearer, body, timeoutMs: CHAIN_TIMEOUT_MS, signal: options?.signal }), (answer)),
57
+ getOrder: (id, options) => call(() => request(server, `/v1/heavy/orders/${order(id)}`, { token: bearer, signal: options?.signal }), (answer)),
58
+ targetSlot: (id, slot, body, options) => call(() => request(server, `/v1/heavy/orders/${order(id)}/slots/${slot}/target`, {
59
+ method: "POST",
60
+ token: bearer,
61
+ body,
62
+ timeoutMs: CHAIN_TIMEOUT_MS,
63
+ signal: options?.signal,
64
+ }), (answer)),
65
+ slotUploaded: (id, slot, options) => call(() => request(server, `/v1/heavy/orders/${order(id)}/slots/${slot}/uploaded`, {
66
+ method: "POST",
67
+ token: bearer,
68
+ body: {},
69
+ timeoutMs: CHAIN_TIMEOUT_MS,
70
+ signal: options?.signal,
71
+ }), (answer)),
72
+ markPaid: (id, body, options) => call(() => request(server, `/v1/heavy/orders/${order(id)}/paid`, {
73
+ method: "POST",
74
+ token: bearer,
75
+ body,
76
+ timeoutMs: CHAIN_TIMEOUT_MS,
77
+ signal: options?.signal,
78
+ }), (answer)),
79
+ };
80
+ }
81
+ /**
82
+ * `POST /v1/items` for one Heavy file.
83
+ *
84
+ * ⛔ SAFE TO ASK AGAIN: the idempotency key names this file of this upload, so a commit whose answer
85
+ * was lost is recognised rather than making a second file out of the same stored pieces.
86
+ */
87
+ export async function commitHeavyItem(input) {
88
+ const reply = await request(input.server, "/v1/items", {
89
+ method: "POST",
90
+ token: input.bearer,
91
+ idempotencyKey: input.idempotencyKey,
92
+ timeoutMs: CHAIN_TIMEOUT_MS,
93
+ body: {
94
+ size: input.parts.reduce((sum, part) => sum + part.sealed_len, 0),
95
+ dek_wrapped: input.dekWrapped,
96
+ content_hash_ct: input.contentHashCt,
97
+ visibility: 0,
98
+ parts: input.parts,
99
+ ...(input.paidBy === undefined ? {} : { paid_by: input.paidBy }),
100
+ },
101
+ });
102
+ const id = isRecord(reply) ? reply["id"] : undefined;
103
+ if (typeof id !== "string" || id === "") {
104
+ throw new NmtsError(HEAVY_COPY.commitNoId, { nextStep: HEAVY_COPY.commitNoIdNext });
105
+ }
106
+ return id;
107
+ }