@pithy-sh/storage 0.2.10 → 0.4.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 (91) hide show
  1. package/dist/capability.d.ts +12 -3
  2. package/dist/capability.d.ts.map +1 -1
  3. package/dist/capability.js +35 -9
  4. package/dist/config/config.d.ts +20 -4
  5. package/dist/config/config.d.ts.map +1 -1
  6. package/dist/config/config.js +23 -6
  7. package/dist/data/storageObject.d.ts +12 -0
  8. package/dist/data/storageObject.d.ts.map +1 -1
  9. package/dist/data/storageObject.js +13 -2
  10. package/dist/data/tables.js +1 -1
  11. package/dist/error/errors.js +2 -2
  12. package/dist/http/handlers.d.ts +48 -16
  13. package/dist/http/handlers.d.ts.map +1 -1
  14. package/dist/http/handlers.js +169 -66
  15. package/dist/http/responses.d.ts +173 -0
  16. package/dist/http/responses.d.ts.map +1 -0
  17. package/dist/http/responses.js +92 -0
  18. package/dist/http/routes.d.ts +13 -2
  19. package/dist/http/routes.d.ts.map +1 -1
  20. package/dist/http/routes.js +134 -22
  21. package/dist/http/schemas.d.ts +6 -0
  22. package/dist/http/schemas.d.ts.map +1 -1
  23. package/dist/http/schemas.js +7 -6
  24. package/dist/http/scopes.d.ts +25 -0
  25. package/dist/http/scopes.d.ts.map +1 -0
  26. package/dist/http/scopes.js +32 -0
  27. package/dist/http/serve.d.ts +5 -2
  28. package/dist/http/serve.d.ts.map +1 -1
  29. package/dist/index.d.ts +2 -0
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +5 -3
  32. package/dist/migrations/0002_ownership.d.ts +5 -0
  33. package/dist/migrations/0002_ownership.d.ts.map +1 -0
  34. package/dist/migrations/0002_ownership.js +114 -0
  35. package/dist/object/cloudflare.d.ts +3 -2
  36. package/dist/object/cloudflare.d.ts.map +1 -1
  37. package/dist/object/cloudflare.js +3 -3
  38. package/dist/object/store.d.ts +2 -7
  39. package/dist/object/store.d.ts.map +1 -1
  40. package/dist/object/store.js +1 -6
  41. package/dist/object/uploadedPart.d.ts +11 -0
  42. package/dist/object/uploadedPart.d.ts.map +1 -0
  43. package/dist/object/uploadedPart.js +12 -0
  44. package/dist/provision/provisionStorage.d.ts +14 -2
  45. package/dist/provision/provisionStorage.d.ts.map +1 -1
  46. package/dist/provision/provisionStorage.js +19 -4
  47. package/dist/provision/resolveStorageConfig.js +1 -1
  48. package/dist/quota/ceiling.d.ts +36 -0
  49. package/dist/quota/ceiling.d.ts.map +1 -0
  50. package/dist/quota/ceiling.js +31 -0
  51. package/dist/quota/quota.d.ts +24 -7
  52. package/dist/quota/quota.d.ts.map +1 -1
  53. package/dist/quota/quota.js +40 -12
  54. package/dist/secret/bundleToken.d.ts +24 -0
  55. package/dist/secret/bundleToken.d.ts.map +1 -0
  56. package/dist/secret/bundleToken.js +74 -0
  57. package/dist/secret/registry.d.ts +5 -1
  58. package/dist/secret/registry.d.ts.map +1 -1
  59. package/dist/secret/registry.js +7 -3
  60. package/dist/seeds/example.d.ts.map +1 -1
  61. package/dist/seeds/example.js +3 -0
  62. package/dist/test-utils/liveStorage.d.ts.map +1 -1
  63. package/dist/test-utils/liveStorage.js +5 -2
  64. package/dist/version.generated.d.ts +1 -1
  65. package/dist/version.generated.d.ts.map +1 -1
  66. package/dist/version.generated.js +1 -1
  67. package/package.json +7 -7
  68. package/pithy.manifest.json +20 -10
  69. package/src/capability.ts +52 -8
  70. package/src/config/config.ts +24 -6
  71. package/src/data/storageObject.ts +22 -6
  72. package/src/error/errors.ts +2 -2
  73. package/src/http/handlers.ts +215 -81
  74. package/src/http/responses.ts +168 -0
  75. package/src/http/routes.ts +245 -46
  76. package/src/http/schemas.ts +11 -5
  77. package/src/http/scopes.ts +39 -0
  78. package/src/http/serve.ts +5 -2
  79. package/src/index.ts +2 -0
  80. package/src/migrations/0002_ownership.ts +176 -0
  81. package/src/object/cloudflare.ts +4 -3
  82. package/src/object/store.ts +6 -10
  83. package/src/object/uploadedPart.ts +17 -0
  84. package/src/provision/provisionStorage.ts +22 -3
  85. package/src/quota/ceiling.ts +44 -0
  86. package/src/quota/quota.ts +63 -20
  87. package/src/secret/bundleToken.ts +81 -0
  88. package/src/secret/registry.ts +6 -8
  89. package/src/seeds/example.ts +3 -0
  90. package/src/test-utils/liveStorage.ts +3 -6
  91. package/src/version.generated.ts +1 -1
@@ -1,19 +1,95 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
- import { StorageObject } from "../data/storageObject.js";
4
3
  import { StorageForbiddenError, StorageNotFoundError, StorageShareExpiredError, StorageShareRevokedError, StorageUploadIncompleteError } from "../error/errors.js";
5
4
  import { collectParts, needsMultipart, planMultipart } from "../object/multipart.js";
6
5
  import { StorageShare } from "../data/share.js";
6
+ import { StorageObject } from "../data/storageObject.js";
7
7
  import { STORAGE_OBJECTS_TABLE, STORAGE_SHARES_TABLE } from "../data/tables.js";
8
8
  import { deriveObjectKey } from "../object/key.js";
9
9
  import { assertWithinQuota, insertReservingQuota, updateSettlingQuota } from "../quota/quota.js";
10
+ import { resolveVisibility } from "@pithy-sh/core/src/access/visibility";
11
+ import { InternalError } from "@pithy-sh/core/src/error/pithyError";
12
+ import { accessLevel, disclosedTenancy, keepReadable, readablePredicate } from "@pithy-sh/core/src/access/access";
10
13
  //#region src/http/handlers.ts
11
- /** Drop the server-only fields. The single place a row becomes something a client may see. */
12
- function view(object) {
14
+ /**
15
+ * The storage request handlers — pure functions over injected dependencies, so every branch is tested
16
+ * against real D1 and real R2 without standing up a Worker. `routes.ts` is a thin shell that resolves
17
+ * these dependencies from the request env and maps their results onto responses.
18
+ *
19
+ * **Request shape is not validated here.** Each route declares its own schemas with
20
+ * `validate(target, Schema)` and hands the handler the already-parsed value, so a
21
+ * malformed request is refused before a dependency is resolved or a row is read. What survives in
22
+ * these handlers is everything a request schema cannot express — ownership, quota, upload state —
23
+ * which is the whole of what they were ever really about.
24
+ *
25
+ * **The object key never leaves this module.** Every client-facing shape goes through {@link view},
26
+ * which drops `key` and `uploadId`. That is not tidiness: the key is the only thing a presigned URL
27
+ * addresses, so a key in a response body is a capability leak waiting for the first adopter who logs
28
+ * their API responses.
29
+ *
30
+ * **Whose a file is, and who may reach it.** Every file is written with its owner, the organization in
31
+ * force, and a visibility — `private`, `organization` or `public` — from the project's policy. Every route
32
+ * asks core's access rules, and the adopter's permission hook if they supplied one, before it acts:
33
+ * reading is the visibility's, and changing a file — completing, aborting, copying, renaming,
34
+ * re-scoping, sharing, deleting — is its owner's, acting for its organization, or a role holding
35
+ * `storage:manage` there.
36
+ *
37
+ * **A file you cannot see reads as missing.** A caller who may not read a file gets `storage/not_found`,
38
+ * and `storage/forbidden` only when they may read it but not change it — because a 403 on a file they
39
+ * cannot see confirms it exists, which is exactly the oracle an enumeration attack wants. A file they
40
+ * can already read has nothing left to hide, so there the honest answer is the useful one.
41
+ */
42
+ /** The power a role holds to edit, delete and re-scope any file in its own organization. */
43
+ const STORAGE_MANAGE_POWER = "storage:manage";
44
+ /** The capability's name, as the permission hook sees it. */
45
+ const CAPABILITY = "storage";
46
+ /**
47
+ * The quota a write of a row held for `ownerId` in `organizationId` is checked against: the ceiling, and
48
+ * whose bytes it sums. The resolved ceiling where the request has one, the configured one otherwise.
49
+ *
50
+ * **A ceiling that covers an organization covers only that organization's rows**, so a row about to be held
51
+ * for a different one — or for none — would sit outside the very sum it is checked against, and never count.
52
+ * That is refused rather than written: it means the billing subject and the organization in force disagree,
53
+ * which is wiring for the adopter to fix, and under-counting has no recovery.
54
+ */
55
+ async function quotaFor(deps, ownerId, organizationId) {
56
+ const ceiling = deps.quotaLimit ? await deps.quotaLimit() : {
57
+ limitBytes: deps.config.quota.bytesPerOwner,
58
+ tenant: null,
59
+ metered: false
60
+ };
61
+ const { metered } = ceiling;
62
+ if (ceiling.tenant === null || ceiling.limitBytes === null || ownerId === null) return {
63
+ ownerId,
64
+ limitBytes: ceiling.limitBytes,
65
+ metered
66
+ };
67
+ if (organizationId !== ceiling.tenant) throw new InternalError({
68
+ message: "This file cannot be counted against the plan it is billed to, so nothing was written.",
69
+ action: "Make the payments subject resolver and the organization in force agree — both should answer the organization the caller acts for.",
70
+ detail: `The storageBytes ceiling covers organization ${ceiling.tenant}; the file would be held for ${organizationId ?? "no organization"}.`
71
+ });
72
+ return {
73
+ ownerId,
74
+ organizationId: ceiling.tenant,
75
+ limitBytes: ceiling.limitBytes,
76
+ metered
77
+ };
78
+ }
79
+ /**
80
+ * Drop the server-only fields. The single place a row becomes something a client may see.
81
+ *
82
+ * The owner and organization are the caller's to see only when they act for the file's organization
83
+ * ({@link disclosedTenancy}). A public file reached from anywhere else names neither: reading a file is not
84
+ * learning which organization its owner belongs to.
85
+ */
86
+ function view(object, caller) {
87
+ const tenancy = disclosedTenancy(object, caller);
13
88
  return {
14
89
  id: object.id,
15
90
  path: object.path,
16
- ownerId: object.ownerId,
91
+ ownerId: tenancy.ownerId,
92
+ organizationId: tenancy.organizationId,
17
93
  contentType: object.contentType,
18
94
  size: object.size,
19
95
  visibility: object.visibility,
@@ -28,27 +104,46 @@ async function findObject(deps, id) {
28
104
  const row = await deps.db.selectFrom(STORAGE_OBJECTS_TABLE).selectAll().where("id", "=", id).executeTakeFirst();
29
105
  return row ? StorageObject.parse(row) : null;
30
106
  }
31
- /** Load one row or throw `storage/not_found`. */
107
+ /**
108
+ * Load one row or throw `storage/not_found`, asking nobody whether the caller may see it — for a share
109
+ * link, where the token is the credential and the rules have already been spent by whoever minted it.
110
+ */
32
111
  async function loadObject(deps, id) {
33
112
  const object = await findObject(deps, id);
34
113
  if (!object) throw new StorageNotFoundError({ detail: `no storage object ${id}` });
35
114
  return object;
36
115
  }
116
+ /** What the caller may do with one file, asking the rules and the hook. */
117
+ function levelOf(deps, object) {
118
+ return accessLevel({
119
+ record: object,
120
+ caller: deps.caller,
121
+ capability: CAPABILITY,
122
+ managePower: STORAGE_MANAGE_POWER,
123
+ hook: deps.permission,
124
+ env: deps.env
125
+ });
126
+ }
127
+ /** Who is asking, for a log line. */
128
+ function callerName(deps) {
129
+ return deps.caller.userId ?? "an anonymous caller";
130
+ }
131
+ /** Load a file the caller may read, or answer not found — for a file that is absent and one they cannot see alike. */
132
+ async function loadReadable(deps, id) {
133
+ const object = await findObject(deps, id);
134
+ if (!object || await levelOf(deps, object) === "none") throw new StorageNotFoundError({ detail: `no storage object ${id} readable by ${callerName(deps)}` });
135
+ return object;
136
+ }
37
137
  /**
38
- * Require the caller to own the object. A private object they do not own is reported as **missing**,
39
- * so the route cannot be used to test whether an id exists. A public object is reported as
40
- * **forbidden**, because its existence is already public knowledge and "missing" would just be a lie.
138
+ * Load a file the caller may change. Not found when they cannot read it; forbidden only when they can,
139
+ * because by then they already know it exists.
41
140
  */
42
- function assertOwner(object, ownerId) {
43
- if (ownerId !== null && object.ownerId === ownerId) return;
44
- if (object.visibility === "public") throw new StorageForbiddenError({ detail: `object ${object.id} is owned by ${object.ownerId ?? "the system"}` });
45
- throw new StorageNotFoundError({ detail: `object ${object.id} is not owned by ${ownerId ?? "an anonymous caller"}` });
46
- }
47
- /** Require the caller to be allowed to *read* the object: it is public, or it is theirs. */
48
- function assertReadable(object, ownerId) {
49
- if (object.visibility === "public") return;
50
- if (ownerId !== null && object.ownerId === ownerId) return;
51
- throw new StorageNotFoundError({ detail: `object ${object.id} is not readable by ${ownerId ?? "an anonymous caller"}` });
141
+ async function loadWritable(deps, id) {
142
+ const object = await findObject(deps, id);
143
+ const level = object ? await levelOf(deps, object) : "none";
144
+ if (!object || level === "none") throw new StorageNotFoundError({ detail: `no storage object ${id} readable by ${callerName(deps)}` });
145
+ if (level !== "write") throw new StorageForbiddenError({ detail: `${callerName(deps)} may read object ${id} but not change it` });
146
+ return object;
52
147
  }
53
148
  /** Require the object's bytes to actually be there. A `pending` row has a record but no content. */
54
149
  function assertStored(object) {
@@ -76,10 +171,11 @@ async function saveObject(deps, object) {
76
171
  */
77
172
  async function initUpload(deps, input) {
78
173
  const now = deps.now();
174
+ const organizationId = deps.caller.acting?.organizationId ?? null;
175
+ const visibility = resolveVisibility(deps.config.visibility, input.visibility, organizationId);
79
176
  await assertWithinQuota({
80
177
  db: deps.db,
81
- ownerId: deps.ownerId,
82
- limitBytes: deps.config.quota.bytesPerOwner,
178
+ ...await quotaFor(deps, deps.caller.userId, organizationId),
83
179
  additionalBytes: input.size
84
180
  });
85
181
  const key = deriveObjectKey();
@@ -110,10 +206,11 @@ async function initUpload(deps, input) {
110
206
  id: deps.newId(),
111
207
  key,
112
208
  path: input.path,
113
- ownerId: deps.ownerId,
209
+ ownerId: deps.caller.userId,
210
+ organizationId,
114
211
  contentType: input.contentType,
115
212
  size: input.size,
116
- visibility: input.visibility ?? deps.config.defaultVisibility,
213
+ visibility,
117
214
  checksum: null,
118
215
  status: "pending",
119
216
  uploadId,
@@ -123,8 +220,7 @@ async function initUpload(deps, input) {
123
220
  try {
124
221
  await insertReservingQuota({
125
222
  db: deps.db,
126
- ownerId: deps.ownerId,
127
- limitBytes: deps.config.quota.bytesPerOwner,
223
+ ...await quotaFor(deps, deps.caller.userId, organizationId),
128
224
  additionalBytes: input.size,
129
225
  record: StorageObject.encode(object)
130
226
  });
@@ -133,7 +229,7 @@ async function initUpload(deps, input) {
133
229
  throw error;
134
230
  }
135
231
  return {
136
- object: view(object),
232
+ object: view(object, deps.caller),
137
233
  upload
138
234
  };
139
235
  }
@@ -160,9 +256,8 @@ async function initUpload(deps, input) {
160
256
  * the first (`quota/quota.ts`).
161
257
  */
162
258
  async function completeUpload(deps, id, input) {
163
- const object = await loadObject(deps, id);
164
- assertOwner(object, deps.ownerId);
165
- if (object.status === "stored") return view(object);
259
+ const object = await loadWritable(deps, id);
260
+ if (object.status === "stored") return view(object, deps.caller);
166
261
  if (object.status !== "pending") throw new StorageUploadIncompleteError({ detail: `object ${id} is ${object.status} and cannot be completed` });
167
262
  if (object.uploadId) {
168
263
  const expected = planMultipart(object.size ?? 0, deps.config.partSizeBytes).partCount;
@@ -185,12 +280,12 @@ async function completeUpload(deps, id, input) {
185
280
  updatedAt: deps.now()
186
281
  };
187
282
  const overshoot = metadata.size - (object.size ?? 0);
188
- if (overshoot <= 0) return view(await saveObject(deps, settled));
283
+ if (overshoot <= 0) return view(await saveObject(deps, settled), deps.caller);
284
+ const quota = await quotaFor(deps, object.ownerId, object.organizationId);
189
285
  try {
190
286
  await updateSettlingQuota({
191
287
  db: deps.db,
192
- ownerId: object.ownerId,
193
- limitBytes: deps.config.quota.bytesPerOwner,
288
+ ...quota,
194
289
  additionalBytes: overshoot,
195
290
  record: StorageObject.encode(settled)
196
291
  });
@@ -204,7 +299,7 @@ async function completeUpload(deps, id, input) {
204
299
  });
205
300
  throw error;
206
301
  }
207
- return view(settled);
302
+ return view(settled, deps.caller);
208
303
  }
209
304
  /**
210
305
  * Abandon an in-flight upload: tell R2 to discard the stored parts, then mark the row `failed`.
@@ -221,8 +316,7 @@ async function completeUpload(deps, id, input) {
221
316
  * than sheltered forever by a row that counts toward no quota (`workflows/sweep.ts`).
222
317
  */
223
318
  async function abortUpload(deps, id) {
224
- const object = await loadObject(deps, id);
225
- assertOwner(object, deps.ownerId);
319
+ const object = await loadWritable(deps, id);
226
320
  if (object.status === "stored") throw new StorageUploadIncompleteError({
227
321
  message: "That upload already finished.",
228
322
  action: "Delete the file instead.",
@@ -235,7 +329,7 @@ async function abortUpload(deps, id) {
235
329
  status: "failed",
236
330
  uploadId: null,
237
331
  updatedAt: deps.now()
238
- }));
332
+ }), deps.caller);
239
333
  }
240
334
  /**
241
335
  * Resume a multipart upload: the parts R2 already holds, plus a **freshly presigned** URL for each
@@ -251,8 +345,7 @@ async function abortUpload(deps, id) {
251
345
  * its parts discarded — re-presigning against either would hand out URLs addressing nothing.
252
346
  */
253
347
  async function listUploadParts(deps, id) {
254
- const object = await loadObject(deps, id);
255
- assertOwner(object, deps.ownerId);
348
+ const object = await loadWritable(deps, id);
256
349
  const uploadId = object.uploadId;
257
350
  if (object.status !== "pending" || !uploadId) throw new StorageUploadIncompleteError({
258
351
  message: "That upload has no parts to resume.",
@@ -311,13 +404,18 @@ function decodeCursor(value) {
311
404
  /** Default page size — generous enough for a file browser, small enough to stay one index read. */
312
405
  const DEFAULT_LIST_LIMIT = 50;
313
406
  /**
314
- * One page of the caller's files, ordered by logical path. Scoped to the authenticated owner: there
315
- * is no way to list another owner's files, and no parameter that could be made to.
407
+ * One page of the files the caller may see, ordered by logical path: their own, their organization's,
408
+ * and — only when `includePublic=true` — every public file. The rules run in SQL, so there is no
409
+ * parameter that lists anyone else's private files; the hook is asked about each row on the page and may
410
+ * remove one, so a page can come back short while its cursor still says there is more.
316
411
  */
317
412
  async function listObjects(deps, query) {
318
413
  const limit = query.limit ?? DEFAULT_LIST_LIMIT;
319
414
  const after = decodeCursor(query.cursor);
320
- let statement = deps.db.selectFrom(STORAGE_OBJECTS_TABLE).selectAll().where("ownerId", "=", deps.ownerId).orderBy("path", "asc").orderBy("id", "asc").limit(limit + 1);
415
+ let statement = deps.db.selectFrom(STORAGE_OBJECTS_TABLE).selectAll().where(readablePredicate(deps.caller, {
416
+ managePower: STORAGE_MANAGE_POWER,
417
+ includePublic: query.includePublic === "true"
418
+ })).orderBy("path", "asc").orderBy("id", "asc").limit(limit + 1);
321
419
  if (query.prefix) {
322
420
  const escaped = query.prefix.replace(/[\\%_]/g, (character) => `\\${character}`);
323
421
  statement = statement.where("path", "like", `${escaped}%`);
@@ -325,7 +423,12 @@ async function listObjects(deps, query) {
325
423
  if (after) statement = statement.where((eb) => eb.or([eb("path", ">", after.path), eb.and([eb("path", "=", after.path), eb("id", ">", after.id)])]));
326
424
  const rows = await statement.execute();
327
425
  const page = rows.slice(0, limit).map((row) => StorageObject.parse(row));
328
- const objects = page.map(view);
426
+ const objects = (await keepReadable(page, {
427
+ capability: CAPABILITY,
428
+ caller: deps.caller,
429
+ hook: deps.permission,
430
+ env: deps.env
431
+ })).map((object) => view(object, deps.caller));
329
432
  if (rows.length <= limit) return { objects };
330
433
  const last = page[page.length - 1];
331
434
  return last ? {
@@ -336,10 +439,9 @@ async function listObjects(deps, query) {
336
439
  })
337
440
  } : { objects };
338
441
  }
339
- /** Load an object for reading, enforcing public-or-owner and that its bytes exist. */
442
+ /** Load an object for reading, enforcing who may read it and that its bytes exist. */
340
443
  async function readableObject(deps, id) {
341
- const object = await loadObject(deps, id);
342
- assertReadable(object, deps.ownerId);
444
+ const object = await loadReadable(deps, id);
343
445
  assertStored(object);
344
446
  return object;
345
447
  }
@@ -359,36 +461,39 @@ async function presignObject(deps, id) {
359
461
  expiresInSeconds: 300
360
462
  };
361
463
  }
362
- /** Rename a file, change who may read it, or both. The key never moves — only the row changes. */
464
+ /**
465
+ * Rename a file, change who may read it, or both. The key never moves — only the row changes. A level the
466
+ * policy does not allow is refused, and `organization` on a file written with no organization is too.
467
+ */
363
468
  async function updateObject(deps, id, input) {
364
- const object = await loadObject(deps, id);
365
- assertOwner(object, deps.ownerId);
469
+ const object = await loadWritable(deps, id);
470
+ const visibility = input.visibility === void 0 ? object.visibility : resolveVisibility(deps.config.visibility, input.visibility, object.organizationId);
366
471
  return view(await saveObject(deps, {
367
472
  ...object,
368
473
  path: input.path ?? object.path,
369
- visibility: input.visibility ?? object.visibility,
474
+ visibility,
370
475
  updatedAt: deps.now()
371
- }));
476
+ }), deps.caller);
372
477
  }
373
478
  /**
374
479
  * Copy a file server-side. The bytes are copied by R2 and never enter the Worker; the copy is a new
375
480
  * object with its own id, its own key, and its own share links — it is not an alias.
376
481
  *
377
- * Owner-scoped, like every other mutating route: you may copy your own files. Copying a *public* file
482
+ * A change, like every other mutating route: you may copy a file you may change. Copying a *public* file
378
483
  * you do not own is a plausible feature and deliberately not this one — it would let any reader
379
484
  * duplicate bytes into their own quota on the owner's storage bill, which is a decision an adopter
380
- * should make explicitly rather than inherit.
485
+ * should make explicitly rather than inherit. The copy is the caller's, in the organization they act for.
381
486
  */
382
487
  async function copyObject(deps, id, input) {
383
- const source = await loadObject(deps, id);
384
- assertOwner(source, deps.ownerId);
488
+ const source = await loadWritable(deps, id);
385
489
  assertStored(source);
490
+ const organizationId = deps.caller.acting?.organizationId ?? null;
386
491
  await assertWithinQuota({
387
492
  db: deps.db,
388
- ownerId: deps.ownerId,
389
- limitBytes: deps.config.quota.bytesPerOwner,
493
+ ...await quotaFor(deps, deps.caller.userId, organizationId),
390
494
  additionalBytes: source.size ?? 0
391
495
  });
496
+ const visibility = resolveVisibility(deps.config.visibility, deps.config.visibility.allowed.includes("private") ? "private" : void 0, organizationId);
392
497
  const key = deriveObjectKey();
393
498
  await deps.store.copy(source.key, key);
394
499
  const now = deps.now();
@@ -397,8 +502,9 @@ async function copyObject(deps, id, input) {
397
502
  id: deps.newId(),
398
503
  key,
399
504
  path: input.path,
400
- ownerId: deps.ownerId,
401
- visibility: "private",
505
+ ownerId: deps.caller.userId,
506
+ organizationId,
507
+ visibility,
402
508
  status: "stored",
403
509
  uploadId: null,
404
510
  createdAt: now,
@@ -407,8 +513,7 @@ async function copyObject(deps, id, input) {
407
513
  try {
408
514
  await insertReservingQuota({
409
515
  db: deps.db,
410
- ownerId: deps.ownerId,
411
- limitBytes: deps.config.quota.bytesPerOwner,
516
+ ...await quotaFor(deps, deps.caller.userId, organizationId),
412
517
  additionalBytes: source.size ?? 0,
413
518
  record: StorageObject.encode(copy)
414
519
  });
@@ -416,7 +521,7 @@ async function copyObject(deps, id, input) {
416
521
  await deps.store.delete(key).catch(() => {});
417
522
  throw error;
418
523
  }
419
- return view(copy);
524
+ return view(copy, deps.caller);
420
525
  }
421
526
  /**
422
527
  * Delete a file: the object first, then the row. Every share link pointing at it goes with the row,
@@ -427,8 +532,7 @@ async function copyObject(deps, id, input) {
427
532
  * sweep collects an object whose row went first.
428
533
  */
429
534
  async function deleteObject(deps, id) {
430
- const object = await loadObject(deps, id);
431
- assertOwner(object, deps.ownerId);
535
+ const object = await loadWritable(deps, id);
432
536
  if (object.uploadId) await deps.store.abortMultipart(object.key, object.uploadId).catch(() => {});
433
537
  await deps.store.delete(object.key).catch(() => {});
434
538
  await deps.db.deleteFrom(STORAGE_OBJECTS_TABLE).where("id", "=", id).execute();
@@ -439,8 +543,7 @@ async function deleteObject(deps, id) {
439
543
  }
440
544
  /** Mint a revocable share link for one file. */
441
545
  async function createShare(deps, id, input) {
442
- const object = await loadObject(deps, id);
443
- assertOwner(object, deps.ownerId);
546
+ const object = await loadWritable(deps, id);
444
547
  assertStored(object);
445
548
  const now = deps.now();
446
549
  const share = {
@@ -469,7 +572,7 @@ async function revokeShare(deps, token) {
469
572
  const row = await deps.db.selectFrom(STORAGE_SHARES_TABLE).selectAll().where("token", "=", token).executeTakeFirst();
470
573
  if (!row) throw new StorageNotFoundError({ detail: `no share token ${token}` });
471
574
  const share = StorageShare.parse(row);
472
- assertOwner(await loadObject(deps, share.objectId), deps.ownerId);
575
+ await loadWritable(deps, share.objectId);
473
576
  if (share.revokedAt) return {
474
577
  token,
475
578
  revokedAt: share.revokedAt
@@ -504,4 +607,4 @@ async function resolveShare(deps, token) {
504
607
  return object;
505
608
  }
506
609
  //#endregion
507
- export { PRESIGNED_URL_TTL_SECONDS, abortUpload, completeUpload, copyObject, createShare, deleteObject, initUpload, listObjects, listUploadParts, presignObject, readableObject, resolveShare, revokeShare, updateObject };
610
+ export { PRESIGNED_URL_TTL_SECONDS, STORAGE_MANAGE_POWER, abortUpload, completeUpload, copyObject, createShare, deleteObject, initUpload, listObjects, listUploadParts, presignObject, readableObject, resolveShare, revokeShare, updateObject };
@@ -0,0 +1,173 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { z } from "zod";
4
+ /**
5
+ * What the storage routes return as JSON, as Zod objects a client can validate against and the OpenAPI
6
+ * contract can describe. The byte-serving routes (`GET` and `HEAD /storage/:id`, `GET /s/:token`) answer
7
+ * with the object itself rather than JSON, and `routes.ts` describes those inline.
8
+ *
9
+ * `schemas.ts` bounds what a caller may send; this file states what it gets back. These describe JSON on
10
+ * the wire, so a date is the ISO-8601 string `c.json` writes, and nothing here carries a codec or a
11
+ * transform: parsing a response hands back exactly what went in, which is what lets
12
+ * `routes.workers.test.ts` parse a real answer and compare it with the original.
13
+ *
14
+ * **A field added here later is `.optional()` as well as `.nullable()`.** A client generated from the
15
+ * contract reads Workers on older releases too, and a required key they cannot send fails it outright.
16
+ */
17
+ /** A stored file as a client sees it. The object key and the R2 upload id never appear. */
18
+ export declare const StorageObjectResponse: z.ZodObject<{
19
+ id: z.ZodString;
20
+ path: z.ZodString;
21
+ ownerId: z.ZodNullable<z.ZodString>;
22
+ organizationId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
23
+ contentType: z.ZodString;
24
+ size: z.ZodNullable<z.ZodNumber>;
25
+ visibility: z.ZodEnum<{
26
+ organization: "organization";
27
+ private: "private";
28
+ public: "public";
29
+ }>;
30
+ checksum: z.ZodNullable<z.ZodString>;
31
+ status: z.ZodEnum<{
32
+ failed: "failed";
33
+ pending: "pending";
34
+ stored: "stored";
35
+ }>;
36
+ createdAt: z.ZodISODateTime;
37
+ updatedAt: z.ZodISODateTime;
38
+ }, z.core.$strip>;
39
+ export type StorageObjectResponse = z.infer<typeof StorageObjectResponse>;
40
+ /** One part of a multipart upload, with the URL its bytes go to. */
41
+ export declare const UploadPartTargetResponse: z.ZodObject<{
42
+ partNumber: z.ZodNumber;
43
+ offset: z.ZodNumber;
44
+ length: z.ZodNumber;
45
+ url: z.ZodString;
46
+ }, z.core.$strip>;
47
+ export type UploadPartTargetResponse = z.infer<typeof UploadPartTargetResponse>;
48
+ /** Where the bytes go: one URL, or one per part. */
49
+ export declare const UploadTargetResponse: z.ZodDiscriminatedUnion<[z.ZodObject<{
50
+ kind: z.ZodLiteral<"single">;
51
+ url: z.ZodString;
52
+ }, z.core.$strip>, z.ZodObject<{
53
+ kind: z.ZodLiteral<"multipart">;
54
+ uploadId: z.ZodString;
55
+ partSize: z.ZodNumber;
56
+ parts: z.ZodArray<z.ZodObject<{
57
+ partNumber: z.ZodNumber;
58
+ offset: z.ZodNumber;
59
+ length: z.ZodNumber;
60
+ url: z.ZodString;
61
+ }, z.core.$strip>>;
62
+ }, z.core.$strip>], "kind">;
63
+ export type UploadTargetResponse = z.infer<typeof UploadTargetResponse>;
64
+ /** What starting an upload returns. */
65
+ export declare const UploadInitResponse: z.ZodObject<{
66
+ object: z.ZodObject<{
67
+ id: z.ZodString;
68
+ path: z.ZodString;
69
+ ownerId: z.ZodNullable<z.ZodString>;
70
+ organizationId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
71
+ contentType: z.ZodString;
72
+ size: z.ZodNullable<z.ZodNumber>;
73
+ visibility: z.ZodEnum<{
74
+ organization: "organization";
75
+ private: "private";
76
+ public: "public";
77
+ }>;
78
+ checksum: z.ZodNullable<z.ZodString>;
79
+ status: z.ZodEnum<{
80
+ failed: "failed";
81
+ pending: "pending";
82
+ stored: "stored";
83
+ }>;
84
+ createdAt: z.ZodISODateTime;
85
+ updatedAt: z.ZodISODateTime;
86
+ }, z.core.$strip>;
87
+ upload: z.ZodDiscriminatedUnion<[z.ZodObject<{
88
+ kind: z.ZodLiteral<"single">;
89
+ url: z.ZodString;
90
+ }, z.core.$strip>, z.ZodObject<{
91
+ kind: z.ZodLiteral<"multipart">;
92
+ uploadId: z.ZodString;
93
+ partSize: z.ZodNumber;
94
+ parts: z.ZodArray<z.ZodObject<{
95
+ partNumber: z.ZodNumber;
96
+ offset: z.ZodNumber;
97
+ length: z.ZodNumber;
98
+ url: z.ZodString;
99
+ }, z.core.$strip>>;
100
+ }, z.core.$strip>], "kind">;
101
+ }, z.core.$strip>;
102
+ export type UploadInitResponse = z.infer<typeof UploadInitResponse>;
103
+ /** One page of the caller's files. */
104
+ export declare const ObjectListResponse: z.ZodObject<{
105
+ objects: z.ZodArray<z.ZodObject<{
106
+ id: z.ZodString;
107
+ path: z.ZodString;
108
+ ownerId: z.ZodNullable<z.ZodString>;
109
+ organizationId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
110
+ contentType: z.ZodString;
111
+ size: z.ZodNullable<z.ZodNumber>;
112
+ visibility: z.ZodEnum<{
113
+ organization: "organization";
114
+ private: "private";
115
+ public: "public";
116
+ }>;
117
+ checksum: z.ZodNullable<z.ZodString>;
118
+ status: z.ZodEnum<{
119
+ failed: "failed";
120
+ pending: "pending";
121
+ stored: "stored";
122
+ }>;
123
+ createdAt: z.ZodISODateTime;
124
+ updatedAt: z.ZodISODateTime;
125
+ }, z.core.$strip>>;
126
+ cursor: z.ZodOptional<z.ZodString>;
127
+ }, z.core.$strip>;
128
+ export type ObjectListResponse = z.infer<typeof ObjectListResponse>;
129
+ /** Where a resuming client stands. */
130
+ export declare const UploadPartsResponse: z.ZodObject<{
131
+ uploadId: z.ZodString;
132
+ partSize: z.ZodNumber;
133
+ partCount: z.ZodNumber;
134
+ uploaded: z.ZodArray<z.ZodObject<{
135
+ partNumber: z.ZodNumber;
136
+ etag: z.ZodString;
137
+ size: z.ZodNumber;
138
+ }, z.core.$strip>>;
139
+ missing: z.ZodArray<z.ZodObject<{
140
+ partNumber: z.ZodNumber;
141
+ offset: z.ZodNumber;
142
+ length: z.ZodNumber;
143
+ url: z.ZodString;
144
+ }, z.core.$strip>>;
145
+ }, z.core.$strip>;
146
+ export type UploadPartsResponse = z.infer<typeof UploadPartsResponse>;
147
+ /** A presigned direct-download URL. */
148
+ export declare const PresignedUrlResponse: z.ZodObject<{
149
+ url: z.ZodString;
150
+ expiresInSeconds: z.ZodNumber;
151
+ }, z.core.$strip>;
152
+ export type PresignedUrlResponse = z.infer<typeof PresignedUrlResponse>;
153
+ /** What deleting a file returns. */
154
+ export declare const ObjectDeletedResponse: z.ZodObject<{
155
+ id: z.ZodString;
156
+ deleted: z.ZodLiteral<true>;
157
+ }, z.core.$strip>;
158
+ export type ObjectDeletedResponse = z.infer<typeof ObjectDeletedResponse>;
159
+ /** A minted share link. */
160
+ export declare const ShareResponse: z.ZodObject<{
161
+ token: z.ZodString;
162
+ objectId: z.ZodString;
163
+ expiresAt: z.ZodNullable<z.ZodISODateTime>;
164
+ createdAt: z.ZodISODateTime;
165
+ }, z.core.$strip>;
166
+ export type ShareResponse = z.infer<typeof ShareResponse>;
167
+ /** What revoking a share link returns. */
168
+ export declare const ShareRevokedResponse: z.ZodObject<{
169
+ token: z.ZodString;
170
+ revokedAt: z.ZodISODateTime;
171
+ }, z.core.$strip>;
172
+ export type ShareRevokedResponse = z.infer<typeof ShareRevokedResponse>;
173
+ //# sourceMappingURL=responses.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"responses.d.ts","sourceRoot":"","sources":["../../src/http/responses.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAIxB;;;;;;;;;;;;GAYG;AAEH,2FAA2F;AAC3F,eAAO,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;iBAoCkC,CAAC;AACrE,MAAM,MAAM,qBAAqB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC;AAE1E,oEAAoE;AACpE,eAAO,MAAM,wBAAwB;;;;;iBAO8B,CAAC;AACpE,MAAM,MAAM,wBAAwB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,wBAAwB,CAAC,CAAC;AAEhF,oDAAoD;AACpD,eAAO,MAAM,oBAAoB;;;;;;;;;;;;;2BAiBa,CAAC;AAC/C,MAAM,MAAM,oBAAoB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,oBAAoB,CAAC,CAAC;AAExE,uCAAuC;AACvC,eAAO,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAK0D,CAAC;AAC1F,MAAM,MAAM,kBAAkB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAEpE,sCAAsC;AACtC,eAAO,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;iBAQe,CAAC;AAC/C,MAAM,MAAM,kBAAkB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAEpE,sCAAsC;AACtC,eAAO,MAAM,mBAAmB;;;;;;;;;;;;;;;iBAQuE,CAAC;AACxG,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAEtE,uCAAuC;AACvC,eAAO,MAAM,oBAAoB;;;iBAKyC,CAAC;AAC3E,MAAM,MAAM,oBAAoB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,oBAAoB,CAAC,CAAC;AAExE,oCAAoC;AACpC,eAAO,MAAM,qBAAqB;;;iBAKE,CAAC;AACrC,MAAM,MAAM,qBAAqB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC;AAE1E,2BAA2B;AAC3B,eAAO,MAAM,aAAa;;;;;iBAYyB,CAAC;AACpD,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,aAAa,CAAC,CAAC;AAE1D,0CAA0C;AAC1C,eAAO,MAAM,oBAAoB;;;iBAKS,CAAC;AAC3C,MAAM,MAAM,oBAAoB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,oBAAoB,CAAC,CAAC"}