@needmoretruth/nmts-cli 0.45.0 → 0.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (252) hide show
  1. package/AGENTS.md +8 -8
  2. package/CHANGELOG.md +78 -0
  3. package/README.ko.md +6 -3
  4. package/README.md +31 -11
  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 +19 -1
  9. package/dist/args.js +14 -2
  10. package/dist/artifact-about.d.ts +1 -1
  11. package/dist/autonomy.js +3 -3
  12. package/dist/collision.d.ts +20 -3
  13. package/dist/collision.js +21 -3
  14. package/dist/commands/erase.js +1 -0
  15. package/dist/commands/handover.d.ts +15 -0
  16. package/dist/commands/handover.js +376 -0
  17. package/dist/commands/heavy-run.d.ts +59 -0
  18. package/dist/commands/heavy-run.js +247 -0
  19. package/dist/commands/heavy.d.ts +7 -0
  20. package/dist/commands/heavy.js +123 -0
  21. package/dist/commands/link.d.ts +12 -0
  22. package/dist/commands/link.js +121 -0
  23. package/dist/commands/ls.d.ts +5 -0
  24. package/dist/commands/ls.js +9 -1
  25. package/dist/commands/public-code-manage.d.ts +24 -0
  26. package/dist/commands/public-code-manage.js +217 -0
  27. package/dist/commands/public-code.d.ts +12 -1
  28. package/dist/commands/public-code.js +140 -45
  29. package/dist/commands/push-heavy.d.ts +6 -0
  30. package/dist/commands/push-heavy.js +128 -0
  31. package/dist/commands/push-tree.d.ts +24 -0
  32. package/dist/commands/push-tree.js +91 -0
  33. package/dist/commands/push.d.ts +4 -13
  34. package/dist/commands/push.js +7 -77
  35. package/dist/commands/put-heavy.d.ts +9 -0
  36. package/dist/commands/put-heavy.js +120 -0
  37. package/dist/commands/put-payer.d.ts +21 -0
  38. package/dist/commands/put-payer.js +24 -0
  39. package/dist/commands/put.d.ts +2 -2
  40. package/dist/commands/put.js +8 -7
  41. package/dist/commands/receive.js +14 -8
  42. package/dist/commands/s3.js +44 -10
  43. package/dist/commands/share-dispatch.js +14 -1
  44. package/dist/commands/share.d.ts +2 -0
  45. package/dist/commands/share.js +45 -35
  46. package/dist/commands/shares-sent.js +8 -3
  47. package/dist/crypto-surface.d.ts +35 -0
  48. package/dist/crypto-surface.js +13 -0
  49. package/dist/crypto.d.ts +8 -0
  50. package/dist/crypto.js +8 -0
  51. package/dist/download-part.d.ts +32 -1
  52. package/dist/download-part.js +95 -6
  53. package/dist/download-range.d.ts +19 -0
  54. package/dist/download-range.js +108 -0
  55. package/dist/download-sink.d.ts +15 -0
  56. package/dist/download.d.ts +14 -0
  57. package/dist/download.js +19 -4
  58. package/dist/handover-codes.d.ts +25 -0
  59. package/dist/handover-codes.js +106 -0
  60. package/dist/handover.d.ts +62 -0
  61. package/dist/handover.js +217 -0
  62. package/dist/heavy-api.d.ts +36 -0
  63. package/dist/heavy-api.js +107 -0
  64. package/dist/heavy-copy.d.ts +72 -0
  65. package/dist/heavy-copy.js +108 -0
  66. package/dist/heavy-evm.d.ts +20 -0
  67. package/dist/heavy-evm.js +106 -0
  68. package/dist/heavy-self-pay.d.ts +92 -0
  69. package/dist/heavy-self-pay.js +167 -0
  70. package/dist/heavy-upload.d.ts +87 -0
  71. package/dist/heavy-upload.js +154 -0
  72. package/dist/heavy-wallet-pay.d.ts +39 -0
  73. package/dist/heavy-wallet-pay.js +73 -0
  74. package/dist/help-options.js +13 -4
  75. package/dist/help.js +24 -3
  76. package/dist/links.d.ts +58 -0
  77. package/dist/links.js +206 -0
  78. package/dist/list-tier.d.ts +7 -0
  79. package/dist/list-tier.js +47 -0
  80. package/dist/main.js +13 -10
  81. package/dist/manifest-write.d.ts +4 -3
  82. package/dist/mcp-tools/reads.js +20 -6
  83. package/dist/mcp-tools/share.js +47 -1
  84. package/dist/mcp-tools/tiers.js +16 -1
  85. package/dist/platform-sign.d.ts +4 -4
  86. package/dist/platform-sign.js +3 -3
  87. package/dist/portable.d.ts +23 -0
  88. package/dist/portable.js +19 -0
  89. package/dist/product.d.ts +1 -1
  90. package/dist/product.js +1 -1
  91. package/dist/public-code-activity.d.ts +35 -0
  92. package/dist/public-code-activity.js +88 -0
  93. package/dist/public-code-refusals.d.ts +25 -0
  94. package/dist/public-code-refusals.js +87 -0
  95. package/dist/public-codes.d.ts +76 -0
  96. package/dist/public-codes.js +182 -0
  97. package/dist/recovery-build.js +16 -0
  98. package/dist/recovery-map-part.d.ts +82 -0
  99. package/dist/recovery-map-part.js +83 -0
  100. package/dist/recovery-map.d.ts +5 -40
  101. package/dist/recovery-map.js +18 -1
  102. package/dist/recovery-source.d.ts +3 -0
  103. package/dist/recovery-source.js +9 -0
  104. package/dist/risk.d.ts +55 -1
  105. package/dist/risk.js +55 -3
  106. package/dist/run-log.d.ts +1 -1
  107. package/dist/run-log.js +7 -1
  108. package/dist/s3/address.d.ts +20 -0
  109. package/dist/s3/address.js +97 -0
  110. package/dist/s3/answer.d.ts +48 -0
  111. package/dist/s3/answer.js +330 -0
  112. package/dist/s3/body-deframe.d.ts +49 -0
  113. package/dist/s3/body-deframe.js +264 -0
  114. package/dist/s3/body-measure.d.ts +13 -0
  115. package/dist/s3/body-measure.js +48 -0
  116. package/dist/s3/body-plan.d.ts +31 -0
  117. package/dist/s3/body-plan.js +159 -0
  118. package/dist/s3/body.d.ts +46 -0
  119. package/dist/s3/body.js +117 -0
  120. package/dist/s3/call.d.ts +36 -0
  121. package/dist/s3/call.js +42 -0
  122. package/dist/s3/checksum.d.ts +26 -0
  123. package/dist/s3/checksum.js +176 -0
  124. package/dist/s3/content-type.d.ts +3 -0
  125. package/dist/s3/content-type.js +49 -0
  126. package/dist/s3/contract.d.ts +91 -14
  127. package/dist/s3/drive-conditions.d.ts +47 -0
  128. package/dist/s3/drive-conditions.js +134 -0
  129. package/dist/s3/drive-key.d.ts +11 -0
  130. package/dist/s3/drive-key.js +58 -0
  131. package/dist/s3/drive-limits.d.ts +33 -0
  132. package/dist/s3/drive-limits.js +53 -0
  133. package/dist/s3/drive-lock.d.ts +11 -0
  134. package/dist/s3/drive-lock.js +47 -0
  135. package/dist/s3/drive-trashed-name.d.ts +13 -0
  136. package/dist/s3/drive-trashed-name.js +59 -0
  137. package/dist/s3/drive-write.d.ts +38 -0
  138. package/dist/s3/drive-write.js +258 -0
  139. package/dist/s3/drive.d.ts +59 -25
  140. package/dist/s3/drive.js +46 -77
  141. package/dist/s3/listing.d.ts +27 -1
  142. package/dist/s3/listing.js +62 -20
  143. package/dist/s3/long-answer.d.ts +12 -0
  144. package/dist/s3/long-answer.js +104 -0
  145. package/dist/s3/multipart-assemble.d.ts +17 -0
  146. package/dist/s3/multipart-assemble.js +68 -0
  147. package/dist/s3/multipart-sweep.d.ts +15 -0
  148. package/dist/s3/multipart-sweep.js +87 -0
  149. package/dist/s3/multipart-view.d.ts +45 -0
  150. package/dist/s3/multipart-view.js +232 -0
  151. package/dist/s3/multipart.d.ts +26 -19
  152. package/dist/s3/multipart.js +193 -78
  153. package/dist/s3/object-read.d.ts +17 -0
  154. package/dist/s3/object-read.js +127 -0
  155. package/dist/s3/object-write.d.ts +35 -0
  156. package/dist/s3/object-write.js +198 -0
  157. package/dist/s3/range.d.ts +14 -0
  158. package/dist/s3/range.js +80 -0
  159. package/dist/s3/response-sink.d.ts +12 -2
  160. package/dist/s3/response-sink.js +71 -7
  161. package/dist/s3/routes.d.ts +0 -1
  162. package/dist/s3/routes.js +242 -217
  163. package/dist/s3/same-file.d.ts +4 -1
  164. package/dist/s3/same-file.js +12 -3
  165. package/dist/s3/server.d.ts +54 -4
  166. package/dist/s3/server.js +174 -14
  167. package/dist/s3/sigv4-canonical.d.ts +91 -0
  168. package/dist/s3/sigv4-canonical.js +148 -0
  169. package/dist/s3/sigv4-presigned.d.ts +13 -0
  170. package/dist/s3/sigv4-presigned.js +82 -0
  171. package/dist/s3/sigv4.d.ts +26 -27
  172. package/dist/s3/sigv4.js +137 -102
  173. package/dist/s3/spool.d.ts +37 -0
  174. package/dist/s3/spool.js +104 -0
  175. package/dist/s3/staging.d.ts +90 -7
  176. package/dist/s3/staging.js +97 -66
  177. package/dist/s3/xml-multipart.d.ts +38 -0
  178. package/dist/s3/xml-multipart.js +47 -0
  179. package/dist/s3/xml-read.d.ts +28 -0
  180. package/dist/s3/xml-read.js +235 -0
  181. package/dist/s3/xml.d.ts +45 -2
  182. package/dist/s3/xml.js +72 -13
  183. package/dist/s3-gateway.d.ts +11 -5
  184. package/dist/s3-gateway.js +5 -2
  185. package/dist/seal.d.ts +1 -1
  186. package/dist/share-codes.d.ts +40 -0
  187. package/dist/share-codes.js +151 -0
  188. package/dist/share.d.ts +39 -0
  189. package/dist/share.js +54 -13
  190. package/dist/shared/lib/api/types-heavy.d.ts +167 -0
  191. package/dist/shared/lib/api/types-heavy.js +60 -0
  192. package/dist/shared/lib/drive/rebuild-verify.js +1 -0
  193. package/dist/shared/lib/filecoin/providers.d.ts +25 -0
  194. package/dist/shared/lib/filecoin/providers.js +58 -0
  195. package/dist/shared/lib/heavy/download.d.ts +48 -0
  196. package/dist/shared/lib/heavy/download.js +116 -0
  197. package/dist/shared/lib/heavy/order-plan.d.ts +77 -0
  198. package/dist/shared/lib/heavy/order-plan.js +83 -0
  199. package/dist/shared/lib/heavy/order-runner.d.ts +9 -0
  200. package/dist/shared/lib/heavy/order-runner.js +300 -0
  201. package/dist/shared/lib/heavy/order-types.d.ts +90 -0
  202. package/dist/shared/lib/heavy/order-types.js +6 -0
  203. package/dist/shared/lib/heavy/order-wire.d.ts +55 -0
  204. package/dist/shared/lib/heavy/order-wire.js +113 -0
  205. package/dist/shared/lib/heavy/piece-cid.d.ts +24 -0
  206. package/dist/shared/lib/heavy/piece-cid.js +55 -0
  207. package/dist/shared/lib/heavy/sp-upload.d.ts +37 -0
  208. package/dist/shared/lib/heavy/sp-upload.js +112 -0
  209. package/dist/shared/lib/heavy/synapse-piece.d.ts +1 -0
  210. package/dist/shared/lib/heavy/synapse-piece.js +8 -0
  211. package/dist/shared/lib/share/handover-format.d.ts +129 -0
  212. package/dist/shared/lib/share/handover-format.js +323 -0
  213. package/dist/shared/lib/share/public-link.d.ts +41 -0
  214. package/dist/shared/lib/share/public-link.js +107 -0
  215. package/dist/shared/lib/share/shared-file-info.js +1 -0
  216. package/dist/shared/lib/storage-network.d.ts +4 -4
  217. package/dist/shared/lib/storage-network.js +7 -7
  218. package/dist/shared/lib/storage-tier.d.ts +28 -0
  219. package/dist/shared/lib/storage-tier.js +63 -0
  220. package/dist/shared/lib/wallet/send-rules.js +1 -0
  221. package/dist/upload-file.d.ts +8 -0
  222. package/dist/upload-file.js +57 -25
  223. package/dist/upload-price-node.d.ts +3 -0
  224. package/dist/upload-price-node.js +3 -6
  225. package/dist/upload-price.d.ts +10 -0
  226. package/dist/upload-price.js +13 -1
  227. package/dist/upload-run.d.ts +80 -0
  228. package/dist/upload-run.js +173 -0
  229. package/dist/upload-steps.js +15 -4
  230. package/dist/upload-store.d.ts +15 -6
  231. package/dist/upload-store.js +6 -0
  232. package/dist/upload-wallet-put.d.ts +9 -4
  233. package/dist/upload-wallet-put.js +16 -6
  234. package/dist/upload-wallet.js +4 -0
  235. package/dist/upload-wire.d.ts +25 -0
  236. package/dist/upload-wire.js +20 -1
  237. package/dist/upload.js +28 -13
  238. package/dist/wallet-sign.js +2 -2
  239. package/docs/commands/handover.md +54 -0
  240. package/docs/commands/heavy.md +35 -0
  241. package/docs/commands/link.md +27 -0
  242. package/docs/commands/mcp.md +2 -1
  243. package/docs/commands/public-code.md +25 -6
  244. package/docs/commands/push.md +4 -1
  245. package/docs/commands/put.md +15 -1
  246. package/docs/commands/share.md +8 -3
  247. package/package.json +5 -2
  248. package/server.json +2 -2
  249. package/vendor/nmts-crypto/nmts_crypto_wasm.d.ts +106 -4
  250. package/vendor/nmts-crypto/nmts_crypto_wasm.js +286 -3
  251. package/vendor/nmts-crypto/nmts_crypto_wasm_bg.wasm +0 -0
  252. package/vendor/nmts-crypto/nmts_crypto_wasm_bg.wasm.d.ts +12 -1
@@ -3,6 +3,9 @@ import { NCF3_SHAPE } from "./seal.js";
3
3
  import { isRecord } from "./guards.js";
4
4
  import { readBlob, readQuiltPatch } from "./walrus.js";
5
5
  import { NETWORK_WHEN_UNRECORDED, networkName } from "./shared/lib/storage-network.js";
6
+ import { reachFetch } from "./reach.js";
7
+ import { FILECOIN_CHAIN_FOR_NETWORK } from "./shared/lib/filecoin/providers.js";
8
+ import { readCopies } from "./shared/lib/heavy/order-wire.js";
6
9
  /** `storage_kind` in the server's part rows. */
7
10
  const DEDICATED_BLOB = 0;
8
11
  const QUILT_PATCH = 1;
@@ -34,6 +37,11 @@ export function asParts(value) {
34
37
  view.network = p["network"];
35
38
  if (typeof p["patch_id"] === "string")
36
39
  view.patch_id = p["patch_id"];
40
+ // ⚠ Checked field by field (`readCopies`); a list that does not read is left out, and the read
41
+ // below then says it has no copy to ask rather than asking a half-read address.
42
+ const copies = p["copies"] === undefined ? null : readCopies(p["copies"]);
43
+ if (copies !== null)
44
+ view.copies = copies;
37
45
  out.push(view);
38
46
  }
39
47
  return { size, parts: out };
@@ -47,6 +55,8 @@ export function asParts(value) {
47
55
  */
48
56
  export async function fetchPart(part, chain, read) {
49
57
  const where = networkName(part.network ?? NETWORK_WHEN_UNRECORDED);
58
+ if (where === "filecoin" && (chain === "testnet" || chain === "mainnet"))
59
+ return readHeavyPart(part, chain, read);
50
60
  if (where !== "walrus") {
51
61
  throw new NmtsError(`Part ${part.part_index} is stored on ${where ?? `an unknown network (${part.network})`}, which this version cannot read.`, { nextStep: "Nothing was written. Open the file in a browser, which may know that network." });
52
62
  }
@@ -57,6 +67,33 @@ export async function fetchPart(part, chain, read) {
57
67
  ? readQuiltPatch(chain, part.patch_id, read ?? {})
58
68
  : readBlob(chain, part.blob_id, read ?? {});
59
69
  }
70
+ /**
71
+ * One NMTS Heavy part, from the first of its copies that serves it (`shared/lib/heavy/download.ts`,
72
+ * the browser's own reader).
73
+ *
74
+ * ⛔ ANY https COMPANY, NOT ONLY THE LISTED ONES. The list exists because a browser page may only
75
+ * talk to hosts its security policy names; this program has no such policy, and somebody who paid
76
+ * from their own EVM wallet may have picked a company the list does not name. The bytes are
77
+ * judged by the decryption, as every part's are, so the company is not trusted either way.
78
+ */
79
+ async function readHeavyPart(part, chain, read) {
80
+ const { fetchHeavyPart } = await import("./shared/lib/heavy/download.js");
81
+ const range = read?.range;
82
+ const response = await fetchHeavyPart({
83
+ pieceCid: part.blob_id,
84
+ copies: part.copies ?? [],
85
+ chain: FILECOIN_CHAIN_FOR_NETWORK[chain],
86
+ allowUnlisted: true,
87
+ fetchImpl: reachFetch,
88
+ ...(range === undefined ? {} : { range }),
89
+ ...(read?.signal === undefined ? {} : { signal: read.signal }),
90
+ });
91
+ const body = new Uint8Array(await response.arrayBuffer());
92
+ if (range === undefined)
93
+ return body;
94
+ // A 206 holds exactly the asked-for bytes; a company that ignored `Range` sent the part from zero.
95
+ return body.length === range.end - range.start ? body : body.subarray(range.start, range.end);
96
+ }
60
97
  /**
61
98
  * Open ONE part and pass its contribution on, a chunk at a time. Returns how much of the file it
62
99
  * contributed.
@@ -70,17 +107,27 @@ export async function fetchPart(part, chain, read) {
70
107
  *
71
108
  * ⛔ `finish()` IS WHAT CATCHES A PART CUT SHORT. Every chunk that arrived authenticates; only the
72
109
  * end-of-stream check knows the rest is missing. Skipping it would accept a truncated part.
110
+ * ⚠ The one caller that skips it is a RANGE that asked for the part's first chunks only
111
+ * (`prefix`): it wants no byte past them, and every byte it keeps is authenticated.
73
112
  *
74
113
  * ⛔ THE ENGINE-SIDE SESSION IS FREED ON EVERY PATH OUT, including a failure: it holds the file
75
114
  * key until it is, and a download that failed is exactly when nobody comes back to tidy up.
76
115
  */
77
- export async function openPart(crypt, dek, part, sealed, isLast, remaining, emit) {
78
- const refuse = () => new NmtsError(`Part ${part.part_index} did not decrypt.`, {
79
- nextStep: "The bytes that arrived are not the bytes this account sealed. Nothing was written. " +
80
- "Try again — a different aggregator may hold the right ones.",
81
- });
116
+ export async function openPart(crypt, dek, part, sealed, position, remaining, emit, prefix = false) {
117
+ const isLast = position.index === position.total - 1;
118
+ const refuse = refusal(part);
82
119
  if (sealed.length < NCF3_SHAPE.headerLen)
83
120
  throw refuse();
121
+ // ⛔ POSITIONAL, AS NCF-3 §4.1 REQUIRES. The header names its own place (`part_index` of
122
+ // `part_total`, bytes 8..16) and every chunk authenticates that header — so a stream fetched in
123
+ // a place it does not claim still decrypts, and only this comparison notices. A reordered or
124
+ // substituted list of pieces would otherwise be stitched together in the wrong order.
125
+ const header = new DataView(sealed.buffer, sealed.byteOffset, NCF3_SHAPE.headerLen);
126
+ const claimedIndex = header.getUint32(8, true);
127
+ const claimedTotal = header.getUint32(12, true);
128
+ if (claimedIndex !== position.index || claimedTotal !== position.total) {
129
+ throw new NmtsError(`Part ${part.part_index} says it is part ${claimedIndex + 1} of ${claimedTotal}, but it was listed as part ${position.index + 1} of ${position.total}.`, { nextStep: "Nothing was written. The list of stored pieces does not match what was sealed." });
130
+ }
84
131
  // ⚠ Constructed on the header alone, which is parsed and checked inside the engine, so a blob
85
132
  // that is not an NCF-3 stream at all fails here rather than as a strange length later.
86
133
  let opener;
@@ -131,7 +178,8 @@ export async function openPart(crypt, dek, part, sealed, isLast, remaining, emit
131
178
  left -= take;
132
179
  }
133
180
  try {
134
- opener.finish();
181
+ if (!prefix)
182
+ opener.finish();
135
183
  }
136
184
  catch {
137
185
  throw refuse();
@@ -142,3 +190,44 @@ export async function openPart(crypt, dek, part, sealed, isLast, remaining, emit
142
190
  }
143
191
  return taken;
144
192
  }
193
+ function refusal(part) {
194
+ return () => new NmtsError(`Part ${part.part_index} did not decrypt.`, {
195
+ nextStep: "The bytes that arrived are not the bytes that were sealed. Nothing was written. " +
196
+ "Try again — a different aggregator may hold the right ones.",
197
+ });
198
+ }
199
+ /**
200
+ * Read a part's 72-byte header, and refuse it unless it is THIS file's part at THIS position.
201
+ *
202
+ * ⛔ THE ENGINE CHECKS THE KEY COMMITMENT FIRST. It covers every field read below, so a length or a
203
+ * position that passes here was sealed under this file's key — a range that leaves the parts
204
+ * before it out works out where it starts from these numbers, and a lie in them would put
205
+ * authentic bytes at the wrong place in the answer.
206
+ *
207
+ * ⛔ THE POSITION IS THE ONE THE CALLER IS READING INTO, never the part's own claim: every part of a
208
+ * file is sealed under one key, so a part served in another's place passes the commitment and is
209
+ * caught only by comparing where it says it is with where it is being used.
210
+ */
211
+ export function checkedHeader(crypt, dek, part, header, position) {
212
+ const refuse = refusal(part);
213
+ if (header.length < NCF3_SHAPE.headerLen)
214
+ throw refuse();
215
+ const bytes = header.subarray(0, NCF3_SHAPE.headerLen);
216
+ try {
217
+ new crypt.StreamDecryptor(dek, bytes).free();
218
+ }
219
+ catch {
220
+ throw refuse();
221
+ }
222
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
223
+ const log2 = view.getUint8(5);
224
+ const declared = view.getBigUint64(16, true);
225
+ if (view.getUint32(8, true) !== position.index || view.getUint32(12, true) !== position.total) {
226
+ throw new NmtsError(`Part ${part.part_index} was served in the wrong place in the file.`, {
227
+ nextStep: "The stored parts do not agree with the file this list describes. Nothing was written.",
228
+ });
229
+ }
230
+ if (declared > BigInt(Number.MAX_SAFE_INTEGER) || log2 > 40)
231
+ throw refuse();
232
+ return { declared: Number(declared), chunkSize: 2 ** log2 };
233
+ }
@@ -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,25 @@
1
+ import type { CryptoGlue } from "./crypto.ts";
2
+ import { type PublicCodeList } from "./public-codes.ts";
3
+ import type { ShareKeys, ShareSealed } from "./share.ts";
4
+ /** How many numbers after 0 opening tries when it cannot read the account's list. */
5
+ export declare const OFFLINE_WALK = 64;
6
+ /**
7
+ * The number a handover is sent from: `--as`, or the lowest-numbered live code. An account that has
8
+ * never published sends from code 0, the code its key has always had.
9
+ */
10
+ export declare function senderIndexOf(list: PublicCodeList, as: string | undefined): number;
11
+ /** The keys at `index`, refused by name when the server lists another code at that number. */
12
+ export declare function checkedKeys(crypt: CryptoGlue, code: string, list: PublicCodeList, index: number): ShareKeys;
13
+ /** Whether `address` is one of this account's codes — live, revoked, or the one it is sending from. */
14
+ export declare function isMine(list: PublicCodeList, keys: ShareKeys, address: Uint8Array): boolean;
15
+ /** What opening found: the file key, the code it opened with, and — when known — whether that code is revoked. */
16
+ export interface OpenedWith {
17
+ dek: Uint8Array;
18
+ index: number;
19
+ display: string;
20
+ address: Uint8Array;
21
+ /** From the account's list when it was read; null when it was not. */
22
+ revoked: boolean | null;
23
+ }
24
+ /** Open a handover envelope with whichever of this account's codes it was sealed to. */
25
+ export declare function openWithMyCodes(crypt: CryptoGlue, code: string, sealed: ShareSealed, server: string): Promise<OpenedWith>;
@@ -0,0 +1,106 @@
1
+ // Which of this account's public codes a handover is made from, and which one opens it.
2
+ //
3
+ // ⛔ A HANDOVER FILE NAMES NO RECIPIENT NUMBER. The envelope was sealed to one of this key's codes
4
+ // and does not say which, so opening tries them: code 0 first — the code every account starts
5
+ // with, and the one every file made before numbered codes was sealed to — then, when a credential
6
+ // on this machine can read the account's list, the live codes lowest first and the revoked ones
7
+ // newest first; with no credential, 1, 2, … up to `OFFLINE_WALK`. A wrong number fails exactly as
8
+ // any other refusal does, so trying several tells nobody anything.
9
+ //
10
+ // ⛔ MAKING ONE SENDS FROM A LIVE CODE. A revoked code that went on sending would leave its
11
+ // recipients unable to trust a revocation; the server refuses that for shares, and a handover has
12
+ // no server to refuse it, so this does.
13
+ import { toBase64Url } from "./bytes.js";
14
+ import { resolveApiKey } from "./credentials.js";
15
+ import { notForThisKey } from "./handover.js";
16
+ import { codeNumber, differentCode, notLiveCode } from "./public-code-refusals.js";
17
+ import { liveCodes, readPublicCodes } from "./public-codes.js";
18
+ import { openShareWithRing, shareKeyRing, shareKeysAt } from "./share-codes.js";
19
+ /** How many numbers after 0 opening tries when it cannot read the account's list. */
20
+ export const OFFLINE_WALK = 64;
21
+ /**
22
+ * The number a handover is sent from: `--as`, or the lowest-numbered live code. An account that has
23
+ * never published sends from code 0, the code its key has always had.
24
+ */
25
+ export function senderIndexOf(list, as) {
26
+ const wanted = as === undefined ? undefined : codeNumber(as, "--as");
27
+ if (list.codes.length === 0) {
28
+ if (wanted !== undefined && wanted !== 0)
29
+ throw notLiveCode(wanted);
30
+ return 0;
31
+ }
32
+ const live = liveCodes(list);
33
+ const row = wanted === undefined ? live[0] : live.find((c) => c.index === wanted);
34
+ if (row === undefined)
35
+ throw notLiveCode(wanted ?? 0);
36
+ return row.index;
37
+ }
38
+ /** The keys at `index`, refused by name when the server lists another code at that number. */
39
+ export function checkedKeys(crypt, code, list, index) {
40
+ const keys = shareKeysAt(crypt, code, index);
41
+ const row = list.codes.find((c) => c.index === index);
42
+ if (row !== undefined && toBase64Url(keys.address) !== row.address) {
43
+ keys.wipe();
44
+ throw differentCode();
45
+ }
46
+ return keys;
47
+ }
48
+ /** Whether `address` is one of this account's codes — live, revoked, or the one it is sending from. */
49
+ export function isMine(list, keys, address) {
50
+ const wire = toBase64Url(address);
51
+ return wire === toBase64Url(keys.address) || list.codes.some((c) => c.address === wire);
52
+ }
53
+ /** The numbers to try after 0: live ascending, then revoked newest first. */
54
+ function laterCodes(list) {
55
+ const live = liveCodes(list).map((c) => c.index);
56
+ const revoked = list.codes
57
+ .filter((c) => c.revokedAt !== null)
58
+ .sort((a, b) => (b.revokedAt ?? "").localeCompare(a.revokedAt ?? "") || b.index - a.index)
59
+ .map((c) => c.index);
60
+ return [...live, ...revoked].filter((i) => i !== 0);
61
+ }
62
+ /** The account's list, when a credential on this machine can read it; null otherwise. */
63
+ async function listIfHeld(server) {
64
+ const key = resolveApiKey();
65
+ if (key === null)
66
+ return null;
67
+ try {
68
+ return await readPublicCodes(server, key.key);
69
+ }
70
+ catch {
71
+ return null;
72
+ }
73
+ }
74
+ /** Open a handover envelope with whichever of this account's codes it was sealed to. */
75
+ export async function openWithMyCodes(crypt, code, sealed, server) {
76
+ // ⛔ ONE RING: the key's derivation runs once however many numbers are tried.
77
+ const ring = shareKeyRing(crypt, code);
78
+ try {
79
+ let found;
80
+ let list = null;
81
+ try {
82
+ found = openShareWithRing(crypt, ring, [0], sealed);
83
+ }
84
+ catch {
85
+ list = await listIfHeld(server);
86
+ const order = list === null ? Array.from({ length: OFFLINE_WALK }, (_, i) => i + 1) : laterCodes(list);
87
+ try {
88
+ found = openShareWithRing(crypt, ring, order, sealed);
89
+ }
90
+ catch {
91
+ throw notForThisKey();
92
+ }
93
+ }
94
+ const keys = ring.at(found.index);
95
+ const row = list?.codes.find((c) => c.index === found.index);
96
+ return {
97
+ ...found,
98
+ display: keys.display,
99
+ address: keys.address.slice(),
100
+ revoked: row === undefined ? null : row.revokedAt !== null,
101
+ };
102
+ }
103
+ finally {
104
+ ring.wipe();
105
+ }
106
+ }
@@ -0,0 +1,62 @@
1
+ import { type CryptoGlue } from "./crypto.ts";
2
+ import { NmtsError } from "./errors.ts";
3
+ import { type ShareKeys, type ShareSealed } from "./share.ts";
4
+ import { type HandoverFile, type HandoverNetwork, type HandoverPart } from "./shared/lib/share/handover-format.ts";
5
+ export declare function isHandoverNetwork(value: string): value is HandoverNetwork;
6
+ /** Refuse a name the handover file cannot carry, before any work is done. */
7
+ export declare function checkHandoverName(name: string, size: number, network: HandoverNetwork): void;
8
+ /** Build a handover file's text. The caller holds the file key and the digest, and wipes them. */
9
+ export declare function makeHandoverText(crypt: CryptoGlue, input: {
10
+ keys: ShareKeys;
11
+ recipientIdentity: Uint8Array;
12
+ recipientAddress: Uint8Array;
13
+ dek: Uint8Array;
14
+ itemId: string;
15
+ name: string;
16
+ size: number;
17
+ digest: Uint8Array;
18
+ parts: readonly HandoverPart[];
19
+ network: HandoverNetwork;
20
+ }): string;
21
+ /** What an opened handover file says. `dek` and `digest` are the caller's to wipe. */
22
+ export interface OpenedHandover {
23
+ name: string;
24
+ size: number;
25
+ /** The sender's public code, readable form — set only because the envelope opened. */
26
+ sender: string;
27
+ /** The same code, 16 bytes — what a revoked-list lookup takes. */
28
+ senderAddress: Uint8Array;
29
+ parts: HandoverPart[];
30
+ /** Earliest end epoch recorded when the file was made (exclusive); 0 when unknown. A hint. */
31
+ expiryEpoch: number;
32
+ dek: Uint8Array;
33
+ digest: Uint8Array;
34
+ }
35
+ /** A handover file read and checked up to its envelope: everything opening it needs. */
36
+ export interface SealedHandover {
37
+ file: HandoverFile;
38
+ /** What the envelope opens with — the sender's identity, the envelope and the two sealed fields. */
39
+ sealed: ShareSealed;
40
+ /** The sender's code as the envelope names it; agreed with the identity the file carries. */
41
+ claimed: Uint8Array;
42
+ partsCt: Uint8Array;
43
+ }
44
+ /** The one refusal for a file none of this account's codes opens. */
45
+ export declare function notForThisKey(): NmtsError;
46
+ /** Read a handover file's text and check what can be checked before opening it. */
47
+ export declare function readHandoverText(crypt: CryptoGlue, text: string, network: HandoverNetwork): SealedHandover;
48
+ /** Everything inside a handover whose envelope opened to `dek`. Wipes `dek` when it fails. */
49
+ export declare function finishHandover(crypt: CryptoGlue, h: SealedHandover, dek: Uint8Array): OpenedHandover;
50
+ /** Open a handover file's text with one of this account's codes. */
51
+ export declare function openHandoverText(crypt: CryptoGlue, keys: ShareKeys, text: string, network: HandoverNetwork): OpenedHandover;
52
+ /** This account's public code file. */
53
+ export declare function publicCodeFileText(keys: ShareKeys): string;
54
+ /**
55
+ * Read a recipient's public code file. Returns only when the identity inside really fingerprints to
56
+ * the code the file names, so what is sealed to is what the person was told.
57
+ */
58
+ export declare function readPublicCodeFileText(crypt: CryptoGlue, text: string): {
59
+ identity: Uint8Array;
60
+ address: Uint8Array;
61
+ display: string;
62
+ };