@pithy-sh/storage 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/dist/capability.d.ts +43 -0
  2. package/dist/capability.d.ts.map +1 -0
  3. package/dist/capability.js +74 -0
  4. package/dist/config/config.d.ts +25 -0
  5. package/dist/config/config.d.ts.map +1 -0
  6. package/dist/config/config.js +47 -0
  7. package/dist/data/share.d.ts +25 -0
  8. package/dist/data/share.d.ts.map +1 -0
  9. package/dist/data/share.js +26 -0
  10. package/dist/data/storageObject.d.ts +53 -0
  11. package/dist/data/storageObject.d.ts.map +1 -0
  12. package/dist/data/storageObject.js +42 -0
  13. package/dist/data/tables.d.ts +21 -0
  14. package/dist/data/tables.d.ts.map +1 -0
  15. package/dist/data/tables.js +24 -0
  16. package/dist/error/errors.d.ts +58 -0
  17. package/dist/error/errors.d.ts.map +1 -0
  18. package/dist/error/errors.js +87 -0
  19. package/dist/http/guard.d.ts +18 -0
  20. package/dist/http/guard.d.ts.map +1 -0
  21. package/dist/http/guard.js +27 -0
  22. package/dist/http/handlers.d.ts +230 -0
  23. package/dist/http/handlers.d.ts.map +1 -0
  24. package/dist/http/handlers.js +505 -0
  25. package/dist/http/routes.d.ts +68 -0
  26. package/dist/http/routes.d.ts.map +1 -0
  27. package/dist/http/routes.js +133 -0
  28. package/dist/http/schemas.d.ts +72 -0
  29. package/dist/http/schemas.d.ts.map +1 -0
  30. package/dist/http/schemas.js +91 -0
  31. package/dist/http/serve.d.ts +119 -0
  32. package/dist/http/serve.d.ts.map +1 -0
  33. package/dist/http/serve.js +207 -0
  34. package/dist/index.d.ts +21 -0
  35. package/dist/index.d.ts.map +1 -0
  36. package/dist/index.js +12 -0
  37. package/dist/migrations/0001_objects.d.ts +22 -0
  38. package/dist/migrations/0001_objects.d.ts.map +1 -0
  39. package/dist/migrations/0001_objects.js +39 -0
  40. package/dist/object/cloudflare.d.ts +21 -0
  41. package/dist/object/cloudflare.d.ts.map +1 -0
  42. package/dist/object/cloudflare.js +46 -0
  43. package/dist/object/key.d.ts +27 -0
  44. package/dist/object/key.d.ts.map +1 -0
  45. package/dist/object/key.js +35 -0
  46. package/dist/object/multipart.d.ts +76 -0
  47. package/dist/object/multipart.d.ts.map +1 -0
  48. package/dist/object/multipart.js +129 -0
  49. package/dist/object/store.d.ts +201 -0
  50. package/dist/object/store.d.ts.map +1 -0
  51. package/dist/object/store.js +176 -0
  52. package/dist/provision/provisionStorage.d.ts +137 -0
  53. package/dist/provision/provisionStorage.d.ts.map +1 -0
  54. package/dist/provision/provisionStorage.js +110 -0
  55. package/dist/provision/resolveStorageConfig.d.ts +43 -0
  56. package/dist/provision/resolveStorageConfig.d.ts.map +1 -0
  57. package/dist/provision/resolveStorageConfig.js +31 -0
  58. package/dist/quota/quota.d.ts +125 -0
  59. package/dist/quota/quota.d.ts.map +1 -0
  60. package/dist/quota/quota.js +100 -0
  61. package/dist/secret/registry.d.ts +70 -0
  62. package/dist/secret/registry.d.ts.map +1 -0
  63. package/dist/secret/registry.js +82 -0
  64. package/dist/seeds/example.d.ts +3 -0
  65. package/dist/seeds/example.d.ts.map +1 -0
  66. package/dist/seeds/example.js +109 -0
  67. package/dist/test-utils/liveStorage.d.ts +50 -0
  68. package/dist/test-utils/liveStorage.d.ts.map +1 -0
  69. package/dist/test-utils/liveStorage.js +196 -0
  70. package/dist/version.generated.d.ts +5 -0
  71. package/dist/version.generated.d.ts.map +1 -0
  72. package/dist/version.generated.js +7 -0
  73. package/dist/workflows/retryPolicy.d.ts +37 -0
  74. package/dist/workflows/retryPolicy.d.ts.map +1 -0
  75. package/dist/workflows/retryPolicy.js +41 -0
  76. package/dist/workflows/specs.d.ts +55 -0
  77. package/dist/workflows/specs.d.ts.map +1 -0
  78. package/dist/workflows/specs.js +58 -0
  79. package/dist/workflows/sweep.d.ts +82 -0
  80. package/dist/workflows/sweep.d.ts.map +1 -0
  81. package/dist/workflows/sweep.js +143 -0
  82. package/dist/workflows/worker.d.ts +49 -0
  83. package/dist/workflows/worker.d.ts.map +1 -0
  84. package/dist/workflows/worker.js +50 -0
  85. package/package.json +22 -11
  86. package/src/version.generated.ts +1 -1
@@ -0,0 +1,43 @@
1
+ import { type Capability } from "@pithy-sh/core/src/capability/capability";
2
+ import type { DatabaseSpecMap } from "@pithy-sh/core/src/data/databases";
3
+ import type { KvNamespaceSpecMap } from "@pithy-sh/core/src/kv/namespaces";
4
+ import { StorageConfig, type StorageConfigInput } from "./config/config";
5
+ import { storageWorkflows } from "./workflows/specs";
6
+ /**
7
+ * Where storage's migrations sort in the app database. Unique per database; the registry composes keys
8
+ * like `0800_storage_0001_objects`. Sits after matchmaking (700).
9
+ */
10
+ export declare const STORAGE_MIGRATION_ORDER = 800;
11
+ export type StorageOptions = StorageConfigInput & {
12
+ /** Mount the object routes somewhere other than `/storage`. */
13
+ basePath?: string;
14
+ /** Mount share fetches somewhere other than `/s`. Short by default — the whole URL gets pasted around. */
15
+ sharePath?: string;
16
+ };
17
+ /**
18
+ * The storage capability, with its resolved config attached. The workflow slice is kept literal so a
19
+ * composed project types `c.var.workflows.trigger("storage/sweep", { dryRun: true })` precisely — an
20
+ * unregistered key or a mistyped payload is a compile error, not a 500.
21
+ */
22
+ export interface StorageCapability extends Capability<DatabaseSpecMap, KvNamespaceSpecMap, "storage", typeof storageWorkflows> {
23
+ /** The resolved storage config. */
24
+ storageConfig: StorageConfig;
25
+ }
26
+ /**
27
+ * The storage capability: general file storage on the adopter's own R2 bucket — uploads that never
28
+ * proxy through the Worker, downloads that do, and a D1 record of what exists and who owns it.
29
+ *
30
+ * The bucket is `STORAGE_BUCKET`, deliberately separate from media's `MEDIA_BUCKET`. Buckets are free
31
+ * — cost is bytes and operations — so two cost nothing, and the separation buys independent teardown
32
+ * and independent public-access posture. `visibility: 'public'` is a plausible thing for a file store
33
+ * to offer and never appropriate for media's originals.
34
+ *
35
+ * `dependsOn: ["secrets"]` is real: the R2 credential bundle is read through the aggregated registry
36
+ * at startup, so a project composing storage without `@pithy-sh/secrets` must fail at assembly, not at
37
+ * the first presign. Auth is *not* listed — it is a seam. Ownership scoping reads `c.var.auth.userId`,
38
+ * so without `@pithy-sh/auth` every owner-scoped route denies rather than opens, which is the right
39
+ * failure and needs no dependency edge. It belongs in the manifest's `optionalCapabilities`.
40
+ */
41
+ export declare function storage(options?: StorageOptions): StorageCapability;
42
+ export declare function isStorageCapability(capability: Capability): capability is StorageCapability;
43
+ //# 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,74 @@
1
+ import { StorageConfig } from "./config/config.js";
2
+ import { storageTables } from "./data/tables.js";
3
+ import { storageSecretsRegistry } from "./secret/registry.js";
4
+ import { registerStorageRoutes } from "./http/routes.js";
5
+ import { storage_0001_objects } from "./migrations/0001_objects.js";
6
+ import { storageExampleSeed } from "./seeds/example.js";
7
+ import { PACKAGE_VERSION } from "./version.generated.js";
8
+ import { storageWorkflows } from "./workflows/specs.js";
9
+ import { defineCapability } from "@pithy-sh/core/src/capability/capability";
10
+ import { workflowBindings } from "@pithy-sh/core/src/workflow/bindings";
11
+ //#region src/capability.ts
12
+ /**
13
+ * Where storage's migrations sort in the app database. Unique per database; the registry composes keys
14
+ * like `0800_storage_0001_objects`. Sits after matchmaking (700).
15
+ */
16
+ const STORAGE_MIGRATION_ORDER = 800;
17
+ /**
18
+ * The storage capability: general file storage on the adopter's own R2 bucket — uploads that never
19
+ * proxy through the Worker, downloads that do, and a D1 record of what exists and who owns it.
20
+ *
21
+ * The bucket is `STORAGE_BUCKET`, deliberately separate from media's `MEDIA_BUCKET`. Buckets are free
22
+ * — cost is bytes and operations — so two cost nothing, and the separation buys independent teardown
23
+ * and independent public-access posture. `visibility: 'public'` is a plausible thing for a file store
24
+ * to offer and never appropriate for media's originals.
25
+ *
26
+ * `dependsOn: ["secrets"]` is real: the R2 credential bundle is read through the aggregated registry
27
+ * at startup, so a project composing storage without `@pithy-sh/secrets` must fail at assembly, not at
28
+ * the first presign. Auth is *not* listed — it is a seam. Ownership scoping reads `c.var.auth.userId`,
29
+ * so without `@pithy-sh/auth` every owner-scoped route denies rather than opens, which is the right
30
+ * failure and needs no dependency edge. It belongs in the manifest's `optionalCapabilities`.
31
+ */
32
+ function storage(options = {}) {
33
+ const { basePath, sharePath, ...configInput } = options;
34
+ const resolved = StorageConfig.parse(configInput);
35
+ const migrations = { "0001_objects": storage_0001_objects };
36
+ const requiredBindings = [
37
+ {
38
+ type: "d1",
39
+ name: "DB"
40
+ },
41
+ {
42
+ type: "r2",
43
+ name: "STORAGE_BUCKET"
44
+ },
45
+ ...workflowBindings(storageWorkflows)
46
+ ];
47
+ const capability = defineCapability({
48
+ name: "storage",
49
+ version: PACKAGE_VERSION,
50
+ dependsOn: ["secrets"],
51
+ secretRegistry: storageSecretsRegistry,
52
+ workflows: storageWorkflows,
53
+ requiredBindings,
54
+ config: StorageConfig,
55
+ databases: { app: {
56
+ binding: "DB",
57
+ tables: storageTables(),
58
+ migrationOrder: 800,
59
+ migrations
60
+ } },
61
+ routes: registerStorageRoutes({
62
+ config: resolved,
63
+ basePath,
64
+ sharePath
65
+ }),
66
+ seeds: [storageExampleSeed]
67
+ });
68
+ return Object.assign(capability, { storageConfig: resolved });
69
+ }
70
+ function isStorageCapability(capability) {
71
+ return capability.name === "storage" && "storageConfig" in capability;
72
+ }
73
+ //#endregion
74
+ export { STORAGE_MIGRATION_ORDER, isStorageCapability, storage };
@@ -0,0 +1,25 @@
1
+ import { z } from "zod";
2
+ export declare const StorageQuota: z.ZodObject<{
3
+ bytesPerOwner: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
4
+ }, z.core.$strip>;
5
+ export type StorageQuota = z.output<typeof StorageQuota>;
6
+ export declare const StorageConfig: z.ZodObject<{
7
+ quota: z.ZodPrefault<z.ZodObject<{
8
+ bytesPerOwner: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
9
+ }, z.core.$strip>>;
10
+ multipartThresholdBytes: z.ZodDefault<z.ZodNumber>;
11
+ partSizeBytes: z.ZodDefault<z.ZodNumber>;
12
+ defaultVisibility: z.ZodDefault<z.ZodEnum<{
13
+ private: "private";
14
+ public: "public";
15
+ }>>;
16
+ pendingTtlSeconds: z.ZodDefault<z.ZodNumber>;
17
+ }, z.core.$strip>;
18
+ export type StorageConfig = z.output<typeof StorageConfig>;
19
+ export type StorageConfigInput = z.input<typeof StorageConfig>;
20
+ /**
21
+ * The largest object this config can store: part size × R2's 10,000-part cap. Surfaced so the CLI and
22
+ * docs can state a real number rather than a rule of thumb.
23
+ */
24
+ export declare function maxObjectBytes(config: StorageConfig): number;
25
+ //# 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,47 @@
1
+ import { StorageVisibility } from "../data/storageObject.js";
2
+ import { DEFAULT_MULTIPART_THRESHOLD_BYTES, DEFAULT_PART_SIZE_BYTES, MAX_PART_SIZE_BYTES, MAX_UPLOAD_PARTS, MIN_PART_SIZE_BYTES } from "../object/multipart.js";
3
+ import { z } from "zod";
4
+ //#region src/config/config.ts
5
+ /**
6
+ * The storage capability's config — the thin, user-owned surface in `pithy.config.ts`. Every field is
7
+ * `.describe()`d: the descriptions feed the self-documenting CLI (CLAUDE.md §Config).
8
+ *
9
+ * Three decisions live here, and each has a real trade behind it.
10
+ *
11
+ * **Quota is unlimited by default, but the field is always present.** A default cap would silently
12
+ * break the first adopter who stores something large; an absent field would mean bolting quotas on
13
+ * later as a breaking change. So the knob exists from day one and starts off.
14
+ *
15
+ * **Multipart threshold 100 MiB, part size 64 MiB.** R2 caps an upload at 10,000 parts, so part size
16
+ * fixes the practical object ceiling: 10,000 × 64 MiB ≈ 625 GiB. Raise `partSizeBytes` to raise the
17
+ * ceiling (R2's own object cap is 4.995 TiB); the cost is that every retry re-sends a larger part.
18
+ *
19
+ * **Default visibility is private.** The safe default is the one where forgetting to set a field
20
+ * cannot leak a file.
21
+ */
22
+ /** The largest single-part upload R2 accepts — 5 GiB, less 5 MiB. Above it, multipart is not optional. */
23
+ const MAX_SINGLE_PART_BYTES = 5363466240;
24
+ 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.");
25
+ const StorageConfig = z.object({
26
+ quota: StorageQuota.prefault({}).describe("Per-owner byte limits. Unlimited unless configured."),
27
+ 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."),
28
+ 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."),
29
+ defaultVisibility: StorageVisibility.default("private").describe("Visibility for an upload that does not name one. Private, so a forgotten field can never publish a file."),
30
+ 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.")
31
+ }).describe("Configuration for the storage capability — quotas, multipart sizing, and default visibility.").check((ctx) => {
32
+ if (ctx.value.multipartThresholdBytes < ctx.value.partSizeBytes) ctx.issues.push({
33
+ code: "custom",
34
+ input: ctx.value,
35
+ path: ["multipartThresholdBytes"],
36
+ message: `multipartThresholdBytes (${ctx.value.multipartThresholdBytes}) is below partSizeBytes (${ctx.value.partSizeBytes}). Every multipart upload would then be a single part.`
37
+ });
38
+ });
39
+ /**
40
+ * The largest object this config can store: part size × R2's 10,000-part cap. Surfaced so the CLI and
41
+ * docs can state a real number rather than a rule of thumb.
42
+ */
43
+ function maxObjectBytes(config) {
44
+ return config.partSizeBytes * MAX_UPLOAD_PARTS;
45
+ }
46
+ //#endregion
47
+ export { StorageConfig, StorageQuota, maxObjectBytes };
@@ -0,0 +1,25 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * One revocable share link — the row in `pithy_storage_shares`.
4
+ *
5
+ * **Why this is a table and not a presigned URL.** A presigned URL cannot be revoked, only expired.
6
+ * Once minted it is valid until its signature lapses, and nothing the owner does can call it back —
7
+ * so "share this file, and let me take it back" is impossible to build on presigning alone. A share
8
+ * is therefore a row: the token is looked up on every fetch, and revoking is a write, effective on
9
+ * the next request.
10
+ *
11
+ * That is also why `revokedAt` is a timestamp rather than a deleted row. A revoked share stays
12
+ * readable as history, and a fetch against it answers `storage/share_revoked` (410 Gone) instead of
13
+ * the `storage/not_found` a deleted row would produce — which tells the holder the link existed and
14
+ * was withdrawn, rather than leaving them guessing.
15
+ */
16
+ export declare const StorageShare: z.ZodObject<{
17
+ token: z.ZodString;
18
+ objectId: z.ZodUUID;
19
+ expiresAt: z.ZodNullable<z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>>;
20
+ revokedAt: z.ZodNullable<z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>>;
21
+ createdAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
22
+ }, z.core.$strip>;
23
+ export type StorageShare = z.output<typeof StorageShare>;
24
+ export type StorageShareRow = z.input<typeof StorageShare>;
25
+ //# 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,26 @@
1
+ import { z } from "zod";
2
+ import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
3
+ //#region src/data/share.ts
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
+ const StorageShare = z.object({
19
+ token: z.string().min(1).describe("The share token — the primary key, and the whole credential. High-entropy and server-generated."),
20
+ objectId: z.uuid().describe("The object this share grants read access to. References `pithy_storage_objects.id`."),
21
+ expiresAt: SQLiteDate.nullable().describe("When the link stops working. Null never expires — only revocation ends it."),
22
+ revokedAt: SQLiteDate.nullable().describe("When the owner withdrew the link. Null while it is live."),
23
+ createdAt: SQLiteDate.describe("When the link was minted.")
24
+ }).describe("One revocable share link — the row in `pithy_storage_shares`.");
25
+ //#endregion
26
+ export { StorageShare };
@@ -0,0 +1,53 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * One stored file — the row in `pithy_storage_objects`.
4
+ *
5
+ * Two identifiers, deliberately. `key` is the R2 object key: server-derived, opaque, unique, and
6
+ * never shown to a client. `path` is the adopter's logical name (`invoices/2026/q3.pdf`): indexed and
7
+ * listed from SQL, and never interpolated into a key. Separating them is what removes traversal,
8
+ * collision, and injection surfaces at once, and it keeps the key format an internal detail we can
9
+ * change without breaking an adopter's paths.
10
+ *
11
+ * `id` is a UUID, not an autoincrement integer, because it is externally exposed in every route path
12
+ * (CLAUDE.md §ID strategy) — a sequential id would let anyone enumerate how many files exist and
13
+ * probe for neighbors.
14
+ *
15
+ * `size` is declared by the client at init and *confirmed* against R2 at completion. It is nullable
16
+ * because a caller may not know it up front; a null size reserves no quota, which is why the handler
17
+ * requires it whenever a quota is configured.
18
+ */
19
+ export declare const StorageVisibility: z.ZodEnum<{
20
+ private: "private";
21
+ public: "public";
22
+ }>;
23
+ export type StorageVisibility = z.infer<typeof StorageVisibility>;
24
+ export declare const StorageObjectStatus: z.ZodEnum<{
25
+ failed: "failed";
26
+ pending: "pending";
27
+ stored: "stored";
28
+ }>;
29
+ export type StorageObjectStatus = z.infer<typeof StorageObjectStatus>;
30
+ export declare const StorageObject: z.ZodObject<{
31
+ id: z.ZodUUID;
32
+ key: z.ZodString;
33
+ path: z.ZodString;
34
+ ownerId: z.ZodNullable<z.ZodString>;
35
+ contentType: z.ZodString;
36
+ size: z.ZodNullable<z.ZodNumber>;
37
+ visibility: z.ZodEnum<{
38
+ private: "private";
39
+ public: "public";
40
+ }>;
41
+ checksum: z.ZodNullable<z.ZodString>;
42
+ status: z.ZodEnum<{
43
+ failed: "failed";
44
+ pending: "pending";
45
+ stored: "stored";
46
+ }>;
47
+ uploadId: z.ZodNullable<z.ZodString>;
48
+ createdAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
49
+ updatedAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
50
+ }, z.core.$strip>;
51
+ export type StorageObject = z.output<typeof StorageObject>;
52
+ export type StorageObjectRow = z.input<typeof StorageObject>;
53
+ //# 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,42 @@
1
+ import { z } from "zod";
2
+ import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
3
+ //#region src/data/storageObject.ts
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
+ 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.");
22
+ const StorageObjectStatus = z.enum([
23
+ "pending",
24
+ "stored",
25
+ "failed"
26
+ ]).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.");
27
+ const StorageObject = z.object({
28
+ id: z.uuid().describe("The object's public id — a UUID, because it appears in every route path."),
29
+ key: z.string().min(1).describe("The opaque R2 object key, server-derived (`obj/<uuid>`). Unique, and never sent to a client."),
30
+ path: z.string().min(1).describe("The adopter's logical path (`invoices/2026/q3.pdf`). Indexed and listable; never part of the key."),
31
+ ownerId: z.string().nullable().describe("The authenticated user who owns the file, from AuthContext. Null for system-owned objects."),
32
+ 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."),
33
+ size: z.number().int().nonnegative().nullable().describe("Byte count. Declared at init so the pending row reserves quota; confirmed against R2 at completion."),
34
+ visibility: StorageVisibility.describe("Whether anyone with the id may read this object, or only its owner."),
35
+ checksum: z.string().nullable().describe("Lowercase hex SHA-256 of the bytes, when one is known. Null until a completion supplies it."),
36
+ status: StorageObjectStatus.describe("The upload's lifecycle state."),
37
+ uploadId: z.string().nullable().describe("The multipart upload id while one is in flight. Null for a single-PUT upload and after completion."),
38
+ createdAt: SQLiteDate.describe("When the upload was initiated — the age the orphan sweep measures."),
39
+ updatedAt: SQLiteDate.describe("When the row last changed state.")
40
+ }).describe("One stored file — the row in `pithy_storage_objects`.");
41
+ //#endregion
42
+ export { StorageObject, StorageObjectStatus, StorageVisibility };
@@ -0,0 +1,21 @@
1
+ import type { D1Database } from "@cloudflare/workers-types";
2
+ import { type DatabaseSchema } from "@pithy-sh/core/src/data/db";
3
+ import type { Kysely } from "kysely";
4
+ import type { z } from "zod";
5
+ import { StorageShare } from "./share";
6
+ import { StorageObject } from "./storageObject";
7
+ /** The objects table. `CamelCasePlugin` snake-cases it to `pithy_storage_objects`. */
8
+ export declare const STORAGE_OBJECTS_TABLE = "pithyStorageObjects";
9
+ /** The share-links table. `CamelCasePlugin` snake-cases it to `pithy_storage_shares`. */
10
+ export declare const STORAGE_SHARES_TABLE = "pithyStorageShares";
11
+ /** The storage tables map. Both are always present — neither is behind a config flag. */
12
+ export declare function storageTables(): Record<string, z.ZodObject>;
13
+ /** The typed Kysely database over the storage tables. */
14
+ export type StorageTables = {
15
+ [STORAGE_OBJECTS_TABLE]: typeof StorageObject;
16
+ [STORAGE_SHARES_TABLE]: typeof StorageShare;
17
+ };
18
+ export type StorageDatabase = Kysely<DatabaseSchema<StorageTables>>;
19
+ /** Build the storage database from the `DB` binding (CamelCasePlugin installed). */
20
+ export declare function storageDatabase(d1: D1Database): StorageDatabase;
21
+ //# 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,24 @@
1
+ import { StorageObject } from "./storageObject.js";
2
+ import { StorageShare } from "./share.js";
3
+ import { createDatabase } from "@pithy-sh/core/src/data/db";
4
+ //#region src/data/tables.ts
5
+ /** The objects table. `CamelCasePlugin` snake-cases it to `pithy_storage_objects`. */
6
+ const STORAGE_OBJECTS_TABLE = "pithyStorageObjects";
7
+ /** The share-links table. `CamelCasePlugin` snake-cases it to `pithy_storage_shares`. */
8
+ const STORAGE_SHARES_TABLE = "pithyStorageShares";
9
+ /** The storage tables map. Both are always present — neither is behind a config flag. */
10
+ function storageTables() {
11
+ return {
12
+ [STORAGE_OBJECTS_TABLE]: StorageObject,
13
+ [STORAGE_SHARES_TABLE]: StorageShare
14
+ };
15
+ }
16
+ /** Build the storage database from the `DB` binding (CamelCasePlugin installed). */
17
+ function storageDatabase(d1) {
18
+ return createDatabase(d1, {
19
+ [STORAGE_OBJECTS_TABLE]: StorageObject,
20
+ [STORAGE_SHARES_TABLE]: StorageShare
21
+ });
22
+ }
23
+ //#endregion
24
+ export { STORAGE_OBJECTS_TABLE, STORAGE_SHARES_TABLE, storageDatabase, storageTables };
@@ -0,0 +1,58 @@
1
+ import { PithyError } from "@pithy-sh/core/src/error/pithyError";
2
+ import type { MessageParams } from "@pithy-sh/core/src/i18n/catalog";
3
+ /**
4
+ * `@pithy-sh/storage` throw sugar. The `storage/*` codes live in core's closed `KitErrorPayload` union
5
+ * (CLAUDE.md §Errors); these subclasses are the package-local vehicles that set one of those members.
6
+ * Runtime code in this package throws one of these, never a plain `new Error`.
7
+ *
8
+ * Public text goes in `message` and `action`; throw-site context goes in `detail`, which the HTTP
9
+ * codec strips. That matters more here than in most capabilities: object keys, upload ids, and byte
10
+ * counts are exactly the kind of internal shape a client should never be handed.
11
+ */
12
+ interface StorageErrorArgs {
13
+ message?: string;
14
+ action?: string;
15
+ detail?: string;
16
+ /**
17
+ * Values a translating client interpolates into its own wording for this code. Client-facing, so —
18
+ * unlike `action` and `detail` — these cross the boundary with `message`.
19
+ */
20
+ params?: MessageParams;
21
+ }
22
+ export declare class StorageNotFoundError extends PithyError {
23
+ constructor(args?: StorageErrorArgs, options?: {
24
+ cause?: unknown;
25
+ });
26
+ }
27
+ export declare class StorageForbiddenError extends PithyError {
28
+ constructor(args?: StorageErrorArgs, options?: {
29
+ cause?: unknown;
30
+ });
31
+ }
32
+ export declare class StorageQuotaExceededError extends PithyError {
33
+ constructor(args?: StorageErrorArgs, options?: {
34
+ cause?: unknown;
35
+ });
36
+ }
37
+ export declare class StorageUploadIncompleteError extends PithyError {
38
+ constructor(args?: StorageErrorArgs, options?: {
39
+ cause?: unknown;
40
+ });
41
+ }
42
+ export declare class StorageMultipartFailedError extends PithyError {
43
+ constructor(args?: StorageErrorArgs, options?: {
44
+ cause?: unknown;
45
+ });
46
+ }
47
+ export declare class StorageShareExpiredError extends PithyError {
48
+ constructor(args?: StorageErrorArgs, options?: {
49
+ cause?: unknown;
50
+ });
51
+ }
52
+ export declare class StorageShareRevokedError extends PithyError {
53
+ constructor(args?: StorageErrorArgs, options?: {
54
+ cause?: unknown;
55
+ });
56
+ }
57
+ export {};
58
+ //# 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,87 @@
1
+ import { PithyError } from "@pithy-sh/core/src/error/pithyError";
2
+ //#region src/error/errors.ts
3
+ var StorageNotFoundError = class extends PithyError {
4
+ constructor(args = {}, options) {
5
+ super({
6
+ code: "storage/not_found",
7
+ status: 404,
8
+ message: args.message ?? "That file does not exist.",
9
+ action: args.action ?? "Check the object id. A file you do not own reads as missing, not as forbidden.",
10
+ detail: args.detail,
11
+ params: args.params
12
+ }, options);
13
+ }
14
+ };
15
+ var StorageForbiddenError = class extends PithyError {
16
+ constructor(args = {}, options) {
17
+ super({
18
+ code: "storage/forbidden",
19
+ status: 403,
20
+ message: args.message ?? "That file is not yours.",
21
+ action: args.action ?? "Sign in as the owner, or ask them for a share link.",
22
+ detail: args.detail,
23
+ params: args.params
24
+ }, options);
25
+ }
26
+ };
27
+ var StorageQuotaExceededError = class extends PithyError {
28
+ constructor(args = {}, options) {
29
+ super({
30
+ code: "storage/quota_exceeded",
31
+ status: 413,
32
+ message: args.message ?? "That upload would put you over your storage quota.",
33
+ action: args.action ?? "Delete something first, or raise the quota in pithy.config.ts.",
34
+ detail: args.detail,
35
+ params: args.params
36
+ }, options);
37
+ }
38
+ };
39
+ var StorageUploadIncompleteError = class extends PithyError {
40
+ constructor(args = {}, options) {
41
+ super({
42
+ code: "storage/upload_incomplete",
43
+ status: 409,
44
+ message: args.message ?? "That file has not finished uploading.",
45
+ action: args.action ?? "Upload every part, then complete the upload.",
46
+ detail: args.detail,
47
+ params: args.params
48
+ }, options);
49
+ }
50
+ };
51
+ var StorageMultipartFailedError = class extends PithyError {
52
+ constructor(args = {}, options) {
53
+ super({
54
+ code: "storage/multipart_failed",
55
+ status: 500,
56
+ message: args.message ?? "The upload could not be assembled. GET /storage/<id>/parts to see what is missing.",
57
+ detail: args.detail,
58
+ params: args.params
59
+ }, options);
60
+ }
61
+ };
62
+ var StorageShareExpiredError = class extends PithyError {
63
+ constructor(args = {}, options) {
64
+ super({
65
+ code: "storage/share_expired",
66
+ status: 410,
67
+ message: args.message ?? "That share link has expired.",
68
+ action: args.action ?? "Ask the owner for a new one.",
69
+ detail: args.detail,
70
+ params: args.params
71
+ }, options);
72
+ }
73
+ };
74
+ var StorageShareRevokedError = class extends PithyError {
75
+ constructor(args = {}, options) {
76
+ super({
77
+ code: "storage/share_revoked",
78
+ status: 410,
79
+ message: args.message ?? "That share link was revoked.",
80
+ action: args.action ?? "Ask the owner for a new one.",
81
+ detail: args.detail,
82
+ params: args.params
83
+ }, options);
84
+ }
85
+ };
86
+ //#endregion
87
+ export { StorageForbiddenError, StorageMultipartFailedError, StorageNotFoundError, StorageQuotaExceededError, StorageShareExpiredError, StorageShareRevokedError, StorageUploadIncompleteError };
@@ -0,0 +1,18 @@
1
+ import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
2
+ import type { MiddlewareHandler } from "hono";
3
+ /**
4
+ * The storage routes' identity gate.
5
+ *
6
+ * **Copied, not imported.** This is deliberately a local copy of the same three lines
7
+ * `@pithy-sh/media` and `@pithy-sh/ledger` each carry, rather than an import from `@pithy-sh/auth`.
8
+ * Importing it would make auth a hard dependency of storage, and a hard dependency is the wrong
9
+ * shape twice over: storage works perfectly well for system-owned objects with no auth capability
10
+ * composed, and — far more importantly — a package that *imports* its authorization from another
11
+ * package fails open when that package is absent. Depending on the core `AuthContext` seam instead
12
+ * means `c.var.auth` is simply `null` with no auth capability composed, and every owner-scoped
13
+ * route **denies**. Failing closed is not a side effect here; it is the reason for the copy.
14
+ *
15
+ * So `dependsOn` stays free of auth and the manifest lists it under `optionalCapabilities`.
16
+ */
17
+ export declare function requireAuth(): MiddlewareHandler<PithyHonoEnv>;
18
+ //# 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,27 @@
1
+ import { UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
2
+ //#region src/http/guard.ts
3
+ /**
4
+ * The storage routes' identity gate.
5
+ *
6
+ * **Copied, not imported.** This is deliberately a local copy of the same three lines
7
+ * `@pithy-sh/media` and `@pithy-sh/ledger` each carry, rather than an import from `@pithy-sh/auth`.
8
+ * Importing it would make auth a hard dependency of storage, and a hard dependency is the wrong
9
+ * shape twice over: storage works perfectly well for system-owned objects with no auth capability
10
+ * composed, and — far more importantly — a package that *imports* its authorization from another
11
+ * package fails open when that package is absent. Depending on the core `AuthContext` seam instead
12
+ * means `c.var.auth` is simply `null` with no auth capability composed, and every owner-scoped
13
+ * route **denies**. Failing closed is not a side effect here; it is the reason for the copy.
14
+ *
15
+ * So `dependsOn` stays free of auth and the manifest lists it under `optionalCapabilities`.
16
+ */
17
+ function requireAuth() {
18
+ return async (c, next) => {
19
+ if (!c.var.auth) throw new UnauthorizedError({
20
+ message: "Authentication required.",
21
+ action: "Sign in and retry with a valid session or bearer token."
22
+ });
23
+ await next();
24
+ };
25
+ }
26
+ //#endregion
27
+ export { requireAuth };