@pithy-sh/storage 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/dist/capability.d.ts +45 -0
  2. package/dist/capability.d.ts.map +1 -0
  3. package/dist/capability.js +76 -0
  4. package/dist/config/config.d.ts +27 -0
  5. package/dist/config/config.d.ts.map +1 -0
  6. package/dist/config/config.js +49 -0
  7. package/dist/data/share.d.ts +27 -0
  8. package/dist/data/share.d.ts.map +1 -0
  9. package/dist/data/share.js +28 -0
  10. package/dist/data/storageObject.d.ts +55 -0
  11. package/dist/data/storageObject.d.ts.map +1 -0
  12. package/dist/data/storageObject.js +44 -0
  13. package/dist/data/tables.d.ts +23 -0
  14. package/dist/data/tables.d.ts.map +1 -0
  15. package/dist/data/tables.js +26 -0
  16. package/dist/error/errors.d.ts +60 -0
  17. package/dist/error/errors.d.ts.map +1 -0
  18. package/dist/error/errors.js +89 -0
  19. package/dist/http/guard.d.ts +20 -0
  20. package/dist/http/guard.d.ts.map +1 -0
  21. package/dist/http/guard.js +29 -0
  22. package/dist/http/handlers.d.ts +232 -0
  23. package/dist/http/handlers.d.ts.map +1 -0
  24. package/dist/http/handlers.js +507 -0
  25. package/dist/http/routes.d.ts +70 -0
  26. package/dist/http/routes.d.ts.map +1 -0
  27. package/dist/http/routes.js +135 -0
  28. package/dist/http/schemas.d.ts +74 -0
  29. package/dist/http/schemas.d.ts.map +1 -0
  30. package/dist/http/schemas.js +93 -0
  31. package/dist/http/serve.d.ts +121 -0
  32. package/dist/http/serve.d.ts.map +1 -0
  33. package/dist/http/serve.js +209 -0
  34. package/dist/index.d.ts +23 -0
  35. package/dist/index.d.ts.map +1 -0
  36. package/dist/index.js +14 -0
  37. package/dist/migrations/0001_objects.d.ts +24 -0
  38. package/dist/migrations/0001_objects.d.ts.map +1 -0
  39. package/dist/migrations/0001_objects.js +41 -0
  40. package/dist/object/cloudflare.d.ts +23 -0
  41. package/dist/object/cloudflare.d.ts.map +1 -0
  42. package/dist/object/cloudflare.js +48 -0
  43. package/dist/object/key.d.ts +29 -0
  44. package/dist/object/key.d.ts.map +1 -0
  45. package/dist/object/key.js +37 -0
  46. package/dist/object/multipart.d.ts +78 -0
  47. package/dist/object/multipart.d.ts.map +1 -0
  48. package/dist/object/multipart.js +131 -0
  49. package/dist/object/store.d.ts +203 -0
  50. package/dist/object/store.d.ts.map +1 -0
  51. package/dist/object/store.js +178 -0
  52. package/dist/provision/provisionStorage.d.ts +139 -0
  53. package/dist/provision/provisionStorage.d.ts.map +1 -0
  54. package/dist/provision/provisionStorage.js +112 -0
  55. package/dist/provision/resolveStorageConfig.d.ts +45 -0
  56. package/dist/provision/resolveStorageConfig.d.ts.map +1 -0
  57. package/dist/provision/resolveStorageConfig.js +33 -0
  58. package/dist/quota/quota.d.ts +127 -0
  59. package/dist/quota/quota.d.ts.map +1 -0
  60. package/dist/quota/quota.js +102 -0
  61. package/dist/secret/registry.d.ts +72 -0
  62. package/dist/secret/registry.d.ts.map +1 -0
  63. package/dist/secret/registry.js +84 -0
  64. package/dist/seeds/example.d.ts +5 -0
  65. package/dist/seeds/example.d.ts.map +1 -0
  66. package/dist/seeds/example.js +111 -0
  67. package/dist/test-utils/liveStorage.d.ts +52 -0
  68. package/dist/test-utils/liveStorage.d.ts.map +1 -0
  69. package/dist/test-utils/liveStorage.js +198 -0
  70. package/dist/version.generated.d.ts +7 -0
  71. package/dist/version.generated.d.ts.map +1 -0
  72. package/dist/version.generated.js +9 -0
  73. package/dist/workflows/retryPolicy.d.ts +39 -0
  74. package/dist/workflows/retryPolicy.d.ts.map +1 -0
  75. package/dist/workflows/retryPolicy.js +43 -0
  76. package/dist/workflows/specs.d.ts +57 -0
  77. package/dist/workflows/specs.d.ts.map +1 -0
  78. package/dist/workflows/specs.js +60 -0
  79. package/dist/workflows/sweep.d.ts +84 -0
  80. package/dist/workflows/sweep.d.ts.map +1 -0
  81. package/dist/workflows/sweep.js +145 -0
  82. package/dist/workflows/worker.d.ts +51 -0
  83. package/dist/workflows/worker.d.ts.map +1 -0
  84. package/dist/workflows/worker.js +52 -0
  85. package/package.json +22 -11
  86. package/src/version.generated.ts +1 -1
@@ -0,0 +1,45 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { type Capability } from "@pithy-sh/core/src/capability/capability";
4
+ import type { DatabaseSpecMap } from "@pithy-sh/core/src/data/databases";
5
+ import type { KvNamespaceSpecMap } from "@pithy-sh/core/src/kv/namespaces";
6
+ import { StorageConfig, type StorageConfigInput } from "./config/config";
7
+ import { storageWorkflows } from "./workflows/specs";
8
+ /**
9
+ * Where storage's migrations sort in the app database. Unique per database; the registry composes keys
10
+ * like `0800_storage_0001_objects`. Sits after matchmaking (700).
11
+ */
12
+ export declare const STORAGE_MIGRATION_ORDER = 800;
13
+ export type StorageOptions = StorageConfigInput & {
14
+ /** Mount the object routes somewhere other than `/storage`. */
15
+ basePath?: string;
16
+ /** Mount share fetches somewhere other than `/s`. Short by default — the whole URL gets pasted around. */
17
+ sharePath?: string;
18
+ };
19
+ /**
20
+ * The storage capability, with its resolved config attached. The workflow slice is kept literal so a
21
+ * composed project types `c.var.workflows.trigger("storage/sweep", { dryRun: true })` precisely — an
22
+ * unregistered key or a mistyped payload is a compile error, not a 500.
23
+ */
24
+ export interface StorageCapability extends Capability<DatabaseSpecMap, KvNamespaceSpecMap, "storage", typeof storageWorkflows> {
25
+ /** The resolved storage config. */
26
+ storageConfig: StorageConfig;
27
+ }
28
+ /**
29
+ * The storage capability: general file storage on the adopter's own R2 bucket — uploads that never
30
+ * proxy through the Worker, downloads that do, and a D1 record of what exists and who owns it.
31
+ *
32
+ * The bucket is `STORAGE_BUCKET`, deliberately separate from media's `MEDIA_BUCKET`. Buckets are free
33
+ * — cost is bytes and operations — so two cost nothing, and the separation buys independent teardown
34
+ * and independent public-access posture. `visibility: 'public'` is a plausible thing for a file store
35
+ * to offer and never appropriate for media's originals.
36
+ *
37
+ * `dependsOn: ["secrets"]` is real: the R2 credential bundle is read through the aggregated registry
38
+ * at startup, so a project composing storage without `@pithy-sh/secrets` must fail at assembly, not at
39
+ * the first presign. Auth is *not* listed — it is a seam. Ownership scoping reads `c.var.auth.userId`,
40
+ * so without `@pithy-sh/auth` every owner-scoped route denies rather than opens, which is the right
41
+ * failure and needs no dependency edge. It belongs in the manifest's `optionalCapabilities`.
42
+ */
43
+ export declare function storage(options?: StorageOptions): StorageCapability;
44
+ export declare function isStorageCapability(capability: Capability): capability is StorageCapability;
45
+ //# sourceMappingURL=capability.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"capability.d.ts","sourceRoot":"","sources":["../src/capability.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,UAAU,EAAoB,MAAM,0CAA0C,CAAC;AAC7F,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AACzE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,kCAAkC,CAAC;AAG3E,OAAO,EAAE,aAAa,EAAE,KAAK,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAOzE,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAErD;;;GAGG;AACH,eAAO,MAAM,uBAAuB,MAAM,CAAC;AAE3C,MAAM,MAAM,cAAc,GAAG,kBAAkB,GAAG;IAChD,+DAA+D;IAC/D,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,0GAA0G;IAC1G,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF;;;;GAIG;AACH,MAAM,WAAW,iBACf,SAAQ,UAAU,CAAC,eAAe,EAAE,kBAAkB,EAAE,SAAS,EAAE,OAAO,gBAAgB,CAAC;IAC3F,mCAAmC;IACnC,aAAa,EAAE,aAAa,CAAC;CAC9B;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,OAAO,CAAC,OAAO,GAAE,cAAmB,GAAG,iBAAiB,CA0CvE;AAED,wBAAgB,mBAAmB,CAAC,UAAU,EAAE,UAAU,GAAG,UAAU,IAAI,iBAAiB,CAE3F"}
@@ -0,0 +1,76 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { StorageConfig } from "./config/config.js";
4
+ import { storageTables } from "./data/tables.js";
5
+ import { storageSecretsRegistry } from "./secret/registry.js";
6
+ import { registerStorageRoutes } from "./http/routes.js";
7
+ import { storage_0001_objects } from "./migrations/0001_objects.js";
8
+ import { storageExampleSeed } from "./seeds/example.js";
9
+ import { PACKAGE_VERSION } from "./version.generated.js";
10
+ import { storageWorkflows } from "./workflows/specs.js";
11
+ import { defineCapability } from "@pithy-sh/core/src/capability/capability";
12
+ import { workflowBindings } from "@pithy-sh/core/src/workflow/bindings";
13
+ //#region src/capability.ts
14
+ /**
15
+ * Where storage's migrations sort in the app database. Unique per database; the registry composes keys
16
+ * like `0800_storage_0001_objects`. Sits after matchmaking (700).
17
+ */
18
+ const STORAGE_MIGRATION_ORDER = 800;
19
+ /**
20
+ * The storage capability: general file storage on the adopter's own R2 bucket — uploads that never
21
+ * proxy through the Worker, downloads that do, and a D1 record of what exists and who owns it.
22
+ *
23
+ * The bucket is `STORAGE_BUCKET`, deliberately separate from media's `MEDIA_BUCKET`. Buckets are free
24
+ * — cost is bytes and operations — so two cost nothing, and the separation buys independent teardown
25
+ * and independent public-access posture. `visibility: 'public'` is a plausible thing for a file store
26
+ * to offer and never appropriate for media's originals.
27
+ *
28
+ * `dependsOn: ["secrets"]` is real: the R2 credential bundle is read through the aggregated registry
29
+ * at startup, so a project composing storage without `@pithy-sh/secrets` must fail at assembly, not at
30
+ * the first presign. Auth is *not* listed — it is a seam. Ownership scoping reads `c.var.auth.userId`,
31
+ * so without `@pithy-sh/auth` every owner-scoped route denies rather than opens, which is the right
32
+ * failure and needs no dependency edge. It belongs in the manifest's `optionalCapabilities`.
33
+ */
34
+ function storage(options = {}) {
35
+ const { basePath, sharePath, ...configInput } = options;
36
+ const resolved = StorageConfig.parse(configInput);
37
+ const migrations = { "0001_objects": storage_0001_objects };
38
+ const requiredBindings = [
39
+ {
40
+ type: "d1",
41
+ name: "DB"
42
+ },
43
+ {
44
+ type: "r2",
45
+ name: "STORAGE_BUCKET"
46
+ },
47
+ ...workflowBindings(storageWorkflows)
48
+ ];
49
+ const capability = defineCapability({
50
+ name: "storage",
51
+ version: PACKAGE_VERSION,
52
+ dependsOn: ["secrets"],
53
+ secretRegistry: storageSecretsRegistry,
54
+ workflows: storageWorkflows,
55
+ requiredBindings,
56
+ config: StorageConfig,
57
+ databases: { app: {
58
+ binding: "DB",
59
+ tables: storageTables(),
60
+ migrationOrder: 800,
61
+ migrations
62
+ } },
63
+ routes: registerStorageRoutes({
64
+ config: resolved,
65
+ basePath,
66
+ sharePath
67
+ }),
68
+ seeds: [storageExampleSeed]
69
+ });
70
+ return Object.assign(capability, { storageConfig: resolved });
71
+ }
72
+ function isStorageCapability(capability) {
73
+ return capability.name === "storage" && "storageConfig" in capability;
74
+ }
75
+ //#endregion
76
+ export { STORAGE_MIGRATION_ORDER, isStorageCapability, storage };
@@ -0,0 +1,27 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { z } from "zod";
4
+ export declare const StorageQuota: z.ZodObject<{
5
+ bytesPerOwner: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
6
+ }, z.core.$strip>;
7
+ export type StorageQuota = z.output<typeof StorageQuota>;
8
+ export declare const StorageConfig: z.ZodObject<{
9
+ quota: z.ZodPrefault<z.ZodObject<{
10
+ bytesPerOwner: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
11
+ }, z.core.$strip>>;
12
+ multipartThresholdBytes: z.ZodDefault<z.ZodNumber>;
13
+ partSizeBytes: z.ZodDefault<z.ZodNumber>;
14
+ defaultVisibility: z.ZodDefault<z.ZodEnum<{
15
+ private: "private";
16
+ public: "public";
17
+ }>>;
18
+ pendingTtlSeconds: z.ZodDefault<z.ZodNumber>;
19
+ }, z.core.$strip>;
20
+ export type StorageConfig = z.output<typeof StorageConfig>;
21
+ export type StorageConfigInput = z.input<typeof StorageConfig>;
22
+ /**
23
+ * The largest object this config can store: part size × R2's 10,000-part cap. Surfaced so the CLI and
24
+ * docs can state a real number rather than a rule of thumb.
25
+ */
26
+ export declare function maxObjectBytes(config: StorageConfig): number;
27
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/config/config.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AA+BxB,eAAO,MAAM,YAAY;;iBAYyF,CAAC;AACnH,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,YAAY,CAAC,CAAC;AAEzD,eAAO,MAAM,aAAa;;;;;;;;;;;iBA6CtB,CAAC;AACL,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,aAAa,CAAC,CAAC;AAC3D,MAAM,MAAM,kBAAkB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,aAAa,CAAC,CAAC;AAE/D;;;GAGG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,aAAa,GAAG,MAAM,CAE5D"}
@@ -0,0 +1,49 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { StorageVisibility } from "../data/storageObject.js";
4
+ import { DEFAULT_MULTIPART_THRESHOLD_BYTES, DEFAULT_PART_SIZE_BYTES, MAX_PART_SIZE_BYTES, MAX_UPLOAD_PARTS, MIN_PART_SIZE_BYTES } from "../object/multipart.js";
5
+ import { z } from "zod";
6
+ //#region src/config/config.ts
7
+ /**
8
+ * The storage capability's config — the thin, user-owned surface in `pithy.config.ts`. Every field is
9
+ * `.describe()`d: the descriptions feed the self-documenting CLI (CLAUDE.md §Config).
10
+ *
11
+ * Three decisions live here, and each has a real trade behind it.
12
+ *
13
+ * **Quota is unlimited by default, but the field is always present.** A default cap would silently
14
+ * break the first adopter who stores something large; an absent field would mean bolting quotas on
15
+ * later as a breaking change. So the knob exists from day one and starts off.
16
+ *
17
+ * **Multipart threshold 100 MiB, part size 64 MiB.** R2 caps an upload at 10,000 parts, so part size
18
+ * fixes the practical object ceiling: 10,000 × 64 MiB ≈ 625 GiB. Raise `partSizeBytes` to raise the
19
+ * ceiling (R2's own object cap is 4.995 TiB); the cost is that every retry re-sends a larger part.
20
+ *
21
+ * **Default visibility is private.** The safe default is the one where forgetting to set a field
22
+ * cannot leak a file.
23
+ */
24
+ /** The largest single-part upload R2 accepts — 5 GiB, less 5 MiB. Above it, multipart is not optional. */
25
+ const MAX_SINGLE_PART_BYTES = 5363466240;
26
+ const StorageQuota = z.object({ bytesPerOwner: z.number().int().positive().nullable().default(null).describe("The total bytes one owner may store, counting uploads still in flight. Null is unlimited — the default, because a cap that arrives by surprise breaks an adopter who was already storing more than it.") }).describe("Per-owner storage limits. Checked when an upload starts, against pending and stored bytes together.");
27
+ const StorageConfig = z.object({
28
+ quota: StorageQuota.prefault({}).describe("Per-owner byte limits. Unlimited unless configured."),
29
+ multipartThresholdBytes: z.number().int().min(MIN_PART_SIZE_BYTES).max(MAX_SINGLE_PART_BYTES).default(DEFAULT_MULTIPART_THRESHOLD_BYTES).describe("Uploads larger than this go multipart; smaller ones get one presigned PUT. It cannot exceed R2's ~5 GiB single-part cap, because above that multipart is the only way to store the bytes at all."),
30
+ partSizeBytes: z.number().int().min(MIN_PART_SIZE_BYTES).max(MAX_PART_SIZE_BYTES).default(DEFAULT_PART_SIZE_BYTES).describe("Bytes per multipart part, for every part but the last. R2 allows at most 10,000 parts, so this fixes the largest object you can store: 64 MiB gives ~625 GiB. The floor is S3's 5 MiB rule for non-final parts."),
31
+ defaultVisibility: StorageVisibility.default("private").describe("Visibility for an upload that does not name one. Private, so a forgotten field can never publish a file."),
32
+ pendingTtlSeconds: z.number().int().positive().default(86400).describe("How long a `pending` row holds its quota reservation before the orphan sweep reclaims it. Long enough for a slow multipart upload to finish; short enough that an abandoned one does not hold a quota forever.")
33
+ }).describe("Configuration for the storage capability — quotas, multipart sizing, and default visibility.").check((ctx) => {
34
+ if (ctx.value.multipartThresholdBytes < ctx.value.partSizeBytes) ctx.issues.push({
35
+ code: "custom",
36
+ input: ctx.value,
37
+ path: ["multipartThresholdBytes"],
38
+ message: `multipartThresholdBytes (${ctx.value.multipartThresholdBytes}) is below partSizeBytes (${ctx.value.partSizeBytes}). Every multipart upload would then be a single part.`
39
+ });
40
+ });
41
+ /**
42
+ * The largest object this config can store: part size × R2's 10,000-part cap. Surfaced so the CLI and
43
+ * docs can state a real number rather than a rule of thumb.
44
+ */
45
+ function maxObjectBytes(config) {
46
+ return config.partSizeBytes * MAX_UPLOAD_PARTS;
47
+ }
48
+ //#endregion
49
+ export { StorageConfig, StorageQuota, maxObjectBytes };
@@ -0,0 +1,27 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { z } from "zod";
4
+ /**
5
+ * One revocable share link — the row in `pithy_storage_shares`.
6
+ *
7
+ * **Why this is a table and not a presigned URL.** A presigned URL cannot be revoked, only expired.
8
+ * Once minted it is valid until its signature lapses, and nothing the owner does can call it back —
9
+ * so "share this file, and let me take it back" is impossible to build on presigning alone. A share
10
+ * is therefore a row: the token is looked up on every fetch, and revoking is a write, effective on
11
+ * the next request.
12
+ *
13
+ * That is also why `revokedAt` is a timestamp rather than a deleted row. A revoked share stays
14
+ * readable as history, and a fetch against it answers `storage/share_revoked` (410 Gone) instead of
15
+ * the `storage/not_found` a deleted row would produce — which tells the holder the link existed and
16
+ * was withdrawn, rather than leaving them guessing.
17
+ */
18
+ export declare const StorageShare: z.ZodObject<{
19
+ token: z.ZodString;
20
+ objectId: z.ZodUUID;
21
+ expiresAt: z.ZodNullable<z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>>;
22
+ revokedAt: z.ZodNullable<z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>>;
23
+ createdAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
24
+ }, z.core.$strip>;
25
+ export type StorageShare = z.output<typeof StorageShare>;
26
+ export type StorageShareRow = z.input<typeof StorageShare>;
27
+ //# sourceMappingURL=share.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"share.d.ts","sourceRoot":"","sources":["../../src/data/share.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,YAAY;;;;;;iBAamD,CAAC;AAC7E,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,YAAY,CAAC,CAAC;AACzD,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,YAAY,CAAC,CAAC"}
@@ -0,0 +1,28 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { z } from "zod";
4
+ import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
5
+ //#region src/data/share.ts
6
+ /**
7
+ * One revocable share link — the row in `pithy_storage_shares`.
8
+ *
9
+ * **Why this is a table and not a presigned URL.** A presigned URL cannot be revoked, only expired.
10
+ * Once minted it is valid until its signature lapses, and nothing the owner does can call it back —
11
+ * so "share this file, and let me take it back" is impossible to build on presigning alone. A share
12
+ * is therefore a row: the token is looked up on every fetch, and revoking is a write, effective on
13
+ * the next request.
14
+ *
15
+ * That is also why `revokedAt` is a timestamp rather than a deleted row. A revoked share stays
16
+ * readable as history, and a fetch against it answers `storage/share_revoked` (410 Gone) instead of
17
+ * the `storage/not_found` a deleted row would produce — which tells the holder the link existed and
18
+ * was withdrawn, rather than leaving them guessing.
19
+ */
20
+ const StorageShare = z.object({
21
+ token: z.string().min(1).describe("The share token — the primary key, and the whole credential. High-entropy and server-generated."),
22
+ objectId: z.uuid().describe("The object this share grants read access to. References `pithy_storage_objects.id`."),
23
+ expiresAt: SQLiteDate.nullable().describe("When the link stops working. Null never expires — only revocation ends it."),
24
+ revokedAt: SQLiteDate.nullable().describe("When the owner withdrew the link. Null while it is live."),
25
+ createdAt: SQLiteDate.describe("When the link was minted.")
26
+ }).describe("One revocable share link — the row in `pithy_storage_shares`.");
27
+ //#endregion
28
+ export { StorageShare };
@@ -0,0 +1,55 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { z } from "zod";
4
+ /**
5
+ * One stored file — the row in `pithy_storage_objects`.
6
+ *
7
+ * Two identifiers, deliberately. `key` is the R2 object key: server-derived, opaque, unique, and
8
+ * never shown to a client. `path` is the adopter's logical name (`invoices/2026/q3.pdf`): indexed and
9
+ * listed from SQL, and never interpolated into a key. Separating them is what removes traversal,
10
+ * collision, and injection surfaces at once, and it keeps the key format an internal detail we can
11
+ * change without breaking an adopter's paths.
12
+ *
13
+ * `id` is a UUID, not an autoincrement integer, because it is externally exposed in every route path
14
+ * (CLAUDE.md §ID strategy) — a sequential id would let anyone enumerate how many files exist and
15
+ * probe for neighbors.
16
+ *
17
+ * `size` is declared by the client at init and *confirmed* against R2 at completion. It is nullable
18
+ * because a caller may not know it up front; a null size reserves no quota, which is why the handler
19
+ * requires it whenever a quota is configured.
20
+ */
21
+ export declare const StorageVisibility: z.ZodEnum<{
22
+ private: "private";
23
+ public: "public";
24
+ }>;
25
+ export type StorageVisibility = z.infer<typeof StorageVisibility>;
26
+ export declare const StorageObjectStatus: z.ZodEnum<{
27
+ failed: "failed";
28
+ pending: "pending";
29
+ stored: "stored";
30
+ }>;
31
+ export type StorageObjectStatus = z.infer<typeof StorageObjectStatus>;
32
+ export declare const StorageObject: z.ZodObject<{
33
+ id: z.ZodUUID;
34
+ key: z.ZodString;
35
+ path: z.ZodString;
36
+ ownerId: z.ZodNullable<z.ZodString>;
37
+ contentType: z.ZodString;
38
+ size: z.ZodNullable<z.ZodNumber>;
39
+ visibility: z.ZodEnum<{
40
+ private: "private";
41
+ public: "public";
42
+ }>;
43
+ checksum: z.ZodNullable<z.ZodString>;
44
+ status: z.ZodEnum<{
45
+ failed: "failed";
46
+ pending: "pending";
47
+ stored: "stored";
48
+ }>;
49
+ uploadId: z.ZodNullable<z.ZodString>;
50
+ createdAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
51
+ updatedAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
52
+ }, z.core.$strip>;
53
+ export type StorageObject = z.output<typeof StorageObject>;
54
+ export type StorageObjectRow = z.input<typeof StorageObject>;
55
+ //# sourceMappingURL=storageObject.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storageObject.d.ts","sourceRoot":"","sources":["../../src/data/storageObject.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB;;;;;;;;;;;;;;;;GAgBG;AAEH,eAAO,MAAM,iBAAiB;;;EAI3B,CAAC;AACJ,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,iBAAiB,CAAC,CAAC;AAElE,eAAO,MAAM,mBAAmB;;;;EAI7B,CAAC;AACJ,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAEtE,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;iBAwC0C,CAAC;AACrE,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,aAAa,CAAC,CAAC;AAC3D,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,aAAa,CAAC,CAAC"}
@@ -0,0 +1,44 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { z } from "zod";
4
+ import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
5
+ //#region src/data/storageObject.ts
6
+ /**
7
+ * One stored file — the row in `pithy_storage_objects`.
8
+ *
9
+ * Two identifiers, deliberately. `key` is the R2 object key: server-derived, opaque, unique, and
10
+ * never shown to a client. `path` is the adopter's logical name (`invoices/2026/q3.pdf`): indexed and
11
+ * listed from SQL, and never interpolated into a key. Separating them is what removes traversal,
12
+ * collision, and injection surfaces at once, and it keeps the key format an internal detail we can
13
+ * change without breaking an adopter's paths.
14
+ *
15
+ * `id` is a UUID, not an autoincrement integer, because it is externally exposed in every route path
16
+ * (CLAUDE.md §ID strategy) — a sequential id would let anyone enumerate how many files exist and
17
+ * probe for neighbors.
18
+ *
19
+ * `size` is declared by the client at init and *confirmed* against R2 at completion. It is nullable
20
+ * because a caller may not know it up front; a null size reserves no quota, which is why the handler
21
+ * requires it whenever a quota is configured.
22
+ */
23
+ const StorageVisibility = z.enum(["private", "public"]).describe("Who may read an object without a share link: `private` is the owner alone, `public` is anyone with the id. Visibility is authorization, not a bucket setting — the bucket itself stays private.");
24
+ const StorageObjectStatus = z.enum([
25
+ "pending",
26
+ "stored",
27
+ "failed"
28
+ ]).describe("Where an upload is: `pending` reserved the row and its quota but has no bytes yet, `stored` has bytes R2 confirmed, `failed` was abandoned. A `pending` row past its TTL is what the orphan sweep reclaims.");
29
+ const StorageObject = z.object({
30
+ id: z.uuid().describe("The object's public id — a UUID, because it appears in every route path."),
31
+ key: z.string().min(1).describe("The opaque R2 object key, server-derived (`obj/<uuid>`). Unique, and never sent to a client."),
32
+ path: z.string().min(1).describe("The adopter's logical path (`invoices/2026/q3.pdf`). Indexed and listable; never part of the key."),
33
+ ownerId: z.string().nullable().describe("The authenticated user who owns the file, from AuthContext. Null for system-owned objects."),
34
+ contentType: z.string().min(1).describe("The MIME type. Declared at init and overwritten at completion with what R2 stored — a presigned PUT cannot sign a content type, so only the completed row is authoritative. An active type is still neutralised on serve."),
35
+ size: z.number().int().nonnegative().nullable().describe("Byte count. Declared at init so the pending row reserves quota; confirmed against R2 at completion."),
36
+ visibility: StorageVisibility.describe("Whether anyone with the id may read this object, or only its owner."),
37
+ checksum: z.string().nullable().describe("Lowercase hex SHA-256 of the bytes, when one is known. Null until a completion supplies it."),
38
+ status: StorageObjectStatus.describe("The upload's lifecycle state."),
39
+ uploadId: z.string().nullable().describe("The multipart upload id while one is in flight. Null for a single-PUT upload and after completion."),
40
+ createdAt: SQLiteDate.describe("When the upload was initiated — the age the orphan sweep measures."),
41
+ updatedAt: SQLiteDate.describe("When the row last changed state.")
42
+ }).describe("One stored file — the row in `pithy_storage_objects`.");
43
+ //#endregion
44
+ export { StorageObject, StorageObjectStatus, StorageVisibility };
@@ -0,0 +1,23 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { D1Database } from "@cloudflare/workers-types";
4
+ import { type DatabaseSchema } from "@pithy-sh/core/src/data/db";
5
+ import type { Kysely } from "kysely";
6
+ import type { z } from "zod";
7
+ import { StorageShare } from "./share";
8
+ import { StorageObject } from "./storageObject";
9
+ /** The objects table. `CamelCasePlugin` snake-cases it to `pithy_storage_objects`. */
10
+ export declare const STORAGE_OBJECTS_TABLE = "pithyStorageObjects";
11
+ /** The share-links table. `CamelCasePlugin` snake-cases it to `pithy_storage_shares`. */
12
+ export declare const STORAGE_SHARES_TABLE = "pithyStorageShares";
13
+ /** The storage tables map. Both are always present — neither is behind a config flag. */
14
+ export declare function storageTables(): Record<string, z.ZodObject>;
15
+ /** The typed Kysely database over the storage tables. */
16
+ export type StorageTables = {
17
+ [STORAGE_OBJECTS_TABLE]: typeof StorageObject;
18
+ [STORAGE_SHARES_TABLE]: typeof StorageShare;
19
+ };
20
+ export type StorageDatabase = Kysely<DatabaseSchema<StorageTables>>;
21
+ /** Build the storage database from the `DB` binding (CamelCasePlugin installed). */
22
+ export declare function storageDatabase(d1: D1Database): StorageDatabase;
23
+ //# sourceMappingURL=tables.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tables.d.ts","sourceRoot":"","sources":["../../src/data/tables.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAkB,KAAK,cAAc,EAAE,MAAM,4BAA4B,CAAC;AACjF,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACrC,OAAO,KAAK,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAC7B,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEhD,sFAAsF;AACtF,eAAO,MAAM,qBAAqB,wBAAwB,CAAC;AAC3D,yFAAyF;AACzF,eAAO,MAAM,oBAAoB,uBAAuB,CAAC;AAEzD,yFAAyF;AACzF,wBAAgB,aAAa,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,SAAS,CAAC,CAK3D;AAED,yDAAyD;AACzD,MAAM,MAAM,aAAa,GAAG;IAC1B,CAAC,qBAAqB,CAAC,EAAE,OAAO,aAAa,CAAC;IAC9C,CAAC,oBAAoB,CAAC,EAAE,OAAO,YAAY,CAAC;CAC7C,CAAC;AACF,MAAM,MAAM,eAAe,GAAG,MAAM,CAAC,cAAc,CAAC,aAAa,CAAC,CAAC,CAAC;AAEpE,oFAAoF;AACpF,wBAAgB,eAAe,CAAC,EAAE,EAAE,UAAU,GAAG,eAAe,CAK/D"}
@@ -0,0 +1,26 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { StorageObject } from "./storageObject.js";
4
+ import { StorageShare } from "./share.js";
5
+ import { createDatabase } from "@pithy-sh/core/src/data/db";
6
+ //#region src/data/tables.ts
7
+ /** The objects table. `CamelCasePlugin` snake-cases it to `pithy_storage_objects`. */
8
+ const STORAGE_OBJECTS_TABLE = "pithyStorageObjects";
9
+ /** The share-links table. `CamelCasePlugin` snake-cases it to `pithy_storage_shares`. */
10
+ const STORAGE_SHARES_TABLE = "pithyStorageShares";
11
+ /** The storage tables map. Both are always present — neither is behind a config flag. */
12
+ function storageTables() {
13
+ return {
14
+ [STORAGE_OBJECTS_TABLE]: StorageObject,
15
+ [STORAGE_SHARES_TABLE]: StorageShare
16
+ };
17
+ }
18
+ /** Build the storage database from the `DB` binding (CamelCasePlugin installed). */
19
+ function storageDatabase(d1) {
20
+ return createDatabase(d1, {
21
+ [STORAGE_OBJECTS_TABLE]: StorageObject,
22
+ [STORAGE_SHARES_TABLE]: StorageShare
23
+ });
24
+ }
25
+ //#endregion
26
+ export { STORAGE_OBJECTS_TABLE, STORAGE_SHARES_TABLE, storageDatabase, storageTables };
@@ -0,0 +1,60 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { PithyError } from "@pithy-sh/core/src/error/pithyError";
4
+ import type { MessageParams } from "@pithy-sh/core/src/i18n/catalog";
5
+ /**
6
+ * `@pithy-sh/storage` throw sugar. The `storage/*` codes live in core's closed `KitErrorPayload` union
7
+ * (CLAUDE.md §Errors); these subclasses are the package-local vehicles that set one of those members.
8
+ * Runtime code in this package throws one of these, never a plain `new Error`.
9
+ *
10
+ * Public text goes in `message` and `action`; throw-site context goes in `detail`, which the HTTP
11
+ * codec strips. That matters more here than in most capabilities: object keys, upload ids, and byte
12
+ * counts are exactly the kind of internal shape a client should never be handed.
13
+ */
14
+ interface StorageErrorArgs {
15
+ message?: string;
16
+ action?: string;
17
+ detail?: string;
18
+ /**
19
+ * Values a translating client interpolates into its own wording for this code. Client-facing, so —
20
+ * unlike `action` and `detail` — these cross the boundary with `message`.
21
+ */
22
+ params?: MessageParams;
23
+ }
24
+ export declare class StorageNotFoundError extends PithyError {
25
+ constructor(args?: StorageErrorArgs, options?: {
26
+ cause?: unknown;
27
+ });
28
+ }
29
+ export declare class StorageForbiddenError extends PithyError {
30
+ constructor(args?: StorageErrorArgs, options?: {
31
+ cause?: unknown;
32
+ });
33
+ }
34
+ export declare class StorageQuotaExceededError extends PithyError {
35
+ constructor(args?: StorageErrorArgs, options?: {
36
+ cause?: unknown;
37
+ });
38
+ }
39
+ export declare class StorageUploadIncompleteError extends PithyError {
40
+ constructor(args?: StorageErrorArgs, options?: {
41
+ cause?: unknown;
42
+ });
43
+ }
44
+ export declare class StorageMultipartFailedError extends PithyError {
45
+ constructor(args?: StorageErrorArgs, options?: {
46
+ cause?: unknown;
47
+ });
48
+ }
49
+ export declare class StorageShareExpiredError extends PithyError {
50
+ constructor(args?: StorageErrorArgs, options?: {
51
+ cause?: unknown;
52
+ });
53
+ }
54
+ export declare class StorageShareRevokedError extends PithyError {
55
+ constructor(args?: StorageErrorArgs, options?: {
56
+ cause?: unknown;
57
+ });
58
+ }
59
+ export {};
60
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/error/errors.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,UAAU,EAAE,MAAM,qCAAqC,CAAC;AACjE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iCAAiC,CAAC;AAErE;;;;;;;;GAQG;AAEH,UAAU,gBAAgB;IACxB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,MAAM,CAAC,EAAE,aAAa,CAAC;CACxB;AAED,qBAAa,oBAAqB,SAAQ,UAAU;IAClD,YAAY,IAAI,GAAE,gBAAqB,EAAE,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,EAYrE;CACF;AAED,qBAAa,qBAAsB,SAAQ,UAAU;IACnD,YAAY,IAAI,GAAE,gBAAqB,EAAE,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,EAYrE;CACF;AAED,qBAAa,yBAA0B,SAAQ,UAAU;IACvD,YAAY,IAAI,GAAE,gBAAqB,EAAE,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,EAYrE;CACF;AAED,qBAAa,4BAA6B,SAAQ,UAAU;IAC1D,YAAY,IAAI,GAAE,gBAAqB,EAAE,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,EAYrE;CACF;AAED,qBAAa,2BAA4B,SAAQ,UAAU;IACzD,YAAY,IAAI,GAAE,gBAAqB,EAAE,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,EAcrE;CACF;AAED,qBAAa,wBAAyB,SAAQ,UAAU;IACtD,YAAY,IAAI,GAAE,gBAAqB,EAAE,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,EAYrE;CACF;AAED,qBAAa,wBAAyB,SAAQ,UAAU;IACtD,YAAY,IAAI,GAAE,gBAAqB,EAAE,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,EAYrE;CACF"}
@@ -0,0 +1,89 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { PithyError } from "@pithy-sh/core/src/error/pithyError";
4
+ //#region src/error/errors.ts
5
+ var StorageNotFoundError = class extends PithyError {
6
+ constructor(args = {}, options) {
7
+ super({
8
+ code: "storage/not_found",
9
+ status: 404,
10
+ message: args.message ?? "That file does not exist.",
11
+ action: args.action ?? "Check the object id. A file you do not own reads as missing, not as forbidden.",
12
+ detail: args.detail,
13
+ params: args.params
14
+ }, options);
15
+ }
16
+ };
17
+ var StorageForbiddenError = class extends PithyError {
18
+ constructor(args = {}, options) {
19
+ super({
20
+ code: "storage/forbidden",
21
+ status: 403,
22
+ message: args.message ?? "That file is not yours.",
23
+ action: args.action ?? "Sign in as the owner, or ask them for a share link.",
24
+ detail: args.detail,
25
+ params: args.params
26
+ }, options);
27
+ }
28
+ };
29
+ var StorageQuotaExceededError = class extends PithyError {
30
+ constructor(args = {}, options) {
31
+ super({
32
+ code: "storage/quota_exceeded",
33
+ status: 413,
34
+ message: args.message ?? "That upload would put you over your storage quota.",
35
+ action: args.action ?? "Delete something first, or raise the quota in pithy.config.ts.",
36
+ detail: args.detail,
37
+ params: args.params
38
+ }, options);
39
+ }
40
+ };
41
+ var StorageUploadIncompleteError = class extends PithyError {
42
+ constructor(args = {}, options) {
43
+ super({
44
+ code: "storage/upload_incomplete",
45
+ status: 409,
46
+ message: args.message ?? "That file has not finished uploading.",
47
+ action: args.action ?? "Upload every part, then complete the upload.",
48
+ detail: args.detail,
49
+ params: args.params
50
+ }, options);
51
+ }
52
+ };
53
+ var StorageMultipartFailedError = class extends PithyError {
54
+ constructor(args = {}, options) {
55
+ super({
56
+ code: "storage/multipart_failed",
57
+ status: 500,
58
+ message: args.message ?? "The upload could not be assembled. GET /storage/<id>/parts to see what is missing.",
59
+ detail: args.detail,
60
+ params: args.params
61
+ }, options);
62
+ }
63
+ };
64
+ var StorageShareExpiredError = class extends PithyError {
65
+ constructor(args = {}, options) {
66
+ super({
67
+ code: "storage/share_expired",
68
+ status: 410,
69
+ message: args.message ?? "That share link has expired.",
70
+ action: args.action ?? "Ask the owner for a new one.",
71
+ detail: args.detail,
72
+ params: args.params
73
+ }, options);
74
+ }
75
+ };
76
+ var StorageShareRevokedError = class extends PithyError {
77
+ constructor(args = {}, options) {
78
+ super({
79
+ code: "storage/share_revoked",
80
+ status: 410,
81
+ message: args.message ?? "That share link was revoked.",
82
+ action: args.action ?? "Ask the owner for a new one.",
83
+ detail: args.detail,
84
+ params: args.params
85
+ }, options);
86
+ }
87
+ };
88
+ //#endregion
89
+ export { StorageForbiddenError, StorageMultipartFailedError, StorageNotFoundError, StorageQuotaExceededError, StorageShareExpiredError, StorageShareRevokedError, StorageUploadIncompleteError };
@@ -0,0 +1,20 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
4
+ import type { MiddlewareHandler } from "hono";
5
+ /**
6
+ * The storage routes' identity gate.
7
+ *
8
+ * **Copied, not imported.** This is deliberately a local copy of the same three lines
9
+ * `@pithy-sh/media` and `@pithy-sh/ledger` each carry, rather than an import from `@pithy-sh/auth`.
10
+ * Importing it would make auth a hard dependency of storage, and a hard dependency is the wrong
11
+ * shape twice over: storage works perfectly well for system-owned objects with no auth capability
12
+ * composed, and — far more importantly — a package that *imports* its authorization from another
13
+ * package fails open when that package is absent. Depending on the core `AuthContext` seam instead
14
+ * means `c.var.auth` is simply `null` with no auth capability composed, and every owner-scoped
15
+ * route **denies**. Failing closed is not a side effect here; it is the reason for the copy.
16
+ *
17
+ * So `dependsOn` stays free of auth and the manifest lists it under `optionalCapabilities`.
18
+ */
19
+ export declare function requireAuth(): MiddlewareHandler<PithyHonoEnv>;
20
+ //# sourceMappingURL=guard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guard.d.ts","sourceRoot":"","sources":["../../src/http/guard.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAE7E,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAE9C;;;;;;;;;;;;;GAaG;AACH,wBAAgB,WAAW,IAAI,iBAAiB,CAAC,YAAY,CAAC,CAU7D"}
@@ -0,0 +1,29 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
4
+ //#region src/http/guard.ts
5
+ /**
6
+ * The storage routes' identity gate.
7
+ *
8
+ * **Copied, not imported.** This is deliberately a local copy of the same three lines
9
+ * `@pithy-sh/media` and `@pithy-sh/ledger` each carry, rather than an import from `@pithy-sh/auth`.
10
+ * Importing it would make auth a hard dependency of storage, and a hard dependency is the wrong
11
+ * shape twice over: storage works perfectly well for system-owned objects with no auth capability
12
+ * composed, and — far more importantly — a package that *imports* its authorization from another
13
+ * package fails open when that package is absent. Depending on the core `AuthContext` seam instead
14
+ * means `c.var.auth` is simply `null` with no auth capability composed, and every owner-scoped
15
+ * route **denies**. Failing closed is not a side effect here; it is the reason for the copy.
16
+ *
17
+ * So `dependsOn` stays free of auth and the manifest lists it under `optionalCapabilities`.
18
+ */
19
+ function requireAuth() {
20
+ return async (c, next) => {
21
+ if (!c.var.auth) throw new UnauthorizedError({
22
+ message: "Authentication required.",
23
+ action: "Sign in and retry with a valid session or bearer token."
24
+ });
25
+ await next();
26
+ };
27
+ }
28
+ //#endregion
29
+ export { requireAuth };