@pithy-sh/core 0.10.0 → 0.12.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 (270) hide show
  1. package/dist/access/access.d.ts +172 -0
  2. package/dist/access/access.d.ts.map +1 -0
  3. package/dist/access/access.js +147 -0
  4. package/dist/access/acting.d.ts +49 -0
  5. package/dist/access/acting.d.ts.map +1 -0
  6. package/dist/access/acting.js +21 -0
  7. package/dist/access/policyCheck.d.ts +33 -0
  8. package/dist/access/policyCheck.d.ts.map +1 -0
  9. package/dist/access/policyCheck.js +48 -0
  10. package/dist/access/usage.d.ts +83 -0
  11. package/dist/access/usage.d.ts.map +1 -0
  12. package/dist/access/usage.js +104 -0
  13. package/dist/access/visibility.d.ts +66 -0
  14. package/dist/access/visibility.d.ts.map +1 -0
  15. package/dist/access/visibility.js +86 -0
  16. package/dist/audit/auditEvent.d.ts +5 -0
  17. package/dist/audit/auditEvent.d.ts.map +1 -1
  18. package/dist/audit/auditEvent.js +2 -0
  19. package/dist/audit/recorder.d.ts +10 -2
  20. package/dist/audit/recorder.d.ts.map +1 -1
  21. package/dist/capability/bindings.d.ts +47 -2
  22. package/dist/capability/bindings.d.ts.map +1 -1
  23. package/dist/capability/bindings.js +117 -7
  24. package/dist/capability/capability.d.ts +110 -28
  25. package/dist/capability/capability.d.ts.map +1 -1
  26. package/dist/capability/capability.js +2 -0
  27. package/dist/capability/manifest.d.ts +2 -1
  28. package/dist/capability/manifest.d.ts.map +1 -1
  29. package/dist/capability/manifest.js +1 -1
  30. package/dist/capability/purge.d.ts +80 -0
  31. package/dist/capability/purge.d.ts.map +1 -0
  32. package/dist/capability/purge.js +76 -0
  33. package/dist/capability/settings.d.ts +86 -2
  34. package/dist/capability/settings.d.ts.map +1 -1
  35. package/dist/capability/settings.js +80 -1
  36. package/dist/cli/commandCatalog.generated.d.ts +238 -24
  37. package/dist/cli/commandCatalog.generated.d.ts.map +1 -1
  38. package/dist/cli/commandCatalog.generated.js +251 -22
  39. package/dist/cli/commandFacts.d.ts +2 -1
  40. package/dist/cli/commandFacts.d.ts.map +1 -1
  41. package/dist/cli/commandFacts.js +2 -0
  42. package/dist/controlPlane/capability.d.ts.map +1 -1
  43. package/dist/controlPlane/capability.js +19 -2
  44. package/dist/controlPlane/context.d.ts +5 -0
  45. package/dist/controlPlane/context.d.ts.map +1 -1
  46. package/dist/controlPlane/context.js +3 -1
  47. package/dist/controlPlane/data/connection.d.ts +49 -12
  48. package/dist/controlPlane/data/connection.d.ts.map +1 -1
  49. package/dist/controlPlane/data/connection.js +56 -2
  50. package/dist/controlPlane/discovery/adminRoute.d.ts +29 -0
  51. package/dist/controlPlane/discovery/adminRoute.d.ts.map +1 -1
  52. package/dist/controlPlane/discovery/adminRoute.js +3 -0
  53. package/dist/controlPlane/error/errors.d.ts +4 -3
  54. package/dist/controlPlane/error/errors.d.ts.map +1 -1
  55. package/dist/controlPlane/http/cors.d.ts +4 -4
  56. package/dist/controlPlane/http/cors.js +4 -4
  57. package/dist/controlPlane/http/guard.d.ts +11 -0
  58. package/dist/controlPlane/http/guard.d.ts.map +1 -1
  59. package/dist/controlPlane/http/guard.js +17 -1
  60. package/dist/controlPlane/http/handlers.d.ts +139 -0
  61. package/dist/controlPlane/http/handlers.d.ts.map +1 -1
  62. package/dist/controlPlane/http/handlers.js +67 -4
  63. package/dist/controlPlane/http/readiness.d.ts +33 -0
  64. package/dist/controlPlane/http/readiness.d.ts.map +1 -0
  65. package/dist/controlPlane/http/readiness.js +39 -0
  66. package/dist/controlPlane/http/responses.d.ts +245 -0
  67. package/dist/controlPlane/http/responses.d.ts.map +1 -1
  68. package/dist/controlPlane/http/responses.js +101 -4
  69. package/dist/controlPlane/http/routes.d.ts +2 -0
  70. package/dist/controlPlane/http/routes.d.ts.map +1 -1
  71. package/dist/controlPlane/http/routes.js +31 -3
  72. package/dist/controlPlane/http/verify.d.ts.map +1 -1
  73. package/dist/controlPlane/http/verify.js +2 -1
  74. package/dist/controlPlane/migrationState/migrationState.d.ts +102 -0
  75. package/dist/controlPlane/migrationState/migrationState.d.ts.map +1 -0
  76. package/dist/controlPlane/migrationState/migrationState.js +142 -0
  77. package/dist/controlPlane/migrations/0003_connection_principal.d.ts +21 -0
  78. package/dist/controlPlane/migrations/0003_connection_principal.d.ts.map +1 -0
  79. package/dist/controlPlane/migrations/0003_connection_principal.js +33 -0
  80. package/dist/controlPlane/scope/scope.d.ts +23 -2
  81. package/dist/controlPlane/scope/scope.d.ts.map +1 -1
  82. package/dist/controlPlane/scope/scope.js +24 -3
  83. package/dist/createBackend.d.ts.map +1 -1
  84. package/dist/createBackend.js +9 -2
  85. package/dist/createEntrypoint.d.ts.map +1 -1
  86. package/dist/createEntrypoint.js +5 -3
  87. package/dist/crypto/envelope.d.ts +86 -0
  88. package/dist/crypto/envelope.d.ts.map +1 -0
  89. package/dist/crypto/envelope.js +129 -0
  90. package/dist/crypto/fieldKeys.d.ts +41 -0
  91. package/dist/crypto/fieldKeys.d.ts.map +1 -0
  92. package/dist/crypto/fieldKeys.js +56 -0
  93. package/dist/data/codecs.d.ts +23 -10
  94. package/dist/data/codecs.d.ts.map +1 -1
  95. package/dist/data/codecs.js +50 -36
  96. package/dist/entitlement/allowance.d.ts +25 -0
  97. package/dist/entitlement/allowance.d.ts.map +1 -0
  98. package/dist/entitlement/allowance.js +80 -0
  99. package/dist/entitlement/entitlement.d.ts +41 -0
  100. package/dist/entitlement/entitlement.d.ts.map +1 -1
  101. package/dist/entitlement/meter.d.ts +57 -0
  102. package/dist/entitlement/meter.d.ts.map +1 -0
  103. package/dist/entitlement/meter.js +13 -0
  104. package/dist/error/extend.d.ts +6 -5
  105. package/dist/error/extend.d.ts.map +1 -1
  106. package/dist/error/http.d.ts +168 -0
  107. package/dist/error/http.d.ts.map +1 -1
  108. package/dist/error/payload.d.ts +336 -0
  109. package/dist/error/payload.d.ts.map +1 -1
  110. package/dist/error/payload.js +116 -4
  111. package/dist/error/pithyError.d.ts +18 -7
  112. package/dist/error/pithyError.d.ts.map +1 -1
  113. package/dist/error/pithyError.js +6 -0
  114. package/dist/http/authContext.d.ts +7 -0
  115. package/dist/http/authContext.d.ts.map +1 -1
  116. package/dist/http/authContext.js +8 -1
  117. package/dist/http/scopeGates.d.ts +20 -0
  118. package/dist/http/scopeGates.d.ts.map +1 -0
  119. package/dist/http/scopeGates.js +36 -0
  120. package/dist/index.d.ts +1 -1
  121. package/dist/index.d.ts.map +1 -1
  122. package/dist/index.js +2 -2
  123. package/dist/logger/logger.d.ts +12 -5
  124. package/dist/logger/logger.d.ts.map +1 -1
  125. package/dist/logger/record.d.ts +98 -0
  126. package/dist/logger/record.d.ts.map +1 -1
  127. package/dist/migrations/capabilitySets.d.ts +23 -0
  128. package/dist/migrations/capabilitySets.d.ts.map +1 -0
  129. package/dist/migrations/capabilitySets.js +74 -0
  130. package/dist/migrations/registry.d.ts +26 -0
  131. package/dist/migrations/registry.d.ts.map +1 -1
  132. package/dist/migrations/registry.js +38 -7
  133. package/dist/migrations/state.d.ts +60 -0
  134. package/dist/migrations/state.d.ts.map +1 -0
  135. package/dist/migrations/state.js +46 -0
  136. package/dist/naming/feature.d.ts +27 -5
  137. package/dist/naming/feature.d.ts.map +1 -1
  138. package/dist/naming/feature.js +36 -6
  139. package/dist/naming/limits.d.ts +47 -3
  140. package/dist/naming/limits.d.ts.map +1 -1
  141. package/dist/naming/limits.js +47 -3
  142. package/dist/naming/provisionScope.d.ts +6 -0
  143. package/dist/naming/provisionScope.d.ts.map +1 -1
  144. package/dist/naming/provisionScope.js +8 -3
  145. package/dist/naming/resourceNames.d.ts +21 -2
  146. package/dist/naming/resourceNames.d.ts.map +1 -1
  147. package/dist/naming/resourceNames.js +21 -3
  148. package/dist/privacy/blindIndex.d.ts +27 -0
  149. package/dist/privacy/blindIndex.d.ts.map +1 -0
  150. package/dist/privacy/blindIndex.js +57 -0
  151. package/dist/privacy/classes.d.ts +142 -0
  152. package/dist/privacy/classes.d.ts.map +1 -0
  153. package/dist/privacy/classes.js +209 -0
  154. package/dist/privacy/classify.d.ts +336 -0
  155. package/dist/privacy/classify.d.ts.map +1 -0
  156. package/dist/privacy/classify.js +1024 -0
  157. package/dist/privacy/encrypted.d.ts +210 -0
  158. package/dist/privacy/encrypted.d.ts.map +1 -0
  159. package/dist/privacy/encrypted.js +350 -0
  160. package/dist/privacy/encryptedColumns.d.ts +64 -0
  161. package/dist/privacy/encryptedColumns.d.ts.map +1 -0
  162. package/dist/privacy/encryptedColumns.js +134 -0
  163. package/dist/privacy/fieldRotation.d.ts +34 -0
  164. package/dist/privacy/fieldRotation.d.ts.map +1 -0
  165. package/dist/privacy/fieldRotation.js +186 -0
  166. package/dist/privacy/inventory.d.ts +12 -0
  167. package/dist/privacy/inventory.d.ts.map +1 -0
  168. package/dist/privacy/inventory.js +154 -0
  169. package/dist/privacy/posture.d.ts +114 -0
  170. package/dist/privacy/posture.d.ts.map +1 -0
  171. package/dist/privacy/posture.js +136 -0
  172. package/dist/privacy/redact.d.ts +7 -0
  173. package/dist/privacy/redact.d.ts.map +1 -0
  174. package/dist/privacy/redact.js +404 -0
  175. package/dist/privacy/report.d.ts +58 -0
  176. package/dist/privacy/report.d.ts.map +1 -0
  177. package/dist/privacy/report.js +15 -0
  178. package/dist/privacy/retirement.d.ts +68 -0
  179. package/dist/privacy/retirement.d.ts.map +1 -0
  180. package/dist/privacy/retirement.js +72 -0
  181. package/dist/privacy/sealed.d.ts +87 -0
  182. package/dist/privacy/sealed.d.ts.map +1 -0
  183. package/dist/privacy/sealed.js +221 -0
  184. package/dist/privacy/types.d.ts +559 -0
  185. package/dist/privacy/types.d.ts.map +1 -0
  186. package/dist/privacy/types.js +2 -0
  187. package/dist/seed/writeD1.d.ts +7 -1
  188. package/dist/seed/writeD1.d.ts.map +1 -1
  189. package/dist/seed/writeD1.js +9 -3
  190. package/dist/seed/writeKv.d.ts +2 -0
  191. package/dist/seed/writeKv.d.ts.map +1 -1
  192. package/dist/seed/writeKv.js +6 -2
  193. package/dist/version.generated.d.ts +1 -1
  194. package/dist/version.generated.js +1 -1
  195. package/dist/worker/serviceLoopback.d.ts +36 -0
  196. package/dist/worker/serviceLoopback.d.ts.map +1 -0
  197. package/dist/worker/serviceLoopback.js +74 -0
  198. package/dist/workflow/faults.d.ts +12 -1
  199. package/dist/workflow/faults.d.ts.map +1 -1
  200. package/dist/workflow/faults.js +22 -15
  201. package/package.json +2 -2
  202. package/src/access/access.ts +298 -0
  203. package/src/access/acting.ts +59 -0
  204. package/src/access/policyCheck.ts +77 -0
  205. package/src/access/usage.ts +141 -0
  206. package/src/access/visibility.ts +109 -0
  207. package/src/audit/auditEvent.ts +4 -0
  208. package/src/audit/recorder.ts +10 -2
  209. package/src/capability/bindings.ts +159 -13
  210. package/src/capability/capability.ts +114 -29
  211. package/src/capability/purge.ts +124 -0
  212. package/src/capability/settings.ts +146 -2
  213. package/src/cli/commandCatalog.generated.ts +271 -22
  214. package/src/cli/commandFacts.ts +2 -0
  215. package/src/controlPlane/capability.ts +36 -1
  216. package/src/controlPlane/context.ts +4 -0
  217. package/src/controlPlane/data/connection.ts +90 -0
  218. package/src/controlPlane/discovery/adminRoute.ts +11 -0
  219. package/src/controlPlane/error/errors.ts +4 -3
  220. package/src/controlPlane/http/cors.ts +4 -4
  221. package/src/controlPlane/http/guard.ts +21 -0
  222. package/src/controlPlane/http/handlers.ts +98 -4
  223. package/src/controlPlane/http/readiness.ts +50 -0
  224. package/src/controlPlane/http/responses.ts +240 -2
  225. package/src/controlPlane/http/routes.ts +55 -1
  226. package/src/controlPlane/http/verify.ts +2 -0
  227. package/src/controlPlane/migrationState/migrationState.ts +200 -0
  228. package/src/controlPlane/migrations/0003_connection_principal.ts +37 -0
  229. package/src/controlPlane/scope/scope.ts +25 -2
  230. package/src/controlPlane/token/base64url.ts +1 -1
  231. package/src/createBackend.ts +28 -6
  232. package/src/createEntrypoint.ts +9 -3
  233. package/src/crypto/envelope.ts +196 -0
  234. package/src/crypto/fieldKeys.ts +76 -0
  235. package/src/data/codecs.ts +69 -37
  236. package/src/entitlement/allowance.ts +85 -0
  237. package/src/entitlement/entitlement.ts +38 -0
  238. package/src/entitlement/meter.ts +69 -0
  239. package/src/error/extend.ts +6 -5
  240. package/src/error/payload.ts +253 -4
  241. package/src/error/pithyError.ts +21 -7
  242. package/src/http/authContext.ts +13 -1
  243. package/src/http/scopeGates.ts +34 -0
  244. package/src/index.ts +2 -0
  245. package/src/logger/logger.ts +12 -5
  246. package/src/migrations/capabilitySets.ts +87 -0
  247. package/src/migrations/registry.ts +46 -2
  248. package/src/migrations/state.ts +94 -0
  249. package/src/naming/feature.ts +46 -7
  250. package/src/naming/limits.ts +35 -3
  251. package/src/naming/provisionScope.ts +19 -1
  252. package/src/naming/resourceNames.ts +52 -5
  253. package/src/privacy/blindIndex.ts +81 -0
  254. package/src/privacy/classes.ts +277 -0
  255. package/src/privacy/classify.ts +1447 -0
  256. package/src/privacy/encrypted.ts +513 -0
  257. package/src/privacy/encryptedColumns.ts +185 -0
  258. package/src/privacy/fieldRotation.ts +234 -0
  259. package/src/privacy/inventory.ts +147 -0
  260. package/src/privacy/posture.ts +205 -0
  261. package/src/privacy/redact.ts +423 -0
  262. package/src/privacy/report.ts +64 -0
  263. package/src/privacy/retirement.ts +102 -0
  264. package/src/privacy/sealed.ts +323 -0
  265. package/src/privacy/types.ts +804 -0
  266. package/src/seed/writeD1.ts +13 -4
  267. package/src/seed/writeKv.ts +6 -2
  268. package/src/version.generated.ts +1 -1
  269. package/src/worker/serviceLoopback.ts +105 -0
  270. package/src/workflow/faults.ts +51 -24
@@ -0,0 +1,76 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { remedy } from "../cli/command";
5
+ import { InternalError } from "../error/pithyError";
6
+ import { EncryptionConfig } from "./envelope";
7
+
8
+ /**
9
+ * **The field key: what an app Worker seals its encrypted fields with** (#390).
10
+ *
11
+ * `PITHY_FIELD_KEYS` is an {@link EncryptionConfig}, the same versioned shape as secrets' master key, and it is a
12
+ * **different key on purpose**. Field encryption seals and opens inside the adopter's own Workers, so every Worker that
13
+ * holds an encrypted field must hold the key it uses. Were that the master key `SECRETS_ENCRYPTION_KEYS`, every such
14
+ * Worker would hold the key to the whole secrets vault, and one compromised would open it. A key of its own limits
15
+ * that to the fields: a Worker that holds an encrypted field and composes no `secrets` is bound this key and never
16
+ * the master key.
17
+ *
18
+ * It is not a second mechanism: `pithy secrets provision` mints it beside the master key, in the same format, binds
19
+ * it to every Worker that holds an encrypted field, and the manager's at-rest cron rotates it every
20
+ * {@link FIELD_KEY_ROTATION_DAYS} days.
21
+ */
22
+
23
+ /** The binding an app Worker reads its field key through. Fixed across environments; only the store entry is scoped. */
24
+ export const FIELD_KEYS_BINDING = "PITHY_FIELD_KEYS";
25
+
26
+ /** How often the manager rotates the field key, in days. */
27
+ export const FIELD_KEY_ROTATION_DAYS = 30;
28
+
29
+ /** A Secrets Store binding: `.get()` resolves the plaintext inside the Worker. */
30
+ export interface FieldKeyBinding {
31
+ get(): Promise<string>;
32
+ }
33
+
34
+ /**
35
+ * Where a field key comes from: the Worker's `env.PITHY_FIELD_KEYS` binding (a Secrets Store binding deployed, a JSON
36
+ * string from `.dev.vars` locally), or a config a caller already resolved.
37
+ */
38
+ export type FieldKeys = FieldKeyBinding | string | EncryptionConfig;
39
+
40
+ /**
41
+ * Resolve a field key to its config. A missing binding, text that is not JSON, and JSON that is not a key set are each
42
+ * refused, and **nothing read is ever echoed**: what failed to parse is the key set.
43
+ */
44
+ export async function resolveFieldKeys(keys: FieldKeys | undefined): Promise<EncryptionConfig> {
45
+ let raw: unknown = keys;
46
+ if (keys === undefined || keys === null) {
47
+ throw new InternalError({
48
+ message: "This Worker holds an encrypted field and no field key.",
49
+ action: `Bind ${FIELD_KEYS_BINDING}. ${remedy("secrets provision").say((command) => `${command} binds it to every Worker with an encrypted field.`)}`,
50
+ detail: `${FIELD_KEYS_BINDING} binding is not configured`,
51
+ });
52
+ }
53
+ if (typeof keys === "object" && "get" in keys && typeof keys.get === "function") raw = await keys.get();
54
+ if (typeof raw === "string") {
55
+ try {
56
+ raw = JSON.parse(raw);
57
+ } catch {
58
+ throw new InternalError({ detail: `${FIELD_KEYS_BINDING} is not valid JSON` });
59
+ }
60
+ }
61
+ const parsed = EncryptionConfig.safeParse(raw);
62
+ if (!parsed.success) throw new InternalError({ detail: `${FIELD_KEYS_BINDING} is not a valid EncryptionConfig` });
63
+ return parsed.data;
64
+ }
65
+
66
+ /**
67
+ * Every live version in a key set, newest first, as numbers. A version key that is not an integer is refused rather
68
+ * than sorted as text, where `"10"` sorts before `"9"`.
69
+ */
70
+ export function liveVersions(config: EncryptionConfig): number[] {
71
+ const versions = Object.keys(config.versions).map(Number);
72
+ if (!versions.every((version) => Number.isInteger(version))) {
73
+ throw new InternalError({ detail: `${FIELD_KEYS_BINDING}: a version key is not a stringified integer` });
74
+ }
75
+ return versions.sort((left, right) => right - left);
76
+ }
@@ -85,46 +85,78 @@ export const JsonDate = z.codec(z.union([z.string(), z.number(), z.date()]), z.d
85
85
  });
86
86
 
87
87
  /**
88
- * sqliteJson: T ↔ JSON string, validated by `schema` on both sides. Decode
89
- * accepts a JSON string or an already-parsed value; the result is validated
90
- * against `schema` before it reaches the app.
88
+ * sqliteJson's decode: a JSON string is parsed, an already-parsed value passes through. One function for every
89
+ * column, so `isSqliteJson` can tell the kit's codec from any other by its decode.
91
90
  *
92
- * **Both `JSON` functions throw**, and both were reachable. `JSON.parse` throws a
93
- * `SyntaxError` on any string that is not a JSON document — which a column holding
94
- * text an older writer put there, or a payload a customer's Worker returned, can be.
95
- * `JSON.stringify` throws a `TypeError` on a `BigInt` and on a cycle, either of
96
- * which a `schema` can legitimately admit. Both become an issue (#358).
91
+ * **`JSON.parse` throws**, and it was reachable: a column holding text an older writer put there, or a payload a
92
+ * customer's Worker returned, need not be a JSON document. That becomes an issue (#358).
97
93
  */
98
- export function sqliteJson<T extends z.ZodType>(schema: T) {
99
- return z.codec(z.union([z.string(), schema]), schema, {
100
- decode: (value, payload): z.input<T> => {
101
- if (typeof value !== "string") return value as z.input<T>;
102
- try {
103
- return JSON.parse(value) as z.input<T>;
104
- } catch {
105
- payload.issues.push({ code: "invalid_format", format: "json", input: value, message: "Not valid JSON." });
106
- return z.NEVER;
107
- }
108
- },
109
- encode: (value, payload): string => {
110
- // The offending value is deliberately not carried onto the issue: it is the thing JSON could not
111
- // hold, so a reporter that renders an issue would be the second place to trip over it.
112
- try {
113
- const json = JSON.stringify(value);
114
- if (typeof json === "string") return json;
115
- } catch {
116
- // Falls through to the one push below. A `BigInt`, a cycle and an `undefined` result are the
117
- // same answer — this value does not survive the round trip — and they deserve the same issue.
118
- }
119
- payload.issues.push({
120
- code: "invalid_format",
121
- format: "json",
122
- input: undefined,
123
- message: "Not serializable as JSON.",
124
- });
125
- return z.NEVER;
126
- },
94
+ function decodeJson(value: unknown, payload: Payload<unknown>): unknown {
95
+ if (typeof value !== "string") return value;
96
+ try {
97
+ return JSON.parse(value);
98
+ } catch {
99
+ payload.issues.push({ code: "invalid_format", format: "json", input: value, message: "Not valid JSON." });
100
+ return z.NEVER;
101
+ }
102
+ }
103
+
104
+ /**
105
+ * sqliteJson's encode. **`JSON.stringify` throws** on a `BigInt` and on a cycle, either of which a schema can
106
+ * legitimately admit, so that becomes an issue too (#358).
107
+ */
108
+ function encodeJson(value: unknown, payload: Payload<unknown>): string {
109
+ // The offending value is deliberately not carried onto the issue: it is the thing JSON could not hold, so a
110
+ // reporter that renders an issue would be the second place to trip over it.
111
+ try {
112
+ const json = JSON.stringify(value);
113
+ if (typeof json === "string") return json;
114
+ } catch {
115
+ // Falls through to the one push below. A `BigInt`, a cycle and an `undefined` result are the same answer —
116
+ // this value does not survive the round trip — and they deserve the same issue.
117
+ }
118
+ payload.issues.push({
119
+ code: "invalid_format",
120
+ format: "json",
121
+ input: undefined,
122
+ message: "Not serializable as JSON.",
127
123
  });
124
+ return z.NEVER;
125
+ }
126
+
127
+ /**
128
+ * sqliteJson: T ↔ JSON string, validated by `schema` on both sides. Decode accepts a JSON string or an
129
+ * already-parsed value; the result is validated against `schema` before it reaches the app.
130
+ */
131
+ export function sqliteJson<T extends z.ZodType>(schema: T): SqliteJson<T> {
132
+ return z.codec(z.union([z.string(), schema]), schema, {
133
+ decode: decodeJson as (value: string | z.output<T>, payload: Payload<string | z.output<T>>) => z.input<T>,
134
+ encode: encodeJson as (value: z.input<T>, payload: Payload<z.input<T>>) => string,
135
+ }) as SqliteJson<T>;
136
+ }
137
+
138
+ /**
139
+ * Names the type `sqliteJson` returns, and nothing else. A type only: no value carries it. `Redacted<T>` reads a JSON
140
+ * column's fields through it, as `redact` reads them through {@link isSqliteJson}, so an adopter's codec of the same
141
+ * shape is opaque to both.
142
+ */
143
+ declare const kitJsonColumn: unique symbol;
144
+
145
+ /** What `sqliteJson(schema)` returns: the kit's JSON column over `schema`. Clones keep it, as they return `this`. */
146
+ export type SqliteJson<T extends z.ZodType> = z.ZodCodec<z.ZodUnion<[z.ZodString, T]>, T> & {
147
+ readonly [kitJsonColumn]: T;
148
+ };
149
+
150
+ /** The schema a kit JSON column decodes to, or `never` for any other node. */
151
+ export type SqliteJsonSchema<S> = S extends { readonly [kitJsonColumn]: infer T } ? T : never;
152
+
153
+ /**
154
+ * Whether a schema is a JSON column `sqliteJson` built, or a clone of one (`.describe()`, `.meta()`), read by its
155
+ * decode. `redact` walks such a column's fields one by one, and treats every other codec as opaque.
156
+ */
157
+ export function isSqliteJson(schema: z.ZodType): boolean {
158
+ const def = schema._zod.def as { type: string; transform?: unknown };
159
+ return def.type === "pipe" && def.transform === decodeJson;
128
160
  }
129
161
 
130
162
  export const MAX_TIMEZONE_LENGTH = 64;
@@ -0,0 +1,85 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { Context } from "hono";
5
+ import type { PithyHonoEnv } from "../capability/capability";
6
+ import { InternalError, messageOf } from "../error/pithyError";
7
+ import type { MeterLimit } from "./entitlement";
8
+
9
+ /**
10
+ * The allowance readers — how much the current caller may have, and whether a switch is on.
11
+ *
12
+ * const seats = await quota(c, "seats"); // number, or null for unlimited
13
+ * if (seats !== null && (await countMembers(orgId)) >= seats) throw new SeatLimitReached(…);
14
+ * if (await feature(c, "auditExport")) { … } // boolean, never null
15
+ *
16
+ * **Neither takes an entitlement key, and that is the point.** A route does not know which tier the
17
+ * caller's holder is on, and during an upgrade overlap it holds two. The provider resolves across every
18
+ * key the holder has and answers the higher, so an adopter compares numbers and never ranks tiers.
19
+ *
20
+ * **Read, never enforced.** A quota denies nothing on its own and a feature set to `false` denies
21
+ * nothing either — `requireEntitlement` still gates on the key alone. What a number means for a request
22
+ * is the adopter's code to decide, because only the adopter can count what it owns.
23
+ *
24
+ * **They live in core for the reason `requireEntitlement` does.** A reader that arrived with
25
+ * `@pithy-sh/payments` would be absent when payments is, and a route reading an allowance must then fail
26
+ * rather than read something. So with no provider composed — or one that declares no allowances — both
27
+ * throw `core/internal` naming the gap. Never `0`, which is a paywall shut for a reason nobody can see;
28
+ * never unlimited, which is a paywall that does not exist.
29
+ */
30
+
31
+ /** The refusal when nothing on the request can answer an allowance. The adopter's wiring, so `core/internal`. */
32
+ function noProvider(c: Context<PithyHonoEnv>, kind: "quota" | "feature", name: string): InternalError {
33
+ const provider = c.var.entitlements?.provider ?? null;
34
+ return new InternalError({
35
+ message: `No ${kind} "${name}" can be resolved here.`,
36
+ action: "Compose a payments capability that declares its entitlements in this Worker's pithy.config.ts.",
37
+ detail:
38
+ provider === null
39
+ ? `no entitlement provider is composed, so ${kind}("${name}") has nothing to read.`
40
+ : `${provider} resolves entitlements and declares no allowances, so ${kind}("${name}") has nothing to read.`,
41
+ });
42
+ }
43
+
44
+ /** How many of `name` the caller's holder may have: a whole number, or `null` for unlimited. */
45
+ export async function quota(c: Context<PithyHonoEnv>, name: string): Promise<number | null> {
46
+ const resolver = c.var.entitlements;
47
+ if (!resolver?.quota) throw noProvider(c, "quota", name);
48
+ return resolver.quota(name);
49
+ }
50
+
51
+ /** Whether `name` is on for the caller's holder. Always a boolean. */
52
+ export async function feature(c: Context<PithyHonoEnv>, name: string): Promise<boolean> {
53
+ const resolver = c.var.entitlements;
54
+ if (!resolver?.feature) throw noProvider(c, "feature", name);
55
+ return resolver.feature(name);
56
+ }
57
+
58
+ /**
59
+ * The ceiling a capability enforces on a meter it counts itself, for the current caller.
60
+ *
61
+ * **No provider, or one that binds nothing to this meter, is `{ enforced: false }`** — and the capability
62
+ * keeps its own configured ceiling. Enforcement is opt-in per meter because a cap that arrives by surprise
63
+ * breaks an adopter who was already over it.
64
+ *
65
+ * **A provider that throws refuses, and logs.** Storage already says which way round to err: over-counting
66
+ * briefly and reclaiming is the right way round, and under-counting has no recovery. Treating a failed read
67
+ * as unenforced would hand a customer an unbounded allowance for as long as the read kept failing. The cost
68
+ * is real and is stated rather than discovered: our bug becomes a refused write for a paying customer.
69
+ * Enforcement being opt-in is what bounds it — an adopter who would rather over-serve leaves the meter
70
+ * advisory.
71
+ */
72
+ export async function meterLimit(c: Context<PithyHonoEnv>, meter: string): Promise<MeterLimit> {
73
+ const resolver = c.var.entitlements;
74
+ if (!resolver?.meterLimit) return { enforced: false };
75
+ try {
76
+ return await resolver.meterLimit(meter);
77
+ } catch (error) {
78
+ c.var.log?.error("meter limit resolution failed", { provider: resolver.provider, meter, cause: messageOf(error) });
79
+ throw new InternalError({
80
+ message: "Usage could not be checked, so nothing was written.",
81
+ action: "Read the preceding log line for why the allowance read failed.",
82
+ detail: `${resolver.provider} threw resolving the ${meter} meter's ceiling; refusing rather than serving unbounded.`,
83
+ });
84
+ }
85
+ }
@@ -132,8 +132,46 @@ export interface EntitlementResolver {
132
132
  * See {@link EntitlementHolder} for why this is a label and a tenant rather than the holder itself.
133
133
  */
134
134
  holder?(): Promise<EntitlementHolder | undefined>;
135
+ /**
136
+ * How many of `name` the current caller's holder may have — a whole number, or `null` for unlimited.
137
+ * Optional: a provider with no allowances omits it, and {@link import("./allowance").quota} refuses
138
+ * rather than inventing a number. A provider throws for a name it does not declare, never answers 0.
139
+ */
140
+ quota?(name: string): Promise<number | null>;
141
+ /** Whether `name` is on for the current caller's holder. Never null. Optional, as {@link quota} is. */
142
+ feature?(name: string): Promise<boolean>;
143
+ /**
144
+ * The ceiling a capability that counts its own rows enforces for `meter` — storage's bytes, media's
145
+ * items — or `{ enforced: false }` where the provider binds no ceiling to it. Optional, and absent is
146
+ * `{ enforced: false }`: a capability composed with no provider keeps its own configured behavior.
147
+ */
148
+ meterLimit?(meter: string): Promise<MeterLimit>;
135
149
  }
136
150
 
151
+ /**
152
+ * What a provider says about one meter for the current caller: whether it binds a ceiling at all, and if
153
+ * it does, what the ceiling is and whose rows it covers. `limit: null` is unlimited — an enforced meter on
154
+ * a subject whose plan or override says so.
155
+ *
156
+ * Two states rather than a nullable number, because "this meter is advisory here" and "this subject is
157
+ * unlimited" are different facts and a capability must fall back to its own configured ceiling on the
158
+ * first and never on the second.
159
+ *
160
+ * **An enforced ceiling says which rows it is the whole of**, because a ceiling counted against the wrong
161
+ * rows is a different allowance. Under organization billing the plan's 10 GB is the company's: counted
162
+ * against one member's files it becomes 10 GB per member, and a paid quota is bypassed by an invitation.
163
+ * So `tenant` is the organization the ceiling was resolved for, exactly as {@link EntitlementHolder.tenant}
164
+ * is, and a capability sums every row it holds for that tenant, whoever wrote it. `null` means the holder
165
+ * is not a tenant: the ceiling is the caller's own, and the caller's rows are what count.
166
+ *
167
+ * It is a counting key, never a gate. A capability that would write a row for a different tenant than the
168
+ * one the ceiling covers refuses the write — that row would sit outside the sum, and under-counting has no
169
+ * recovery.
170
+ */
171
+ export type MeterLimit =
172
+ | { readonly enforced: false }
173
+ | { readonly enforced: true; readonly limit: number | null; readonly tenant: string | null };
174
+
137
175
  /**
138
176
  * How a resolver's holder appears in a denial's `detail` and on the denial's audit row — and **nothing a
139
177
  * gate may compare**.
@@ -0,0 +1,69 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { Capability } from "../capability/capability";
5
+ import type { Logger } from "../logger/logger";
6
+
7
+ /**
8
+ * The usage-meter seam — how a capability that writes the rows a meter counts asks whether one more is
9
+ * allowed, when there is no request to ask through.
10
+ *
11
+ * `@pithy-sh/email` enqueues from a route, from a Workflow step and from a cron, and only the first has a
12
+ * `c.var.entitlements`. So the meter it charges is found the way the ledger is found — among the composed
13
+ * capabilities, by a structural predicate — and it is handed the holder explicitly. Nothing here imports the
14
+ * provider: an email capability composed with no payments finds no meter and enqueues as it always did.
15
+ *
16
+ * **A meter refuses; it never bills.** `charge` either records the use or throws the provider's own refusal
17
+ * (`payments/quota_exceeded`, 402). What it counted is never reported to a store — the kit does not sell
18
+ * overage — so this seam has no way to read a count back out.
19
+ */
20
+
21
+ /** Who a charge is against: the holder pair, exactly as the provider keys it. */
22
+ export interface MeterSubject {
23
+ /** The kind of holder — `user` or `organization` under `@pithy-sh/payments`. */
24
+ readonly subjectType: string;
25
+ /** The holder's id. */
26
+ readonly subjectId: string;
27
+ }
28
+
29
+ /** One charge against one meter. */
30
+ export interface MeterCharge {
31
+ /** Who uses it. */
32
+ readonly subject: MeterSubject;
33
+ /** Which meter — `emails`. */
34
+ readonly meter: string;
35
+ /** How many. A whole number from 1. */
36
+ readonly amount: number;
37
+ /** The clock. Defaults to now. */
38
+ readonly now?: Date;
39
+ /** Where a refused or failed charge is logged. Optional; the provider logs through its own when absent. */
40
+ readonly log?: Logger;
41
+ }
42
+
43
+ /** The meter a provider exposes. */
44
+ export interface UsageMeter {
45
+ /** The capability answering — `payments`. */
46
+ readonly provider: string;
47
+ /**
48
+ * Record `amount` of `meter` against `subject`, or refuse. An advisory meter records nothing and refuses
49
+ * nothing. **A charge that cannot be checked refuses**, because under-counting has no recovery.
50
+ */
51
+ charge(env: Record<string, unknown>, charge: MeterCharge): Promise<void>;
52
+ }
53
+
54
+ /** A composed capability that provides a meter. */
55
+ export interface UsageMeterProvider extends Capability {
56
+ /** The meter. */
57
+ readonly usageMeter: UsageMeter;
58
+ }
59
+
60
+ /** Whether a composed capability provides a usage meter. Structural, so no provider package is imported. */
61
+ export function isUsageMeterProvider(capability: Capability): capability is UsageMeterProvider {
62
+ const meter = (capability as { usageMeter?: { charge?: unknown } }).usageMeter;
63
+ return typeof meter?.charge === "function";
64
+ }
65
+
66
+ /** The composed usage meter, or undefined when nothing composed provides one. */
67
+ export function composedUsageMeter(capabilities: readonly Capability[]): UsageMeter | undefined {
68
+ return capabilities.find(isUsageMeterProvider)?.usageMeter;
69
+ }
@@ -2,6 +2,7 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import type { MessageParams } from "../i18n/catalog";
5
+ import type { UnmarkedString } from "../privacy/types";
5
6
  import type { ErrorPayload, KitErrorDomain } from "./payload";
6
7
  import { ExtendedErrorPayload } from "./payload";
7
8
  import { InternalError } from "./pithyError";
@@ -95,11 +96,11 @@ export function defineErrorPayload<const Code extends `${string}/${string}`>(
95
96
  /** The HTTP status this code maps to. A 4xx or a 5xx — an error is not a success. */
96
97
  status: number;
97
98
  /** Public, safe-to-expose summary. Sent to clients and shown in the terminal. */
98
- message: string;
99
- /** Operator remediation hint. Becomes the CLI action line. Never sent to a client. */
100
- action?: string;
101
- /** Internal context for logs + audit. NEVER serialized to clients — the HTTP codec strips it. */
102
- detail?: string;
99
+ message: UnmarkedString;
100
+ /** Operator remediation hint. Becomes the CLI action line. Never sent to a client. Never a marked value (#132). */
101
+ action?: UnmarkedString;
102
+ /** Internal context for logs + audit. NEVER serialized to clients — the HTTP codec strips it. Never a marked value (#132). */
103
+ detail?: UnmarkedString;
103
104
  /**
104
105
  * Values a translating client interpolates into its own wording for this code. Client-facing:
105
106
  * these cross the boundary with `message`, unlike `action` and `detail`.