@needmoretruth/nmts-cli 0.45.0 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (224) hide show
  1. package/AGENTS.md +2 -2
  2. package/CHANGELOG.md +61 -0
  3. package/README.ko.md +6 -3
  4. package/README.md +15 -3
  5. package/dist/api-advice.js +17 -2
  6. package/dist/api.d.ts +22 -0
  7. package/dist/api.js +49 -1
  8. package/dist/arg-options.d.ts +8 -0
  9. package/dist/args.js +7 -1
  10. package/dist/artifact-about.d.ts +1 -1
  11. package/dist/collision.d.ts +20 -3
  12. package/dist/collision.js +21 -3
  13. package/dist/commands/erase.js +1 -0
  14. package/dist/commands/handover.d.ts +13 -0
  15. package/dist/commands/handover.js +328 -0
  16. package/dist/commands/heavy-run.d.ts +59 -0
  17. package/dist/commands/heavy-run.js +247 -0
  18. package/dist/commands/heavy.d.ts +7 -0
  19. package/dist/commands/heavy.js +123 -0
  20. package/dist/commands/ls.d.ts +5 -0
  21. package/dist/commands/ls.js +9 -1
  22. package/dist/commands/public-code.d.ts +6 -0
  23. package/dist/commands/public-code.js +46 -0
  24. package/dist/commands/push-heavy.d.ts +6 -0
  25. package/dist/commands/push-heavy.js +128 -0
  26. package/dist/commands/push-tree.d.ts +24 -0
  27. package/dist/commands/push-tree.js +91 -0
  28. package/dist/commands/push.d.ts +4 -13
  29. package/dist/commands/push.js +7 -77
  30. package/dist/commands/put-heavy.d.ts +9 -0
  31. package/dist/commands/put-heavy.js +120 -0
  32. package/dist/commands/put-payer.d.ts +21 -0
  33. package/dist/commands/put-payer.js +24 -0
  34. package/dist/commands/put.d.ts +2 -2
  35. package/dist/commands/put.js +8 -7
  36. package/dist/commands/receive.js +3 -3
  37. package/dist/commands/s3.js +44 -10
  38. package/dist/crypto-surface.d.ts +8 -0
  39. package/dist/crypto-surface.js +3 -0
  40. package/dist/crypto.d.ts +3 -0
  41. package/dist/crypto.js +3 -0
  42. package/dist/download-part.d.ts +32 -1
  43. package/dist/download-part.js +95 -6
  44. package/dist/download-range.d.ts +19 -0
  45. package/dist/download-range.js +108 -0
  46. package/dist/download-sink.d.ts +15 -0
  47. package/dist/download.d.ts +14 -0
  48. package/dist/download.js +19 -4
  49. package/dist/handover.d.ts +44 -0
  50. package/dist/handover.js +199 -0
  51. package/dist/heavy-api.d.ts +36 -0
  52. package/dist/heavy-api.js +107 -0
  53. package/dist/heavy-copy.d.ts +72 -0
  54. package/dist/heavy-copy.js +108 -0
  55. package/dist/heavy-evm.d.ts +20 -0
  56. package/dist/heavy-evm.js +106 -0
  57. package/dist/heavy-self-pay.d.ts +92 -0
  58. package/dist/heavy-self-pay.js +167 -0
  59. package/dist/heavy-upload.d.ts +87 -0
  60. package/dist/heavy-upload.js +154 -0
  61. package/dist/heavy-wallet-pay.d.ts +39 -0
  62. package/dist/heavy-wallet-pay.js +73 -0
  63. package/dist/help-options.js +4 -2
  64. package/dist/help.js +16 -3
  65. package/dist/list-tier.d.ts +7 -0
  66. package/dist/list-tier.js +47 -0
  67. package/dist/main.js +12 -10
  68. package/dist/manifest-write.d.ts +4 -3
  69. package/dist/platform-sign.d.ts +4 -4
  70. package/dist/platform-sign.js +3 -3
  71. package/dist/portable.d.ts +15 -0
  72. package/dist/portable.js +11 -0
  73. package/dist/product.d.ts +1 -1
  74. package/dist/product.js +1 -1
  75. package/dist/recovery-build.js +16 -0
  76. package/dist/recovery-map-part.d.ts +82 -0
  77. package/dist/recovery-map-part.js +83 -0
  78. package/dist/recovery-map.d.ts +5 -40
  79. package/dist/recovery-map.js +18 -1
  80. package/dist/recovery-source.d.ts +3 -0
  81. package/dist/recovery-source.js +9 -0
  82. package/dist/risk.d.ts +30 -0
  83. package/dist/risk.js +23 -2
  84. package/dist/run-log.d.ts +1 -1
  85. package/dist/run-log.js +7 -1
  86. package/dist/s3/address.d.ts +20 -0
  87. package/dist/s3/address.js +97 -0
  88. package/dist/s3/answer.d.ts +48 -0
  89. package/dist/s3/answer.js +330 -0
  90. package/dist/s3/body-deframe.d.ts +49 -0
  91. package/dist/s3/body-deframe.js +264 -0
  92. package/dist/s3/body-measure.d.ts +13 -0
  93. package/dist/s3/body-measure.js +48 -0
  94. package/dist/s3/body-plan.d.ts +31 -0
  95. package/dist/s3/body-plan.js +159 -0
  96. package/dist/s3/body.d.ts +46 -0
  97. package/dist/s3/body.js +117 -0
  98. package/dist/s3/call.d.ts +36 -0
  99. package/dist/s3/call.js +42 -0
  100. package/dist/s3/checksum.d.ts +26 -0
  101. package/dist/s3/checksum.js +176 -0
  102. package/dist/s3/content-type.d.ts +3 -0
  103. package/dist/s3/content-type.js +49 -0
  104. package/dist/s3/contract.d.ts +91 -14
  105. package/dist/s3/drive-conditions.d.ts +47 -0
  106. package/dist/s3/drive-conditions.js +134 -0
  107. package/dist/s3/drive-key.d.ts +11 -0
  108. package/dist/s3/drive-key.js +58 -0
  109. package/dist/s3/drive-limits.d.ts +33 -0
  110. package/dist/s3/drive-limits.js +53 -0
  111. package/dist/s3/drive-lock.d.ts +11 -0
  112. package/dist/s3/drive-lock.js +47 -0
  113. package/dist/s3/drive-trashed-name.d.ts +13 -0
  114. package/dist/s3/drive-trashed-name.js +59 -0
  115. package/dist/s3/drive-write.d.ts +38 -0
  116. package/dist/s3/drive-write.js +258 -0
  117. package/dist/s3/drive.d.ts +59 -25
  118. package/dist/s3/drive.js +46 -77
  119. package/dist/s3/listing.d.ts +27 -1
  120. package/dist/s3/listing.js +62 -20
  121. package/dist/s3/long-answer.d.ts +12 -0
  122. package/dist/s3/long-answer.js +104 -0
  123. package/dist/s3/multipart-assemble.d.ts +17 -0
  124. package/dist/s3/multipart-assemble.js +68 -0
  125. package/dist/s3/multipart-sweep.d.ts +15 -0
  126. package/dist/s3/multipart-sweep.js +87 -0
  127. package/dist/s3/multipart-view.d.ts +45 -0
  128. package/dist/s3/multipart-view.js +232 -0
  129. package/dist/s3/multipart.d.ts +26 -19
  130. package/dist/s3/multipart.js +193 -78
  131. package/dist/s3/object-read.d.ts +17 -0
  132. package/dist/s3/object-read.js +127 -0
  133. package/dist/s3/object-write.d.ts +35 -0
  134. package/dist/s3/object-write.js +198 -0
  135. package/dist/s3/range.d.ts +14 -0
  136. package/dist/s3/range.js +80 -0
  137. package/dist/s3/response-sink.d.ts +12 -2
  138. package/dist/s3/response-sink.js +71 -7
  139. package/dist/s3/routes.d.ts +0 -1
  140. package/dist/s3/routes.js +242 -217
  141. package/dist/s3/same-file.d.ts +4 -1
  142. package/dist/s3/same-file.js +12 -3
  143. package/dist/s3/server.d.ts +54 -4
  144. package/dist/s3/server.js +174 -14
  145. package/dist/s3/sigv4-canonical.d.ts +91 -0
  146. package/dist/s3/sigv4-canonical.js +148 -0
  147. package/dist/s3/sigv4-presigned.d.ts +13 -0
  148. package/dist/s3/sigv4-presigned.js +82 -0
  149. package/dist/s3/sigv4.d.ts +26 -27
  150. package/dist/s3/sigv4.js +137 -102
  151. package/dist/s3/spool.d.ts +37 -0
  152. package/dist/s3/spool.js +104 -0
  153. package/dist/s3/staging.d.ts +90 -7
  154. package/dist/s3/staging.js +97 -66
  155. package/dist/s3/xml-multipart.d.ts +38 -0
  156. package/dist/s3/xml-multipart.js +47 -0
  157. package/dist/s3/xml-read.d.ts +28 -0
  158. package/dist/s3/xml-read.js +235 -0
  159. package/dist/s3/xml.d.ts +45 -2
  160. package/dist/s3/xml.js +72 -13
  161. package/dist/s3-gateway.d.ts +11 -5
  162. package/dist/s3-gateway.js +5 -2
  163. package/dist/seal.d.ts +1 -1
  164. package/dist/share.d.ts +5 -0
  165. package/dist/share.js +1 -1
  166. package/dist/shared/lib/api/types-heavy.d.ts +167 -0
  167. package/dist/shared/lib/api/types-heavy.js +60 -0
  168. package/dist/shared/lib/drive/rebuild-verify.js +1 -0
  169. package/dist/shared/lib/filecoin/providers.d.ts +25 -0
  170. package/dist/shared/lib/filecoin/providers.js +58 -0
  171. package/dist/shared/lib/heavy/download.d.ts +48 -0
  172. package/dist/shared/lib/heavy/download.js +116 -0
  173. package/dist/shared/lib/heavy/order-plan.d.ts +77 -0
  174. package/dist/shared/lib/heavy/order-plan.js +83 -0
  175. package/dist/shared/lib/heavy/order-runner.d.ts +9 -0
  176. package/dist/shared/lib/heavy/order-runner.js +300 -0
  177. package/dist/shared/lib/heavy/order-types.d.ts +90 -0
  178. package/dist/shared/lib/heavy/order-types.js +6 -0
  179. package/dist/shared/lib/heavy/order-wire.d.ts +55 -0
  180. package/dist/shared/lib/heavy/order-wire.js +113 -0
  181. package/dist/shared/lib/heavy/piece-cid.d.ts +24 -0
  182. package/dist/shared/lib/heavy/piece-cid.js +55 -0
  183. package/dist/shared/lib/heavy/sp-upload.d.ts +37 -0
  184. package/dist/shared/lib/heavy/sp-upload.js +112 -0
  185. package/dist/shared/lib/heavy/synapse-piece.d.ts +1 -0
  186. package/dist/shared/lib/heavy/synapse-piece.js +8 -0
  187. package/dist/shared/lib/share/handover-format.d.ts +129 -0
  188. package/dist/shared/lib/share/handover-format.js +323 -0
  189. package/dist/shared/lib/share/shared-file-info.js +1 -0
  190. package/dist/shared/lib/storage-network.d.ts +4 -4
  191. package/dist/shared/lib/storage-network.js +7 -7
  192. package/dist/shared/lib/storage-tier.d.ts +28 -0
  193. package/dist/shared/lib/storage-tier.js +63 -0
  194. package/dist/shared/lib/wallet/send-rules.js +1 -0
  195. package/dist/upload-file.d.ts +8 -0
  196. package/dist/upload-file.js +57 -25
  197. package/dist/upload-price-node.d.ts +3 -0
  198. package/dist/upload-price-node.js +3 -6
  199. package/dist/upload-price.d.ts +10 -0
  200. package/dist/upload-price.js +13 -1
  201. package/dist/upload-run.d.ts +80 -0
  202. package/dist/upload-run.js +173 -0
  203. package/dist/upload-steps.js +15 -4
  204. package/dist/upload-store.d.ts +15 -6
  205. package/dist/upload-store.js +6 -0
  206. package/dist/upload-wallet-put.d.ts +9 -4
  207. package/dist/upload-wallet-put.js +16 -6
  208. package/dist/upload-wallet.js +4 -0
  209. package/dist/upload-wire.d.ts +25 -0
  210. package/dist/upload-wire.js +20 -1
  211. package/dist/upload.js +28 -13
  212. package/dist/wallet-sign.js +2 -2
  213. package/docs/commands/handover.md +38 -0
  214. package/docs/commands/heavy.md +35 -0
  215. package/docs/commands/public-code.md +7 -0
  216. package/docs/commands/push.md +4 -1
  217. package/docs/commands/put.md +15 -1
  218. package/docs/commands/share.md +3 -1
  219. package/package.json +5 -2
  220. package/server.json +2 -2
  221. package/vendor/nmts-crypto/nmts_crypto_wasm.d.ts +17 -1
  222. package/vendor/nmts-crypto/nmts_crypto_wasm.js +28 -0
  223. package/vendor/nmts-crypto/nmts_crypto_wasm_bg.wasm +0 -0
  224. package/vendor/nmts-crypto/nmts_crypto_wasm_bg.wasm.d.ts +2 -1
@@ -0,0 +1,97 @@
1
+ // Which bucket and which key a request names, and whether it names something this gateway does.
2
+ //
3
+ // ⛔ A SUB-RESOURCE IS NEVER AN OBJECT. `?acl`, `?tagging`, `?policy` and the rest ask about a
4
+ // bucket or a key rather than for its bytes. Falling through to the object branch answered
5
+ // `GET ?acl` with the file, stored the XML of `PUT ?tagging` as the file, and trashed the file
6
+ // on `DELETE ?tagging` — each a 200 for something that did not happen, or something that should
7
+ // not have. Every name below is classified first, and one this gateway does not do is 501.
8
+ //
9
+ // ⚠ THE PRESIGNED `X-Amz-*` PARAMETERS AND THE SDK'S `x-id` ARE NOT SUB-RESOURCES and are not
10
+ // listed; the signature has already consumed them by the time anything here looks.
11
+ import { S3Refusal } from "./answer.js";
12
+ /**
13
+ * Every query parameter S3 treats as naming a sub-resource.
14
+ *
15
+ * ⚠ `uploads`, `uploadId`, `delete`, `location` and `versioning` are answered; `versionId` is
16
+ * listed so that a request for one version is refused rather than answered with the only one.
17
+ */
18
+ export const SUB_RESOURCES = [
19
+ "accelerate",
20
+ "acl",
21
+ "analytics",
22
+ "attributes",
23
+ "cors",
24
+ "delete",
25
+ "encryption",
26
+ "intelligent-tiering",
27
+ "inventory",
28
+ "legal-hold",
29
+ "lifecycle",
30
+ "location",
31
+ "logging",
32
+ "metrics",
33
+ "notification",
34
+ "object-lock",
35
+ "ownershipControls",
36
+ "policy",
37
+ "policyStatus",
38
+ "publicAccessBlock",
39
+ "replication",
40
+ "requestPayment",
41
+ "restore",
42
+ "retention",
43
+ "select",
44
+ "tagging",
45
+ "torrent",
46
+ "uploads",
47
+ "versioning",
48
+ "versionId",
49
+ "versions",
50
+ "website",
51
+ ];
52
+ /** The sub-resource this query names, or null when it names none. */
53
+ export function subResourceOf(query) {
54
+ for (const name of query.keys()) {
55
+ if (SUB_RESOURCES.includes(name))
56
+ return name;
57
+ }
58
+ return null;
59
+ }
60
+ function decoded(part) {
61
+ try {
62
+ return decodeURIComponent(part);
63
+ }
64
+ catch {
65
+ throw new S3Refusal(400, "InvalidURI", "The request path is not valid percent-encoding.");
66
+ }
67
+ }
68
+ /** `Host` without its port, lower-cased. An IPv6 literal keeps its brackets. */
69
+ function hostOnly(host) {
70
+ const lower = host.trim().toLowerCase();
71
+ if (lower.startsWith("[")) {
72
+ const close = lower.indexOf("]");
73
+ return close < 0 ? lower : lower.slice(0, close + 1);
74
+ }
75
+ const colon = lower.lastIndexOf(":");
76
+ return colon >= 0 && /^\d*$/.test(lower.slice(colon + 1)) ? lower.slice(0, colon) : lower;
77
+ }
78
+ /**
79
+ * `/drive/photos/a.jpg` → bucket `drive`, key `photos/a.jpg`; or, virtual-hosted, `Host:
80
+ * drive.s3.example.com` and `/photos/a.jpg` → the same two.
81
+ */
82
+ export function addressOf(pathname, host, virtualHostBase) {
83
+ if (virtualHostBase !== undefined && host !== undefined) {
84
+ const base = hostOnly(virtualHostBase).replace(/^\.+/, "");
85
+ const named = hostOnly(host);
86
+ if (base !== "" && named.endsWith(`.${base}`)) {
87
+ const bucket = named.slice(0, named.length - base.length - 1);
88
+ if (bucket !== "")
89
+ return { bucket, key: decoded(pathname.replace(/^\//, "")) };
90
+ }
91
+ }
92
+ const trimmed = pathname.replace(/^\//, "");
93
+ const at = trimmed.indexOf("/");
94
+ if (at < 0)
95
+ return { bucket: decoded(trimmed), key: "" };
96
+ return { bucket: decoded(trimmed.slice(0, at)), key: decoded(trimmed.slice(at + 1)) };
97
+ }
@@ -0,0 +1,48 @@
1
+ import type { ServerResponse } from "node:http";
2
+ /** A refusal this gateway decided on, carrying the S3 status and code it is answered with. */
3
+ export declare class S3Refusal extends Error {
4
+ readonly status: number;
5
+ readonly code: string;
6
+ constructor(status: number, code: string, message: string);
7
+ }
8
+ /** One failure, as the error document and headers an S3 client reads. */
9
+ export interface S3Answer {
10
+ readonly status: number;
11
+ readonly code: string;
12
+ readonly message: string;
13
+ /** Seconds a client should wait before sending it again, when anything said. */
14
+ readonly retryAfter: number | null;
15
+ /**
16
+ * What the client was not told: the failure's own code or name and its own words, for whoever
17
+ * runs the gateway. Null when `message` already says everything there is.
18
+ */
19
+ readonly reason: string | null;
20
+ }
21
+ /**
22
+ * How long a client is asked to wait after the storage network did not take the bytes, when nothing
23
+ * named a wait. The storage is paid for and the bytes are kept, so the retry costs only the push.
24
+ */
25
+ export declare const PUSH_RETRY_AFTER_SECONDS = 5;
26
+ /** What an S3 client should be told about a thrown value. */
27
+ export declare function answerFor(error: unknown): S3Answer;
28
+ /**
29
+ * Why this response failed, for whoever runs the gateway: undefined when it did not, or when its
30
+ * client was told everything there was.
31
+ *
32
+ * ⛔ NEVER A KEY. The request's path, and each of its segments, is taken out of the reason, since a
33
+ * failure's words may quote the file it was about and the log never names a file.
34
+ */
35
+ export declare function failureReasonOf(res: ServerResponse): string | undefined;
36
+ /** Keep why this response failed, when its client was told less than that. */
37
+ export declare function noteFailure(res: ServerResponse, answer: S3Answer, resource: string): void;
38
+ /** Answer with an XML body, or with its headers alone for a HEAD. */
39
+ export declare function sendXml(res: ServerResponse, status: number, body: string, extra?: Record<string, string>): void;
40
+ /** Answer one refusal as the error document S3 sends. */
41
+ export declare function refuse(res: ServerResponse, status: number, code: string, message: string, resource: string, extra?: Record<string, string>): void;
42
+ /**
43
+ * Answer whatever was thrown, if the response can still carry an answer.
44
+ *
45
+ * ⛔ A RESPONSE THAT HAS BEGUN IS DESTROYED, NOT ENDED. Its status and length went out already; a
46
+ * clean end after a short body is what every client files away as a whole file.
47
+ */
48
+ export declare function failWith(res: ServerResponse, error: unknown, resource: string): void;
@@ -0,0 +1,330 @@
1
+ // How a failure reads to an S3 client: one status and one code, chosen for what the client does next.
2
+ //
3
+ // ⛔ THE CODE IS AN INSTRUCTION, NOT A LABEL. S3 clients branch on it: `SlowDown` and a 503 mean
4
+ // "wait and send it again", `AccessDenied` means "stop, this pair cannot", `InternalError` means
5
+ // "something broke". Answering 500 for "the account is out of credits" had a sync tool retry an
6
+ // upload that could never succeed until somebody paid, and answering it for "the storage network
7
+ // did not answer" told the same tool to give up on a request a minute's wait would have carried.
8
+ //
9
+ // ⚠ EVERY FIELD IS READ AS UNKNOWN. What reaches this file was thrown by the command-line tool, by
10
+ // the SDK, by Node or by a business's own resolver; none of them promised a shape, so `code`,
11
+ // `status` and `retryAfter` are each looked up and type-checked rather than assumed.
12
+ import { BodyRefusal } from "./body.js";
13
+ import { isKeyConflict } from "./same-file.js";
14
+ import { errorXml } from "./xml.js";
15
+ /** A refusal this gateway decided on, carrying the S3 status and code it is answered with. */
16
+ export class S3Refusal extends Error {
17
+ status;
18
+ code;
19
+ constructor(status, code, message) {
20
+ super(message);
21
+ this.name = "S3Refusal";
22
+ this.status = status;
23
+ this.code = code;
24
+ }
25
+ }
26
+ /**
27
+ * What each kind of failure is answered with: the status, the code and one fixed sentence.
28
+ *
29
+ * ⛔ THE SENTENCE IS THIS GATEWAY'S, NOT THE FAILURE'S. What was thrown is written for whoever runs
30
+ * NMTS on the machine: a local path with a process id in it, a database's own error, the next
31
+ * command for a person to type. Through a business's gateway the client is somebody else
32
+ * entirely, and those words are about the business, not about the request. They go to the
33
+ * gateway's log instead (`failureReasonOf`).
34
+ */
35
+ const KINDS = {
36
+ /** The account cannot pay for this: no retry will change that until somebody acts. */
37
+ account: {
38
+ status: 403,
39
+ code: "AccountProblem",
40
+ message: "The account this bucket belongs to cannot pay for this: it is short of credits or over a " +
41
+ "spending limit. Sending it again will not help until that changes.",
42
+ },
43
+ /** Whoever the account is reached through may not do this, now or with this credential. */
44
+ denied: {
45
+ status: 403,
46
+ code: "AccessDenied",
47
+ message: "The account this bucket belongs to does not allow this request. Sending it again will not " +
48
+ "help until that changes.",
49
+ },
50
+ /** Not now, but later: the request itself was fine. */
51
+ later: {
52
+ status: 503,
53
+ code: "SlowDown",
54
+ message: "NMTS or the storage network could not take this request just now. Send it again after a short wait.",
55
+ },
56
+ /**
57
+ * The upload or the account moved on while this ran; a new request starts from where it is now.
58
+ *
59
+ * ⚠ `OperationAborted` BECAUSE A 409 IS NOT RETRIED BLINDLY. The AWS SDKs and botocore retry by
60
+ * themselves on 500, 502, 503 and 504 and on lists of throttling and transient codes; 409 is not
61
+ * among those statuses and `OperationAborted` is on none of those lists, so the application
62
+ * hears it once. Its meaning in S3 -- a conflicting operation on this resource, to be tried
63
+ * again -- is what these refusals are: the same request sent again is a new upload from the start.
64
+ */
65
+ conflict: {
66
+ status: 409,
67
+ code: "OperationAborted",
68
+ message: "Something else changed this upload or this account while the request ran. Send it again as a new request.",
69
+ },
70
+ /** Refused as it was sent: the same request again gets the same answer. */
71
+ refused: {
72
+ status: 400,
73
+ code: "InvalidRequest",
74
+ message: "NMTS refused this request as it was sent. Sending it again unchanged will not help.",
75
+ },
76
+ notDone: { status: 501, code: "NotImplemented", message: "NMTS does not do this yet." },
77
+ /** S3's own words for its own 500. */
78
+ internal: { status: 500, code: "InternalError", message: "We encountered an internal error. Please try again." },
79
+ };
80
+ /**
81
+ * NMTS's refusals and what each is answered as: by its code first, then by its status.
82
+ *
83
+ * ⛔ ONE TABLE. A code is listed where it says more than its status does -- `CREDITS_SHORT` is a 409
84
+ * on the wire and an account that cannot pay here -- or where it may arrive without a status, as
85
+ * `WALLET_SHORT` does. Every other refusal is placed by its status alone, which is how a code
86
+ * NMTS adds tomorrow still lands somewhere a client acts on sensibly. Rows are read in order.
87
+ */
88
+ const TABLE = [
89
+ {
90
+ kind: "account",
91
+ codes: ["CREDITS_SHORT", "CREDIT_FILE_CAP", "CREDIT_DAILY_CAP", "WALLET_SHORT", "DEPOSIT_FEE_INSUFFICIENT"],
92
+ status: (s) => s === 402,
93
+ },
94
+ {
95
+ kind: "denied",
96
+ codes: [
97
+ "DELEGATION_INVALID",
98
+ "DELEGATION_EXPIRED",
99
+ "DELEGATION_SCOPE",
100
+ "NOT_A_MEMBER",
101
+ "API_KEY_REVOKED",
102
+ "API_KEY_EXPIRED",
103
+ "API_KEY_SCOPE",
104
+ "TERMS_ACCEPTANCE_REQUIRED",
105
+ "ACCOUNT_BANNED",
106
+ ],
107
+ status: (s) => s === 401 || s === 403,
108
+ },
109
+ { kind: "later", codes: ["RATE_LIMITED", "CHAIN_SPEND_CAP", "CHAIN_UNCERTAIN"], status: (s) => s === 429 },
110
+ { kind: "conflict", codes: ["SPONSORED_IDEM_MISMATCH", "SPONSORED_STATE"], status: (s) => s === 409 },
111
+ { kind: "notDone", codes: ["NOT_IMPLEMENTED"], status: (s) => s === 501 },
112
+ { kind: "later", codes: [], status: (s) => s >= 500 },
113
+ { kind: "refused", codes: [], status: (s) => s >= 400 && s < 500 },
114
+ ];
115
+ /**
116
+ * How long a client is asked to wait after the storage network did not take the bytes, when nothing
117
+ * named a wait. The storage is paid for and the bytes are kept, so the retry costs only the push.
118
+ */
119
+ export const PUSH_RETRY_AFTER_SECONDS = 5;
120
+ /** Node's names for a connection that was never made or did not last. */
121
+ const UNREACHABLE_CODES = new Set([
122
+ "ECONNRESET",
123
+ "ECONNREFUSED",
124
+ "ECONNABORTED",
125
+ "EAI_AGAIN",
126
+ "ENOTFOUND",
127
+ "ETIMEDOUT",
128
+ "EPIPE",
129
+ "EHOSTUNREACH",
130
+ "ENETUNREACH",
131
+ "UND_ERR_SOCKET",
132
+ "UND_ERR_CONNECT_TIMEOUT",
133
+ "UND_ERR_HEADERS_TIMEOUT",
134
+ "UND_ERR_BODY_TIMEOUT",
135
+ ]);
136
+ /**
137
+ * The sentences this package throws when NMTS or the storage network did not answer.
138
+ *
139
+ * ⚠ ANCHORED TO THOSE SENTENCES. A looser pattern — the word "network" anywhere — also matches a
140
+ * refusal such as "a file on a network this build cannot read", and answering that with
141
+ * `SlowDown` has a client retry forever something that will never work.
142
+ */
143
+ const UNREACHABLE_WORDS = /^Could not reach |^fetch failed$|did not answer within \d+ ?ms|could not be read from the .+ storage network/;
144
+ function field(error, name) {
145
+ if (typeof error !== "object" || error === null || !(name in error))
146
+ return undefined;
147
+ return Reflect.get(error, name);
148
+ }
149
+ function stringField(error, name) {
150
+ const value = field(error, name);
151
+ return typeof value === "string" ? value : null;
152
+ }
153
+ function numberField(error, name) {
154
+ const value = field(error, name);
155
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
156
+ }
157
+ /** True when a failure is a connection to NMTS or the storage network that did not happen. */
158
+ function unreachable(error, depth = 0) {
159
+ if (depth > 4 || typeof error !== "object" || error === null)
160
+ return false;
161
+ const code = stringField(error, "code");
162
+ if (code !== null && UNREACHABLE_CODES.has(code))
163
+ return true;
164
+ if (error instanceof Error && UNREACHABLE_WORDS.test(error.message))
165
+ return true;
166
+ return unreachable(field(error, "cause"), depth + 1);
167
+ }
168
+ /** The step of an upload a failure names: "uploading" is the push of paid-for bytes to the relay. */
169
+ function pushFailed(error) {
170
+ return stringField(error, "phase") === "uploading";
171
+ }
172
+ /**
173
+ * Which kind a failure is, when it is anything other than an accident.
174
+ *
175
+ * ⚠ A PUSH THE STORAGE NETWORK DID NOT TAKE IS READ BY ITS PHASE, NOT ITS WORDS. Its sentence starts
176
+ * with what was being done, which is why no pattern over sentences caught it.
177
+ * ⚠ EXIT CODES 2 AND 4 ARE THIS PACKAGE REFUSING ITS INPUT -- a name the drive cannot hold, an empty
178
+ * file -- so what was refused is the client's request, not something that broke.
179
+ */
180
+ function kindOf(error) {
181
+ const code = stringField(error, "code");
182
+ if (code !== null) {
183
+ const row = TABLE.find((r) => r.codes.includes(code));
184
+ if (row !== undefined)
185
+ return row.kind;
186
+ }
187
+ const status = numberField(error, "status");
188
+ if (status !== null) {
189
+ const row = TABLE.find((r) => r.status(status));
190
+ if (row !== undefined)
191
+ return row.kind;
192
+ }
193
+ if (pushFailed(error) || unreachable(error))
194
+ return "later";
195
+ const exit = numberField(error, "exitCode");
196
+ if (exit === 2 || exit === 4)
197
+ return "refused";
198
+ return null;
199
+ }
200
+ /** Long enough for any sentence this package throws; a log line is no place for a stack. */
201
+ const MAX_REASON = 400;
202
+ /** The failure's own code or name and its own words, as one line for whoever runs the gateway. */
203
+ function reasonOf(error) {
204
+ const label = stringField(error, "code") ?? (error instanceof Error ? error.name : typeof error);
205
+ const words = error instanceof Error ? error.message : String(error);
206
+ return `${label}: ${words}`.replace(/\s+/g, " ").slice(0, MAX_REASON);
207
+ }
208
+ /** What an S3 client should be told about a thrown value. */
209
+ export function answerFor(error) {
210
+ const message = error instanceof Error ? error.message : String(error);
211
+ // The refusals this gateway phrased itself: their words were written for the client.
212
+ if (error instanceof S3Refusal || error instanceof BodyRefusal) {
213
+ return { status: error.status, code: error.code, message, retryAfter: null, reason: null };
214
+ }
215
+ // ⛔ A KEY THAT HOLDS A DIFFERENT FILE IS 409, NOT 500 — the request was well formed and the
216
+ // drive declined it. Told 500 a sync tool retries the upload forever; told 409 it records a
217
+ // conflict and moves on. ⚠ The code stays `InvalidRequest`: the S3 codes that come with a 409
218
+ // and are not about buckets (`OperationAborted`, `ConditionalRequestConflict`) both mean "try
219
+ // again", which is the one thing that will never help here.
220
+ if (isKeyConflict(error))
221
+ return { status: 409, code: "InvalidRequest", message, retryAfter: null, reason: null };
222
+ const name = kindOf(error) ?? "internal";
223
+ const kind = KINDS[name];
224
+ let retryAfter = null;
225
+ if (name === "later") {
226
+ const wait = numberField(error, "retryAfter");
227
+ if (wait !== null)
228
+ retryAfter = Math.max(0, Math.ceil(wait));
229
+ else if (pushFailed(error))
230
+ retryAfter = PUSH_RETRY_AFTER_SECONDS;
231
+ }
232
+ return { status: kind.status, code: kind.code, message: kind.message, retryAfter, reason: reasonOf(error) };
233
+ }
234
+ /**
235
+ * Why each failed response failed, in more words than its client was given.
236
+ *
237
+ * ⛔ HELD BESIDE THE RESPONSE, NOT PASSED BACK UP. The code that answers a failure is deep inside an
238
+ * operation and knows nothing of the log; whoever holds the log reads this when the response
239
+ * closes. A weak map, so a response nobody asks about takes its reason with it.
240
+ */
241
+ const REASONS = new WeakMap();
242
+ /**
243
+ * Why this response failed, for whoever runs the gateway: undefined when it did not, or when its
244
+ * client was told everything there was.
245
+ *
246
+ * ⛔ NEVER A KEY. The request's path, and each of its segments, is taken out of the reason, since a
247
+ * failure's words may quote the file it was about and the log never names a file.
248
+ */
249
+ export function failureReasonOf(res) {
250
+ return REASONS.get(res);
251
+ }
252
+ function escapeRegExp(text) {
253
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
254
+ }
255
+ /**
256
+ * `text` with the request's path replaced wherever it stands as a word: every tail of it (the key
257
+ * without its bucket, the name without its folders) and every segment on its own.
258
+ */
259
+ function withoutPath(text, resource) {
260
+ let decoded = resource;
261
+ try {
262
+ decoded = decodeURIComponent(resource);
263
+ }
264
+ catch {
265
+ // A path with a broken escape is taken out as it arrived.
266
+ }
267
+ const names = new Set();
268
+ for (const path of [resource, decoded]) {
269
+ const segments = path.split("/");
270
+ segments.forEach((segment, at) => {
271
+ names.add(segment);
272
+ names.add(segments.slice(at).join("/"));
273
+ });
274
+ }
275
+ let out = text;
276
+ for (const name of [...names].filter((n) => n.length > 0).sort((a, b) => b.length - a.length)) {
277
+ out = out.replace(new RegExp(`(?<![\\p{L}\\p{N}])${escapeRegExp(name)}(?![\\p{L}\\p{N}])`, "gu"), "…");
278
+ }
279
+ return out;
280
+ }
281
+ /** Keep why this response failed, when its client was told less than that. */
282
+ export function noteFailure(res, answer, resource) {
283
+ if (answer.reason !== null)
284
+ REASONS.set(res, withoutPath(answer.reason, resource));
285
+ }
286
+ /**
287
+ * Whether the request is still sending a body that nothing has read.
288
+ *
289
+ * ⛔ SUCH A REQUEST IS ANSWERED WITH `Connection: close`. Kept open, the connection would have to
290
+ * take in every byte of a body that was already refused -- gigabytes of an upload whose
291
+ * signature did not hold -- before it could carry the next request; closed, the reading stops
292
+ * with the answer. A client that sent `Expect: 100-continue` and is refused never sends it at all.
293
+ */
294
+ function bodyStillComing(res) {
295
+ const req = res.req;
296
+ if (req === undefined || req.complete)
297
+ return false;
298
+ const length = req.headers["content-length"];
299
+ return req.headers["transfer-encoding"] !== undefined || (length !== undefined && length !== "0");
300
+ }
301
+ /** Answer with an XML body, or with its headers alone for a HEAD. */
302
+ export function sendXml(res, status, body, extra = {}) {
303
+ res.writeHead(status, {
304
+ ...extra,
305
+ ...(bodyStillComing(res) ? { connection: "close" } : {}),
306
+ "content-type": "application/xml",
307
+ "content-length": String(Buffer.byteLength(body)),
308
+ });
309
+ res.end(body);
310
+ }
311
+ /** Answer one refusal as the error document S3 sends. */
312
+ export function refuse(res, status, code, message, resource, extra = {}) {
313
+ sendXml(res, status, errorXml(code, message, resource), extra);
314
+ }
315
+ /**
316
+ * Answer whatever was thrown, if the response can still carry an answer.
317
+ *
318
+ * ⛔ A RESPONSE THAT HAS BEGUN IS DESTROYED, NOT ENDED. Its status and length went out already; a
319
+ * clean end after a short body is what every client files away as a whole file.
320
+ */
321
+ export function failWith(res, error, resource) {
322
+ const answer = answerFor(error);
323
+ noteFailure(res, answer, resource);
324
+ if (res.headersSent) {
325
+ if (!res.writableEnded)
326
+ res.destroy();
327
+ return;
328
+ }
329
+ refuse(res, answer.status, answer.code, answer.message, resource, answer.retryAfter === null ? {} : { "retry-after": String(answer.retryAfter) });
330
+ }
@@ -0,0 +1,49 @@
1
+ import { BodyRefusal, type Plan } from "./body-plan.ts";
2
+ import { type ChecksumAlgorithm } from "./checksum.ts";
3
+ /**
4
+ * Takes `aws-chunked` framing off a body, checking each chunk signature and the trailer on the way.
5
+ *
6
+ * The format, per chunk: `<size in hex>[;chunk-signature=<64 hex>]\r\n<size bytes>\r\n`. A chunk of
7
+ * size 0 ends the data; after it comes `\r\n` (chunk-signed), or trailer lines `name:value\r\n` --
8
+ * followed, when chunk-signed, by `x-amz-trailer-signature:<64 hex>\r\n` -- and a last `\r\n`.
9
+ *
10
+ * ⚠ LENIENT IN EXACTLY ONE PLACE: the body may end without the final empty line once the last
11
+ * chunk and every promised trailer are in. The AWS SDK for JavaScript sends `0\r\n` and nothing
12
+ * more when it has no checksum to add; the bytes and their checks are complete by then, and a
13
+ * refusal would be over a line that carries nothing.
14
+ */
15
+ export declare class Deframer {
16
+ private state;
17
+ private line;
18
+ private lineBytes;
19
+ private trailerBytes;
20
+ private remaining;
21
+ private crlf;
22
+ private decoded;
23
+ private chunkHash;
24
+ private chunkSignature;
25
+ private previous;
26
+ private trailerSignature;
27
+ private readonly trailerPairs;
28
+ readonly trailerValues: Map<ChecksumAlgorithm, Buffer<ArrayBufferLike>>;
29
+ private readonly plan;
30
+ private readonly signed;
31
+ private readonly emit;
32
+ constructor(plan: Plan, emit: (bytes: Buffer) => void);
33
+ feed(chunk: Buffer): BodyRefusal | null;
34
+ /** The body has ended: was it whole? */
35
+ finish(): BodyRefusal | null;
36
+ private takeLine;
37
+ private onChunkHeader;
38
+ private hmac;
39
+ /** One link of the chain: this chunk's signature over its bytes and the signature before it. */
40
+ private checkChunk;
41
+ private onTrailerLine;
42
+ /**
43
+ * Every promised trailer is in; for a chunk-signed body, the trailer signature holds.
44
+ *
45
+ * The string it signs is `AWS4-HMAC-SHA256-TRAILER`, the timestamp, the scope, the last chunk's
46
+ * signature, and the SHA-256 of the trailer headers as `name:value\n`, sorted by name.
47
+ */
48
+ private closeTrailer;
49
+ }