@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
package/dist/s3/routes.js CHANGED
@@ -1,52 +1,21 @@
1
- // Which answer an S3 request gets: the signature first, then the bucket, then the verb.
1
+ // Which answer an S3 request gets: the signature first, then the bucket, then the operation.
2
2
  //
3
- // ⛔ WHAT IS NOT ANSWERED IS REFUSED, LOUDLY. An S3 client that asks for something this gateway does
4
- // not do gets 501 and a sentence naming what it does do. The alternative -- answering an empty
5
- // listing, or a 200 with nothing behind it -- is how a backup tool reports success over a backup
6
- // that never happened.
7
- import { listObjects, objectsOf, folderPrefixesOf, MAX_KEYS_LIMIT } from "./listing.js";
8
- import { handleMultipart, isMultipartRequest } from "./multipart.js";
9
- import { responseSink } from "./response-sink.js";
10
- import { isKeyConflict } from "./same-file.js";
11
- import { STREAMING_PAYLOAD, STREAMING_PAYLOAD_TRAILER, verifyAgainst, } from "./sigv4.js";
12
- import { errorXml, listBucketsXml, listObjectsXml } from "./xml.js";
13
- /**
14
- * What a caller signed with a pair it may not use here.
15
- *
16
- * ⛔ THE SAME ANSWER WHETHER OR NOT THE BUCKET EXISTS, which is why the restriction is checked
17
- * before the resolver is asked. Answering `NoSuchBucket` for a name the caller may not touch
18
- * would turn this gateway into a way of asking "does this business have a customer called…",
19
- * one guess at a time.
20
- */
21
- const NOT_YOURS = "That access key may not use that bucket.";
22
- export function fail(res, status, code, message, resource) {
23
- const body = errorXml(code, message, resource);
24
- res.writeHead(status, { "content-type": "application/xml", "content-length": String(Buffer.byteLength(body)) });
25
- res.end(body);
26
- }
27
- /** `/drive/photos/a.jpg` → bucket `drive`, key `photos/a.jpg`. */
28
- function splitPath(pathname) {
29
- const trimmed = pathname.replace(/^\//, "");
30
- const at = trimmed.indexOf("/");
31
- if (at < 0)
32
- return { bucket: decodeURIComponent(trimmed), key: "" };
33
- return { bucket: decodeURIComponent(trimmed.slice(0, at)), key: decodeURIComponent(trimmed.slice(at + 1)) };
34
- }
35
- function headerOf(req, name) {
36
- const raw = req.headers[name];
37
- return Array.isArray(raw) ? raw.join(",") : raw;
38
- }
39
- /** The one sentence a write gets from `nmts s3` when this machine has not agreed to spending. */
40
- function readOnlyOnThisMachine() {
41
- return ("This gateway is read only. Uploading spends credits, and this machine has not agreed to " +
42
- "spending — `nmts consent grant spend`, run by the person whose account this is, is what " +
43
- "changes that. Nothing was written.");
44
- }
45
- /** Whether the pair that signed is allowed anywhere near this bucket name. */
46
- function mayTouch(credential, bucket) {
47
- const only = credential.buckets;
48
- return only === undefined || only.includes(bucket);
49
- }
3
+ // ⛔ WHAT IS NOT ANSWERED IS REFUSED, LOUDLY. Every request is classified before anything is read
4
+ // or written — the verb, whether it names a key, and which sub-resource it asks about — and a
5
+ // combination this gateway does not do gets 501 and a sentence naming it. The alternative --
6
+ // answering an empty listing, or a 200 with nothing behind it, or the file itself for a question
7
+ // about the file -- is how a backup tool reports success over a backup that never happened.
8
+ import { failWith, refuse, S3Refusal, sendXml } from "./answer.js";
9
+ import { addressOf, subResourceOf } from "./address.js";
10
+ import { headerOf, mayTouch, NOT_YOURS, readOnlyBecause } from "./call.js";
11
+ import { MAX_CONCURRENT_WRITES, RETRY_AFTER_SECONDS } from "./drive-limits.js";
12
+ import { queryParts } from "./sigv4-canonical.js";
13
+ import { folderPrefixesOf, listObjects, MAX_KEYS_LIMIT, objectsOf } from "./listing.js";
14
+ import { abortUpload, beginUpload, completeUpload, listParts, listUploads, uploadPart } from "./multipart.js";
15
+ import { readObject } from "./object-read.js";
16
+ import { copyObject, deleteObject, deleteObjects, putObject } from "./object-write.js";
17
+ import { verifyAgainst } from "./sigv4.js";
18
+ import { listBucketsXml, listObjectsXml, locationXml, versioningXml } from "./xml.js";
50
19
  /** What `ListBuckets` says: what the gateway can name, narrowed to what this pair may touch. */
51
20
  async function bucketsFor(options, credential) {
52
21
  const only = credential.buckets;
@@ -55,195 +24,251 @@ async function bucketsFor(options, credential) {
55
24
  const named = await options.bucketNames();
56
25
  return only === undefined ? named : named.filter((name) => only.includes(name));
57
26
  }
58
- function objectHeaders(object) {
59
- return {
60
- "content-type": "application/octet-stream",
61
- "last-modified": new Date(object.entry.updatedAt).toUTCString(),
62
- etag: object.etag,
63
- "accept-ranges": "none",
64
- };
27
+ /**
28
+ * `max-keys` as S3 reads it: absent is the ceiling, above it is the ceiling, zero is zero keys, and
29
+ * anything that is not a whole number of zero or more is refused.
30
+ *
31
+ * ⛔ THE NUMBER APPLIED IS THE NUMBER ECHOED in `<MaxKeys>`. `0` used to be read as "not given" and
32
+ * answered a thousand keys, and a negative number sliced the listing from its far end.
33
+ */
34
+ function maxKeysOf(query) {
35
+ const raw = query.get("max-keys");
36
+ if (raw === null)
37
+ return MAX_KEYS_LIMIT;
38
+ const trimmed = raw.trim();
39
+ if (!/^-?\d+$/.test(trimmed)) {
40
+ throw new S3Refusal(400, "InvalidArgument", "Provided max-keys not an integer or within integer range.");
41
+ }
42
+ const asked = Number(trimmed);
43
+ if (asked < 0)
44
+ throw new S3Refusal(400, "InvalidArgument", "max-keys must be zero or more.");
45
+ return Math.min(asked, MAX_KEYS_LIMIT);
46
+ }
47
+ /**
48
+ * The query, decoded exactly as the signature decodes it.
49
+ *
50
+ * ⛔ ONE DECODING. `URLSearchParams` reads `+` as a space and the signature check, like S3, reads
51
+ * it as `+`: a prefix of `a+b` was signed as one string and answered as another. Every
52
+ * parameter is taken from the same decoder the signature used, so what was signed is what is
53
+ * answered.
54
+ */
55
+ function queryOf(raw) {
56
+ const query = new URLSearchParams();
57
+ for (const part of queryParts(raw))
58
+ query.append(part.key, part.value);
59
+ return query;
60
+ }
61
+ /** How many writes are running now, per gateway. */
62
+ const writesRunning = new WeakMap();
63
+ /**
64
+ * Run one write, or answer `SlowDown` when the gateway is already running as many as it allows.
65
+ *
66
+ * ⛔ A CEILING ON WHAT IS HELD AT ONCE. Every write in flight holds a spool of somebody's bytes on
67
+ * this disk and a connection to the network behind it; with no ceiling a client that opens a
68
+ * thousand uploads at once holds a thousand. S3's own answer to "too much at once" is 503
69
+ * `SlowDown`, and every client waits and sends again.
70
+ */
71
+ async function limited(call, work) {
72
+ const ceiling = call.options.maxConcurrentWrites ?? MAX_CONCURRENT_WRITES;
73
+ let running = writesRunning.get(call.options);
74
+ if (running === undefined) {
75
+ running = { count: 0 };
76
+ writesRunning.set(call.options, running);
77
+ }
78
+ if (running.count >= ceiling) {
79
+ refuse(call.res, 503, "SlowDown", `This gateway is already running ${running.count} writes, the most it runs at once. Send it again shortly.`, call.resource, { "retry-after": String(RETRY_AFTER_SECONDS) });
80
+ return;
81
+ }
82
+ running.count += 1;
83
+ try {
84
+ await work();
85
+ }
86
+ finally {
87
+ running.count -= 1;
88
+ }
89
+ }
90
+ async function listBucket(call) {
91
+ const { query } = call;
92
+ const maxKeys = maxKeysOf(query);
93
+ const entries = await call.source.entries();
94
+ const prefix = query.get("prefix") ?? "";
95
+ const delimiter = query.get("delimiter") ?? "";
96
+ const listing = listObjects(objectsOf(entries), folderPrefixesOf(entries), {
97
+ prefix,
98
+ delimiter,
99
+ maxKeys,
100
+ after: query.get("continuation-token") ?? query.get("start-after") ?? query.get("marker"),
101
+ });
102
+ sendXml(call.res, 200, listObjectsXml({
103
+ bucket: call.bucket,
104
+ prefix,
105
+ delimiter,
106
+ maxKeys,
107
+ v2: query.get("list-type") === "2",
108
+ contents: listing.contents,
109
+ commonPrefixes: listing.commonPrefixes,
110
+ truncated: listing.truncated,
111
+ next: listing.next,
112
+ encodingType: query.get("encoding-type"),
113
+ }));
114
+ }
115
+ /** Classify one request against its bucket. Nothing is read or written until `run`. */
116
+ function routeOf(call) {
117
+ const { method, query, key, res, resource, options } = call;
118
+ const sub = subResourceOf(query);
119
+ const writer = call.source.write;
120
+ const staging = writer?.multipart;
121
+ const notDone = (why) => ({
122
+ name: "NotImplemented",
123
+ run: () => refuse(res, 501, "NotImplemented", why, resource),
124
+ });
125
+ const writing = (name, run) => writer === undefined
126
+ ? { name, run: () => refuse(res, 501, "NotImplemented", readOnlyBecause(options), resource) }
127
+ : { name, run: () => limited(call, () => run(writer)) };
128
+ const staged = (name, run) => writing(name, async () => {
129
+ if (staging !== undefined)
130
+ await run(staging);
131
+ else
132
+ refuse(res, 501, "NotImplemented", "This gateway does not stage multipart uploads.", resource);
133
+ });
134
+ if (key === "") {
135
+ const read = method === "GET" || method === "HEAD";
136
+ if (sub === "location" && read)
137
+ return { name: "GetBucketLocation", run: () => sendXml(res, 200, locationXml()) };
138
+ if (sub === "versioning" && method === "GET") {
139
+ return { name: "GetBucketVersioning", run: () => sendXml(res, 200, versioningXml()) };
140
+ }
141
+ if (sub === "uploads" && method === "GET") {
142
+ return { name: "ListMultipartUploads", run: () => listUploads(call, staging) };
143
+ }
144
+ if (sub === "delete" && method === "POST")
145
+ return writing("DeleteObjects", (w) => deleteObjects(call, w));
146
+ if (sub !== null)
147
+ return notDone(`This gateway does not answer ${method} ?${sub} on a bucket.`);
148
+ if (method === "HEAD") {
149
+ return {
150
+ name: "HeadBucket",
151
+ run: () => {
152
+ res.writeHead(200, { "x-amz-bucket-region": "us-east-1", "content-length": "0" });
153
+ res.end();
154
+ },
155
+ };
156
+ }
157
+ if (method === "GET") {
158
+ return { name: query.get("list-type") === "2" ? "ListObjectsV2" : "ListObjects", run: () => listBucket(call) };
159
+ }
160
+ // ⛔ MEASURED, NOT GUESSED: rclone's first act when copying a file is to create the bucket, and
161
+ // a refusal here ends the copy before the upload is ever attempted. The bucket exists, so the
162
+ // honest answer to "make it" is that it is made.
163
+ if (method === "PUT") {
164
+ return {
165
+ name: "CreateBucket",
166
+ run: () => {
167
+ res.writeHead(200, { "content-length": "0" });
168
+ res.end();
169
+ },
170
+ };
171
+ }
172
+ return notDone(`This gateway does not answer ${method} on a bucket.`);
173
+ }
174
+ const uploadId = query.get("uploadId");
175
+ if (sub === "uploads") {
176
+ return method === "POST"
177
+ ? staged("CreateMultipartUpload", (s) => beginUpload(call, s))
178
+ : notDone(`This gateway does not answer ${method} ?uploads on a key.`);
179
+ }
180
+ if (sub !== null)
181
+ return notDone(`This gateway does not answer ${method} ?${sub}.`);
182
+ if (uploadId !== null) {
183
+ if (method === "GET")
184
+ return { name: "ListParts", run: () => listParts(call, staging, uploadId) };
185
+ if (method === "PUT" && headerOf(call.req, "x-amz-copy-source") !== undefined) {
186
+ return notDone("This gateway does not copy into a part (UploadPartCopy). Upload the part's bytes instead.");
187
+ }
188
+ if (method === "PUT")
189
+ return staged("UploadPart", (s) => uploadPart(call, s, uploadId, writer?.maxObjectBytes));
190
+ if (method === "POST")
191
+ return staged("CompleteMultipartUpload", (s) => completeUpload(call, s, uploadId));
192
+ if (method === "DELETE")
193
+ return staged("AbortMultipartUpload", (s) => abortUpload(call, s, uploadId));
194
+ return notDone(`This gateway does not answer ${method} on an upload.`);
195
+ }
196
+ if (method === "GET" || method === "HEAD") {
197
+ return { name: method === "GET" ? "GetObject" : "HeadObject", run: () => readObject(call, method === "HEAD") };
198
+ }
199
+ if (method === "PUT") {
200
+ const copySource = headerOf(call.req, "x-amz-copy-source");
201
+ return copySource === undefined
202
+ ? writing("PutObject", (w) => putObject(call, w))
203
+ : writing("CopyObject", (w) => copyObject(call, w, copySource));
204
+ }
205
+ if (method === "DELETE")
206
+ return writing("DeleteObject", (w) => deleteObject(call, w));
207
+ return notDone(`This gateway does not answer ${method} on that address.`);
65
208
  }
66
209
  export async function handle(req, res, options) {
67
210
  const url = req.url ?? "/";
68
211
  const at = url.indexOf("?");
69
212
  const pathname = at < 0 ? url : url.slice(0, at);
70
- const query = new URLSearchParams(at < 0 ? "" : url.slice(at + 1));
71
213
  const method = (req.method ?? "GET").toUpperCase();
72
- const verdict = verifyAgainst({ method, url, headers: req.headers }, options.credentials, options.now?.() ?? Date.now());
73
- if (!verdict.ok) {
74
- fail(res, 403, verdict.code, verdict.message, pathname);
75
- return;
76
- }
77
- const credential = verdict.credential;
78
- const { bucket, key } = splitPath(pathname);
79
- if (pathname === "/" && (method === "GET" || method === "HEAD")) {
80
- const body = listBucketsXml(await bucketsFor(options, credential), new Date(0).toISOString());
81
- res.writeHead(200, { "content-type": "application/xml", "content-length": String(Buffer.byteLength(body)) });
82
- res.end(method === "HEAD" ? undefined : body);
83
- return;
214
+ // ⛔ ONE LINE PER REQUEST: THE OPERATION AND THE STATUS. See `GatewayOptions.log` for why never a key.
215
+ let operation = "Refused";
216
+ const log = options.log;
217
+ if (log !== undefined)
218
+ res.once("close", () => log(`${operation} ${res.statusCode}`));
219
+ let verdict;
220
+ let query;
221
+ try {
222
+ verdict = verifyAgainst({ method, url, headers: req.headers }, options.credentials, options.now?.() ?? Date.now());
223
+ query = queryOf(at < 0 ? "" : url.slice(at + 1));
84
224
  }
85
- if (!mayTouch(credential, bucket)) {
86
- fail(res, 403, "AccessDenied", NOT_YOURS, pathname);
225
+ catch (error) {
226
+ // The canonical query decodes every parameter, and a malformed one throws there.
227
+ if (!(error instanceof URIError))
228
+ throw error;
229
+ refuse(res, 400, "InvalidURI", "The query string is not valid percent-encoding.", pathname);
87
230
  return;
88
231
  }
89
- const source = await options.bucketOf(bucket);
90
- if (source === null) {
91
- fail(res, 404, "NoSuchBucket", `No bucket named ${bucket} is served here.`, pathname);
232
+ if (!verdict.ok) {
233
+ refuse(res, 403, verdict.code, verdict.message, pathname);
92
234
  return;
93
235
  }
94
- // ⛔ MEASURED, NOT GUESSED: rclone's first act when copying a file is to create the bucket, and a
95
- // refusal here ends the copy before the upload is ever attempted. The bucket exists, so the
96
- // honest answer to "make it" is that it is made.
97
- if (key === "" && method === "PUT") {
98
- res.writeHead(200, { "content-length": "0" });
99
- res.end();
100
- return;
236
+ const credential = verdict.credential;
237
+ let address;
238
+ try {
239
+ address = addressOf(pathname, headerOf(req, "host"), options.virtualHostBase);
101
240
  }
102
- const entries = await source.entries();
103
- if (key === "" && (method === "GET" || method === "HEAD")) {
104
- const objects = objectsOf(entries);
105
- const listing = listObjects(objects, folderPrefixesOf(entries), {
106
- prefix: query.get("prefix") ?? "",
107
- delimiter: query.get("delimiter") ?? "",
108
- maxKeys: Number(query.get("max-keys") ?? MAX_KEYS_LIMIT) || MAX_KEYS_LIMIT,
109
- after: query.get("continuation-token") ?? query.get("start-after") ?? query.get("marker"),
110
- });
111
- const body = listObjectsXml({
112
- bucket,
113
- prefix: query.get("prefix") ?? "",
114
- delimiter: query.get("delimiter") ?? "",
115
- maxKeys: Number(query.get("max-keys") ?? MAX_KEYS_LIMIT) || MAX_KEYS_LIMIT,
116
- v2: query.get("list-type") === "2",
117
- contents: listing.contents,
118
- commonPrefixes: listing.commonPrefixes,
119
- truncated: listing.truncated,
120
- next: listing.next,
121
- encodingType: query.get("encoding-type"),
122
- });
123
- res.writeHead(200, { "content-type": "application/xml", "content-length": String(Buffer.byteLength(body)) });
124
- res.end(method === "HEAD" ? undefined : body);
125
- options.log?.(`${method} list prefix=${query.get("prefix") ?? ""} → ${listing.contents.length} keys`);
241
+ catch (error) {
242
+ failWith(res, error, pathname);
126
243
  return;
127
244
  }
128
- if (method === "HEAD" || method === "GET") {
129
- const object = objectsOf(entries).find((o) => o.key === key);
130
- if (object === undefined) {
131
- fail(res, 404, "NoSuchKey", "This account's file list has no such file.", pathname);
132
- return;
133
- }
134
- if (method === "HEAD") {
135
- res.writeHead(200, { ...objectHeaders(object), "content-length": String(object.size) });
136
- res.end();
137
- options.log?.(`HEAD ${key}`);
245
+ if (address.bucket === "") {
246
+ if (method !== "GET" && method !== "HEAD") {
247
+ operation = "NotImplemented";
248
+ refuse(res, 501, "NotImplemented", `This gateway does not answer ${method} on the service.`, pathname);
138
249
  return;
139
250
  }
140
- if (object.entry.dekWrapped === undefined) {
141
- fail(res, 500, "InternalError", "That entry has no key in the file list.", pathname);
142
- return;
143
- }
144
- const sink = responseSink(res, { headers: objectHeaders(object) });
145
- try {
146
- await source.fetch(object, sink);
147
- options.log?.(`GET ${key} → ${object.size} bytes`);
148
- }
149
- catch (error) {
150
- await sink.abandon();
151
- if (!res.headersSent) {
152
- fail(res, 502, "InternalError", error instanceof Error ? error.message : String(error), pathname);
153
- }
154
- options.log?.(`GET ${key} → failed`);
155
- }
251
+ operation = "ListBuckets";
252
+ sendXml(res, 200, listBucketsXml(await bucketsFor(options, credential), new Date(0).toISOString()));
156
253
  return;
157
254
  }
158
- const writer = source.write;
159
- // ⛔ WHETHER A TAKEN KEY IS A CONFLICT IS NOT DECIDED HERE.
160
- // It used to be, on the strength of the NAME alone, and both upload paths carried their own
161
- // copy of that check. The question is now about CONTENT — is the file arriving the file
162
- // already there — and it cannot be answered until the bytes have arrived, so it is answered
163
- // once, by the writer, at the point both paths meet. What reaches this layer is the verdict:
164
- // a writer that returns normally means the key now holds these bytes (whether it had to send
165
- // them or they were already there), and one that throws a conflict means something else is at
166
- // that key. ⭐ The status matters: 409 is a request the drive declined, 500 is a fault of ours.
167
- const refuseConflict = (error) => {
168
- fail(res, 409, "InvalidRequest", error instanceof Error ? error.message : String(error), pathname);
169
- };
170
- if (isMultipartRequest(method, query) && key !== "") {
171
- if (writer === undefined) {
172
- fail(res, 501, "NotImplemented", options.readOnlyBecause ?? readOnlyOnThisMachine(), pathname);
173
- return;
174
- }
175
- const handled = await handleMultipart({
176
- req,
177
- res,
178
- bucket,
179
- key,
180
- method,
181
- query,
182
- writer,
183
- payloadHash: /^[0-9a-f]{64}$/.test(verdict.payloadHash) ? verdict.payloadHash : null,
184
- fail: (status, code, message) => fail(res, status, code, message, pathname),
185
- ...(options.log === undefined ? {} : { log: options.log }),
186
- });
187
- if (handled)
188
- return;
189
- }
190
- if (method === "PUT" && key !== "") {
191
- if (writer === undefined) {
192
- fail(res, 501, "NotImplemented", options.readOnlyBecause ?? readOnlyOnThisMachine(), pathname);
193
- return;
194
- }
195
- const declared = headerOf(req, "x-amz-content-sha256");
196
- if (declared === STREAMING_PAYLOAD || declared === STREAMING_PAYLOAD_TRAILER) {
197
- fail(res, 501, "NotImplemented", "This gateway does not read chunk-signed uploads yet. Tell the client to send the body " +
198
- "unsigned (the AWS CLI calls this --no-sign-payload on http endpoints; rclone already " +
199
- "does it).", pathname);
200
- return;
201
- }
202
- const length = Number(headerOf(req, "content-length") ?? "");
203
- if (!Number.isInteger(length) || length < 0) {
204
- fail(res, 411, "MissingContentLength", "This gateway needs to know the size before it starts.", pathname);
205
- return;
206
- }
207
- try {
208
- await writer.put(key, req, length);
209
- }
210
- catch (error) {
211
- if (isKeyConflict(error)) {
212
- refuseConflict(error);
213
- return;
214
- }
215
- fail(res, 500, "InternalError", error instanceof Error ? error.message : String(error), pathname);
216
- return;
217
- }
218
- res.writeHead(200, { "content-length": "0" });
219
- res.end();
220
- options.log?.(`PUT ${key} → ${length} bytes`);
255
+ if (!mayTouch(credential, address.bucket)) {
256
+ refuse(res, 403, "AccessDenied", NOT_YOURS, pathname);
221
257
  return;
222
258
  }
223
- if (method === "DELETE" && key !== "") {
224
- if (writer === undefined) {
225
- fail(res, 501, "NotImplemented", options.readOnlyBecause ?? readOnlyOnThisMachine(), pathname);
226
- return;
227
- }
228
- const object = objectsOf(entries).find((o) => o.key === key);
229
- if (object === undefined) {
230
- // S3 answers 204 for a key that is not there, and clients rely on it: a sync that deletes
231
- // the same key twice must not fail the second time.
232
- res.writeHead(204);
233
- res.end();
234
- return;
235
- }
236
- try {
237
- await writer.trash(object);
238
- }
239
- catch (error) {
240
- fail(res, 500, "InternalError", error instanceof Error ? error.message : String(error), pathname);
241
- return;
242
- }
243
- res.writeHead(204);
244
- res.end();
245
- options.log?.(`DELETE ${key} → trash`);
259
+ const source = await options.bucketOf(address.bucket);
260
+ if (source === null) {
261
+ refuse(res, 404, "NoSuchBucket", `No bucket named ${address.bucket} is served here.`, pathname);
246
262
  return;
247
263
  }
248
- fail(res, 501, "NotImplemented", `This gateway does not answer ${method} on that address.`, pathname);
264
+ const { bucket, key } = address;
265
+ const call = { req, res, method, query, bucket, key, resource: pathname, verdict, options, source };
266
+ const route = routeOf(call);
267
+ operation = route.name;
268
+ try {
269
+ await route.run();
270
+ }
271
+ catch (error) {
272
+ failWith(res, error, pathname);
273
+ }
249
274
  }
@@ -1,4 +1,5 @@
1
1
  import type { ManifestEntry } from "../shared/lib/drive/manifest-codec.ts";
2
+ import { type DriveObject } from "./listing.ts";
2
3
  import { NmtsError } from "../errors.ts";
3
4
  /** What this drive holds at a key, compared with what is arriving. */
4
5
  export type SameFile =
@@ -42,6 +43,8 @@ export declare function recordedHash(accountCode: string, contentHashCt: string
42
43
  * and pays nothing for this.
43
44
  */
44
45
  export declare function verdictForKey(entries: readonly ManifestEntry[], key: string, accountCode: string, path: string): Promise<SameFile>;
46
+ /** The same question, for the file already found at the key (or nothing). */
47
+ export declare function verdictFor(standing: DriveObject | undefined, accountCode: string, path: string): Promise<SameFile>;
45
48
  /** The verdict, given what is on record and what arrived. */
46
49
  export declare function compare(recorded: Uint8Array | null | undefined, arriving: Uint8Array): SameFile;
47
50
  /**
@@ -51,4 +54,4 @@ export declare function compare(recorded: Uint8Array | null | undefined, arrivin
51
54
  * file that changed and for a file this drive cannot compare, and the two need different things
52
55
  * from the person reading the log.
53
56
  */
54
- export declare function refusalFor(verdict: "differs" | "unknown", key: string): KeyConflict;
57
+ export declare function refusalFor(verdict: "differs" | "unknown" | "spelling", key: string, standing?: string): KeyConflict;
@@ -14,7 +14,8 @@
14
14
  //
15
15
  // ⛔ "REFUSE" MEANS THE UPLOAD, NOT THE REQUEST. Identical content is answered 200 with nothing
16
16
  // sent and nothing charged, because from the client's side the statement "that file is at that
17
- // key" is true. Only DIFFERENT content is a conflict.
17
+ // key" is true. Only DIFFERENT content is a conflict — and only on a drive that does not replace
18
+ // files (`overwrite: "refuse"`, the default); one that does sends the old file to the trash.
18
19
  import { createHash } from "node:crypto";
19
20
  import { createReadStream } from "node:fs";
20
21
  import { AAD, DERIVED, loadCrypto } from "../crypto.js";
@@ -81,7 +82,10 @@ export async function recordedHash(accountCode, contentHashCt) {
81
82
  * and pays nothing for this.
82
83
  */
83
84
  export async function verdictForKey(entries, key, accountCode, path) {
84
- const standing = objectsOf(entries).find((o) => o.key === key);
85
+ return verdictFor(objectsOf(entries).find((o) => o.key === key), accountCode, path);
86
+ }
87
+ /** The same question, for the file already found at the key (or nothing). */
88
+ export async function verdictFor(standing, accountCode, path) {
85
89
  if (standing === undefined)
86
90
  return "free";
87
91
  return compare(await recordedHash(accountCode, standing.entry.contentHashCt), await hashOfFile(path));
@@ -107,7 +111,12 @@ export function compare(recorded, arriving) {
107
111
  * file that changed and for a file this drive cannot compare, and the two need different things
108
112
  * from the person reading the log.
109
113
  */
110
- export function refusalFor(verdict, key) {
114
+ export function refusalFor(verdict, key, standing = key) {
115
+ if (verdict === "spelling") {
116
+ return new KeyConflict(`A file is already at ${standing}, which is ${key} with its accents written the other way ` +
117
+ "(composed or decomposed Unicode). This drive treats the two as one name and does not replace " +
118
+ "files. Use the spelling the listing shows, or delete that file first.");
119
+ }
111
120
  return new KeyConflict(verdict === "differs"
112
121
  ? `A different file is already at ${key}, and this drive does not replace files. Delete it ` +
113
122
  "first — a delete puts it in the trash, where it stays recoverable for thirty days."
@@ -1,20 +1,70 @@
1
- import { type IncomingMessage, type Server, type ServerResponse } from "node:http";
1
+ import { type IncomingMessage, type Server, type ServerOptions, type ServerResponse } from "node:http";
2
2
  import type { GatewayOptions } from "./contract.ts";
3
- import type { GatewayCredential } from "./sigv4.ts";
4
- export type { DriveSource, DriveWriter, GatewayOptions } from "./contract.ts";
3
+ import { type GatewayCredential } from "./sigv4.ts";
4
+ export type { CopySource, DriveSource, DriveWriter, GatewayOptions, StoreOutcome, WriteMeta, } from "./contract.ts";
5
+ export { failureReasonOf } from "./answer.ts";
5
6
  /** Where the drive is served. Loopback, always — see the note above. */
6
7
  export declare const BIND_ADDRESS = "127.0.0.1";
8
+ /**
9
+ * How a Node server in front of this gateway is made -- `createServer(GATEWAY_SERVER_OPTIONS, …)`.
10
+ *
11
+ * ⛔ NO LIMIT ON THE WHOLE REQUEST. Node's default gives a request five minutes from its first byte
12
+ * to its last, and then cuts it: an upload of a few gigabytes over an ordinary line takes longer
13
+ * than that, and was cut part way every time. What stops a client that holds a connection open
14
+ * for nothing is the limit on headers, kept here as Node's default because setting the other to
15
+ * zero would silently take it to zero too, and the idle limit on a body (`BODY_IDLE_MS`).
16
+ */
17
+ export declare const GATEWAY_SERVER_OPTIONS: ServerOptions;
18
+ /**
19
+ * How long a request body may go without a byte arriving before the connection is closed.
20
+ *
21
+ * ⚠ ONLY WHILE THE BODY IS ARRIVING. Once its last byte is in, what follows -- a file being sealed
22
+ * and sent to the storage network, which can take minutes -- is this side's work, and the
23
+ * connection is not the client's to lose for it. Time the body spends waiting on this side (a
24
+ * disk that is slow to take it) is not counted either.
25
+ */
26
+ export declare const BODY_IDLE_MS = 120000;
7
27
  /** A random pair, made fresh every time the gateway starts and stored nowhere. */
8
28
  export declare function newCredential(): GatewayCredential;
9
29
  /** A plain Node request handler, so this can be mounted in somebody else's server. */
10
30
  export type GatewayHandler = (req: IncomingMessage, res: ServerResponse) => void;
31
+ /**
32
+ * Close the connection when the request's body stops arriving for `idleMs`, until its last byte is in.
33
+ *
34
+ * ⚠ IT WATCHES THE SOCKET'S COUNT OF BYTES, NOT THE BODY'S EVENTS. Listening for the body's data
35
+ * would start it flowing before whoever reads it is ready. While the body waits on this side --
36
+ * as many bytes buffered as the stream holds -- the quiet is this side's, and is not counted.
37
+ */
38
+ export declare function watchBodyIdle(req: IncomingMessage, idleMs?: number): void;
11
39
  /**
12
40
  * The gateway as a handler, which is the form that listens to nothing.
13
41
  *
14
42
  * ⛔ SEPARATE FROM `createGateway` BECAUSE WHO LISTENS IS NOT THIS FILE'S DECISION. The
15
43
  * command-line tool binds loopback and says why at the top of this file; a business mounting
16
44
  * this behind its own TLS has already made that decision, and a library that opened a socket of
17
- * its own would be making it again, differently.
45
+ * its own would be making it again, differently. What it should make that socket with is
46
+ * `GATEWAY_SERVER_OPTIONS` and `checkContinueHandler`.
18
47
  */
19
48
  export declare function gatewayHandler(options: GatewayOptions): GatewayHandler;
49
+ /** A refusal a request earns before its body is read. */
50
+ export interface EarlyRefusal {
51
+ readonly status: number;
52
+ readonly code: string;
53
+ readonly message: string;
54
+ }
55
+ /**
56
+ * What the request's line and headers alone say it will be refused with, or null when nothing
57
+ * known before its body stands in its way: the signature, and whether the pair may touch the bucket.
58
+ *
59
+ * ⛔ ASKED BEFORE `100 Continue`, SO A REFUSED UPLOAD NEVER SENDS ITS BODY. A client that sends
60
+ * `Expect: 100-continue` waits for that line before sending gigabytes; Node sends it by itself
61
+ * unless a server asks first, and then a request whose signature does not hold uploaded its whole
62
+ * body to be refused at the end. A server that handles `Expect` itself calls this first.
63
+ */
64
+ export declare function refusalBeforeBody(req: IncomingMessage, options: Pick<GatewayOptions, "credentials" | "now" | "virtualHostBase">): EarlyRefusal | null;
65
+ /**
66
+ * A listener for Node's `checkContinue` event: `100 Continue` and then `then`, or the refusal the
67
+ * request would have earned, answered at once with `Connection: close` so its body is never read.
68
+ */
69
+ export declare function checkContinueHandler(options: GatewayOptions, then: GatewayHandler): GatewayHandler;
20
70
  export declare function createGateway(options: GatewayOptions): Server;