@pithy-sh/auth 0.11.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 (246) hide show
  1. package/README.md +30 -2
  2. package/dist/audit/actions.d.ts +39 -0
  3. package/dist/audit/actions.d.ts.map +1 -1
  4. package/dist/audit/actions.js +40 -1
  5. package/dist/audit/emit.d.ts +34 -0
  6. package/dist/audit/emit.d.ts.map +1 -1
  7. package/dist/audit/emit.js +47 -1
  8. package/dist/audit/evidence.d.ts +8 -2
  9. package/dist/audit/evidence.d.ts.map +1 -1
  10. package/dist/capability.d.ts +31 -11
  11. package/dist/capability.d.ts.map +1 -1
  12. package/dist/capability.js +38 -5
  13. package/dist/client/api.d.ts +55 -12
  14. package/dist/client/api.d.ts.map +1 -1
  15. package/dist/client/api.js +57 -18
  16. package/dist/client/bearer.d.ts +110 -0
  17. package/dist/client/bearer.d.ts.map +1 -0
  18. package/dist/client/bearer.js +265 -0
  19. package/dist/client/handoff.d.ts +77 -0
  20. package/dist/client/handoff.d.ts.map +1 -0
  21. package/dist/client/handoff.js +119 -0
  22. package/dist/client/mcp.d.ts +70 -0
  23. package/dist/client/mcp.d.ts.map +1 -0
  24. package/dist/client/mcp.js +65 -0
  25. package/dist/data/betterAuth.d.ts +3 -2
  26. package/dist/data/betterAuth.d.ts.map +1 -1
  27. package/dist/data/betterAuth.js +5 -3
  28. package/dist/data/kitFields.d.ts +5 -0
  29. package/dist/data/kitFields.d.ts.map +1 -1
  30. package/dist/data/kitFields.js +5 -0
  31. package/dist/data/tables.d.ts +25 -4
  32. package/dist/data/tables.d.ts.map +1 -1
  33. package/dist/data/tables.js +5 -3
  34. package/dist/data/userLifecycle.d.ts +9 -0
  35. package/dist/data/userLifecycle.d.ts.map +1 -1
  36. package/dist/data/userLifecycle.js +6 -2
  37. package/dist/data/verificationOutcome.d.ts +53 -0
  38. package/dist/data/verificationOutcome.d.ts.map +1 -0
  39. package/dist/data/verificationOutcome.js +50 -0
  40. package/dist/email/send.js +6 -2
  41. package/dist/http/adminRoutes.d.ts.map +1 -1
  42. package/dist/http/adminRoutes.js +56 -10
  43. package/dist/http/csrf.d.ts.map +1 -1
  44. package/dist/http/csrf.js +2 -1
  45. package/dist/http/guards.d.ts +15 -11
  46. package/dist/http/guards.d.ts.map +1 -1
  47. package/dist/http/guards.js +46 -11
  48. package/dist/http/handoff.d.ts +76 -0
  49. package/dist/http/handoff.d.ts.map +1 -0
  50. package/dist/http/handoff.js +316 -0
  51. package/dist/http/middleware.d.ts +12 -0
  52. package/dist/http/middleware.d.ts.map +1 -1
  53. package/dist/http/middleware.js +25 -4
  54. package/dist/http/resolve.d.ts.map +1 -1
  55. package/dist/http/resolve.js +9 -3
  56. package/dist/http/responses.d.ts +142 -0
  57. package/dist/http/responses.d.ts.map +1 -1
  58. package/dist/http/responses.js +66 -10
  59. package/dist/http/routes.d.ts +2 -0
  60. package/dist/http/routes.d.ts.map +1 -1
  61. package/dist/http/routes.js +35 -4
  62. package/dist/http/schemas.d.ts +57 -0
  63. package/dist/http/schemas.d.ts.map +1 -1
  64. package/dist/http/schemas.js +44 -1
  65. package/dist/http/views.d.ts +22 -2
  66. package/dist/http/views.d.ts.map +1 -1
  67. package/dist/http/views.js +40 -4
  68. package/dist/index.d.ts +2 -0
  69. package/dist/index.d.ts.map +1 -1
  70. package/dist/index.js +4 -2
  71. package/dist/instance/auth.d.ts +148 -10
  72. package/dist/instance/auth.d.ts.map +1 -1
  73. package/dist/instance/auth.js +86 -41
  74. package/dist/instance/plugins.d.ts +6 -0
  75. package/dist/instance/plugins.d.ts.map +1 -1
  76. package/dist/instance/plugins.js +14 -1
  77. package/dist/ledger/read.d.ts +53 -0
  78. package/dist/ledger/read.d.ts.map +1 -0
  79. package/dist/ledger/read.js +85 -0
  80. package/dist/ledger/record.d.ts +35 -0
  81. package/dist/ledger/record.d.ts.map +1 -0
  82. package/dist/ledger/record.js +98 -0
  83. package/dist/lifecycle/erasure.d.ts +9 -0
  84. package/dist/lifecycle/erasure.d.ts.map +1 -0
  85. package/dist/lifecycle/erasure.js +96 -0
  86. package/dist/lifecycle/inactivity.d.ts +19 -0
  87. package/dist/lifecycle/inactivity.d.ts.map +1 -0
  88. package/dist/lifecycle/inactivity.js +28 -0
  89. package/dist/lifecycle/transitions.d.ts +22 -1
  90. package/dist/lifecycle/transitions.d.ts.map +1 -1
  91. package/dist/lifecycle/transitions.js +51 -4
  92. package/dist/mcp/argumentClass.d.ts +51 -0
  93. package/dist/mcp/argumentClass.d.ts.map +1 -0
  94. package/dist/mcp/argumentClass.js +69 -0
  95. package/dist/mcp/capability.d.ts +50 -0
  96. package/dist/mcp/capability.d.ts.map +1 -0
  97. package/dist/mcp/capability.js +140 -0
  98. package/dist/mcp/clientMetadata.d.ts +40 -0
  99. package/dist/mcp/clientMetadata.d.ts.map +1 -0
  100. package/dist/mcp/clientMetadata.js +68 -0
  101. package/dist/mcp/consent.d.ts +49 -0
  102. package/dist/mcp/consent.d.ts.map +1 -0
  103. package/dist/mcp/consent.js +69 -0
  104. package/dist/mcp/dispatch.d.ts +35 -0
  105. package/dist/mcp/dispatch.d.ts.map +1 -0
  106. package/dist/mcp/dispatch.js +135 -0
  107. package/dist/mcp/floor.d.ts +37 -0
  108. package/dist/mcp/floor.d.ts.map +1 -0
  109. package/dist/mcp/floor.js +41 -0
  110. package/dist/mcp/host.d.ts +34 -0
  111. package/dist/mcp/host.d.ts.map +1 -0
  112. package/dist/mcp/host.js +2 -0
  113. package/dist/mcp/http/redirectList.d.ts +9 -0
  114. package/dist/mcp/http/redirectList.d.ts.map +1 -0
  115. package/dist/mcp/http/redirectList.js +24 -0
  116. package/dist/mcp/http/responses.d.ts +143 -0
  117. package/dist/mcp/http/responses.d.ts.map +1 -0
  118. package/dist/mcp/http/responses.js +83 -0
  119. package/dist/mcp/http/routes.d.ts +28 -0
  120. package/dist/mcp/http/routes.d.ts.map +1 -0
  121. package/dist/mcp/http/routes.js +517 -0
  122. package/dist/mcp/http/schemas.d.ts +24 -0
  123. package/dist/mcp/http/schemas.d.ts.map +1 -0
  124. package/dist/mcp/http/schemas.js +18 -0
  125. package/dist/mcp/marker.d.ts +15 -0
  126. package/dist/mcp/marker.d.ts.map +1 -0
  127. package/dist/mcp/marker.js +15 -0
  128. package/dist/mcp/provider.d.ts +78 -0
  129. package/dist/mcp/provider.d.ts.map +1 -0
  130. package/dist/mcp/provider.js +108 -0
  131. package/dist/mcp/purge.d.ts +15 -0
  132. package/dist/mcp/purge.d.ts.map +1 -0
  133. package/dist/mcp/purge.js +31 -0
  134. package/dist/mcp/rpc.d.ts +79 -0
  135. package/dist/mcp/rpc.d.ts.map +1 -0
  136. package/dist/mcp/rpc.js +103 -0
  137. package/dist/mcp/toolAudit.d.ts +76 -0
  138. package/dist/mcp/toolAudit.d.ts.map +1 -0
  139. package/dist/mcp/toolAudit.js +86 -0
  140. package/dist/migrations/0006_verification_outcomes.d.ts +15 -0
  141. package/dist/migrations/0006_verification_outcomes.d.ts.map +1 -0
  142. package/dist/migrations/0006_verification_outcomes.js +35 -0
  143. package/dist/migrations/0007_erasure_record.d.ts +17 -0
  144. package/dist/migrations/0007_erasure_record.d.ts.map +1 -0
  145. package/dist/migrations/0007_erasure_record.js +36 -0
  146. package/dist/migrations/0008_last_active.d.ts +15 -0
  147. package/dist/migrations/0008_last_active.d.ts.map +1 -0
  148. package/dist/migrations/0008_last_active.js +29 -0
  149. package/dist/migrations/set.d.ts +4 -1
  150. package/dist/migrations/set.d.ts.map +1 -1
  151. package/dist/migrations/set.js +8 -2
  152. package/dist/peer.d.ts +3 -2
  153. package/dist/peer.d.ts.map +1 -1
  154. package/dist/processing/activities.d.ts +6 -0
  155. package/dist/processing/activities.d.ts.map +1 -0
  156. package/dist/processing/activities.js +12 -0
  157. package/dist/purge/contribution.d.ts +20 -5
  158. package/dist/purge/contribution.d.ts.map +1 -1
  159. package/dist/purge/contribution.js +20 -6
  160. package/dist/purge/run.d.ts +75 -5
  161. package/dist/purge/run.d.ts.map +1 -1
  162. package/dist/purge/run.js +117 -14
  163. package/dist/purge/workflow.d.ts +15 -2
  164. package/dist/purge/workflow.d.ts.map +1 -1
  165. package/dist/purge/workflow.js +51 -7
  166. package/dist/test-utils/accountFootprint.d.ts +5 -2
  167. package/dist/test-utils/accountFootprint.d.ts.map +1 -1
  168. package/dist/test-utils/accountFootprint.js +7 -2
  169. package/dist/test-utils/liveApp.d.ts +6 -0
  170. package/dist/test-utils/liveApp.d.ts.map +1 -1
  171. package/dist/test-utils/liveApp.js +7 -2
  172. package/dist/token/handoff.d.ts +80 -0
  173. package/dist/token/handoff.d.ts.map +1 -0
  174. package/dist/token/handoff.js +136 -0
  175. package/dist/version.generated.d.ts +1 -1
  176. package/dist/version.generated.js +1 -1
  177. package/docs/account-lifecycle.md +59 -7
  178. package/docs/apple-signin.md +32 -4
  179. package/docs/facebook-oauth.md +2 -2
  180. package/docs/github-oauth.md +2 -2
  181. package/docs/google-oauth.md +9 -7
  182. package/docs/microsoft-oauth.md +2 -2
  183. package/package.json +11 -5
  184. package/pithy.manifest.json +2 -2
  185. package/pithy.mcp.manifest.json +36 -0
  186. package/src/audit/actions.ts +39 -0
  187. package/src/audit/emit.ts +63 -0
  188. package/src/audit/evidence.ts +8 -4
  189. package/src/capability.ts +80 -23
  190. package/src/client/api.ts +69 -19
  191. package/src/client/bearer.ts +388 -0
  192. package/src/client/handoff.ts +172 -0
  193. package/src/client/mcp.ts +140 -0
  194. package/src/data/betterAuth.ts +8 -4
  195. package/src/data/kitFields.ts +2 -0
  196. package/src/data/tables.ts +4 -2
  197. package/src/data/userLifecycle.ts +15 -3
  198. package/src/data/verificationOutcome.ts +86 -0
  199. package/src/email/send.ts +2 -2
  200. package/src/http/adminRoutes.ts +68 -3
  201. package/src/http/csrf.ts +4 -1
  202. package/src/http/guards.ts +48 -11
  203. package/src/http/handoff.ts +350 -0
  204. package/src/http/middleware.ts +29 -3
  205. package/src/http/resolve.ts +25 -25
  206. package/src/http/responses.ts +134 -8
  207. package/src/http/routes.ts +63 -4
  208. package/src/http/schemas.ts +85 -0
  209. package/src/http/views.ts +46 -2
  210. package/src/index.ts +2 -0
  211. package/src/instance/auth.ts +51 -1
  212. package/src/instance/plugins.ts +20 -2
  213. package/src/ledger/read.ts +133 -0
  214. package/src/ledger/record.ts +198 -0
  215. package/src/lifecycle/erasure.ts +118 -0
  216. package/src/lifecycle/inactivity.ts +56 -0
  217. package/src/lifecycle/transitions.ts +75 -5
  218. package/src/mcp/argumentClass.ts +112 -0
  219. package/src/mcp/capability.ts +194 -0
  220. package/src/mcp/clientMetadata.ts +81 -0
  221. package/src/mcp/consent.ts +95 -0
  222. package/src/mcp/dispatch.ts +154 -0
  223. package/src/mcp/floor.ts +62 -0
  224. package/src/mcp/host.ts +36 -0
  225. package/src/mcp/http/redirectList.ts +26 -0
  226. package/src/mcp/http/responses.ts +157 -0
  227. package/src/mcp/http/routes.ts +635 -0
  228. package/src/mcp/http/schemas.ts +37 -0
  229. package/src/mcp/marker.ts +18 -0
  230. package/src/mcp/provider.ts +151 -0
  231. package/src/mcp/purge.ts +39 -0
  232. package/src/mcp/rpc.ts +135 -0
  233. package/src/mcp/toolAudit.ts +132 -0
  234. package/src/migrations/0006_verification_outcomes.ts +51 -0
  235. package/src/migrations/0007_erasure_record.ts +43 -0
  236. package/src/migrations/0008_last_active.ts +30 -0
  237. package/src/migrations/set.ts +7 -1
  238. package/src/processing/activities.ts +14 -0
  239. package/src/purge/contribution.ts +37 -10
  240. package/src/purge/run.ts +179 -16
  241. package/src/purge/workflow.ts +65 -7
  242. package/src/seeds/example.ts +2 -2
  243. package/src/test-utils/accountFootprint.ts +10 -1
  244. package/src/test-utils/liveApp.ts +10 -1
  245. package/src/token/handoff.ts +180 -0
  246. package/src/version.generated.ts +1 -1
@@ -0,0 +1,35 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { AuthDatabase } from "../data/tables";
4
+ import type { VerificationType } from "../data/verificationOutcome";
5
+ /** The verification ledger's four writers. */
6
+ export interface VerificationLedger {
7
+ /** `verification.create.after`: remember the row, and move a wrong code's ledger row onto its re-issue. */
8
+ created(row: unknown, requestContext: unknown): Promise<void>;
9
+ /** `verification.delete.before`: remember the live row about to be consumed. */
10
+ consuming(row: unknown, requestContext: unknown): void;
11
+ /** The send callback, once the email seam has answered: record the row created in this request. */
12
+ issued(requestContext: unknown, input: IssuedInput): Promise<void>;
13
+ /** `session.create.after`: stamp the row consumed in this request as used, by this user. */
14
+ signedIn(requestContext: unknown, userId: unknown): Promise<void>;
15
+ }
16
+ /** What the send callback knows. The address is read to find the account and is never stored. */
17
+ export interface IssuedInput {
18
+ /** What was issued. */
19
+ type: VerificationType;
20
+ /** Who it was sent to — looked up, never written. */
21
+ email: string;
22
+ /** The `pithy_email_jobs` row that carries it, or null when the seam queued nothing. */
23
+ emailJobId: string | null;
24
+ }
25
+ /** A date off a Better Auth row: a `Date` from the adapter, an ISO string or a number from anywhere else. */
26
+ export declare function dateOf(value: unknown): Date | null;
27
+ /** The id and dates off a verification row, or null for anything not shaped like one. */
28
+ export declare function verificationRowOf(row: unknown): {
29
+ id: string;
30
+ createdAt: Date | null;
31
+ expiresAt: Date;
32
+ } | null;
33
+ /** Build the ledger's writers over one database. `now` is injectable for the tests that pin a clock. */
34
+ export declare function verificationLedger(db: AuthDatabase, now?: () => Date): VerificationLedger;
35
+ //# sourceMappingURL=record.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"record.d.ts","sourceRoot":"","sources":["../../src/ledger/record.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAoDpE,8CAA8C;AAC9C,MAAM,WAAW,kBAAkB;IACjC,2GAA2G;IAC3G,OAAO,CAAC,GAAG,EAAE,OAAO,EAAE,cAAc,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9D,gFAAgF;IAChF,SAAS,CAAC,GAAG,EAAE,OAAO,EAAE,cAAc,EAAE,OAAO,GAAG,IAAI,CAAC;IACvD,mGAAmG;IACnG,MAAM,CAAC,cAAc,EAAE,OAAO,EAAE,KAAK,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACnE,4FAA4F;IAC5F,QAAQ,CAAC,cAAc,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACnE;AAED,iGAAiG;AACjG,MAAM,WAAW,WAAW;IAC1B,uBAAuB;IACvB,IAAI,EAAE,gBAAgB,CAAC;IACvB,qDAAqD;IACrD,KAAK,EAAE,MAAM,CAAC;IACd,wFAAwF;IACxF,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3B;AAED,6GAA6G;AAC7G,wBAAgB,MAAM,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI,GAAG,IAAI,CAIlD;AAED,yFAAyF;AACzF,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,OAAO,GAAG;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,IAAI,GAAG,IAAI,CAAC;IAAC,SAAS,EAAE,IAAI,CAAA;CAAE,GAAG,IAAI,CAO9G;AAED,wGAAwG;AACxG,wBAAgB,kBAAkB,CAAC,EAAE,EAAE,YAAY,EAAE,GAAG,GAAE,MAAM,IAAuB,GAAG,kBAAkB,CA2F3G"}
@@ -0,0 +1,98 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
4
+ //#region src/ledger/record.ts
5
+ /** A date off a Better Auth row: a `Date` from the adapter, an ISO string or a number from anywhere else. */
6
+ function dateOf(value) {
7
+ const date = value instanceof Date ? value : typeof value === "string" || typeof value === "number" ? new Date(value) : null;
8
+ return date && Number.isFinite(date.getTime()) ? date : null;
9
+ }
10
+ /** The id and dates off a verification row, or null for anything not shaped like one. */
11
+ function verificationRowOf(row) {
12
+ if (typeof row !== "object" || row === null) return null;
13
+ const { id, createdAt, expiresAt } = row;
14
+ if (typeof id !== "string" || id === "") return null;
15
+ const expires = dateOf(expiresAt);
16
+ if (!expires) return null;
17
+ return {
18
+ id,
19
+ createdAt: dateOf(createdAt),
20
+ expiresAt: expires
21
+ };
22
+ }
23
+ /** Build the ledger's writers over one database. `now` is injectable for the tests that pin a clock. */
24
+ function verificationLedger(db, now = () => /* @__PURE__ */ new Date()) {
25
+ const pending = /* @__PURE__ */ new WeakMap();
26
+ const stateOf = (requestContext) => {
27
+ if (typeof requestContext !== "object" || requestContext === null) return null;
28
+ let state = pending.get(requestContext);
29
+ if (!state) {
30
+ state = {};
31
+ pending.set(requestContext, state);
32
+ }
33
+ return state;
34
+ };
35
+ return {
36
+ async created(row, requestContext) {
37
+ const state = stateOf(requestContext);
38
+ const verification = verificationRowOf(row);
39
+ if (!state || !verification) return;
40
+ const consumed = state.consuming;
41
+ if (consumed && consumed.expiresAt.getTime() === verification.expiresAt.getTime()) {
42
+ state.consuming = void 0;
43
+ await swallow(() => db.updateTable("pithyAuthVerificationOutcomes").set({ verificationId: verification.id }).where("verificationId", "=", consumed.id).execute());
44
+ }
45
+ state.created = {
46
+ id: verification.id,
47
+ issuedAt: verification.createdAt ?? now(),
48
+ expiresAt: verification.expiresAt
49
+ };
50
+ },
51
+ consuming(row, requestContext) {
52
+ const state = stateOf(requestContext);
53
+ const verification = verificationRowOf(row);
54
+ if (!state || !verification) return;
55
+ if (verification.expiresAt.getTime() <= now().getTime()) return;
56
+ state.consuming = {
57
+ id: verification.id,
58
+ expiresAt: verification.expiresAt
59
+ };
60
+ },
61
+ async issued(requestContext, input) {
62
+ const state = stateOf(requestContext);
63
+ const created = state?.created;
64
+ if (!state || !created) return;
65
+ state.created = void 0;
66
+ await swallow(async () => {
67
+ const user = await db.selectFrom("pithyAuthUsers").select("id").where("email", "=", input.email.toLowerCase()).executeTakeFirst();
68
+ await db.insertInto("pithyAuthVerificationOutcomes").values({
69
+ verificationId: created.id,
70
+ type: input.type,
71
+ userId: user?.id ?? null,
72
+ emailJobId: input.emailJobId,
73
+ issuedAt: SQLiteDate.encode(created.issuedAt),
74
+ expiresAt: SQLiteDate.encode(created.expiresAt),
75
+ usedAt: null
76
+ }).execute();
77
+ });
78
+ },
79
+ async signedIn(requestContext, userId) {
80
+ const state = stateOf(requestContext);
81
+ const consumed = state?.consuming;
82
+ if (!state || !consumed || typeof userId !== "string" || userId === "") return;
83
+ state.consuming = void 0;
84
+ await swallow(() => db.updateTable("pithyAuthVerificationOutcomes").set((eb) => ({
85
+ usedAt: SQLiteDate.encode(now()),
86
+ userId: eb.fn.coalesce("userId", eb.val(userId))
87
+ })).where("verificationId", "=", consumed.id).where("usedAt", "is", null).execute());
88
+ }
89
+ };
90
+ }
91
+ /** Run a ledger write and drop its failure: the ledger reports on sign-in and is never the reason one fails. */
92
+ async function swallow(write) {
93
+ try {
94
+ await write();
95
+ } catch {}
96
+ }
97
+ //#endregion
98
+ export { dateOf, verificationLedger, verificationRowOf };
@@ -0,0 +1,9 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { ErasureHistoryReader, ErasureRecords } from "@pithy-sh/core/src/capability/erasure";
4
+ import { type AuthDatabase } from "../data/tables";
5
+ /** The reader, over one auth database. */
6
+ export declare function userErasureReader(db: AuthDatabase): ErasureHistoryReader;
7
+ /** What auth declares: the `user` subject, the actions its purge records, and the reader over its database. */
8
+ export declare function authErasureRecords(database: string): ErasureRecords;
9
+ //# sourceMappingURL=erasure.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"erasure.d.ts","sourceRoot":"","sources":["../../src/lifecycle/erasure.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,oBAAoB,EAAqB,cAAc,EAAE,MAAM,uCAAuC,CAAC;AAGrH,OAAO,EAAE,KAAK,YAAY,EAAgB,MAAM,gBAAgB,CAAC;AAqBjE,0CAA0C;AAC1C,wBAAgB,iBAAiB,CAAC,EAAE,EAAE,YAAY,GAAG,oBAAoB,CAsExE;AAED,+GAA+G;AAC/G,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,GAAG,cAAc,CAgBnE"}
@@ -0,0 +1,96 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { AuthAuditActions } from "../audit/actions.js";
4
+ import { UserLifecycleEvent } from "../data/userLifecycle.js";
5
+ import { authDatabase } from "../data/tables.js";
6
+ import { resolveDb } from "../http/resolve.js";
7
+ import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
8
+ //#region src/lifecycle/erasure.ts
9
+ /**
10
+ * **A user's erasure record, read back for the control plane's attestation (#823).**
11
+ *
12
+ * `pithy_auth_user_lifecycle` is the one `pithy_auth_*` table a purge leaves behind, and it names the account by id
13
+ * and nothing else. This reads the rows an erasure is made of — the deletion, any restore, each step, a failure, the
14
+ * end — and hands them to core through the {@link ErasureRecords} seam, so the control plane never imports auth.
15
+ */
16
+ /** The rows an erasure is made of. A suspension is not one. */
17
+ const ERASURE_ACTIONS = [
18
+ "deleted",
19
+ "restored",
20
+ "purge_step",
21
+ "purge_retained",
22
+ "purge_failed",
23
+ "purged"
24
+ ];
25
+ /** The rows that are the purge itself, rather than the deletion it runs under. */
26
+ const PURGE_ACTIONS = [
27
+ "purge_step",
28
+ "purge_retained",
29
+ "purge_failed",
30
+ "purged"
31
+ ];
32
+ /** The rows that end a deletion: its purge finishing, or the subject coming back. */
33
+ const CLOSING_ACTIONS = ["purged", "restored"];
34
+ /** The reader, over one auth database. */
35
+ function userErasureReader(db) {
36
+ return {
37
+ history: async (userIds) => {
38
+ if (userIds.length === 0) return [];
39
+ return (await db.selectFrom("pithyAuthUserLifecycle").selectAll().where("userId", "in", [...userIds]).where("action", "in", [...ERASURE_ACTIONS]).orderBy("id", "asc").execute()).map((raw) => {
40
+ const row = UserLifecycleEvent.parse(raw);
41
+ return {
42
+ subjectId: row.userId,
43
+ action: row.action,
44
+ actorType: row.actorType,
45
+ reason: row.reason,
46
+ step: row.step,
47
+ mode: row.mode,
48
+ purgeAfter: row.purgeAfter,
49
+ at: row.createdAt
50
+ };
51
+ });
52
+ },
53
+ subjectsIn: async (since, until) => {
54
+ const from = SQLiteDate.encode(since);
55
+ const to = SQLiteDate.encode(until);
56
+ return (await db.selectFrom("pithyAuthUserLifecycle as row").select("row.userId").distinct().where((eb) => eb.or([
57
+ eb.and([
58
+ eb("row.action", "in", [...PURGE_ACTIONS]),
59
+ eb("row.createdAt", ">=", from),
60
+ eb("row.createdAt", "<=", to)
61
+ ]),
62
+ eb.and([
63
+ eb("row.action", "=", "deleted"),
64
+ eb("row.purgeAfter", ">=", from),
65
+ eb("row.purgeAfter", "<=", to)
66
+ ]),
67
+ eb.and([
68
+ eb("row.action", "=", "deleted"),
69
+ eb("row.createdAt", "<=", to),
70
+ eb.or([eb("row.purgeAfter", "<=", to), eb("row.purgeAfter", "is", null)]),
71
+ eb.not(eb.exists(eb.selectFrom("pithyAuthUserLifecycle as closed").select("closed.id").whereRef("closed.userId", "=", "row.userId").whereRef("closed.id", ">", "row.id").where("closed.action", "in", [...CLOSING_ACTIONS]).where("closed.createdAt", "<", from)))
72
+ ])
73
+ ])).orderBy("row.userId").execute()).map((row) => row.userId);
74
+ }
75
+ };
76
+ }
77
+ /** What auth declares: the `user` subject, the actions its purge records, and the reader over its database. */
78
+ function authErasureRecords(database) {
79
+ return {
80
+ subject: "user",
81
+ resourceType: "user",
82
+ auditActions: {
83
+ deleted: [
84
+ AuthAuditActions.adminUserSoftDeleted,
85
+ AuthAuditActions.adminUserHardDeleted,
86
+ AuthAuditActions.userSelfDeleted
87
+ ],
88
+ step: AuthAuditActions.adminUserPurgeStep,
89
+ failed: AuthAuditActions.adminUserPurgeFailed,
90
+ purged: AuthAuditActions.adminUserPurged
91
+ },
92
+ read: (env) => userErasureReader(authDatabase(resolveDb(env, database)))
93
+ };
94
+ }
95
+ //#endregion
96
+ export { authErasureRecords, userErasureReader };
@@ -0,0 +1,19 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { AuthDatabase } from "../data/tables";
4
+ /**
5
+ * **Inactivity, as the retention policy's class ages count it.**
6
+ *
7
+ * An account is active when it opens a session: a sign-in, or a token refresh. Each one stamps `lastActiveAt` on the
8
+ * account, and a live session refreshed since counts too. An account untouched for longer than the strictest class
9
+ * age it holds is soft-deleted through the lifecycle — `../purge/run.ts` runs the pass — with the same notice mail,
10
+ * the same window and the same purge as any other deletion.
11
+ */
12
+ /** Stamp an account active now. Moves the clock forward only, so a late write never makes it look older. */
13
+ export declare function recordActivity(db: AuthDatabase, userId: string, at: Date): Promise<void>;
14
+ /**
15
+ * The accounts inactive since `cutoff`, oldest first, at most `limit`: not deleted, last active before it (or, never
16
+ * stamped, created before it), and holding no session refreshed since.
17
+ */
18
+ export declare function inactiveAccounts(db: AuthDatabase, cutoff: Date, limit: number): Promise<string[]>;
19
+ //# sourceMappingURL=inactivity.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inactivity.d.ts","sourceRoot":"","sources":["../../src/lifecycle/inactivity.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAEnD;;;;;;;GAOG;AAEH,4GAA4G;AAC5G,wBAAsB,cAAc,CAAC,EAAE,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAQ9F;AAED;;;GAGG;AACH,wBAAsB,gBAAgB,CAAC,EAAE,EAAE,YAAY,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAyBvG"}
@@ -0,0 +1,28 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
4
+ //#region src/lifecycle/inactivity.ts
5
+ /**
6
+ * **Inactivity, as the retention policy's class ages count it.**
7
+ *
8
+ * An account is active when it opens a session: a sign-in, or a token refresh. Each one stamps `lastActiveAt` on the
9
+ * account, and a live session refreshed since counts too. An account untouched for longer than the strictest class
10
+ * age it holds is soft-deleted through the lifecycle — `../purge/run.ts` runs the pass — with the same notice mail,
11
+ * the same window and the same purge as any other deletion.
12
+ */
13
+ /** Stamp an account active now. Moves the clock forward only, so a late write never makes it look older. */
14
+ async function recordActivity(db, userId, at) {
15
+ const ms = SQLiteDate.encode(at);
16
+ await db.updateTable("pithyAuthUsers").set({ lastActiveAt: ms }).where("id", "=", userId).where((eb) => eb.or([eb("lastActiveAt", "is", null), eb("lastActiveAt", "<", ms)])).execute();
17
+ }
18
+ /**
19
+ * The accounts inactive since `cutoff`, oldest first, at most `limit`: not deleted, last active before it (or, never
20
+ * stamped, created before it), and holding no session refreshed since.
21
+ */
22
+ async function inactiveAccounts(db, cutoff, limit) {
23
+ const ms = SQLiteDate.encode(cutoff);
24
+ const iso = cutoff.toISOString();
25
+ return (await db.selectFrom("pithyAuthUsers").select("id").where("deletedAt", "is", null).where((eb) => eb.or([eb("lastActiveAt", "<", ms), eb.and([eb("lastActiveAt", "is", null), eb("createdAt", "<", iso)])])).where(({ not, exists, selectFrom }) => not(exists(selectFrom("pithyAuthSessions").select("pithyAuthSessions.id").whereRef("pithyAuthSessions.userId", "=", "pithyAuthUsers.id").where("pithyAuthSessions.updatedAt", ">=", iso)))).orderBy("lastActiveAt", "asc").orderBy("id", "asc").limit(limit).execute()).map((row) => row.id);
26
+ }
27
+ //#endregion
28
+ export { inactiveAccounts, recordActivity };
@@ -138,6 +138,11 @@ export declare function reinstateUser(deps: LifecycleDeps, input: {
138
138
  }): Promise<LifecycleTransition>;
139
139
  /** How a deletion runs: shut now and purged once the window closes, or purged now. */
140
140
  export type DeletionMode = "soft" | "hard";
141
+ /**
142
+ * How many days a soft deletion stays restorable: the Worker's `retention.purgeWindows.user` when its block
143
+ * names one, else `retention.purgeAfterDays` from this capability's own config.
144
+ */
145
+ export declare function userPurgeWindowDays(config: Pick<LifecycleDeps["config"], "retention">): number;
141
146
  /** What a deletion did, and the deletion it left in force. */
142
147
  export interface DeleteTransition extends LifecycleTransition {
143
148
  /**
@@ -227,6 +232,11 @@ export declare function purgeSubject(deps: LifecycleDeps, userId: string): Promi
227
232
  } | {
228
233
  state: "gone";
229
234
  }>;
235
+ /**
236
+ * The account's address, as a purge step reads it (#814) — `null` when there is no account, or no address. Read
237
+ * inside the step that asks, so it is never carried in a Workflow's journal.
238
+ */
239
+ export declare function purgeAddress(db: AuthDatabase, userId: string): Promise<string | null>;
230
240
  /** One account whose purge is due: which, and the deletion it is due under — ms-epoch, so a Workflow journal holds it. */
231
241
  export interface DuePurge {
232
242
  readonly userId: string;
@@ -240,12 +250,23 @@ export interface DuePurge {
240
250
  export declare function duePurges(deps: LifecycleDeps, limit: number): Promise<DuePurge[]>;
241
251
  /**
242
252
  * Record that one purge step — one capability's contribution — erased its rows. The contribution's summary is
243
- * the row's reason, so the history says what the step erased and not only that it ran.
253
+ * the row's reason, so the history says what the step erased and not only that it ran. With `retained`, the step
254
+ * kept its rows instead (#814): the row is `purge_retained`, and its reason is the basis the capability gave.
244
255
  */
245
256
  export declare function recordPurgeStep(deps: LifecycleDeps, input: {
246
257
  userId: string;
247
258
  step: string;
248
259
  summary?: string | null;
260
+ retained?: boolean;
261
+ }): Promise<void>;
262
+ /**
263
+ * Record that a purge gave up (#823): the step it stopped at, in the history and in the trail. The daily pass starts
264
+ * the purge again tomorrow, so this is where it stands until then, not an end. The failure's message is never
265
+ * written: it is code the kit did not write, and it may name the person.
266
+ */
267
+ export declare function recordPurgeFailure(deps: LifecycleDeps, input: {
268
+ userId: string;
269
+ step: string;
249
270
  }): Promise<void>;
250
271
  /**
251
272
  * The deletion-complete mail, sent **before the address is erased** (#622). The purge calls this after every
@@ -1 +1 @@
1
- {"version":3,"file":"transitions.d.ts","sourceRoot":"","sources":["../../src/lifecycle/transitions.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAuB,MAAM,2BAA2B,CAAC;AAEjF,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mCAAmC,CAAC;AAInE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,kCAAkC,CAAC;AAC/D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,kCAAkC,CAAC;AAGrE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,KAAK,EAAuB,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AACzF,OAAO,KAAK,EAA0B,kBAAkB,EAAyB,MAAM,SAAS,CAAC;AAIjG;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,6BAA6B;AAC7B,MAAM,WAAW,cAAc;IAC7B,6BAA6B;IAC7B,QAAQ,CAAC,IAAI,EAAE,sBAAsB,CAAC;IACtC,oGAAoG;IACpG,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5B;AAED,kFAAkF;AAClF,MAAM,WAAW,aAAa;IAC5B,uBAAuB;IACvB,QAAQ,CAAC,EAAE,EAAE,YAAY,CAAC;IAC1B,mFAAmF;IACnF,QAAQ,CAAC,EAAE,EAAE,UAAU,CAAC;IACxB,mEAAmE;IACnE,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC;IACzB,uEAAuE;IACvE,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,UAAU,EAAE,WAAW,GAAG,iBAAiB,CAAC,CAAC;IACnE,2BAA2B;IAC3B,QAAQ,CAAC,KAAK,EAA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;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAWpH;AAED;;;;;GAKG;AACH,wBAAsB,iBAAiB,CACrC,IAAI,EAAE,aAAa,EACnB,KAAK,EAAE;IAAE,SAAS,EAAE,cAAc,CAAC;IAAC,MAAM,CAAC,EAAE,OAAO,CAAA;CAAE,GACrD,OAAO,CAAC,mBAAmB,CAAC,CAY9B;AAED;;;;;;;;GAQG;AACH,wBAAsB,aAAa,CAAC,IAAI,EAAE,aAAa,EAAE,KAAK,EAAE;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAYhH"}
@@ -7,6 +7,8 @@ import { ConflictError, NotFoundError, ValidationError } from "@pithy-sh/core/sr
7
7
  import { SQLiteBoolean, SQLiteDate } from "@pithy-sh/core/src/data/codecs";
8
8
  import { formattingLocaleOf } from "@pithy-sh/core/src/i18n/locale";
9
9
  import { sql } from "kysely";
10
+ import { composedRetention } from "@pithy-sh/core/src/retention/composed";
11
+ import { purgeWindowDays } from "@pithy-sh/core/src/retention/policy";
10
12
  //#region src/lifecycle/transitions.ts
11
13
  /** A reason, trimmed and bounded, or null when none was given. */
12
14
  function reasonOf(reason) {
@@ -60,6 +62,8 @@ function encoded(row) {
60
62
  suspendedUntil: row.suspendedUntil ? SQLiteDate.encode(row.suspendedUntil) : null,
61
63
  step: row.step ?? null,
62
64
  notify: row.notify === void 0 || row.notify === null ? null : SQLiteBoolean.encode(row.notify),
65
+ mode: row.mode ?? null,
66
+ purgeAfter: row.purgeAfter ? SQLiteDate.encode(row.purgeAfter) : null,
63
67
  createdAt: SQLiteDate.encode(row.at)
64
68
  };
65
69
  }
@@ -89,6 +93,8 @@ async function move(deps, update, row) {
89
93
  "suspendedUntil",
90
94
  "step",
91
95
  "notify",
96
+ "mode",
97
+ "purgeAfter",
92
98
  "createdAt"
93
99
  ]).expression(deps.db.selectNoFrom([
94
100
  sql.val(v.userId).as("userId"),
@@ -99,6 +105,8 @@ async function move(deps, update, row) {
99
105
  sql.val(v.suspendedUntil).as("suspendedUntil"),
100
106
  sql.val(v.step).as("step"),
101
107
  sql.val(v.notify).as("notify"),
108
+ sql.val(v.mode).as("mode"),
109
+ sql.val(v.purgeAfter).as("purgeAfter"),
102
110
  sql.val(v.createdAt).as("createdAt")
103
111
  ]).where(sql`changes()`, ">", 0)).compile();
104
112
  const [updated] = await deps.d1.batch([prepared(deps.d1, update.compile()), prepared(deps.d1, insert)]);
@@ -320,6 +328,14 @@ async function reinstateUser(deps, input) {
320
328
  };
321
329
  }
322
330
  /**
331
+ * How many days a soft deletion stays restorable: the Worker's `retention.purgeWindows.user` when its block
332
+ * names one, else `retention.purgeAfterDays` from this capability's own config.
333
+ */
334
+ function userPurgeWindowDays(config) {
335
+ const retention = composedRetention();
336
+ return (retention && purgeWindowDays(retention, "user")) ?? config.retention.purgeAfterDays;
337
+ }
338
+ /**
323
339
  * Delete an account. Audited as the account's own deletion when its holder is the actor.
324
340
  *
325
341
  * **Soft, the default**: it is shut now, and its data is erased once `retention.purgeAfterDays` have passed.
@@ -338,7 +354,7 @@ async function deleteUser(deps, input) {
338
354
  const at = (deps.now ?? (() => /* @__PURE__ */ new Date()))();
339
355
  const reason = reasonOf(input.reason);
340
356
  const hard = input.mode === "hard";
341
- const purgeAfter = hard ? at : new Date(at.getTime() + deps.config.retention.purgeAfterDays * 864e5);
357
+ const purgeAfter = hard ? at : new Date(at.getTime() + userPurgeWindowDays(deps.config) * 864e5);
342
358
  const subject = await subjectOf(deps.db, input.userId);
343
359
  const row = {
344
360
  userId: input.userId,
@@ -346,6 +362,8 @@ async function deleteUser(deps, input) {
346
362
  actor: input.actor,
347
363
  reason,
348
364
  at,
365
+ mode: hard ? "hard" : "soft",
366
+ purgeAfter,
349
367
  ...hard && input.notify !== void 0 ? { notify: input.notify } : {}
350
368
  };
351
369
  const existing = subject.columns.deletedAt;
@@ -542,6 +560,13 @@ async function purgeSubject(deps, userId) {
542
560
  };
543
561
  }
544
562
  /**
563
+ * The account's address, as a purge step reads it (#814) — `null` when there is no account, or no address. Read
564
+ * inside the step that asks, so it is never carried in a Workflow's journal.
565
+ */
566
+ async function purgeAddress(db, userId) {
567
+ return (await db.selectFrom("pithyAuthUsers").select("email").where("id", "=", userId).executeTakeFirst())?.email ?? null;
568
+ }
569
+ /**
545
570
  * The accounts whose purge is due — deleted, with `purgeAfter` passed — oldest first, at most `limit` (#622).
546
571
  * What the daily cron starts a purge for. An account still inside its window is not here, and neither is one
547
572
  * that was restored. Each carries its deletion's start, which names the purge's instance (`../purge/start.ts`).
@@ -555,18 +580,40 @@ async function duePurges(deps, limit) {
555
580
  }
556
581
  /**
557
582
  * Record that one purge step — one capability's contribution — erased its rows. The contribution's summary is
558
- * the row's reason, so the history says what the step erased and not only that it ran.
583
+ * the row's reason, so the history says what the step erased and not only that it ran. With `retained`, the step
584
+ * kept its rows instead (#814): the row is `purge_retained`, and its reason is the basis the capability gave.
559
585
  */
560
586
  async function recordPurgeStep(deps, input) {
561
587
  const at = (deps.now ?? (() => /* @__PURE__ */ new Date()))();
562
588
  await record(deps, {
563
589
  userId: input.userId,
564
- action: "purge_step",
590
+ action: input.retained ? "purge_retained" : "purge_step",
565
591
  actor: PURGE,
566
592
  reason: input.summary?.trim() ? input.summary.trim().slice(0, 500) : null,
567
593
  at,
568
594
  step: input.step
569
595
  });
596
+ await audit(deps, AuthAuditActions.adminUserPurgeStep, input.userId, PURGE, {
597
+ step: input.step,
598
+ disposition: input.retained ? "retained" : "erased"
599
+ });
600
+ }
601
+ /**
602
+ * Record that a purge gave up (#823): the step it stopped at, in the history and in the trail. The daily pass starts
603
+ * the purge again tomorrow, so this is where it stands until then, not an end. The failure's message is never
604
+ * written: it is code the kit did not write, and it may name the person.
605
+ */
606
+ async function recordPurgeFailure(deps, input) {
607
+ const at = (deps.now ?? (() => /* @__PURE__ */ new Date()))();
608
+ await record(deps, {
609
+ userId: input.userId,
610
+ action: "purge_failed",
611
+ actor: PURGE,
612
+ reason: null,
613
+ at,
614
+ step: input.step
615
+ });
616
+ await audit(deps, AuthAuditActions.adminUserPurgeFailed, input.userId, PURGE, { step: input.step });
570
617
  }
571
618
  /**
572
619
  * The deletion-complete mail, sent **before the address is erased** (#622). The purge calls this after every
@@ -620,4 +667,4 @@ async function completePurge(deps, input) {
620
667
  };
621
668
  }
622
669
  //#endregion
623
- export { completePurge, deleteUser, duePurges, mailPurgeComplete, purgeSubject, recordPurgeStep, reinstateUser, requirePresent, restoreUser, suspendUser };
670
+ export { completePurge, deleteUser, duePurges, mailPurgeComplete, purgeAddress, purgeSubject, recordPurgeFailure, recordPurgeStep, reinstateUser, requirePresent, restoreUser, suspendUser, userPurgeWindowDays };
@@ -0,0 +1,51 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { ToolArguments } from "./dispatch";
4
+ /**
5
+ * What a tool call's arguments leave in its audit row (`docs/AGENT-ACCESS.md` §9).
6
+ *
7
+ * A tool's arguments may carry a customer's own data, and an audit trail that copied them would be a second place
8
+ * that data lives. So the row keeps the route's path parameters verbatim, because they are the resource ids the
9
+ * route already records, and of the query and the body only the top-level key names, sorted, with each value's
10
+ * JSON type. No value, no length, no nested key.
11
+ */
12
+ /** A value's JSON type, with an array told apart from an object. */
13
+ export type JsonType = "string" | "number" | "boolean" | "null" | "array" | "object";
14
+ /** One top-level key and the JSON type of its value. */
15
+ export interface KeyClass {
16
+ /** The key's name, cut to {@link MAX_RECORDED_TEXT}. */
17
+ readonly key: string;
18
+ readonly type: JsonType;
19
+ /** Set when the name was longer than {@link MAX_RECORDED_TEXT} and was cut. */
20
+ readonly truncated?: true;
21
+ }
22
+ /** A query or body as the row records it: its type, and for an object its keys. */
23
+ export interface ValueClass {
24
+ readonly type: JsonType;
25
+ readonly keys?: readonly KeyClass[];
26
+ /** How many keys past {@link MAX_CLASSED_KEYS} were counted rather than named. */
27
+ readonly omitted?: number;
28
+ }
29
+ /** A call's arguments, classed. */
30
+ export interface ArgumentClass {
31
+ /** Each path parameter's value, cut to {@link MAX_RECORDED_TEXT}. */
32
+ readonly path?: Readonly<Record<string, string>>;
33
+ /** The path parameters whose values were cut. */
34
+ readonly truncatedPath?: readonly string[];
35
+ readonly query?: ValueClass;
36
+ readonly body?: ValueClass;
37
+ }
38
+ /** The most keys one query or body names, so a row stays bounded whatever an agent sends. */
39
+ export declare const MAX_CLASSED_KEYS = 64;
40
+ /**
41
+ * The longest key name or path value a row records. With {@link MAX_CLASSED_KEYS}, it bounds the whole class, so an
42
+ * agent cannot pad its arguments until the row is too large to write.
43
+ */
44
+ export declare const MAX_RECORDED_TEXT = 128;
45
+ /** A value's JSON type. */
46
+ export declare function jsonType(value: unknown): JsonType;
47
+ /** The parameters a Hono path declares, in order. A trailing wildcard is the `path` argument `toolUrl` fills it from. */
48
+ export declare function pathParamNames(path: string): string[];
49
+ /** The class of a call's arguments against the route path the tool dispatches to. */
50
+ export declare function argumentClass(routePath: string, args: ToolArguments): ArgumentClass;
51
+ //# sourceMappingURL=argumentClass.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"argumentClass.d.ts","sourceRoot":"","sources":["../../src/mcp/argumentClass.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEhD;;;;;;;GAOG;AAEH,oEAAoE;AACpE,MAAM,MAAM,QAAQ,GAAG,QAAQ,GAAG,QAAQ,GAAG,SAAS,GAAG,MAAM,GAAG,OAAO,GAAG,QAAQ,CAAC;AAErF,wDAAwD;AACxD,MAAM,WAAW,QAAQ;IACvB,wDAAwD;IACxD,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC;IACxB,+EAA+E;IAC/E,QAAQ,CAAC,SAAS,CAAC,EAAE,IAAI,CAAC;CAC3B;AAED,mFAAmF;AACnF,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC;IACxB,QAAQ,CAAC,IAAI,CAAC,EAAE,SAAS,QAAQ,EAAE,CAAC;IACpC,kFAAkF;IAClF,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED,mCAAmC;AACnC,MAAM,WAAW,aAAa;IAC5B,qEAAqE;IACrE,QAAQ,CAAC,IAAI,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IACjD,iDAAiD;IACjD,QAAQ,CAAC,aAAa,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC3C,QAAQ,CAAC,KAAK,CAAC,EAAE,UAAU,CAAC;IAC5B,QAAQ,CAAC,IAAI,CAAC,EAAE,UAAU,CAAC;CAC5B;AAED,6FAA6F;AAC7F,eAAO,MAAM,gBAAgB,KAAK,CAAC;AAEnC;;;GAGG;AACH,eAAO,MAAM,iBAAiB,MAAM,CAAC;AAErC,2BAA2B;AAC3B,wBAAgB,QAAQ,CAAC,KAAK,EAAE,OAAO,GAAG,QAAQ,CAcjD;AAED,yHAAyH;AACzH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAGrD;AAoBD,qFAAqF;AACrF,wBAAgB,aAAa,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,aAAa,GAAG,aAAa,CAgBnF"}
@@ -0,0 +1,69 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ //#region src/mcp/argumentClass.ts
4
+ /** The most keys one query or body names, so a row stays bounded whatever an agent sends. */
5
+ const MAX_CLASSED_KEYS = 64;
6
+ /**
7
+ * The longest key name or path value a row records. With {@link MAX_CLASSED_KEYS}, it bounds the whole class, so an
8
+ * agent cannot pad its arguments until the row is too large to write.
9
+ */
10
+ const MAX_RECORDED_TEXT = 128;
11
+ /** A value's JSON type. */
12
+ function jsonType(value) {
13
+ if (value === null) return "null";
14
+ if (Array.isArray(value)) return "array";
15
+ switch (typeof value) {
16
+ case "string": return "string";
17
+ case "number":
18
+ case "bigint": return "number";
19
+ case "boolean": return "boolean";
20
+ default: return "object";
21
+ }
22
+ }
23
+ /** The parameters a Hono path declares, in order. A trailing wildcard is the `path` argument `toolUrl` fills it from. */
24
+ function pathParamNames(path) {
25
+ const names = [...path.matchAll(/:([A-Za-z0-9_]+)(\{[^}]*\})?\??/g)].map((match) => match[1] ?? "");
26
+ return path.endsWith("*") ? [...names, "path"] : names;
27
+ }
28
+ function classed(value) {
29
+ const type = jsonType(value);
30
+ if (type !== "object") return { type };
31
+ const entries = Object.entries(value).filter(([, entry]) => entry !== void 0).map(([key, entry]) => ({
32
+ key,
33
+ type: jsonType(entry)
34
+ })).sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
35
+ const keys = entries.slice(0, 64).map((entry) => entry.key.length > 128 ? {
36
+ ...entry,
37
+ key: entry.key.slice(0, 128),
38
+ truncated: true
39
+ } : entry);
40
+ const omitted = entries.length - keys.length;
41
+ return omitted > 0 ? {
42
+ type,
43
+ keys,
44
+ omitted
45
+ } : {
46
+ type,
47
+ keys
48
+ };
49
+ }
50
+ /** The class of a call's arguments against the route path the tool dispatches to. */
51
+ function argumentClass(routePath, args) {
52
+ const path = {};
53
+ const truncatedPath = [];
54
+ for (const name of pathParamNames(routePath)) {
55
+ const value = args.path?.[name];
56
+ if (value === void 0 || value === null) continue;
57
+ const text = String(value);
58
+ path[name] = text.slice(0, 128);
59
+ if (text.length > 128) truncatedPath.push(name);
60
+ }
61
+ return {
62
+ ...Object.keys(path).length === 0 ? {} : { path },
63
+ ...truncatedPath.length === 0 ? {} : { truncatedPath },
64
+ ...args.query === void 0 ? {} : { query: classed(args.query) },
65
+ ...args.body === void 0 ? {} : { body: classed(args.body) }
66
+ };
67
+ }
68
+ //#endregion
69
+ export { MAX_CLASSED_KEYS, MAX_RECORDED_TEXT, argumentClass, jsonType, pathParamNames };