@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
package/dist/s3/sigv4.js CHANGED
@@ -6,57 +6,30 @@
6
6
  // machine, and every page a browser on it loads, can also reach 127.0.0.1. The signature is the
7
7
  // one thing that separates the tool the person started from everything else running as them.
8
8
  //
9
- // ⛔ WHAT IS DELIBERATELY NOT HERE. The body is not hashed here. The signature covers a payload hash
9
+ // ⛔ TWO WAYS TO CARRY ONE SIGNATURE. An `Authorization` header, which is what every S3 client
10
+ // sends, and a presigned URL (`X-Amz-Algorithm`, `X-Amz-Credential`, … in the query), which is
11
+ // what a client hands to somebody who has no key: a browser, `curl`, a download link. Both are
12
+ // checked by the same code against the same pairs with the same comparison; what differs is only
13
+ // where the parts are read from, and that a presigned URL carries its own lifetime. The query
14
+ // form is read in `sigv4-presigned.ts`; what both forms share is in `sigv4-canonical.ts`.
15
+ //
16
+ // ⛔ WHAT IS DELIBERATELY NOT HERE. The body is not read here. The signature covers a payload hash
10
17
  // the client DECLARES in `x-amz-content-sha256`, and whether the bytes that follow really hash to
11
- // that value can only be known once they have all arrived. This module returns the declared value
12
- // and the caller enforces it while streaming -- doing it here would mean holding whole uploads in
13
- // memory before a single byte reached the storage network.
18
+ // that value -- or, for a chunk-signed body, whether each chunk's signature holds -- can only be
19
+ // known once they have arrived. This module checks that the declared value is one S3 allows and
20
+ // hands `body.ts` what it needs to continue the check while the bytes stream: the signing key,
21
+ // the scope, the timestamp and the seed signature. Doing it here would mean holding whole uploads
22
+ // in memory before a single byte reached the storage network.
14
23
  //
15
24
  // The rules implemented are S3's, which differ from the generic SigV4 ones in one way that matters:
16
25
  // the canonical path is the request path EXACTLY as it arrived, neither normalised nor re-encoded.
17
26
  import { createHash, createHmac, timingSafeEqual } from "node:crypto";
27
+ import { amzDateToMs, canonicalOf, headerValue, isPayloadHash, parseCredentialScope, queryParts, refuse, scopeProblem, signingKey, unsignedHeaders, } from "./sigv4-canonical.js";
28
+ import { isPresigned, presentedFromQuery } from "./sigv4-presigned.js";
29
+ export { amzDateToMs, canonicalQuery, isPayloadHash, STREAMING_PAYLOAD, STREAMING_PAYLOAD_TRAILER, STREAMING_UNSIGNED_PAYLOAD_TRAILER, UNSIGNED_PAYLOAD, } from "./sigv4-canonical.js";
30
+ export { MAX_PRESIGNED_EXPIRY_SECONDS } from "./sigv4-presigned.js";
18
31
  /** How far a request's own timestamp may sit from ours before it is refused. AWS uses the same. */
19
32
  export const MAX_CLOCK_SKEW_MS = 15 * 60 * 1000;
20
- /** The literals a client may put in `x-amz-content-sha256` instead of a hex digest. */
21
- export const UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
22
- export const STREAMING_PAYLOAD = "STREAMING-AWS4-HMAC-SHA256-PAYLOAD";
23
- export const STREAMING_PAYLOAD_TRAILER = "STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER";
24
- /** One refusal, shaped so it satisfies both verdict types — neither of which has an `ok: true`. */
25
- function refuse(code, message) {
26
- return { ok: false, code, message };
27
- }
28
- function headerValue(headers, name) {
29
- const raw = headers[name];
30
- if (raw === undefined)
31
- return undefined;
32
- return Array.isArray(raw) ? raw.join(",") : String(raw);
33
- }
34
- /**
35
- * RFC 3986 encoding, which is what SigV4 means by "URI-encode".
36
- *
37
- * ⚠ `encodeURIComponent` leaves `!'()*` alone and AWS does not, so those four are finished by hand.
38
- * A query string that contains one of them and is encoded the JavaScript way produces a different
39
- * canonical request from the client's, and the request is refused for no reason a person can see.
40
- */
41
- function uriEncode(value) {
42
- return encodeURIComponent(value).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
43
- }
44
- /** `k=v&k2=v2` in the order AWS wants: encoded, sorted by key and then by value. */
45
- export function canonicalQuery(rawQuery) {
46
- if (rawQuery.length === 0)
47
- return "";
48
- const pairs = [];
49
- for (const part of rawQuery.split("&")) {
50
- if (part.length === 0)
51
- continue;
52
- const at = part.indexOf("=");
53
- const key = at < 0 ? part : part.slice(0, at);
54
- const value = at < 0 ? "" : part.slice(at + 1);
55
- pairs.push([uriEncode(decodeURIComponent(key)), uriEncode(decodeURIComponent(value))]);
56
- }
57
- pairs.sort((a, b) => (a[0] === b[0] ? (a[1] < b[1] ? -1 : 1) : a[0] < b[0] ? -1 : 1));
58
- return pairs.map(([k, v]) => `${k}=${v}`).join("&");
59
- }
60
33
  /** Pull apart `AWS4-HMAC-SHA256 Credential=…, SignedHeaders=…, Signature=…`. */
61
34
  export function parseAuthorization(header) {
62
35
  if (header === undefined || !header.startsWith("AWS4-HMAC-SHA256 "))
@@ -73,66 +46,106 @@ export function parseAuthorization(header) {
73
46
  const signature = fields.get("Signature");
74
47
  if (credential === undefined || signedHeaders === undefined || signature === undefined)
75
48
  return null;
76
- const scope = credential.split("/");
77
- if (scope.length !== 5 || scope[4] !== "aws4_request")
78
- return null;
79
- const [accessKeyId, date, region, service] = scope;
80
- if (accessKeyId === undefined || date === undefined || region === undefined || service === undefined) {
49
+ const scope = parseCredentialScope(credential);
50
+ if (scope === null)
81
51
  return null;
82
- }
83
52
  return {
84
- accessKeyId,
85
- date,
86
- region,
87
- service,
53
+ ...scope,
88
54
  signedHeaders: signedHeaders.split(";").filter((h) => h.length > 0),
89
55
  signature,
90
56
  };
91
57
  }
92
- function signingKey(secret, date, region, service) {
93
- const kDate = createHmac("sha256", `AWS4${secret}`).update(date).digest();
94
- const kRegion = createHmac("sha256", kDate).update(region).digest();
95
- const kService = createHmac("sha256", kRegion).update(service).digest();
96
- return createHmac("sha256", kService).update("aws4_request").digest();
58
+ /** Which of the two forms the request used, and its parts. */
59
+ function present(request) {
60
+ const at = request.url.indexOf("?");
61
+ const rawQuery = at < 0 ? "" : request.url.slice(at + 1);
62
+ let parts;
63
+ try {
64
+ parts = queryParts(rawQuery);
65
+ }
66
+ catch {
67
+ return refuse("InvalidURI", "the query string has a percent escape that does not decode");
68
+ }
69
+ const presigned = isPresigned(parts);
70
+ const header = headerValue(request.headers, "authorization");
71
+ // ⛔ ONE SIGNATURE PER REQUEST. With both, which one was checked would be a choice this code
72
+ // made, and the other would be a signature nobody verified riding on a request that passed.
73
+ if (presigned && header !== undefined) {
74
+ return refuse("InvalidArgument", "a request is signed by an authorization header or by its query, not both");
75
+ }
76
+ // ⛔ NO SESSION TOKENS, IN EITHER FORM. This gateway hands out plain pairs and nothing else, so a
77
+ // request signed with temporary credentials was not signed with one of them. The presigned
78
+ // form's query parameter is refused where that form is read.
79
+ if (headerValue(request.headers, "x-amz-security-token") !== undefined) {
80
+ return refuse("InvalidToken", "this gateway issues no session tokens, so x-amz-security-token cannot be honoured");
81
+ }
82
+ if (presigned)
83
+ return presentedFromQuery(request, parts);
84
+ const auth = parseAuthorization(header);
85
+ if (auth === null) {
86
+ return refuse("AccessDenied", "no AWS Signature Version 4 authorization header or presigned query");
87
+ }
88
+ const problem = scopeProblem(auth);
89
+ if (problem !== null)
90
+ return refuse("AuthorizationHeaderMalformed", `The authorization header is malformed: ${problem}.`);
91
+ return {
92
+ ...auth,
93
+ stamp: headerValue(request.headers, "x-amz-date"),
94
+ expiresSeconds: null,
95
+ canonicalQuery: canonicalOf(parts),
96
+ payloadHash: headerValue(request.headers, "x-amz-content-sha256"),
97
+ };
97
98
  }
98
- /** `20260824T232759Z` → epoch milliseconds, or null if it is not that shape. */
99
- export function amzDateToMs(stamp) {
100
- if (stamp === undefined)
101
- return null;
102
- const m = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/.exec(stamp);
103
- if (m === null)
104
- return null;
105
- return Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5]), Number(m[6]));
99
+ function isRefusal(value) {
100
+ return "ok" in value;
106
101
  }
107
102
  /**
108
- * Rebuild the string the client signed and check that the signature matches.
103
+ * The check itself, once the parts have been found and the pair chosen.
109
104
  *
110
- * The clock is passed in rather than read here: a test that cannot choose "now" cannot check the
111
- * skew rule at all, and that rule is the one that stops a captured request being replayed tomorrow.
105
+ * ⛔ A PRESIGNED URL LIVES FROM ITS DATE TO ITS DATE PLUS `X-Amz-Expires`, AND NO LONGER. The skew
106
+ * rule still guards its start -- a URL dated further ahead than the clock may drift is refused --
107
+ * but its end is the lifetime it names with no slack added: slack on an expiry is a link that
108
+ * still works after the person who made it was told it would not.
112
109
  */
113
- export function verifySignature(request, credential, now) {
114
- const auth = parseAuthorization(headerValue(request.headers, "authorization"));
115
- if (auth === null)
116
- return refuse("AccessDenied", "no AWS Signature Version 4 authorization header");
117
- if (auth.accessKeyId !== credential.accessKeyId) {
110
+ function verifyPresented(request, presented, credential, now) {
111
+ if (presented.accessKeyId !== credential.accessKeyId) {
118
112
  return refuse("InvalidAccessKeyId", "that access key is not the one this gateway printed");
119
113
  }
120
- const stamp = headerValue(request.headers, "x-amz-date");
114
+ const stamp = presented.stamp;
121
115
  const signedAt = amzDateToMs(stamp);
122
- if (signedAt === null)
116
+ if (stamp === undefined || signedAt === null)
123
117
  return refuse("AccessDenied", "missing or malformed x-amz-date");
124
- if (Math.abs(now - signedAt) > MAX_CLOCK_SKEW_MS) {
125
- return refuse("RequestTimeTooSkewed", "the request's own timestamp is too far from this clock");
118
+ if (presented.expiresSeconds === null) {
119
+ if (Math.abs(now - signedAt) > MAX_CLOCK_SKEW_MS) {
120
+ return refuse("RequestTimeTooSkewed", "the request's own timestamp is too far from this clock");
121
+ }
126
122
  }
127
- if (stamp !== undefined && !stamp.startsWith(auth.date)) {
123
+ else {
124
+ if (signedAt - now > MAX_CLOCK_SKEW_MS) {
125
+ return refuse("RequestTimeTooSkewed", "the presigned URL is dated further ahead than this clock allows");
126
+ }
127
+ if (now > signedAt + presented.expiresSeconds * 1000) {
128
+ return refuse("AccessDenied", "Request has expired");
129
+ }
130
+ }
131
+ // Exactly the day: the scope's date was checked to be eight digits, so an empty one cannot pass
132
+ // as the start of every timestamp.
133
+ if (stamp.slice(0, 8) !== presented.date) {
128
134
  return refuse("AccessDenied", "the signature's date does not match x-amz-date");
129
135
  }
130
- const payloadHash = headerValue(request.headers, "x-amz-content-sha256");
136
+ const unsigned = unsignedHeaders(request, presented);
137
+ if (unsigned.length > 0) {
138
+ return refuse("AccessDenied", `There were headers present in the request which were not signed: ${unsigned.join(", ")}`);
139
+ }
140
+ const payloadHash = presented.payloadHash;
131
141
  if (payloadHash === undefined) {
132
142
  return refuse("AccessDenied", "missing x-amz-content-sha256");
133
143
  }
144
+ if (!isPayloadHash(payloadHash)) {
145
+ return refuse("InvalidArgument", "x-amz-content-sha256 must be a lowercase hex SHA-256, UNSIGNED-PAYLOAD or one of the STREAMING- values");
146
+ }
134
147
  const canonicalHeaders = [];
135
- for (const name of auth.signedHeaders) {
148
+ for (const name of presented.signedHeaders) {
136
149
  const value = headerValue(request.headers, name);
137
150
  if (value === undefined) {
138
151
  return refuse("AccessDenied", `the signature covers a header that is not here: ${name}`);
@@ -141,31 +154,42 @@ export function verifySignature(request, credential, now) {
141
154
  }
142
155
  const at = request.url.indexOf("?");
143
156
  const path = at < 0 ? request.url : request.url.slice(0, at);
144
- const query = at < 0 ? "" : request.url.slice(at + 1);
145
157
  const canonicalRequest = [
146
158
  request.method.toUpperCase(),
147
159
  path,
148
- canonicalQuery(query),
160
+ presented.canonicalQuery,
149
161
  canonicalHeaders.join(""),
150
- auth.signedHeaders.join(";"),
162
+ presented.signedHeaders.join(";"),
151
163
  payloadHash,
152
164
  ].join("\n");
153
- const scope = `${auth.date}/${auth.region}/${auth.service}/aws4_request`;
165
+ const scope = `${presented.date}/${presented.region}/${presented.service}/aws4_request`;
154
166
  const stringToSign = [
155
167
  "AWS4-HMAC-SHA256",
156
168
  stamp,
157
169
  scope,
158
170
  createHash("sha256").update(canonicalRequest).digest("hex"),
159
171
  ].join("\n");
160
- const expected = createHmac("sha256", signingKey(credential.secretAccessKey, auth.date, auth.region, auth.service))
161
- .update(stringToSign)
162
- .digest("hex");
163
- const given = Buffer.from(auth.signature, "utf8");
172
+ const key = signingKey(credential.secretAccessKey, presented.date, presented.region, presented.service);
173
+ const expected = createHmac("sha256", key).update(stringToSign).digest("hex");
174
+ const given = Buffer.from(presented.signature, "utf8");
164
175
  const mine = Buffer.from(expected, "utf8");
165
176
  if (given.length !== mine.length || !timingSafeEqual(given, mine)) {
166
177
  return refuse("SignatureDoesNotMatch", "the signature does not match what was signed");
167
178
  }
168
- return { ok: true, payloadHash };
179
+ return { ok: true, payloadHash, signing: { key, scope, stamp, seedSignature: expected } };
180
+ }
181
+ /**
182
+ * Rebuild the string the client signed and check that the signature matches -- in the
183
+ * `Authorization` header or in a presigned query, whichever the request carries.
184
+ *
185
+ * The clock is passed in rather than read here: a test that cannot choose "now" cannot check the
186
+ * skew rule at all, and that rule is the one that stops a captured request being replayed tomorrow.
187
+ */
188
+ export function verifySignature(request, credential, now) {
189
+ const presented = present(request);
190
+ if (isRefusal(presented))
191
+ return presented;
192
+ return verifyPresented(request, presented, credential, now);
169
193
  }
170
194
  /**
171
195
  * Which of a gateway's pairs the request named, without telling the clock how many there are.
@@ -174,32 +198,43 @@ export function verifySignature(request, credential, now) {
174
198
  * it travels in the header in the clear -- but a scan that returned at the first match would
175
199
  * take a length of time that says WHERE in the list a key sits, and that is a fact about the
176
200
  * gateway's customers rather than about the request.
201
+ *
202
+ * ⛔ TWO PAIRS WITH ONE ID ARE NOBODY'S. Which secret, and which bucket restriction, a request is
203
+ * held to would otherwise be whichever came later in the list -- a choice made by the order a
204
+ * business happened to build it in. `gatewayHandler` refuses such a list when the gateway is
205
+ * made; this answers `"ambiguous"` for a list changed after that.
177
206
  */
178
207
  function named(credentials, accessKeyId) {
179
208
  const wanted = Buffer.from(accessKeyId, "utf8");
180
209
  let found = null;
210
+ let matches = 0;
181
211
  for (const candidate of credentials) {
182
212
  const id = Buffer.from(candidate.accessKeyId, "utf8");
183
- if (id.length === wanted.length && timingSafeEqual(id, wanted))
213
+ if (id.length === wanted.length && timingSafeEqual(id, wanted)) {
184
214
  found = candidate;
215
+ matches += 1;
216
+ }
185
217
  }
186
- return found;
218
+ return matches > 1 ? "ambiguous" : found;
187
219
  }
188
220
  /**
189
221
  * The whole check, against every pair a gateway answers to: which one signed, and whether it did.
190
222
  *
191
- * ⚠ THE THREE REFUSALS ARE DIFFERENT ON PURPOSE. "No authorization header at all", "a key this
192
- * gateway does not have" and "a signature that does not hold" are three different things for
193
- * whoever is reading a client's logs, and none of them says anything about what is in the drive.
223
+ * ⚠ THE THREE REFUSALS ARE DIFFERENT ON PURPOSE. "No signature at all", "a key this gateway does
224
+ * not have" and "a signature that does not hold" are three different things for whoever is
225
+ * reading a client's logs, and none of them says anything about what is in the drive.
194
226
  */
195
227
  export function verifyAgainst(request, credentials, now) {
196
- const auth = parseAuthorization(headerValue(request.headers, "authorization"));
197
- if (auth === null)
198
- return refuse("AccessDenied", "no AWS Signature Version 4 authorization header");
199
- const credential = named(credentials, auth.accessKeyId);
228
+ const presented = present(request);
229
+ if (isRefusal(presented))
230
+ return presented;
231
+ const credential = named(credentials, presented.accessKeyId);
200
232
  if (credential === null) {
201
233
  return refuse("InvalidAccessKeyId", "that access key is not one this gateway answers to");
202
234
  }
203
- const verdict = verifySignature(request, credential, now);
204
- return verdict.ok ? { ok: true, payloadHash: verdict.payloadHash, credential } : verdict;
235
+ if (credential === "ambiguous") {
236
+ return refuse("InvalidAccessKeyId", "more than one of this gateway's pairs has that access key id");
237
+ }
238
+ const verdict = verifyPresented(request, presented, credential, now);
239
+ return verdict.ok ? { ...verdict, credential } : verdict;
205
240
  }
@@ -0,0 +1,37 @@
1
+ import type { DecodedBody } from "./body.ts";
2
+ /** What a spooled body came to. */
3
+ export interface Spooled {
4
+ readonly size: number;
5
+ /** Hex MD5 of the bytes, when it was asked for — what S3 answers as a part's tag. */
6
+ readonly md5: string | null;
7
+ }
8
+ /**
9
+ * Write a body to a new file, 0600, and return only once every rule the request carried held.
10
+ *
11
+ * ⛔ THE FILE IS CREATED EXCLUSIVELY. Its name is the caller's fresh random one; a file already
12
+ * there under that name is not ours, and writing into it would be writing somebody's plaintext
13
+ * into a file somebody else can read.
14
+ *
15
+ * ⛔ `limit` COUNTS THE BYTES THAT ARRIVE, NOT THE ONES DECLARED. A length header is the client's
16
+ * word; the spool stops, and the upload is refused, the moment one byte past the limit is in.
17
+ */
18
+ export declare function spoolBody(body: DecodedBody, path: string, options: {
19
+ md5: boolean;
20
+ limit?: number | undefined;
21
+ }): Promise<Spooled>;
22
+ /**
23
+ * Read a small body — an XML ask — into a string, refusing one larger than `limit` bytes.
24
+ *
25
+ * ⚠ AN OVERSIZED BODY IS READ TO ITS END AND DISCARDED rather than cut off. Stopping mid-body
26
+ * tears the connection down, and a client told nothing but "connection reset" retries the same
27
+ * request; the refusal below is what tells it why.
28
+ */
29
+ export declare function readBodyText(body: DecodedBody, limit: number, what: string): Promise<string>;
30
+ /**
31
+ * Run `use` on a decoded body; when it fails, whatever of the body is still unread is read and dropped.
32
+ *
33
+ * ⛔ A BODY NOBODY READS HOLDS THE CONNECTION. The decoder pauses the request while its output is
34
+ * full, so a refusal answered before the body was consumed — no such upload, a key that is not
35
+ * free — would leave the client stuck mid-upload, never reading the answer it was sent.
36
+ */
37
+ export declare function consuming<T>(body: DecodedBody, use: () => Promise<T>): Promise<T>;
@@ -0,0 +1,104 @@
1
+ // A request body, taken off the socket: into a file for an object, into memory for a small XML ask.
2
+ //
3
+ // ⛔ THE BODY IS WAITED FOR TWICE, AND BOTH WAITS ARE HERE. Once for its bytes and once for its
4
+ // verdict — `verified`, which only settles after the last byte is in. Everything that stores a
5
+ // body goes through this file, so "spooled but not yet verified" cannot be mistaken for
6
+ // "ready to store" in one caller and not another.
7
+ //
8
+ // ⚠ THE VERDICT IS LISTENED TO BEFORE THE FIRST BYTE IS READ. A body that fails while it is still
9
+ // arriving rejects `verified` with nobody awaiting it yet, and an unheard rejection takes the
10
+ // whole process down with it — every other upload in flight included.
11
+ import { createHash } from "node:crypto";
12
+ import { createWriteStream } from "node:fs";
13
+ import { Transform } from "node:stream";
14
+ import { pipeline } from "node:stream/promises";
15
+ import { S3Refusal } from "./answer.js";
16
+ import { tooLarge } from "./drive-limits.js";
17
+ /** `verified`, as a value: null when it held, the refusal otherwise. Never rejects. */
18
+ function heard(body) {
19
+ return body.verified.then(() => null, (refusal) => refusal ?? new S3Refusal(400, "InvalidRequest", "The request body was refused."));
20
+ }
21
+ function shortOrLong(declared, arrived) {
22
+ return new S3Refusal(400, "IncompleteBody", `The request said ${declared} bytes and ${arrived} arrived. Nothing was stored.`);
23
+ }
24
+ /**
25
+ * Write a body to a new file, 0600, and return only once every rule the request carried held.
26
+ *
27
+ * ⛔ THE FILE IS CREATED EXCLUSIVELY. Its name is the caller's fresh random one; a file already
28
+ * there under that name is not ours, and writing into it would be writing somebody's plaintext
29
+ * into a file somebody else can read.
30
+ *
31
+ * ⛔ `limit` COUNTS THE BYTES THAT ARRIVE, NOT THE ONES DECLARED. A length header is the client's
32
+ * word; the spool stops, and the upload is refused, the moment one byte past the limit is in.
33
+ */
34
+ export async function spoolBody(body, path, options) {
35
+ const verdict = heard(body);
36
+ const digest = options.md5 ? createHash("md5") : null;
37
+ const limit = options.limit;
38
+ let size = 0;
39
+ const counting = new Transform({
40
+ transform(chunk, _encoding, next) {
41
+ size += chunk.length;
42
+ if (limit !== undefined && size > limit) {
43
+ next(tooLarge(limit));
44
+ return;
45
+ }
46
+ digest?.update(chunk);
47
+ next(null, chunk);
48
+ },
49
+ });
50
+ await pipeline(body.stream, counting, createWriteStream(path, { flags: "wx", mode: 0o600 }));
51
+ const refusal = await verdict;
52
+ if (refusal !== null)
53
+ throw refusal;
54
+ if (body.size !== null && size !== body.size)
55
+ throw shortOrLong(body.size, size);
56
+ return { size, md5: digest === null ? null : digest.digest("hex") };
57
+ }
58
+ /**
59
+ * Read a small body — an XML ask — into a string, refusing one larger than `limit` bytes.
60
+ *
61
+ * ⚠ AN OVERSIZED BODY IS READ TO ITS END AND DISCARDED rather than cut off. Stopping mid-body
62
+ * tears the connection down, and a client told nothing but "connection reset" retries the same
63
+ * request; the refusal below is what tells it why.
64
+ */
65
+ export async function readBodyText(body, limit, what) {
66
+ const tooLarge = new S3Refusal(400, "MalformedXML", `${what} is larger than ${limit} bytes.`);
67
+ const verdict = heard(body);
68
+ if (body.size !== null && body.size > limit) {
69
+ body.stream.resume();
70
+ throw tooLarge;
71
+ }
72
+ const chunks = [];
73
+ let total = 0;
74
+ for await (const chunk of body.stream) {
75
+ const bytes = typeof chunk === "string" ? Buffer.from(chunk) : chunk instanceof Uint8Array ? chunk : new Uint8Array(0);
76
+ total += bytes.length;
77
+ if (total <= limit)
78
+ chunks.push(bytes);
79
+ }
80
+ if (total > limit)
81
+ throw tooLarge;
82
+ const refusal = await verdict;
83
+ if (refusal !== null)
84
+ throw refusal;
85
+ if (body.size !== null && total !== body.size)
86
+ throw shortOrLong(body.size, total);
87
+ return Buffer.concat(chunks).toString("utf8");
88
+ }
89
+ /**
90
+ * Run `use` on a decoded body; when it fails, whatever of the body is still unread is read and dropped.
91
+ *
92
+ * ⛔ A BODY NOBODY READS HOLDS THE CONNECTION. The decoder pauses the request while its output is
93
+ * full, so a refusal answered before the body was consumed — no such upload, a key that is not
94
+ * free — would leave the client stuck mid-upload, never reading the answer it was sent.
95
+ */
96
+ export async function consuming(body, use) {
97
+ try {
98
+ return await use();
99
+ }
100
+ catch (error) {
101
+ body.stream.resume();
102
+ throw error;
103
+ }
104
+ }
@@ -1,10 +1,93 @@
1
- import { type Readable } from "node:stream";
1
+ import type { DecodedBody } from "./body.ts";
2
+ import type { StoreOutcome, WriteMeta } from "./contract.ts";
3
+ import type { WriteCondition } from "./drive-conditions.ts";
4
+ import type { ObjectChecksum } from "./multipart-assemble.ts";
5
+ import type { PartChoice } from "./xml-read.ts";
6
+ export type { PartChoice } from "./xml-read.ts";
7
+ export type { ObjectChecksum } from "./multipart-assemble.ts";
2
8
  /** What the staging does with a finished file: store it in the drive at that key. */
3
- export type StoreFile = (key: string, path: string) => Promise<void>;
9
+ export type StoreFile = (key: string, path: string, meta: WriteMeta, condition?: WriteCondition) => Promise<StoreOutcome>;
10
+ /** How long an upload nobody has touched is kept. S3 leaves this to a lifecycle rule. */
11
+ export declare const UPLOAD_LIFETIME_MS: number;
12
+ /** How long a finished upload is remembered, so a finish sent twice is answered the same twice. */
13
+ export declare const FINISHED_MEMORY_MS: number;
14
+ /** How often a gateway's own store sweeps its directory, and marks the uploads it is working on. */
15
+ export declare const SWEEP_EVERY_MS: number;
16
+ /** One piece, as `ListParts` describes it. */
17
+ export interface StagedPart {
18
+ readonly partNumber: number;
19
+ /** The quoted MD5 of the piece's bytes — what S3 answers for a part. */
20
+ readonly etag: string;
21
+ readonly size: number;
22
+ readonly stagedAt: number;
23
+ }
24
+ /** One upload in progress, as `ListMultipartUploads` describes it. */
25
+ export interface StagedUpload {
26
+ readonly uploadId: string;
27
+ readonly key: string;
28
+ readonly meta: WriteMeta;
29
+ readonly initiated: number;
30
+ }
31
+ /** What a finish carries beyond its part list. */
32
+ export interface CompleteOptions {
33
+ /**
34
+ * Called once the upload and the list have been checked and what is left is the store, which can
35
+ * take minutes: the gateway begins its 200 then. Every refusal about the request itself is thrown
36
+ * before it.
37
+ */
38
+ readonly accepted?: (() => void) | undefined;
39
+ /** `If-Match` / `If-None-Match` on the finish, judged where the file is stored. */
40
+ readonly condition?: WriteCondition | undefined;
41
+ /** What the client says the whole object comes to. */
42
+ readonly checksum?: ObjectChecksum | null | undefined;
43
+ }
44
+ /** A bucket's uploads, as the drive the bucket has now sees them. */
4
45
  export interface Staging {
5
- begin(key: string): Promise<string>;
6
- part(uploadId: string, partNumber: number, body: Readable, size: number, expectedSha256: string | null): Promise<string>;
7
- complete(uploadId: string): Promise<string>;
8
- abort(uploadId: string): Promise<void>;
46
+ begin(key: string, meta: WriteMeta): Promise<string>;
47
+ /** Stage one piece and answer its tag. `key` must be the one the upload began with. */
48
+ part(uploadId: string, key: string, partNumber: number, body: DecodedBody): Promise<string>;
49
+ /** Join exactly the listed pieces, in the order listed, and store them at the upload's key. */
50
+ complete(uploadId: string, key: string, parts: readonly PartChoice[], options?: CompleteOptions): Promise<StoreOutcome>;
51
+ /** Remove an upload and its pieces. One being finished is waited for first, never cut short. */
52
+ abort(uploadId: string, key: string): Promise<void>;
53
+ /** The pieces staged so far, by part number. */
54
+ parts(uploadId: string, key: string): Promise<readonly StagedPart[]>;
55
+ /** Every upload begun and neither finished nor aborted, by key and then by when it began. */
56
+ uploads(): Promise<readonly StagedUpload[]>;
57
+ }
58
+ /** What a bucket's drive hands its view of the store, fresh on every request. */
59
+ export interface UploadAccount {
60
+ /** Store a finished file through the bucket's drive as it is now. */
61
+ readonly store: StoreFile;
62
+ /**
63
+ * Which account the bucket belongs to now. Absent, or null, means the caller does not say — the
64
+ * account behind the bucket never changes, as it does not for `nmts s3`.
65
+ */
66
+ readonly owner?: (() => Promise<string | null>) | undefined;
67
+ /** The most bytes one object may have. */
68
+ readonly maxObjectBytes?: number | undefined;
69
+ }
70
+ export interface StagingStore {
71
+ /** The store as one bucket sees it through the drive it has now. */
72
+ view(bucket: string, account: UploadAccount): Staging;
73
+ /** Remove what nobody has touched for `UPLOAD_LIFETIME_MS`: remembered uploads and the directory's own. */
74
+ sweep(): Promise<void>;
75
+ /** Stop sweeping, and wait for every finish in progress. The directory itself is the caller's. */
76
+ close(): Promise<void>;
77
+ }
78
+ export interface StagingOptions {
79
+ readonly clock?: (() => number) | undefined;
80
+ /**
81
+ * Sweep the directory now and then this often, on a timer that does not keep a process alive.
82
+ * Absent: remembered uploads are swept when one begins, and the directory is left alone.
83
+ */
84
+ readonly sweepEveryMs?: number | undefined;
85
+ /** How many uploads one bucket may have in progress. `MAX_UPLOADS_PER_BUCKET` unless said. */
86
+ readonly maxUploadsPerBucket?: number | undefined;
9
87
  }
10
- export declare function createStaging(root: string, store: StoreFile): Staging;
88
+ export declare function createStagingStore(root: string, options?: StagingOptions): StagingStore;
89
+ /**
90
+ * A staging for one bucket whose account never changes, storing through `store`: what a caller that
91
+ * builds its drive once needs, and nothing more.
92
+ */
93
+ export declare function createStaging(root: string, store: StoreFile, clock?: () => number): Staging;