@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,258 @@
1
+ // How a drive is changed through the gateway: a file stored at a key, a folder made by its marker,
2
+ // what is at a set of keys sent to the trash. `drive.ts` builds one of these for every drive that
3
+ // may be written.
4
+ //
5
+ // ⛔ EVERY DECISION IS TAKEN INSIDE THE KEY'S LOCK, ON A LIST READ THERE (`drive-lock.ts`). Whether
6
+ // the key is free, whether a condition holds, whether the bytes are the ones already stored —
7
+ // each is a fact about the list at one moment, and a list cached for seconds, or read before
8
+ // another write to the same key finished, answers them for a moment that has passed.
9
+ //
10
+ // ⛔ THE TAG ANSWERED IS THE TAG OF THE FILE THIS REQUEST STORED, found by the id the store
11
+ // returned. "Whatever is at the key afterwards" was somebody else's file whenever another write
12
+ // landed in between — and a client that holds a tag which never belonged to its own upload
13
+ // compares every later listing against the wrong thing.
14
+ import { mkdir as makeDir, rm as removeFile, stat } from "node:fs/promises";
15
+ import { join } from "node:path";
16
+ import { fileSink } from "../download-sink-node.js";
17
+ import { NmtsError } from "../errors.js";
18
+ import { S3Refusal } from "./answer.js";
19
+ import { checkWriteCondition, UNCONDITIONAL } from "./drive-conditions.js";
20
+ import { checkKey, sameKey } from "./drive-key.js";
21
+ import { checkDeclaredSize, checkNotEmpty, tooLarge } from "./drive-limits.js";
22
+ import { trashedHolders } from "./drive-trashed-name.js";
23
+ import { EMPTY_ETAG, isFolderKey, objectsOf } from "./listing.js";
24
+ import { spoolFileName } from "./multipart-sweep.js";
25
+ import { KeyConflict, refusalFor, verdictFor } from "./same-file.js";
26
+ import { readBodyText, spoolBody } from "./spool.js";
27
+ /** `photos/2026/a.jpg` → the folder to make and the name to store under. */
28
+ export function placeOf(key) {
29
+ const at = key.lastIndexOf("/");
30
+ if (at < 0)
31
+ return { folder: undefined, name: key };
32
+ const folder = key.slice(0, at);
33
+ return { folder: folder === "" ? undefined : folder, name: key.slice(at + 1) };
34
+ }
35
+ /**
36
+ * Refuse a key that a folder, or a file above it, already stands in the way of.
37
+ *
38
+ * ⛔ A FILE AND A FOLDER CANNOT SHARE A PATH, and the upload path, handed one that did, stored the
39
+ * file as `photos (2)` — a 500 for a key that still held nothing, and another stored copy on
40
+ * every retry. That is a conflict about the key, so it is a 409.
41
+ */
42
+ function refuseClash(objects, key) {
43
+ const byKey = new Map(objects.map((o) => [sameKey(o.key), o]));
44
+ const path = isFolderKey(key) ? key.slice(0, -1) : key;
45
+ if (!isFolderKey(key) && byKey.has(sameKey(`${key}/`))) {
46
+ throw new KeyConflict(`A folder is already at ${key}, so no file can be stored at that key.`);
47
+ }
48
+ const names = path.split("/");
49
+ for (let depth = isFolderKey(key) ? names.length : names.length - 1; depth > 0; depth -= 1) {
50
+ const above = names.slice(0, depth).join("/");
51
+ const standing = byKey.get(sameKey(above));
52
+ if (standing !== undefined && !isFolderKey(standing.key)) {
53
+ throw new KeyConflict(`A file is already at ${above}, so nothing can be stored inside it.`);
54
+ }
55
+ }
56
+ }
57
+ /**
58
+ * Refuse, on the list as it is cached, a write whose answer is already known: a folder in the way,
59
+ * or a condition that does not hold. The protocol layer asks this before reading a body, so a
60
+ * refusal it can know keeps its own status and costs nobody an upload; the writer asks again,
61
+ * inside the key's lock, and that answer is the one that decides.
62
+ */
63
+ export function precheck(objects, key, condition) {
64
+ refuseClash(objects, key);
65
+ const folder = isFolderKey(key);
66
+ checkWriteCondition(objects.find((o) => isFolderKey(o.key) === folder && sameKey(o.key) === sameKey(key)), condition);
67
+ }
68
+ /** The id `store` answered with, when it answered one. */
69
+ function storedId(stored) {
70
+ if (typeof stored !== "object" || stored === null)
71
+ return null;
72
+ const id = Reflect.get(stored, "id");
73
+ return typeof id === "string" && id !== "" ? id : null;
74
+ }
75
+ export function createWriter(setup) {
76
+ const { account, locks, overwrite } = setup;
77
+ const max = setup.maxObjectBytes;
78
+ const lockName = (key) => `${setup.bucket}\u0000${sameKey(key)}`;
79
+ const fresh = async () => objectsOf(await setup.entries({ fresh: true }));
80
+ /**
81
+ * Store one local file at a drive key, making the folders above it if they are missing.
82
+ *
83
+ * ⭐ IDENTICAL CONTENT IS NOT AN ERROR. Nothing is sent and nothing is charged, and the caller is
84
+ * told the upload finished — because the statement it was making, "that file is at that key",
85
+ * is true. Answering 409 there is what made every backup run fail on every file it had already
86
+ * stored, and a sync tool writes 409 down as a failure.
87
+ *
88
+ * ⛔ UNDER `replace`, EVERY STORE ASKS FOR THE OVERWRITE RULE, not only the ones this list says
89
+ * are taken: another device can put a file at the key between this read and the store, and the
90
+ * rename rule would then store this one beside it as `name (2)`.
91
+ */
92
+ const storeFile = (key, path, meta, condition = UNCONDITIONAL) => locks.run([lockName(key)], async () => {
93
+ checkKey(key);
94
+ const { folder, name } = placeOf(key);
95
+ const known = await setup.entries({ fresh: true });
96
+ const objects = objectsOf(known);
97
+ refuseClash(objects, key);
98
+ const standing = objects.find((o) => !isFolderKey(o.key) && sameKey(o.key) === sameKey(key));
99
+ checkWriteCondition(standing, condition);
100
+ const size = (await stat(path)).size;
101
+ checkNotEmpty(size);
102
+ if (max !== undefined && size > max)
103
+ throw tooLarge(max);
104
+ if (standing !== undefined) {
105
+ if (standing.key !== key) {
106
+ if (overwrite !== "replace")
107
+ throw refusalFor("spelling", key, standing.key);
108
+ }
109
+ else {
110
+ const verdict = await account.withCode((code) => verdictFor(standing, code, path));
111
+ if (verdict === "same") {
112
+ setup.onAlreadyStored?.(key);
113
+ return { etag: standing.etag, outcome: "unchanged" };
114
+ }
115
+ if (overwrite !== "replace")
116
+ throw refusalFor(verdict === "free" ? "differs" : verdict, key);
117
+ }
118
+ }
119
+ if (folder !== undefined)
120
+ await account.makeFolder(folder);
121
+ // ⛔ A NAME ONLY THE TRASH HOLDS IS FREE TO S3, so the trashed holder moves aside first
122
+ // (`drive-trashed-name.ts`) — otherwise the upload path numbers this file instead.
123
+ if (account.freeTrashedName !== undefined && trashedHolders(known, folder, name).length > 0) {
124
+ await account.freeTrashedName(folder, name);
125
+ }
126
+ const stored = await account.store(path, name, folder, { replace: overwrite === "replace", meta });
127
+ setup.forget();
128
+ const after = await fresh();
129
+ const id = storedId(stored);
130
+ const mine = id === null ? after.find((o) => o.key === key) : after.find((o) => o.entry.id === id);
131
+ if (mine === undefined) {
132
+ throw new NmtsError(`The file was stored, but the file list does not show it at ${key}.`);
133
+ }
134
+ if (mine.key !== key) {
135
+ throw new KeyConflict(`Something else was stored at ${key} while this upload was, so this one was stored as ${mine.key}.`);
136
+ }
137
+ return { etag: mine.etag, outcome: standing === undefined ? "stored" : "replaced" };
138
+ });
139
+ /** A zero-byte PUT to `photos/`: the folder, made if it is missing, and the empty object's tag. */
140
+ const makeMarker = (key, condition) => locks.run([lockName(key)], async () => {
141
+ const objects = await fresh();
142
+ refuseClash(objects, key);
143
+ const standing = objects.find((o) => isFolderKey(o.key) && sameKey(o.key) === sameKey(key));
144
+ checkWriteCondition(standing, condition);
145
+ if (standing !== undefined)
146
+ return { etag: EMPTY_ETAG, outcome: "unchanged" };
147
+ await account.makeFolder(key.slice(0, -1));
148
+ setup.forget();
149
+ return { etag: EMPTY_ETAG, outcome: "stored" };
150
+ });
151
+ /** A fresh 0600 file under the staging root, removed whatever `use` does. */
152
+ const withSpool = async (use) => {
153
+ await makeDir(setup.stagingRoot, { recursive: true, mode: 0o700 });
154
+ const spool = join(setup.stagingRoot, spoolFileName());
155
+ try {
156
+ return await use(spool);
157
+ }
158
+ finally {
159
+ await removeFile(spool, { force: true });
160
+ }
161
+ };
162
+ const remove = (keys, condition = UNCONDITIONAL) => locks.run(keys.map(lockName), async () => {
163
+ const objects = await fresh();
164
+ const outcomes = keys.map((key) => ({ key, error: null }));
165
+ const going = [];
166
+ const seen = new Set();
167
+ keys.forEach((key, at) => {
168
+ const object = objects.find((o) => o.key === key) ?? objects.find((o) => sameKey(o.key) === sameKey(key));
169
+ try {
170
+ checkWriteCondition(object, condition);
171
+ }
172
+ catch (error) {
173
+ outcomes[at] = { key, error };
174
+ return;
175
+ }
176
+ // Not there, or named twice: gone either way, which is what S3 answers.
177
+ if (object === undefined || seen.has(object.key))
178
+ return;
179
+ seen.add(object.key);
180
+ // ⛔ A FOLDER MARKER NAMES THE FOLDER, NOT WHAT IS IN IT. Deleting `photos/` while files are
181
+ // under it would trash every one of them; in S3 it removes an empty object and leaves the
182
+ // files. So a folder goes to the trash only once nothing live is left inside it.
183
+ if (isFolderKey(object.key) && objects.some((o) => o.key !== object.key && o.key.startsWith(object.key)))
184
+ return;
185
+ going.push({ at, key, path: `/${isFolderKey(object.key) ? object.key.slice(0, -1) : object.key}` });
186
+ });
187
+ let failed = going;
188
+ if (going.length > 1 && account.trashMany !== undefined) {
189
+ try {
190
+ await account.trashMany(going.map((g) => g.path));
191
+ failed = [];
192
+ }
193
+ catch {
194
+ // One key the batch could not take refuses the whole write; each is tried on its own.
195
+ }
196
+ }
197
+ const errors = new Map();
198
+ for (const one of failed) {
199
+ try {
200
+ await account.trash(one.path);
201
+ }
202
+ catch (error) {
203
+ errors.set(one.at, error);
204
+ }
205
+ }
206
+ setup.forget();
207
+ if (errors.size > 0) {
208
+ // ⛔ A KEY ALREADY GONE IS DELETED, whoever sent it to the trash first.
209
+ const now = await fresh();
210
+ for (const [at, error] of errors) {
211
+ const key = keys[at] ?? "";
212
+ if (now.some((o) => o.key === key))
213
+ outcomes[at] = { key, error };
214
+ }
215
+ }
216
+ return outcomes;
217
+ });
218
+ return {
219
+ put: async (key, body, meta, condition = UNCONDITIONAL) => {
220
+ checkKey(key);
221
+ if (isFolderKey(key)) {
222
+ if (body.size !== 0) {
223
+ throw new S3Refusal(400, "InvalidArgument", "A key ending in `/` names a folder, and a folder holds no bytes of its own. Nothing was stored.");
224
+ }
225
+ await readBodyText(body, 0, "A folder marker");
226
+ return await makeMarker(key, condition);
227
+ }
228
+ checkNotEmpty(body.size);
229
+ checkDeclaredSize(body.size, max);
230
+ // ⛔ THE BODY IS SPOOLED TO A FILE FIRST, 0600, and deleted whatever happens. The upload
231
+ // path reserves storage, cuts parts and seals them from a file; ⛔ `spoolBody` returns
232
+ // only once the body's own rules held, so nothing reaches `storeFile` before that.
233
+ return await withSpool(async (spool) => {
234
+ await spoolBody(body, spool, { md5: false, limit: max });
235
+ return await storeFile(key, spool, meta, condition);
236
+ });
237
+ },
238
+ // ⚠ A COPY IS A DOWNLOAD AND AN UPLOAD. The bytes are sealed under the source file's own key,
239
+ // which the destination does not hold, so there is nothing to copy but the plaintext —
240
+ // fetched into a spool, checked against its recorded hash on the way, and stored like any
241
+ // other upload, same-file rule and all.
242
+ copy: async (from, key, meta, condition = UNCONDITIONAL) => {
243
+ checkKey(key);
244
+ if (isFolderKey(key)) {
245
+ throw new S3Refusal(400, "InvalidArgument", "A copy cannot be stored at a key ending in `/`, which names a folder.");
246
+ }
247
+ checkNotEmpty(from.object.size);
248
+ checkDeclaredSize(from.object.size, max);
249
+ return await withSpool(async (spool) => {
250
+ await from.source.fetch(from.object, fileSink(spool, { force: false }));
251
+ return await storeFile(key, spool, meta, condition);
252
+ });
253
+ },
254
+ remove,
255
+ multipart: setup.staging.view(setup.bucket, { store: storeFile, owner: setup.owner, maxObjectBytes: max }),
256
+ maxObjectBytes: max,
257
+ };
258
+ }
@@ -2,9 +2,11 @@ import type { PlaintextSink } from "../download-sink.ts";
2
2
  import type { Network } from "../network.ts";
3
3
  import type { ManifestEntry } from "../shared/lib/drive/manifest-codec.ts";
4
4
  import type { ReadOptions } from "../walrus.ts";
5
+ import type { DriveSource, WriteMeta } from "./contract.ts";
6
+ import { type KeyLocks } from "./drive-lock.ts";
5
7
  import type { DriveObject } from "./listing.ts";
6
- import type { DriveSource } from "./server.ts";
7
- import { type Staging } from "./staging.ts";
8
+ import { type StagingStore } from "./staging.ts";
9
+ export { placeOf } from "./drive-write.ts";
8
10
  /**
9
11
  * How long a file list may be reused before it is fetched again.
10
12
  *
@@ -12,16 +14,20 @@ import { type Staging } from "./staging.ts";
12
14
  * mean a server round trip and a decryption for each one, so a listing of a large drive would
13
15
  * take minutes and cost the account's rate budget. ⚠ It also means a file uploaded from another
14
16
  * device can be up to this long in appearing here, which is the trade and is written in the
15
- * tool's own words when it starts.
17
+ * tool's own words when it starts. Every write reads the list fresh, past this cache.
16
18
  */
17
19
  export declare const LIST_CACHE_MS = 5000;
20
+ /** What `store` may answer: the id of the file it stored, so the tag answered is that file's. */
21
+ export interface StoredFile {
22
+ readonly id?: string | undefined;
23
+ }
18
24
  /**
19
25
  * Where a drive comes from, for whoever is running the gateway.
20
26
  *
21
- * ⛔ SIX FUNCTIONS AND NO CREDENTIAL. The command-line tool holds an open session; the SDK holds a
22
- * client whose key may be in a business's sealed store and is borrowed one call at a time.
23
- * Nothing in this file may care which, so nothing in this file is handed a key -- `withCode`
24
- * borrows one for the length of a comparison and the caller decides what that costs.
27
+ * ⛔ A HANDFUL OF FUNCTIONS AND NO CREDENTIAL. The command-line tool holds an open session; the SDK
28
+ * holds a client whose key may be in a business's sealed store and is borrowed one call at a
29
+ * time. Nothing in this file may care which, so nothing in this file is handed a key --
30
+ * `withCode` borrows one for the length of a comparison and the caller decides what that costs.
25
31
  */
26
32
  export interface DriveAccount {
27
33
  /** The account's file list, read fresh from the server. Empty for an account that has none. */
@@ -35,17 +41,34 @@ export interface DriveAccount {
35
41
  withCode<T>(use: (code: string) => Promise<T>): Promise<T>;
36
42
  /** Make this folder path, and any folder above it that is missing. */
37
43
  makeFolder(path: string): Promise<void>;
38
- /** Store one local file under `name`, in `folder` — the top of the account when undefined. */
39
- store(local: string, name: string, folder: string | undefined): Promise<void>;
44
+ /**
45
+ * Store one local file under `name`, in `folder` — the top of the account when undefined — and
46
+ * answer the stored file's id when it can (see `StoredFile`).
47
+ *
48
+ * `how.replace` true: a file already at that name goes to the trash (the upload path's
49
+ * "overwrite" rule). False: the upload path's "rename" rule. `how.meta` is what the client sent.
50
+ */
51
+ store(local: string, name: string, folder: string | undefined, how: {
52
+ readonly replace: boolean;
53
+ readonly meta: WriteMeta;
54
+ }): Promise<StoredFile | void>;
40
55
  /** Send one path — with its leading slash — to the trash, where it stays for thirty days. */
41
56
  trash(path: string): Promise<void>;
57
+ /** Send several paths to the trash in one write to the file list. Absent: one `trash` each. */
58
+ trashMany?(paths: readonly string[]): Promise<void>;
59
+ /**
60
+ * Rename, inside the trash, whatever there holds `name` in `folder`, so a new file can take the
61
+ * name (`drive-trashed-name.ts`). Absent: the upload path numbers the new file instead, and the
62
+ * gateway answers that it landed under another name.
63
+ */
64
+ freeTrashedName?(folder: string | undefined, name: string): Promise<void>;
42
65
  /** Fetch, decrypt and deliver one file into the sink. `fetchObject` below is how both do it. */
43
66
  fetch(object: DriveObject, sink: PlaintextSink): Promise<void>;
44
67
  }
45
68
  export interface DriveSourceOptions {
46
69
  readonly account: DriveAccount;
47
70
  /**
48
- * Where the pieces of a multipart upload wait until they are one file.
71
+ * Where the pieces of a multipart upload, and each upload's body, wait until they are stored.
49
72
  *
50
73
  * ⛔ 0700, AND MADE WHEN IT IS FIRST NEEDED. Pieces are somebody's plaintext; leaving them in a
51
74
  * shared temporary directory under a predictable name would put them where any other account
@@ -58,15 +81,36 @@ export interface DriveSourceOptions {
58
81
  */
59
82
  readonly writable: boolean;
60
83
  /**
61
- * The staging an earlier source for the same bucket was using, when there was one.
84
+ * The gateway's multipart staging, shared by every drive it builds. Absent: one of this drive's
85
+ * own, under `stagingRoot`.
62
86
  *
63
- * ⛔ AN UPLOAD IN PIECES OUTLIVES THE SOURCE IT BEGAN UNDER. A caller that rebuilds its sources —
64
- * a gateway re-asking whose bucket this is — would otherwise hand the next piece to a staging
65
- * that has never heard of the upload, and a large file could never finish.
87
+ * ⛔ SHARED, NOT CARRIED. An upload in pieces outlives the drive it began under — a gateway
88
+ * re-asking whose a bucket is builds a new one — and the staging is where it lives meanwhile.
89
+ * What finishes it is the drive the bucket has when the finish arrives (`staging.ts`).
90
+ */
91
+ readonly staging?: StagingStore | undefined;
92
+ /** The bucket this drive answers to, which is what an upload in the shared staging is filed under. */
93
+ readonly bucket?: string | undefined;
94
+ /**
95
+ * Which account this drive is — its id. An upload begun under another account is not this
96
+ * drive's to finish. Absent: the account behind the bucket never changes.
66
97
  */
67
- readonly multipart?: Staging | undefined;
98
+ readonly owner?: (() => Promise<string>) | undefined;
99
+ /** The gateway's per-key locks, shared by every drive it builds. Absent: this drive's own. */
100
+ readonly locks?: KeyLocks | undefined;
101
+ /** The most bytes one object may have. Absent: no limit but the upload path's own. */
102
+ readonly maxObjectBytes?: number | undefined;
68
103
  /** How long a file list may be reused. `LIST_CACHE_MS` unless a caller has a reason. */
69
104
  readonly listCacheMs?: number | undefined;
105
+ /**
106
+ * What a write onto a key holding DIFFERENT bytes does. `refuse` unless a caller says otherwise.
107
+ *
108
+ * `refuse` answers 409 and stores nothing: the drive keeps what it has, and a person deletes it
109
+ * first if they mean to replace it. `replace` stores the new bytes and sends the old file to the
110
+ * trash, where it stays recoverable for thirty days — which is what every S3 client expects a PUT
111
+ * to do. Identical bytes are `unchanged` either way, and nothing is sent.
112
+ */
113
+ readonly overwrite?: "replace" | "refuse" | undefined;
70
114
  /**
71
115
  * Told the key when it already held exactly these bytes, so nothing was sent.
72
116
  *
@@ -92,16 +136,6 @@ export interface ObjectReader {
92
136
  /** Hosts to read stored bytes from, instead of the network's own aggregators. */
93
137
  readonly read?: ReadOptions | undefined;
94
138
  }
95
- /**
96
- * `photos/2026/a.jpg` → the folder to make and the name to store under.
97
- *
98
- * A key with no slash lands at the top of the account, which is `undefined` rather than `""`: the
99
- * two mean the same thing to a person and different things to the upload path.
100
- */
101
- export declare function placeOf(key: string): {
102
- folder: string | undefined;
103
- name: string;
104
- };
105
139
  /** The real reader: the stored bytes, opened with this account's key and delivered to the sink. */
106
140
  export declare function fetchObject(reader: ObjectReader, object: DriveObject, sink: PlaintextSink): Promise<void>;
107
141
  /** One account as the protocol layer sees it: a cached list, a reader, and a writer when allowed. */
package/dist/s3/drive.js CHANGED
@@ -3,24 +3,23 @@
3
3
  // ⛔ ONE IMPLEMENTATION, TWO CALLERS, WHICH IS THE WHOLE REASON THIS FILE EXISTS. `nmts s3` serves
4
4
  // the drive of whoever is at this machine; the SDK's gateway serves whichever account a
5
5
  // business's resolver hands back. What the two do with an upload -- spool it, ask whether the
6
- // key already holds exactly these bytes, make the folders above it, store it, forget the cached
7
- // list -- is the same work, and a second copy of it would be a second place for the same-file
6
+ // key already holds exactly these bytes, make the folders above it, store it (replacing what is
7
+ // there, or refusing to), read the list again for the tag of what was stored -- is the same
8
+ // work (`drive-write.ts`), and a second copy of it would be a second place for the same-file
8
9
  // rule to be got right. The two differ only in where the account comes from, which is the seam
9
10
  // below.
10
11
  //
11
- // ⛔ THE SAME-FILE QUESTION IS ANSWERED HERE AND NOWHERE ELSE. Both ways of uploading -- one PUT,
12
- // or pieces staged and joined -- end in `storeFile`, so a rule written here cannot disagree with
12
+ // ⛔ THE SAME-FILE QUESTION IS ANSWERED IN ONE PLACE. Both ways of uploading -- one PUT, or pieces
13
+ // staged and joined -- end in the same store, so a rule written there cannot disagree with
13
14
  // itself; written in the protocol layer it would have to be written twice, once for each, and
14
15
  // the two would differ the first time one of them changed.
15
- import { randomUUID } from "node:crypto";
16
- import { createWriteStream } from "node:fs";
17
- import { mkdir as makeDir, rm as removeFile, stat } from "node:fs/promises";
18
- import { join } from "node:path";
19
- import { pipeline } from "node:stream/promises";
20
16
  import { fetchFile } from "../download.js";
17
+ import { KIND_FOLDER } from "../drive-paths.js";
21
18
  import { NmtsError } from "../errors.js";
22
- import { refusalFor, verdictForKey } from "./same-file.js";
23
- import { createStaging } from "./staging.js";
19
+ import { createKeyLocks } from "./drive-lock.js";
20
+ import { createWriter } from "./drive-write.js";
21
+ import { createStagingStore } from "./staging.js";
22
+ export { placeOf } from "./drive-write.js";
24
23
  /**
25
24
  * How long a file list may be reused before it is fetched again.
26
25
  *
@@ -28,22 +27,9 @@ import { createStaging } from "./staging.js";
28
27
  * mean a server round trip and a decryption for each one, so a listing of a large drive would
29
28
  * take minutes and cost the account's rate budget. ⚠ It also means a file uploaded from another
30
29
  * device can be up to this long in appearing here, which is the trade and is written in the
31
- * tool's own words when it starts.
30
+ * tool's own words when it starts. Every write reads the list fresh, past this cache.
32
31
  */
33
32
  export const LIST_CACHE_MS = 5_000;
34
- /**
35
- * `photos/2026/a.jpg` → the folder to make and the name to store under.
36
- *
37
- * A key with no slash lands at the top of the account, which is `undefined` rather than `""`: the
38
- * two mean the same thing to a person and different things to the upload path.
39
- */
40
- export function placeOf(key) {
41
- const at = key.lastIndexOf("/");
42
- if (at < 0)
43
- return { folder: undefined, name: key };
44
- const folder = key.slice(0, at);
45
- return { folder: folder === "" ? undefined : folder, name: key.slice(at + 1) };
46
- }
47
33
  /** The real reader: the stored bytes, opened with this account's key and delivered to the sink. */
48
34
  export async function fetchObject(reader, object, sink) {
49
35
  const wrapped = object.entry.dekWrapped;
@@ -62,74 +48,57 @@ export async function fetchObject(reader, object, sink) {
62
48
  ...(reader.read === undefined ? {} : { read: reader.read }),
63
49
  });
64
50
  }
51
+ /** A folder marker's bytes: none. Nothing is fetched, because a folder has nothing stored. */
52
+ async function deliverNothing(sink) {
53
+ sink.expect(0);
54
+ await sink.commit();
55
+ }
65
56
  /** One account as the protocol layer sees it: a cached list, a reader, and a writer when allowed. */
66
57
  export function createDriveSource(options) {
67
58
  const account = options.account;
68
59
  const cacheMs = options.listCacheMs ?? LIST_CACHE_MS;
69
60
  let cached = [];
70
61
  let cachedAt = 0;
71
- const entries = async () => {
72
- if (Date.now() - cachedAt < cacheMs)
62
+ const entries = async (asked) => {
63
+ if (asked?.fresh !== true && Date.now() - cachedAt < cacheMs)
73
64
  return cached;
74
- cached = await account.readList();
65
+ const read = await account.readList();
66
+ cached = read;
75
67
  cachedAt = Date.now();
76
- return cached;
68
+ return read;
77
69
  };
78
- /**
79
- * Store one local file at a drive key, making the folders above it if they are missing.
80
- *
81
- * ⭐ IDENTICAL CONTENT IS NOT AN ERROR. Nothing is sent and nothing is charged, and the caller is
82
- * told the upload finished — because the statement it was making, "that file is at that key",
83
- * is true. Answering 409 there is what made every backup run fail on every file it had already
84
- * stored, and a sync tool writes 409 down as a failure.
85
- */
86
- const storeFile = async (key, path) => {
87
- const { folder, name } = placeOf(key);
88
- const known = await entries();
89
- const verdict = await account.withCode((code) => verdictForKey(known, key, code, path));
90
- if (verdict === "same") {
91
- options.onAlreadyStored?.(key);
92
- return;
93
- }
94
- if (verdict !== "free")
95
- throw refusalFor(verdict, key);
96
- if (folder !== undefined)
97
- await account.makeFolder(folder);
98
- await account.store(path, name, folder);
99
- cachedAt = 0;
70
+ // ⚠ ASKED ONCE PER DRIVE, and asked again after a failure rather than remembering it.
71
+ const ownerOf = options.owner;
72
+ let owner = null;
73
+ const ownerNow = () => {
74
+ if (ownerOf === undefined)
75
+ return Promise.resolve(null);
76
+ owner ??= ownerOf().catch((error) => {
77
+ owner = null;
78
+ throw error;
79
+ });
80
+ return owner;
100
81
  };
101
82
  return {
102
83
  entries,
103
- fetch: (object, sink) => account.fetch(object, sink),
84
+ fetch: (object, sink) => (object.entry.kind === KIND_FOLDER ? deliverNothing(sink) : account.fetch(object, sink)),
104
85
  ...(options.writable
105
86
  ? {
106
- write: {
107
- // ⛔ THE BODY IS SPOOLED TO A FILE FIRST, 0600, and deleted whatever happens. The
108
- // upload path reserves storage, cuts parts and seals them from a file, and giving it
109
- // a socket instead would mean either holding whole uploads in memory or writing a
110
- // second upload path — and a second upload path is a second place for "what if the
111
- // reservation succeeds and the part fails" to be got right.
112
- put: async (key, body, size) => {
113
- await makeDir(options.stagingRoot, { recursive: true, mode: 0o700 });
114
- const spool = join(options.stagingRoot, randomUUID());
115
- try {
116
- await pipeline(body, createWriteStream(spool, { mode: 0o600 }));
117
- const written = (await stat(spool)).size;
118
- if (written !== size) {
119
- throw new NmtsError(`The upload said ${size} bytes and ${written} arrived. Nothing was stored.`);
120
- }
121
- await storeFile(key, spool);
122
- }
123
- finally {
124
- await removeFile(spool, { force: true });
125
- }
126
- },
127
- multipart: options.multipart ?? createStaging(options.stagingRoot, storeFile),
128
- trash: async (object) => {
129
- await account.trash(`/${object.key}`);
87
+ write: createWriter({
88
+ account,
89
+ entries,
90
+ forget: () => {
130
91
  cachedAt = 0;
131
92
  },
132
- },
93
+ stagingRoot: options.stagingRoot,
94
+ staging: options.staging ?? createStagingStore(options.stagingRoot),
95
+ bucket: options.bucket ?? "",
96
+ owner: ownerNow,
97
+ locks: options.locks ?? createKeyLocks(),
98
+ overwrite: options.overwrite ?? "refuse",
99
+ maxObjectBytes: options.maxObjectBytes,
100
+ onAlreadyStored: options.onAlreadyStored,
101
+ }),
133
102
  }
134
103
  : {}),
135
104
  };
@@ -32,6 +32,12 @@ export interface ListQuery {
32
32
  /**
33
33
  * An ETag that is stable for a file and changes when the file does.
34
34
  *
35
+ * ⛔ IT IS A HASH OF WHAT CHANGES WHEN THE FILE DOES: the entry's id, its time and its size. A file
36
+ * replaced at the same key is a new entry; one edited in place has a new time. The tag used to
37
+ * be the id and the time laid side by side and cut to 32 characters, which for a long id cut the
38
+ * time off altogether — and a tag that does not change when the file does is how a sync tool
39
+ * decides there is nothing to fetch.
40
+ *
35
41
  * ⛔ IT ENDS IN `-1` FOR A REASON. S3 clients treat an ETag that looks like a hex digest as the
36
42
  * MD5 of the object and check downloads against it; this drive has no MD5 of anything -- the
37
43
  * bytes are encrypted before they leave the machine and the digest it does keep is a different
@@ -40,7 +46,27 @@ export interface ListQuery {
40
46
  * reported as corrupt.
41
47
  */
42
48
  export declare function etagOf(entry: ManifestEntry): string;
43
- /** Every live file in the account, as keys, in the order S3 promises: ascending by key. */
49
+ /** The tag of an object with no bytes: the MD5 of nothing, which is what S3 answers for one. */
50
+ export declare const EMPTY_ETAG = "\"d41d8cd98f00b204e9800998ecf8427e\"";
51
+ /**
52
+ * Two keys in the order S3 lists them, which is the order of their UTF-8 bytes.
53
+ *
54
+ * ⛔ NOT `<`. JavaScript compares UTF-16 code units, and those put a character above U+FFFF (most
55
+ * emoji) BEFORE one in U+E000–U+FFFF, where UTF-8 puts it after. A client that pages through a
56
+ * listing resumes after the last key it saw, so a listing in the other order skips keys or
57
+ * repeats them.
58
+ */
59
+ export declare function compareKeys(a: string, b: string): number;
60
+ /** True for the key of a folder marker: it ends in `/`. */
61
+ export declare function isFolderKey(key: string): boolean;
62
+ /**
63
+ * Every live file in the account, and every live folder as its marker, as keys, in the order S3
64
+ * promises: ascending by key.
65
+ *
66
+ * ⚠ A MARKER'S ENTRY IS THE FOLDER'S, WITH AN EMPTY `dekWrapped`. A folder has no key to open, and
67
+ * the reader refuses an entry with none; the empty string says "nothing to open", and the drive's
68
+ * own `fetch` answers a folder with no bytes before anything would try.
69
+ */
44
70
  export declare function objectsOf(entries: readonly ManifestEntry[]): DriveObject[];
45
71
  /** Every live folder, as a key ending in the delimiter — see the note at the top of this file. */
46
72
  export declare function folderPrefixesOf(entries: readonly ManifestEntry[]): string[];