@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
@@ -8,6 +8,8 @@ import { SQLiteBoolean, SQLiteDate } from "@pithy-sh/core/src/data/codecs";
8
8
  import { ConflictError, NotFoundError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
9
9
  import { formattingLocaleOf } from "@pithy-sh/core/src/i18n/locale";
10
10
  import type { Logger } from "@pithy-sh/core/src/logger/logger";
11
+ import { composedRetention } from "@pithy-sh/core/src/retention/composed";
12
+ import { purgeWindowDays } from "@pithy-sh/core/src/retention/policy";
11
13
  import type { EnqueueInput } from "@pithy-sh/email/src/send/enqueue";
12
14
  import { type CompiledQuery, sql } from "kysely";
13
15
  import { type AuthAuditAction, AuthAuditActions } from "../audit/actions";
@@ -165,6 +167,10 @@ interface HistoryRow {
165
167
  readonly step?: string | null;
166
168
  /** A hard deletion's choice for the purge's last mail; see `UserLifecycleEvent.notify`. */
167
169
  readonly notify?: boolean | null;
170
+ /** A deletion's mode, kept for the erasure attestation (#823). */
171
+ readonly mode?: DeletionMode | null;
172
+ /** When a deletion's purge comes due, kept for the erasure attestation (#823). */
173
+ readonly purgeAfter?: Date | null;
168
174
  }
169
175
 
170
176
  /** The history row's values, as the table stores them. */
@@ -178,6 +184,8 @@ function encoded(row: HistoryRow) {
178
184
  suspendedUntil: row.suspendedUntil ? SQLiteDate.encode(row.suspendedUntil) : null,
179
185
  step: row.step ?? null,
180
186
  notify: row.notify === undefined || row.notify === null ? null : SQLiteBoolean.encode(row.notify),
187
+ mode: row.mode ?? null,
188
+ purgeAfter: row.purgeAfter ? SQLiteDate.encode(row.purgeAfter) : null,
181
189
  createdAt: SQLiteDate.encode(row.at),
182
190
  };
183
191
  }
@@ -203,7 +211,19 @@ async function move(deps: LifecycleDeps, update: { compile(): CompiledQuery }, r
203
211
  const v = encoded(row);
204
212
  const insert = deps.db
205
213
  .insertInto("pithyAuthUserLifecycle")
206
- .columns(["userId", "action", "actorType", "actorId", "reason", "suspendedUntil", "step", "notify", "createdAt"])
214
+ .columns([
215
+ "userId",
216
+ "action",
217
+ "actorType",
218
+ "actorId",
219
+ "reason",
220
+ "suspendedUntil",
221
+ "step",
222
+ "notify",
223
+ "mode",
224
+ "purgeAfter",
225
+ "createdAt",
226
+ ])
207
227
  .expression(
208
228
  deps.db
209
229
  .selectNoFrom([
@@ -215,6 +235,8 @@ async function move(deps: LifecycleDeps, update: { compile(): CompiledQuery }, r
215
235
  sql.val(v.suspendedUntil).as("suspendedUntil"),
216
236
  sql.val(v.step).as("step"),
217
237
  sql.val(v.notify).as("notify"),
238
+ sql.val(v.mode).as("mode"),
239
+ sql.val(v.purgeAfter).as("purgeAfter"),
218
240
  sql.val(v.createdAt).as("createdAt"),
219
241
  ])
220
242
  .where(sql<number>`changes()`, ">", 0),
@@ -507,6 +529,15 @@ export async function reinstateUser(
507
529
  /** How a deletion runs: shut now and purged once the window closes, or purged now. */
508
530
  export type DeletionMode = "soft" | "hard";
509
531
 
532
+ /**
533
+ * How many days a soft deletion stays restorable: the Worker's `retention.purgeWindows.user` when its block
534
+ * names one, else `retention.purgeAfterDays` from this capability's own config.
535
+ */
536
+ export function userPurgeWindowDays(config: Pick<LifecycleDeps["config"], "retention">): number {
537
+ const retention = composedRetention();
538
+ return (retention && purgeWindowDays(retention, "user")) ?? config.retention.purgeAfterDays;
539
+ }
540
+
510
541
  /** What a deletion did, and the deletion it left in force. */
511
542
  export interface DeleteTransition extends LifecycleTransition {
512
543
  /**
@@ -543,16 +574,20 @@ export async function deleteUser(
543
574
  const at = (deps.now ?? (() => new Date()))();
544
575
  const reason = reasonOf(input.reason);
545
576
  const hard = input.mode === "hard";
546
- const purgeAfter = hard ? at : new Date(at.getTime() + deps.config.retention.purgeAfterDays * 86_400_000);
577
+ const purgeAfter = hard ? at : new Date(at.getTime() + userPurgeWindowDays(deps.config) * 86_400_000);
547
578
  const subject = await subjectOf(deps.db, input.userId);
548
579
  // A hard deletion's `notify` is the purge's to read, so it is written on the row: the purge that sends the last
549
580
  // mail may be one the daily pass started, with no request to carry it (#622).
581
+ // The mode and the due instant ride on the row too, because the purge erases the account's own column and the
582
+ // erasure attestation still has to say both (#823).
550
583
  const row: HistoryRow = {
551
584
  userId: input.userId,
552
585
  action: "deleted",
553
586
  actor: input.actor,
554
587
  reason,
555
588
  at,
589
+ mode: hard ? "hard" : "soft",
590
+ purgeAfter,
556
591
  ...(hard && input.notify !== undefined ? { notify: input.notify } : {}),
557
592
  };
558
593
  const existing = subject.columns.deletedAt;
@@ -780,6 +815,15 @@ export async function purgeSubject(
780
815
  return { state: "due", recipient: { email: row.email, name: row.name, locale: row.locale ?? null }, notify };
781
816
  }
782
817
 
818
+ /**
819
+ * The account's address, as a purge step reads it (#814) — `null` when there is no account, or no address. Read
820
+ * inside the step that asks, so it is never carried in a Workflow's journal.
821
+ */
822
+ export async function purgeAddress(db: AuthDatabase, userId: string): Promise<string | null> {
823
+ const row = await db.selectFrom("pithyAuthUsers").select("email").where("id", "=", userId).executeTakeFirst();
824
+ return row?.email ?? null;
825
+ }
826
+
783
827
  /** One account whose purge is due: which, and the deletion it is due under — ms-epoch, so a Workflow journal holds it. */
784
828
  export interface DuePurge {
785
829
  readonly userId: string;
@@ -808,21 +852,47 @@ export async function duePurges(deps: LifecycleDeps, limit: number): Promise<Due
808
852
 
809
853
  /**
810
854
  * Record that one purge step — one capability's contribution — erased its rows. The contribution's summary is
811
- * the row's reason, so the history says what the step erased and not only that it ran.
855
+ * the row's reason, so the history says what the step erased and not only that it ran. With `retained`, the step
856
+ * kept its rows instead (#814): the row is `purge_retained`, and its reason is the basis the capability gave.
812
857
  */
813
858
  export async function recordPurgeStep(
814
859
  deps: LifecycleDeps,
815
- input: { userId: string; step: string; summary?: string | null },
860
+ input: { userId: string; step: string; summary?: string | null; retained?: boolean },
816
861
  ): Promise<void> {
817
862
  const at = (deps.now ?? (() => new Date()))();
818
863
  await record(deps, {
819
864
  userId: input.userId,
820
- action: "purge_step",
865
+ // A retained step kept its rows (#814): its own action, so the trail never reads a kept step as an erased one.
866
+ action: input.retained ? "purge_retained" : "purge_step",
821
867
  actor: PURGE,
822
868
  reason: input.summary?.trim() ? input.summary.trim().slice(0, MAX_REASON) : null,
823
869
  at,
824
870
  step: input.step,
825
871
  });
872
+ // The trail's record of the step, which the erasure attestation cites by id and chain position (#823). The step's
873
+ // name and disposition only: the summary is the row's, and the trail never holds anything about the person.
874
+ await audit(deps, AuthAuditActions.adminUserPurgeStep, input.userId, PURGE, {
875
+ step: input.step,
876
+ disposition: input.retained ? "retained" : "erased",
877
+ });
878
+ }
879
+
880
+ /**
881
+ * Record that a purge gave up (#823): the step it stopped at, in the history and in the trail. The daily pass starts
882
+ * the purge again tomorrow, so this is where it stands until then, not an end. The failure's message is never
883
+ * written: it is code the kit did not write, and it may name the person.
884
+ */
885
+ export async function recordPurgeFailure(deps: LifecycleDeps, input: { userId: string; step: string }): Promise<void> {
886
+ const at = (deps.now ?? (() => new Date()))();
887
+ await record(deps, {
888
+ userId: input.userId,
889
+ action: "purge_failed",
890
+ actor: PURGE,
891
+ reason: null,
892
+ at,
893
+ step: input.step,
894
+ });
895
+ await audit(deps, AuthAuditActions.adminUserPurgeFailed, input.userId, PURGE, { step: input.step });
826
896
  }
827
897
 
828
898
  /**
@@ -0,0 +1,112 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { ToolArguments } from "./dispatch";
5
+
6
+ /**
7
+ * What a tool call's arguments leave in its audit row (`docs/AGENT-ACCESS.md` §9).
8
+ *
9
+ * A tool's arguments may carry a customer's own data, and an audit trail that copied them would be a second place
10
+ * that data lives. So the row keeps the route's path parameters verbatim, because they are the resource ids the
11
+ * route already records, and of the query and the body only the top-level key names, sorted, with each value's
12
+ * JSON type. No value, no length, no nested key.
13
+ */
14
+
15
+ /** A value's JSON type, with an array told apart from an object. */
16
+ export type JsonType = "string" | "number" | "boolean" | "null" | "array" | "object";
17
+
18
+ /** One top-level key and the JSON type of its value. */
19
+ export interface KeyClass {
20
+ /** The key's name, cut to {@link MAX_RECORDED_TEXT}. */
21
+ readonly key: string;
22
+ readonly type: JsonType;
23
+ /** Set when the name was longer than {@link MAX_RECORDED_TEXT} and was cut. */
24
+ readonly truncated?: true;
25
+ }
26
+
27
+ /** A query or body as the row records it: its type, and for an object its keys. */
28
+ export interface ValueClass {
29
+ readonly type: JsonType;
30
+ readonly keys?: readonly KeyClass[];
31
+ /** How many keys past {@link MAX_CLASSED_KEYS} were counted rather than named. */
32
+ readonly omitted?: number;
33
+ }
34
+
35
+ /** A call's arguments, classed. */
36
+ export interface ArgumentClass {
37
+ /** Each path parameter's value, cut to {@link MAX_RECORDED_TEXT}. */
38
+ readonly path?: Readonly<Record<string, string>>;
39
+ /** The path parameters whose values were cut. */
40
+ readonly truncatedPath?: readonly string[];
41
+ readonly query?: ValueClass;
42
+ readonly body?: ValueClass;
43
+ }
44
+
45
+ /** The most keys one query or body names, so a row stays bounded whatever an agent sends. */
46
+ export const MAX_CLASSED_KEYS = 64;
47
+
48
+ /**
49
+ * The longest key name or path value a row records. With {@link MAX_CLASSED_KEYS}, it bounds the whole class, so an
50
+ * agent cannot pad its arguments until the row is too large to write.
51
+ */
52
+ export const MAX_RECORDED_TEXT = 128;
53
+
54
+ /** A value's JSON type. */
55
+ export function jsonType(value: unknown): JsonType {
56
+ if (value === null) return "null";
57
+ if (Array.isArray(value)) return "array";
58
+ switch (typeof value) {
59
+ case "string":
60
+ return "string";
61
+ case "number":
62
+ case "bigint":
63
+ return "number";
64
+ case "boolean":
65
+ return "boolean";
66
+ default:
67
+ return "object";
68
+ }
69
+ }
70
+
71
+ /** The parameters a Hono path declares, in order. A trailing wildcard is the `path` argument `toolUrl` fills it from. */
72
+ export function pathParamNames(path: string): string[] {
73
+ const names = [...path.matchAll(/:([A-Za-z0-9_]+)(\{[^}]*\})?\??/g)].map((match) => match[1] ?? "");
74
+ return path.endsWith("*") ? [...names, "path"] : names;
75
+ }
76
+
77
+ function classed(value: unknown): ValueClass {
78
+ const type = jsonType(value);
79
+ if (type !== "object") return { type };
80
+ const entries = Object.entries(value as Record<string, unknown>)
81
+ .filter(([, entry]) => entry !== undefined)
82
+ .map(([key, entry]) => ({ key, type: jsonType(entry) }))
83
+ .sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
84
+ const keys = entries
85
+ .slice(0, MAX_CLASSED_KEYS)
86
+ .map((entry) =>
87
+ entry.key.length > MAX_RECORDED_TEXT
88
+ ? { ...entry, key: entry.key.slice(0, MAX_RECORDED_TEXT), truncated: true as const }
89
+ : entry,
90
+ );
91
+ const omitted = entries.length - keys.length;
92
+ return omitted > 0 ? { type, keys, omitted } : { type, keys };
93
+ }
94
+
95
+ /** The class of a call's arguments against the route path the tool dispatches to. */
96
+ export function argumentClass(routePath: string, args: ToolArguments): ArgumentClass {
97
+ const path: Record<string, string> = {};
98
+ const truncatedPath: string[] = [];
99
+ for (const name of pathParamNames(routePath)) {
100
+ const value = args.path?.[name];
101
+ if (value === undefined || value === null) continue;
102
+ const text = String(value);
103
+ path[name] = text.slice(0, MAX_RECORDED_TEXT);
104
+ if (text.length > MAX_RECORDED_TEXT) truncatedPath.push(name);
105
+ }
106
+ return {
107
+ ...(Object.keys(path).length === 0 ? {} : { path }),
108
+ ...(truncatedPath.length === 0 ? {} : { truncatedPath }),
109
+ ...(args.query === undefined ? {} : { query: classed(args.query) }),
110
+ ...(args.body === undefined ? {} : { body: classed(args.body) }),
111
+ };
112
+ }
@@ -0,0 +1,194 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { type Capability, defineCapability, type PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
5
+ import type { PurgeContext } from "@pithy-sh/core/src/capability/purge";
6
+ import { ValidationError } from "@pithy-sh/core/src/error/pithyError";
7
+ import { type AppTool, appTools } from "@pithy-sh/core/src/mcp/tools";
8
+ import { routeGroupsOf } from "@pithy-sh/core/src/openapi/routeGroups";
9
+ import type { Hono } from "hono";
10
+ import { z } from "zod";
11
+ import { isAuthCapability } from "../capability";
12
+ import { authPluginPlan } from "../migrations/pluginTables";
13
+ import { PACKAGE_NAME, PACKAGE_VERSION } from "../version.generated";
14
+ import { clientMetadataDiscovery } from "./clientMetadata";
15
+ import { floorLine, isOpenToEverySignedInUser, McpFloor } from "./floor";
16
+ import type { McpHost, McpWiring } from "./host";
17
+ import { registerMcpRoutes } from "./http/routes";
18
+ import { MCP_CAPABILITY_NAME } from "./marker";
19
+ import { mcpAuthorizationServer } from "./provider";
20
+ import { eraseMcpUser, exportMcpUser } from "./purge";
21
+
22
+ /**
23
+ * The MCP capability: the app's own agent surface, authorized as a user (`docs/AGENT-ACCESS.md` §4).
24
+ *
25
+ * **An agent that uses an application is a user of it.** It acts *as somebody*, with that person's authorization,
26
+ * through the app's own routes — never through the control-plane seam, which creates no user and no session. So
27
+ * this capability composes an OAuth 2.1 authorization server into the auth instance (`./provider.ts`), serves a
28
+ * streamable HTTP MCP endpoint (`./routes.ts`), and offers each caller the routes their role reaches as tools
29
+ * (`@pithy-sh/core/src/mcp/tools.ts`). Composing it mounts the endpoint; the adopter writes no route.
30
+ *
31
+ * **The default is closed.** It is off until composed, and composing it means choosing a {@link McpFloor}.
32
+ */
33
+
34
+ /** The migration order of the provider's tables in the `app` database. */
35
+ export const MCP_MIGRATION_ORDER = 1700;
36
+
37
+ /** The MCP capability's configuration. */
38
+ export const McpConfig = z
39
+ .object({
40
+ path: z
41
+ .string()
42
+ .regex(/^\/[a-z0-9/_-]*[a-z0-9]$/, "A path like `/mcp`.")
43
+ .default("/mcp")
44
+ .describe("Where the MCP endpoint mounts. A client is pointed at `<origin><path>`. Defaults to `/mcp`."),
45
+ floor: McpFloor,
46
+ consentPath: z
47
+ .string()
48
+ .regex(/^\/[A-Za-z0-9/_-]*$/, "A path like `/agent-consent`.")
49
+ .default("/agent-consent")
50
+ .describe(
51
+ "The scaffolded consent screen's path in this Worker's front end. Both sign-in and consent for an agent land there. Defaults to `/agent-consent`, which `pithy ui` writes.",
52
+ ),
53
+ database: z
54
+ .string()
55
+ .default("DB")
56
+ .describe("The D1 binding auth uses. The provider's tables live beside auth's. Must match `auth({ database })`."),
57
+ })
58
+ .describe("Configuration for the MCP capability.");
59
+ export type McpConfig = z.output<typeof McpConfig>;
60
+ export type McpConfigInput = z.input<typeof McpConfig>;
61
+
62
+ /** The MCP capability, with its resolved config attached for inspection. */
63
+ export interface McpCapability extends Capability {
64
+ readonly mcpConfig: McpConfig;
65
+ /** What auth composes into its instance. */
66
+ readonly mcpWiring: McpWiring;
67
+ /** Every tool the composed app offers, before any caller's role filters it. Empty until the app is built. */
68
+ readonly tools: () => readonly AppTool[];
69
+ /** Whether the endpoint is open to every signed-in user, and the floor in one line. Read by `pithy doctor`. */
70
+ readonly floorReport: { readonly open: boolean; readonly line: string };
71
+ }
72
+
73
+ /** The provider's tables, derived once from the plugin itself. Its options shape no column, so any resource does. */
74
+ const providerPlan = authPluginPlan([
75
+ mcpAuthorizationServer({
76
+ resource: "https://schema.invalid/mcp",
77
+ consentPage: "/agent-consent",
78
+ clientDiscovery: clientMetadataDiscovery(),
79
+ })[0],
80
+ ]);
81
+
82
+ /** The one migration that plan holds: the plugin's tables, under this capability's own namespace. */
83
+ export const PROVIDER_MIGRATION = (() => {
84
+ const [migration] = Object.values(providerPlan.migrations);
85
+ if (migration === undefined) {
86
+ throw new ValidationError({
87
+ message: "The OAuth provider declared no tables.",
88
+ detail: "authPluginPlan derived no migration for the oauth-provider plugin",
89
+ });
90
+ }
91
+ return migration;
92
+ })();
93
+
94
+ /** Refuse a composition this capability cannot serve, naming what to change. */
95
+ function hostFrom(capabilities: readonly Capability[], config: McpConfig): McpHost {
96
+ const authCap = capabilities.find(isAuthCapability);
97
+ if (!authCap) {
98
+ throw new ValidationError({
99
+ message: "The mcp capability requires the auth capability.",
100
+ action: "Add `auth(...)` to your capabilities. An agent acts as a signed-in user, and auth is who signs them in.",
101
+ });
102
+ }
103
+ if (authCap.authConfig.database !== config.database) {
104
+ throw new ValidationError({
105
+ message: "The mcp capability and the auth capability name different databases.",
106
+ action: `Set mcp({ database: "${authCap.authConfig.database}" }). The provider's tables live beside auth's.`,
107
+ detail: `mcp database ${config.database}, auth database ${authCap.authConfig.database}`,
108
+ });
109
+ }
110
+ const pluginIds = authCap.authConfig.plugins.map((plugin) => plugin.id);
111
+ if (pluginIds.includes("oauth-provider")) {
112
+ throw new ValidationError({
113
+ message: "auth({ plugins }) already composes an OAuth provider.",
114
+ action:
115
+ "Remove oauthProvider() from auth({ plugins: [...] }). The mcp capability composes the one this endpoint uses.",
116
+ });
117
+ }
118
+ return authCap.mcpHost;
119
+ }
120
+
121
+ /** The MCP capability. */
122
+ export function mcp(options: McpConfigInput): McpCapability {
123
+ const config = McpConfig.parse(options);
124
+ const wiring: McpWiring = {
125
+ path: config.path,
126
+ consentPage: config.consentPath,
127
+ clientDiscovery: clientMetadataDiscovery(),
128
+ };
129
+ let host: McpHost | undefined;
130
+ let app: Hono<PithyHonoEnv> | undefined;
131
+ let tools: readonly AppTool[] | undefined;
132
+
133
+ const ready = <T>(value: T | undefined, what: string): T => {
134
+ if (value === undefined) {
135
+ throw new ValidationError({
136
+ message: "The mcp capability is not composed.",
137
+ action: "Compose it through createBackend; it needs the auth capability beside it.",
138
+ detail: `mcp read its ${what} before createBackend composed it`,
139
+ });
140
+ }
141
+ return value;
142
+ };
143
+
144
+ const capability = defineCapability({
145
+ name: MCP_CAPABILITY_NAME,
146
+ version: PACKAGE_VERSION,
147
+ package: PACKAGE_NAME,
148
+ config: McpConfig,
149
+ dependsOn: ["auth"],
150
+ requiredBindings: [{ type: "d1", name: config.database }],
151
+ databases: {
152
+ app: {
153
+ binding: config.database,
154
+ tables: {},
155
+ migrationOrder: MCP_MIGRATION_ORDER,
156
+ migrations: { "0001_init": PROVIDER_MIGRATION },
157
+ },
158
+ },
159
+ purge: [
160
+ {
161
+ subject: "user",
162
+ summary:
163
+ "Every application the person let act as them: the consents, and the access and refresh tokens minted under them. A dynamically registered client is the application's, not the person's, and stays.",
164
+ erase: (context: PurgeContext) => eraseMcpUser(context, config.database),
165
+ export: (context: PurgeContext) => exportMcpUser(context, config.database),
166
+ },
167
+ ],
168
+ compose: ({ capabilities }) => {
169
+ host = hostFrom(capabilities, config);
170
+ },
171
+ routes: (router) => {
172
+ app = router as unknown as Hono<PithyHonoEnv>;
173
+ registerMcpRoutes(router as unknown as Hono<PithyHonoEnv>, {
174
+ path: config.path,
175
+ floor: config.floor,
176
+ host: () => ready(host, "auth host"),
177
+ app: () => ready(app, "router"),
178
+ tools: () => {
179
+ // Read once, after `createBackend` has recorded every capability's routes — the first request is the
180
+ // earliest moment the whole table exists, and it does not change afterwards.
181
+ tools ??= appTools(routeGroupsOf(ready(app, "router")) ?? []);
182
+ return tools;
183
+ },
184
+ });
185
+ },
186
+ });
187
+
188
+ return Object.assign(capability, {
189
+ mcpConfig: config,
190
+ mcpWiring: wiring,
191
+ tools: () => tools ?? (app ? appTools(routeGroupsOf(app) ?? []) : []),
192
+ floorReport: { open: isOpenToEverySignedInUser(config.floor), line: floorLine(config.floor) },
193
+ });
194
+ }
@@ -0,0 +1,81 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { createCimdClientDiscovery } from "@better-auth/cimd";
5
+ import { isPublicRoutableHost } from "@better-auth/core/utils/host";
6
+ import type { ClientDiscovery, ClientMetadataResourceFetch } from "@better-auth/oauth-provider";
7
+
8
+ /**
9
+ * Client ID Metadata Documents: a client whose `client_id` is an HTTPS URL, and whose registration is the document
10
+ * served there (`docs/AGENT-ACCESS.md` §4.0).
11
+ *
12
+ * **Composed, not written.** `@better-auth/cimd` fetches the document, refuses one whose `client_id` is not its own
13
+ * URL, caps it at 5 KB and 5 seconds, caches it by its own caching headers within {@link METADATA_CACHE_CEILING}, and
14
+ * persists the client it describes. The MCP profile requires `client_name` and `redirect_uris`. What this module adds
15
+ * is the network boundary the plugin asks its host to own, and the one fact the consent screen may present as
16
+ * verified.
17
+ */
18
+
19
+ /** The longest a fetched document is trusted before it is fetched again, whatever its caching headers say. */
20
+ export const METADATA_CACHE_CEILING = "60m";
21
+
22
+ /** The discovery id the provider stores on every client a metadata document created. */
23
+ export const CLIENT_METADATA_DISCOVERY_ID = "cimd";
24
+
25
+ /** Where a request is going, whichever form it arrived in. */
26
+ function targetOf(input: RequestInfo | URL): URL {
27
+ if (input instanceof URL) return input;
28
+ return new URL(typeof input === "string" ? input : input.url);
29
+ }
30
+
31
+ /**
32
+ * The fetch a metadata document, or a resource it names, is read over: HTTPS to a public host, a read, and never a
33
+ * redirect followed — a 3xx comes back as itself, and the plugin refuses anything but a 200.
34
+ *
35
+ * The host is classified before anything leaves. A name that resolves to private space is refused by Cloudflare's
36
+ * network at connection time, which is the resolve-and-pin guarantee a Worker cannot implement over `fetch` itself.
37
+ */
38
+ export const fetchClientMetadata: ClientMetadataResourceFetch = async (input, init) => {
39
+ const url = targetOf(input);
40
+ if (url.protocol !== "https:") throw new TypeError(`A client metadata document is fetched over HTTPS only: ${url}`);
41
+ if (!isPublicRoutableHost(url.hostname)) {
42
+ throw new TypeError(`A client metadata document is fetched from a public host only: ${url.hostname}`);
43
+ }
44
+ const method = (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase();
45
+ if (method !== "GET" && method !== "HEAD") {
46
+ throw new TypeError(`A client metadata document is read with GET or HEAD only, not ${method}`);
47
+ }
48
+ return fetch(url, {
49
+ method,
50
+ redirect: "manual",
51
+ ...(init?.headers === undefined ? {} : { headers: init.headers }),
52
+ ...(init?.signal == null ? {} : { signal: init.signal }),
53
+ });
54
+ };
55
+
56
+ /**
57
+ * The provider's discovery for metadata-document clients. Built once per composed `mcp()`, so its cache and its
58
+ * fetch budget outlive the per-request auth instance.
59
+ */
60
+ export function clientMetadataDiscovery(): ClientDiscovery {
61
+ return createCimdClientDiscovery({
62
+ fetchClientMetadataResource: fetchClientMetadata,
63
+ metadataProfile: "mcp-2026-07-28",
64
+ metadataRevalidationInterval: METADATA_CACHE_CEILING,
65
+ });
66
+ }
67
+
68
+ /**
69
+ * The host a client's identity was proven by, or `null` when nothing was. A metadata-document client is whoever
70
+ * serves the document at its id, so its id's host is verified; a dynamically registered client named itself, and
71
+ * nothing about it is.
72
+ */
73
+ export function verifiedHost(client: {
74
+ readonly clientId: string;
75
+ readonly clientDiscoveryId?: string | null;
76
+ }): string | null {
77
+ if (client.clientDiscoveryId !== CLIENT_METADATA_DISCOVERY_ID) return null;
78
+ if (!URL.canParse(client.clientId)) return null;
79
+ const url = new URL(client.clientId);
80
+ return url.protocol === "https:" ? url.host : null;
81
+ }
@@ -0,0 +1,95 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { type AppTool, mayCall, type ToolCaller } from "@pithy-sh/core/src/mcp/tools";
5
+ import type { ConsentCapability, ConsentScope, ConsentView } from "./http/responses";
6
+ import { MCP_SCOPES } from "./provider";
7
+
8
+ /**
9
+ * What the consent screen shows, built from the tools and the signer (`docs/AGENT-ACCESS.md` §4.3).
10
+ *
11
+ * **The unit of consent is a capability, not a tool.** One row per composed capability the user can reach, each
12
+ * listing what the client will then be able to do, in the capability's own words — each route's own summary —
13
+ * counted: *3 of 5 operations*. Per-tool consent cannot work, because a tool list changes without a deploy; a
14
+ * capability changes when a Worker deploys, which is a cadence a grant can survive.
15
+ *
16
+ * **Never a permission the user does not hold.** A row lists only the operations the signer's role reaches, and a
17
+ * capability with none is not listed at all. What the role withholds is a count, never a name — the screen says
18
+ * *two need a role you do not hold*, which discloses nothing a list would not.
19
+ *
20
+ * **Informational.** Nothing on it is selectable: one decision, *let this client act as you in this application*,
21
+ * with these rows as its consequence. The role is the ceiling either way, and the screen says so.
22
+ *
23
+ * **Codes, never sentences.** Everything here is data the screen words in the reader's language; a sentence built
24
+ * on the server would reach a Spanish screen in English.
25
+ */
26
+
27
+ /** Why a scope the client asked for is not granted: the role does not reach it, or no such permission exists. */
28
+ export type NotGrantedReason = ConsentScope["reason"];
29
+
30
+ /** The client, as the screen presents it. */
31
+ export interface ConsentClient {
32
+ readonly id: string;
33
+ /** The host a metadata document proved the client by, or `null` when it registered itself. */
34
+ readonly verifiedHost: string | null;
35
+ readonly reportedName: string | null;
36
+ readonly reportedUri: string | null;
37
+ readonly redirectUri: string;
38
+ }
39
+
40
+ /** The capability rows: only what the caller reaches, grouped, counted. */
41
+ export function consentCapabilities(tools: readonly AppTool[], caller: ToolCaller): ConsentCapability[] {
42
+ const rows = new Map<string, { reachable: AppTool[]; total: number }>();
43
+ for (const tool of tools) {
44
+ const row = rows.get(tool.capability) ?? { reachable: [], total: 0 };
45
+ row.total += 1;
46
+ if (mayCall(tool, caller)) row.reachable.push(tool);
47
+ rows.set(tool.capability, row);
48
+ }
49
+ return [...rows.entries()]
50
+ .filter(([, row]) => row.reachable.length > 0)
51
+ .map(([capability, row]) => ({
52
+ capability,
53
+ operations: row.reachable.map((tool) => ({ tool: tool.name, summary: tool.summary, effect: tool.effect })),
54
+ reachable: row.reachable.length,
55
+ total: row.total,
56
+ effects: {
57
+ writes: row.reachable.filter((tool) => tool.effect === "writes").length,
58
+ sends: row.reachable.filter((tool) => tool.effect === "sends").length,
59
+ charges: row.reachable.filter((tool) => tool.effect === "charges").length,
60
+ deletes: row.reachable.filter((tool) => tool.effect === "deletes").length,
61
+ },
62
+ }));
63
+ }
64
+
65
+ /**
66
+ * Each scope the client asked for, and what approving does with it. **A request the user cannot give is explained,
67
+ * not hidden**: the client named it, so saying it is not granted discloses nothing, and leaving it off would let the
68
+ * user believe they had granted it.
69
+ */
70
+ export function consentScopes(
71
+ requested: readonly string[],
72
+ tools: readonly AppTool[],
73
+ caller: ToolCaller,
74
+ ): ConsentScope[] {
75
+ return requested.map((scope) => {
76
+ if ((MCP_SCOPES as readonly string[]).includes(scope)) return { scope, granted: true, reason: null };
77
+ const tool = tools.find((entry) => entry.name === scope);
78
+ if (tool !== undefined && !mayCall(tool, caller)) return { scope, granted: false, reason: "role" };
79
+ return { scope, granted: false, reason: "unknown" };
80
+ });
81
+ }
82
+
83
+ /** Everything the consent screen shows. */
84
+ export function consentView(input: {
85
+ readonly client: ConsentClient;
86
+ readonly tools: readonly AppTool[];
87
+ readonly caller: ToolCaller;
88
+ readonly requestedScopes: readonly string[];
89
+ }): ConsentView {
90
+ return {
91
+ client: input.client,
92
+ capabilities: consentCapabilities(input.tools, input.caller),
93
+ requested: consentScopes(input.requestedScopes, input.tools, input.caller),
94
+ };
95
+ }