@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,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
+ }
@@ -0,0 +1,264 @@
1
+ // The `aws-chunked` framing taken off a body, with each chunk signature and the trailer checked on
2
+ // the way. One of the parts of `body.ts`; only it imports this.
3
+ import { createHash, createHmac, timingSafeEqual } from "node:crypto";
4
+ import { BodyRefusal, incomplete, invalid } from "./body-plan.js";
5
+ import { algorithmOfHeader, checksumHeaderName, parseChecksumValue } from "./checksum.js";
6
+ const EMPTY_SHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
7
+ /** A chunk header or trailer line longer than this is not one a client wrote. */
8
+ const MAX_LINE_BYTES = 4096;
9
+ /** Nor is a trailer section longer than this: S3's trailers are a checksum and a signature. */
10
+ const MAX_TRAILER_BYTES = 16 * 1024;
11
+ function sameHex(a, b) {
12
+ const left = Buffer.from(a, "utf8");
13
+ const right = Buffer.from(b, "utf8");
14
+ return left.length === right.length && timingSafeEqual(left, right);
15
+ }
16
+ /**
17
+ * Takes `aws-chunked` framing off a body, checking each chunk signature and the trailer on the way.
18
+ *
19
+ * The format, per chunk: `<size in hex>[;chunk-signature=<64 hex>]\r\n<size bytes>\r\n`. A chunk of
20
+ * size 0 ends the data; after it comes `\r\n` (chunk-signed), or trailer lines `name:value\r\n` --
21
+ * followed, when chunk-signed, by `x-amz-trailer-signature:<64 hex>\r\n` -- and a last `\r\n`.
22
+ *
23
+ * ⚠ LENIENT IN EXACTLY ONE PLACE: the body may end without the final empty line once the last
24
+ * chunk and every promised trailer are in. The AWS SDK for JavaScript sends `0\r\n` and nothing
25
+ * more when it has no checksum to add; the bytes and their checks are complete by then, and a
26
+ * refusal would be over a line that carries nothing.
27
+ */
28
+ export class Deframer {
29
+ state = "size";
30
+ line = [];
31
+ lineBytes = 0;
32
+ trailerBytes = 0;
33
+ remaining = 0;
34
+ crlf = 0;
35
+ decoded = 0;
36
+ chunkHash = null;
37
+ chunkSignature = "";
38
+ previous;
39
+ trailerSignature = null;
40
+ trailerPairs = [];
41
+ trailerValues = new Map();
42
+ plan;
43
+ signed;
44
+ emit;
45
+ constructor(plan, emit) {
46
+ this.plan = plan;
47
+ this.signed = plan.framing === "signed" || plan.framing === "signed-trailer";
48
+ this.emit = emit;
49
+ this.previous = plan.signing.seedSignature;
50
+ }
51
+ feed(chunk) {
52
+ let at = 0;
53
+ while (at < chunk.length) {
54
+ switch (this.state) {
55
+ case "size":
56
+ case "trailer": {
57
+ const newline = chunk.indexOf(0x0a, at);
58
+ const end = newline < 0 ? chunk.length : newline;
59
+ if (this.state === "trailer") {
60
+ this.trailerBytes += end - at + (newline < 0 ? 0 : 1);
61
+ if (this.trailerBytes > MAX_TRAILER_BYTES)
62
+ return invalid("the trailer is longer than any client writes");
63
+ }
64
+ this.lineBytes += end - at;
65
+ if (this.lineBytes > MAX_LINE_BYTES)
66
+ return invalid("a chunk header or trailer line is longer than any client writes");
67
+ if (end > at)
68
+ this.line.push(chunk.subarray(at, end));
69
+ if (newline < 0)
70
+ return null;
71
+ at = newline + 1;
72
+ const text = this.takeLine();
73
+ const refused = this.state === "size"
74
+ ? this.onChunkHeader(text)
75
+ : this.onTrailerLine(text.endsWith("\r") ? text.slice(0, -1) : text);
76
+ if (refused !== null)
77
+ return refused;
78
+ break;
79
+ }
80
+ case "data": {
81
+ const take = Math.min(this.remaining, chunk.length - at);
82
+ const piece = chunk.subarray(at, at + take);
83
+ at += take;
84
+ this.remaining -= take;
85
+ this.chunkHash?.update(piece);
86
+ this.emit(piece);
87
+ if (this.remaining === 0) {
88
+ if (this.chunkHash !== null) {
89
+ const refused = this.checkChunk(this.chunkHash.digest("hex"));
90
+ this.chunkHash = null;
91
+ if (refused !== null)
92
+ return refused;
93
+ }
94
+ this.state = "data-end";
95
+ this.crlf = 0;
96
+ }
97
+ break;
98
+ }
99
+ case "data-end":
100
+ case "final-crlf": {
101
+ const expected = this.crlf === 0 ? 0x0d : 0x0a;
102
+ if (chunk[at] !== expected) {
103
+ return invalid(this.state === "data-end"
104
+ ? "a chunk's bytes are not followed by CRLF, so its size does not match its data"
105
+ : "the last chunk is not followed by CRLF");
106
+ }
107
+ at += 1;
108
+ this.crlf += 1;
109
+ if (this.crlf === 2)
110
+ this.state = this.state === "data-end" ? "size" : "end";
111
+ break;
112
+ }
113
+ case "end":
114
+ return invalid("bytes follow the end of the aws-chunked body");
115
+ }
116
+ }
117
+ return null;
118
+ }
119
+ /** The body has ended: was it whole? */
120
+ finish() {
121
+ switch (this.state) {
122
+ case "size":
123
+ case "data":
124
+ case "data-end":
125
+ return incomplete("the body ended before its last chunk");
126
+ case "final-crlf":
127
+ case "end":
128
+ return null;
129
+ case "trailer": {
130
+ if (this.lineBytes > 0) {
131
+ const text = this.takeLine();
132
+ const line = text.endsWith("\r") ? text.slice(0, -1) : text;
133
+ // The final empty line, cut short of its LF: closing the trailer is all it would do.
134
+ if (line.length === 0)
135
+ return this.onTrailerLine(line);
136
+ const refused = this.onTrailerLine(line);
137
+ if (refused !== null)
138
+ return refused;
139
+ }
140
+ return this.closeTrailer();
141
+ }
142
+ }
143
+ }
144
+ takeLine() {
145
+ const text = Buffer.concat(this.line).toString("latin1");
146
+ this.line = [];
147
+ this.lineBytes = 0;
148
+ return text;
149
+ }
150
+ onChunkHeader(raw) {
151
+ if (!raw.endsWith("\r"))
152
+ return invalid("a chunk header does not end in CRLF");
153
+ const text = raw.slice(0, -1);
154
+ const semicolon = text.indexOf(";");
155
+ const sizeText = semicolon < 0 ? text : text.slice(0, semicolon);
156
+ if (!/^[0-9a-fA-F]{1,13}$/.test(sizeText))
157
+ return invalid("a chunk does not start with its size in hex");
158
+ const size = parseInt(sizeText, 16);
159
+ if (this.signed) {
160
+ const match = semicolon < 0 ? null : /^chunk-signature=([0-9a-f]{64})$/.exec(text.slice(semicolon + 1));
161
+ const signature = match?.[1];
162
+ if (signature === undefined)
163
+ return invalid("a chunk of a chunk-signed body carries no chunk-signature");
164
+ this.chunkSignature = signature;
165
+ }
166
+ if (this.decoded + size > this.plan.size) {
167
+ return incomplete("the chunks carry more bytes than x-amz-decoded-content-length");
168
+ }
169
+ if (size === 0) {
170
+ if (this.signed) {
171
+ const refused = this.checkChunk(EMPTY_SHA256);
172
+ if (refused !== null)
173
+ return refused;
174
+ }
175
+ this.state = this.plan.framing === "signed" ? "final-crlf" : "trailer";
176
+ this.crlf = 0;
177
+ return null;
178
+ }
179
+ this.decoded += size;
180
+ this.remaining = size;
181
+ this.chunkHash = this.signed ? createHash("sha256") : null;
182
+ this.state = "data";
183
+ return null;
184
+ }
185
+ hmac(stringToSign) {
186
+ return createHmac("sha256", this.plan.signing.key).update(stringToSign).digest("hex");
187
+ }
188
+ /** One link of the chain: this chunk's signature over its bytes and the signature before it. */
189
+ checkChunk(dataHash) {
190
+ const { stamp, scope } = this.plan.signing;
191
+ const expected = this.hmac(["AWS4-HMAC-SHA256-PAYLOAD", stamp, scope, this.previous, EMPTY_SHA256, dataHash].join("\n"));
192
+ if (!sameHex(expected, this.chunkSignature)) {
193
+ return new BodyRefusal(403, "SignatureDoesNotMatch", "a chunk's signature does not match its bytes");
194
+ }
195
+ this.previous = expected;
196
+ return null;
197
+ }
198
+ onTrailerLine(line) {
199
+ if (line.length === 0) {
200
+ this.state = "end";
201
+ return this.closeTrailer();
202
+ }
203
+ if (this.trailerSignature !== null)
204
+ return invalid("only the end of the body may follow the trailer signature");
205
+ const colon = line.indexOf(":");
206
+ if (colon < 0)
207
+ return invalid("a trailer line is not name:value");
208
+ const name = line.slice(0, colon).trim().toLowerCase();
209
+ const value = line.slice(colon + 1).trim();
210
+ if (name === "x-amz-trailer-signature") {
211
+ if (this.plan.framing !== "signed-trailer")
212
+ return invalid("an unsigned trailer carries a trailer signature");
213
+ if (!/^[0-9a-f]{64}$/.test(value))
214
+ return invalid("the trailer signature is not 64 hex digits");
215
+ this.trailerSignature = value;
216
+ return null;
217
+ }
218
+ const algorithm = algorithmOfHeader(name);
219
+ if (algorithm === null || !this.plan.trailers.includes(algorithm)) {
220
+ return invalid(`the trailer ${name} was not declared in x-amz-trailer`);
221
+ }
222
+ if (this.trailerValues.has(algorithm))
223
+ return invalid(`the trailer ${name} arrives twice`);
224
+ const parsed = parseChecksumValue(algorithm, value);
225
+ if (parsed === null)
226
+ return invalid(`the trailer ${name} is not a ${algorithm} value`);
227
+ this.trailerValues.set(algorithm, parsed);
228
+ this.trailerPairs.push([name, value]);
229
+ return null;
230
+ }
231
+ /**
232
+ * Every promised trailer is in; for a chunk-signed body, the trailer signature holds.
233
+ *
234
+ * The string it signs is `AWS4-HMAC-SHA256-TRAILER`, the timestamp, the scope, the last chunk's
235
+ * signature, and the SHA-256 of the trailer headers as `name:value\n`, sorted by name.
236
+ */
237
+ closeTrailer() {
238
+ for (const algorithm of this.plan.trailers) {
239
+ if (!this.trailerValues.has(algorithm)) {
240
+ return invalid(`x-amz-trailer promised ${checksumHeaderName(algorithm)} and the body ended without it`);
241
+ }
242
+ }
243
+ if (this.plan.framing !== "signed-trailer")
244
+ return null;
245
+ if (this.trailerSignature === null)
246
+ return invalid("a chunk-signed trailer carries no x-amz-trailer-signature");
247
+ const canonical = [...this.trailerPairs]
248
+ .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))
249
+ .map(([name, value]) => `${name}:${value}\n`)
250
+ .join("");
251
+ const { stamp, scope } = this.plan.signing;
252
+ const expected = this.hmac([
253
+ "AWS4-HMAC-SHA256-TRAILER",
254
+ stamp,
255
+ scope,
256
+ this.previous,
257
+ createHash("sha256").update(canonical).digest("hex"),
258
+ ].join("\n"));
259
+ if (!sameHex(expected, this.trailerSignature)) {
260
+ return new BodyRefusal(403, "SignatureDoesNotMatch", "the trailer signature does not match the trailer");
261
+ }
262
+ return null;
263
+ }
264
+ }
@@ -0,0 +1,13 @@
1
+ import { BodyRefusal, type Plan } from "./body-plan.ts";
2
+ import { type ChecksumAlgorithm } from "./checksum.ts";
3
+ /** The digests and checksums of the decoded bytes, computed as they pass. */
4
+ export declare class Measure {
5
+ count: number;
6
+ private readonly sha256;
7
+ private readonly md5;
8
+ private readonly checksums;
9
+ constructor(plan: Plan);
10
+ update(bytes: Buffer): void;
11
+ /** The verdict on the whole body, in the order a client would want the first failure named. */
12
+ judge(plan: Plan, trailerValues: ReadonlyMap<ChecksumAlgorithm, Buffer>): BodyRefusal | null;
13
+ }