@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,6 +1,17 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
+ import {
5
+ type AccessCaller,
6
+ type AccessLevel,
7
+ accessLevel,
8
+ disclosedTenancy,
9
+ keepReadable,
10
+ type PermissionHook,
11
+ readablePredicate,
12
+ } from "@pithy-sh/core/src/access/access";
13
+ import { resolveVisibility } from "@pithy-sh/core/src/access/visibility";
14
+ import { InternalError } from "@pithy-sh/core/src/error/pithyError";
4
15
  import type { StorageConfig } from "../config/config";
5
16
  import { StorageShare } from "../data/share";
6
17
  import { StorageObject } from "../data/storageObject";
@@ -14,8 +25,10 @@ import {
14
25
  } from "../error/errors";
15
26
  import { deriveObjectKey } from "../object/key";
16
27
  import { collectParts, needsMultipart, planMultipart } from "../object/multipart";
17
- import type { ObjectStore, UploadedPart } from "../object/store";
18
- import { assertWithinQuota, insertReservingQuota, updateSettlingQuota } from "../quota/quota";
28
+ import type { ObjectStore } from "../object/store";
29
+ import type { UploadedPart } from "../object/uploadedPart";
30
+ import type { StorageCeiling } from "../quota/ceiling";
31
+ import { assertWithinQuota, insertReservingQuota, type QuotaCheck, updateSettlingQuota } from "../quota/quota";
19
32
  import type {
20
33
  CompleteUploadInput,
21
34
  CopyObjectInput,
@@ -31,7 +44,7 @@ import type {
31
44
  * these dependencies from the request env and maps their results onto responses.
32
45
  *
33
46
  * **Request shape is not validated here.** Each route declares its own schemas with
34
- * `zValidator(target, Schema, validationHook)` and hands the handler the already-parsed value, so a
47
+ * `validate(target, Schema)` and hands the handler the already-parsed value, so a
35
48
  * malformed request is refused before a dependency is resolved or a row is read. What survives in
36
49
  * these handlers is everything a request schema cannot express — ownership, quota, upload state —
37
50
  * which is the whole of what they were ever really about.
@@ -41,28 +54,87 @@ import type {
41
54
  * addresses, so a key in a response body is a capability leak waiting for the first adopter who logs
42
55
  * their API responses.
43
56
  *
44
- * **A file you cannot see reads as missing.** `assertOwner` answers `storage/not_found` for a private
45
- * object owned by someone else and `storage/forbidden` only when the object is already public —
46
- * because a 403 on a private object confirms it exists, which is exactly the oracle an enumeration
47
- * attack wants. Public objects have nothing left to hide, so there the honest answer is the useful one.
57
+ * **Whose a file is, and who may reach it.** Every file is written with its owner, the organization in
58
+ * force, and a visibility — `private`, `organization` or `public` — from the project's policy. Every route
59
+ * asks core's access rules, and the adopter's permission hook if they supplied one, before it acts:
60
+ * reading is the visibility's, and changing a file — completing, aborting, copying, renaming,
61
+ * re-scoping, sharing, deleting — is its owner's, acting for its organization, or a role holding
62
+ * `storage:manage` there.
63
+ *
64
+ * **A file you cannot see reads as missing.** A caller who may not read a file gets `storage/not_found`,
65
+ * and `storage/forbidden` only when they may read it but not change it — because a 403 on a file they
66
+ * cannot see confirms it exists, which is exactly the oracle an enumeration attack wants. A file they
67
+ * can already read has nothing left to hide, so there the honest answer is the useful one.
48
68
  */
49
69
 
70
+ /** The power a role holds to edit, delete and re-scope any file in its own organization. */
71
+ export const STORAGE_MANAGE_POWER = "storage:manage";
72
+
73
+ /** The capability's name, as the permission hook sees it. */
74
+ const CAPABILITY = "storage";
75
+
50
76
  /** Everything a handler needs, all injectable. */
51
77
  export interface HandlerDeps {
52
78
  /** The storage database. */
53
79
  db: StorageDatabase;
54
80
  /** The object plane — presigning, the multipart lifecycle, and binding-backed reads. */
55
81
  store: ObjectStore;
56
- /** The resolved storage config: quota, multipart sizing, default visibility. */
82
+ /** The resolved storage config: quota, multipart sizing, the visibility policy. */
57
83
  config: StorageConfig;
58
- /** The authenticated caller from the core `AuthContext` seam, or null for an unauthenticated read. */
59
- ownerId: string | null;
84
+ /** Who is asking: the signed-in user from `AuthContext`, if any, and the organization they act for. */
85
+ caller: AccessCaller;
86
+ /** The adopter's permission hook, if they supplied one. */
87
+ permission?: PermissionHook;
88
+ /** The Worker env, handed to the permission hook. */
89
+ env: Record<string, unknown>;
60
90
  /** Mints an object id. */
61
91
  newId: () => string;
62
92
  /** Mints a share token. */
63
93
  newToken: () => string;
64
94
  /** The current time. */
65
95
  now: () => Date;
96
+ /**
97
+ * The byte ceiling for this request's writes, and whose bytes it covers.
98
+ *
99
+ * Absent means the configured `quota.bytesPerOwner`, per owner, which is what a project composing no
100
+ * entitlement provider has always had. The default resolver fills it from the `storageBytes` meter when the
101
+ * provider enforces one, so a plan's quota — or a subject's pinned one, or `unrestricted` — becomes the
102
+ * ceiling, summed across the organization when the plan is an organization's, and an advisory meter leaves
103
+ * the configured number in force.
104
+ */
105
+ quotaLimit?: () => Promise<StorageCeiling>;
106
+ }
107
+
108
+ /**
109
+ * The quota a write of a row held for `ownerId` in `organizationId` is checked against: the ceiling, and
110
+ * whose bytes it sums. The resolved ceiling where the request has one, the configured one otherwise.
111
+ *
112
+ * **A ceiling that covers an organization covers only that organization's rows**, so a row about to be held
113
+ * for a different one — or for none — would sit outside the very sum it is checked against, and never count.
114
+ * That is refused rather than written: it means the billing subject and the organization in force disagree,
115
+ * which is wiring for the adopter to fix, and under-counting has no recovery.
116
+ */
117
+ async function quotaFor(
118
+ deps: HandlerDeps,
119
+ ownerId: string | null,
120
+ organizationId: string | null,
121
+ ): Promise<Pick<QuotaCheck, "ownerId" | "organizationId" | "limitBytes" | "metered">> {
122
+ const ceiling = deps.quotaLimit
123
+ ? await deps.quotaLimit()
124
+ : { limitBytes: deps.config.quota.bytesPerOwner, tenant: null, metered: false };
125
+ const { metered } = ceiling;
126
+ if (ceiling.tenant === null || ceiling.limitBytes === null || ownerId === null) {
127
+ return { ownerId, limitBytes: ceiling.limitBytes, metered };
128
+ }
129
+ if (organizationId !== ceiling.tenant) {
130
+ throw new InternalError({
131
+ message: "This file cannot be counted against the plan it is billed to, so nothing was written.",
132
+ action:
133
+ "Make the payments subject resolver and the organization in force agree — both should answer the organization the caller acts for.",
134
+ detail: `The storageBytes ceiling covers organization ${ceiling.tenant}; the file would be held for ${organizationId ?? "no organization"}.`,
135
+ });
136
+ }
137
+ return { ownerId, organizationId: ceiling.tenant, limitBytes: ceiling.limitBytes, metered };
66
138
  }
67
139
 
68
140
  /** The client-facing shape of a stored file. Deliberately without `key` and `uploadId`. */
@@ -70,9 +142,10 @@ export interface StorageObjectView {
70
142
  id: string;
71
143
  path: string;
72
144
  ownerId: string | null;
145
+ organizationId: string | null;
73
146
  contentType: string;
74
147
  size: number | null;
75
- visibility: "private" | "public";
148
+ visibility: StorageObject["visibility"];
76
149
  checksum: string | null;
77
150
  status: "pending" | "stored" | "failed";
78
151
  createdAt: Date;
@@ -106,12 +179,20 @@ export interface ShareView {
106
179
  createdAt: Date;
107
180
  }
108
181
 
109
- /** Drop the server-only fields. The single place a row becomes something a client may see. */
110
- function view(object: StorageObject): StorageObjectView {
182
+ /**
183
+ * Drop the server-only fields. The single place a row becomes something a client may see.
184
+ *
185
+ * The owner and organization are the caller's to see only when they act for the file's organization
186
+ * ({@link disclosedTenancy}). A public file reached from anywhere else names neither: reading a file is not
187
+ * learning which organization its owner belongs to.
188
+ */
189
+ function view(object: StorageObject, caller: AccessCaller): StorageObjectView {
190
+ const tenancy = disclosedTenancy(object, caller);
111
191
  return {
112
192
  id: object.id,
113
193
  path: object.path,
114
- ownerId: object.ownerId,
194
+ ownerId: tenancy.ownerId,
195
+ organizationId: tenancy.organizationId,
115
196
  contentType: object.contentType,
116
197
  size: object.size,
117
198
  visibility: object.visibility,
@@ -128,33 +209,56 @@ async function findObject(deps: HandlerDeps, id: string): Promise<StorageObject
128
209
  return row ? StorageObject.parse(row) : null;
129
210
  }
130
211
 
131
- /** Load one row or throw `storage/not_found`. */
212
+ /**
213
+ * Load one row or throw `storage/not_found`, asking nobody whether the caller may see it — for a share
214
+ * link, where the token is the credential and the rules have already been spent by whoever minted it.
215
+ */
132
216
  async function loadObject(deps: HandlerDeps, id: string): Promise<StorageObject> {
133
217
  const object = await findObject(deps, id);
134
218
  if (!object) throw new StorageNotFoundError({ detail: `no storage object ${id}` });
135
219
  return object;
136
220
  }
137
221
 
138
- /**
139
- * Require the caller to own the object. A private object they do not own is reported as **missing**,
140
- * so the route cannot be used to test whether an id exists. A public object is reported as
141
- * **forbidden**, because its existence is already public knowledge and "missing" would just be a lie.
142
- */
143
- function assertOwner(object: StorageObject, ownerId: string | null): void {
144
- if (ownerId !== null && object.ownerId === ownerId) return;
145
- if (object.visibility === "public") {
146
- throw new StorageForbiddenError({ detail: `object ${object.id} is owned by ${object.ownerId ?? "the system"}` });
222
+ /** What the caller may do with one file, asking the rules and the hook. */
223
+ function levelOf(deps: HandlerDeps, object: StorageObject): Promise<AccessLevel> {
224
+ return accessLevel({
225
+ record: object,
226
+ caller: deps.caller,
227
+ capability: CAPABILITY,
228
+ managePower: STORAGE_MANAGE_POWER,
229
+ hook: deps.permission,
230
+ env: deps.env,
231
+ });
232
+ }
233
+
234
+ /** Who is asking, for a log line. */
235
+ function callerName(deps: HandlerDeps): string {
236
+ return deps.caller.userId ?? "an anonymous caller";
237
+ }
238
+
239
+ /** Load a file the caller may read, or answer not found — for a file that is absent and one they cannot see alike. */
240
+ async function loadReadable(deps: HandlerDeps, id: string): Promise<StorageObject> {
241
+ const object = await findObject(deps, id);
242
+ if (!object || (await levelOf(deps, object)) === "none") {
243
+ throw new StorageNotFoundError({ detail: `no storage object ${id} readable by ${callerName(deps)}` });
147
244
  }
148
- throw new StorageNotFoundError({ detail: `object ${object.id} is not owned by ${ownerId ?? "an anonymous caller"}` });
245
+ return object;
149
246
  }
150
247
 
151
- /** Require the caller to be allowed to *read* the object: it is public, or it is theirs. */
152
- function assertReadable(object: StorageObject, ownerId: string | null): void {
153
- if (object.visibility === "public") return;
154
- if (ownerId !== null && object.ownerId === ownerId) return;
155
- throw new StorageNotFoundError({
156
- detail: `object ${object.id} is not readable by ${ownerId ?? "an anonymous caller"}`,
157
- });
248
+ /**
249
+ * Load a file the caller may change. Not found when they cannot read it; forbidden only when they can,
250
+ * because by then they already know it exists.
251
+ */
252
+ async function loadWritable(deps: HandlerDeps, id: string): Promise<StorageObject> {
253
+ const object = await findObject(deps, id);
254
+ const level = object ? await levelOf(deps, object) : "none";
255
+ if (!object || level === "none") {
256
+ throw new StorageNotFoundError({ detail: `no storage object ${id} readable by ${callerName(deps)}` });
257
+ }
258
+ if (level !== "write") {
259
+ throw new StorageForbiddenError({ detail: `${callerName(deps)} may read object ${id} but not change it` });
260
+ }
261
+ return object;
158
262
  }
159
263
 
160
264
  /** Require the object's bytes to actually be there. A `pending` row has a record but no content. */
@@ -185,11 +289,14 @@ async function saveObject(deps: HandlerDeps, object: StorageObject): Promise<Sto
185
289
  */
186
290
  export async function initUpload(deps: HandlerDeps, input: CreateUploadInput): Promise<UploadInitResult> {
187
291
  const now = deps.now();
292
+ // Whose it is comes from the request, never the body, and a level the policy does not allow is
293
+ // refused before a byte of R2 is reserved.
294
+ const organizationId = deps.caller.acting?.organizationId ?? null;
295
+ const visibility = resolveVisibility(deps.config.visibility, input.visibility, organizationId);
188
296
 
189
297
  await assertWithinQuota({
190
298
  db: deps.db,
191
- ownerId: deps.ownerId,
192
- limitBytes: deps.config.quota.bytesPerOwner,
299
+ ...(await quotaFor(deps, deps.caller.userId, organizationId)),
193
300
  additionalBytes: input.size,
194
301
  });
195
302
 
@@ -219,10 +326,11 @@ export async function initUpload(deps: HandlerDeps, input: CreateUploadInput): P
219
326
  id: deps.newId(),
220
327
  key,
221
328
  path: input.path,
222
- ownerId: deps.ownerId,
329
+ ownerId: deps.caller.userId,
330
+ organizationId,
223
331
  contentType: input.contentType,
224
332
  size: input.size,
225
- visibility: input.visibility ?? deps.config.defaultVisibility,
333
+ visibility,
226
334
  checksum: null,
227
335
  status: "pending",
228
336
  uploadId,
@@ -232,8 +340,7 @@ export async function initUpload(deps: HandlerDeps, input: CreateUploadInput): P
232
340
  try {
233
341
  await insertReservingQuota({
234
342
  db: deps.db,
235
- ownerId: deps.ownerId,
236
- limitBytes: deps.config.quota.bytesPerOwner,
343
+ ...(await quotaFor(deps, deps.caller.userId, organizationId)),
237
344
  additionalBytes: input.size,
238
345
  record: StorageObject.encode(object),
239
346
  });
@@ -244,7 +351,7 @@ export async function initUpload(deps: HandlerDeps, input: CreateUploadInput): P
244
351
  throw error;
245
352
  }
246
353
 
247
- return { object: view(object), upload };
354
+ return { object: view(object, deps.caller), upload };
248
355
  }
249
356
 
250
357
  /**
@@ -274,11 +381,10 @@ export async function completeUpload(
274
381
  id: string,
275
382
  input: CompleteUploadInput,
276
383
  ): Promise<StorageObjectView> {
277
- const object = await loadObject(deps, id);
278
- assertOwner(object, deps.ownerId);
384
+ const object = await loadWritable(deps, id);
279
385
  // Completing twice is a no-op rather than an error: a client that retried a dropped response gets
280
386
  // the same answer, which is what makes the route safe to retry at all.
281
- if (object.status === "stored") return view(object);
387
+ if (object.status === "stored") return view(object, deps.caller);
282
388
  if (object.status !== "pending") {
283
389
  throw new StorageUploadIncompleteError({ detail: `object ${id} is ${object.status} and cannot be completed` });
284
390
  }
@@ -318,13 +424,15 @@ export async function completeUpload(
318
424
  // An upload smaller than it declared claims nothing further, so it is written unconditionally. A
319
425
  // quota an adopter lowered under an in-flight upload must not turn a shrinking completion into a
320
426
  // deletion of bytes the owner was, at reservation time, granted.
321
- if (overshoot <= 0) return view(await saveObject(deps, settled));
427
+ if (overshoot <= 0) return view(await saveObject(deps, settled), deps.caller);
322
428
 
429
+ // Resolved before the settlement's `try`: a ceiling that cannot be read, or that covers another
430
+ // organization, refuses this request — it is not a verdict on the bytes, so it must not discard them.
431
+ const quota = await quotaFor(deps, object.ownerId, object.organizationId);
323
432
  try {
324
433
  await updateSettlingQuota({
325
434
  db: deps.db,
326
- ownerId: object.ownerId,
327
- limitBytes: deps.config.quota.bytesPerOwner,
435
+ ...quota,
328
436
  additionalBytes: overshoot,
329
437
  record: StorageObject.encode(settled),
330
438
  });
@@ -337,7 +445,7 @@ export async function completeUpload(
337
445
  await saveObject(deps, { ...object, status: "failed", uploadId: null, updatedAt: deps.now() });
338
446
  throw error;
339
447
  }
340
- return view(settled);
448
+ return view(settled, deps.caller);
341
449
  }
342
450
 
343
451
  /**
@@ -355,8 +463,7 @@ export async function completeUpload(
355
463
  * than sheltered forever by a row that counts toward no quota (`workflows/sweep.ts`).
356
464
  */
357
465
  export async function abortUpload(deps: HandlerDeps, id: string): Promise<StorageObjectView> {
358
- const object = await loadObject(deps, id);
359
- assertOwner(object, deps.ownerId);
466
+ const object = await loadWritable(deps, id);
360
467
  if (object.status === "stored") {
361
468
  throw new StorageUploadIncompleteError({
362
469
  message: "That upload already finished.",
@@ -369,7 +476,10 @@ export async function abortUpload(deps: HandlerDeps, id: string): Promise<Storag
369
476
  // too, so aborting never leaves an object the sweep has to find later.
370
477
  await deps.store.delete(object.key);
371
478
 
372
- return view(await saveObject(deps, { ...object, status: "failed", uploadId: null, updatedAt: deps.now() }));
479
+ return view(
480
+ await saveObject(deps, { ...object, status: "failed", uploadId: null, updatedAt: deps.now() }),
481
+ deps.caller,
482
+ );
373
483
  }
374
484
 
375
485
  /** Where a resuming client stands: what R2 already holds, and a live URL for everything it does not. */
@@ -395,8 +505,7 @@ export interface UploadPartsResult {
395
505
  * its parts discarded — re-presigning against either would hand out URLs addressing nothing.
396
506
  */
397
507
  export async function listUploadParts(deps: HandlerDeps, id: string): Promise<UploadPartsResult> {
398
- const object = await loadObject(deps, id);
399
- assertOwner(object, deps.ownerId);
508
+ const object = await loadWritable(deps, id);
400
509
  const uploadId = object.uploadId;
401
510
  if (object.status !== "pending" || !uploadId) {
402
511
  throw new StorageUploadIncompleteError({
@@ -460,8 +569,10 @@ function decodeCursor(value: string | undefined): ListCursor | null {
460
569
  const DEFAULT_LIST_LIMIT = 50;
461
570
 
462
571
  /**
463
- * One page of the caller's files, ordered by logical path. Scoped to the authenticated owner: there
464
- * is no way to list another owner's files, and no parameter that could be made to.
572
+ * One page of the files the caller may see, ordered by logical path: their own, their organization's,
573
+ * and — only when `includePublic=true` — every public file. The rules run in SQL, so there is no
574
+ * parameter that lists anyone else's private files; the hook is asked about each row on the page and may
575
+ * remove one, so a page can come back short while its cursor still says there is more.
465
576
  */
466
577
  export async function listObjects(
467
578
  deps: HandlerDeps,
@@ -473,7 +584,12 @@ export async function listObjects(
473
584
  let statement = deps.db
474
585
  .selectFrom(STORAGE_OBJECTS_TABLE)
475
586
  .selectAll()
476
- .where("ownerId", "=", deps.ownerId)
587
+ .where(
588
+ readablePredicate(deps.caller, {
589
+ managePower: STORAGE_MANAGE_POWER,
590
+ includePublic: query.includePublic === "true",
591
+ }),
592
+ )
477
593
  .orderBy("path", "asc")
478
594
  .orderBy("id", "asc")
479
595
  // One extra row is what distinguishes "this page is full" from "there is another page", without
@@ -494,16 +610,23 @@ export async function listObjects(
494
610
 
495
611
  const rows = await statement.execute();
496
612
  const page = rows.slice(0, limit).map((row) => StorageObject.parse(row));
497
- const objects = page.map(view);
613
+ // The cursor is the page's, computed before the hook runs: a row the hook removes is still a row the
614
+ // next page must start after.
615
+ const kept = await keepReadable(page, {
616
+ capability: CAPABILITY,
617
+ caller: deps.caller,
618
+ hook: deps.permission,
619
+ env: deps.env,
620
+ });
621
+ const objects = kept.map((object) => view(object, deps.caller));
498
622
  if (rows.length <= limit) return { objects };
499
623
  const last = page[page.length - 1];
500
624
  return last ? { objects, cursor: encodeCursor({ path: last.path, id: last.id }) } : { objects };
501
625
  }
502
626
 
503
- /** Load an object for reading, enforcing public-or-owner and that its bytes exist. */
627
+ /** Load an object for reading, enforcing who may read it and that its bytes exist. */
504
628
  export async function readableObject(deps: HandlerDeps, id: string): Promise<StorageObject> {
505
- const object = await loadObject(deps, id);
506
- assertReadable(object, deps.ownerId);
629
+ const object = await loadReadable(deps, id);
507
630
  assertStored(object);
508
631
  return object;
509
632
  }
@@ -524,21 +647,28 @@ export async function presignObject(deps: HandlerDeps, id: string): Promise<{ ur
524
647
  return { url, expiresInSeconds: PRESIGNED_URL_TTL_SECONDS };
525
648
  }
526
649
 
527
- /** Rename a file, change who may read it, or both. The key never moves — only the row changes. */
650
+ /**
651
+ * Rename a file, change who may read it, or both. The key never moves — only the row changes. A level the
652
+ * policy does not allow is refused, and `organization` on a file written with no organization is too.
653
+ */
528
654
  export async function updateObject(
529
655
  deps: HandlerDeps,
530
656
  id: string,
531
657
  input: UpdateObjectInput,
532
658
  ): Promise<StorageObjectView> {
533
- const object = await loadObject(deps, id);
534
- assertOwner(object, deps.ownerId);
659
+ const object = await loadWritable(deps, id);
660
+ const visibility =
661
+ input.visibility === undefined
662
+ ? object.visibility
663
+ : resolveVisibility(deps.config.visibility, input.visibility, object.organizationId);
535
664
  return view(
536
665
  await saveObject(deps, {
537
666
  ...object,
538
667
  path: input.path ?? object.path,
539
- visibility: input.visibility ?? object.visibility,
668
+ visibility,
540
669
  updatedAt: deps.now(),
541
670
  }),
671
+ deps.caller,
542
672
  );
543
673
  }
544
674
 
@@ -546,23 +676,32 @@ export async function updateObject(
546
676
  * Copy a file server-side. The bytes are copied by R2 and never enter the Worker; the copy is a new
547
677
  * object with its own id, its own key, and its own share links — it is not an alias.
548
678
  *
549
- * Owner-scoped, like every other mutating route: you may copy your own files. Copying a *public* file
679
+ * A change, like every other mutating route: you may copy a file you may change. Copying a *public* file
550
680
  * you do not own is a plausible feature and deliberately not this one — it would let any reader
551
681
  * duplicate bytes into their own quota on the owner's storage bill, which is a decision an adopter
552
- * should make explicitly rather than inherit.
682
+ * should make explicitly rather than inherit. The copy is the caller's, in the organization they act for.
553
683
  */
554
684
  export async function copyObject(deps: HandlerDeps, id: string, input: CopyObjectInput): Promise<StorageObjectView> {
555
- const source = await loadObject(deps, id);
556
- assertOwner(source, deps.ownerId);
685
+ const source = await loadWritable(deps, id);
557
686
  assertStored(source);
558
687
 
688
+ const organizationId = deps.caller.acting?.organizationId ?? null;
559
689
  await assertWithinQuota({
560
690
  db: deps.db,
561
- ownerId: deps.ownerId,
562
- limitBytes: deps.config.quota.bytesPerOwner,
691
+ ...(await quotaFor(deps, deps.caller.userId, organizationId)),
563
692
  additionalBytes: source.size ?? 0,
564
693
  });
565
694
 
695
+ // A copy starts private even when the source was public. Republishing is a decision, and a copy made to
696
+ // take a private working copy of your own public file should not re-publish it by default. Where the policy
697
+ // allows no private file, it starts at the policy's default instead. Either way the level goes through the
698
+ // one check every write does, so the kit never writes a file outside its own policy.
699
+ const visibility = resolveVisibility(
700
+ deps.config.visibility,
701
+ deps.config.visibility.allowed.includes("private") ? "private" : undefined,
702
+ organizationId,
703
+ );
704
+
566
705
  const key = deriveObjectKey();
567
706
  await deps.store.copy(source.key, key);
568
707
  const now = deps.now();
@@ -571,10 +710,9 @@ export async function copyObject(deps: HandlerDeps, id: string, input: CopyObjec
571
710
  id: deps.newId(),
572
711
  key,
573
712
  path: input.path,
574
- ownerId: deps.ownerId,
575
- // A copy starts private even when the source was public. Republishing is a decision, and a copy
576
- // made to take a private working copy of your own public file should not re-publish it by default.
577
- visibility: "private",
713
+ ownerId: deps.caller.userId,
714
+ organizationId,
715
+ visibility,
578
716
  status: "stored",
579
717
  uploadId: null,
580
718
  createdAt: now,
@@ -585,8 +723,7 @@ export async function copyObject(deps: HandlerDeps, id: string, input: CopyObjec
585
723
  // owner, and concurrent copies of one 1 GiB file against a 1 GiB quota must not all pass.
586
724
  await insertReservingQuota({
587
725
  db: deps.db,
588
- ownerId: deps.ownerId,
589
- limitBytes: deps.config.quota.bytesPerOwner,
726
+ ...(await quotaFor(deps, deps.caller.userId, organizationId)),
590
727
  additionalBytes: source.size ?? 0,
591
728
  record: StorageObject.encode(copy),
592
729
  });
@@ -596,7 +733,7 @@ export async function copyObject(deps: HandlerDeps, id: string, input: CopyObjec
596
733
  await deps.store.delete(key).catch(() => {});
597
734
  throw error;
598
735
  }
599
- return view(copy);
736
+ return view(copy, deps.caller);
600
737
  }
601
738
 
602
739
  /**
@@ -608,8 +745,7 @@ export async function copyObject(deps: HandlerDeps, id: string, input: CopyObjec
608
745
  * sweep collects an object whose row went first.
609
746
  */
610
747
  export async function deleteObject(deps: HandlerDeps, id: string): Promise<{ id: string; deleted: true }> {
611
- const object = await loadObject(deps, id);
612
- assertOwner(object, deps.ownerId);
748
+ const object = await loadWritable(deps, id);
613
749
  if (object.uploadId) await deps.store.abortMultipart(object.key, object.uploadId).catch(() => {});
614
750
  await deps.store.delete(object.key).catch(() => {});
615
751
  await deps.db.deleteFrom(STORAGE_OBJECTS_TABLE).where("id", "=", id).execute();
@@ -618,8 +754,7 @@ export async function deleteObject(deps: HandlerDeps, id: string): Promise<{ id:
618
754
 
619
755
  /** Mint a revocable share link for one file. */
620
756
  export async function createShare(deps: HandlerDeps, id: string, input: CreateShareInput): Promise<ShareView> {
621
- const object = await loadObject(deps, id);
622
- assertOwner(object, deps.ownerId);
757
+ const object = await loadWritable(deps, id);
623
758
  assertStored(object);
624
759
 
625
760
  const now = deps.now();
@@ -645,8 +780,7 @@ export async function revokeShare(deps: HandlerDeps, token: string): Promise<{ t
645
780
  const row = await deps.db.selectFrom(STORAGE_SHARES_TABLE).selectAll().where("token", "=", token).executeTakeFirst();
646
781
  if (!row) throw new StorageNotFoundError({ detail: `no share token ${token}` });
647
782
  const share = StorageShare.parse(row);
648
- const object = await loadObject(deps, share.objectId);
649
- assertOwner(object, deps.ownerId);
783
+ await loadWritable(deps, share.objectId);
650
784
  if (share.revokedAt) return { token, revokedAt: share.revokedAt };
651
785
 
652
786
  const revokedAt = deps.now();