@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,316 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { Session } from "../data/betterAuth.js";
4
+ import { authDatabase } from "../data/tables.js";
5
+ import { correlation, emitHandoffExchanged, emitHandoffIssued } from "../audit/emit.js";
6
+ import { parseDeviceMeta, registerDevice } from "../device/registry.js";
7
+ import { getAuthInstance, resolveDb } from "./resolve.js";
8
+ import { guardErrorCallbackURL } from "./errorCallbackUrl.js";
9
+ import { apiErrorToPithy } from "./errors.js";
10
+ import { isHandoffChallenge, issueHandoff, redeemHandoff } from "../token/handoff.js";
11
+ import { ForbiddenError, InternalError, NotFoundError, PithyError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
12
+ //#region src/http/handoff.ts
13
+ /**
14
+ * The redirect half of a native sign-in, and the trade that ends it.
15
+ *
16
+ * A native app starts a social sign-in with its own deep link as `callbackURL` (a scheme in `trustedOrigins`,
17
+ * such as `myapp://auth/callback`). Better Auth checks that URL when the sign-in starts and, at the provider's
18
+ * callback, answers with a redirect to it carrying the session as a cookie. A cookie set on a redirect to an app
19
+ * scheme lands in the system browser, which the app never reads. {@link handOffToApp} replaces that answer: the
20
+ * session cookies are dropped and the deep link carries a one-time code instead (`../token/handoff.ts`). The app
21
+ * posts the code to `POST {base}/handoff`, {@link exchangeHandoff}, and gets the raw session token back.
22
+ *
23
+ * The code is bound to the app that asked for it. The app puts the S256 challenge of a verifier only it holds on
24
+ * its `callbackURL` as `handoff_challenge`, Better Auth keeps that URL with the sign-in's state, and the challenge
25
+ * comes back here on the redirect. It is moved off the link and stored with the code, and the trade must present
26
+ * the verifier. A deep link with no challenge gets no code at all.
27
+ *
28
+ * Which redirects are handed off: any whose link carries `handoff_challenge`, whatever its scheme, and any to a
29
+ * non-http(s) scheme. So an app's https universal link (iOS) or app link (Android), which the operating system
30
+ * routes only to the app that proves it owns the domain, gets a code when the app asks for one with a challenge.
31
+ * An http(s) callback with no challenge is a web page, and a web page gets its cookie.
32
+ *
33
+ * A magic link is handed off only to an https link. Whoever asks for the link chooses the challenge, and the
34
+ * person who opens it is somebody else, so the code must reach only the app that owns the link's domain. Any app
35
+ * can claim a custom scheme; a magic link to one is refused, and a native app without a universal link signs in
36
+ * by email with a one-time code instead.
37
+ *
38
+ * A native app starts a redirect sign-in with {@link startNativeSignIn}, a GET the system browser's sign-in sheet
39
+ * opens, rather than by posting `/sign-in/social` itself. Better Auth binds the sign-in to a signed `state`
40
+ * cookie and checks it at the provider's callback; set on the app's own request, that cookie would never reach
41
+ * the sheet that completes the callback.
42
+ */
43
+ /** The deep-link query parameter the one-time code travels in. */
44
+ const HANDOFF_CODE_PARAM = "code";
45
+ /** The `callbackURL` query parameter the app's S256 challenge travels in. */
46
+ const HANDOFF_CHALLENGE_PARAM = "handoff_challenge";
47
+ /** The `error` a deep link gets back when it carried no challenge to bind a code to. */
48
+ const HANDOFF_UNBOUND_ERROR = "handoff_challenge_required";
49
+ /** The `error` a magic link to a custom scheme gets back: only an https universal link or app link is handed one. */
50
+ const HANDOFF_SCHEME_REFUSED_ERROR = "handoff_scheme_refused";
51
+ /** Better Auth's magic-link verification, under `basePath`: the one redirect that ends an emailed sign-in. */
52
+ const MAGIC_LINK_VERIFY_PATH = "/magic-link/verify";
53
+ /** The cookie lines a response sets, as name and value. */
54
+ function setCookies(response) {
55
+ return response.headers.getSetCookie().map((line) => {
56
+ const pair = line.slice(0, line.indexOf(";") === -1 ? line.length : line.indexOf(";"));
57
+ const equals = pair.indexOf("=");
58
+ return {
59
+ line,
60
+ name: pair.slice(0, equals).trim(),
61
+ value: pair.slice(equals + 1).trim()
62
+ };
63
+ });
64
+ }
65
+ /** The raw session token inside a signed session cookie: everything before the signature. */
66
+ function rawToken(cookieValue) {
67
+ let decoded;
68
+ try {
69
+ decoded = decodeURIComponent(cookieValue);
70
+ } catch {
71
+ return null;
72
+ }
73
+ const token = decoded.split(".")[0];
74
+ return token ? token : null;
75
+ }
76
+ /**
77
+ * The app link a redirect points at, or null when it points anywhere a browser should go: a custom-scheme deep link,
78
+ * or an http(s) link that asked for a handoff by carrying a challenge.
79
+ */
80
+ function appLink(response) {
81
+ if (response.status < 300 || response.status >= 400) return null;
82
+ const location = response.headers.get("location");
83
+ if (!location) return null;
84
+ let target;
85
+ try {
86
+ target = new URL(location);
87
+ } catch {
88
+ return null;
89
+ }
90
+ return (target.protocol === "http:" || target.protocol === "https:") && !target.searchParams.has("handoff_challenge") ? null : target;
91
+ }
92
+ /** The `trustedOrigins` entry that would admit a link: its origin for http(s), its scheme otherwise. */
93
+ function trustedEntry(target) {
94
+ return target.protocol === "http:" || target.protocol === "https:" ? target.origin : `${target.protocol}//`;
95
+ }
96
+ /**
97
+ * Rewrite a sign-in that ends on an app link into a handoff, or answer null and leave the response as Better Auth
98
+ * wrote it: any answer that is not a redirect to an app link, and a redirect that sets no session (a refused
99
+ * sign-in returning its error to the app).
100
+ *
101
+ * An app link outside `trustedOrigins` is refused rather than followed. Better Auth checked the callback when the
102
+ * sign-in started, so reaching that branch means something else wrote the redirect, and a session must never be
103
+ * handed to a scheme this Worker does not trust.
104
+ */
105
+ async function handOffToApp(c, wiring, instance, response) {
106
+ const target = appLink(response);
107
+ if (!target) return null;
108
+ const context = await instance.$context;
109
+ const sessionCookieNames = [
110
+ context.authCookies.sessionToken.name,
111
+ context.authCookies.sessionData.name,
112
+ context.authCookies.dontRememberToken.name,
113
+ context.authCookies.accountData.name
114
+ ];
115
+ const isSessionCookie = (name) => sessionCookieNames.some((cookie) => name === cookie || name.startsWith(`${cookie}.`));
116
+ const cookies = setCookies(response);
117
+ const session = cookies.find((cookie) => cookie.name === context.authCookies.sessionToken.name && cookie.value);
118
+ if (!session) return null;
119
+ if (!context.isTrustedOrigin(target.href, { allowRelativePaths: false })) {
120
+ const token = rawToken(session.value);
121
+ if (token) await authDatabase(resolveDb(c.env, wiring.config.database)).deleteFrom("pithyAuthSessions").where("token", "=", token).execute();
122
+ throw new ForbiddenError({
123
+ message: "That app link is not one this service trusts.",
124
+ action: `Add the app's link to auth's \`trustedOrigins\`, for example "${trustedEntry(target)}".`,
125
+ detail: `sign-in redirect to untrusted app link ${trustedEntry(target)}`
126
+ });
127
+ }
128
+ const token = rawToken(session.value);
129
+ if (!token) return null;
130
+ const db = authDatabase(resolveDb(c.env, wiring.config.database));
131
+ const row = await db.selectFrom("pithyAuthSessions").select(["id", "userId"]).where("token", "=", token).executeTakeFirst();
132
+ if (!row) return null;
133
+ const challenge = target.searchParams.get(HANDOFF_CHALLENGE_PARAM);
134
+ target.searchParams.delete(HANDOFF_CHALLENGE_PARAM);
135
+ const refusal = new URL(c.req.raw.url).pathname === `${wiring.config.basePath}${MAGIC_LINK_VERIFY_PATH}` && target.protocol !== "https:" ? HANDOFF_SCHEME_REFUSED_ERROR : challenge !== null && isHandoffChallenge(challenge) ? null : HANDOFF_UNBOUND_ERROR;
136
+ if (refusal === null && challenge !== null) {
137
+ const { code } = await issueHandoff(db, {
138
+ sessionId: row.id,
139
+ challenge,
140
+ now: /* @__PURE__ */ new Date()
141
+ });
142
+ target.searchParams.set(HANDOFF_CODE_PARAM, code);
143
+ } else {
144
+ await db.deleteFrom("pithyAuthSessions").where("id", "=", row.id).execute();
145
+ target.searchParams.set("error", refusal ?? "handoff_challenge_required");
146
+ }
147
+ const headers = new Headers(response.headers);
148
+ headers.delete("set-cookie");
149
+ headers.delete("set-auth-token");
150
+ headers.set("location", target.href);
151
+ headers.set("cache-control", "no-store");
152
+ headers.set("referrer-policy", "no-referrer");
153
+ for (const cookie of cookies) if (!isSessionCookie(cookie.name)) headers.append("set-cookie", cookie.line);
154
+ await emitHandoffIssued(c.var.emit, {
155
+ ...refusal === null ? { outcome: "success" } : {
156
+ outcome: "denied",
157
+ reason: refusal === "handoff_scheme_refused" ? "scheme" : "unbound"
158
+ },
159
+ userId: row.userId,
160
+ sessionId: row.id,
161
+ ...correlation(c.req.raw.headers)
162
+ });
163
+ return new Response(null, {
164
+ status: response.status,
165
+ headers
166
+ });
167
+ }
168
+ /**
169
+ * Start a native redirect sign-in inside the system browser's sign-in sheet: run the social sign-in here and
170
+ * answer a redirect to the provider that carries Better Auth's `Set-Cookie`, so the signed `state` cookie lands in
171
+ * the jar of the browser that will come back through the provider's callback.
172
+ *
173
+ * Only for the handoff: the callback must be a link `trustedOrigins` admits, carrying a well-formed
174
+ * `handoff_challenge`, and a navigation another page started (`Sec-Fetch-Site` other than `none`) is refused. A web page starts its sign-in with the JSON `POST /sign-in/social`, as it always has.
175
+ * The sign-in runs on a request of its own with the sheet's cookies, origin and fetch metadata left behind:
176
+ * nothing the sheet already holds takes part in it.
177
+ */
178
+ async function startNativeSignIn(c, wiring, query) {
179
+ const site = c.req.raw.headers.get("sec-fetch-site");
180
+ if (site !== null && site !== "none") throw new ForbiddenError({
181
+ message: "Start a sign-in from the app.",
182
+ action: "Open the start address in the system browser's sign-in sheet, not from a link on a page.",
183
+ detail: `native sign-in start reached from ${site}`
184
+ });
185
+ if (!wiring.config[query.provider].enabled) throw new NotFoundError({
186
+ message: "That sign-in provider is not available here.",
187
+ action: `Enable \`${query.provider}\` in auth's config, or stop offering it.`,
188
+ detail: `native sign-in start for disabled provider ${query.provider}`
189
+ });
190
+ const instance = await getAuthInstance(c, wiring);
191
+ const context = await instance.$context;
192
+ for (const [field, value] of [["callbackURL", query.callbackURL], ["errorCallbackURL", query.errorCallbackURL]]) if (value !== void 0 && !context.isTrustedOrigin(value, { allowRelativePaths: false })) throw new ForbiddenError({
193
+ message: "That app link is not one this service trusts.",
194
+ action: "Add the app's link to auth's `trustedOrigins`.",
195
+ detail: `native sign-in start with untrusted ${field}`
196
+ });
197
+ let challenge;
198
+ try {
199
+ challenge = new URL(query.callbackURL).searchParams.get(HANDOFF_CHALLENGE_PARAM);
200
+ } catch {
201
+ challenge = null;
202
+ }
203
+ if (challenge === null || !isHandoffChallenge(challenge)) throw new ValidationError({
204
+ message: "That sign-in link has no handoff challenge.",
205
+ action: "Start a native sign-in with `handoffCallbackURL` from `@pithy-sh/auth/src/client/handoff`.",
206
+ detail: "native sign-in start without a well-formed handoff challenge",
207
+ issues: [{
208
+ path: ["callbackURL"],
209
+ message: `carries no well-formed ${HANDOFF_CHALLENGE_PARAM}`,
210
+ code: "custom"
211
+ }]
212
+ });
213
+ const headers = new Headers(c.req.raw.headers);
214
+ for (const name of [...headers.keys()]) if (name === "cookie" || name === "origin" || name === "referer" || name.startsWith("sec-fetch-")) headers.delete(name);
215
+ headers.delete("content-length");
216
+ headers.set("content-type", "application/json");
217
+ const signIn = new Request(new URL(`${wiring.config.basePath}/sign-in/social`, c.req.raw.url), {
218
+ method: "POST",
219
+ headers,
220
+ body: JSON.stringify({
221
+ provider: query.provider,
222
+ callbackURL: query.callbackURL,
223
+ ...query.errorCallbackURL === void 0 ? {} : { errorCallbackURL: query.errorCallbackURL }
224
+ })
225
+ });
226
+ let answer;
227
+ try {
228
+ answer = await instance.handler(await guardErrorCallbackURL(signIn, signIn.url));
229
+ } catch (error) {
230
+ throw apiErrorToPithy(error);
231
+ }
232
+ if (!answer.ok) return answer;
233
+ const body = await answer.json();
234
+ const url = typeof body === "object" && body !== null ? body.url : void 0;
235
+ if (typeof url !== "string") throw new InternalError({ detail: "the social sign-in answered without an authorization URL" });
236
+ const redirect = new Headers({
237
+ location: url,
238
+ "cache-control": "no-store",
239
+ "referrer-policy": "no-referrer"
240
+ });
241
+ for (const line of answer.headers.getSetCookie()) redirect.append("set-cookie", line);
242
+ return new Response(null, {
243
+ status: 302,
244
+ headers: redirect
245
+ });
246
+ }
247
+ /** The refusal every failed trade gets. One answer for spent, expired, unknown and a wrong verifier. */
248
+ function handoffInvalid(reason) {
249
+ return new PithyError({
250
+ code: "auth/handoff_invalid",
251
+ status: 400,
252
+ message: "That sign-in link has expired or was already used. Sign in again.",
253
+ detail: `handoff refused: ${reason}`
254
+ });
255
+ }
256
+ /**
257
+ * Trade a one-time code and its verifier for the session the code stands for. The code is spent by the attempt
258
+ * whatever the answer, so a wrong verifier gets one guess.
259
+ * Device headers sent with the trade register the device and bind it to the session, as they would on any other
260
+ * native sign-in; the browser that completed the redirect had none to send.
261
+ */
262
+ async function exchangeHandoff(c, wiring, body) {
263
+ const db = authDatabase(resolveDb(c.env, wiring.config.database));
264
+ const corr = correlation(c.req.raw.headers);
265
+ const now = /* @__PURE__ */ new Date();
266
+ const redemption = await redeemHandoff(db, {
267
+ code: body.code,
268
+ verifier: body.verifier
269
+ }, now);
270
+ if (!redemption.ok) {
271
+ await emitHandoffExchanged(c.var.emit, {
272
+ outcome: "denied",
273
+ reason: redemption.reason,
274
+ ...corr
275
+ });
276
+ throw handoffInvalid(redemption.reason);
277
+ }
278
+ const row = await db.selectFrom("pithyAuthSessions").select([
279
+ "id",
280
+ "token",
281
+ "userId",
282
+ "expiresAt",
283
+ "deviceId"
284
+ ]).where("id", "=", redemption.sessionId).executeTakeFirst();
285
+ const expiresAt = row ? Session.shape.expiresAt.parse(row.expiresAt) : null;
286
+ if (!row || !expiresAt || expiresAt.getTime() <= now.getTime()) {
287
+ await emitHandoffExchanged(c.var.emit, {
288
+ outcome: "denied",
289
+ reason: "unknown",
290
+ ...corr
291
+ });
292
+ throw handoffInvalid("the session the code stood for has ended");
293
+ }
294
+ const device = parseDeviceMeta(c.req.raw.headers);
295
+ if (device && !row.deviceId) {
296
+ await registerDevice(db, device, {
297
+ userId: row.userId,
298
+ lastIp: corr.ip ?? null,
299
+ now
300
+ });
301
+ await db.updateTable("pithyAuthSessions").set({ deviceId: device.id }).where("id", "=", row.id).execute();
302
+ }
303
+ await emitHandoffExchanged(c.var.emit, {
304
+ outcome: "success",
305
+ userId: row.userId,
306
+ sessionId: row.id,
307
+ ...corr
308
+ });
309
+ c.header("cache-control", "no-store");
310
+ return c.json({
311
+ token: row.token,
312
+ expiresAt: expiresAt.toISOString()
313
+ });
314
+ }
315
+ //#endregion
316
+ export { HANDOFF_CHALLENGE_PARAM, HANDOFF_CODE_PARAM, HANDOFF_SCHEME_REFUSED_ERROR, HANDOFF_UNBOUND_ERROR, exchangeHandoff, handOffToApp, startNativeSignIn };
@@ -3,6 +3,18 @@
3
3
  import type { PithyHonoEnv, PithyMiddleware } from "@pithy-sh/core/src/capability/capability";
4
4
  import type { Context, MiddlewareHandler } from "hono";
5
5
  import type { AuthWiring } from "../capability";
6
+ /**
7
+ * The header Better Auth's `apiKey()` plugin reads a key from by default. With `enableSessionForAPIKeys` on, the plugin
8
+ * answers `getSession` for a request carrying one, so a key stands for its owner's session. It is the default
9
+ * rather than whatever an adopter configured, because the plugin does not expose its options: an adopter who renames
10
+ * the header keeps `x-api-key` for keys meant to reach this middleware.
11
+ */
12
+ export declare const API_KEY_HEADER = "x-api-key";
13
+ /**
14
+ * Whether a request carries anything `getSession` could resolve: a bearer token, a session cookie, or an API key. A
15
+ * request with none stays anonymous without building the instance or reading D1.
16
+ */
17
+ export declare function carriesCredential(headers: Headers): boolean;
6
18
  export declare function createSessionMiddleware(wiring: AuthWiring): PithyMiddleware;
7
19
  /**
8
20
  * The gate other capabilities stack on a protected route. Rejects a request whose `AuthContext` was
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../../src/http/middleware.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,0CAA0C,CAAC;AAI9F,OAAO,KAAK,EAAE,OAAO,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AACvD,OAAO,KAAK,EAAE,UAAU,EAAuC,MAAM,eAAe,CAAC;AA6DrF,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,UAAU,GAAG,eAAe,CAqB3E;AA4FD;;;;;;;;GAQG;AACH,wBAAgB,WAAW,IAAI,iBAAiB,CAAC,YAAY,CAAC,CAY7D;AAED,yGAAyG;AACzG,MAAM,WAAW,aAAa;IAC5B,mBAAmB;IACnB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,yCAAyC;IACzC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,uEAAuE;IACvE,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;CAC7B;AAED;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,GAAG,aAAa,GAAG,IAAI,CAI5E;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,IAAI,iBAAiB,CAAC,YAAY,CAAC,CAYtE"}
1
+ {"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../../src/http/middleware.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,0CAA0C,CAAC;AAI9F,OAAO,KAAK,EAAE,OAAO,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AACvD,OAAO,KAAK,EAAE,UAAU,EAAuC,MAAM,eAAe,CAAC;AA+DrF;;;;;GAKG;AACH,eAAO,MAAM,cAAc,cAAc,CAAC;AAE1C;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAE3D;AAED,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,UAAU,GAAG,eAAe,CA6B3E;AA4FD;;;;;;;;GAQG;AACH,wBAAgB,WAAW,IAAI,iBAAiB,CAAC,YAAY,CAAC,CAY7D;AAED,yGAAyG;AACzG,MAAM,WAAW,aAAa;IAC5B,mBAAmB;IACnB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,yCAAyC;IACzC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,uEAAuE;IACvE,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;CAC7B;AAED;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,GAAG,aAAa,GAAG,IAAI,CAI5E;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,IAAI,iBAAiB,CAAC,YAAY,CAAC,CAYtE"}
@@ -1,6 +1,7 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
  import { authDatabase } from "../data/tables.js";
4
+ import { dispatchedAuth } from "../mcp/dispatch.js";
4
5
  import { LifecycleColumns } from "../lifecycle/state.js";
5
6
  import { lifecycleRefusalFor, noteRefusal, noticedRefusal, suspendedHolder } from "../lifecycle/enforce.js";
6
7
  import { getAuthInstance, resolveDb } from "./resolve.js";
@@ -11,9 +12,10 @@ import { AuthContext } from "@pithy-sh/core/src/http/authContext";
11
12
  //#region src/http/middleware.ts
12
13
  /**
13
14
  * The session-resolution middleware: it fills core's `AuthContext` seam (`c.var.auth`) for every
14
- * request that carries a credential — a bearer token or a session cookie. Better Auth resolves both
15
+ * request that carries a credential — a bearer token, a session cookie, or an API key in `x-api-key` when
16
+ * the adopter composes `apiKey({ enableSessionForAPIKeys: true })`. Better Auth resolves all three
15
17
  * transparently (the bearer plugin rewrites the header into the session cookie), so one `getSession`
16
- * call covers mobile and web. A credential-less request stays anonymous (no instance build, no D1 hit).
18
+ * call covers mobile, web and a machine. A credential-less request stays anonymous (no instance build, no D1 hit).
17
19
  * Resolution never throws — an invalid credential simply leaves `auth` null for `requireAuth` to reject.
18
20
  */
19
21
  /** The session's authentication instant when it is a real `Date`, else `null`. Never anything else. */
@@ -52,10 +54,29 @@ async function resolvedScopes(c, resolve, session) {
52
54
  }
53
55
  return parsed.data;
54
56
  }
57
+ /**
58
+ * The header Better Auth's `apiKey()` plugin reads a key from by default. With `enableSessionForAPIKeys` on, the plugin
59
+ * answers `getSession` for a request carrying one, so a key stands for its owner's session. It is the default
60
+ * rather than whatever an adopter configured, because the plugin does not expose its options: an adopter who renames
61
+ * the header keeps `x-api-key` for keys meant to reach this middleware.
62
+ */
63
+ const API_KEY_HEADER = "x-api-key";
64
+ /**
65
+ * Whether a request carries anything `getSession` could resolve: a bearer token, a session cookie, or an API key. A
66
+ * request with none stays anonymous without building the instance or reading D1.
67
+ */
68
+ function carriesCredential(headers) {
69
+ return headers.has("authorization") || headers.has("cookie") || headers.has("x-api-key");
70
+ }
55
71
  function createSessionMiddleware(wiring) {
56
72
  return (app) => {
57
73
  app.use("*", async (c, next) => {
58
- if (!c.req.raw.headers.has("authorization") && !c.req.raw.headers.has("cookie")) return await next();
74
+ const dispatched = dispatchedAuth(c.req.raw);
75
+ if (dispatched !== void 0) {
76
+ c.set("auth", dispatched);
77
+ return await next();
78
+ }
79
+ if (!carriesCredential(c.req.raw.headers)) return await next();
59
80
  let instance;
60
81
  try {
61
82
  instance = await getAuthInstance(c, wiring);
@@ -185,4 +206,4 @@ function requireAccountHolder() {
185
206
  };
186
207
  }
187
208
  //#endregion
188
- export { accountHolder, createSessionMiddleware, requireAccountHolder, requireAuth };
209
+ export { API_KEY_HEADER, accountHolder, carriesCredential, createSessionMiddleware, requireAccountHolder, requireAuth };
@@ -1 +1 @@
1
- {"version":3,"file":"resolve.d.ts","sourceRoot":"","sources":["../../src/http/resolve.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAE5D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAK7E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAGhD,OAAO,EAAE,KAAK,YAAY,EAAY,MAAM,kBAAkB,CAAC;AAuB/D,2GAA2G;AAC3G,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,WAAW,EAAE,MAAM,GAAG,UAAU,CASvF;AA0BD,wBAAgB,eAAe,CAAC,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,YAAY,CAAC,CAMnG"}
1
+ {"version":3,"file":"resolve.d.ts","sourceRoot":"","sources":["../../src/http/resolve.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAE5D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAK7E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAGhD,OAAO,EAAE,KAAK,YAAY,EAAY,MAAM,kBAAkB,CAAC;AAwB/D,2GAA2G;AAC3G,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,WAAW,EAAE,MAAM,GAAG,UAAU,CASvF;AA0BD,wBAAgB,eAAe,CAAC,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,YAAY,CAAC,CAMnG"}
@@ -7,6 +7,7 @@ import { makeSendAuthEmail } from "../email/send.js";
7
7
  import { resolveProvider } from "../instance/providers.js";
8
8
  import { makeAuth } from "../instance/auth.js";
9
9
  import { ensureJwksSealedUnderCurrent } from "../instance/jwksReencryption.js";
10
+ import { mcpAuthorizationServer } from "../mcp/provider.js";
10
11
  import { InternalError } from "@pithy-sh/core/src/error/pithyError";
11
12
  import { createWorkerLogger } from "@pithy-sh/core/src/logger/worker";
12
13
  //#region src/http/resolve.ts
@@ -29,7 +30,7 @@ function resolveDb(env, bindingName) {
29
30
  /**
30
31
  * The language to write a sign-in email in, for one address.
31
32
  *
32
- * **The stored preference first, the request's negotiation second** (pithy-sh/pithy#441). Somebody who
33
+ * **The stored preference first, the request's negotiation second.** Somebody who
33
34
  * picked a language in a settings pane has said something durable about themselves; the device they are
34
35
  * signing in from tonight has only sent an `Accept-Language`. But most of what this is asked about is a
35
36
  * *first* sign-in, where no row exists yet — and that is precisely the message a project cannot afford
@@ -86,12 +87,13 @@ async function buildAuthInstance(c, wiring) {
86
87
  log: (c.get("log") ?? createWorkerLogger({ name: "auth" })).child("auth")
87
88
  });
88
89
  const listener = wiring.onSessionRevoked;
90
+ const baseURL = baseURLResolver(cfg.baseURL)(c.req.raw);
89
91
  return makeAuth({
90
92
  db: authDatabase(d1),
91
93
  ...listener ? { onSessionRevoked: (session) => listener(session, d1) } : {},
92
94
  secret,
93
95
  sessionSecrets,
94
- baseURL: baseURLResolver(cfg.baseURL)(c.req.raw),
96
+ baseURL,
95
97
  locale: c.var.locale?.catalogLocale ?? null,
96
98
  basePath: cfg.basePath,
97
99
  trustedOrigins: cfg.trustedOrigins,
@@ -116,7 +118,11 @@ async function buildAuthInstance(c, wiring) {
116
118
  ...wiring.resolveGithubUserInfo ? { resolveGithubUserInfo: wiring.resolveGithubUserInfo } : {},
117
119
  emit: (event) => c.var.emit(event),
118
120
  requestHeaders: c.req.raw.headers,
119
- plugins: cfg.plugins
121
+ plugins: wiring.mcp ? [...cfg.plugins, ...mcpAuthorizationServer({
122
+ resource: `${baseURL}${wiring.mcp.path}`,
123
+ consentPage: wiring.mcp.consentPage,
124
+ clientDiscovery: wiring.mcp.clientDiscovery
125
+ })] : cfg.plugins
120
126
  });
121
127
  }
122
128
  //#endregion
@@ -11,6 +11,13 @@ export declare const AdminUserView: z.ZodObject<{
11
11
  locale: z.ZodOptional<z.ZodNullable<z.ZodString>>;
12
12
  createdAt: z.ZodISODateTime;
13
13
  updatedAt: z.ZodISODateTime;
14
+ state: z.ZodOptional<z.ZodEnum<{
15
+ active: "active";
16
+ deleted: "deleted";
17
+ suspended: "suspended";
18
+ }>>;
19
+ suspendedUntil: z.ZodOptional<z.ZodNullable<z.ZodISODateTime>>;
20
+ purgeAfter: z.ZodOptional<z.ZodNullable<z.ZodISODateTime>>;
14
21
  }, z.core.$strip>;
15
22
  export type AdminUserView = z.output<typeof AdminUserView>;
16
23
  /** A session as a management client may see it — the token is not part of the contract. */
@@ -53,6 +60,13 @@ export declare const AdminUsersResponse: z.ZodObject<{
53
60
  locale: z.ZodOptional<z.ZodNullable<z.ZodString>>;
54
61
  createdAt: z.ZodISODateTime;
55
62
  updatedAt: z.ZodISODateTime;
63
+ state: z.ZodOptional<z.ZodEnum<{
64
+ active: "active";
65
+ deleted: "deleted";
66
+ suspended: "suspended";
67
+ }>>;
68
+ suspendedUntil: z.ZodOptional<z.ZodNullable<z.ZodISODateTime>>;
69
+ purgeAfter: z.ZodOptional<z.ZodNullable<z.ZodISODateTime>>;
56
70
  }, z.core.$strip>>;
57
71
  nextCursor: z.ZodNullable<z.ZodString>;
58
72
  }, z.core.$strip>;
@@ -67,6 +81,13 @@ export declare const AdminUserResponse: z.ZodObject<{
67
81
  locale: z.ZodOptional<z.ZodNullable<z.ZodString>>;
68
82
  createdAt: z.ZodISODateTime;
69
83
  updatedAt: z.ZodISODateTime;
84
+ state: z.ZodOptional<z.ZodEnum<{
85
+ active: "active";
86
+ deleted: "deleted";
87
+ suspended: "suspended";
88
+ }>>;
89
+ suspendedUntil: z.ZodOptional<z.ZodNullable<z.ZodISODateTime>>;
90
+ purgeAfter: z.ZodOptional<z.ZodNullable<z.ZodISODateTime>>;
70
91
  }, z.core.$strip>;
71
92
  providers: z.ZodDiscriminatedUnion<[z.ZodObject<{
72
93
  state: z.ZodLiteral<"read">;
@@ -134,6 +155,84 @@ export declare const AdminDevicesResponse: z.ZodObject<{
134
155
  nextCursor: z.ZodNullable<z.ZodString>;
135
156
  }, z.core.$strip>;
136
157
  export type AdminDevicesResponse = z.output<typeof AdminDevicesResponse>;
158
+ /**
159
+ * One sign-in link or code from the verification ledger (#829), as a management client sees it.
160
+ *
161
+ * Never the token and never the address: the ledger holds neither. The mail is named by its job id, which is how
162
+ * a reader holding `email:jobs:read` joins this to a bounce, a deferral or a suppression.
163
+ */
164
+ export declare const AdminVerificationView: z.ZodObject<{
165
+ verificationId: z.ZodString;
166
+ type: z.ZodEnum<{
167
+ magic_link: "magic_link";
168
+ otp: "otp";
169
+ }>;
170
+ state: z.ZodEnum<{
171
+ expired: "expired";
172
+ pending: "pending";
173
+ used: "used";
174
+ }>;
175
+ userId: z.ZodNullable<z.ZodString>;
176
+ emailJobId: z.ZodNullable<z.ZodString>;
177
+ issuedAt: z.ZodISODateTime;
178
+ expiresAt: z.ZodISODateTime;
179
+ usedAt: z.ZodNullable<z.ZodISODateTime>;
180
+ }, z.core.$strip>;
181
+ export type AdminVerificationView = z.output<typeof AdminVerificationView>;
182
+ /** How many of one type were issued over the window, and where they stand. */
183
+ export declare const VerificationTypeCounts: z.ZodObject<{
184
+ type: z.ZodEnum<{
185
+ magic_link: "magic_link";
186
+ otp: "otp";
187
+ }>;
188
+ issued: z.ZodNumber;
189
+ used: z.ZodNumber;
190
+ expired: z.ZodNumber;
191
+ pending: z.ZodNumber;
192
+ }, z.core.$strip>;
193
+ export type VerificationTypeCounts = z.output<typeof VerificationTypeCounts>;
194
+ /**
195
+ * `GET {base}/admin/verifications` (#829): the window it covered, the counts by type and state over all of it,
196
+ * and a page of its rows, newest issue first.
197
+ *
198
+ * The counts cover every row in the window whatever the page or the filters say, and every type, with zeros —
199
+ * so a pane reading "sign-in links: 0 issued" can tell it from a Worker that did not say.
200
+ */
201
+ export declare const AdminVerificationsResponse: z.ZodObject<{
202
+ window: z.ZodObject<{
203
+ since: z.ZodISODateTime;
204
+ until: z.ZodISODateTime;
205
+ }, z.core.$strip>;
206
+ counts: z.ZodArray<z.ZodObject<{
207
+ type: z.ZodEnum<{
208
+ magic_link: "magic_link";
209
+ otp: "otp";
210
+ }>;
211
+ issued: z.ZodNumber;
212
+ used: z.ZodNumber;
213
+ expired: z.ZodNumber;
214
+ pending: z.ZodNumber;
215
+ }, z.core.$strip>>;
216
+ verifications: z.ZodArray<z.ZodObject<{
217
+ verificationId: z.ZodString;
218
+ type: z.ZodEnum<{
219
+ magic_link: "magic_link";
220
+ otp: "otp";
221
+ }>;
222
+ state: z.ZodEnum<{
223
+ expired: "expired";
224
+ pending: "pending";
225
+ used: "used";
226
+ }>;
227
+ userId: z.ZodNullable<z.ZodString>;
228
+ emailJobId: z.ZodNullable<z.ZodString>;
229
+ issuedAt: z.ZodISODateTime;
230
+ expiresAt: z.ZodISODateTime;
231
+ usedAt: z.ZodNullable<z.ZodISODateTime>;
232
+ }, z.core.$strip>>;
233
+ nextCursor: z.ZodNullable<z.ZodString>;
234
+ }, z.core.$strip>;
235
+ export type AdminVerificationsResponse = z.output<typeof AdminVerificationsResponse>;
137
236
  /**
138
237
  * `POST {base}/admin/sessions/revoke` and `POST {base}/admin/users/:userId/sessions/revoke`.
139
238
  *
@@ -248,6 +347,11 @@ export declare const AuthUserExport: z.ZodObject<{
248
347
  locale: z.ZodOptional<z.ZodNullable<z.ZodString>>;
249
348
  createdAt: z.ZodISODateTime;
250
349
  updatedAt: z.ZodISODateTime;
350
+ state: z.ZodOptional<z.ZodEnum<{
351
+ active: "active";
352
+ deleted: "deleted";
353
+ suspended: "suspended";
354
+ }>>;
251
355
  suspendedAt: z.ZodNullable<z.ZodISODateTime>;
252
356
  suspendedUntil: z.ZodNullable<z.ZodISODateTime>;
253
357
  deletedAt: z.ZodNullable<z.ZodISODateTime>;
@@ -289,6 +393,23 @@ export declare const AuthUserExport: z.ZodObject<{
289
393
  suspendedUntil: z.ZodNullable<z.ZodISODateTime>;
290
394
  createdAt: z.ZodISODateTime;
291
395
  }, z.core.$strip>>;
396
+ verifications: z.ZodOptional<z.ZodArray<z.ZodObject<{
397
+ verificationId: z.ZodString;
398
+ type: z.ZodEnum<{
399
+ magic_link: "magic_link";
400
+ otp: "otp";
401
+ }>;
402
+ state: z.ZodEnum<{
403
+ expired: "expired";
404
+ pending: "pending";
405
+ used: "used";
406
+ }>;
407
+ userId: z.ZodNullable<z.ZodString>;
408
+ emailJobId: z.ZodNullable<z.ZodString>;
409
+ issuedAt: z.ZodISODateTime;
410
+ expiresAt: z.ZodISODateTime;
411
+ usedAt: z.ZodNullable<z.ZodISODateTime>;
412
+ }, z.core.$strip>>>;
292
413
  plugins: z.ZodRecord<z.ZodString, z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
293
414
  }, z.core.$strip>;
294
415
  export type AuthUserExport = z.output<typeof AuthUserExport>;
@@ -308,15 +429,30 @@ export declare const AdminUserExportResponse: z.ZodObject<{
308
429
  capabilities: z.ZodArray<z.ZodDiscriminatedUnion<[z.ZodObject<{
309
430
  capability: z.ZodString;
310
431
  summary: z.ZodString;
432
+ disposition: z.ZodOptional<z.ZodEnum<{
433
+ erase: "erase";
434
+ retain: "retain";
435
+ }>>;
436
+ basis: z.ZodOptional<z.ZodString>;
311
437
  state: z.ZodLiteral<"exported">;
312
438
  data: z.ZodRecord<z.ZodString, z.ZodUnknown>;
313
439
  }, z.core.$strip>, z.ZodObject<{
314
440
  capability: z.ZodString;
315
441
  summary: z.ZodString;
442
+ disposition: z.ZodOptional<z.ZodEnum<{
443
+ erase: "erase";
444
+ retain: "retain";
445
+ }>>;
446
+ basis: z.ZodOptional<z.ZodString>;
316
447
  state: z.ZodLiteral<"not_exported">;
317
448
  }, z.core.$strip>, z.ZodObject<{
318
449
  capability: z.ZodString;
319
450
  summary: z.ZodString;
451
+ disposition: z.ZodOptional<z.ZodEnum<{
452
+ erase: "erase";
453
+ retain: "retain";
454
+ }>>;
455
+ basis: z.ZodOptional<z.ZodString>;
320
456
  state: z.ZodLiteral<"unavailable">;
321
457
  }, z.core.$strip>], "state">>;
322
458
  }, z.core.$strip>;
@@ -328,6 +464,12 @@ export declare const TokenRotateResponse: z.ZodObject<{
328
464
  expiresAt: z.ZodISODateTime;
329
465
  }, z.core.$strip>;
330
466
  export type TokenRotateResponse = z.output<typeof TokenRotateResponse>;
467
+ /** `POST {base}/handoff`. */
468
+ export declare const HandoffExchangeResponse: z.ZodObject<{
469
+ token: z.ZodString;
470
+ expiresAt: z.ZodISODateTime;
471
+ }, z.core.$strip>;
472
+ export type HandoffExchangeResponse = z.output<typeof HandoffExchangeResponse>;
331
473
  /** One of the caller's own registered devices. */
332
474
  export declare const MyDeviceView: z.ZodObject<{
333
475
  id: z.ZodString;