@pithy-sh/storage 0.1.1 → 0.1.3

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 (86) hide show
  1. package/dist/capability.d.ts +43 -0
  2. package/dist/capability.d.ts.map +1 -0
  3. package/dist/capability.js +74 -0
  4. package/dist/config/config.d.ts +25 -0
  5. package/dist/config/config.d.ts.map +1 -0
  6. package/dist/config/config.js +47 -0
  7. package/dist/data/share.d.ts +25 -0
  8. package/dist/data/share.d.ts.map +1 -0
  9. package/dist/data/share.js +26 -0
  10. package/dist/data/storageObject.d.ts +53 -0
  11. package/dist/data/storageObject.d.ts.map +1 -0
  12. package/dist/data/storageObject.js +42 -0
  13. package/dist/data/tables.d.ts +21 -0
  14. package/dist/data/tables.d.ts.map +1 -0
  15. package/dist/data/tables.js +24 -0
  16. package/dist/error/errors.d.ts +58 -0
  17. package/dist/error/errors.d.ts.map +1 -0
  18. package/dist/error/errors.js +87 -0
  19. package/dist/http/guard.d.ts +18 -0
  20. package/dist/http/guard.d.ts.map +1 -0
  21. package/dist/http/guard.js +27 -0
  22. package/dist/http/handlers.d.ts +230 -0
  23. package/dist/http/handlers.d.ts.map +1 -0
  24. package/dist/http/handlers.js +505 -0
  25. package/dist/http/routes.d.ts +68 -0
  26. package/dist/http/routes.d.ts.map +1 -0
  27. package/dist/http/routes.js +133 -0
  28. package/dist/http/schemas.d.ts +72 -0
  29. package/dist/http/schemas.d.ts.map +1 -0
  30. package/dist/http/schemas.js +91 -0
  31. package/dist/http/serve.d.ts +119 -0
  32. package/dist/http/serve.d.ts.map +1 -0
  33. package/dist/http/serve.js +207 -0
  34. package/dist/index.d.ts +21 -0
  35. package/dist/index.d.ts.map +1 -0
  36. package/dist/index.js +12 -0
  37. package/dist/migrations/0001_objects.d.ts +22 -0
  38. package/dist/migrations/0001_objects.d.ts.map +1 -0
  39. package/dist/migrations/0001_objects.js +39 -0
  40. package/dist/object/cloudflare.d.ts +21 -0
  41. package/dist/object/cloudflare.d.ts.map +1 -0
  42. package/dist/object/cloudflare.js +46 -0
  43. package/dist/object/key.d.ts +27 -0
  44. package/dist/object/key.d.ts.map +1 -0
  45. package/dist/object/key.js +35 -0
  46. package/dist/object/multipart.d.ts +76 -0
  47. package/dist/object/multipart.d.ts.map +1 -0
  48. package/dist/object/multipart.js +129 -0
  49. package/dist/object/store.d.ts +201 -0
  50. package/dist/object/store.d.ts.map +1 -0
  51. package/dist/object/store.js +176 -0
  52. package/dist/provision/provisionStorage.d.ts +137 -0
  53. package/dist/provision/provisionStorage.d.ts.map +1 -0
  54. package/dist/provision/provisionStorage.js +110 -0
  55. package/dist/provision/resolveStorageConfig.d.ts +43 -0
  56. package/dist/provision/resolveStorageConfig.d.ts.map +1 -0
  57. package/dist/provision/resolveStorageConfig.js +31 -0
  58. package/dist/quota/quota.d.ts +125 -0
  59. package/dist/quota/quota.d.ts.map +1 -0
  60. package/dist/quota/quota.js +100 -0
  61. package/dist/secret/registry.d.ts +70 -0
  62. package/dist/secret/registry.d.ts.map +1 -0
  63. package/dist/secret/registry.js +82 -0
  64. package/dist/seeds/example.d.ts +3 -0
  65. package/dist/seeds/example.d.ts.map +1 -0
  66. package/dist/seeds/example.js +109 -0
  67. package/dist/test-utils/liveStorage.d.ts +50 -0
  68. package/dist/test-utils/liveStorage.d.ts.map +1 -0
  69. package/dist/test-utils/liveStorage.js +196 -0
  70. package/dist/version.generated.d.ts +5 -0
  71. package/dist/version.generated.d.ts.map +1 -0
  72. package/dist/version.generated.js +7 -0
  73. package/dist/workflows/retryPolicy.d.ts +37 -0
  74. package/dist/workflows/retryPolicy.d.ts.map +1 -0
  75. package/dist/workflows/retryPolicy.js +41 -0
  76. package/dist/workflows/specs.d.ts +55 -0
  77. package/dist/workflows/specs.d.ts.map +1 -0
  78. package/dist/workflows/specs.js +58 -0
  79. package/dist/workflows/sweep.d.ts +82 -0
  80. package/dist/workflows/sweep.d.ts.map +1 -0
  81. package/dist/workflows/sweep.js +143 -0
  82. package/dist/workflows/worker.d.ts +49 -0
  83. package/dist/workflows/worker.d.ts.map +1 -0
  84. package/dist/workflows/worker.js +50 -0
  85. package/package.json +22 -11
  86. package/src/version.generated.ts +1 -1
@@ -0,0 +1,505 @@
1
+ import { StorageObject } from "../data/storageObject.js";
2
+ import { StorageForbiddenError, StorageNotFoundError, StorageShareExpiredError, StorageShareRevokedError, StorageUploadIncompleteError } from "../error/errors.js";
3
+ import { collectParts, needsMultipart, planMultipart } from "../object/multipart.js";
4
+ import { StorageShare } from "../data/share.js";
5
+ import { STORAGE_OBJECTS_TABLE, STORAGE_SHARES_TABLE } from "../data/tables.js";
6
+ import { deriveObjectKey } from "../object/key.js";
7
+ import { assertWithinQuota, insertReservingQuota, updateSettlingQuota } from "../quota/quota.js";
8
+ //#region src/http/handlers.ts
9
+ /** Drop the server-only fields. The single place a row becomes something a client may see. */
10
+ function view(object) {
11
+ return {
12
+ id: object.id,
13
+ path: object.path,
14
+ ownerId: object.ownerId,
15
+ contentType: object.contentType,
16
+ size: object.size,
17
+ visibility: object.visibility,
18
+ checksum: object.checksum,
19
+ status: object.status,
20
+ createdAt: object.createdAt,
21
+ updatedAt: object.updatedAt
22
+ };
23
+ }
24
+ /** Load one row, decoded through the schema. Null when absent. */
25
+ async function findObject(deps, id) {
26
+ const row = await deps.db.selectFrom(STORAGE_OBJECTS_TABLE).selectAll().where("id", "=", id).executeTakeFirst();
27
+ return row ? StorageObject.parse(row) : null;
28
+ }
29
+ /** Load one row or throw `storage/not_found`. */
30
+ async function loadObject(deps, id) {
31
+ const object = await findObject(deps, id);
32
+ if (!object) throw new StorageNotFoundError({ detail: `no storage object ${id}` });
33
+ return object;
34
+ }
35
+ /**
36
+ * Require the caller to own the object. A private object they do not own is reported as **missing**,
37
+ * so the route cannot be used to test whether an id exists. A public object is reported as
38
+ * **forbidden**, because its existence is already public knowledge and "missing" would just be a lie.
39
+ */
40
+ function assertOwner(object, ownerId) {
41
+ if (ownerId !== null && object.ownerId === ownerId) return;
42
+ if (object.visibility === "public") throw new StorageForbiddenError({ detail: `object ${object.id} is owned by ${object.ownerId ?? "the system"}` });
43
+ throw new StorageNotFoundError({ detail: `object ${object.id} is not owned by ${ownerId ?? "an anonymous caller"}` });
44
+ }
45
+ /** Require the caller to be allowed to *read* the object: it is public, or it is theirs. */
46
+ function assertReadable(object, ownerId) {
47
+ if (object.visibility === "public") return;
48
+ if (ownerId !== null && object.ownerId === ownerId) return;
49
+ throw new StorageNotFoundError({ detail: `object ${object.id} is not readable by ${ownerId ?? "an anonymous caller"}` });
50
+ }
51
+ /** Require the object's bytes to actually be there. A `pending` row has a record but no content. */
52
+ function assertStored(object) {
53
+ if (object.status === "stored") return;
54
+ throw new StorageUploadIncompleteError({ detail: `object ${object.id} is ${object.status}, not stored` });
55
+ }
56
+ /** Write a whole row back through the codec — the round-trip rule, so no field bypasses its codec. */
57
+ async function saveObject(deps, object) {
58
+ const record = StorageObject.encode(object);
59
+ await deps.db.updateTable(STORAGE_OBJECTS_TABLE).set(record).where("id", "=", object.id).execute();
60
+ return object;
61
+ }
62
+ /**
63
+ * Start an upload: reserve the row and its quota, then mint the URL(s) the client PUTs to.
64
+ *
65
+ * **The reservation is the insert, and the insert is conditional.** A `pending` row holds its bytes
66
+ * against the owner's quota, so the row has to exist before an upload can proceed — but a check that
67
+ * ran separately from the write would let a burst of concurrent inits each read a used total none of
68
+ * them had yet contributed to. `insertReservingQuota` evaluates the sum inside the write instead, so
69
+ * the tenth concurrent init sees the other nine (`quota/quota.ts`).
70
+ *
71
+ * The pre-check above it is a courtesy: it refuses an obviously oversized upload before an R2
72
+ * multipart upload exists to clean up. When the conditional insert loses the race anyway, that
73
+ * multipart upload is aborted — a refused init leaves R2 holding nothing.
74
+ */
75
+ async function initUpload(deps, input) {
76
+ const now = deps.now();
77
+ await assertWithinQuota({
78
+ db: deps.db,
79
+ ownerId: deps.ownerId,
80
+ limitBytes: deps.config.quota.bytesPerOwner,
81
+ additionalBytes: input.size
82
+ });
83
+ const key = deriveObjectKey();
84
+ const multipart = needsMultipart(input.size, deps.config.multipartThresholdBytes);
85
+ let upload;
86
+ let uploadId = null;
87
+ if (multipart) {
88
+ const plan = planMultipart(input.size, deps.config.partSizeBytes);
89
+ uploadId = await deps.store.initMultipart(key, input.contentType);
90
+ const parts = [];
91
+ for (const part of plan.parts) parts.push({
92
+ partNumber: part.partNumber,
93
+ offset: part.offset,
94
+ length: part.length,
95
+ url: await deps.store.presignPart(key, uploadId, part.partNumber)
96
+ });
97
+ upload = {
98
+ kind: "multipart",
99
+ uploadId,
100
+ partSize: plan.partSize,
101
+ parts
102
+ };
103
+ } else upload = {
104
+ kind: "single",
105
+ url: await deps.store.presignPut(key, input.contentType, input.size)
106
+ };
107
+ const object = {
108
+ id: deps.newId(),
109
+ key,
110
+ path: input.path,
111
+ ownerId: deps.ownerId,
112
+ contentType: input.contentType,
113
+ size: input.size,
114
+ visibility: input.visibility ?? deps.config.defaultVisibility,
115
+ checksum: null,
116
+ status: "pending",
117
+ uploadId,
118
+ createdAt: now,
119
+ updatedAt: now
120
+ };
121
+ try {
122
+ await insertReservingQuota({
123
+ db: deps.db,
124
+ ownerId: deps.ownerId,
125
+ limitBytes: deps.config.quota.bytesPerOwner,
126
+ additionalBytes: input.size,
127
+ record: StorageObject.encode(object)
128
+ });
129
+ } catch (error) {
130
+ if (uploadId) await deps.store.abortMultipart(key, uploadId).catch(() => {});
131
+ throw error;
132
+ }
133
+ return {
134
+ object: view(object),
135
+ upload
136
+ };
137
+ }
138
+ /**
139
+ * Finalize an upload: assemble the parts (for a multipart), then confirm against R2 that the bytes
140
+ * are really there before the row is allowed to claim they are.
141
+ *
142
+ * The `head` is not a formality. Without it a client could complete an upload it never performed and
143
+ * leave a `stored` row pointing at nothing — a 404 from R2 at read time, long after the request that
144
+ * caused it. The size *and the content type* R2 reports win over the declared ones, so the row records
145
+ * what was stored rather than what was promised.
146
+ *
147
+ * **It is also where the quota is settled.** Part URLs carry no signed `Content-Length` — the final
148
+ * part's differs from every other, so pinning one at mint time would mean knowing the total up front
149
+ * and would still leave the last part unconstrained. The declared size therefore buys a *reservation*,
150
+ * not a limit, and an owner who declares 100 MiB can PUT far more across those URLs. Completion is the
151
+ * first and last point where the real byte count is known and the object can still be thrown away, so
152
+ * anything past the reservation is re-asserted against the quota here.
153
+ *
154
+ * **That re-assertion is the write, for the same reason the reservation was.** A check that ran ahead
155
+ * of the `UPDATE` would let two completions racing on one owner both read a total neither had yet
156
+ * contributed to, both pass, and both store — the init race, reproduced at the other end of the
157
+ * lifecycle. `updateSettlingQuota` evaluates the sum inside the update, so the second completion sees
158
+ * the first (`quota/quota.ts`).
159
+ */
160
+ async function completeUpload(deps, id, input) {
161
+ const object = await loadObject(deps, id);
162
+ assertOwner(object, deps.ownerId);
163
+ if (object.status === "stored") return view(object);
164
+ if (object.status !== "pending") throw new StorageUploadIncompleteError({ detail: `object ${id} is ${object.status} and cannot be completed` });
165
+ if (object.uploadId) {
166
+ const expected = planMultipart(object.size ?? 0, deps.config.partSizeBytes).partCount;
167
+ const parts = collectParts(input.parts, expected);
168
+ await deps.store.completeMultipart(object.key, object.uploadId, parts);
169
+ }
170
+ const metadata = await deps.store.head(object.key);
171
+ if (!metadata) throw new StorageUploadIncompleteError({
172
+ message: "No bytes were uploaded for that file.",
173
+ action: "Upload to the URL the init call returned, then complete again.",
174
+ detail: `R2 has no object at ${object.key}`
175
+ });
176
+ const settled = {
177
+ ...object,
178
+ status: "stored",
179
+ size: metadata.size,
180
+ contentType: metadata.contentType ?? object.contentType,
181
+ checksum: input.checksum ?? metadata.checksumSha256 ?? null,
182
+ uploadId: null,
183
+ updatedAt: deps.now()
184
+ };
185
+ const overshoot = metadata.size - (object.size ?? 0);
186
+ if (overshoot <= 0) return view(await saveObject(deps, settled));
187
+ try {
188
+ await updateSettlingQuota({
189
+ db: deps.db,
190
+ ownerId: object.ownerId,
191
+ limitBytes: deps.config.quota.bytesPerOwner,
192
+ additionalBytes: overshoot,
193
+ record: StorageObject.encode(settled)
194
+ });
195
+ } catch (error) {
196
+ await deps.store.delete(object.key).catch(() => {});
197
+ await saveObject(deps, {
198
+ ...object,
199
+ status: "failed",
200
+ uploadId: null,
201
+ updatedAt: deps.now()
202
+ });
203
+ throw error;
204
+ }
205
+ return view(settled);
206
+ }
207
+ /**
208
+ * Abandon an in-flight upload: tell R2 to discard the stored parts, then mark the row `failed`.
209
+ *
210
+ * The row survives rather than being deleted. `failed` rows are excluded from the quota sum, so they
211
+ * hold nothing, and keeping them means an owner can see that an upload was attempted and abandoned
212
+ * instead of the record silently evaporating.
213
+ *
214
+ * **The bytes are R2's problem after this, not the row's.** A single-PUT abort cannot revoke the
215
+ * presigned URL it handed out — nothing can, which is the whole cost of presigning — so a client may
216
+ * still PUT to it for the rest of that URL's hour, after the delete below has run. The row that
217
+ * survives therefore stops *claiming* its key the moment it goes `failed`: the orphan sweep matches
218
+ * only rows that bill for a key, so anything that lands afterwards is collected as an orphan rather
219
+ * than sheltered forever by a row that counts toward no quota (`workflows/sweep.ts`).
220
+ */
221
+ async function abortUpload(deps, id) {
222
+ const object = await loadObject(deps, id);
223
+ assertOwner(object, deps.ownerId);
224
+ if (object.status === "stored") throw new StorageUploadIncompleteError({
225
+ message: "That upload already finished.",
226
+ action: "Delete the file instead.",
227
+ detail: `object ${id} is stored`
228
+ });
229
+ if (object.uploadId) await deps.store.abortMultipart(object.key, object.uploadId);
230
+ await deps.store.delete(object.key);
231
+ return view(await saveObject(deps, {
232
+ ...object,
233
+ status: "failed",
234
+ uploadId: null,
235
+ updatedAt: deps.now()
236
+ }));
237
+ }
238
+ /**
239
+ * Resume a multipart upload: the parts R2 already holds, plus a **freshly presigned** URL for each
240
+ * one still missing.
241
+ *
242
+ * This is what makes multipart resumable at all. `initUpload` presigns every part once, and those
243
+ * URLs lapse an hour later — a 40 GiB upload is 640 of them, and a client that stalls or dies has no
244
+ * way back to the ones it never sent. Re-minting them here is the recovery path, and it is a route
245
+ * rather than a longer TTL because a presigned URL cannot be revoked: minting on demand keeps each
246
+ * one's life short and its issue authorized.
247
+ *
248
+ * Only while the row is `pending`. A `stored` row has no upload left to resume, and a `failed` one had
249
+ * its parts discarded — re-presigning against either would hand out URLs addressing nothing.
250
+ */
251
+ async function listUploadParts(deps, id) {
252
+ const object = await loadObject(deps, id);
253
+ assertOwner(object, deps.ownerId);
254
+ const uploadId = object.uploadId;
255
+ if (object.status !== "pending" || !uploadId) throw new StorageUploadIncompleteError({
256
+ message: "That upload has no parts to resume.",
257
+ action: "Only an in-flight multipart upload can be resumed. Start a new upload.",
258
+ detail: `object ${id} is ${object.status} with uploadId ${uploadId ?? "null"}`
259
+ });
260
+ const plan = planMultipart(object.size ?? 0, deps.config.partSizeBytes);
261
+ const uploaded = await deps.store.listParts(object.key, uploadId);
262
+ const stored = new Set(uploaded.map((part) => part.partNumber));
263
+ const missing = [];
264
+ for (const part of plan.parts) {
265
+ if (stored.has(part.partNumber)) continue;
266
+ missing.push({
267
+ partNumber: part.partNumber,
268
+ offset: part.offset,
269
+ length: part.length,
270
+ url: await deps.store.presignPart(object.key, uploadId, part.partNumber)
271
+ });
272
+ }
273
+ return {
274
+ uploadId,
275
+ partSize: plan.partSize,
276
+ partCount: plan.partCount,
277
+ uploaded,
278
+ missing
279
+ };
280
+ }
281
+ /**
282
+ * Encode a cursor. Keyset, not offset: an `OFFSET` page skips rows a concurrent upload shifted, so a
283
+ * client paging through their files while uploading would miss some. Base64url keeps it opaque, which
284
+ * is the point — the shape is ours to change.
285
+ */
286
+ function encodeCursor(cursor) {
287
+ const json = JSON.stringify(cursor);
288
+ const bytes = new TextEncoder().encode(json);
289
+ const binary = String.fromCharCode(...bytes);
290
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
291
+ }
292
+ /** Decode a cursor, or `null` when it is not one we minted. A bad cursor starts from the beginning. */
293
+ function decodeCursor(value) {
294
+ if (!value) return null;
295
+ try {
296
+ const binary = atob(value.replace(/-/g, "+").replace(/_/g, "/"));
297
+ const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
298
+ const parsed = JSON.parse(new TextDecoder().decode(bytes));
299
+ if (typeof parsed !== "object" || parsed === null) return null;
300
+ const { path, id } = parsed;
301
+ return typeof path === "string" && typeof id === "string" ? {
302
+ path,
303
+ id
304
+ } : null;
305
+ } catch {
306
+ return null;
307
+ }
308
+ }
309
+ /** Default page size — generous enough for a file browser, small enough to stay one index read. */
310
+ const DEFAULT_LIST_LIMIT = 50;
311
+ /**
312
+ * One page of the caller's files, ordered by logical path. Scoped to the authenticated owner: there
313
+ * is no way to list another owner's files, and no parameter that could be made to.
314
+ */
315
+ async function listObjects(deps, query) {
316
+ const limit = query.limit ?? DEFAULT_LIST_LIMIT;
317
+ const after = decodeCursor(query.cursor);
318
+ let statement = deps.db.selectFrom(STORAGE_OBJECTS_TABLE).selectAll().where("ownerId", "=", deps.ownerId).orderBy("path", "asc").orderBy("id", "asc").limit(limit + 1);
319
+ if (query.prefix) {
320
+ const escaped = query.prefix.replace(/[\\%_]/g, (character) => `\\${character}`);
321
+ statement = statement.where("path", "like", `${escaped}%`);
322
+ }
323
+ if (after) statement = statement.where((eb) => eb.or([eb("path", ">", after.path), eb.and([eb("path", "=", after.path), eb("id", ">", after.id)])]));
324
+ const rows = await statement.execute();
325
+ const page = rows.slice(0, limit).map((row) => StorageObject.parse(row));
326
+ const objects = page.map(view);
327
+ if (rows.length <= limit) return { objects };
328
+ const last = page[page.length - 1];
329
+ return last ? {
330
+ objects,
331
+ cursor: encodeCursor({
332
+ path: last.path,
333
+ id: last.id
334
+ })
335
+ } : { objects };
336
+ }
337
+ /** Load an object for reading, enforcing public-or-owner and that its bytes exist. */
338
+ async function readableObject(deps, id) {
339
+ const object = await loadObject(deps, id);
340
+ assertReadable(object, deps.ownerId);
341
+ assertStored(object);
342
+ return object;
343
+ }
344
+ /** How long a direct-download URL stays valid. Short: it is bearer-equivalent and cannot be revoked. */
345
+ const PRESIGNED_URL_TTL_SECONDS = 300;
346
+ /**
347
+ * Mint a presigned GET — the no-Worker-in-the-byte-path escape hatch.
348
+ *
349
+ * Authorization happens **here**, once, and then the URL is on its own: it cannot be revoked, and
350
+ * anyone holding it can read the bytes until it lapses. Five minutes is short enough that a URL
351
+ * pasted into a chat is dead before it is read, and long enough to start a large download.
352
+ */
353
+ async function presignObject(deps, id) {
354
+ const object = await readableObject(deps, id);
355
+ return {
356
+ url: await deps.store.presignGet(object.key, { expiresIn: 300 }),
357
+ expiresInSeconds: 300
358
+ };
359
+ }
360
+ /** Rename a file, change who may read it, or both. The key never moves — only the row changes. */
361
+ async function updateObject(deps, id, input) {
362
+ const object = await loadObject(deps, id);
363
+ assertOwner(object, deps.ownerId);
364
+ return view(await saveObject(deps, {
365
+ ...object,
366
+ path: input.path ?? object.path,
367
+ visibility: input.visibility ?? object.visibility,
368
+ updatedAt: deps.now()
369
+ }));
370
+ }
371
+ /**
372
+ * Copy a file server-side. The bytes are copied by R2 and never enter the Worker; the copy is a new
373
+ * object with its own id, its own key, and its own share links — it is not an alias.
374
+ *
375
+ * Owner-scoped, like every other mutating route: you may copy your own files. Copying a *public* file
376
+ * you do not own is a plausible feature and deliberately not this one — it would let any reader
377
+ * duplicate bytes into their own quota on the owner's storage bill, which is a decision an adopter
378
+ * should make explicitly rather than inherit.
379
+ */
380
+ async function copyObject(deps, id, input) {
381
+ const source = await loadObject(deps, id);
382
+ assertOwner(source, deps.ownerId);
383
+ assertStored(source);
384
+ await assertWithinQuota({
385
+ db: deps.db,
386
+ ownerId: deps.ownerId,
387
+ limitBytes: deps.config.quota.bytesPerOwner,
388
+ additionalBytes: source.size ?? 0
389
+ });
390
+ const key = deriveObjectKey();
391
+ await deps.store.copy(source.key, key);
392
+ const now = deps.now();
393
+ const copy = {
394
+ ...source,
395
+ id: deps.newId(),
396
+ key,
397
+ path: input.path,
398
+ ownerId: deps.ownerId,
399
+ visibility: "private",
400
+ status: "stored",
401
+ uploadId: null,
402
+ createdAt: now,
403
+ updatedAt: now
404
+ };
405
+ try {
406
+ await insertReservingQuota({
407
+ db: deps.db,
408
+ ownerId: deps.ownerId,
409
+ limitBytes: deps.config.quota.bytesPerOwner,
410
+ additionalBytes: source.size ?? 0,
411
+ record: StorageObject.encode(copy)
412
+ });
413
+ } catch (error) {
414
+ await deps.store.delete(key).catch(() => {});
415
+ throw error;
416
+ }
417
+ return view(copy);
418
+ }
419
+ /**
420
+ * Delete a file: the object first, then the row. Every share link pointing at it goes with the row,
421
+ * through the foreign key's `ON DELETE CASCADE` — a share that outlived its object would be a live
422
+ * token for bytes that no longer exist.
423
+ *
424
+ * The object delete is best-effort. An R2 hiccup must not leave a row nobody can remove; the orphan
425
+ * sweep collects an object whose row went first.
426
+ */
427
+ async function deleteObject(deps, id) {
428
+ const object = await loadObject(deps, id);
429
+ assertOwner(object, deps.ownerId);
430
+ if (object.uploadId) await deps.store.abortMultipart(object.key, object.uploadId).catch(() => {});
431
+ await deps.store.delete(object.key).catch(() => {});
432
+ await deps.db.deleteFrom(STORAGE_OBJECTS_TABLE).where("id", "=", id).execute();
433
+ return {
434
+ id,
435
+ deleted: true
436
+ };
437
+ }
438
+ /** Mint a revocable share link for one file. */
439
+ async function createShare(deps, id, input) {
440
+ const object = await loadObject(deps, id);
441
+ assertOwner(object, deps.ownerId);
442
+ assertStored(object);
443
+ const now = deps.now();
444
+ const share = {
445
+ token: deps.newToken(),
446
+ objectId: object.id,
447
+ expiresAt: input.expiresInSeconds ? new Date(now.getTime() + input.expiresInSeconds * 1e3) : null,
448
+ revokedAt: null,
449
+ createdAt: now
450
+ };
451
+ await deps.db.insertInto(STORAGE_SHARES_TABLE).values(StorageShare.encode(share)).execute();
452
+ return {
453
+ token: share.token,
454
+ objectId: share.objectId,
455
+ expiresAt: share.expiresAt,
456
+ createdAt: share.createdAt
457
+ };
458
+ }
459
+ /**
460
+ * Withdraw a share link. A write, effective on the very next request — which is the whole reason a
461
+ * share is a row and not a presigned URL.
462
+ *
463
+ * Revoking twice is a no-op. The first revocation time is kept, because when a link stopped working
464
+ * is the fact anyone actually needs.
465
+ */
466
+ async function revokeShare(deps, token) {
467
+ const row = await deps.db.selectFrom(STORAGE_SHARES_TABLE).selectAll().where("token", "=", token).executeTakeFirst();
468
+ if (!row) throw new StorageNotFoundError({ detail: `no share token ${token}` });
469
+ const share = StorageShare.parse(row);
470
+ assertOwner(await loadObject(deps, share.objectId), deps.ownerId);
471
+ if (share.revokedAt) return {
472
+ token,
473
+ revokedAt: share.revokedAt
474
+ };
475
+ const revokedAt = deps.now();
476
+ await deps.db.updateTable(STORAGE_SHARES_TABLE).set(StorageShare.encode({
477
+ ...share,
478
+ revokedAt
479
+ })).where("token", "=", token).execute();
480
+ return {
481
+ token,
482
+ revokedAt
483
+ };
484
+ }
485
+ /**
486
+ * Resolve a share token to the object it grants read access to.
487
+ *
488
+ * Revoked and expired are **separate answers**, deliberately. Both are 410, but `storage/share_revoked`
489
+ * says the owner took the link back and `storage/share_expired` says it simply aged out — one is worth
490
+ * asking about, the other is worth re-requesting. Collapsing them into "gone" throws away the only
491
+ * information the holder can act on. Revocation is checked first: an explicit withdrawal is the more
492
+ * specific fact about a link that is both.
493
+ */
494
+ async function resolveShare(deps, token) {
495
+ const row = await deps.db.selectFrom(STORAGE_SHARES_TABLE).selectAll().where("token", "=", token).executeTakeFirst();
496
+ if (!row) throw new StorageNotFoundError({ detail: `no share token ${token}` });
497
+ const share = StorageShare.parse(row);
498
+ if (share.revokedAt) throw new StorageShareRevokedError({ detail: `share ${token} revoked at ${share.revokedAt.toISOString()}` });
499
+ if (share.expiresAt && share.expiresAt.getTime() <= deps.now().getTime()) throw new StorageShareExpiredError({ detail: `share ${token} expired at ${share.expiresAt.toISOString()}` });
500
+ const object = await loadObject(deps, share.objectId);
501
+ assertStored(object);
502
+ return object;
503
+ }
504
+ //#endregion
505
+ export { PRESIGNED_URL_TTL_SECONDS, abortUpload, completeUpload, copyObject, createShare, deleteObject, initUpload, listObjects, listUploadParts, presignObject, readableObject, resolveShare, revokeShare, updateObject };
@@ -0,0 +1,68 @@
1
+ import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
2
+ import type { Context, Hono } from "hono";
3
+ import type { StorageConfig } from "../config/config";
4
+ import { type HandlerDeps } from "./handlers";
5
+ /**
6
+ * The storage routes, their declared verification strategies, and what each accepts:
7
+ *
8
+ * POST /storage → start an upload (bearer | session)
9
+ * json: CreateUploadInput
10
+ * GET /storage → list your files (bearer | session, owner-scoped)
11
+ * query: ListObjectsQuery
12
+ * DELETE /storage/shares/:token → revoke a share (bearer | session, owner-scoped)
13
+ * param: ShareTokenParam
14
+ * POST /storage/:id/complete → finalize a multipart (bearer | session, owner-scoped)
15
+ * param: ObjectIdParam, json: CompleteUploadInput
16
+ * POST /storage/:id/abort → abandon an upload (bearer | session, owner-scoped)
17
+ * param: ObjectIdParam — no body
18
+ * GET /storage/:id/parts → resume a multipart (bearer | session, owner-scoped)
19
+ * param: ObjectIdParam
20
+ * POST /storage/:id/copy → server-side copy (bearer | session, owner-scoped)
21
+ * param: ObjectIdParam, json: CopyObjectInput
22
+ * POST /storage/:id/shares → mint a revocable share (bearer | session, owner-scoped)
23
+ * param: ObjectIdParam, json: CreateShareInput
24
+ * GET /storage/:id/url → presigned direct URL (bearer | session, owner-or-public)
25
+ * param: ObjectIdParam
26
+ * GET /storage/:id → stream the bytes (public when `visibility: 'public'`,
27
+ * otherwise bearer | session + owner)
28
+ * param: ObjectIdParam, query: ObjectReadQuery
29
+ * HEAD /storage/:id → metadata only (bearer | session, owner-scoped)
30
+ * param: ObjectIdParam
31
+ * PATCH /storage/:id → rename or change access (bearer | session, owner-scoped)
32
+ * param: ObjectIdParam, json: UpdateObjectInput
33
+ * DELETE /storage/:id → delete file and row (bearer | session, owner-scoped)
34
+ * param: ObjectIdParam
35
+ * GET /s/:token → fetch via a share link (public — the token is the credential)
36
+ * param: ShareTokenParam, query: ObjectReadQuery
37
+ *
38
+ * **Every validator sits after the guard.** An unauthenticated request with a malformed body is a
39
+ * 401, never a 400 — shape is not something a caller learns before being verified. `POST
40
+ * /storage/:id/abort` carries no json validator because it reads no body: adding one would 400 the
41
+ * bodyless POST every client sends today.
42
+ *
43
+ * `GET /storage/:id` is the one route with two strategies, because a public file must be readable by
44
+ * someone with no session at all. It is therefore **not** wrapped in {@link requireAuth}: the guard
45
+ * would deny before the handler could see that the object is public. Authorization happens inside the
46
+ * handler instead, against `c.var.auth` — which is `null` with no auth capability composed, so a
47
+ * private object is denied by default and only an explicitly public one is served.
48
+ *
49
+ * **Static segments are registered before `:param` ones.** Hono matches in registration order, so
50
+ * `/storage/shares/:token` has to come before `/storage/:id` or a DELETE to `/storage/shares/abc`
51
+ * would be read as deleting the object whose id is `shares`.
52
+ *
53
+ * **Uploads never proxy bytes through the Worker; downloads do.** That asymmetry is the design, not
54
+ * an inconsistency — `serve.ts` carries the reasoning.
55
+ */
56
+ export interface StorageRoutesOptions {
57
+ /** The resolved storage config. */
58
+ config: StorageConfig;
59
+ /** Where the object routes mount. Defaults to `/storage`. */
60
+ basePath?: string;
61
+ /** Where share fetches mount. Defaults to `/s` — short, because the whole URL gets pasted around. */
62
+ sharePath?: string;
63
+ /** Test seam: resolve handler deps from the request. Defaults to the env-based resolver. */
64
+ resolveDeps?: (c: Context<PithyHonoEnv>) => Promise<HandlerDeps>;
65
+ }
66
+ /** Register the storage sub-router. Returned as the capability's `routes` hook. */
67
+ export declare function registerStorageRoutes(options: StorageRoutesOptions): (app: Hono<PithyHonoEnv>) => void;
68
+ //# sourceMappingURL=routes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../src/http/routes.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAI7E,OAAO,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC1C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAKtD,OAAO,EAML,KAAK,WAAW,EASjB,MAAM,YAAY,CAAC;AAqBpB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkDG;AACH,MAAM,WAAW,oBAAoB;IACnC,mCAAmC;IACnC,MAAM,EAAE,aAAa,CAAC;IACtB,6DAA6D;IAC7D,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,qGAAqG;IACrG,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,4FAA4F;IAC5F,WAAW,CAAC,EAAE,CAAC,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,KAAK,OAAO,CAAC,WAAW,CAAC,CAAC;CAClE;AAuDD,mFAAmF;AACnF,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,oBAAoB,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,KAAK,IAAI,CAiJtG"}