@needmoretruth/nmts-cli 0.44.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 (248) hide show
  1. package/AGENTS.md +2 -2
  2. package/CHANGELOG.md +73 -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 +14 -0
  9. package/dist/args.js +11 -2
  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/get.d.ts +2 -0
  15. package/dist/commands/get.js +13 -1
  16. package/dist/commands/handover.d.ts +13 -0
  17. package/dist/commands/handover.js +328 -0
  18. package/dist/commands/heavy-run.d.ts +59 -0
  19. package/dist/commands/heavy-run.js +247 -0
  20. package/dist/commands/heavy.d.ts +7 -0
  21. package/dist/commands/heavy.js +123 -0
  22. package/dist/commands/ls.d.ts +7 -0
  23. package/dist/commands/ls.js +27 -6
  24. package/dist/commands/public-code.d.ts +6 -0
  25. package/dist/commands/public-code.js +46 -0
  26. package/dist/commands/push-heavy.d.ts +6 -0
  27. package/dist/commands/push-heavy.js +128 -0
  28. package/dist/commands/push-tree.d.ts +24 -0
  29. package/dist/commands/push-tree.js +91 -0
  30. package/dist/commands/push.d.ts +4 -13
  31. package/dist/commands/push.js +7 -77
  32. package/dist/commands/put-heavy.d.ts +9 -0
  33. package/dist/commands/put-heavy.js +120 -0
  34. package/dist/commands/put-payer.d.ts +21 -0
  35. package/dist/commands/put-payer.js +24 -0
  36. package/dist/commands/put-thumbnail.d.ts +4 -0
  37. package/dist/commands/put-thumbnail.js +119 -0
  38. package/dist/commands/put-wallet.d.ts +2 -0
  39. package/dist/commands/put-wallet.js +3 -2
  40. package/dist/commands/put.d.ts +10 -2
  41. package/dist/commands/put.js +13 -7
  42. package/dist/commands/receive.js +3 -3
  43. package/dist/commands/s3.js +44 -10
  44. package/dist/crypto-surface.d.ts +8 -0
  45. package/dist/crypto-surface.js +3 -0
  46. package/dist/crypto.d.ts +3 -0
  47. package/dist/crypto.js +3 -0
  48. package/dist/download-part.d.ts +32 -1
  49. package/dist/download-part.js +95 -6
  50. package/dist/download-range.d.ts +19 -0
  51. package/dist/download-range.js +108 -0
  52. package/dist/download-sink.d.ts +15 -0
  53. package/dist/download.d.ts +14 -0
  54. package/dist/download.js +19 -4
  55. package/dist/drive-edit/trash.js +5 -3
  56. package/dist/drive-edit/tree.d.ts +6 -0
  57. package/dist/drive-edit/tree.js +10 -0
  58. package/dist/drive-erase.js +2 -2
  59. package/dist/drive-paths.d.ts +2 -2
  60. package/dist/drive-paths.js +2 -2
  61. package/dist/handover.d.ts +44 -0
  62. package/dist/handover.js +199 -0
  63. package/dist/heavy-api.d.ts +36 -0
  64. package/dist/heavy-api.js +107 -0
  65. package/dist/heavy-copy.d.ts +72 -0
  66. package/dist/heavy-copy.js +108 -0
  67. package/dist/heavy-evm.d.ts +20 -0
  68. package/dist/heavy-evm.js +106 -0
  69. package/dist/heavy-self-pay.d.ts +92 -0
  70. package/dist/heavy-self-pay.js +167 -0
  71. package/dist/heavy-upload.d.ts +87 -0
  72. package/dist/heavy-upload.js +154 -0
  73. package/dist/heavy-wallet-pay.d.ts +39 -0
  74. package/dist/heavy-wallet-pay.js +73 -0
  75. package/dist/help-options.js +8 -2
  76. package/dist/help.js +16 -3
  77. package/dist/list-tier.d.ts +7 -0
  78. package/dist/list-tier.js +47 -0
  79. package/dist/main.js +14 -9
  80. package/dist/manifest-write.d.ts +4 -3
  81. package/dist/mcp-tools/files.js +21 -2
  82. package/dist/mcp-tools/reads.js +9 -1
  83. package/dist/platform-sign.d.ts +4 -4
  84. package/dist/platform-sign.js +3 -3
  85. package/dist/portable.d.ts +17 -1
  86. package/dist/portable.js +13 -1
  87. package/dist/product.d.ts +1 -1
  88. package/dist/product.js +1 -1
  89. package/dist/recovery-build.js +16 -0
  90. package/dist/recovery-map-part.d.ts +82 -0
  91. package/dist/recovery-map-part.js +83 -0
  92. package/dist/recovery-map.d.ts +5 -40
  93. package/dist/recovery-map.js +18 -1
  94. package/dist/recovery-source.d.ts +3 -0
  95. package/dist/recovery-source.js +9 -0
  96. package/dist/risk.d.ts +30 -0
  97. package/dist/risk.js +23 -2
  98. package/dist/run-log.d.ts +1 -1
  99. package/dist/run-log.js +7 -1
  100. package/dist/s3/address.d.ts +20 -0
  101. package/dist/s3/address.js +97 -0
  102. package/dist/s3/answer.d.ts +48 -0
  103. package/dist/s3/answer.js +330 -0
  104. package/dist/s3/body-deframe.d.ts +49 -0
  105. package/dist/s3/body-deframe.js +264 -0
  106. package/dist/s3/body-measure.d.ts +13 -0
  107. package/dist/s3/body-measure.js +48 -0
  108. package/dist/s3/body-plan.d.ts +31 -0
  109. package/dist/s3/body-plan.js +159 -0
  110. package/dist/s3/body.d.ts +46 -0
  111. package/dist/s3/body.js +117 -0
  112. package/dist/s3/call.d.ts +36 -0
  113. package/dist/s3/call.js +42 -0
  114. package/dist/s3/checksum.d.ts +26 -0
  115. package/dist/s3/checksum.js +176 -0
  116. package/dist/s3/content-type.d.ts +3 -0
  117. package/dist/s3/content-type.js +49 -0
  118. package/dist/s3/contract.d.ts +91 -14
  119. package/dist/s3/drive-conditions.d.ts +47 -0
  120. package/dist/s3/drive-conditions.js +134 -0
  121. package/dist/s3/drive-key.d.ts +11 -0
  122. package/dist/s3/drive-key.js +58 -0
  123. package/dist/s3/drive-limits.d.ts +33 -0
  124. package/dist/s3/drive-limits.js +53 -0
  125. package/dist/s3/drive-lock.d.ts +11 -0
  126. package/dist/s3/drive-lock.js +47 -0
  127. package/dist/s3/drive-trashed-name.d.ts +13 -0
  128. package/dist/s3/drive-trashed-name.js +59 -0
  129. package/dist/s3/drive-write.d.ts +38 -0
  130. package/dist/s3/drive-write.js +258 -0
  131. package/dist/s3/drive.d.ts +59 -25
  132. package/dist/s3/drive.js +46 -77
  133. package/dist/s3/listing.d.ts +27 -1
  134. package/dist/s3/listing.js +62 -20
  135. package/dist/s3/long-answer.d.ts +12 -0
  136. package/dist/s3/long-answer.js +104 -0
  137. package/dist/s3/multipart-assemble.d.ts +17 -0
  138. package/dist/s3/multipart-assemble.js +68 -0
  139. package/dist/s3/multipart-sweep.d.ts +15 -0
  140. package/dist/s3/multipart-sweep.js +87 -0
  141. package/dist/s3/multipart-view.d.ts +45 -0
  142. package/dist/s3/multipart-view.js +232 -0
  143. package/dist/s3/multipart.d.ts +26 -19
  144. package/dist/s3/multipart.js +193 -78
  145. package/dist/s3/object-read.d.ts +17 -0
  146. package/dist/s3/object-read.js +127 -0
  147. package/dist/s3/object-write.d.ts +35 -0
  148. package/dist/s3/object-write.js +198 -0
  149. package/dist/s3/range.d.ts +14 -0
  150. package/dist/s3/range.js +80 -0
  151. package/dist/s3/response-sink.d.ts +12 -2
  152. package/dist/s3/response-sink.js +71 -7
  153. package/dist/s3/routes.d.ts +0 -1
  154. package/dist/s3/routes.js +242 -217
  155. package/dist/s3/same-file.d.ts +4 -1
  156. package/dist/s3/same-file.js +12 -3
  157. package/dist/s3/server.d.ts +54 -4
  158. package/dist/s3/server.js +174 -14
  159. package/dist/s3/sigv4-canonical.d.ts +91 -0
  160. package/dist/s3/sigv4-canonical.js +148 -0
  161. package/dist/s3/sigv4-presigned.d.ts +13 -0
  162. package/dist/s3/sigv4-presigned.js +82 -0
  163. package/dist/s3/sigv4.d.ts +26 -27
  164. package/dist/s3/sigv4.js +137 -102
  165. package/dist/s3/spool.d.ts +37 -0
  166. package/dist/s3/spool.js +104 -0
  167. package/dist/s3/staging.d.ts +90 -7
  168. package/dist/s3/staging.js +97 -66
  169. package/dist/s3/xml-multipart.d.ts +38 -0
  170. package/dist/s3/xml-multipart.js +47 -0
  171. package/dist/s3/xml-read.d.ts +28 -0
  172. package/dist/s3/xml-read.js +235 -0
  173. package/dist/s3/xml.d.ts +45 -2
  174. package/dist/s3/xml.js +72 -13
  175. package/dist/s3-gateway.d.ts +11 -5
  176. package/dist/s3-gateway.js +5 -2
  177. package/dist/seal.d.ts +1 -1
  178. package/dist/share.d.ts +5 -0
  179. package/dist/share.js +1 -1
  180. package/dist/shared/lib/api/types-heavy.d.ts +167 -0
  181. package/dist/shared/lib/api/types-heavy.js +60 -0
  182. package/dist/shared/lib/drive/manifest-codec.d.ts +11 -31
  183. package/dist/shared/lib/drive/manifest-codec.js +15 -23
  184. package/dist/shared/lib/drive/manifest-index.d.ts +10 -1
  185. package/dist/shared/lib/drive/manifest-index.js +30 -8
  186. package/dist/shared/lib/drive/manifest-wire-extras.d.ts +50 -0
  187. package/dist/shared/lib/drive/manifest-wire-extras.js +65 -0
  188. package/dist/shared/lib/drive/preview-classify.d.ts +17 -0
  189. package/dist/shared/lib/drive/preview-classify.js +96 -0
  190. package/dist/shared/lib/drive/rebuild-verify.js +1 -0
  191. package/dist/shared/lib/filecoin/providers.d.ts +25 -0
  192. package/dist/shared/lib/filecoin/providers.js +58 -0
  193. package/dist/shared/lib/heavy/download.d.ts +48 -0
  194. package/dist/shared/lib/heavy/download.js +116 -0
  195. package/dist/shared/lib/heavy/order-plan.d.ts +77 -0
  196. package/dist/shared/lib/heavy/order-plan.js +83 -0
  197. package/dist/shared/lib/heavy/order-runner.d.ts +9 -0
  198. package/dist/shared/lib/heavy/order-runner.js +300 -0
  199. package/dist/shared/lib/heavy/order-types.d.ts +90 -0
  200. package/dist/shared/lib/heavy/order-types.js +6 -0
  201. package/dist/shared/lib/heavy/order-wire.d.ts +55 -0
  202. package/dist/shared/lib/heavy/order-wire.js +113 -0
  203. package/dist/shared/lib/heavy/piece-cid.d.ts +24 -0
  204. package/dist/shared/lib/heavy/piece-cid.js +55 -0
  205. package/dist/shared/lib/heavy/sp-upload.d.ts +37 -0
  206. package/dist/shared/lib/heavy/sp-upload.js +112 -0
  207. package/dist/shared/lib/heavy/synapse-piece.d.ts +1 -0
  208. package/dist/shared/lib/heavy/synapse-piece.js +8 -0
  209. package/dist/shared/lib/share/handover-format.d.ts +129 -0
  210. package/dist/shared/lib/share/handover-format.js +323 -0
  211. package/dist/shared/lib/share/shared-file-info.js +1 -0
  212. package/dist/shared/lib/storage-network.d.ts +4 -4
  213. package/dist/shared/lib/storage-network.js +7 -7
  214. package/dist/shared/lib/storage-tier.d.ts +28 -0
  215. package/dist/shared/lib/storage-tier.js +63 -0
  216. package/dist/shared/lib/wallet/send-rules.js +1 -0
  217. package/dist/upload-file.d.ts +8 -0
  218. package/dist/upload-file.js +57 -25
  219. package/dist/upload-price-node.d.ts +3 -0
  220. package/dist/upload-price-node.js +3 -6
  221. package/dist/upload-price.d.ts +10 -0
  222. package/dist/upload-price.js +13 -1
  223. package/dist/upload-run.d.ts +80 -0
  224. package/dist/upload-run.js +173 -0
  225. package/dist/upload-steps.js +15 -4
  226. package/dist/upload-store.d.ts +15 -6
  227. package/dist/upload-store.js +6 -0
  228. package/dist/upload-wallet-put.d.ts +11 -4
  229. package/dist/upload-wallet-put.js +17 -6
  230. package/dist/upload-wallet.js +4 -0
  231. package/dist/upload-wire.d.ts +25 -0
  232. package/dist/upload-wire.js +20 -1
  233. package/dist/upload.js +28 -13
  234. package/dist/wallet-sign.js +2 -2
  235. package/docs/commands/get.md +3 -0
  236. package/docs/commands/handover.md +38 -0
  237. package/docs/commands/heavy.md +35 -0
  238. package/docs/commands/ls.md +5 -0
  239. package/docs/commands/public-code.md +7 -0
  240. package/docs/commands/push.md +4 -1
  241. package/docs/commands/put.md +23 -1
  242. package/docs/commands/share.md +3 -1
  243. package/package.json +5 -2
  244. package/server.json +2 -2
  245. package/vendor/nmts-crypto/nmts_crypto_wasm.d.ts +17 -1
  246. package/vendor/nmts-crypto/nmts_crypto_wasm.js +28 -0
  247. package/vendor/nmts-crypto/nmts_crypto_wasm_bg.wasm +0 -0
  248. package/vendor/nmts-crypto/nmts_crypto_wasm_bg.wasm.d.ts +2 -1
@@ -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;
@@ -0,0 +1,232 @@
1
+ // One bucket's uploads in pieces, as the drive the bucket has now sees them. One of the parts of
2
+ // `staging.ts`, which holds what is shared by every bucket; only it imports this.
3
+ //
4
+ // ⛔ EVERY OPERATION ASKS WHOSE THE BUCKET IS NOW. An upload remembers the account it began under,
5
+ // and the drive handing out this view says which account it is; when the two differ the bucket
6
+ // has been given to somebody else, and the upload is gone for this caller — refused as
7
+ // `NoSuchUpload`, and its pieces removed, the first time anybody asks about it.
8
+ import { randomBytes } from "node:crypto";
9
+ import { mkdir, rename, rm } from "node:fs/promises";
10
+ import { join } from "node:path";
11
+ import { S3Refusal } from "./answer.js";
12
+ import { checkNotEmpty, SlowDown, tooLarge } from "./drive-limits.js";
13
+ import { compareKeys } from "./listing.js";
14
+ import { checkComposite, joinPieces } from "./multipart-assemble.js";
15
+ import { spoolBody } from "./spool.js";
16
+ function noSuchUpload() {
17
+ return new S3Refusal(404, "NoSuchUpload", "No upload is in progress with that id. It may have been finished, aborted, or left untouched for more than a day.");
18
+ }
19
+ /** A tag as a client may send it back: with or without its quotes. */
20
+ function bare(etag) {
21
+ return etag.trim().replace(/^W\//, "").replace(/^"|"$/g, "");
22
+ }
23
+ /**
24
+ * A new upload id: the time it began, then randomness, all hex.
25
+ *
26
+ * ⛔ SORTED BY TIME AS A STRING. `ListMultipartUploads` resumes after an id, and S3 lists one key's
27
+ * uploads by when they began; an id that sorts the same way lets a listing resume after an id
28
+ * even once that upload is gone, without skipping the key's later ones.
29
+ */
30
+ function newUploadId(now) {
31
+ return `${Math.max(0, Math.floor(now)).toString(16).padStart(12, "0")}${randomBytes(10).toString("hex")}`;
32
+ }
33
+ export function bucketView(book, bucket, account) {
34
+ const { inFlight, finished, clock } = book;
35
+ const ownerNow = async () => (account.owner === undefined ? null : await account.owner());
36
+ const limit = account.maxObjectBytes;
37
+ const active = (upload) => {
38
+ upload.lastActivity = clock();
39
+ };
40
+ /** The upload with this id in this bucket, still the current account's, or NoSuchUpload. */
41
+ const current = async (uploadId) => {
42
+ const upload = inFlight.get(uploadId);
43
+ if (upload === undefined || upload.bucket !== bucket)
44
+ throw noSuchUpload();
45
+ if (upload.owner !== (await ownerNow())) {
46
+ // ⛔ The bucket answers to another account now. The upload is not theirs to finish, list or
47
+ // see, and the pieces are nobody's any more.
48
+ await book.drop(uploadId, upload);
49
+ throw noSuchUpload();
50
+ }
51
+ return upload;
52
+ };
53
+ /** …and only for the key it began with, which is S3's rule too. */
54
+ const opened = async (uploadId, key) => {
55
+ const upload = await current(uploadId);
56
+ if (upload.key !== key)
57
+ throw noSuchUpload();
58
+ return upload;
59
+ };
60
+ const assembleAndStore = async (uploadId, upload, chosen, options) => {
61
+ const dir = book.dirOf(uploadId);
62
+ const whole = join(dir, `whole-${randomBytes(16).toString("hex")}`);
63
+ try {
64
+ await joinPieces(whole, chosen.map((piece) => join(dir, piece.file)), options.checksum);
65
+ const outcome = await account.store(upload.key, whole, upload.meta, options.condition);
66
+ inFlight.delete(uploadId);
67
+ finished.set(uploadId, { bucket, key: upload.key, owner: upload.owner, outcome, at: clock() });
68
+ await rm(dir, { recursive: true, force: true });
69
+ return outcome;
70
+ }
71
+ finally {
72
+ await rm(whole, { force: true });
73
+ }
74
+ };
75
+ return {
76
+ async begin(key, meta) {
77
+ await book.sweepMemory();
78
+ let open = 0;
79
+ for (const upload of inFlight.values())
80
+ if (upload.bucket === bucket)
81
+ open += 1;
82
+ if (open >= book.maxPerBucket) {
83
+ throw new SlowDown(`This bucket already has ${open} uploads begun and not finished, the most this gateway keeps. ` +
84
+ "Finish or abort one, or wait for one to finish.");
85
+ }
86
+ const owner = await ownerNow();
87
+ const now = clock();
88
+ const uploadId = newUploadId(now);
89
+ await mkdir(book.dirOf(uploadId), { recursive: true, mode: 0o700 });
90
+ inFlight.set(uploadId, {
91
+ bucket,
92
+ key,
93
+ meta,
94
+ owner,
95
+ initiated: now,
96
+ lastActivity: now,
97
+ arriving: 0,
98
+ pieces: new Map(),
99
+ finishing: null,
100
+ });
101
+ return uploadId;
102
+ },
103
+ // ⛔ EACH PIECE IS ITS OWN FILE, and nothing is appended: a real client sends them concurrently
104
+ // and out of order (measured from rclone: 1, 3, 2), and sends one again when a connection
105
+ // drops. The piece is only counted once its bytes are in AND the body's rules held.
106
+ async part(uploadId, key, partNumber, body) {
107
+ const upload = await opened(uploadId, key);
108
+ const dir = book.dirOf(uploadId);
109
+ const file = `${partNumber}-${randomBytes(16).toString("hex")}`;
110
+ const path = join(dir, file);
111
+ const temporary = `${path}.arriving`;
112
+ active(upload);
113
+ upload.arriving += 1;
114
+ let spooled;
115
+ try {
116
+ spooled = await spoolBody(body, temporary, { md5: true, limit });
117
+ await rename(temporary, path);
118
+ }
119
+ catch (error) {
120
+ await rm(temporary, { force: true });
121
+ // An abort that landed while this piece was arriving took its directory with it.
122
+ if (inFlight.get(uploadId) !== upload)
123
+ throw noSuchUpload();
124
+ throw error;
125
+ }
126
+ finally {
127
+ upload.arriving -= 1;
128
+ active(upload);
129
+ }
130
+ // …or landed just after, and took the upload with it.
131
+ if (inFlight.get(uploadId) !== upload) {
132
+ await rm(path, { force: true });
133
+ throw noSuchUpload();
134
+ }
135
+ const etag = `"${spooled.md5 ?? ""}"`;
136
+ const before = upload.pieces.get(partNumber);
137
+ const checksums = new Map(body.checksums?.() ?? []);
138
+ upload.pieces.set(partNumber, { partNumber, etag, size: spooled.size, stagedAt: clock(), file, checksums });
139
+ // A finish reading the old piece keeps it; the directory goes with the upload either way.
140
+ if (before !== undefined && upload.finishing === null) {
141
+ await rm(join(dir, before.file), { force: true });
142
+ }
143
+ return etag;
144
+ },
145
+ async complete(uploadId, key, parts, options = {}) {
146
+ const done = finished.get(uploadId);
147
+ if (done !== undefined && done.bucket === bucket && done.key === key && done.owner === (await ownerNow())) {
148
+ return done.outcome;
149
+ }
150
+ const upload = await current(uploadId);
151
+ if (upload.key !== key) {
152
+ throw new S3Refusal(400, "InvalidRequest", "That upload was begun for a different key. Finish it at the key it began with.");
153
+ }
154
+ active(upload);
155
+ if (upload.finishing !== null) {
156
+ options.accepted?.();
157
+ return upload.finishing;
158
+ }
159
+ const chosen = [];
160
+ let last = 0;
161
+ let total = 0;
162
+ for (const asked of parts) {
163
+ if (asked.partNumber <= last) {
164
+ throw new S3Refusal(400, "InvalidPartOrder", "The parts must be listed once each, in ascending order of part number.");
165
+ }
166
+ last = asked.partNumber;
167
+ const piece = upload.pieces.get(asked.partNumber);
168
+ if (piece === undefined || bare(piece.etag) !== bare(asked.etag)) {
169
+ throw new S3Refusal(400, "InvalidPart", `Part ${asked.partNumber} was not staged with that tag. Send it again, or list the tag it was answered with.`);
170
+ }
171
+ chosen.push(piece);
172
+ total += piece.size;
173
+ }
174
+ if (limit !== undefined && total > limit)
175
+ throw tooLarge(limit);
176
+ checkNotEmpty(total);
177
+ checkComposite(options.checksum, chosen.map((piece) => piece.checksums));
178
+ options.accepted?.();
179
+ const finishing = assembleAndStore(uploadId, upload, chosen, options);
180
+ upload.finishing = finishing;
181
+ try {
182
+ return await finishing;
183
+ }
184
+ catch (error) {
185
+ // ⛔ The pieces stay — see the top of `staging.ts` — unless the upload was dropped meanwhile.
186
+ if (upload.finishing === finishing)
187
+ upload.finishing = null;
188
+ if (inFlight.get(uploadId) !== upload)
189
+ await rm(book.dirOf(uploadId), { recursive: true, force: true });
190
+ throw error;
191
+ }
192
+ finally {
193
+ active(upload);
194
+ }
195
+ },
196
+ async abort(uploadId, key) {
197
+ const upload = await opened(uploadId, key);
198
+ // ⛔ A FINISH IN PROGRESS IS WAITED FOR, NOT CUT SHORT. Its store is reading the joined file
199
+ // out of this directory; removing it underneath stored a truncated file, or failed a finish
200
+ // the client had every reason to think would work. Once it has settled, a finish that
201
+ // worked means there is nothing left to abort — S3's `NoSuchUpload` — and one that failed
202
+ // has left its pieces, which this then removes.
203
+ const finishing = upload.finishing;
204
+ if (finishing !== null) {
205
+ await finishing.catch(() => undefined);
206
+ if (inFlight.get(uploadId) !== upload)
207
+ throw noSuchUpload();
208
+ }
209
+ await book.drop(uploadId, upload);
210
+ },
211
+ async parts(uploadId, key) {
212
+ const upload = await opened(uploadId, key);
213
+ return [...upload.pieces.values()]
214
+ .sort((a, b) => a.partNumber - b.partNumber)
215
+ .map(({ partNumber, etag, size, stagedAt }) => ({ partNumber, etag, size, stagedAt }));
216
+ },
217
+ async uploads() {
218
+ const owner = await ownerNow();
219
+ const out = [];
220
+ for (const [uploadId, upload] of [...inFlight.entries()]) {
221
+ if (upload.bucket !== bucket)
222
+ continue;
223
+ if (upload.owner !== owner) {
224
+ await book.drop(uploadId, upload);
225
+ continue;
226
+ }
227
+ out.push({ uploadId, key: upload.key, meta: upload.meta, initiated: upload.initiated });
228
+ }
229
+ return out.sort((a, b) => compareKeys(a.key, b.key) || (a.uploadId < b.uploadId ? -1 : a.uploadId > b.uploadId ? 1 : 0));
230
+ },
231
+ };
232
+ }
@@ -1,21 +1,28 @@
1
- import type { IncomingMessage, ServerResponse } from "node:http";
2
- import type { DriveWriter } from "./server.ts";
1
+ import { type Call } from "./call.ts";
2
+ import type { Staging } from "./staging.ts";
3
3
  /** S3's own ceiling, and a bound on what one client can stage on this machine. */
4
4
  export declare const MAX_PARTS = 10000;
5
- export interface MultipartContext {
6
- readonly req: IncomingMessage;
7
- readonly res: ServerResponse;
8
- readonly bucket: string;
9
- readonly key: string;
10
- readonly method: string;
11
- readonly query: URLSearchParams;
12
- readonly writer: DriveWriter;
13
- /** The declared payload hash from the signature, when it was a real digest. */
14
- readonly payloadHash: string | null;
15
- readonly fail: (status: number, code: string, message: string) => void;
16
- readonly log?: ((line: string) => void) | undefined;
17
- }
18
- /** True when this request belongs to a multipart upload rather than a plain object call. */
19
- export declare function isMultipartRequest(method: string, query: URLSearchParams): boolean;
20
- /** Answer one multipart request. Returns false when the shape is not one this gateway knows. */
21
- export declare function handleMultipart(context: MultipartContext): Promise<boolean>;
5
+ /** Ten thousand parts, each with its tag and checksums, fit well inside this. */
6
+ export declare const MAX_COMPLETE_BODY: number;
7
+ /** The most rows one listing answers — S3's number for both. */
8
+ export declare const MAX_LISTED = 1000;
9
+ export declare function beginUpload(call: Call, staging: Staging): Promise<void>;
10
+ export declare function uploadPart(call: Call, staging: Staging, uploadId: string, maxObjectBytes?: number): Promise<void>;
11
+ export declare function completeUpload(call: Call, staging: Staging, uploadId: string): Promise<void>;
12
+ export declare function abortUpload(call: Call, staging: Staging, uploadId: string): Promise<void>;
13
+ /** `ListParts`: the pieces of one upload, a page at a time. */
14
+ export declare function listParts(call: Call, staging: Staging | undefined, uploadId: string): Promise<void>;
15
+ /**
16
+ * `ListMultipartUploads`: every upload begun here and not yet finished or aborted.
17
+ *
18
+ * ⚠ A READ-ONLY DRIVE HAS NONE, and says so with an empty list rather than a refusal: the question
19
+ * has a true answer, and `rclone cleanup` asks it before deciding there is nothing to clean.
20
+ *
21
+ * ⛔ PAGED OVER ROWS, NOT UPLOADS. A common prefix is one row however many uploads it stands for,
22
+ * and the next page resumes after the last row answered — the prefix itself, when that is what
23
+ * it was, so none of the uploads it stood for come back on the next page as if new. And one
24
+ * key's uploads resume after the marker's id whether or not that upload still exists: ids sort
25
+ * by when they began (`staging.ts`), so an upload finished between two pages costs the listing
26
+ * nothing.
27
+ */
28
+ export declare function listUploads(call: Call, staging: Staging | undefined): Promise<void>;
@@ -10,95 +10,210 @@
10
10
  // The out-of-order part is the one a from-the-specification implementation gets wrong, because
11
11
  // reading the spec top to bottom suggests a sequence.
12
12
  //
13
+ // ⛔ THE PART LIST THE CLIENT SENDS IS WHAT THE FILE IS MADE OF. A client may stage a piece it then
14
+ // leaves out — a retry that sent part 3 twice under different numbers, a resumed upload that
15
+ // re-cut its pieces — and S3 builds the object from the list, checking each listed tag against
16
+ // what it staged. Joining everything staged instead makes a file that is longer than the one
17
+ // the client meant, and reports it as stored.
18
+ //
13
19
  // ⚠ THE PIECES ARE STAGED, and staging is the caller's business rather than this file's: this
14
- // module speaks the protocol and the writer it is handed does the filesystem.
15
- import { isKeyConflict } from "./same-file.js";
20
+ // module speaks the protocol and the staging it is handed does the filesystem.
21
+ import { S3Refusal, sendXml } from "./answer.js";
22
+ import { BodyRefusal, decodeBody } from "./body.js";
23
+ import { headerOf, metaOf } from "./call.js";
24
+ import { algorithmOfHeader, parseChecksumValue } from "./checksum.js";
25
+ import { refuseConditions, writeConditionOf } from "./drive-conditions.js";
26
+ import { checkKey } from "./drive-key.js";
27
+ import { checkDeclaredSize } from "./drive-limits.js";
28
+ import { precheck } from "./drive-write.js";
29
+ import { compareKeys, isFolderKey, objectsOf } from "./listing.js";
30
+ import { answerAfter } from "./long-answer.js";
31
+ import { consuming, readBodyText } from "./spool.js";
16
32
  import { completeUploadXml, initiateUploadXml } from "./xml.js";
33
+ import { listPartsXml, listUploadsXml } from "./xml-multipart.js";
34
+ import { completeAskOf, parseXml } from "./xml-read.js";
17
35
  /** S3's own ceiling, and a bound on what one client can stage on this machine. */
18
36
  export const MAX_PARTS = 10_000;
19
- /** True when this request belongs to a multipart upload rather than a plain object call. */
20
- export function isMultipartRequest(method, query) {
21
- return query.has("uploads") || query.has("uploadId") || method === "POST";
37
+ /** Ten thousand parts, each with its tag and checksums, fit well inside this. */
38
+ export const MAX_COMPLETE_BODY = 4 * 1024 * 1024;
39
+ /** The most rows one listing answers — S3's number for both. */
40
+ export const MAX_LISTED = 1000;
41
+ /** An integer query parameter, clamped, or the fallback when it is absent or not a number. */
42
+ function intParam(query, name, fallback, max) {
43
+ const raw = query.get(name);
44
+ if (raw === null || !/^\d{1,9}$/.test(raw.trim()))
45
+ return fallback;
46
+ return Math.min(Number(raw.trim()), max);
47
+ }
48
+ export async function beginUpload(call, staging) {
49
+ checkKey(call.key);
50
+ if (isFolderKey(call.key)) {
51
+ throw new S3Refusal(400, "InvalidArgument", "A key ending in `/` names a folder, which is not uploaded in parts.");
52
+ }
53
+ refuseConditions(call.req, "CreateMultipartUpload");
54
+ const uploadId = await staging.begin(call.key, metaOf(call.req));
55
+ sendXml(call.res, 200, initiateUploadXml(call.bucket, call.key, uploadId));
22
56
  }
23
- function send(res, body) {
24
- res.writeHead(200, {
25
- "content-type": "application/xml",
26
- "content-length": String(Buffer.byteLength(body)),
57
+ export async function uploadPart(call, staging, uploadId, maxObjectBytes) {
58
+ const raw = call.query.get("partNumber") ?? "";
59
+ const partNumber = /^\d{1,5}$/.test(raw) ? Number(raw) : 0;
60
+ if (partNumber < 1 || partNumber > MAX_PARTS) {
61
+ const why = `Part number must be an integer between 1 and ${MAX_PARTS}, inclusive.`;
62
+ throw new S3Refusal(400, "InvalidArgument", why);
63
+ }
64
+ refuseConditions(call.req, "UploadPart");
65
+ const body = decodeBody(call.req, call.verdict);
66
+ if (body instanceof BodyRefusal)
67
+ throw body;
68
+ const etag = await consuming(body, async () => {
69
+ checkDeclaredSize(body.size, maxObjectBytes);
70
+ return await staging.part(uploadId, call.key, partNumber, body);
27
71
  });
28
- res.end(body);
72
+ call.res.writeHead(200, { etag, "content-length": "0" });
73
+ call.res.end();
29
74
  }
30
- /** Answer one multipart request. Returns false when the shape is not one this gateway knows. */
31
- export async function handleMultipart(context) {
32
- const { method, query, writer, key, res, req } = context;
33
- const staging = writer.multipart;
34
- if (staging === undefined) {
35
- context.fail(501, "NotImplemented", "This gateway does not stage multipart uploads.");
36
- return true;
75
+ /**
76
+ * The whole object's checksum a finish names, if it names one.
77
+ *
78
+ * ⚠ S3's DEFAULT KIND IS COMPOSITE, except for CRC64NVME, which is only ever full-object. A
79
+ * composite value may carry `-N` after it, the number of parts, which is not part of the value.
80
+ */
81
+ function objectChecksumOf(call) {
82
+ let found = null;
83
+ const typed = headerOf(call.req, "x-amz-checksum-type")?.trim().toUpperCase();
84
+ if (typed !== undefined && typed !== "FULL_OBJECT" && typed !== "COMPOSITE") {
85
+ throw new S3Refusal(400, "InvalidRequest", `x-amz-checksum-type is FULL_OBJECT or COMPOSITE, not ${typed}.`);
37
86
  }
38
- if (method === "POST" && query.has("uploads")) {
39
- const uploadId = await staging.begin(key);
40
- send(res, initiateUploadXml(context.bucket, key, uploadId));
41
- context.log?.(`multipart begin ${key}`);
42
- return true;
87
+ for (const [name, raw] of Object.entries(call.req.headers)) {
88
+ const algorithm = algorithmOfHeader(name);
89
+ if (algorithm === null)
90
+ continue;
91
+ const text = (Array.isArray(raw) ? raw.join(",") : (raw ?? "")).trim().replace(/-\d+$/, "");
92
+ const value = parseChecksumValue(algorithm, text);
93
+ if (value === null)
94
+ throw new S3Refusal(400, "InvalidRequest", `${name} is not a ${algorithm} value.`);
95
+ if (found !== null)
96
+ throw new S3Refusal(400, "InvalidRequest", "A finish may name one checksum of the whole object.");
97
+ const type = typed ?? (algorithm === "crc64nvme" ? "FULL_OBJECT" : "COMPOSITE");
98
+ found = { algorithm, value, type };
43
99
  }
44
- const uploadId = query.get("uploadId");
45
- if (uploadId === null)
46
- return false;
47
- if (method === "PUT") {
48
- const partNumber = Number(query.get("partNumber") ?? "");
49
- if (!Number.isInteger(partNumber) || partNumber < 1 || partNumber > MAX_PARTS) {
50
- context.fail(400, "InvalidPart", `A part number must be between 1 and ${MAX_PARTS}.`);
51
- return true;
52
- }
53
- const size = Number(req.headers["content-length"] ?? "");
54
- if (!Number.isInteger(size) || size < 0) {
55
- context.fail(411, "MissingContentLength", "This gateway needs the part's size before it starts.");
56
- return true;
57
- }
58
- try {
59
- const etag = await staging.part(uploadId, partNumber, req, size, context.payloadHash);
60
- res.writeHead(200, { etag, "content-length": "0" });
61
- res.end();
62
- }
63
- catch (error) {
64
- context.fail(400, "InvalidPart", error instanceof Error ? error.message : String(error));
65
- }
66
- return true;
100
+ return found;
101
+ }
102
+ export async function completeUpload(call, staging, uploadId) {
103
+ const condition = writeConditionOf(call.req, "CompleteMultipartUpload");
104
+ const checksum = objectChecksumOf(call);
105
+ // ⛔ `x-amz-checksum-*` HERE IS THE OBJECT'S, NOT THE PART LIST'S — see `multipart-assemble.ts`.
106
+ const body = decodeBody(call.req, call.verdict, { checksumsDescribeObject: true });
107
+ if (body instanceof BodyRefusal)
108
+ throw body;
109
+ const text = await consuming(body, () => readBodyText(body, MAX_COMPLETE_BODY, "The part list"));
110
+ const parts = completeAskOf(parseXml(text));
111
+ precheck(objectsOf(await call.source.entries()), call.key, condition);
112
+ // ⛔ The 200 begins when the staging says the upload and the list hold — see `long-answer.ts`.
113
+ await answerAfter(call, async (accepted) => {
114
+ const outcome = await staging.complete(uploadId, call.key, parts, { accepted, condition, checksum });
115
+ return completeUploadXml(call.bucket, call.key, outcome.etag);
116
+ });
117
+ }
118
+ export async function abortUpload(call, staging, uploadId) {
119
+ refuseConditions(call.req, "AbortMultipartUpload");
120
+ await staging.abort(uploadId, call.key);
121
+ call.res.writeHead(204);
122
+ call.res.end();
123
+ }
124
+ /** `ListParts`: the pieces of one upload, a page at a time. */
125
+ export async function listParts(call, staging, uploadId) {
126
+ if (staging === undefined) {
127
+ throw new S3Refusal(404, "NoSuchUpload", "No upload is in progress with that id.");
67
128
  }
68
- if (method === "POST") {
69
- // ⛔ THE PART LIST IN THE BODY IS NOT READ. It carries the tags this gateway itself handed back,
70
- // so believing it would be believing our own echo; what the file is made of is what was
71
- // staged, in part-number order. Reading it would only add a way to disagree with ourselves.
72
- await drain(req);
73
- try {
74
- const etag = await staging.complete(uploadId);
75
- send(res, completeUploadXml(context.bucket, key, etag));
76
- context.log?.(`multipart complete ${key}`);
77
- }
78
- catch (error) {
79
- // ⛔ A KEY THAT HOLDS A DIFFERENT FILE IS A 409, NOT A 500 — the request was well formed and
80
- // the drive declined it. Told 500, a sync tool retries the whole upload forever; told 409
81
- // it records a conflict and moves on. The verdict itself is the writer's (`same-file.ts`),
82
- // reached only once the pieces are one file, because until then there is nothing to hash.
83
- if (isKeyConflict(error)) {
84
- context.fail(409, "InvalidRequest", error instanceof Error ? error.message : String(error));
85
- }
86
- else {
87
- context.fail(500, "InternalError", error instanceof Error ? error.message : String(error));
88
- }
129
+ const all = await staging.parts(uploadId, call.key);
130
+ const marker = intParam(call.query, "part-number-marker", 0, MAX_PARTS);
131
+ const maxParts = intParam(call.query, "max-parts", MAX_LISTED, MAX_LISTED);
132
+ const after = all.filter((part) => part.partNumber > marker);
133
+ const page = after.slice(0, maxParts);
134
+ const meta = (await staging.uploads()).find((upload) => upload.uploadId === uploadId)?.meta;
135
+ sendXml(call.res, 200, listPartsXml({
136
+ bucket: call.bucket,
137
+ key: call.key,
138
+ uploadId,
139
+ storageClass: meta?.storageClass ?? "STANDARD",
140
+ marker,
141
+ maxParts,
142
+ parts: page.map((part) => ({ ...part, lastModified: new Date(part.stagedAt).toISOString() })),
143
+ truncated: after.length > page.length,
144
+ }));
145
+ }
146
+ /**
147
+ * `ListMultipartUploads`: every upload begun here and not yet finished or aborted.
148
+ *
149
+ * ⚠ A READ-ONLY DRIVE HAS NONE, and says so with an empty list rather than a refusal: the question
150
+ * has a true answer, and `rclone cleanup` asks it before deciding there is nothing to clean.
151
+ *
152
+ * ⛔ PAGED OVER ROWS, NOT UPLOADS. A common prefix is one row however many uploads it stands for,
153
+ * and the next page resumes after the last row answered — the prefix itself, when that is what
154
+ * it was, so none of the uploads it stood for come back on the next page as if new. And one
155
+ * key's uploads resume after the marker's id whether or not that upload still exists: ids sort
156
+ * by when they began (`staging.ts`), so an upload finished between two pages costs the listing
157
+ * nothing.
158
+ */
159
+ export async function listUploads(call, staging) {
160
+ const query = call.query;
161
+ const prefix = query.get("prefix") ?? "";
162
+ const delimiter = query.get("delimiter") ?? "";
163
+ const keyMarker = query.get("key-marker") ?? "";
164
+ const uploadIdMarker = query.get("upload-id-marker") ?? "";
165
+ const maxUploads = intParam(query, "max-uploads", MAX_LISTED, MAX_LISTED);
166
+ const all = (staging === undefined ? [] : await staging.uploads()).filter((upload) => upload.key.startsWith(prefix));
167
+ const rows = [];
168
+ const grouped = new Set();
169
+ for (const upload of all) {
170
+ const rest = upload.key.slice(prefix.length);
171
+ const at = delimiter === "" ? -1 : rest.indexOf(delimiter);
172
+ if (at < 0) {
173
+ rows.push({ sort: upload.key, upload });
174
+ continue;
89
175
  }
90
- return true;
176
+ const common = prefix + rest.slice(0, at + delimiter.length);
177
+ if (grouped.has(common))
178
+ continue;
179
+ grouped.add(common);
180
+ rows.push({ sort: common, upload: null });
91
181
  }
92
- if (method === "DELETE") {
93
- await staging.abort(uploadId);
94
- res.writeHead(204);
95
- res.end();
96
- context.log?.(`multipart abort ${key}`);
97
- return true;
182
+ const idOf = (row) => row.upload?.uploadId ?? "";
183
+ rows.sort((a, b) => compareKeys(a.sort, b.sort) || (idOf(a) < idOf(b) ? -1 : idOf(a) > idOf(b) ? 1 : 0));
184
+ const started = keyMarker === ""
185
+ ? rows
186
+ : rows.filter((row) => compareKeys(row.sort, keyMarker) > 0 ||
187
+ (row.upload !== null && row.sort === keyMarker && uploadIdMarker !== "" && idOf(row) > uploadIdMarker));
188
+ const page = started.slice(0, maxUploads);
189
+ const truncated = maxUploads > 0 && started.length > page.length;
190
+ const last = page[page.length - 1];
191
+ const uploads = [];
192
+ const commonPrefixes = [];
193
+ for (const row of page) {
194
+ if (row.upload === null) {
195
+ commonPrefixes.push(row.sort);
196
+ continue;
197
+ }
198
+ uploads.push({
199
+ key: row.upload.key,
200
+ uploadId: row.upload.uploadId,
201
+ initiated: new Date(row.upload.initiated).toISOString(),
202
+ storageClass: row.upload.meta.storageClass ?? "STANDARD",
203
+ });
98
204
  }
99
- return false;
100
- }
101
- async function drain(req) {
102
- for await (const chunk of req)
103
- void chunk;
205
+ sendXml(call.res, 200, listUploadsXml({
206
+ bucket: call.bucket,
207
+ prefix,
208
+ delimiter,
209
+ keyMarker,
210
+ uploadIdMarker,
211
+ maxUploads,
212
+ uploads,
213
+ commonPrefixes,
214
+ truncated,
215
+ nextKeyMarker: truncated && last !== undefined ? last.sort : "",
216
+ nextUploadIdMarker: truncated && last !== undefined ? idOf(last) : "",
217
+ encodingType: query.get("encoding-type"),
218
+ }));
104
219
  }
@@ -0,0 +1,17 @@
1
+ import { type Call } from "./call.ts";
2
+ import { type DriveObject } from "./listing.ts";
3
+ /**
4
+ * The headers a file is answered with.
5
+ *
6
+ * ⛔ A FILE IS NEVER A PAGE OF THE GATEWAY'S ORIGIN. A business serves its users' files from its own
7
+ * host, often through presigned links a browser opens, and a file named `.html` or `.svg` is
8
+ * answered with a type a browser runs. `Content-Security-Policy: sandbox` makes whatever it runs
9
+ * run in an origin of its own, with no scripts and no reach into the host's cookies or storage;
10
+ * `nosniff` keeps a browser from deciding that a file sent as bytes or text is script after all.
11
+ * A business that wants its users' files downloaded rather than shown says so per link, with
12
+ * `response-content-disposition` (below).
13
+ */
14
+ export declare function objectHeaders(object: DriveObject): Record<string, string>;
15
+ /** The live file at this call's key, or a 404 already answered. */
16
+ export declare function objectAt(call: Call): Promise<DriveObject | null>;
17
+ export declare function readObject(call: Call, head: boolean): Promise<void>;