@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
@@ -25,9 +25,10 @@ import { NEUTRAL_PROVIDER_REFUSAL } from "../http/providerRefusal";
25
25
  * The mitigating fact is that it requires a provider-signed, audience-bound assertion of the address,
26
26
  * so it is not an address an attacker picks — which is why the claim above says *the redirect
27
27
  * callback* and not *provider sign-in*.
28
- * - **A plugin that calls `handleOAuthUserInfo` without going through `provider.getUserInfo`.**
29
- * `plugins/one-tap/index.mjs:45-70` builds the user info straight from a verified Google id token;
30
- * `plugins/oauth-proxy/index.mjs:110` lifts it out of an encrypted proxy payload. The kit composes
28
+ * - **A plugin that calls `handleOAuthUserInfo` outside the redirect callback.** `plugins/one-tap/index.mjs:64`
29
+ * resolves a verified Google id token through Google's own `getUserInfo` with no OAuth state, which
30
+ * this gate passes through, or builds the user info itself when Google is not configured;
31
+ * `plugins/oauth-proxy/index.mjs:127` lifts it out of an encrypted proxy payload. The kit composes
31
32
  * neither. `./refusalTransport` is where a composed plugin is ruled on.
32
33
  * - **An adopter plugin that replaces `ctx.socialProviders` in its own `init`.** Kit plugins run first
33
34
  * by contract (`./auth.ts` composes them ahead of the adopter's), so the wrap is installed before
@@ -47,8 +48,8 @@ import { NEUTRAL_PROVIDER_REFUSAL } from "../http/providerRefusal";
47
48
  * | 4 | Not attached, no account at that address | Refused |
48
49
  *
49
50
  * Rows 3 and 4 differ only in whether a row exists at an address **the caller chose**, and Better Auth
50
- * answers them with two different codes — `account_not_linked` (`oauth2/link-account.mjs:86`, returned
51
- * only inside `if (dbUser)`) and `signup_disabled` (`:202`, the `else` of that same branch). Both reach
51
+ * answers them with two different codes — `account_not_linked` (`oauth2/link-account.mjs:142`, returned
52
+ * only inside `if (dbUser)`) and `signup_disabled` (`:257`, the `else` of that same branch). Both reach
52
53
  * the browser as `?error=<code>`. That is an account-enumeration oracle needing one provider account,
53
54
  * none on the target, and no page render.
54
55
  *
@@ -58,20 +59,21 @@ import { NEUTRAL_PROVIDER_REFUSAL } from "../http/providerRefusal";
58
59
  * another, and the last keyed on a value `callbackURL` supplies, so it rewrote *successful* sign-ins.
59
60
  * By the time a response exists the fact that distinguished the two cases is gone and what is left is
60
61
  * partly the caller's. `getUserInfo` is the last seam that holds the fact itself: `callback.mjs:120`
61
- * calls it, `:220` calls `handleOAuthUserInfo`, and **nothing runs in between** — so a refusal thrown
62
+ * calls it, `:172` calls `handleOAuthUserInfo`, and **nothing between them reads a user row** — so a refusal thrown
62
63
  * here means neither of those two lines is ever reached and there is no pair left to collapse.
63
64
  *
64
65
  * ## Why a wrapper, and not a `getUserInfo` supplied in the config block
65
66
  *
66
67
  * `options.getUserInfo` short-circuits each provider's own resolver on its first line
67
- * (`social-providers/google.mjs:118`, `facebook.mjs:93`, `apple.mjs:62`, `github.mjs:65`), so supplying
68
- * one means reimplementing the profile fetch it replaced — Google's id-token decode, Facebook's
69
- * access-token-owner check. `./githubUserInfo.ts` already records what that costs: replacing GitHub's
70
- * resolver silently dropped `name` and `image`, which had to be re-derived. Wrapping calls the
71
- * dependency's own resolver and reads its result, so nothing is reimplemented and nothing reconstructed.
68
+ * (`social-providers/google.mjs:118`, `facebook.mjs:93`, `apple.mjs:62`, `github.mjs:65`,
69
+ * `microsoft-entra-id.mjs:99`), so supplying one means reimplementing the profile fetch it replaced —
70
+ * Google's id-token decode, Facebook's access-token-owner check. `./githubUserInfo.ts` already records
71
+ * what that costs: replacing GitHub's resolver silently dropped `name` and `image`, which had to be
72
+ * re-derived. Wrapping calls the dependency's own resolver and reads its result, so nothing is
73
+ * reimplemented and nothing reconstructed.
72
74
  *
73
75
  * **And it is the wrapping that makes the predicate read the right flag.** `mapProfileToUser` is applied
74
- * *inside* each provider's own `getUserInfo` — every one of the four spreads `...userMap` over the
76
+ * *inside* each provider's own `getUserInfo` — every one of the five spreads `...userMap` over the
75
77
  * `emailVerified` it computed — so the value this module reads is by construction the **effective** flag.
76
78
  * Facebook is the trap that makes this load-bearing: it sits outside `trustedProviders` like GitHub, but
77
79
  * `./auth.ts` asserts its address as verified with a documented reason, and its OAuth response carries no
@@ -134,8 +136,8 @@ type UserInfoResult = Awaited<ReturnType<OAuthProvider["getUserInfo"]>>;
134
136
  * than asserted:** `providerSignInGate.workers.test.ts` drives a refusal the dependency still emits
135
137
  * (`email_not_found`) beside one this gate emits and requires the two `Location` headers to differ in
136
138
  * nothing but the code. `ctx.redirect(url)` is itself only `new APIError("FOUND", undefined, headers)`
137
- * with `location` set (`better-call/dist/context.mjs:60`), and better-auth's router passes a `FOUND`
138
- * straight through its `onError` to `toResponse` (`api/index.mjs:192`), so this is the same object the
139
+ * with `location` set (`better-call/dist/context.mjs:62`), and better-auth's router passes a `FOUND`
140
+ * straight through its `onError` to `toResponse` (`api/index.mjs:196`), so this is the same object the
139
141
  * dependency would have thrown — built without the endpoint context `getUserInfo` is not handed.
140
142
  *
141
143
  * The value being appended to is the OAuth state's own `errorURL`, which is where `redirectOnError`
@@ -165,12 +167,13 @@ function refusalWithoutRedirect(): APIError {
165
167
  /**
166
168
  * Is this provider identity already attached to some account here? Row 1.
167
169
  *
168
- * **Keyed on `(providerId, accountId)`, which is wider than Better Auth's `(issuer, accountId)`, and
169
- * wider is the safe direction.** Deriving the issuer means copying `createOAuthAccountIssuer` —
170
- * `local:oauth:${encodeAccountIssuerProviderId(id)}` — from a package the kit does not depend on, and a
171
- * second copy of a dependency's decision is the defect class this repo has been bitten by four times
172
- * (#106, #108, #109, #113). A false match here passes the attempt through and lets Better Auth decide,
173
- * which is today's behavior; a false *miss* is what would be dangerous, and widening cannot cause one.
170
+ * **Keyed on `(providerId, accountId)`, which is Better Auth's own account key.** 1.7.0–1.7.2 keyed an
171
+ * account on `(issuer, accountId)` instead, and this gate read the wider pair rather than copy how Better
172
+ * Auth derived an issuer. 1.7.3 reverted to the 1.6 model (better-auth/better-auth#11153), and the lookup
173
+ * the callback makes is now `findAccountOwnerByKey({ providerId, accountId })` (`link-account.mjs:80`), so
174
+ * the two ask the same question of the same columns (#787). A false match here would pass the attempt
175
+ * through and let Better Auth decide, which is the safe direction; a false *miss* is what would be
176
+ * dangerous, and an identical key cannot cause one.
174
177
  *
175
178
  * It reads no address and no verified flag, which is what keeps an `allowDifferentEmails` link signing in.
176
179
  *
@@ -214,13 +217,13 @@ async function gateProviderSignIn(args: {
214
217
  }): Promise<void> {
215
218
  const { ctx, provider, token, result, deps } = args;
216
219
 
217
- // No OAuth state: `/link-social` and `/account-info` with an id token (`api/routes/account.mjs:174`,
218
- // `:609`), which never generate one, and `/sign-in/social`'s own id-token branch, which returns before
220
+ // No OAuth state: `/link-social` and `/account-info` with an id token (`api/routes/account.mjs:172`,
221
+ // `:604`), which never generate one, and `/sign-in/social`'s own id-token branch, which returns before
219
222
  // `generateState`. The first two must be untouched — linking from inside the account is a different
220
223
  // flow with both sides already proven — and the third is the uncovered path named in the reach section.
221
224
  //
222
225
  // **`getOAuthState()` throws where no request state was established**, which is every caller reaching
223
- // a provider object by hand rather than through an endpoint (`to-auth-endpoints.mjs:50` wraps them
226
+ // a provider object by hand rather than through an endpoint (`to-auth-endpoints.mjs:52` wraps them
224
227
  // all, `auth.api.*` included). Deliberately not caught: a missing store cannot be a callback today,
225
228
  // and swallowing it would turn a dependency that stopped establishing one into a silent pass-through
226
229
  // instead of a loud failure. There is no such caller in this kit.
@@ -234,7 +237,7 @@ async function gateProviderSignIn(args: {
234
237
  // Verified, load-bearing, and planted against — the gate keys on this field.
235
238
  if (state.link !== undefined && state.link !== null) return;
236
239
 
237
- // No address at all. Better Auth answers `email_not_found` from `callback.mjs:205`, which is the same
240
+ // No address at all. Better Auth answers `email_not_found` from `callback.mjs:168`, which is the same
238
241
  // string on both sides of the fork, so there is nothing here to collapse and nothing to decide. The
239
242
  // kit's own GitHub resolver fails closed to exactly this shape (`./githubUserInfo.ts`).
240
243
  const email = result.user.email;
@@ -245,7 +248,7 @@ async function gateProviderSignIn(args: {
245
248
 
246
249
  const local = await ctx.internalAdapter.findUserByEmail(email);
247
250
 
248
- // Row 2, as the two halves of `link-account.mjs:83` — read from the dependency's own resolved values
251
+ // Row 2, as the two halves of `link-account.mjs:139` — read from the dependency's own resolved values
249
252
  // rather than restated. `emailVerified` here is the **effective** flag: this is the return of the
250
253
  // provider's own `getUserInfo`, so `mapProfileToUser` has already run and Facebook's forced `true` is
251
254
  // already in it.
@@ -268,10 +271,10 @@ async function gateProviderSignIn(args: {
268
271
  // every first provider sign-up into a refusal. Three ways the refusal is certain:
269
272
  //
270
273
  // - **A local row exists.** Better Auth never creates a user when one matched, and row 2 has just
271
- // failed, so `link-account.mjs:86` is where that attempt ends.
274
+ // failed, so `link-account.mjs:142` is where that attempt ends.
272
275
  // - **Sign-up is disabled for this provider** — `provider.options.disableSignUp`, which is the kit's
273
276
  // own `signUpOption()` output (`./auth.ts`) read back off the object rather than restated.
274
- // `callback.mjs:229` also ORs in `disableImplicitSignUp && !requestSignUp`; ignoring that half is
277
+ // `callback.mjs:181` also ORs in `disableImplicitSignUp && !requestSignUp`; ignoring that half is
275
278
  // deliberate, since the kit never sets it and ignoring it can only cause a pass-through.
276
279
  // - **The address is not verified**, which the kit's own `user.create.before` hook refuses anyway.
277
280
  const certain = local !== null || provider.options?.disableSignUp === true || result.user.emailVerified !== true;
@@ -9,6 +9,7 @@ import type {
9
9
  FacebookOAuthCredentials,
10
10
  GithubOAuthCredentials,
11
11
  GoogleOAuthCredentials,
12
+ MicrosoftOAuthCredentials,
12
13
  } from "./secrets";
13
14
 
14
15
  /**
@@ -56,7 +57,7 @@ export type ResolvedProvider<Credentials> =
56
57
  export const PROVIDER_DISABLED: { readonly state: "disabled" } = { state: "disabled" };
57
58
 
58
59
  /** The social providers the kit composes. Ordered as they are declared in config. */
59
- export const SOCIAL_PROVIDER_IDS = ["google", "apple", "facebook", "github"] as const;
60
+ export const SOCIAL_PROVIDER_IDS = ["google", "apple", "facebook", "github", "microsoft"] as const;
60
61
 
61
62
  /** One of the kit's social providers. */
62
63
  export type SocialProviderId = (typeof SOCIAL_PROVIDER_IDS)[number];
@@ -64,9 +65,9 @@ export type SocialProviderId = (typeof SOCIAL_PROVIDER_IDS)[number];
64
65
  /**
65
66
  * Every provider's state for one instance.
66
67
  *
67
- * A record rather than four loose fields, because two things read it — the `socialProviders` block the
68
+ * A record rather than five loose fields, because two things read it — the `socialProviders` block the
68
69
  * instance is built from, and the refusal that answers a caller who asked for one that is not there —
69
- * and they must be reading the same four values or they will disagree about what is available.
70
+ * and they must be reading the same five values or they will disagree about what is available.
70
71
  */
71
72
  export interface ResolvedProviders {
72
73
  /** Google OAuth: disabled, ready with its credential pair, or declared and unreadable. */
@@ -77,17 +78,20 @@ export interface ResolvedProviders {
77
78
  facebook: ResolvedProvider<FacebookOAuthCredentials>;
78
79
  /** GitHub OAuth: disabled, ready with its credential pair, or declared and unreadable. */
79
80
  github: ResolvedProvider<GithubOAuthCredentials>;
81
+ /** Microsoft Entra ID: disabled, ready with its credential set and tenant, or declared and unreadable. */
82
+ microsoft: ResolvedProvider<MicrosoftOAuthCredentials>;
80
83
  }
81
84
 
82
85
  /**
83
86
  * Every provider disabled — what a composition that enables no social sign-in resolves to, and the
84
- * base a construction site spreads over rather than spelling four times.
87
+ * base a construction site spreads over rather than spelling five times.
85
88
  */
86
89
  export const NO_SOCIAL_PROVIDERS: Readonly<ResolvedProviders> = {
87
90
  google: PROVIDER_DISABLED,
88
91
  apple: PROVIDER_DISABLED,
89
92
  facebook: PROVIDER_DISABLED,
90
93
  github: PROVIDER_DISABLED,
94
+ microsoft: PROVIDER_DISABLED,
91
95
  };
92
96
 
93
97
  /**
@@ -1,10 +1,12 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
+ import { ValidationError } from "@pithy-sh/core/src/error/pithyError";
4
5
  import type { SecretsStoreEnv } from "@pithy-sh/secrets/src/env/bindings";
5
6
  import { defineSecretRegistry } from "@pithy-sh/secrets/src/registry";
6
7
  import { sharedSecretsStore } from "@pithy-sh/secrets/src/sharedSecretsStore";
7
8
  import { z } from "zod";
9
+ import type { SessionSecretVersions } from "./sessionSecrets";
8
10
 
9
11
  /**
10
12
  * The secrets `@pithy-sh/auth` reads, declared as a minimal registry. The secret name is the join key:
@@ -24,12 +26,51 @@ import { z } from "zod";
24
26
  * Read only when the provider is enabled; rotated in the Meta app dashboard, not on our schedule.
25
27
  * - `auth-github-credentials` — the GitHub OAuth app client id and secret, as a typed JSON value.
26
28
  * Read only when the provider is enabled; rotated in GitHub Developer settings, not on our schedule.
29
+ * - `auth-microsoft-credentials` — the Microsoft Entra ID app registration's client id, client secret,
30
+ * and tenant, as a typed JSON value. The tenant rides inside because it means nothing apart from the
31
+ * registration it belongs to. Rotatable: an Entra client secret expires (24 months at most).
27
32
  */
28
33
  export const AUTH_SESSION_SECRET = "auth-session-secret";
29
34
  export const AUTH_GOOGLE_CREDENTIALS = "auth-google-credentials";
30
35
  export const AUTH_APPLE_CREDENTIALS = "auth-apple-credentials";
31
36
  export const AUTH_FACEBOOK_CREDENTIALS = "auth-facebook-credentials";
32
37
  export const AUTH_GITHUB_CREDENTIALS = "auth-github-credentials";
38
+ export const AUTH_MICROSOFT_CREDENTIALS = "auth-microsoft-credentials";
39
+
40
+ /**
41
+ * The JWKS private keys, as `auth-session-secret`'s overlap names them (#602).
42
+ *
43
+ * Better Auth encrypts every key in `pithy_auth_jwks` under the session secret, and a key never expires —
44
+ * so retiring the version one is sealed under would leave a signing key nothing can open. The session
45
+ * secret's registry entry names this dependent, `instance/jwksReencryption.ts` moves the keys under the
46
+ * newest version and records it, and the secrets manager retires nothing until it has.
47
+ */
48
+ export const AUTH_JWKS_DEPENDENT = "auth-jwks";
49
+
50
+ /**
51
+ * The Better Auth plugins that seal rows of their own under the session secret, by id.
52
+ *
53
+ * `two-factor` seals every TOTP secret with `symmetricEncrypt({ key: ctx.context.secretConfig })`, and its
54
+ * backup codes the same way under `storeBackupCodes: "encrypted"` (`plugins/two-factor/index.mjs`,
55
+ * `backup-codes/index.mjs`). Neither expires. Nothing in the kit re-encrypts them, so an unattended rotation
56
+ * beside one is refused at `auth()` rather than allowed to retire the version they are sealed under.
57
+ */
58
+ export const SESSION_SECRET_SEALING_PLUGINS: readonly string[] = ["two-factor"];
59
+
60
+ /** Seconds in a day. */
61
+ const DAY_SECONDS = 86_400;
62
+
63
+ /**
64
+ * How many days a replaced session secret keeps verifying: the session's own lifetime, rounded up.
65
+ *
66
+ * **That is the whole of the overlap's argument.** A session in use is re-signed on its next request
67
+ * (`http/credentialResign.ts`), and its expiry slides forward on use — so a session that goes the whole
68
+ * overlap without one request has expired by the time the overlap ends. Any shorter, and a session used
69
+ * yesterday is signed out when the old version retires.
70
+ */
71
+ export function sessionSecretOverlapDays(sessionExpiresIn: number): number {
72
+ return Math.max(1, Math.ceil(sessionExpiresIn / DAY_SECONDS));
73
+ }
33
74
 
34
75
  /** The Google OAuth credential pair, stored as one typed JSON secret. */
35
76
  export const GoogleOAuthCredentials = z
@@ -108,18 +149,52 @@ export const GithubOAuthCredentials = z
108
149
  .describe("A GitHub OAuth credential pair (`clientId` + `clientSecret`) for one environment.");
109
150
  export type GithubOAuthCredentials = z.infer<typeof GithubOAuthCredentials>;
110
151
 
152
+ /**
153
+ * The Microsoft Entra ID credentials, stored as one typed JSON secret.
154
+ *
155
+ * **`tenantId` is required and may not be empty.** Better Auth builds its endpoints from
156
+ * `options.tenantId || "common"`, so an empty string would not fail: it would quietly open a
157
+ * single-tenant app to every Entra tenant and every personal account.
158
+ */
159
+ export const MicrosoftOAuthCredentials = z
160
+ .object({
161
+ clientId: z
162
+ .string()
163
+ .meta({ multiline: false })
164
+ .describe(
165
+ "The Application (client) ID of the Entra ID app registration for this environment. Not secret on its own, but stored with the secret so the set is atomic.",
166
+ ),
167
+ clientSecret: z
168
+ .string()
169
+ .meta({ multiline: false })
170
+ .describe(
171
+ "A client secret value from the same app registration. Expires (24 months at most), so rotate it on schedule. Never committed, never an env literal.",
172
+ ),
173
+ tenantId: z
174
+ .string()
175
+ .min(1)
176
+ .meta({ multiline: false })
177
+ .describe(
178
+ "Who may sign in: a directory (tenant) ID for one organization, `organizations` for any work or school account, `consumers` for personal accounts only, or `common` for both.",
179
+ ),
180
+ })
181
+ .describe("A Microsoft Entra ID credential set (`clientId` + `clientSecret` + `tenantId`) for one environment.");
182
+ export type MicrosoftOAuthCredentials = z.infer<typeof MicrosoftOAuthCredentials>;
183
+
111
184
  /**
112
185
  * Where a human goes for each OAuth credential pair, and where the same human rotates it.
113
186
  *
114
187
  * **The settings page, not the product homepage.** The point is to end a search, not to start one — and
115
- * these four are the case with no command and no possible one, so the link is the entire remedy the kit
116
- * can offer. Named constants because origin and rotation are the same page for all four, and two copies
188
+ * these five are the case with no command and no possible one, so the link is the entire remedy the kit
189
+ * can offer. Named constants because origin and rotation are the same page for all five, and two copies
117
190
  * of a URL is one that goes stale.
118
191
  */
119
192
  const GOOGLE_CREDENTIALS_PAGE = "https://console.cloud.google.com/apis/credentials";
120
193
  const APPLE_KEYS_PAGE = "https://developer.apple.com/account/resources/authkeys/list";
121
194
  const FACEBOOK_APPS_PAGE = "https://developers.facebook.com/apps/";
122
195
  const GITHUB_OAUTH_APPS_PAGE = "https://github.com/settings/developers";
196
+ const MICROSOFT_APP_REGISTRATIONS_PAGE =
197
+ "https://entra.microsoft.com/#view/Microsoft_AAD_RegisteredApps/ApplicationsListBlade";
123
198
 
124
199
  export const authSecretsRegistry = defineSecretRegistry({
125
200
  // `devValue` is the whole difference between an app that runs after `pithy add auth` and one that
@@ -135,8 +210,11 @@ export const authSecretsRegistry = defineSecretRegistry({
135
210
  // a session signature, so the kit both makes it and replaces it.
136
211
  origin: { kind: "minted", recipe: { kind: "random", bytes: 32, encoding: "base64url" } },
137
212
  rotation: { kind: "local" },
213
+ // The default session lifetime's overlap, and the JWKS keys sealed under it (#602). `auth()` declares
214
+ // its own from the configured `sessionExpiresIn`; this is what a module reading the secret sees.
215
+ overlap: { days: 7, minimumDays: 7, reencrypt: [AUTH_JWKS_DEPENDENT] },
138
216
  },
139
- // The four below are `obtained` and rotate `manual`, and each names the page rather than the product.
217
+ // The five below are `obtained` and rotate `manual`, and each names the page rather than the product.
140
218
  // An adopter searching Google's console for which of four credential types "client secret" means is the
141
219
  // gap this closes — and nothing will ever mint one, so saying where is the whole of what the kit can do.
142
220
  [AUTH_GOOGLE_CREDENTIALS]: {
@@ -175,8 +253,60 @@ export const authSecretsRegistry = defineSecretRegistry({
175
253
  origin: { kind: "obtained", issuer: "github", documentation: GITHUB_OAUTH_APPS_PAGE },
176
254
  rotation: { kind: "manual", issuer: "github", documentation: GITHUB_OAUTH_APPS_PAGE },
177
255
  },
256
+ [AUTH_MICROSOFT_CREDENTIALS]: {
257
+ backend: "d1",
258
+ scope: "environment",
259
+ rotatable: true,
260
+ valueType: "json",
261
+ schema: MicrosoftOAuthCredentials,
262
+ origin: { kind: "obtained", issuer: "microsoft", documentation: MICROSOFT_APP_REGISTRATIONS_PAGE },
263
+ rotation: { kind: "manual", issuer: "microsoft", documentation: MICROSOFT_APP_REGISTRATIONS_PAGE },
264
+ },
178
265
  });
179
266
 
267
+ /**
268
+ * **The registry `auth()` contributes, from its own configuration (#602).**
269
+ *
270
+ * The session secret's overlap follows the configured session lifetime — {@link sessionSecretOverlapDays} —
271
+ * and it is both the overlap and its floor: an adopter who lengthens sessions lengthens the overlap with
272
+ * them, rather than holding a seven-day overlap against a thirty-day session. `rotateEveryDays` is
273
+ * `sessionSecretRotateEveryDays`, and only an adopter sets it: the kit turns no unattended rotation on.
274
+ *
275
+ * Checked by `defineSecretRegistry` like every registry, so a period no longer than the session lifetime is
276
+ * refused here, at `auth()`, naming the secret — rather than at a 03:00 cron that could only skip it.
277
+ *
278
+ * **A period is refused beside a plugin that seals rows under the session secret** —
279
+ * {@link SESSION_SECRET_SEALING_PLUGINS}. Only the JWKS keys are moved before a retirement; a plugin's own
280
+ * sealed rows would be left under the retired version, and nothing could open them again.
281
+ */
282
+ export function authSecretsRegistryFor(config: {
283
+ sessionExpiresIn: number;
284
+ sessionSecretRotateEveryDays?: number;
285
+ plugins?: readonly { id: string }[];
286
+ }) {
287
+ if (config.sessionSecretRotateEveryDays !== undefined) {
288
+ const sealing = (config.plugins ?? []).find((plugin) => SESSION_SECRET_SEALING_PLUGINS.includes(plugin.id));
289
+ if (sealing !== undefined) {
290
+ throw new ValidationError({
291
+ message: `${AUTH_SESSION_SECRET} cannot rotate unattended while the Better Auth "${sealing.id}" plugin is composed.`,
292
+ action: `Remove sessionSecretRotateEveryDays from auth({ ... }), or remove ${sealing.id}() from auth({ plugins: [...] }). ${sealing.id}() seals its secrets under ${AUTH_SESSION_SECRET}, and a rotation retires the version they are sealed under with nothing to move them first.`,
293
+ detail: `sessionSecretRotateEveryDays set with plugin "${sealing.id}", which seals rows under ${AUTH_SESSION_SECRET}`,
294
+ });
295
+ }
296
+ }
297
+ const days = sessionSecretOverlapDays(config.sessionExpiresIn);
298
+ return defineSecretRegistry({
299
+ ...authSecretsRegistry,
300
+ [AUTH_SESSION_SECRET]: {
301
+ ...authSecretsRegistry[AUTH_SESSION_SECRET],
302
+ overlap: { days, minimumDays: days, reencrypt: [AUTH_JWKS_DEPENDENT] },
303
+ ...(config.sessionSecretRotateEveryDays === undefined
304
+ ? {}
305
+ : { rotateEveryDays: config.sessionSecretRotateEveryDays }),
306
+ },
307
+ });
308
+ }
309
+
180
310
  /**
181
311
  * Which provider a credential belongs to — the join the CLI must never make by spelling (#541).
182
312
  *
@@ -189,15 +319,16 @@ const PROVIDER_CREDENTIALS = [
189
319
  ["apple", AUTH_APPLE_CREDENTIALS],
190
320
  ["facebook", AUTH_FACEBOOK_CREDENTIALS],
191
321
  ["github", AUTH_GITHUB_CREDENTIALS],
322
+ ["microsoft", AUTH_MICROSOFT_CREDENTIALS],
192
323
  ] as const;
193
324
 
194
- /** The four toggles this reads off the resolved `AuthConfig` — nothing else about it is its business. */
325
+ /** The five toggles this reads off the resolved `AuthConfig` — nothing else about it is its business. */
195
326
  export type AuthProviderToggles = Record<(typeof PROVIDER_CREDENTIALS)[number][0], { enabled: boolean }>;
196
327
 
197
328
  /**
198
329
  * **The provider credentials this composition cannot reach**, as the `inapplicableSecrets` contribution.
199
330
  *
200
- * Auth declares four credentials whether or not a project runs four providers, so a project on Google
331
+ * Auth declares five credentials whether or not a project runs five providers, so a project on Google
201
332
  * and GitHub carries two secrets nothing will ever read. `pithy doctor` asked for them every run under
202
333
  * *"fine to leave until you need it"* — softening, not silence, and "until you need it" is wrong about a
203
334
  * provider the configuration has not enabled.
@@ -217,12 +348,22 @@ export function inapplicableProviderSecrets(providers: AuthProviderToggles): Rec
217
348
  return declared;
218
349
  }
219
350
 
220
- /** Resolve the Better Auth session secret for this invocation. */
351
+ /** Resolve the Better Auth session secret for this invocation — the current version alone. */
221
352
  export async function resolveSessionSecret(env: SecretsStoreEnv): Promise<string> {
222
353
  const secrets = await sharedSecretsStore(env, authSecretsRegistry);
223
354
  return secrets.get(AUTH_SESSION_SECRET);
224
355
  }
225
356
 
357
+ /**
358
+ * Resolve every retained version of the session secret (#602) — what an instance needs to open values sealed
359
+ * under the previous version, and what a credential signed under it is verified against. One read through
360
+ * the same cached accessor as {@link resolveSessionSecret}.
361
+ */
362
+ export async function resolveSessionSecrets(env: SecretsStoreEnv): Promise<SessionSecretVersions> {
363
+ const secrets = await sharedSecretsStore(env, authSecretsRegistry);
364
+ return secrets.getVersions(AUTH_SESSION_SECRET);
365
+ }
366
+
226
367
  /** Resolve the Google OAuth credential pair for this invocation (only call when Google is enabled). */
227
368
  export async function resolveGoogleCredentials(env: SecretsStoreEnv): Promise<GoogleOAuthCredentials> {
228
369
  const secrets = await sharedSecretsStore(env, authSecretsRegistry);
@@ -246,3 +387,9 @@ export async function resolveGithubCredentials(env: SecretsStoreEnv): Promise<Gi
246
387
  const secrets = await sharedSecretsStore(env, authSecretsRegistry);
247
388
  return secrets.get(AUTH_GITHUB_CREDENTIALS);
248
389
  }
390
+
391
+ /** Resolve the Microsoft Entra ID credentials for this invocation (only call when Microsoft is enabled). */
392
+ export async function resolveMicrosoftCredentials(env: SecretsStoreEnv): Promise<MicrosoftOAuthCredentials> {
393
+ const secrets = await sharedSecretsStore(env, authSecretsRegistry);
394
+ return secrets.get(AUTH_MICROSOFT_CREDENTIALS);
395
+ }
@@ -0,0 +1,64 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ /**
5
+ * **The session secret as Better Auth needs it across a rotation (#602): every retained version.**
6
+ *
7
+ * `auth-session-secret` is `rotatable: true`, and an unattended rotation appends a version and keeps the
8
+ * previous one for the overlap. The kit used to hand Better Auth one value — the current one — which made
9
+ * the overlap decorative: the moment the version changed, the JWKS private keys were sealed under a value
10
+ * the instance no longer held. Better Auth 1.7 takes a version set instead (`secrets: [{ version, value }]`,
11
+ * newest first): it encrypts under the first and decrypts under whichever version a ciphertext names
12
+ * (`$ba$<version>$…`, `better-auth/dist/crypto/index.mjs`).
13
+ *
14
+ * **It versions encryption and not signatures.** With `secrets` set, `ctx.secret` is the first entry alone
15
+ * (`context/create-context.mjs:75`), and the session cookie is signed and verified under `ctx.secret`
16
+ * (`cookies/index.mjs:172`). So a cookie signed under the previous version still fails after a rotation;
17
+ * `http/credentialResign.ts` is what verifies it under a retained version and re-signs it.
18
+ *
19
+ * **`secret` is the oldest retained version, and that is deliberate.** With a version set, Better Auth reads
20
+ * `secret` only as the *legacy* secret — the one it tries on a bare ciphertext with no `$ba$` envelope. Every
21
+ * JWKS key written before the kit passed a version set is one of those, sealed under the value that was
22
+ * current then, which is the oldest the envelope still holds. Re-encryption moves them into the envelope;
23
+ * until it has, this is what opens them.
24
+ */
25
+
26
+ /** A secret's retained versions, as `secretsStore(…).getVersions` answers. */
27
+ export interface SessionSecretVersions {
28
+ /** The version key reads resolve to. */
29
+ currentVersion: string;
30
+ /** Every retained version: version key → value. */
31
+ versions: Readonly<Record<string, string>>;
32
+ }
33
+
34
+ /** What `betterAuth()` is handed: the version set, newest first, and the legacy secret. */
35
+ export interface BetterAuthSecretOptions {
36
+ /** Every retained version, current first, then the rest newest first. */
37
+ secrets: { version: number; value: string }[];
38
+ /** The oldest retained version — Better Auth's legacy secret, for a ciphertext sealed before versions existed. */
39
+ secret: string;
40
+ }
41
+
42
+ /** The retained versions, current first and the rest in descending numeric order. */
43
+ function ordered(versions: SessionSecretVersions): { version: number; value: string }[] {
44
+ const prior = Object.entries(versions.versions)
45
+ .filter(([version]) => version !== versions.currentVersion)
46
+ .map(([version, value]) => ({ version: Number(version), value }))
47
+ .sort((left, right) => right.version - left.version);
48
+ const current = versions.versions[versions.currentVersion];
49
+ return current === undefined ? prior : [{ version: Number(versions.currentVersion), value: current }, ...prior];
50
+ }
51
+
52
+ /** The version set and legacy secret for `betterAuth()`. */
53
+ export function betterAuthSecrets(versions: SessionSecretVersions): BetterAuthSecretOptions {
54
+ const secrets = ordered(versions);
55
+ const oldest = [...secrets].sort((left, right) => left.version - right.version)[0];
56
+ return { secrets, secret: oldest?.value ?? "" };
57
+ }
58
+
59
+ /** Every retained value but the current one, newest first — what a credential signed before a rotation is tried under. */
60
+ export function priorSessionSecrets(versions: SessionSecretVersions): string[] {
61
+ return ordered(versions)
62
+ .filter((one) => String(one.version) !== versions.currentVersion)
63
+ .map((one) => one.value);
64
+ }
@@ -0,0 +1,89 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { PithyError } from "@pithy-sh/core/src/error/pithyError";
5
+ import type { AuthDatabase } from "../data/tables";
6
+ import { accountStanding, LifecycleColumns, lifecycleRefusal } from "./state";
7
+
8
+ /**
9
+ * The reads enforcement needs, and the one place a refusal is remembered for the rest of a request.
10
+ *
11
+ * ## Where an account is refused
12
+ *
13
+ * - **Every request** — the session middleware reads the state off the user Better Auth resolved for the
14
+ * session, which carries the columns, so the check costs no query. A refused account gets no
15
+ * `AuthContext`, so every `requireAuth()` in the kit refuses it whoever wrote the guard; this capability's
16
+ * own `requireAuth()` raises the refusal itself, with its code, rather than a 401.
17
+ * - **Every sign-in and every token refresh** — `session.create.before` in `../instance/auth.ts`. Every way
18
+ * a session comes into being goes through `createSession`, so one hook covers magic link, OTP, every
19
+ * social callback and `/token/rotate` alike.
20
+ * - **Better Auth's own endpoints that act as the session's holder** — `/token`, `/get-session`,
21
+ * `/update-user` and the rest — refused in `handleBetterAuth` from the middleware's verdict, because
22
+ * Better Auth resolves its own session there and never asks this capability.
23
+ *
24
+ * The reason for a suspension is the one read only a refused request pays for: it lives in
25
+ * `pithy_auth_user_lifecycle`, not on the user row, so an account in good standing never costs a lookup.
26
+ */
27
+
28
+ /** The reason given for the suspension in force — the newest `suspended` row — or null when none was written. */
29
+ export async function suspensionReason(db: AuthDatabase, userId: string): Promise<string | null> {
30
+ const row = await db
31
+ .selectFrom("pithyAuthUserLifecycle")
32
+ .select("reason")
33
+ .where("userId", "=", userId)
34
+ .where("action", "=", "suspended")
35
+ .orderBy("id", "desc")
36
+ .limit(1)
37
+ .executeTakeFirst();
38
+ const reason = row?.reason?.trim();
39
+ return reason ? reason : null;
40
+ }
41
+
42
+ /** An account's lifecycle columns, read from its row, or `null` when there is no such account. */
43
+ export async function readLifecycleColumns(db: AuthDatabase, userId: string): Promise<LifecycleColumns | null> {
44
+ const row = await db
45
+ .selectFrom("pithyAuthUsers")
46
+ .select(["suspendedAt", "suspendedUntil", "deletedAt", "purgeAfter"])
47
+ .where("id", "=", userId)
48
+ .executeTakeFirst();
49
+ return row ? LifecycleColumns.parse(row) : null;
50
+ }
51
+
52
+ /**
53
+ * The refusal for this account at `now`, or `null` when it may act.
54
+ *
55
+ * `columns` is what the caller already holds — the session's user object, a row it read. Absent, the row is
56
+ * read here, which is the sign-in path: a session about to be created has no user object yet.
57
+ */
58
+ export async function lifecycleRefusalFor(
59
+ db: AuthDatabase,
60
+ userId: string,
61
+ columns: Partial<LifecycleColumns> | null | undefined,
62
+ now: Date,
63
+ ): Promise<PithyError | null> {
64
+ const held = columns ?? (await readLifecycleColumns(db, userId)) ?? {};
65
+ const standing = accountStanding(held, now);
66
+ if (standing.state === "active") return null;
67
+ const reason = standing.state === "suspended" ? await suspensionReason(db, userId) : null;
68
+ return lifecycleRefusal(userId, standing, reason);
69
+ }
70
+
71
+ /**
72
+ * The refusal the session middleware reached for this request, keyed by the request's context.
73
+ *
74
+ * A WeakMap rather than a request variable because `PithyVars` is core's, and this is a fact only this
75
+ * capability's own guards read — a refused account already has no `AuthContext`, which is the part every
76
+ * other capability's guard needs. Keyed by the context the way `../http/resolve.ts` caches the instance, so
77
+ * it dies with the request.
78
+ */
79
+ const refusals = new WeakMap<object, PithyError>();
80
+
81
+ /** Remember that this request's credential belongs to an account that may not act. */
82
+ export function noteRefusal(context: object, refusal: PithyError): void {
83
+ refusals.set(context, refusal);
84
+ }
85
+
86
+ /** The refusal the session middleware reached for this request, if it reached one. */
87
+ export function noticedRefusal(context: object): PithyError | undefined {
88
+ return refusals.get(context);
89
+ }
@@ -0,0 +1,54 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { D1Database } from "@cloudflare/workers-types";
5
+ import type { UserLifecycleActorType } from "../data/userLifecycle";
6
+
7
+ /**
8
+ * The four seams an adopter's own code follows the account lifecycle through, without polling (#620).
9
+ *
10
+ * **On the transition, not on a route.** An account is suspended from the management surface today and may be
11
+ * from somewhere else tomorrow; a listener hung off one route would miss the others, which is the argument
12
+ * `onSessionRevoked` already makes for the session row. `./transitions.ts` is the only place a transition is
13
+ * written, so it is the only place these fire — once per transition that actually happened, never for a
14
+ * request that found the account already in the state it asked for.
15
+ *
16
+ * **Non-fatal by contract.** By the time a hook runs the transition is written and recorded. A hook that throws
17
+ * is logged and swallowed, so it can neither undo the transition nor turn it into an error the caller retries
18
+ * — a retry would find the account already moved and fire nothing, and the adopter's side effect would be
19
+ * lost either way.
20
+ */
21
+
22
+ /** What happened, handed to every hook. */
23
+ export interface UserLifecycleHookEvent {
24
+ /** The account it happened to. */
25
+ readonly userId: string;
26
+ /** Who made the transition: the kind, and the principal's id where there is one. */
27
+ readonly actor: { readonly type: UserLifecycleActorType; readonly id: string | null };
28
+ /** The reason given, or null when the transition needed none. */
29
+ readonly reason: string | null;
30
+ /** When the transition was written. */
31
+ readonly at: Date;
32
+ /** For a suspension, when it ends by itself; null for one that lasts until a reinstatement. */
33
+ readonly suspendedUntil?: Date | null;
34
+ /** For a deletion, when the account's data may be erased. */
35
+ readonly purgeAfter?: Date | null;
36
+ }
37
+
38
+ /**
39
+ * One hook. Handed the request's D1 binding, for the reason `SessionRevokedListener` is: the listener almost
40
+ * certainly writes to the same database under a different capability's view of it.
41
+ */
42
+ export type UserLifecycleListener = (event: UserLifecycleHookEvent, d1: D1Database) => void | Promise<void>;
43
+
44
+ /** The four hooks, each optional. Passed to `auth()` beside the config. */
45
+ export interface UserLifecycleHooks {
46
+ /** An account was suspended. */
47
+ readonly onUserSuspended?: UserLifecycleListener;
48
+ /** A suspended account was reinstated. */
49
+ readonly onUserReinstated?: UserLifecycleListener;
50
+ /** An account was deleted — by an operator or by its owner — and its purge window began. */
51
+ readonly onUserDeleted?: UserLifecycleListener;
52
+ /** A deleted account's data was erased. The last thing that happens to it. */
53
+ readonly onUserPurged?: UserLifecycleListener;
54
+ }