@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,9 @@
1
+ import { type Session } from "../session.ts";
2
+ import { type AccountSettings } from "../shared/lib/drive/manifest-settings.ts";
3
+ import { type HeavyPayer } from "./heavy-run.ts";
4
+ import { type PutOptions } from "./put.ts";
5
+ /** Who would pay, by address, for a dry run — derived offline, nothing signed. */
6
+ export declare function payerAddressOf(session: Session, payer: HeavyPayer, options: PutOptions, settings: AccountSettings | undefined): Promise<Record<string, unknown>>;
7
+ /** The dry run's words for a person: one plan line per payer, and the closing line. */
8
+ export declare function sayDryRun(say: (line: string) => void, name: string, facts: Record<string, unknown>): void;
9
+ export declare function putHeavy(target: string | undefined, options: PutOptions): Promise<number>;
@@ -0,0 +1,120 @@
1
+ // `nmts put <file> --tier heavy` — one file into NMTS Heavy: whole copies kept by two separate
2
+ // storage companies on Filecoin. Paid with credits (the default), with WAL from the wallet
3
+ // (`--pay wallet`), or — developer mode — by this key's own EVM wallet (`--pay evm`).
4
+ //
5
+ // ⛔ EVERYTHING BUT THE ONE FILE IS `heavy-run.ts`: the payer, the review, the agreement, the progress
6
+ // and the failure words are the same for `push --tier heavy`, so they live once.
7
+ import { basename, resolve } from "node:path";
8
+ import { parseAsked } from "../collision.js";
9
+ import { loadCrypto } from "../crypto.js";
10
+ import { NmtsError } from "../errors.js";
11
+ import { HEAVY_COPY } from "../heavy-copy.js";
12
+ import { evmAddressFor, evmIndexOf } from "../heavy-evm.js";
13
+ import { copiesOf } from "../heavy-self-pay.js";
14
+ import { paddingRuleOf, readFileList } from "../manifest.js";
15
+ import { resolveNetwork } from "../network.js";
16
+ import { BINARY_NAME } from "../product.js";
17
+ import { Progress, silentSink } from "../progress.js";
18
+ import { stderrSink } from "../progress-node.js";
19
+ import { openSession } from "../session.js";
20
+ import { activeWalletOf } from "../shared/lib/drive/manifest-settings.js";
21
+ import { fileSource } from "../upload-file-node.js";
22
+ import { measureLocal } from "../upload-price-node.js";
23
+ import { walletAddress } from "../wallet.js";
24
+ import { payingWalletIndex } from "../wallet-pay-index.js";
25
+ import { heavyDryRun, heavyPayerOf, recordHeavy, refuseHeavyClashes, runHeavy, termDaysOf } from "./heavy-run.js";
26
+ import { folderIdFor } from "./put.js";
27
+ /** Who would pay, by address, for a dry run — derived offline, nothing signed. */
28
+ export async function payerAddressOf(session, payer, options, settings) {
29
+ if (payer === "evm") {
30
+ return { payer: await evmAddressFor(session.code, evmIndexOf(options.evmWallet)), copies: copiesOf(options.copies) };
31
+ }
32
+ if (payer === "credits")
33
+ return {};
34
+ const wallet = await payingWalletIndex({ wallet: options.wallet, readActiveWallet: async () => activeWalletOf(settings) });
35
+ return { wallet: await walletAddress(session.code, wallet), termDays: termDaysOf(options.days) };
36
+ }
37
+ /** The dry run's words for a person: one plan line per payer, and the closing line. */
38
+ export function sayDryRun(say, name, facts) {
39
+ const bytes = typeof facts["bytes"] === "number" ? facts["bytes"] : 0;
40
+ if (typeof facts["credits"] === "number")
41
+ say(HEAVY_COPY.creditsPlan(name, bytes, facts["credits"]));
42
+ if (typeof facts["payer"] === "string")
43
+ say(HEAVY_COPY.evmPlan(name, bytes, Number(facts["copies"]), facts["payer"]));
44
+ if (typeof facts["wallet"] === "string")
45
+ say(HEAVY_COPY.walletDryPlan(name, bytes, Number(facts["termDays"]), facts["wallet"]));
46
+ say(HEAVY_COPY.dryRunEnd);
47
+ }
48
+ export async function putHeavy(target, options) {
49
+ const say = options.write ?? ((line) => process.stdout.write(`${line}\n`));
50
+ const payer = heavyPayerOf(options.pay);
51
+ refuseHeavyClashes(options, payer);
52
+ if (target === undefined || target === "") {
53
+ throw new NmtsError("Say which file to put.", {
54
+ exitCode: 2,
55
+ nextStep: `\`${BINARY_NAME} put <file>\` — a path on this machine.`,
56
+ });
57
+ }
58
+ const localPath = resolve(target);
59
+ const size = measureLocal(localPath);
60
+ const session = await openSession({ server: options.server, network: options.network });
61
+ const network = resolveNetwork(session.server, session.network);
62
+ const asked = parseAsked(options.onCollision);
63
+ const list = await readFileList(session.server, session.apiKey, session.code, session.accountId);
64
+ const rule = paddingRuleOf(list.manifest?.settings);
65
+ const name = options.name ?? basename(localPath);
66
+ const destination = (options.to ?? "").replace(/^\.?\//, "").replace(/\/$/, "");
67
+ const parentId = folderIdFor(options.to, list.manifest?.entries ?? []);
68
+ const file = { source: fileSource(localPath, size), name, parentId, destination };
69
+ if (options.dryRun === true) {
70
+ const facts = { ...heavyDryRun([file], rule, payer), ...(await payerAddressOf(session, payer, options, list.manifest?.settings)) };
71
+ if (options.json)
72
+ say(JSON.stringify({ name, ...facts }));
73
+ else
74
+ sayDryRun(say, name, facts);
75
+ return 0;
76
+ }
77
+ const json = options.json === true;
78
+ const report = await runHeavy({
79
+ session,
80
+ network,
81
+ crypt: await loadCrypto(),
82
+ rule,
83
+ settings: list.manifest?.settings,
84
+ say,
85
+ json,
86
+ progress: new Progress(json ? silentSink() : stderrSink(), "uploading"),
87
+ }, [file], payer, options);
88
+ const done = report.files[0];
89
+ if (done === undefined)
90
+ throw new NmtsError(HEAVY_COPY.commitNoId, { nextStep: HEAVY_COPY.commitNoIdNext });
91
+ const added = await recordHeavy(session, done, asked);
92
+ if (json) {
93
+ say(JSON.stringify({
94
+ id: done.itemId,
95
+ name: added.name,
96
+ bytes: size,
97
+ sealedBytes: done.sealedBytes,
98
+ parts: done.parts,
99
+ ...report.facts,
100
+ renamed: added.name !== name,
101
+ ...(added.replaced === null ? {} : { replacedIntoTrash: added.replaced }),
102
+ fileListVersion: added.seq,
103
+ }));
104
+ return 0;
105
+ }
106
+ say(` saved as ${added.name}`);
107
+ if (typeof report.facts["expiryEpoch"] === "number")
108
+ say(HEAVY_COPY.stored(report.facts["expiryEpoch"]));
109
+ if (added.replaced !== null) {
110
+ say(``);
111
+ say(` A file called ${name} was already there. It is in the trash now — ${BINARY_NAME} restore`);
112
+ say(` brings it back for 30 days. This machine is set to overwrite: ${BINARY_NAME} on-collision`);
113
+ }
114
+ else if (added.name !== name) {
115
+ say(``);
116
+ say(` A file called ${name} was already there, so this one was numbered rather than`);
117
+ say(` replacing it. This machine is set to rename: ${BINARY_NAME} on-collision`);
118
+ }
119
+ return 0;
120
+ }
@@ -1,3 +1,4 @@
1
+ import { type StorageTier } from "../shared/lib/storage-tier.ts";
1
2
  /** Who pays, or a refusal for a payer this tool does not know. */
2
3
  export declare function payerOf(pay: string | undefined): "credits" | "wallet";
3
4
  /** The options that only mean something when the wallet pays, refused when it does not. */
@@ -8,3 +9,23 @@ export declare function refuseWalletOnlyOptions(options: {
8
9
  trustServerTipAddress?: boolean;
9
10
  from?: string | undefined;
10
11
  }): void;
12
+ /** What NMTS Heavy adds to an upload command line: the tier, and the self-paid knobs. */
13
+ export interface HeavyFlags {
14
+ /** `--tier standard|heavy`. Absent = standard. */
15
+ tier?: string | undefined;
16
+ /** `--tier heavy --pay evm`: how many copies, 1..12 (default 2). */
17
+ copies?: string | undefined;
18
+ /** `--tier heavy --pay evm`: which storage companies, by id, comma-separated. */
19
+ providers?: string | undefined;
20
+ /** `--tier heavy --pay evm`: which of this key's EVM wallets pays. Absent = 0. */
21
+ evmWallet?: string | undefined;
22
+ /** `--tier heavy --pay wallet`: how many days to keep it, 1..365 (default 28). */
23
+ days?: string | undefined;
24
+ }
25
+ /**
26
+ * Which tier this upload goes to — the same reader the browser and the SDK use — and a refusal for
27
+ * every option that means nothing on that tier. Decided before a file is measured.
28
+ */
29
+ export declare function tierOf(options: HeavyFlags & {
30
+ pay?: string | undefined;
31
+ }): StorageTier;
@@ -7,6 +7,8 @@
7
7
  // ⚠ They moved out of `put.ts` on 2026-09-16 (`--wallet` joined them and that file has a ceiling).
8
8
  // `put.ts` re-exports them, so `push.ts` and the tests spell the same path they always did.
9
9
  import { NmtsError } from "../errors.js";
10
+ import { HEAVY_COPY } from "../heavy-copy.js";
11
+ import { DEFAULT_STORAGE_TIER, parseStorageTier } from "../shared/lib/storage-tier.js";
10
12
  /** Who pays, or a refusal for a payer this tool does not know. */
11
13
  export function payerOf(pay) {
12
14
  if (pay === undefined || pay === "credits")
@@ -51,3 +53,25 @@ export function refuseWalletOnlyOptions(options) {
51
53
  });
52
54
  }
53
55
  }
56
+ /**
57
+ * Which tier this upload goes to — the same reader the browser and the SDK use — and a refusal for
58
+ * every option that means nothing on that tier. Decided before a file is measured.
59
+ */
60
+ export function tierOf(options) {
61
+ let tier;
62
+ try {
63
+ tier = options.tier === undefined ? DEFAULT_STORAGE_TIER : parseStorageTier(options.tier);
64
+ }
65
+ catch (error) {
66
+ throw new NmtsError(error instanceof Error ? error.message : String(error), { exitCode: 2 });
67
+ }
68
+ if (tier === "standard") {
69
+ if (options.pay === "evm")
70
+ throw new NmtsError(HEAVY_COPY.evmNeedsHeavy, { exitCode: 2 });
71
+ for (const [flag, value] of [["--copies", options.copies], ["--providers", options.providers], ["--evm-wallet", options.evmWallet], ["--days", options.days]]) {
72
+ if (value !== undefined)
73
+ throw new NmtsError(HEAVY_COPY.heavyOnlyFlag(flag), { exitCode: 2 });
74
+ }
75
+ }
76
+ return tier;
77
+ }
@@ -1,5 +1,5 @@
1
1
  import type { ManifestEntry } from "../shared/lib/drive/manifest-codec.ts";
2
- export interface PutOptions {
2
+ export interface PutOptions extends HeavyFlags {
3
3
  server?: string | undefined;
4
4
  network?: string | undefined;
5
5
  /** The name it gets in the drive. Defaults to the local file's own name. */
@@ -54,7 +54,7 @@ export interface PutOptions {
54
54
  onStored?: (itemId: string, savedAs: string) => void;
55
55
  }
56
56
  /** Who pays, and the options that lose their meaning under that answer — the rule is in `put-payer.ts`; this is its one road. */
57
- import { payerOf, refuseWalletOnlyOptions } from "./put-payer.ts";
57
+ import { payerOf, refuseWalletOnlyOptions, type HeavyFlags } from "./put-payer.ts";
58
58
  export { payerOf, refuseWalletOnlyOptions };
59
59
  /**
60
60
  * The folder id `--to` names, or null for the root. Refuses rather than guessing.
@@ -27,15 +27,15 @@ import { paddingRuleOf, readFileList } from "../manifest.js";
27
27
  import { resolveNetwork } from "../network.js";
28
28
  import { BINARY_NAME } from "../product.js";
29
29
  import { resolveServer } from "../server.js";
30
- import { clearItemRecord, clearReservation } from "../upload-store.js";
30
+ import { forgetUpload } from "../upload-run.js";
31
31
  import { createUploadApi } from "../upload-api.js";
32
- import { partKeysOf, uploadFile } from "../upload-file.js";
32
+ import { uploadFile } from "../upload-file.js";
33
33
  import { fileSource } from "../upload-file-node.js";
34
34
  import { CREDIT_BYTES, creditsFor, partSizeFor, planAndPrice, UPLOAD_EPOCHS } from "../upload-price.js";
35
35
  import { measureLocal } from "../upload-price-node.js";
36
36
  import { createBlobProtocol, readCurrentEpoch } from "../walrus-write.js";
37
37
  /** Who pays, and the options that lose their meaning under that answer — the rule is in `put-payer.ts`; this is its one road. */
38
- import { payerOf, refuseWalletOnlyOptions } from "./put-payer.js";
38
+ import { payerOf, refuseWalletOnlyOptions, tierOf } from "./put-payer.js";
39
39
  export { payerOf, refuseWalletOnlyOptions };
40
40
  /**
41
41
  * The folder id `--to` names, or null for the root. Refuses rather than guessing.
@@ -69,6 +69,9 @@ export function folderIdFor(wanted, entries) {
69
69
  return folder.id;
70
70
  }
71
71
  export async function put(target, options = {}) {
72
+ // NMTS Heavy is its own road (`put-heavy.ts`), taken before the preview picture: Heavy refuses one.
73
+ if (tierOf(options) === "heavy")
74
+ return (await import("./put-heavy.js")).putHeavy(target, options);
72
75
  if (options.thumbnail === true || options.thumbnailFile !== undefined) {
73
76
  return (await import("./put-thumbnail.js")).putWithThumbnail(target, options, put);
74
77
  }
@@ -267,10 +270,8 @@ export async function put(target, options = {}) {
267
270
  options.onStored?.(result.itemId, added.name);
268
271
  // ⛔ ONLY NOW, AND EVERY PART. Until the entry is in the list the file is paid for and invisible,
269
272
  // and the records are the only thing that lets a second run finish the job without spending
270
- // again. Clearing the file-level one first would leave a run able to commit a second time.
271
- await clearItemRecord(result.fileKey);
272
- for (const record of partKeysOf(result.fileKey, result.parts))
273
- await clearReservation(record);
273
+ // again. The order they are forgotten in is `forgetUpload`'s.
274
+ await forgetUpload(result.fileKey, result.parts);
274
275
  // ⛔ THE DISPLACED FILE IS TOLD TO THE SERVER ONLY NOW, and only after the new one is in the
275
276
  // list. Until this line the person still had the file they started with.
276
277
  // ⚠ A failure here leaves it hidden in this account's trash while the server still counts it as
@@ -81,9 +81,9 @@ export async function receive(id, options = {}) {
81
81
  ? null
82
82
  : options.out !== undefined
83
83
  ? resolve(options.out)
84
- : options.intoDir !== undefined
85
- ? destinationFor(options.intoDir, opened.name)
86
- : resolve(opened.name);
84
+ : // ⛔ The name is the SENDER'S choice, so it lands in a directory by its last segment only:
85
+ // `../x` or an absolute path must not put a file outside where this tool was run.
86
+ destinationFor(options.intoDir ?? ".", opened.name);
87
87
  // ⛔ `--force` has nothing to overwrite on the stdout branch and is ignored there on purpose.
88
88
  // On the disk branch the file streams into a temporary name beside the destination and is
89
89
  // renamed into place only once the sender's digest matches, so a share that turns out to be
@@ -18,6 +18,8 @@ import { tmpdir } from "node:os";
18
18
  import { join } from "node:path";
19
19
  import { randomUUID } from "node:crypto";
20
20
  import { createDriveSource, fetchObject, LIST_CACHE_MS } from "../s3/drive.js";
21
+ import { freeTrashedName } from "../s3/drive-trashed-name.js";
22
+ import { createStagingStore, SWEEP_EVERY_MS } from "../s3/staging.js";
21
23
  import { NmtsError } from "../errors.js";
22
24
  import { ensureFolderPath } from "../drive-edit.js";
23
25
  import { put } from "./put.js";
@@ -30,6 +32,17 @@ import { BUCKET } from "../s3/listing.js";
30
32
  import { BIND_ADDRESS, createGateway, newCredential } from "../s3/server.js";
31
33
  /** MinIO's port, which is what most S3 tools already have in their examples. */
32
34
  export const DEFAULT_PORT = 9000;
35
+ /** The `id` in the one line `put --json` prints, or undefined when there is none to read. */
36
+ function idIn(line) {
37
+ try {
38
+ const parsed = JSON.parse(line);
39
+ const id = typeof parsed === "object" && parsed !== null ? Reflect.get(parsed, "id") : undefined;
40
+ return typeof id === "string" ? id : undefined;
41
+ }
42
+ catch {
43
+ return undefined;
44
+ }
45
+ }
33
46
  function portOf(raw) {
34
47
  if (raw === undefined)
35
48
  return DEFAULT_PORT;
@@ -54,6 +67,8 @@ export async function s3(options = {}) {
54
67
  * takes and afterwards.
55
68
  */
56
69
  const stagingRoot = join(tmpdir(), `nmts-s3-${randomUUID()}`);
70
+ // The uploads in pieces, swept on a timer that does not keep the process alive.
71
+ const staging = createStagingStore(stagingRoot, { sweepEveryMs: SWEEP_EVERY_MS });
57
72
  // ⛔ THE QUESTION WAS ANSWERED BEFORE THIS STARTED. A gateway cannot ask: its caller is a program
58
73
  // and its stdin is not a terminal. `s3` is a medium act (`risk.ts`) — uploads through it spend
59
74
  // credits — so the tier gate asked at the start, or the mode waved it through, and every write
@@ -62,14 +77,19 @@ export async function s3(options = {}) {
62
77
  /**
63
78
  * This account, as the shared drive module takes it.
64
79
  *
65
- * ⛔ THE SIX FUNCTIONS ARE THE ONLY THING THIS COMMAND CONTRIBUTES. What an upload DOES — the
80
+ * ⛔ THESE FUNCTIONS ARE THE ONLY THING THIS COMMAND CONTRIBUTES. What an upload DOES — the
66
81
  * same-file verdict, the folders above the key, forgetting the cached list — lives in
67
82
  * `s3/drive.ts`, so that the gateway a business runs from the SDK and the one a person runs
68
83
  * here cannot come to disagree about it.
69
84
  */
70
85
  const source = createDriveSource({
71
86
  stagingRoot,
87
+ staging,
88
+ bucket: BUCKET,
72
89
  writable,
90
+ // ⛔ A FILE ALREADY IN THE DRIVE IS NOT REPLACED FROM HERE. Different bytes at a taken key are
91
+ // refused, and the person deletes the old file first; what is said at start-up below.
92
+ overwrite: "refuse",
73
93
  onAlreadyStored: (key) => say(`same ${key} — already stored, nothing sent`),
74
94
  account: {
75
95
  readList: async () => {
@@ -81,22 +101,32 @@ export async function s3(options = {}) {
81
101
  makeFolder: async (folder) => {
82
102
  await ensureFolderPath(session, folder);
83
103
  },
84
- store: async (path, name, folder) => {
104
+ // ⚠ The collision rule is named rather than left to this machine's setting: the drive module
105
+ // decides replace-or-not, and a person's `on-collision` must not quietly change that answer.
106
+ // ⚠ Asked for `--json` so the id of the stored file comes back, and the tag answered is its.
107
+ store: async (path, name, folder, how) => {
108
+ let said = "";
85
109
  await put(path, {
86
110
  server: options.server,
87
111
  network: options.network,
88
112
  ...(folder === undefined ? {} : { to: folder }),
89
113
  name,
90
- write: () => undefined,
114
+ onCollision: how.replace ? "overwrite" : "rename",
115
+ json: true,
116
+ write: (line) => {
117
+ said = line;
118
+ },
91
119
  });
120
+ return { id: idIn(said) };
92
121
  },
93
122
  trash: async (path) => {
94
- await rm([path], {
95
- server: options.server,
96
- network: options.network,
97
- write: () => undefined,
98
- });
123
+ await rm([path], { server: options.server, network: options.network, write: () => undefined });
124
+ },
125
+ // One run of `rm` is one write to the file list, however many paths it names.
126
+ trashMany: async (paths) => {
127
+ await rm(paths, { server: options.server, network: options.network, write: () => undefined });
99
128
  },
129
+ freeTrashedName: (folder, name) => freeTrashedName(session, folder, name),
100
130
  fetch: (object, sink) => fetchObject({ server: session.server, bearer: session.apiKey, code: session.code, chain }, object, sink),
101
131
  },
102
132
  });
@@ -152,11 +182,15 @@ export async function s3(options = {}) {
152
182
  }
153
183
  await new Promise((resolve) => {
154
184
  const stop = () => {
155
- // Nothing half-uploaded outlives the command that was staging it.
156
- void removeFile(stagingRoot, { recursive: true, force: true });
157
185
  server.close(() => resolve());
158
186
  // A client holding a connection open must not keep the process alive after Ctrl-C.
159
187
  server.closeAllConnections();
188
+ // Nothing half-uploaded outlives the command that was staging it — but a finish still
189
+ // storing is waited for, rather than having its file removed underneath it.
190
+ void staging
191
+ .close()
192
+ .then(() => removeFile(stagingRoot, { recursive: true, force: true }))
193
+ .catch(() => undefined);
160
194
  };
161
195
  process.once("SIGINT", stop);
162
196
  process.once("SIGTERM", stop);
@@ -223,6 +223,14 @@ export interface CryptoGlue {
223
223
  * would look like the account's money had vanished.
224
224
  */
225
225
  wallet_seed_for(walletRoot: Uint8Array, index: number): Uint8Array;
226
+ /**
227
+ * The secp256k1 private key (32 bytes) of EVM wallet `index`, from the same wallet root
228
+ * (NCF-3 §1.9) — the key that pays Filecoin itself for NMTS Heavy on the self-paid path.
229
+ *
230
+ * ⛔ KEY MATERIAL, LIKE `wallet_seed_for`. The address is computed from it on this side
231
+ * (`heavy-evm.ts`); the key is wiped by whoever asked for it.
232
+ */
233
+ evm_key_for(walletRoot: Uint8Array, index: number): Uint8Array;
226
234
  }
227
235
  export declare function isCryptoGlue(value: unknown): value is CryptoGlue;
228
236
  /** Which of the required functions this object does not have. Empty means it is the engine. */
@@ -43,6 +43,9 @@ const REQUIRED = [
43
43
  // "this function is missing" said at load time is a different day's problem from
44
44
  // `undefined is not a function` in the middle of deriving somebody's second account.
45
45
  "derive_ai_account_code",
46
+ // The EVM wallets (NCF-3 §1.9), required for the same reason: `put --tier heavy --pay evm` and
47
+ // `heavy wallet` cannot run on a build without it.
48
+ "evm_key_for",
46
49
  ];
47
50
  export function isCryptoGlue(value) {
48
51
  return missingExports(value).length === 0;
package/dist/crypto.d.ts CHANGED
@@ -29,6 +29,9 @@ export declare const AAD: {
29
29
  readonly shareName: "nmts/v3/share-name";
30
30
  /** Seals the shared file's plaintext digest for the recipient, under the same file key. */
31
31
  readonly shareContentHash: "nmts/v3/share-content-hash";
32
+ /** Seals a handover file's list of stored pieces under the file's own key (NCF-3 §5.6), so a file
33
+ * that is intercepted does not even say where the ciphertext is. */
34
+ readonly handoverParts: "nmts/v3/handover-parts";
32
35
  /** Seals the RECOVERY LIST — where every file's bytes are (NRM §1). ⛔ The old spelling of the
33
36
  * artefact's name is frozen INTO the separator: every list ever sealed is bound to these bytes. */
34
37
  readonly recoveryMap: "nmts/v3/recovery-map";
package/dist/crypto.js CHANGED
@@ -47,6 +47,9 @@ export const AAD = {
47
47
  shareName: "nmts/v3/share-name",
48
48
  /** Seals the shared file's plaintext digest for the recipient, under the same file key. */
49
49
  shareContentHash: "nmts/v3/share-content-hash",
50
+ /** Seals a handover file's list of stored pieces under the file's own key (NCF-3 §5.6), so a file
51
+ * that is intercepted does not even say where the ciphertext is. */
52
+ handoverParts: "nmts/v3/handover-parts",
50
53
  /** Seals the RECOVERY LIST — where every file's bytes are (NRM §1). ⛔ The old spelling of the
51
54
  * artefact's name is frozen INTO the separator: every list ever sealed is bound to these bytes. */
52
55
  recoveryMap: "nmts/v3/recovery-map",
@@ -1,11 +1,14 @@
1
1
  import type { CryptoGlue } from "./crypto.ts";
2
2
  import { type ReadOptions } from "./walrus.ts";
3
+ import type { HeavyCopy } from "./shared/lib/api/types-heavy.ts";
3
4
  export interface PartView {
4
5
  part_index: number;
5
6
  storage_kind: number;
6
7
  network?: number;
7
8
  blob_id: string;
8
9
  patch_id?: string;
10
+ /** Network 1 (NMTS Heavy): the storage companies keeping a whole copy each, in the order to ask. */
11
+ copies?: HeavyCopy[];
9
12
  }
10
13
  export interface PartsResponse {
11
14
  size: number;
@@ -33,8 +36,36 @@ export declare function fetchPart(part: PartView, chain: string, read: ReadOptio
33
36
  *
34
37
  * ⛔ `finish()` IS WHAT CATCHES A PART CUT SHORT. Every chunk that arrived authenticates; only the
35
38
  * end-of-stream check knows the rest is missing. Skipping it would accept a truncated part.
39
+ * ⚠ The one caller that skips it is a RANGE that asked for the part's first chunks only
40
+ * (`prefix`): it wants no byte past them, and every byte it keeps is authenticated.
36
41
  *
37
42
  * ⛔ THE ENGINE-SIDE SESSION IS FREED ON EVERY PATH OUT, including a failure: it holds the file
38
43
  * key until it is, and a download that failed is exactly when nobody comes back to tidy up.
39
44
  */
40
- export declare function openPart(crypt: CryptoGlue, dek: Uint8Array, part: PartView, sealed: Uint8Array, isLast: boolean, remaining: number, emit: (body: Uint8Array) => Promise<void>): Promise<number>;
45
+ export declare function openPart(crypt: CryptoGlue, dek: Uint8Array, part: PartView, sealed: Uint8Array, position: {
46
+ index: number;
47
+ total: number;
48
+ }, remaining: number, emit: (body: Uint8Array) => Promise<void>, prefix?: boolean): Promise<number>;
49
+ /** What a part's sealed header says about it, once it is known to be this file's. */
50
+ export interface PartHeader {
51
+ /** Plaintext bytes the stream declares — the whole part, padding included. */
52
+ declared: number;
53
+ /** Plaintext bytes per chunk. */
54
+ chunkSize: number;
55
+ }
56
+ /**
57
+ * Read a part's 72-byte header, and refuse it unless it is THIS file's part at THIS position.
58
+ *
59
+ * ⛔ THE ENGINE CHECKS THE KEY COMMITMENT FIRST. It covers every field read below, so a length or a
60
+ * position that passes here was sealed under this file's key — a range that leaves the parts
61
+ * before it out works out where it starts from these numbers, and a lie in them would put
62
+ * authentic bytes at the wrong place in the answer.
63
+ *
64
+ * ⛔ THE POSITION IS THE ONE THE CALLER IS READING INTO, never the part's own claim: every part of a
65
+ * file is sealed under one key, so a part served in another's place passes the commitment and is
66
+ * caught only by comparing where it says it is with where it is being used.
67
+ */
68
+ export declare function checkedHeader(crypt: CryptoGlue, dek: Uint8Array, part: PartView, header: Uint8Array, position: {
69
+ index: number;
70
+ total: number;
71
+ }): PartHeader;
@@ -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
+ }