@pithy-sh/auth 0.8.0 → 0.10.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 (164) hide show
  1. package/README.md +12 -2
  2. package/dist/audit/actions.d.ts +21 -0
  3. package/dist/audit/actions.d.ts.map +1 -1
  4. package/dist/audit/actions.js +22 -1
  5. package/dist/audit/emit.js +1 -1
  6. package/dist/caller/certificate.d.ts +83 -0
  7. package/dist/caller/certificate.d.ts.map +1 -0
  8. package/dist/caller/certificate.js +92 -0
  9. package/dist/caller/request.d.ts +66 -0
  10. package/dist/caller/request.d.ts.map +1 -0
  11. package/dist/caller/request.js +71 -0
  12. package/dist/caller/token.d.ts +130 -0
  13. package/dist/caller/token.d.ts.map +1 -0
  14. package/dist/caller/token.js +207 -0
  15. package/dist/capability.d.ts +70 -2
  16. package/dist/capability.d.ts.map +1 -1
  17. package/dist/capability.js +28 -7
  18. package/dist/client/lifecycle.d.ts +19 -0
  19. package/dist/client/lifecycle.d.ts.map +1 -0
  20. package/dist/client/lifecycle.js +25 -0
  21. package/dist/client/projection.d.ts +4 -0
  22. package/dist/client/projection.d.ts.map +1 -1
  23. package/dist/data/betterAuth.d.ts +5 -1
  24. package/dist/data/betterAuth.d.ts.map +1 -1
  25. package/dist/data/betterAuth.js +7 -3
  26. package/dist/data/kitFields.d.ts +20 -25
  27. package/dist/data/kitFields.d.ts.map +1 -1
  28. package/dist/data/kitFields.js +28 -32
  29. package/dist/data/tables.d.ts +29 -3
  30. package/dist/data/tables.d.ts.map +1 -1
  31. package/dist/data/tables.js +5 -3
  32. package/dist/data/userLifecycle.d.ts +61 -0
  33. package/dist/data/userLifecycle.d.ts.map +1 -0
  34. package/dist/data/userLifecycle.js +50 -0
  35. package/dist/http/credentialResign.d.ts +46 -0
  36. package/dist/http/credentialResign.d.ts.map +1 -0
  37. package/dist/http/credentialResign.js +203 -0
  38. package/dist/http/errorCallbackUrl.d.ts.map +1 -1
  39. package/dist/http/errorCallbackUrl.js +15 -9
  40. package/dist/http/guards.d.ts +23 -1
  41. package/dist/http/guards.d.ts.map +1 -1
  42. package/dist/http/guards.js +28 -3
  43. package/dist/http/lifecycleGate.d.ts +18 -0
  44. package/dist/http/lifecycleGate.d.ts.map +1 -0
  45. package/dist/http/lifecycleGate.js +75 -0
  46. package/dist/http/middleware.d.ts +5 -0
  47. package/dist/http/middleware.d.ts.map +1 -1
  48. package/dist/http/middleware.js +113 -21
  49. package/dist/http/providerRefusal.d.ts +8 -7
  50. package/dist/http/providerRefusal.d.ts.map +1 -1
  51. package/dist/http/providerRefusal.js +37 -32
  52. package/dist/http/resolve.d.ts.map +1 -1
  53. package/dist/http/resolve.js +23 -5
  54. package/dist/http/routes.d.ts.map +1 -1
  55. package/dist/http/routes.js +20 -1
  56. package/dist/instance/auth.d.ts +1280 -5
  57. package/dist/instance/auth.d.ts.map +1 -1
  58. package/dist/instance/auth.js +59 -4
  59. package/dist/instance/jwksReencryption.d.ts +75 -0
  60. package/dist/instance/jwksReencryption.d.ts.map +1 -0
  61. package/dist/instance/jwksReencryption.js +160 -0
  62. package/dist/instance/microsoftEmail.d.ts +70 -0
  63. package/dist/instance/microsoftEmail.d.ts.map +1 -0
  64. package/dist/instance/microsoftEmail.js +96 -0
  65. package/dist/instance/providerSignInGate.d.ts +14 -12
  66. package/dist/instance/providerSignInGate.d.ts.map +1 -1
  67. package/dist/instance/providerSignInGate.js +23 -20
  68. package/dist/instance/providers.d.ts +7 -5
  69. package/dist/instance/providers.d.ts.map +1 -1
  70. package/dist/instance/providers.js +5 -3
  71. package/dist/instance/secrets.d.ts +232 -4
  72. package/dist/instance/secrets.d.ts.map +1 -1
  73. package/dist/instance/secrets.js +129 -7
  74. package/dist/instance/sessionSecrets.d.ts +45 -0
  75. package/dist/instance/sessionSecrets.d.ts.map +1 -0
  76. package/dist/instance/sessionSecrets.js +29 -0
  77. package/dist/lifecycle/enforce.d.ts +40 -0
  78. package/dist/lifecycle/enforce.d.ts.map +1 -0
  79. package/dist/lifecycle/enforce.js +70 -0
  80. package/dist/lifecycle/hooks.d.ts +53 -0
  81. package/dist/lifecycle/hooks.d.ts.map +1 -0
  82. package/dist/lifecycle/hooks.js +2 -0
  83. package/dist/lifecycle/request.d.ts +15 -0
  84. package/dist/lifecycle/request.d.ts.map +1 -0
  85. package/dist/lifecycle/request.js +27 -0
  86. package/dist/lifecycle/state.d.ts +64 -0
  87. package/dist/lifecycle/state.d.ts.map +1 -0
  88. package/dist/lifecycle/state.js +90 -0
  89. package/dist/lifecycle/transitions.d.ts +132 -0
  90. package/dist/lifecycle/transitions.d.ts.map +1 -0
  91. package/dist/lifecycle/transitions.js +349 -0
  92. package/dist/migrations/0001_init.d.ts.map +1 -1
  93. package/dist/migrations/0003_account_issuer_nullable.d.ts +5 -0
  94. package/dist/migrations/0003_account_issuer_nullable.d.ts.map +1 -0
  95. package/dist/migrations/0003_account_issuer_nullable.js +131 -0
  96. package/dist/migrations/0004_user_lifecycle.d.ts +28 -0
  97. package/dist/migrations/0004_user_lifecycle.d.ts.map +1 -0
  98. package/dist/migrations/0004_user_lifecycle.js +47 -0
  99. package/dist/migrations/set.d.ts +3 -1
  100. package/dist/migrations/set.d.ts.map +1 -1
  101. package/dist/migrations/set.js +6 -2
  102. package/dist/peer.d.ts +4 -0
  103. package/dist/peer.d.ts.map +1 -1
  104. package/dist/test-utils/liveApp.d.ts +26 -0
  105. package/dist/test-utils/liveApp.d.ts.map +1 -1
  106. package/dist/test-utils/liveApp.js +1 -0
  107. package/dist/test-utils/schemaDrift.d.ts +49 -0
  108. package/dist/test-utils/schemaDrift.d.ts.map +1 -0
  109. package/dist/test-utils/schemaDrift.js +35 -0
  110. package/dist/test-utils/scopedBackend.d.ts +204 -0
  111. package/dist/test-utils/scopedBackend.d.ts.map +1 -0
  112. package/dist/test-utils/scopedBackend.js +166 -0
  113. package/dist/version.generated.d.ts +1 -1
  114. package/dist/version.generated.d.ts.map +1 -1
  115. package/dist/version.generated.js +1 -1
  116. package/docs/account-lifecycle.md +105 -0
  117. package/docs/apple-signin.md +7 -1
  118. package/docs/facebook-oauth.md +7 -1
  119. package/docs/github-oauth.md +7 -1
  120. package/docs/google-oauth.md +7 -1
  121. package/docs/microsoft-oauth.md +177 -0
  122. package/docs/server-authoritative.md +182 -0
  123. package/package.json +11 -8
  124. package/pithy.manifest.json +17 -3
  125. package/src/audit/actions.ts +23 -0
  126. package/src/audit/emit.ts +1 -1
  127. package/src/caller/certificate.ts +133 -0
  128. package/src/caller/request.ts +84 -0
  129. package/src/caller/token.ts +276 -0
  130. package/src/capability.ts +170 -38
  131. package/src/client/lifecycle.ts +27 -0
  132. package/src/client/projection.ts +4 -0
  133. package/src/data/betterAuth.ts +23 -2
  134. package/src/data/kitFields.ts +27 -0
  135. package/src/data/tables.ts +4 -2
  136. package/src/data/userLifecycle.ts +80 -0
  137. package/src/http/credentialResign.ts +268 -0
  138. package/src/http/errorCallbackUrl.ts +21 -13
  139. package/src/http/guards.ts +29 -1
  140. package/src/http/lifecycleGate.ts +78 -0
  141. package/src/http/middleware.ts +161 -37
  142. package/src/http/providerRefusal.ts +40 -32
  143. package/src/http/resolve.ts +34 -5
  144. package/src/http/routes.ts +39 -2
  145. package/src/instance/auth.ts +91 -6
  146. package/src/instance/jwksReencryption.ts +206 -0
  147. package/src/instance/microsoftEmail.ts +111 -0
  148. package/src/instance/providerSignInGate.ts +30 -27
  149. package/src/instance/providers.ts +8 -4
  150. package/src/instance/secrets.ts +153 -6
  151. package/src/instance/sessionSecrets.ts +64 -0
  152. package/src/lifecycle/enforce.ts +89 -0
  153. package/src/lifecycle/hooks.ts +54 -0
  154. package/src/lifecycle/request.ts +31 -0
  155. package/src/lifecycle/state.ts +101 -0
  156. package/src/lifecycle/transitions.ts +483 -0
  157. package/src/migrations/0001_init.ts +8 -10
  158. package/src/migrations/0003_account_issuer_nullable.ts +199 -0
  159. package/src/migrations/0004_user_lifecycle.ts +68 -0
  160. package/src/migrations/set.ts +5 -1
  161. package/src/test-utils/liveApp.ts +2 -1
  162. package/src/test-utils/schemaDrift.ts +82 -0
  163. package/src/test-utils/scopedBackend.ts +137 -0
  164. package/src/version.generated.ts +1 -1
@@ -14,6 +14,8 @@ import { correlation, emitDenied, emitDeviceRevoked, emitTokenRefresh, emitToken
14
14
  import type { AuthWiring } from "../capability";
15
15
  import { authDatabase } from "../data/tables";
16
16
  import { deleteDevice, deviceSessionTokens, listDevices } from "../device/registry";
17
+ import { noticedRefusal } from "../lifecycle/enforce";
18
+ import { isLifecycleRefusal } from "../lifecycle/state";
17
19
  import { PROFILE_IMAGE_PATH } from "../profile/profile";
18
20
  import {
19
21
  consumeSession,
@@ -25,6 +27,7 @@ import {
25
27
  import { registerAuthAdminRoutes } from "./adminRoutes";
26
28
  import { guardErrorCallbackURL } from "./errorCallbackUrl";
27
29
  import { apiErrorToPithy } from "./errors";
30
+ import { admitsRefusedAccount, lifecycleRedirect } from "./lifecycleGate";
28
31
  import { requireAuth } from "./middleware";
29
32
  import { requireFreshAuthentication } from "./providerFreshness";
30
33
  import { collapseProviderRefusal } from "./providerRefusal";
@@ -279,8 +282,17 @@ async function auditRefusal(c: Ctx, response: Response): Promise<void> {
279
282
  async function handleBetterAuth(c: Ctx, wiring: AuthWiring): Promise<Response> {
280
283
  const instance = await getAuthInstance(c, wiring);
281
284
 
285
+ // **A suspended or deleted account does not reach Better Auth as itself (#620).** The session middleware
286
+ // has already refused it an `AuthContext`, but Better Auth resolves its own session on these endpoints and
287
+ // would happily mint a `/token` for it. So its verdict is applied here too, on every endpoint that acts as
288
+ // the credential's holder — and not on the ones that end a session or start a new one. `./lifecycleGate`
289
+ // says which, and why a stale cookie must not stop somebody else signing in.
290
+ const pathname = new URL(c.req.raw.url).pathname;
291
+ const refusal = noticedRefusal(c);
292
+ if (refusal && !admitsRefusedAccount(pathname.slice(wiring.config.basePath.length))) throw refusal;
293
+
282
294
  // **The first of the two guards on the refusal redirect (#625).** `errorCallbackURL` is the caller's
283
- // string and `redirectOnError` concatenates it without parsing, so the shape handed *in* decides
295
+ // string and `redirectOnError` builds the redirect on it, so the shape handed *in* decides
284
296
  // whether the collapse below is reading a query at all. `./errorCallbackUrl` normalizes it to something
285
297
  // the kit produced, or refuses it — and carries the argument for why guarding the input is not the same
286
298
  // job as reading the output, and why both stay.
@@ -290,7 +302,26 @@ async function handleBetterAuth(c: Ctx, wiring: AuthWiring): Promise<Response> {
290
302
  try {
291
303
  response = await instance.handler(request);
292
304
  } catch (error) {
293
- throw apiErrorToPithy(error);
305
+ const pithy = apiErrorToPithy(error);
306
+ // A sign-in refused because the account is suspended or deleted: the session hook threw it, so it
307
+ // arrives here rather than as a Better Auth response, and is recorded here for the same reason.
308
+ if (isLifecycleRefusal(pithy)) {
309
+ if (isSignInAttempt(pathname)) {
310
+ await emitDenied(c.var.emit, { ...correlation(c.req.raw.headers), detail: pithy.payload.code });
311
+ }
312
+ // A magic link is a browser navigation, so the refusal goes back to the screen the link named rather
313
+ // than stranding the reader on this origin's 403. OTP and every JSON caller get the envelope.
314
+ if (c.req.method === "GET" && pathname === `${wiring.config.basePath}/magic-link/verify`) {
315
+ const redirect = lifecycleRedirect(
316
+ new URL(request.url),
317
+ wiring.config.baseURL,
318
+ wiring.config.trustedOrigins,
319
+ pithy,
320
+ );
321
+ if (redirect) return redirect;
322
+ }
323
+ }
324
+ throw pithy;
294
325
  }
295
326
 
296
327
  // **The enumeration oracle on the social callback, closed here because here is the only place both
@@ -390,6 +421,12 @@ async function rotateToken(c: Ctx, wiring: AuthWiring): Promise<Response> {
390
421
  });
391
422
  }
392
423
 
424
+ // An account that may not act gets no successor (#620). `session.create.before` would refuse the mint below
425
+ // anyway; refusing here, from the middleware's verdict, is what keeps the presented token unspent and the
426
+ // successor never written, so a reinstated account's device still holds a credential that works.
427
+ const refusal = noticedRefusal(c);
428
+ if (refusal) throw refusal;
429
+
393
430
  const ip = headers.get("cf-connecting-ip") ?? undefined;
394
431
  const userAgent = headers.get("user-agent") ?? undefined;
395
432
  const session = current.session as {
@@ -2,6 +2,7 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import type { AuditEmit } from "@pithy-sh/core/src/audit/recorder";
5
+ import type { PithyError } from "@pithy-sh/core/src/error/pithyError";
5
6
  import { type BetterAuthPlugin, betterAuth } from "better-auth";
6
7
  import { APIError, createAuthMiddleware } from "better-auth/api";
7
8
  import { emitAfterRequest, emitProviderAccountChanged, emitProviderUnavailable } from "../audit/emit";
@@ -16,8 +17,10 @@ import { KIT_SESSION_FIELDS, KIT_USER_FIELDS } from "../data/kitFields";
16
17
  import type { AuthDatabase } from "../data/tables";
17
18
  import { parseDeviceMeta, registerDevice } from "../device/registry";
18
19
  import { PROVIDER_CHANGE_FRESH_AGE_SECONDS } from "../http/providerFreshness";
20
+ import { lifecycleRefusalFor } from "../lifecycle/enforce";
19
21
  import { refuseUnsafeProfile, sanitizeProfile } from "../profile/profile";
20
22
  import { defaultGithubUserInfo, type GithubUserInfoResolver } from "./githubUserInfo";
23
+ import { microsoftProfileToUser } from "./microsoftEmail";
21
24
  import { kitPlugins } from "./plugins";
22
25
  import {
23
26
  providerUnavailable,
@@ -25,6 +28,7 @@ import {
25
28
  type SocialProviderId,
26
29
  unavailableProviderFor,
27
30
  } from "./providers";
31
+ import { betterAuthSecrets, type SessionSecretVersions } from "./sessionSecrets";
28
32
 
29
33
  /**
30
34
  * Build the `socialProviders` block from whichever provider credentials were resolved. Exported so the
@@ -104,9 +108,39 @@ export function socialProviders(deps: AuthInstanceDeps): Record<string, unknown>
104
108
  ...signUpOption(deps.providerSignUp.github),
105
109
  };
106
110
  }
111
+ if (deps.microsoft.state === "ready") {
112
+ // Entra ID cannot vouch for an email it did not verify: work and school tokens carry no
113
+ // `email_verified`, and `email` is a directory attribute a tenant admin sets to anything. So
114
+ // Microsoft stays out of `trustedProviders`, and `mapProfileToUser` decides the flag from the two
115
+ // claims Microsoft computes and a tenant cannot write — `./microsoftEmail.ts` has the rule. It is
116
+ // spread over Better Auth's own default, which reads claims a tenant can influence.
117
+ const microsoft = deps.microsoft.credentials;
118
+ providers.microsoft = {
119
+ clientId: microsoft.clientId,
120
+ clientSecret: microsoft.clientSecret,
121
+ tenantId: microsoft.tenantId,
122
+ // The stock resolver fetches a Graph photo and stores it as `data:image/jpeg;base64, …` — a space
123
+ // after the comma, which `../profile/profile.ts` refuses, so the create hook would drop every one.
124
+ // A third-party fetch per sign-in for a value that is always discarded is not worth making.
125
+ disableProfilePhoto: true,
126
+ mapProfileToUser: microsoftProfileToUser,
127
+ ...signUpOption(deps.providerSignUp.microsoft),
128
+ };
129
+ }
107
130
  return Object.keys(providers).length > 0 ? providers : undefined;
108
131
  }
109
132
 
133
+ /**
134
+ * The providers whose email links into an existing account on the strength of their name alone.
135
+ *
136
+ * Google and Apple, and nobody else, permanently. Facebook's verified flag is asserted in its block with
137
+ * a reason; GitHub's comes from its emails API; Microsoft's is decided per sign-in by
138
+ * `./microsoftEmail.ts`, because Entra ID cannot vouch for an email it did not verify. Adding a provider
139
+ * here would skip the verified half of the linking gate for it — `./providerSignInGate.ts` reads the same
140
+ * list off the context.
141
+ */
142
+ export const TRUSTED_PROVIDERS: readonly string[] = ["google", "apple"];
143
+
110
144
  /**
111
145
  * The seeding guard: a new account may be created only for an email a provider has **verified**.
112
146
  *
@@ -136,10 +170,37 @@ function refuseUnsafeProfileFields(user: { name?: unknown; image?: unknown }): v
136
170
  throw new APIError("BAD_REQUEST", { code: "INVALID_PROFILE_FIELD", message: refusal.message });
137
171
  }
138
172
 
139
- /** The endpoint context a database hook is handed, narrowed to the two things attribution needs. */
173
+ /** The endpoint context a database hook is handed, narrowed to what attribution and refusal need. */
140
174
  interface HookContext {
141
175
  headers?: Headers;
142
176
  context?: { session?: { user?: { id?: string } } | null };
177
+ /** The endpoint path this write was reached from, e.g. `/callback/google`. Absent outside an endpoint. */
178
+ path?: string;
179
+ }
180
+
181
+ /**
182
+ * Refuse a session for an account that may not act, in the shape the endpoint creating it can answer.
183
+ *
184
+ * **On the social callback, an `APIError` carrying the kit's code**, because that endpoint answers a refusal
185
+ * by redirecting to the caller's `errorCallbackURL` with `?error=<code>` — but only for an `APIError`
186
+ * (`callback.mjs:192`). A `PithyError` would escape it and leave a browser mid-OAuth on a bare 403 body
187
+ * instead of back on the adopter's screen. The code is the same string either way, and the reason travels as
188
+ * `error_description`, which is where Better Auth puts a refusal's message.
189
+ *
190
+ * **Everywhere else, the `PithyError` itself**, which `handleBetterAuth` renders through the one error
191
+ * envelope — or, on the magic-link verify redirect, turns into the same `?error=` redirect.
192
+ */
193
+ function refuseSession(refusal: PithyError, ctx: HookContext | null | undefined): never {
194
+ if (ctx?.path?.startsWith("/callback/")) {
195
+ // Spelled out per code rather than copied off the payload, so `providerRefusal.test.ts` — which reads
196
+ // every `APIError` code in this package off the source — sees both and holds each to a verdict.
197
+ const message = refusal.payload.message;
198
+ if (refusal.payload.code === "auth/account_deleted") {
199
+ throw new APIError("FORBIDDEN", { code: "auth/account_deleted", message });
200
+ }
201
+ throw new APIError("FORBIDDEN", { code: "auth/account_suspended", message });
202
+ }
203
+ throw refusal;
143
204
  }
144
205
 
145
206
  /**
@@ -206,8 +267,15 @@ export interface AuthInstanceDeps<Plugins extends readonly BetterAuthPlugin[] =
206
267
  extends ResolvedProviders {
207
268
  /** The shared Kysely over the `pithy_auth_*` tables (carries `CamelCasePlugin`). */
208
269
  db: AuthDatabase;
209
- /** The Better-Auth signing/encryption secret, sourced from `@pithy-sh/secrets`. */
270
+ /** The Better-Auth signing/encryption secret, sourced from `@pithy-sh/secrets` — the current version. */
210
271
  secret: string;
272
+ /**
273
+ * Every retained version of the session secret, when the caller resolved them (#602). Given, Better Auth
274
+ * gets the whole version set — newest first — so a value sealed under the previous version still opens
275
+ * through a rotation's overlap; see `./sessionSecrets.ts`. Absent, it gets `secret` alone, which is what an
276
+ * instance built outside a request (a seed, a test) has always had.
277
+ */
278
+ sessionSecrets?: SessionSecretVersions;
211
279
  /** The public base URL of this environment's auth worker (no trailing slash). */
212
280
  baseURL: string;
213
281
  /** The mount path; must equal the Hono route the handler is mounted under. */
@@ -314,13 +382,23 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
314
382
  appName: "Pithy",
315
383
  baseURL: deps.baseURL,
316
384
  basePath: deps.basePath,
317
- secret: deps.secret,
385
+ ...(deps.sessionSecrets === undefined ? { secret: deps.secret } : betterAuthSecrets(deps.sessionSecrets)),
318
386
  telemetry: { enabled: false },
319
387
  trustedOrigins: deps.trustedOrigins,
320
388
  database: { db: deps.db, type: "sqlite", transaction: false },
321
389
  advanced: {
322
- // WebCrypto UUID ids for every model — anti-enumeration, Workers-safe.
323
- database: { generateId: () => crypto.randomUUID() },
390
+ database: {
391
+ // WebCrypto UUID ids for every model — anti-enumeration, Workers-safe.
392
+ generateId: () => crypto.randomUUID(),
393
+ // **Off at runtime, and checked in CI instead (#787).** Better Auth 1.7.3 compares its schema with
394
+ // the database when an instance initializes and refuses requests on a mismatch. Its verdict is
395
+ // cached per instance, and this instance is built per request (`../http/resolve.ts`), so the check
396
+ // would run on every request: eight more D1 statements on top of the five an authenticated request
397
+ // costs, measured by `http/scopes.workers.test.ts`. The kit owns these tables through its own
398
+ // migrations, and `migrations/betterAuthSchemaDrift.workers.test.ts` runs Better Auth's own check
399
+ // against them at the lockfile's version and at the newest the range admits.
400
+ validateSchema: false,
401
+ },
324
402
  },
325
403
  // Better Auth's errors bubble out of `handler` so the Hono boundary maps them to PithyError.
326
404
  //
@@ -439,6 +517,13 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
439
517
  * `deviceId` by override for the same reason.
440
518
  */
441
519
  before: async (session, ctx) => {
520
+ // **No session for an account that may not act (#620).** Every sign-in and every token
521
+ // refresh creates its session here — magic link, OTP, each social callback, `/token/rotate` —
522
+ // so this one check is what makes a suspension hold at every door, and the reason it is not
523
+ // written once per endpoint. The row is read rather than trusted from the caller: nothing
524
+ // that arrives with a sign-in may say whether its own account is suspended.
525
+ const refusal = await lifecycleRefusalFor(deps.db, session.userId, null, new Date());
526
+ if (refusal) refuseSession(refusal, ctx);
442
527
  // **`undefined` and `null` are different answers here, and collapsing them is a hole.**
443
528
  // Absent means nobody supplied one, which is a sign-in: stamp it. Present-and-null is a
444
529
  // rotation of a session written before the column existed, and it must stay null so the gate
@@ -596,7 +681,7 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
596
681
  accountLinking: {
597
682
  enabled: true,
598
683
  // Link a social sign-in to an existing magic-link user when the verified emails match.
599
- trustedProviders: ["google", "apple"],
684
+ trustedProviders: [...TRUSTED_PROVIDERS],
600
685
  /**
601
686
  * **A signed-in user may attach a provider whose email differs from their account's.**
602
687
  *
@@ -0,0 +1,206 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { D1Database } from "@cloudflare/workers-types";
5
+ import { createDatabase } from "@pithy-sh/core/src/data/db";
6
+ import type { Logger } from "@pithy-sh/core/src/logger/logger";
7
+ import { secretsTables } from "@pithy-sh/secrets/src/data/tables";
8
+ import {
9
+ claimReencryption,
10
+ currentSealedVersion,
11
+ recordReencryption,
12
+ recordSoleVersion,
13
+ } from "@pithy-sh/secrets/src/rotation/reencryption";
14
+ import { parseEnvelope, type SecretConfig, symmetricDecrypt, symmetricEncrypt } from "better-auth/crypto";
15
+ import type { AuthDatabase } from "../data/tables";
16
+ import { AUTH_JWKS_DEPENDENT, AUTH_SESSION_SECRET } from "./secrets";
17
+ import { betterAuthSecrets, type SessionSecretVersions } from "./sessionSecrets";
18
+
19
+ /**
20
+ * **The JWKS private keys, moved under the session secret's newest version before the old one retires (#602).**
21
+ *
22
+ * Better Auth seals every key in `pithy_auth_jwks` under the session secret (`plugins/jwt/utils.mjs`), and a
23
+ * key has no expiry that would make it safe to stop being able to open it. An unattended rotation of
24
+ * `auth-session-secret` therefore waits, before it retires the previous version, for this Worker to say the
25
+ * keys have moved — the secret's registry entry names them as `auth-jwks` — and this is where they move.
26
+ *
27
+ * Each key is opened under whichever retained version it names (`$ba$<version>$…`), or — for one sealed
28
+ * before the kit handed Better Auth a version set, which carries no envelope — under each retained version
29
+ * in turn, oldest first. It is sealed again under the current version and written back only if the row
30
+ * still holds what was read, so two isolates moving the same key cannot interleave into a value neither
31
+ * wrote. Then the move is recorded in the secrets D1, where the manager reads it.
32
+ *
33
+ * **It never makes a key unopenable.** A key no retained version opens is left exactly as it is and
34
+ * counted; it was already lost, and nothing here can lose it further. It does not hold the record back,
35
+ * because waiting cannot make it open — and a retirement held forever over a key that will never be used
36
+ * is an envelope that grows on every rotation.
37
+ */
38
+
39
+ /** What one pass did, in counts. */
40
+ export interface JwksReencryption {
41
+ /** Keys sealed again under the current version. */
42
+ moved: number;
43
+ /** Keys already under it. */
44
+ current: number;
45
+ /** Keys no retained version opens. Left as they were. */
46
+ unopenable: number;
47
+ }
48
+
49
+ /** Better Auth's own key structure for a version set, built the way `buildSecretConfig` builds it. */
50
+ function secretConfig(versions: SessionSecretVersions): SecretConfig {
51
+ const { secrets } = betterAuthSecrets(versions);
52
+ return {
53
+ keys: new Map(secrets.map((one) => [one.version, one.value])),
54
+ currentVersion: Number(versions.currentVersion),
55
+ };
56
+ }
57
+
58
+ /** Open one stored private key, or `null` when no retained version opens it. */
59
+ async function opened(stored: string, versions: SessionSecretVersions, config: SecretConfig): Promise<string | null> {
60
+ if (parseEnvelope(stored) !== null) {
61
+ return await symmetricDecrypt({ key: config, data: stored }).catch(() => null);
62
+ }
63
+ // A bare ciphertext, from before the version set: sealed under whichever value was current then.
64
+ const oldestFirst = [...betterAuthSecrets(versions).secrets].sort((left, right) => left.version - right.version);
65
+ for (const candidate of oldestFirst) {
66
+ const plain = await symmetricDecrypt({ key: candidate.value, data: stored }).catch(() => null);
67
+ if (plain !== null) return plain;
68
+ }
69
+ return null;
70
+ }
71
+
72
+ /** Move every JWKS private key under the current version of the session secret. */
73
+ export async function reencryptJwks(db: AuthDatabase, versions: SessionSecretVersions): Promise<JwksReencryption> {
74
+ const config = secretConfig(versions);
75
+ const current = Number(versions.currentVersion);
76
+ const result: JwksReencryption = { moved: 0, current: 0, unopenable: 0 };
77
+ const rows = await db.selectFrom("pithyAuthJwks").select(["id", "privateKey"]).execute();
78
+ for (const row of rows) {
79
+ let stored: unknown;
80
+ try {
81
+ stored = JSON.parse(row.privateKey);
82
+ } catch {
83
+ stored = undefined;
84
+ }
85
+ if (typeof stored !== "string") {
86
+ result.unopenable += 1;
87
+ continue;
88
+ }
89
+ if (parseEnvelope(stored)?.version === current) {
90
+ result.current += 1;
91
+ continue;
92
+ }
93
+ const plain = await opened(stored, versions, config);
94
+ if (plain === null) {
95
+ result.unopenable += 1;
96
+ continue;
97
+ }
98
+ const sealed = JSON.stringify(await symmetricEncrypt({ key: config, data: plain }));
99
+ await db
100
+ .updateTable("pithyAuthJwks")
101
+ .set({ privateKey: sealed })
102
+ .where("id", "=", row.id)
103
+ .where("privateKey", "=", row.privateKey)
104
+ .execute();
105
+ result.moved += 1;
106
+ }
107
+ return result;
108
+ }
109
+
110
+ /**
111
+ * The versions this isolate has finished with — moved, or failed to — keyed by version and fingerprint, so a
112
+ * version key reused after an `update` is a new version here too.
113
+ */
114
+ const settled = new Set<string>();
115
+
116
+ /** The versions this isolate was told to wait on, with when to ask again. */
117
+ const waiting = new Map<string, number>();
118
+
119
+ /** Forget what this isolate has settled or is waiting on. For tests. */
120
+ export function resetJwksReencryption(): void {
121
+ settled.clear();
122
+ waiting.clear();
123
+ }
124
+
125
+ /** What {@link ensureJwksSealedUnderCurrent} needs. */
126
+ export interface EnsureJwksDeps {
127
+ /** The application database the JWKS keys live in. */
128
+ db: AuthDatabase;
129
+ /**
130
+ * That database's binding name — `auth({ database })`. The holder the move is recorded under, so two auth
131
+ * Workers over two databases are waited for one by one rather than one answering for both.
132
+ */
133
+ holder: string;
134
+ /** The secrets D1 the move is recorded in. */
135
+ secrets: D1Database;
136
+ /** The session secret's retained versions, as this request resolved them. */
137
+ versions: SessionSecretVersions;
138
+ /** Where a failure is said. Never fatal. */
139
+ log: Logger;
140
+ /** The clock. Defaults to now. */
141
+ now?: Date;
142
+ }
143
+
144
+ /**
145
+ * Make sure the JWKS keys are sealed under the current version, and that the secrets D1 says so — once per
146
+ * version per isolate.
147
+ *
148
+ * **Recorded with one version too.** While the secret holds one version there is nothing to move, and the
149
+ * record says the keys are under it ({@link recordSoleVersion}). That is how the manager knows this database
150
+ * holds keys before the first rotation: a holder it has never heard from is one it cannot wait for.
151
+ *
152
+ * **Not on the first request that sees the version.** Another isolate may still hold the envelope it cached
153
+ * before the append, with no key for the new version; a key re-sealed under it now would fail there. So the
154
+ * first sight is recorded, and the move waits until every cache filled before it has expired
155
+ * (`claimReencryption`, `REENCRYPTION_SETTLE_MS`). An isolate told to wait does not ask again until then.
156
+ *
157
+ * **Never fatal.** It runs on a request, and the request it rides on is somebody signing in; a failure here
158
+ * leaves the keys where they were — still opening, since the previous version is still held — and the
159
+ * retirement waiting. The next isolate tries again.
160
+ */
161
+ export async function ensureJwksSealedUnderCurrent(deps: EnsureJwksDeps): Promise<void> {
162
+ const { versions } = deps;
163
+ const sole = Object.keys(versions.versions).length < 2;
164
+ const now = deps.now ?? new Date();
165
+ try {
166
+ const sealed = await currentSealedVersion(versions);
167
+ const key = `${deps.holder}:${sole ? "sole" : "rotating"}:${sealed.version}:${sealed.fingerprint}`;
168
+ if (settled.has(key) || (waiting.get(key) ?? 0) > now.getTime()) return;
169
+ try {
170
+ const secretsDb = createDatabase(deps.secrets, secretsTables);
171
+ const where = { name: AUTH_SESSION_SECRET, dependent: AUTH_JWKS_DEPENDENT, holder: deps.holder };
172
+ if (sole) {
173
+ settled.add(key);
174
+ await recordSoleVersion(secretsDb, { ...where, sealed, now });
175
+ return;
176
+ }
177
+ const claim = await claimReencryption(secretsDb, { ...where, sealed, now });
178
+ if (claim.state === "moved") {
179
+ settled.add(key);
180
+ return;
181
+ }
182
+ if (claim.state === "settling") {
183
+ waiting.set(key, claim.until.getTime());
184
+ return;
185
+ }
186
+ settled.add(key);
187
+ const moved = await reencryptJwks(deps.db, versions);
188
+ await recordReencryption(secretsDb, { ...where, ...sealed, now });
189
+ deps.log.info("jwks re-encrypted under the current session secret", { version: sealed.version, ...moved });
190
+ if (moved.unopenable > 0) {
191
+ deps.log.warn("jwks keys no retained session secret opens were left as they were", {
192
+ unopenable: moved.unopenable,
193
+ });
194
+ }
195
+ } catch (error) {
196
+ // Settled for this isolate, so a failing database is not asked again on every request it serves.
197
+ // Another isolate tries; until one finishes, retirement waits and the previous version keeps opening.
198
+ settled.add(key);
199
+ throw error;
200
+ }
201
+ } catch (error) {
202
+ deps.log.warn("jwks re-encryption did not finish; the previous session secret stays until it does", {
203
+ reason: error instanceof Error ? error.message : String(error),
204
+ });
205
+ }
206
+ }
@@ -0,0 +1,111 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { getOAuthState } from "better-auth/api";
5
+
6
+ /**
7
+ * Whether a Microsoft sign-in's email is the signer's own — the one decision the Microsoft provider adds (#262).
8
+ *
9
+ * ## Why Microsoft needs a rule of its own
10
+ *
11
+ * Every other provider the kit serves can say which address it verified. Entra ID cannot. A work or
12
+ * school ID token carries no `email_verified` claim, and its `email` is read from the directory's `mail`
13
+ * attribute — which a tenant admin sets to any string, a stranger's address at a domain they do not own
14
+ * included. Sign in, and the token asserts you are somebody else. That is the nOAuth takeover class, and
15
+ * it is a property of Entra ID, not of an app's configuration. Microsoft's own claims reference says of
16
+ * `email`: "This value isn't guaranteed to be correct, and is mutable over time - never use it for
17
+ * authorization." So Microsoft stays out of `trustedProviders` permanently, and this decides the flag.
18
+ *
19
+ * ## The three ways an address is verified, and nothing else
20
+ *
21
+ * - **`xms_edov === true`** — "email domain owner verified", the optional claim Microsoft published as
22
+ * the nOAuth remediation. The tenant provably owns the address's domain, so it cannot be a stranger's.
23
+ * Off unless the app registration asks for it; `docs/microsoft-oauth.md` walks that step.
24
+ * - **`tid` is the personal-accounts tenant.** A personal Microsoft account is in no directory, has no
25
+ * admin, and its address is the account itself, confirmed by Microsoft at sign-up. It never carries
26
+ * `xms_edov`, so it needs its own clause.
27
+ * - **Linking from inside the account, to the account's own address.** The verify-to-link challenge's
28
+ * second half. Somebody refused above signs in by magic link — which proves the address — and connects
29
+ * Microsoft from inside. That Microsoft identity naming the very address the session holds is verified
30
+ * by the kit, not by Microsoft. A different address is not, and Better Auth's link branch refuses it.
31
+ *
32
+ * Anything else — the claim absent, `false`, `"true"`, `1` — is unverified. **Absence is never read as
33
+ * verification**, and only the boolean `true` is. `email_verified` and `verified_primary_email` are read
34
+ * by Better Auth's own default and deliberately not here: Entra does not issue the first for work
35
+ * accounts, and the second is sourced from directory attributes this rule does not get to vouch for.
36
+ *
37
+ * `oid` and `tid` are immutable, so once an identity is linked it signs in on `oid` forever
38
+ * (`./providerSignInGate.ts`, row 1) and none of this runs again for it.
39
+ */
40
+
41
+ /**
42
+ * The tenant id every personal Microsoft account signs in under.
43
+ *
44
+ * Source: https://learn.microsoft.com/en-us/entra/identity-platform/id-token-claims-reference — the `tid`
45
+ * row: "For sign-ins to the personal Microsoft account tenant (services like Xbox, Teams for Life, or
46
+ * Outlook), the value is `9188040d-6c67-4c5b-b112-36a304b66dad`." The `iss` row names the same GUID.
47
+ * Compared exactly: Microsoft issues it lowercase, and a token that spells it otherwise is not one of its.
48
+ */
49
+ export const MICROSOFT_PERSONAL_ACCOUNTS_TENANT_ID = "9188040d-6c67-4c5b-b112-36a304b66dad";
50
+
51
+ /** The part of a link-in-progress this rule reads: the signed-in account's own address. */
52
+ export interface LinkInProgress {
53
+ /** The address on the account the session belongs to, as Better Auth's `/link-social` stored it. */
54
+ readonly email: unknown;
55
+ }
56
+
57
+ /**
58
+ * Decide the flag from the decoded ID token and, on a link, the account it is being linked to.
59
+ *
60
+ * Pure, so every hostile shape can be driven without a request. `profile` is the whole decoded ID token —
61
+ * Better Auth hands `mapProfileToUser` the `decodeJwt` result itself (`@better-auth/core`
62
+ * `social-providers/microsoft-entra-id.mjs`), so `xms_edov` and `tid` are in reach as claims, not as
63
+ * fields somebody copied.
64
+ */
65
+ export function microsoftEmailVerified(
66
+ profile: Readonly<Record<string, unknown>>,
67
+ link: LinkInProgress | null,
68
+ ): boolean {
69
+ if (profile.xms_edov === true) return true;
70
+ if (profile.tid === MICROSOFT_PERSONAL_ACCOUNTS_TENANT_ID) return true;
71
+ if (link === null) return false;
72
+ const { email } = profile;
73
+ if (typeof email !== "string" || email.length === 0) return false;
74
+ if (typeof link.email !== "string" || link.email.length === 0) return false;
75
+ return email.toLowerCase() === link.email.toLowerCase();
76
+ }
77
+
78
+ /**
79
+ * The link this callback completes, or `null` when it is a sign-in.
80
+ *
81
+ * `link` is written by Better Auth's `/link-social` alone: `generateState` spreads the caller's
82
+ * `additionalData` first and assigns `link` last, so a sign-in overwrites any injected one
83
+ * (`./providerSignInGate.ts` records it, and plants against it).
84
+ *
85
+ * **`getOAuthState()` throws where no request state was established**, and here the throw is caught on
86
+ * purpose, unlike the gate's. The gate's safe direction is a loud failure; this one's is *unverified*,
87
+ * and that is exactly what a missing link means.
88
+ */
89
+ async function linkInProgress(): Promise<LinkInProgress | null> {
90
+ try {
91
+ const state = await getOAuthState();
92
+ const link: unknown = state?.link;
93
+ if (typeof link !== "object" || link === null || !("email" in link)) return null;
94
+ return { email: link.email };
95
+ } catch {
96
+ return null;
97
+ }
98
+ }
99
+
100
+ /**
101
+ * The Microsoft block's `mapProfileToUser`: the rule, applied to this callback.
102
+ *
103
+ * **It always states the flag.** Better Auth computes its own default first and spreads this over it, so
104
+ * a mapper that omitted the key on the unverified path would leave that default — read off claims a
105
+ * tenant can influence — standing.
106
+ */
107
+ export async function microsoftProfileToUser(
108
+ profile: Readonly<Record<string, unknown>>,
109
+ ): Promise<{ emailVerified: boolean }> {
110
+ return { emailVerified: microsoftEmailVerified(profile, await linkInProgress()) };
111
+ }