@pithy-sh/storage 0.3.0 → 0.5.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 (84) 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.d.ts +4 -3
  12. package/dist/error/errors.d.ts.map +1 -1
  13. package/dist/error/errors.js +2 -2
  14. package/dist/http/handlers.d.ts +45 -14
  15. package/dist/http/handlers.d.ts.map +1 -1
  16. package/dist/http/handlers.js +169 -66
  17. package/dist/http/responses.d.ts +6 -0
  18. package/dist/http/responses.d.ts.map +1 -1
  19. package/dist/http/responses.js +2 -1
  20. package/dist/http/routes.d.ts +13 -2
  21. package/dist/http/routes.d.ts.map +1 -1
  22. package/dist/http/routes.js +37 -9
  23. package/dist/http/schemas.d.ts +6 -0
  24. package/dist/http/schemas.d.ts.map +1 -1
  25. package/dist/http/schemas.js +6 -5
  26. package/dist/http/scopes.d.ts +25 -0
  27. package/dist/http/scopes.d.ts.map +1 -0
  28. package/dist/http/scopes.js +32 -0
  29. package/dist/http/serve.d.ts +5 -2
  30. package/dist/http/serve.d.ts.map +1 -1
  31. package/dist/index.d.ts +2 -0
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +5 -3
  34. package/dist/migrations/0002_ownership.d.ts +5 -0
  35. package/dist/migrations/0002_ownership.d.ts.map +1 -0
  36. package/dist/migrations/0002_ownership.js +114 -0
  37. package/dist/object/cloudflare.d.ts +2 -1
  38. package/dist/object/cloudflare.d.ts.map +1 -1
  39. package/dist/object/cloudflare.js +2 -2
  40. package/dist/provision/provisionStorage.d.ts +14 -2
  41. package/dist/provision/provisionStorage.d.ts.map +1 -1
  42. package/dist/provision/provisionStorage.js +19 -4
  43. package/dist/provision/resolveStorageConfig.js +1 -1
  44. package/dist/quota/ceiling.d.ts +36 -0
  45. package/dist/quota/ceiling.d.ts.map +1 -0
  46. package/dist/quota/ceiling.js +31 -0
  47. package/dist/quota/quota.d.ts +24 -7
  48. package/dist/quota/quota.d.ts.map +1 -1
  49. package/dist/quota/quota.js +40 -12
  50. package/dist/secret/bundleToken.d.ts +24 -0
  51. package/dist/secret/bundleToken.d.ts.map +1 -0
  52. package/dist/secret/bundleToken.js +74 -0
  53. package/dist/secret/registry.d.ts +5 -1
  54. package/dist/secret/registry.d.ts.map +1 -1
  55. package/dist/secret/registry.js +7 -3
  56. package/dist/seeds/example.d.ts.map +1 -1
  57. package/dist/seeds/example.js +3 -0
  58. package/dist/test-utils/liveStorage.d.ts.map +1 -1
  59. package/dist/test-utils/liveStorage.js +5 -2
  60. package/dist/version.generated.d.ts +1 -1
  61. package/dist/version.generated.js +1 -1
  62. package/package.json +5 -5
  63. package/pithy.manifest.json +20 -10
  64. package/src/capability.ts +52 -8
  65. package/src/config/config.ts +24 -6
  66. package/src/data/storageObject.ts +22 -6
  67. package/src/error/errors.ts +6 -5
  68. package/src/http/handlers.ts +212 -79
  69. package/src/http/responses.ts +13 -1
  70. package/src/http/routes.ts +64 -10
  71. package/src/http/schemas.ts +10 -4
  72. package/src/http/scopes.ts +39 -0
  73. package/src/http/serve.ts +5 -2
  74. package/src/index.ts +2 -0
  75. package/src/migrations/0002_ownership.ts +176 -0
  76. package/src/object/cloudflare.ts +2 -2
  77. package/src/provision/provisionStorage.ts +22 -3
  78. package/src/quota/ceiling.ts +44 -0
  79. package/src/quota/quota.ts +63 -20
  80. package/src/secret/bundleToken.ts +81 -0
  81. package/src/secret/registry.ts +6 -8
  82. package/src/seeds/example.ts +3 -0
  83. package/src/test-utils/liveStorage.ts +3 -6
  84. package/src/version.generated.ts +1 -1
@@ -0,0 +1,36 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
4
+ import type { Context } from "hono";
5
+ import type { StorageConfig } from "../config/config";
6
+ /** The byte ceiling one request's writes are held to, and whose bytes it is the whole of. */
7
+ export interface StorageCeiling {
8
+ /** The ceiling in bytes. Null is unlimited. */
9
+ limitBytes: number | null;
10
+ /**
11
+ * The organization the ceiling covers, or null when it is the caller's own. Set, every byte stored for
12
+ * that organization counts against it, whoever uploaded it — an organization's plan is the organization's.
13
+ */
14
+ tenant: string | null;
15
+ /**
16
+ * Whether the number is an enforced `storageBytes` meter's. A refusal is then the plan's —
17
+ * `payments/quota_exceeded` at 402, the remedy a bigger tier — and otherwise the configured
18
+ * `bytesPerOwner`'s, `storage/quota_exceeded` at 413.
19
+ */
20
+ metered: boolean;
21
+ }
22
+ /**
23
+ * The byte ceiling for one request: the `storageBytes` quota where an entitlement provider enforces that
24
+ * meter, the configured `quota.bytesPerOwner` where it does not.
25
+ *
26
+ * **Configured behavior is the fallback, never replaced by surprise.** With no provider composed, or one that
27
+ * leaves `storageBytes` advisory, this is `bytesPerOwner` exactly, counted per owner — which is what every
28
+ * project had before plans could say how much a customer may store. Enforced, it is the billing subject's
29
+ * effective quota: their plan's number, a number pinned for them, or `null` — unlimited — for an
30
+ * `unrestricted` subject. Under organization billing that subject is the organization, and so is the sum.
31
+ *
32
+ * A provider whose read fails refuses the write rather than serving it unbounded: `meterLimit` throws, and
33
+ * the request fails with it. Over-counting is recoverable; under-counting is not.
34
+ */
35
+ export declare function storageCeiling(c: Context<PithyHonoEnv>, config: StorageConfig): Promise<StorageCeiling>;
36
+ //# sourceMappingURL=ceiling.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ceiling.d.ts","sourceRoot":"","sources":["../../src/quota/ceiling.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAE7E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEtD,6FAA6F;AAC7F,MAAM,WAAW,cAAc;IAC7B,+CAA+C;IAC/C,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B;;;OAGG;IACH,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB;;;;OAIG;IACH,OAAO,EAAE,OAAO,CAAC;CAClB;AAED;;;;;;;;;;;;GAYG;AACH,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,aAAa,GAAG,OAAO,CAAC,cAAc,CAAC,CAK7G"}
@@ -0,0 +1,31 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { meterLimit } from "@pithy-sh/core/src/entitlement/allowance";
4
+ //#region src/quota/ceiling.ts
5
+ /**
6
+ * The byte ceiling for one request: the `storageBytes` quota where an entitlement provider enforces that
7
+ * meter, the configured `quota.bytesPerOwner` where it does not.
8
+ *
9
+ * **Configured behavior is the fallback, never replaced by surprise.** With no provider composed, or one that
10
+ * leaves `storageBytes` advisory, this is `bytesPerOwner` exactly, counted per owner — which is what every
11
+ * project had before plans could say how much a customer may store. Enforced, it is the billing subject's
12
+ * effective quota: their plan's number, a number pinned for them, or `null` — unlimited — for an
13
+ * `unrestricted` subject. Under organization billing that subject is the organization, and so is the sum.
14
+ *
15
+ * A provider whose read fails refuses the write rather than serving it unbounded: `meterLimit` throws, and
16
+ * the request fails with it. Over-counting is recoverable; under-counting is not.
17
+ */
18
+ async function storageCeiling(c, config) {
19
+ const ceiling = await meterLimit(c, "storageBytes");
20
+ return ceiling.enforced ? {
21
+ limitBytes: ceiling.limit,
22
+ tenant: ceiling.tenant,
23
+ metered: true
24
+ } : {
25
+ limitBytes: config.quota.bytesPerOwner,
26
+ tenant: null,
27
+ metered: false
28
+ };
29
+ }
30
+ //#endregion
31
+ export { storageCeiling };
@@ -40,6 +40,10 @@ import { type StorageDatabase } from "../data/tables";
40
40
  *
41
41
  * A `null` limit is unlimited and skips the query entirely. A `null` owner (a system object) has no
42
42
  * quota — there is no principal to bill it to.
43
+ *
44
+ * **Whose bytes are summed is the ceiling's to say.** A configured `bytesPerOwner` is per owner. An
45
+ * organization's plan is the organization's, so a check carrying `organizationId` sums every row held for
46
+ * that organization, whoever uploaded it — counted per member, the plan's number would be per member.
43
47
  */
44
48
  /** What a quota check needs. */
45
49
  export interface QuotaCheck {
@@ -47,8 +51,19 @@ export interface QuotaCheck {
47
51
  db: StorageDatabase;
48
52
  /** The owner the bytes are billed to. Null is a system object, which no quota applies to. */
49
53
  ownerId: string | null;
50
- /** The configured per-owner ceiling in bytes. Null is unlimited. */
54
+ /**
55
+ * The organization the ceiling covers, when it is an organization's. Set, the sum is every row held for it
56
+ * rather than the owner's alone. The row being written must be held for it too, or it would never count.
57
+ */
58
+ organizationId?: string;
59
+ /** The ceiling in bytes — the configured `bytesPerOwner`, or a plan's. Null is unlimited. */
51
60
  limitBytes: number | null;
61
+ /**
62
+ * Whether `limitBytes` is an enforced `storageBytes` meter's. True, a refusal is the plan's own —
63
+ * `payments/quota_exceeded` at 402, as the `emails` and `mediaItems` meters refuse — because the remedy
64
+ * is a bigger tier or a pinned number, not a config edit. Absent or false, it is `storage/quota_exceeded`.
65
+ */
66
+ metered?: boolean;
52
67
  /** The bytes this upload declares — what the pending row is about to reserve. */
53
68
  additionalBytes: number;
54
69
  }
@@ -76,12 +91,14 @@ export interface QuotaSettlement extends QuotaCheck {
76
91
  */
77
92
  export declare const QUOTA_COUNTED_STATUSES: readonly StorageObjectStatus[];
78
93
  /**
79
- * Bytes an owner currently holds: every `pending` reservation plus every `stored` object. `failed`
80
- * rows are excluded — they hold no bytes and reserve nothing.
94
+ * Bytes an owner currently holds — or, with `organizationId`, every byte held for that organization:
95
+ * every `pending` reservation plus every `stored` object. `failed` rows are excluded — they hold no bytes
96
+ * and reserve nothing.
81
97
  */
82
- export declare function usedBytes(db: StorageDatabase, ownerId: string): Promise<number>;
98
+ export declare function usedBytes(db: StorageDatabase, ownerId: string, organizationId?: string): Promise<number>;
83
99
  /**
84
- * Throw `storage/quota_exceeded` when this upload would put the owner over their limit. The
100
+ * Throw `storage/quota_exceeded` when this upload would put the owner over their limit — or
101
+ * `payments/quota_exceeded` when the limit is a metered plan's ({@link QuotaCheck.metered}). The
85
102
  * comparison is `used + additional > limit`, so an upload landing exactly on the limit is allowed —
86
103
  * a quota is a ceiling you may reach, not one you must stay under.
87
104
  *
@@ -93,7 +110,7 @@ export declare function usedBytes(db: StorageDatabase, ownerId: string): Promise
93
110
  export declare function assertWithinQuota(check: QuotaCheck): Promise<void>;
94
111
  /**
95
112
  * Insert a storage row **only if** it fits inside the owner's quota, and throw
96
- * `storage/quota_exceeded` when it does not.
113
+ * `storage/quota_exceeded` (or a metered plan's `payments/quota_exceeded`) when it does not.
97
114
  *
98
115
  * The sum and the write are one statement — `INSERT … SELECT <values> WHERE (SELECT sum(size) …) <=
99
116
  * limit - additional` — because two statements cannot be made to hold a reservation without a
@@ -107,7 +124,7 @@ export declare function assertWithinQuota(check: QuotaCheck): Promise<void>;
107
124
  export declare function insertReservingQuota(reservation: QuotaReservation): Promise<void>;
108
125
  /**
109
126
  * Rewrite one row **only if** the bytes it newly claims still fit inside the owner's quota, and throw
110
- * `storage/quota_exceeded` when they do not.
127
+ * `storage/quota_exceeded` (or a metered plan's `payments/quota_exceeded`) when they do not.
111
128
  *
112
129
  * This is {@link insertReservingQuota}'s other half, and it exists for the identical reason. A
113
130
  * completion measures what R2 actually holds against what the pending row reserved, and the difference
@@ -1 +1 @@
1
- {"version":3,"file":"quota.d.ts","sourceRoot":"","sources":["../../src/quota/quota.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,gBAAgB,EAAE,mBAAmB,EA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CAAC,UAAU,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC,CAmCpF"}
@@ -2,6 +2,7 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
  import { StorageQuotaExceededError } from "../error/errors.js";
4
4
  import { STORAGE_OBJECTS_TABLE } from "../data/tables.js";
5
+ import { PithyError } from "@pithy-sh/core/src/error/pithyError";
5
6
  import { sql } from "kysely";
6
7
  //#region src/quota/quota.ts
7
8
  /**
@@ -14,12 +15,18 @@ import { sql } from "kysely";
14
15
  * (`workflows/sweep.ts`).
15
16
  */
16
17
  const QUOTA_COUNTED_STATUSES = ["pending", "stored"];
18
+ /** The column and value a sum is keyed on: the organization's rows where the ceiling is one's, the owner's otherwise. */
19
+ function heldBy(ownerId, organizationId) {
20
+ return organizationId === void 0 ? ["ownerId", ownerId] : ["organizationId", organizationId];
21
+ }
17
22
  /**
18
- * Bytes an owner currently holds: every `pending` reservation plus every `stored` object. `failed`
19
- * rows are excluded — they hold no bytes and reserve nothing.
23
+ * Bytes an owner currently holds — or, with `organizationId`, every byte held for that organization:
24
+ * every `pending` reservation plus every `stored` object. `failed` rows are excluded — they hold no bytes
25
+ * and reserve nothing.
20
26
  */
21
- async function usedBytes(db, ownerId) {
22
- const row = await db.selectFrom(STORAGE_OBJECTS_TABLE).select(sql`coalesce(sum(size), 0)`.as("used")).where("ownerId", "=", ownerId).where("status", "in", [...QUOTA_COUNTED_STATUSES]).executeTakeFirst();
27
+ async function usedBytes(db, ownerId, organizationId) {
28
+ const [column, holder] = heldBy(ownerId, organizationId);
29
+ const row = await db.selectFrom(STORAGE_OBJECTS_TABLE).select(sql`coalesce(sum(size), 0)`.as("used")).where(column, "=", holder).where("status", "in", [...QUOTA_COUNTED_STATUSES]).executeTakeFirst();
23
30
  return Number(row?.used ?? 0);
24
31
  }
25
32
  /** A size a caller declared has to be a real byte count. Zero is fine; negative is a client bug. */
@@ -32,7 +39,26 @@ function assertDeclaredSize(additionalBytes) {
32
39
  });
33
40
  }
34
41
  /**
35
- * Throw `storage/quota_exceeded` when this upload would put the owner over their limit. The
42
+ * The refusal for a write past `check`'s ceiling: the plan's where the ceiling is a meter's, storage's own
43
+ * where it is the configured `bytesPerOwner`. `detail` is throw-site context and never crosses the wire.
44
+ */
45
+ function quotaRefusal(check, detail) {
46
+ if (!check.metered) return new StorageQuotaExceededError({ detail });
47
+ return new PithyError({
48
+ code: "payments/quota_exceeded",
49
+ status: 402,
50
+ message: "This plan's storage allowance is used up.",
51
+ action: "Delete something first, upgrade the plan, or pin a larger storageBytes allowance for this subject from the control plane.",
52
+ params: {
53
+ meter: "storageBytes",
54
+ limit: check.limitBytes ?? 0
55
+ },
56
+ detail
57
+ });
58
+ }
59
+ /**
60
+ * Throw `storage/quota_exceeded` when this upload would put the owner over their limit — or
61
+ * `payments/quota_exceeded` when the limit is a metered plan's ({@link QuotaCheck.metered}). The
36
62
  * comparison is `used + additional > limit`, so an upload landing exactly on the limit is allowed —
37
63
  * a quota is a ceiling you may reach, not one you must stay under.
38
64
  *
@@ -44,12 +70,12 @@ function assertDeclaredSize(additionalBytes) {
44
70
  async function assertWithinQuota(check) {
45
71
  if (check.limitBytes === null || check.ownerId === null) return;
46
72
  assertDeclaredSize(check.additionalBytes);
47
- const used = await usedBytes(check.db, check.ownerId);
48
- if (used + check.additionalBytes > check.limitBytes) throw new StorageQuotaExceededError({ detail: `owner would hold ${used + check.additionalBytes} bytes against a limit of ${check.limitBytes}` });
73
+ const used = await usedBytes(check.db, check.ownerId, check.organizationId);
74
+ if (used + check.additionalBytes > check.limitBytes) throw quotaRefusal(check, `owner would hold ${used + check.additionalBytes} bytes against a limit of ${check.limitBytes}`);
49
75
  }
50
76
  /**
51
77
  * Insert a storage row **only if** it fits inside the owner's quota, and throw
52
- * `storage/quota_exceeded` when it does not.
78
+ * `storage/quota_exceeded` (or a metered plan's `payments/quota_exceeded`) when it does not.
53
79
  *
54
80
  * The sum and the write are one statement — `INSERT … SELECT <values> WHERE (SELECT sum(size) …) <=
55
81
  * limit - additional` — because two statements cannot be made to hold a reservation without a
@@ -67,13 +93,14 @@ async function insertReservingQuota(reservation) {
67
93
  return;
68
94
  }
69
95
  assertDeclaredSize(additionalBytes);
96
+ const [column, holder] = heldBy(ownerId, reservation.organizationId);
70
97
  const columns = Object.keys(record);
71
- const values = db.selectNoFrom((eb) => columns.map((column) => eb.val(record[column]).as(column))).where((eb) => eb(eb.selectFrom(STORAGE_OBJECTS_TABLE).select(sql`coalesce(sum(size), 0)`.as("used")).where("ownerId", "=", ownerId).where("status", "in", [...QUOTA_COUNTED_STATUSES]), "<=", limitBytes - additionalBytes));
72
- if (!await db.insertInto("pithyStorageObjects").columns(columns).expression(values).returning("id").executeTakeFirst()) throw new StorageQuotaExceededError({ detail: `reservation of ${additionalBytes} bytes lost against a limit of ${limitBytes}` });
98
+ const values = db.selectNoFrom((eb) => columns.map((column) => eb.val(record[column]).as(column))).where((eb) => eb(eb.selectFrom(STORAGE_OBJECTS_TABLE).select(sql`coalesce(sum(size), 0)`.as("used")).where(column, "=", holder).where("status", "in", [...QUOTA_COUNTED_STATUSES]), "<=", limitBytes - additionalBytes));
99
+ if (!await db.insertInto("pithyStorageObjects").columns(columns).expression(values).returning("id").executeTakeFirst()) throw quotaRefusal(reservation, `reservation of ${additionalBytes} bytes lost against a limit of ${limitBytes}`);
73
100
  }
74
101
  /**
75
102
  * Rewrite one row **only if** the bytes it newly claims still fit inside the owner's quota, and throw
76
- * `storage/quota_exceeded` when they do not.
103
+ * `storage/quota_exceeded` (or a metered plan's `payments/quota_exceeded`) when they do not.
77
104
  *
78
105
  * This is {@link insertReservingQuota}'s other half, and it exists for the identical reason. A
79
106
  * completion measures what R2 actually holds against what the pending row reserved, and the difference
@@ -96,7 +123,8 @@ async function updateSettlingQuota(settlement) {
96
123
  return;
97
124
  }
98
125
  assertDeclaredSize(additionalBytes);
99
- if (!await db.updateTable("pithyStorageObjects").set(record).where("id", "=", record.id).where((eb) => eb(eb.selectFrom("pithyStorageObjects").select(sql`coalesce(sum(size), 0)`.as("used")).where("ownerId", "=", ownerId).where("status", "in", [...QUOTA_COUNTED_STATUSES]), "<=", limitBytes - additionalBytes)).returning("id").executeTakeFirst()) throw new StorageQuotaExceededError({ detail: `settlement of ${additionalBytes} further bytes lost against a limit of ${limitBytes}` });
126
+ const [column, holder] = heldBy(ownerId, settlement.organizationId);
127
+ if (!await db.updateTable("pithyStorageObjects").set(record).where("id", "=", record.id).where((eb) => eb(eb.selectFrom("pithyStorageObjects").select(sql`coalesce(sum(size), 0)`.as("used")).where(column, "=", holder).where("status", "in", [...QUOTA_COUNTED_STATUSES]), "<=", limitBytes - additionalBytes)).returning("id").executeTakeFirst()) throw quotaRefusal(settlement, `settlement of ${additionalBytes} further bytes lost against a limit of ${limitBytes}`);
100
128
  }
101
129
  //#endregion
102
130
  export { QUOTA_COUNTED_STATUSES, assertWithinQuota, insertReservingQuota, updateSettlingQuota, usedBytes };
@@ -0,0 +1,24 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { type CapabilitySettings } from "@pithy-sh/core/src/capability/settings";
4
+ /** The field an R2 bundle carried a Cloudflare API token in, before #728. */
5
+ export declare const R2_BUNDLE_TOKEN_FIELD = "apiToken";
6
+ /**
7
+ * **`pithy doctor`'s check for a Cloudflare API token still stored in an R2 bundle (#728).**
8
+ *
9
+ * Until #728, `pithy storage provision` and `pithy media provision` wrote a Cloudflare API token into the
10
+ * R2 bundle beside the key pair — the bootstrap one, unless the operator passed another. Nothing reads it:
11
+ * the object store signs every call with the pair. It is still a credential the application holds, and a
12
+ * deployed application holds one, `runtime`. The provision rewrites the bundle whole, so re-running it — once
13
+ * the app Workers run this kit — is the fix. The token itself stays: see {@link KEEP_THE_TOKEN}.
14
+ *
15
+ * Asked once `runtime` is minted in an environment, which is the mark that it has taken the upgrade, the
16
+ * way media's check for its own supplied token is. The bundle is sealed under a key that never leaves the
17
+ * manager, so the manager is asked whether it carries the field — a bit, never the value. `dev` has no
18
+ * manager and is never asked.
19
+ */
20
+ export declare function bundleTokenCheck(options: {
21
+ secret: string;
22
+ provision: string;
23
+ }): CapabilitySettings;
24
+ //# sourceMappingURL=bundleToken.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bundleToken.d.ts","sourceRoot":"","sources":["../../src/secret/bundleToken.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,KAAK,kBAAkB,EAIxB,MAAM,wCAAwC,CAAC;AAMhD,6EAA6E;AAC7E,eAAO,MAAM,qBAAqB,aAAa,CAAC;AAiBhD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,GAAG,kBAAkB,CAkCnG"}
@@ -0,0 +1,74 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { SettingsAccountIncomplete } from "@pithy-sh/core/src/capability/settings";
4
+ import { remedy } from "@pithy-sh/core/src/cli/command";
5
+ import { LOCAL_ENVIRONMENT } from "@pithy-sh/core/src/naming/environment";
6
+ import { runtimeTokenSecretName } from "@pithy-sh/secrets/src/provision/provisionSecrets";
7
+ //#region src/secret/bundleToken.ts
8
+ /** The field an R2 bundle carried a Cloudflare API token in, before #728. */
9
+ const R2_BUNDLE_TOKEN_FIELD = "apiToken";
10
+ /**
11
+ * **The app Workers move first.** A Worker on the kit before #728 requires the token in this bundle, and the
12
+ * new kit reads the old bundle as well as the new one. So deploying the app on this kit, then rewriting, has
13
+ * no gap; the other order has one.
14
+ */
15
+ const UPGRADE_FIRST = "Deploy your app Workers on this kit first. An older one cannot read the rewritten bundle.";
16
+ /**
17
+ * **Nothing to revoke.** The bundle's token was the bootstrap one unless the operator passed another, and the
18
+ * one they passed was the R2 token the S3 key pair derives from: an R2 access key is a Cloudflare API token,
19
+ * its id the key id. Revoking that parent invalidates the pair the rewritten bundle still signs with.
20
+ */
21
+ const KEEP_THE_TOKEN = "Keep that token. It is your bootstrap one, or the R2 token the key pair derives from, and revoking that breaks the pair.";
22
+ /**
23
+ * **`pithy doctor`'s check for a Cloudflare API token still stored in an R2 bundle (#728).**
24
+ *
25
+ * Until #728, `pithy storage provision` and `pithy media provision` wrote a Cloudflare API token into the
26
+ * R2 bundle beside the key pair — the bootstrap one, unless the operator passed another. Nothing reads it:
27
+ * the object store signs every call with the pair. It is still a credential the application holds, and a
28
+ * deployed application holds one, `runtime`. The provision rewrites the bundle whole, so re-running it — once
29
+ * the app Workers run this kit — is the fix. The token itself stays: see {@link KEEP_THE_TOKEN}.
30
+ *
31
+ * Asked once `runtime` is minted in an environment, which is the mark that it has taken the upgrade, the
32
+ * way media's check for its own supplied token is. The bundle is sealed under a key that never leaves the
33
+ * manager, so the manager is asked whether it carries the field — a bit, never the value. `dev` has no
34
+ * manager and is never asked.
35
+ */
36
+ function bundleTokenCheck(options) {
37
+ return {
38
+ local: () => [],
39
+ async account(context) {
40
+ const findings = [];
41
+ const unanswered = [];
42
+ const provision = remedy(options.provision, { flags: { "--worker": context.workerDirectory } });
43
+ for (const { name: environment } of context.environments) {
44
+ if (environment === LOCAL_ENVIRONMENT) continue;
45
+ try {
46
+ const runtime = runtimeTokenSecretName(context.project, environment);
47
+ if (!await context.account.storeEntry(runtime)) continue;
48
+ if (!await context.account.vaultSecretField({
49
+ name: options.secret,
50
+ environment,
51
+ field: "apiToken"
52
+ })) continue;
53
+ } catch (cause) {
54
+ unanswered.push({
55
+ environment,
56
+ cause
57
+ });
58
+ continue;
59
+ }
60
+ findings.push({
61
+ setting: `${options.secret} ${R2_BUNDLE_TOKEN_FIELD}`,
62
+ environment,
63
+ problem: `${options.secret} still holds a Cloudflare API token beside the R2 key pair. Nothing reads it, and the application holds one token: runtime.`,
64
+ action: `${UPGRADE_FIRST} ${provision.say((command) => `Then run ${command} to rewrite the bundle without it.`)} ${KEEP_THE_TOKEN}`,
65
+ ...provision.fix === void 0 ? {} : { fix: String(provision.fix) }
66
+ });
67
+ }
68
+ if (unanswered.length > 0) throw new SettingsAccountIncomplete(findings, unanswered);
69
+ return findings;
70
+ }
71
+ };
72
+ }
73
+ //#endregion
74
+ export { R2_BUNDLE_TOKEN_FIELD, bundleTokenCheck };
@@ -22,13 +22,17 @@ import { z } from "zod";
22
22
  * The credentials one R2 bucket is addressed and presigned with. Composed from
23
23
  * {@link R2Credentials} rather than redeclaring the key pair — that shape is `@pithy-sh/cloudflare`'s
24
24
  * to define, and `CloudflareR2Manager` validates its config against it.
25
+ *
26
+ * **No Cloudflare API token (#728).** A deployed application holds one, `runtime`, and the object store
27
+ * needs none: every operation is S3, signed with the key pair. The bundle carried the token the pair
28
+ * derives from until then; a bundle written before parses, the parse drops it, and the next provision
29
+ * rewrites the bundle without it.
25
30
  */
26
31
  export declare const R2StorageCredentials: z.ZodObject<{
27
32
  accessKeyId: z.ZodString;
28
33
  secretAccessKey: z.ZodString;
29
34
  accountId: z.ZodString;
30
35
  bucket: z.ZodString;
31
- apiToken: z.ZodString;
32
36
  }, z.core.$strip>;
33
37
  export type R2StorageCredentials = z.output<typeof R2StorageCredentials>;
34
38
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../../src/secret/registry.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAE/F,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB;;;;;;;;;;;;;;;GAeG;AAEH;;;;GAIG;AACH,eAAO,MAAM,oBAAoB;;;;;;iBAkBmF,CAAC;AACrH,MAAM,MAAM,oBAAoB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,oBAAoB,CAAC,CAAC;AAEzE;;;;GAIG;AACH,MAAM,WAAW,kBAAkB;IACjC;;;;;;;;OAQG;IACH,OAAO,EAAE,IAAI,CAAC;IACd,uEAAuE;IACvE,KAAK,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;IAC1F,SAAS,EAAE,MAAM,CAAC;IAClB,0BAA0B;IAC1B,MAAM,EAAE,OAAO,oBAAoB,CAAC;IACpC,uFAAuF;IACvF,MAAM,EAAE,YAAY,CAAC;IACrB,qFAAqF;IACrF,QAAQ,EAAE,cAAc,CAAC;IACzB;;;;;OAKG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAmCD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,CAAC,CAAC,SAAS,MAAM,EAC1D,IAAI,EAAE,CAAC,EACP,OAAO,CAAC,EAAE,MAAM,GACf,MAAM,CAAC,CAAC,EAAE,kBAAkB,CAAC,CAG/B;AAED,+EAA+E;AAC/E,eAAO,MAAM,iBAAiB,2BAA2B,CAAC;AAE1D,iHAAiH;AACjH,eAAO,MAAM,sBAAsB,mBAAmB,CAAC;AAEvD,uGAAuG;AACvG,eAAO,MAAM,sBAAsB,sDAAmE,CAAC"}
@@ -24,12 +24,16 @@ import { defineSecretRegistry } from "@pithy-sh/secrets/src/registry";
24
24
  * The credentials one R2 bucket is addressed and presigned with. Composed from
25
25
  * {@link R2Credentials} rather than redeclaring the key pair — that shape is `@pithy-sh/cloudflare`'s
26
26
  * to define, and `CloudflareR2Manager` validates its config against it.
27
+ *
28
+ * **No Cloudflare API token (#728).** A deployed application holds one, `runtime`, and the object store
29
+ * needs none: every operation is S3, signed with the key pair. The bundle carried the token the pair
30
+ * derives from until then; a bundle written before parses, the parse drops it, and the next provision
31
+ * rewrites the bundle without it.
27
32
  */
28
33
  const R2StorageCredentials = R2Credentials.extend({
29
34
  accountId: z.string().min(1).meta({ multiline: false }).describe("The Cloudflare account id the bucket lives in — the S3 endpoint host."),
30
- bucket: z.string().min(1).meta({ multiline: false }).describe("The R2 bucket name every presigned URL and server-side object call targets."),
31
- apiToken: z.string().min(1).meta({ multiline: false }).describe("The R2-scoped Cloudflare API token the key pair was derived from. Carried alongside because an R2 S3 access key IS a CF API token — the id is the key id, the SHA-256 of the value is the secret — so whatever provisions the pair already holds it, and `CloudflareR2Manager` needs it to prove bucket access.")
32
- }).describe("The account, key pair, scoped token, and bucket name the object store presigns and addresses R2 with.");
35
+ bucket: z.string().min(1).meta({ multiline: false }).describe("The R2 bucket name every presigned URL and server-side object call targets.")
36
+ }).describe("The account, key pair, and bucket name the object store presigns and addresses R2 with.");
33
37
  /**
34
38
  * Where a human makes an R2 S3 access-key pair, and where the same human makes the next one.
35
39
  *
@@ -1 +1 @@
1
- {"version":3,"file":"example.d.ts","sourceRoot":"","sources":["../../src/seeds/example.ts"],"names":[],"mappings":"AAIA,OAAO,EAA4C,KAAK,OAAO,EAAE,MAAM,8BAA8B,CAAC;AA+DtG,eAAO,MAAM,kBAAkB,EAAE,OAoD/B,CAAC"}
1
+ {"version":3,"file":"example.d.ts","sourceRoot":"","sources":["../../src/seeds/example.ts"],"names":[],"mappings":"AAIA,OAAO,EAA4C,KAAK,OAAO,EAAE,MAAM,8BAA8B,CAAC;AA+DtG,eAAO,MAAM,kBAAkB,EAAE,OAuD/B,CAAC"}
@@ -67,6 +67,7 @@ const storageExampleSeed = defineSeed({
67
67
  key: demoKey(NOTES_ID),
68
68
  path: "notes/analytical-engine.txt",
69
69
  ownerId: EXAMPLE_ADA.id,
70
+ organizationId: null,
70
71
  contentType: "text/plain",
71
72
  size: byteLength(NOTES_ID),
72
73
  visibility: "private",
@@ -81,6 +82,7 @@ const storageExampleSeed = defineSeed({
81
82
  key: demoKey(PLAN_ID),
82
83
  path: "plans/compiler.txt",
83
84
  ownerId: EXAMPLE_GRACE.id,
85
+ organizationId: null,
84
86
  contentType: "text/plain",
85
87
  size: byteLength(PLAN_ID),
86
88
  visibility: "private",
@@ -95,6 +97,7 @@ const storageExampleSeed = defineSeed({
95
97
  key: demoKey(README_ID),
96
98
  path: "public/readme.txt",
97
99
  ownerId: EXAMPLE_ADA.id,
100
+ organizationId: null,
98
101
  contentType: "text/plain",
99
102
  size: byteLength(README_ID),
100
103
  visibility: "public",
@@ -1 +1 @@
1
- {"version":3,"file":"liveStorage.d.ts","sourceRoot":"","sources":["../../src/test-utils/liveStorage.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,uCAAuC,CAAC;AACjF,OAAO,EAAE,KAAK,gBAAgB,EAAqC,MAAM,6CAA6C,CAAC;AAMvH,OAAO,EAAE,KAAK,eAAe,EAAmB,MAAM,gBAAgB,CAAC;AAEvE,OAAO,EAAiC,KAAK,WAAW,EAAe,MAAM,iBAAiB,CAAC;AAG/F;;;;;;;;;;;;;;;;;;GAkBG;AAEH,0GAA0G;AAC1G,MAAM,WAAW,eAAe;IAC9B,oFAAoF;IACpF,UAAU,EAAE,MAAM,CAAC;IACnB,4FAA4F;IAC5F,KAAK,EAAE,WAAW,CAAC;IACnB,gFAAgF;IAChF,OAAO,EAAE,mBAAmB,CAAC;CAC9B;AA2ID;;;;;;GAMG;AACH,wBAAsB,cAAc,CAAC,CAAC,EACpC,KAAK,EAAE,gBAAgB,EACvB,QAAQ,EAAE,CAAC,KAAK,EAAE,eAAe,KAAK,OAAO,CAAC,CAAC,CAAC,GAC/C,OAAO,CAAC,CAAC,CAAC,CAyBZ;AAiBD;;;;;;;GAOG;AACH,wBAAsB,gBAAgB,CAAC,CAAC,EACtC,KAAK,EAAE,gBAAgB,EACvB,QAAQ,EAAE,CAAC,EAAE,EAAE,eAAe,KAAK,OAAO,CAAC,CAAC,CAAC,GAC5C,OAAO,CAAC,CAAC,CAAC,CAaZ"}
1
+ {"version":3,"file":"liveStorage.d.ts","sourceRoot":"","sources":["../../src/test-utils/liveStorage.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,uCAAuC,CAAC;AACjF,OAAO,EAAE,KAAK,gBAAgB,EAAqC,MAAM,6CAA6C,CAAC;AAMvH,OAAO,EAAE,KAAK,eAAe,EAAmB,MAAM,gBAAgB,CAAC;AAGvE,OAAO,EAAiC,KAAK,WAAW,EAAe,MAAM,iBAAiB,CAAC;AAG/F;;;;;;;;;;;;;;;;;;GAkBG;AAEH,0GAA0G;AAC1G,MAAM,WAAW,eAAe;IAC9B,oFAAoF;IACpF,UAAU,EAAE,MAAM,CAAC;IACnB,4FAA4F;IAC5F,KAAK,EAAE,WAAW,CAAC;IACnB,gFAAgF;IAChF,OAAO,EAAE,mBAAmB,CAAC;CAC9B;AA2ID;;;;;;GAMG;AACH,wBAAsB,cAAc,CAAC,CAAC,EACpC,KAAK,EAAE,gBAAgB,EACvB,QAAQ,EAAE,CAAC,KAAK,EAAE,eAAe,KAAK,OAAO,CAAC,CAAC,CAAC,GAC/C,OAAO,CAAC,CAAC,CAAC,CAqBZ;AAiBD;;;;;;;GAOG;AACH,wBAAsB,gBAAgB,CAAC,CAAC,EACtC,KAAK,EAAE,gBAAgB,EACvB,QAAQ,EAAE,CAAC,EAAE,EAAE,eAAe,KAAK,OAAO,CAAC,CAAC,CAAC,GAC5C,OAAO,CAAC,CAAC,CAAC,CAaZ"}
@@ -4,6 +4,7 @@ import { storageDatabase } from "../data/tables.js";
4
4
  import { STORAGE_R2_SECRET, storageSecretsRegistry } from "../secret/registry.js";
5
5
  import { ObjectListing, ObjectMetadata, objectStore } from "../object/store.js";
6
6
  import { storage_0001_objects } from "../migrations/0001_objects.js";
7
+ import { storage_0002_ownership } from "../migrations/0002_ownership.js";
7
8
  import "../capability.js";
8
9
  import { configureSharedSecrets } from "@pithy-sh/secrets/src/sharedSecretsStore";
9
10
  import { CloudflareClients } from "@pithy-sh/cloudflare/src/client/clients";
@@ -151,7 +152,6 @@ async function withLiveBucket(creds, exercise) {
151
152
  const store = liveObjectStore({
152
153
  ...r2,
153
154
  accountId: creds.accountId,
154
- apiToken: creds.apiToken,
155
155
  bucket: bucketName
156
156
  }, manager, open);
157
157
  return withThrowawayResource(() => provisioner.createBucket(bucketName), () => exercise({
@@ -169,7 +169,10 @@ function storageMigrations() {
169
169
  database: "app",
170
170
  namespace: "storage",
171
171
  order: 800,
172
- migrations: { "0001_objects": storage_0001_objects }
172
+ migrations: {
173
+ "0001_objects": storage_0001_objects,
174
+ "0002_ownership": storage_0002_ownership
175
+ }
173
176
  }]).app;
174
177
  if (!provider) throw new Error("no app migration provider");
175
178
  return provider;
@@ -3,5 +3,5 @@
3
3
  /** This package's npm name — the join key against a release feed. */
4
4
  export declare const PACKAGE_NAME = "@pithy-sh/storage";
5
5
  /** This package's version, stamped from its own package.json at generation time. */
6
- export declare const PACKAGE_VERSION = "0.3.0";
6
+ export declare const PACKAGE_VERSION = "0.5.0";
7
7
  //# sourceMappingURL=version.generated.d.ts.map
@@ -4,6 +4,6 @@
4
4
  /** This package's npm name — the join key against a release feed. */
5
5
  const PACKAGE_NAME = "@pithy-sh/storage";
6
6
  /** This package's version, stamped from its own package.json at generation time. */
7
- const PACKAGE_VERSION = "0.3.0";
7
+ const PACKAGE_VERSION = "0.5.0";
8
8
  //#endregion
9
9
  export { PACKAGE_NAME, PACKAGE_VERSION };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pithy-sh/storage",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -26,7 +26,7 @@
26
26
  },
27
27
  "scripts": {
28
28
  "build": "tsdown && tsc -p tsconfig.build.json && bun ../../tooling/build/src/stampDeclarations.ts",
29
- "typecheck": "tsc -p tsconfig.json",
29
+ "typecheck": "bun check -p tsconfig.json",
30
30
  "test": "vitest run",
31
31
  "test:node": "vitest run --project=node",
32
32
  "test:workers": "vitest run --project=workers",
@@ -39,9 +39,9 @@
39
39
  "@hono/zod-validator": "^0.9.0"
40
40
  },
41
41
  "peerDependencies": {
42
- "@pithy-sh/cloudflare": "^0.5.0",
43
- "@pithy-sh/core": "^0.10.0",
44
- "@pithy-sh/secrets": "^0.4.0",
42
+ "@pithy-sh/cloudflare": "^0.7.0",
43
+ "@pithy-sh/core": "^0.12.0",
44
+ "@pithy-sh/secrets": "^0.6.0",
45
45
  "hono": "^4.13.2",
46
46
  "kysely": "^0.29.0",
47
47
  "zod": "^4.4.0"
@@ -2,8 +2,15 @@
2
2
  "name": "storage",
3
3
  "package": "@pithy-sh/storage",
4
4
  "requiredBindings": [
5
- { "type": "d1", "name": "DB" },
6
- { "type": "r2", "name": "STORAGE_BUCKET", "resource": "storage" },
5
+ {
6
+ "type": "d1",
7
+ "name": "DB"
8
+ },
9
+ {
10
+ "type": "r2",
11
+ "name": "STORAGE_BUCKET",
12
+ "resource": "storage"
13
+ },
7
14
  {
8
15
  "type": "workflow",
9
16
  "name": "STORAGE_SWEEP",
@@ -13,7 +20,7 @@
13
20
  }
14
21
  ],
15
22
  "peerCapabilities": ["secrets"],
16
- "optionalCapabilities": ["auth"],
23
+ "optionalCapabilities": ["auth", "organization"],
17
24
  "migrationNamespace": "storage",
18
25
  "secrets": [
19
26
  {
@@ -30,15 +37,16 @@
30
37
  }
31
38
  }
32
39
  ],
33
- "whenToEnable": "Put your users' files in your own R2, behind one ObjectStore seam any capability can hold. Uploads never pass through your Worker — the client PUTs straight to a presigned URL, so a 40 GiB file costs one request and not one byte of transfer — and anything over 100 MiB is split into resumable parts automatically. Downloads do stream through the Worker, deliberately: that is the only way a read can be authorized per request, honour Range and If-None-Match, and carry a Content-Disposition you chose. Uploaded bytes are treated as untrusted on the way back out: every object response carries nosniff and a locked-down CSP, and an active type (HTML, SVG, anything +xml, script) is served as an attachment whatever was stored — so a user's upload cannot execute on your origin, and this route is not where your own HTML belongs. Keys are server-derived and opaque, so a client can never name an object or guess the one beside it; you supply a logical path, and that path is what gets stored, indexed, and listed. It has per-owner byte quotas that count uploads still in flight, server-side copy, revocable share links (a presigned URL can only expire — a share can be taken back), and a daily Workflow that reconciles orphaned rows and orphaned objects in both directions. It takes no position on what the bytes are — no transcoding, no thumbnails, no AI. That is @pithy-sh/media, which already presigns through this ObjectStore against its own bucket and credential name, and inherits none of these tables or routes for doing so. Files belong to an authenticated owner, so add auth too.",
40
+ "whenToEnable": "Put your users' files in your own R2, behind one ObjectStore seam any capability can hold. Uploads never pass through your Worker — the client PUTs straight to a presigned URL, so a 40 GiB file costs one request and not one byte of transfer — and anything over 100 MiB is split into resumable parts automatically. Downloads do stream through the Worker, deliberately: that is the only way a read can be authorized per request, honour Range and If-None-Match, and carry a Content-Disposition you chose. Uploaded bytes are treated as untrusted on the way back out: every object response carries nosniff and a locked-down CSP, and an active type (HTML, SVG, anything +xml, script) is served as an attachment whatever was stored — so a user's upload cannot execute on your origin, and this route is not where your own HTML belongs. Keys are server-derived and opaque, so a client can never name an object or guess the one beside it; you supply a logical path, and that path is what gets stored, indexed, and listed. It has per-owner byte quotas that count uploads still in flight, server-side copy, revocable share links (a presigned URL can only expire — a share can be taken back), and a daily Workflow that reconciles orphaned rows and orphaned objects in both directions. It takes no position on what the bytes are — no transcoding, no thumbnails, no AI. That is @pithy-sh/media, which already presigns through this ObjectStore against its own bucket and credential name, and inherits none of these tables or routes for doing so. Every file carries its owner, the organization in force, and a visibility — private, organization or public — and a file a caller may not read is not found, never forbidden. Files belong to an authenticated owner, so add auth too, and organization if files belong to teams.",
34
41
  "scaffold": [
35
42
  "Add a `storage({ ... })` block to pithy.config.ts. Every option has a working default; the one worth setting early is `quota`.",
36
43
  "Bind a D1 database named DB in wrangler.jsonc — the same app database your other capabilities use.",
37
44
  "Run `pithy migrate` to create pithy_storage_objects and pithy_storage_shares.",
38
45
  "Run `pithy storage provision` to create the per-environment R2 buckets, write the credentials secret, and deploy the sweep worker. `pithy add` writes bindings and touches no Cloudflare account; provisioning is the separate, explicit step.",
39
- "Supply an R2 S3 access-key pair to that command with --r2-access-key-id and --r2-secret-access-key, or set R2_CREDENTIALS in .dev.vars. Cloudflare exposes no API for minting one, so it cannot be created for you — make the pair under R2 -> Manage API tokens.",
46
+ "Supply an R2 S3 access-key pair to that command with --r2-access-key-id and --r2-secret-access-key, or set R2_CREDENTIALS in the account config. Cloudflare exposes no API for minting one, so it cannot be created for you — make the pair under R2 -> Manage API tokens.",
40
47
  "Add `@pithy-sh/secrets` if it is not already installed. The R2 credentials are read through it, so storage will not compose without it.",
41
- "Add `@pithy-sh/auth` if it is not already installed. Every owner-scoped route reads the authenticated user from the AuthContext seam; with no auth capability composed those routes deny, which is the right default but not a useful one."
48
+ "Add `@pithy-sh/auth` if it is not already installed. Every write reads the authenticated user from the AuthContext seam; with no auth capability composed those routes deny, which is the right default but not a useful one. Add `@pithy-sh/organization` to scope files to teams, and give some role `storage:manage` so an organization can clean up after somebody who left.",
49
+ "Share a file with one person, or put one on legal hold, with `storage({ permission })` — a hook asked on every read and write that answers `allow`, `deny` or `default`. Revocable share links are unchanged by it."
42
50
  ],
43
51
  "configOptions": [
44
52
  {
@@ -57,10 +65,12 @@
57
65
  "describe": "Bytes per part, for every part but the last. 64 MiB. R2 allows at most 10,000 parts, so this fixes the largest object you can store — about 625 GiB. Raise it for larger objects; the cost is that every retry re-sends a bigger part."
58
66
  },
59
67
  {
60
- "key": "defaultVisibility",
61
- "choices": ["private", "public"],
62
- "default": "private",
63
- "describe": "Visibility for an upload that does not name one. Private, so a forgotten field can never publish a file."
68
+ "key": "visibility",
69
+ "default": {
70
+ "default": "private",
71
+ "allowed": ["private", "organization", "public"]
72
+ },
73
+ "describe": "Who may read a file: `default` is the level an upload gets when it names none, `allowed` every level a write may name. Drop `public` from `allowed` and nothing can ever be published."
64
74
  },
65
75
  {
66
76
  "key": "pendingTtlSeconds",