@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
@@ -9,9 +9,13 @@
9
9
  // entry's own field alone would list files whose bytes the server already refuses -- an S3 client
10
10
  // would see them, ask for them, and get a failure for every one.
11
11
  //
12
- // ⚠ ONE DELIBERATE DIFFERENCE FROM S3: a folder holding no files still comes back as a common
13
- // prefix. Real S3 has no folders, so an empty one cannot exist there; this drive does have them,
14
- // and hiding them would make `rclone lsd` describe a drive that is not the one in the browser.
12
+ // ⛔ A FOLDER IS A FOLDER MARKER: the key `photos/`, no bytes, and the tag of an empty object.
13
+ // That is how S3 itself holds an empty folder — the zero-byte object a console's "create folder"
14
+ // makes and every sync tool knows to skip — so a folder here lists, HEADs and GETs exactly like
15
+ // one there, and a zero-byte PUT of `photos/` is how a client makes one. Without it a folder
16
+ // holding no files could only be seen as a common prefix, and a client that made one with a
17
+ // marker was told 200 and then 404 for the key it had just written.
18
+ import { createHash } from "node:crypto";
15
19
  import { buildIndex, fullPathOf, isLive, KIND_FOLDER } from "../drive-paths.js";
16
20
  /**
17
21
  * The bucket `nmts s3` serves. Named for what it is, and not configurable: two names for one drive
@@ -27,6 +31,12 @@ export const MAX_KEYS_LIMIT = 1000;
27
31
  /**
28
32
  * An ETag that is stable for a file and changes when the file does.
29
33
  *
34
+ * ⛔ IT IS A HASH OF WHAT CHANGES WHEN THE FILE DOES: the entry's id, its time and its size. A file
35
+ * replaced at the same key is a new entry; one edited in place has a new time. The tag used to
36
+ * be the id and the time laid side by side and cut to 32 characters, which for a long id cut the
37
+ * time off altogether — and a tag that does not change when the file does is how a sync tool
38
+ * decides there is nothing to fetch.
39
+ *
30
40
  * ⛔ IT ENDS IN `-1` FOR A REASON. S3 clients treat an ETag that looks like a hex digest as the
31
41
  * MD5 of the object and check downloads against it; this drive has no MD5 of anything -- the
32
42
  * bytes are encrypted before they leave the machine and the digest it does keep is a different
@@ -35,28 +45,57 @@ export const MAX_KEYS_LIMIT = 1000;
35
45
  * reported as corrupt.
36
46
  */
37
47
  export function etagOf(entry) {
38
- const id = entry.id.replace(/[^0-9a-zA-Z]/g, "");
39
- const stamp = entry.updatedAt.toString(16);
40
- return `"${(id + stamp).slice(0, 32).padEnd(32, "0")}-1"`;
48
+ const digest = createHash("sha256").update(`${entry.id}\n${entry.updatedAt}\n${entry.size}`).digest("hex");
49
+ return `"${digest.slice(0, 32)}-1"`;
50
+ }
51
+ /** The tag of an object with no bytes: the MD5 of nothing, which is what S3 answers for one. */
52
+ export const EMPTY_ETAG = `"d41d8cd98f00b204e9800998ecf8427e"`;
53
+ /**
54
+ * Two keys in the order S3 lists them, which is the order of their UTF-8 bytes.
55
+ *
56
+ * ⛔ NOT `<`. JavaScript compares UTF-16 code units, and those put a character above U+FFFF (most
57
+ * emoji) BEFORE one in U+E000–U+FFFF, where UTF-8 puts it after. A client that pages through a
58
+ * listing resumes after the last key it saw, so a listing in the other order skips keys or
59
+ * repeats them.
60
+ */
61
+ export function compareKeys(a, b) {
62
+ const shorter = Math.min(a.length, b.length);
63
+ for (let i = 0; i < shorter;) {
64
+ const x = a.codePointAt(i) ?? 0;
65
+ const y = b.codePointAt(i) ?? 0;
66
+ if (x !== y)
67
+ return x < y ? -1 : 1;
68
+ i += x > 0xffff ? 2 : 1;
69
+ }
70
+ return a.length === b.length ? 0 : a.length < b.length ? -1 : 1;
71
+ }
72
+ /** True for the key of a folder marker: it ends in `/`. */
73
+ export function isFolderKey(key) {
74
+ return key.endsWith("/");
41
75
  }
42
- /** Every live file in the account, as keys, in the order S3 promises: ascending by key. */
76
+ /**
77
+ * Every live file in the account, and every live folder as its marker, as keys, in the order S3
78
+ * promises: ascending by key.
79
+ *
80
+ * ⚠ A MARKER'S ENTRY IS THE FOLDER'S, WITH AN EMPTY `dekWrapped`. A folder has no key to open, and
81
+ * the reader refuses an entry with none; the empty string says "nothing to open", and the drive's
82
+ * own `fetch` answers a folder with no bytes before anything would try.
83
+ */
43
84
  export function objectsOf(entries) {
44
85
  const index = buildIndex(entries);
45
86
  const rows = [];
46
87
  for (const entry of entries) {
47
- if (entry.kind === KIND_FOLDER)
48
- continue;
49
88
  if (!isLive(index, entry))
50
89
  continue;
51
- rows.push({
52
- key: fullPathOf(index, entry).replace(/^\//, ""),
53
- lastModified: new Date(entry.updatedAt).toISOString(),
54
- etag: etagOf(entry),
55
- size: entry.size,
56
- entry,
57
- });
90
+ const key = fullPathOf(index, entry).replace(/^\//, "");
91
+ const lastModified = new Date(entry.updatedAt).toISOString();
92
+ if (entry.kind === KIND_FOLDER) {
93
+ rows.push({ key: `${key}/`, lastModified, etag: EMPTY_ETAG, size: 0, entry: { ...entry, dekWrapped: "" } });
94
+ continue;
95
+ }
96
+ rows.push({ key, lastModified, etag: etagOf(entry), size: entry.size, entry });
58
97
  }
59
- rows.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
98
+ rows.sort((a, b) => compareKeys(a.key, b.key));
60
99
  return rows;
61
100
  }
62
101
  /** Every live folder, as a key ending in the delimiter — see the note at the top of this file. */
@@ -116,10 +155,13 @@ export function listObjects(objects, folders, query) {
116
155
  rows.push({ sort: prefix, row: null, prefix });
117
156
  }
118
157
  }
119
- rows.sort((a, b) => (a.sort < b.sort ? -1 : a.sort > b.sort ? 1 : 0));
120
- const started = query.after === null ? rows : rows.filter((r) => r.sort > (query.after ?? ""));
158
+ rows.sort((a, b) => compareKeys(a.sort, b.sort));
159
+ const after = query.after;
160
+ const started = after === null ? rows : rows.filter((r) => compareKeys(r.sort, after) > 0);
121
161
  const page = started.slice(0, maxKeys);
122
- const truncated = started.length > page.length;
162
+ // ⚠ `max-keys=0` asks for nothing and is answered nothing, untruncated: S3's answer, and the only
163
+ // one a client can act on — "truncated" with no key to resume after has it ask again forever.
164
+ const truncated = maxKeys > 0 && started.length > page.length;
123
165
  const last = page[page.length - 1];
124
166
  // ⛔ Split in a loop rather than two filter-and-map passes: a `map` over a filtered array cannot
125
167
  // convince the type checker that the field is there, and the usual way round that is to invent
@@ -0,0 +1,12 @@
1
+ import type { Call } from "./call.ts";
2
+ /** How often a space is written while the store runs: well inside the 60 seconds botocore waits. */
3
+ export declare const KEEP_ALIVE_MS = 10000;
4
+ /**
5
+ * Run `work` and answer with the XML it resolves to -- or, when `work` has called `accepted` and is
6
+ * still running one keep-alive interval later, begin the 200 then and keep the client hearing
7
+ * something while the rest runs.
8
+ *
9
+ * A `work` that settles before that is answered as though it had never called `accepted`: its
10
+ * result with 200, its throw with its own status.
11
+ */
12
+ export declare function answerAfter(call: Call, work: (accepted: () => void) => Promise<string>): Promise<void>;
@@ -0,0 +1,104 @@
1
+ // An answer that can take longer than a client waits for its first byte: `CompleteMultipartUpload`
2
+ // and `CopyObject`, which seal a whole file and send it to the storage network before they can say
3
+ // how that went.
4
+ //
5
+ // ⛔ A STORE THAT OUTLASTS ONE KEEP-ALIVE INTERVAL IS ANSWERED 200 AT ONCE, AND WHAT IT COMES TO GOES
6
+ // IN THE BODY. That is what S3 does for these two operations, and S3 clients read it: botocore
7
+ // gives up on a connection that sends nothing for 60 seconds and sends the request again, and a
8
+ // large file takes longer than that to store. A space every `KEEP_ALIVE_MS` keeps the connection
9
+ // from going quiet; XML allows white space between the declaration and the root element.
10
+ //
11
+ // ⛔ ONE THAT ENDS INSIDE THE INTERVAL KEEPS ITS OWN STATUS. The caller does all of its checking
12
+ // first and calls `accepted()` when what is left is the store itself -- but a store can still be
13
+ // refused in its first moments: the key holds another file, the account cannot pay, the account
14
+ // refuses the credential. An `Error` inside a 200 is what the AWS SDK for JavaScript v3 turns
15
+ // into a 503 and botocore into a 500, and both then send the request again, for a refusal no
16
+ // retry changes. So `accepted()` only arms a timer: the 200 begins when the timer fires, and a
17
+ // store that has settled by then is answered as any other operation is, with its own status.
18
+ //
19
+ // ⚠ NOTHING FOLLOWS `</Error>`. The AWS SDK for JavaScript v3 decides that a 200 failed by whether
20
+ // the last bytes of the body end in `</Error>`; one newline after it and that SDK reports the
21
+ // failure as a success.
22
+ import { randomBytes } from "node:crypto";
23
+ import { answerFor, noteFailure, sendXml } from "./answer.js";
24
+ import { errorXml, HEAD } from "./xml.js";
25
+ /** How often a space is written while the store runs: well inside the 60 seconds botocore waits. */
26
+ export const KEEP_ALIVE_MS = 10_000;
27
+ /** A document without its XML declaration, which went out when the answer began. */
28
+ function rootOf(xml) {
29
+ return xml.startsWith(HEAD) ? xml.slice(HEAD.length) : xml;
30
+ }
31
+ /**
32
+ * The request id this answer names, in its header and in an `Error` document's `RequestId`.
33
+ *
34
+ * ⚠ ONE ALREADY ON THE RESPONSE IS KEPT. A server in front of the gateway that names every request
35
+ * in its own log sets it before the gateway runs; a second id here would be one that log has
36
+ * never heard of.
37
+ */
38
+ function requestIdOf(call) {
39
+ const already = call.res.getHeader("x-amz-request-id");
40
+ return typeof already === "string" && already.length > 0 ? already : randomBytes(8).toString("hex").toUpperCase();
41
+ }
42
+ /**
43
+ * Run `work` and answer with the XML it resolves to -- or, when `work` has called `accepted` and is
44
+ * still running one keep-alive interval later, begin the 200 then and keep the client hearing
45
+ * something while the rest runs.
46
+ *
47
+ * A `work` that settles before that is answered as though it had never called `accepted`: its
48
+ * result with 200, its throw with its own status.
49
+ */
50
+ export async function answerAfter(call, work) {
51
+ const { res } = call;
52
+ const requestId = requestIdOf(call);
53
+ const every = call.options.keepAliveMs ?? KEEP_ALIVE_MS;
54
+ let asked = false;
55
+ let began = false;
56
+ let armed = null;
57
+ let beat = null;
58
+ const stop = () => {
59
+ if (armed !== null)
60
+ clearTimeout(armed);
61
+ if (beat !== null)
62
+ clearInterval(beat);
63
+ armed = null;
64
+ beat = null;
65
+ };
66
+ const begin = () => {
67
+ armed = null;
68
+ if (res.headersSent || res.destroyed || res.writableEnded)
69
+ return;
70
+ began = true;
71
+ res.writeHead(200, { "content-type": "application/xml", "x-amz-request-id": requestId });
72
+ res.write(HEAD);
73
+ beat = setInterval(() => {
74
+ if (!res.destroyed && !res.writableEnded)
75
+ res.write(" ");
76
+ }, every);
77
+ };
78
+ const accepted = () => {
79
+ if (asked)
80
+ return;
81
+ asked = true;
82
+ armed = setTimeout(begin, every);
83
+ // A client that hung up hears nothing more; the store goes on, and its retry finds the result.
84
+ res.once("close", stop);
85
+ };
86
+ let xml;
87
+ try {
88
+ xml = await work(accepted);
89
+ }
90
+ catch (error) {
91
+ stop();
92
+ if (!began)
93
+ throw error;
94
+ const answer = answerFor(error);
95
+ noteFailure(res, answer, call.resource);
96
+ res.end(rootOf(errorXml(answer.code, answer.message, call.resource, requestId)));
97
+ return;
98
+ }
99
+ stop();
100
+ if (began)
101
+ res.end(rootOf(xml));
102
+ else
103
+ sendXml(res, 200, xml, { "x-amz-request-id": requestId });
104
+ }
@@ -0,0 +1,17 @@
1
+ import { type ChecksumAlgorithm } from "./checksum.ts";
2
+ /** What a finish says the whole object comes to. */
3
+ export interface ObjectChecksum {
4
+ readonly algorithm: ChecksumAlgorithm;
5
+ readonly value: Buffer;
6
+ readonly type: "FULL_OBJECT" | "COMPOSITE";
7
+ }
8
+ /**
9
+ * Check a composite checksum against the pieces' own, before anything is joined. Returns without
10
+ * checking when a piece has no checksum of that kind (see the top of this file).
11
+ */
12
+ export declare function checkComposite(checksum: ObjectChecksum | null | undefined, pieces: ReadonlyArray<ReadonlyMap<ChecksumAlgorithm, Buffer>>): void;
13
+ /**
14
+ * Write these files one after another into a new file, 0600, computing a `FULL_OBJECT` checksum
15
+ * as they pass, and refuse the result when it does not match.
16
+ */
17
+ export declare function joinPieces(whole: string, paths: readonly string[], checksum?: ObjectChecksum | null): Promise<void>;
@@ -0,0 +1,68 @@
1
+ // Joining the pieces of an upload into one file, and holding it to the checksum the finish named.
2
+ //
3
+ // ⛔ THE CHECKSUM ON A FINISH IS THE WHOLE OBJECT'S, NOT THE FINISH'S BODY. `x-amz-checksum-*` on
4
+ // `CompleteMultipartUpload` is what the client says the assembled object comes to — and it used
5
+ // to be checked against the XML of the part list, which it never matches, so a client that sent
6
+ // one could never finish. S3 knows two kinds:
7
+ // · `FULL_OBJECT`: a checksum of every byte, in order. Computed here while the pieces are
8
+ // joined, and a file that does not match is not stored.
9
+ // · `COMPOSITE` (S3's default for a finish): a checksum of the pieces' own checksums, joined in
10
+ // order, with `-N` after it. It is checked from the checksums each piece arrived with, when
11
+ // every chosen piece arrived with one of that kind; ⚠ when any did not, there is nothing to
12
+ // check it against here, and it is accepted without being checked — the pieces themselves
13
+ // were each held to whatever their own requests promised.
14
+ import { createReadStream, createWriteStream } from "node:fs";
15
+ import { Transform } from "node:stream";
16
+ import { pipeline } from "node:stream/promises";
17
+ import { S3Refusal } from "./answer.js";
18
+ import { runningChecksum } from "./checksum.js";
19
+ function mismatch(algorithm) {
20
+ return new S3Refusal(400, "BadDigest", `The ${algorithm.toUpperCase()} you specified for the whole object did not match the calculated checksum. Nothing was stored.`);
21
+ }
22
+ /**
23
+ * Check a composite checksum against the pieces' own, before anything is joined. Returns without
24
+ * checking when a piece has no checksum of that kind (see the top of this file).
25
+ */
26
+ export function checkComposite(checksum, pieces) {
27
+ if (checksum === null || checksum === undefined || checksum.type !== "COMPOSITE")
28
+ return;
29
+ const running = runningChecksum(checksum.algorithm);
30
+ for (const piece of pieces) {
31
+ const own = piece.get(checksum.algorithm);
32
+ if (own === undefined)
33
+ return;
34
+ running.update(own);
35
+ }
36
+ if (!running.digest().equals(checksum.value))
37
+ throw mismatch(checksum.algorithm);
38
+ }
39
+ /**
40
+ * Write these files one after another into a new file, 0600, computing a `FULL_OBJECT` checksum
41
+ * as they pass, and refuse the result when it does not match.
42
+ */
43
+ export async function joinPieces(whole, paths, checksum) {
44
+ const full = checksum !== null && checksum !== undefined && checksum.type === "FULL_OBJECT" ? checksum : null;
45
+ const running = full === null ? null : runningChecksum(full.algorithm);
46
+ const out = createWriteStream(whole, { flags: "wx", mode: 0o600 });
47
+ try {
48
+ for (const path of paths) {
49
+ const measuring = new Transform({
50
+ transform(chunk, _encoding, next) {
51
+ running?.update(chunk);
52
+ next(null, chunk);
53
+ },
54
+ });
55
+ await pipeline(createReadStream(path), measuring, out, { end: false });
56
+ }
57
+ await new Promise((resolve, reject) => {
58
+ out.once("error", reject);
59
+ out.end(resolve);
60
+ });
61
+ }
62
+ catch (error) {
63
+ out.destroy();
64
+ throw error;
65
+ }
66
+ if (full !== null && running !== null && !running.digest().equals(full.value))
67
+ throw mismatch(full.algorithm);
68
+ }
@@ -0,0 +1,15 @@
1
+ /** An upload's directory: `nmts-mpu-` and the upload id. */
2
+ export declare const UPLOAD_DIR: RegExp;
3
+ /** A single upload's body, spooled before it is stored: `nmts-put-` and a random id. */
4
+ export declare const SPOOL_FILE: RegExp;
5
+ /** The directory an upload's pieces live in. */
6
+ export declare function uploadDirName(uploadId: string): string;
7
+ /** A fresh name for one upload's spooled body. */
8
+ export declare function spoolFileName(): string;
9
+ /** Mark a directory as in use now, so no process's sweep takes it for abandoned. */
10
+ export declare function touch(path: string, now: number): Promise<void>;
11
+ /**
12
+ * Remove every upload directory and spooled body under `root` that this gateway's names made, that
13
+ * `inUse` does not claim, and that has not changed for `lifetimeMs`.
14
+ */
15
+ export declare function sweepRoot(root: string, now: number, lifetimeMs: number, inUse: (uploadId: string) => boolean): Promise<void>;
@@ -0,0 +1,87 @@
1
+ // Removing what a gateway left in its staging directory and nobody will come back for.
2
+ //
3
+ // ⛔ THE DIRECTORY, NOT THE MEMORY. A process that stopped — a restart, a crash, a deploy — takes
4
+ // its record of every upload with it, and the pieces on disk are somebody's plaintext that no
5
+ // request can reach any more. Walking only the uploads a process remembers never finds them. So
6
+ // the directory itself is read, when a gateway starts and every so often after.
7
+ //
8
+ // ⛔ ONLY WHAT THIS GATEWAY'S NAMES MADE, AND ONLY WHAT NOBODY HAS TOUCHED FOR A DAY. A staging
9
+ // directory a caller named may hold anything else, and may be shared by several processes of
10
+ // the same backend. A name this gateway did not make is never touched, and one it did make is
11
+ // removed only when neither it nor anything in it has changed for `UPLOAD_LIFETIME_MS`. A
12
+ // process working on an upload touches its directory while it does (`staging.ts`), so an upload
13
+ // in use by another process is never a day old.
14
+ import { randomUUID } from "node:crypto";
15
+ import { lstat, readdir, rm, utimes } from "node:fs/promises";
16
+ import { join } from "node:path";
17
+ /** An upload's directory: `nmts-mpu-` and the upload id. */
18
+ export const UPLOAD_DIR = /^nmts-mpu-([0-9a-f]{32})$/;
19
+ /** A single upload's body, spooled before it is stored: `nmts-put-` and a random id. */
20
+ export const SPOOL_FILE = /^nmts-put-[0-9a-f-]{36}$/;
21
+ /** The directory an upload's pieces live in. */
22
+ export function uploadDirName(uploadId) {
23
+ return `nmts-mpu-${uploadId}`;
24
+ }
25
+ /** A fresh name for one upload's spooled body. */
26
+ export function spoolFileName() {
27
+ return `nmts-put-${randomUUID()}`;
28
+ }
29
+ /** The newest change to a path or, for a directory, to anything directly in it. Null when it is gone. */
30
+ async function lastChanged(path) {
31
+ let newest;
32
+ try {
33
+ const own = await lstat(path);
34
+ newest = own.mtimeMs;
35
+ if (!own.isDirectory())
36
+ return newest;
37
+ }
38
+ catch {
39
+ return null;
40
+ }
41
+ let names;
42
+ try {
43
+ names = await readdir(path);
44
+ }
45
+ catch {
46
+ return newest;
47
+ }
48
+ for (const name of names) {
49
+ try {
50
+ newest = Math.max(newest, (await lstat(join(path, name))).mtimeMs);
51
+ }
52
+ catch {
53
+ // Removed while this looked: its going is a change too, and the directory's time shows it.
54
+ }
55
+ }
56
+ return newest;
57
+ }
58
+ /** Mark a directory as in use now, so no process's sweep takes it for abandoned. */
59
+ export async function touch(path, now) {
60
+ const at = new Date(now);
61
+ await utimes(path, at, at).catch(() => undefined);
62
+ }
63
+ /**
64
+ * Remove every upload directory and spooled body under `root` that this gateway's names made, that
65
+ * `inUse` does not claim, and that has not changed for `lifetimeMs`.
66
+ */
67
+ export async function sweepRoot(root, now, lifetimeMs, inUse) {
68
+ let names;
69
+ try {
70
+ names = await readdir(root);
71
+ }
72
+ catch {
73
+ return;
74
+ }
75
+ for (const name of names) {
76
+ const upload = UPLOAD_DIR.exec(name);
77
+ if (upload === null && !SPOOL_FILE.test(name))
78
+ continue;
79
+ if (upload !== null && inUse(upload[1] ?? ""))
80
+ continue;
81
+ const path = join(root, name);
82
+ const changed = await lastChanged(path);
83
+ if (changed === null || now - changed <= lifetimeMs)
84
+ continue;
85
+ await rm(path, { recursive: true, force: true });
86
+ }
87
+ }
@@ -0,0 +1,45 @@
1
+ import type { ChecksumAlgorithm } from "./checksum.ts";
2
+ import type { StoreOutcome, WriteMeta } from "./contract.ts";
3
+ import type { StagedPart, Staging, UploadAccount } from "./staging.ts";
4
+ /** One piece, and what it was held to. */
5
+ export interface Piece extends StagedPart {
6
+ /** The piece's own file: a fresh name each time, so a piece sent twice never mixes with itself. */
7
+ readonly file: string;
8
+ /** The checksums its request held it to, for a finish that names a composite one. */
9
+ readonly checksums: ReadonlyMap<ChecksumAlgorithm, Buffer>;
10
+ }
11
+ export interface Upload {
12
+ readonly bucket: string;
13
+ readonly key: string;
14
+ readonly meta: WriteMeta;
15
+ /** The account the bucket belonged to when this began. */
16
+ readonly owner: string | null;
17
+ readonly initiated: number;
18
+ lastActivity: number;
19
+ /** Pieces arriving now. An upload with any is in use and is not swept. */
20
+ arriving: number;
21
+ readonly pieces: Map<number, Piece>;
22
+ /** The finish in progress, which a second finish of the same upload waits on rather than repeats. */
23
+ finishing: Promise<StoreOutcome> | null;
24
+ }
25
+ /** A finished upload, remembered so a finish sent twice is answered the same twice. */
26
+ export interface Finished {
27
+ readonly bucket: string;
28
+ readonly key: string;
29
+ readonly owner: string | null;
30
+ readonly outcome: StoreOutcome;
31
+ readonly at: number;
32
+ }
33
+ /** What every bucket's view shares: the uploads, and what the store does with them. */
34
+ export interface UploadBook {
35
+ readonly inFlight: Map<string, Upload>;
36
+ readonly finished: Map<string, Finished>;
37
+ readonly clock: () => number;
38
+ readonly maxPerBucket: number;
39
+ dirOf(uploadId: string): string;
40
+ /** Forget an upload and remove its pieces — unless a finish is reading them, which removes them itself. */
41
+ drop(uploadId: string, upload: Upload): Promise<void>;
42
+ /** Remove what nobody has touched for a day, from memory and from disk. */
43
+ sweepMemory(): Promise<void>;
44
+ }
45
+ export declare function bucketView(book: UploadBook, bucket: string, account: UploadAccount): Staging;