@pithy-sh/auth 0.9.0 → 0.11.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 (188) hide show
  1. package/README.md +8 -2
  2. package/dist/admin/users.js +1 -1
  3. package/dist/audit/actions.d.ts +40 -0
  4. package/dist/audit/actions.d.ts.map +1 -1
  5. package/dist/audit/actions.js +41 -1
  6. package/dist/audit/emit.d.ts +2 -0
  7. package/dist/audit/emit.d.ts.map +1 -1
  8. package/dist/audit/emit.js +2 -2
  9. package/dist/capability.d.ts +45 -1
  10. package/dist/capability.d.ts.map +1 -1
  11. package/dist/capability.js +40 -5
  12. package/dist/client/lifecycle.d.ts +19 -0
  13. package/dist/client/lifecycle.d.ts.map +1 -0
  14. package/dist/client/lifecycle.js +25 -0
  15. package/dist/client/projection.d.ts +4 -0
  16. package/dist/client/projection.d.ts.map +1 -1
  17. package/dist/data/betterAuth.d.ts +4 -0
  18. package/dist/data/betterAuth.d.ts.map +1 -1
  19. package/dist/data/betterAuth.js +6 -2
  20. package/dist/data/kitFields.d.ts +20 -25
  21. package/dist/data/kitFields.d.ts.map +1 -1
  22. package/dist/data/kitFields.js +28 -32
  23. package/dist/data/tables.d.ts +29 -2
  24. package/dist/data/tables.d.ts.map +1 -1
  25. package/dist/data/tables.js +5 -3
  26. package/dist/data/userLifecycle.d.ts +62 -0
  27. package/dist/data/userLifecycle.d.ts.map +1 -0
  28. package/dist/data/userLifecycle.js +51 -0
  29. package/dist/http/adminRoutes.d.ts.map +1 -1
  30. package/dist/http/adminRoutes.js +270 -5
  31. package/dist/http/guards.d.ts +24 -1
  32. package/dist/http/guards.d.ts.map +1 -1
  33. package/dist/http/guards.js +59 -3
  34. package/dist/http/lifecycleGate.d.ts +18 -0
  35. package/dist/http/lifecycleGate.d.ts.map +1 -0
  36. package/dist/http/lifecycleGate.js +75 -0
  37. package/dist/http/middleware.d.ts +30 -1
  38. package/dist/http/middleware.d.ts.map +1 -1
  39. package/dist/http/middleware.js +89 -7
  40. package/dist/http/providerRefusal.d.ts.map +1 -1
  41. package/dist/http/providerRefusal.js +8 -0
  42. package/dist/http/resolve.d.ts.map +1 -1
  43. package/dist/http/resolve.js +7 -4
  44. package/dist/http/responses.d.ts +180 -0
  45. package/dist/http/responses.d.ts.map +1 -1
  46. package/dist/http/responses.js +142 -1
  47. package/dist/http/routes.d.ts +1 -0
  48. package/dist/http/routes.d.ts.map +1 -1
  49. package/dist/http/routes.js +65 -4
  50. package/dist/http/schemas.d.ts +57 -0
  51. package/dist/http/schemas.d.ts.map +1 -1
  52. package/dist/http/schemas.js +51 -1
  53. package/dist/http/views.d.ts +39 -2
  54. package/dist/http/views.d.ts.map +1 -1
  55. package/dist/http/views.js +105 -1
  56. package/dist/instance/auth.d.ts +55 -3
  57. package/dist/instance/auth.d.ts.map +1 -1
  58. package/dist/instance/auth.js +53 -2
  59. package/dist/instance/microsoftEmail.d.ts +70 -0
  60. package/dist/instance/microsoftEmail.d.ts.map +1 -0
  61. package/dist/instance/microsoftEmail.js +96 -0
  62. package/dist/instance/providerSignInGate.d.ts +7 -6
  63. package/dist/instance/providerSignInGate.d.ts.map +1 -1
  64. package/dist/instance/providerSignInGate.js +7 -6
  65. package/dist/instance/providers.d.ts +7 -5
  66. package/dist/instance/providers.d.ts.map +1 -1
  67. package/dist/instance/providers.js +5 -3
  68. package/dist/instance/secrets.d.ts +64 -3
  69. package/dist/instance/secrets.d.ts.map +1 -1
  70. package/dist/instance/secrets.js +44 -5
  71. package/dist/lifecycle/audited.d.ts +48 -0
  72. package/dist/lifecycle/audited.d.ts.map +1 -0
  73. package/dist/lifecycle/audited.js +65 -0
  74. package/dist/lifecycle/enforce.d.ts +75 -0
  75. package/dist/lifecycle/enforce.d.ts.map +1 -0
  76. package/dist/lifecycle/enforce.js +111 -0
  77. package/dist/lifecycle/hooks.d.ts +53 -0
  78. package/dist/lifecycle/hooks.d.ts.map +1 -0
  79. package/dist/lifecycle/hooks.js +2 -0
  80. package/dist/lifecycle/reason.d.ts +11 -0
  81. package/dist/lifecycle/reason.d.ts.map +1 -0
  82. package/dist/lifecycle/reason.js +13 -0
  83. package/dist/lifecycle/request.d.ts +18 -0
  84. package/dist/lifecycle/request.d.ts.map +1 -0
  85. package/dist/lifecycle/request.js +31 -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 +272 -0
  90. package/dist/lifecycle/transitions.d.ts.map +1 -0
  91. package/dist/lifecycle/transitions.js +623 -0
  92. package/dist/migrations/0004_user_lifecycle.d.ts +28 -0
  93. package/dist/migrations/0004_user_lifecycle.d.ts.map +1 -0
  94. package/dist/migrations/0004_user_lifecycle.js +47 -0
  95. package/dist/migrations/0005_purge_once.d.ts +22 -0
  96. package/dist/migrations/0005_purge_once.d.ts.map +1 -0
  97. package/dist/migrations/0005_purge_once.js +35 -0
  98. package/dist/migrations/pluginTables.d.ts +8 -0
  99. package/dist/migrations/pluginTables.d.ts.map +1 -1
  100. package/dist/migrations/pluginTables.js +8 -1
  101. package/dist/migrations/set.d.ts +3 -1
  102. package/dist/migrations/set.d.ts.map +1 -1
  103. package/dist/migrations/set.js +6 -2
  104. package/dist/peer.d.ts +4 -0
  105. package/dist/peer.d.ts.map +1 -1
  106. package/dist/purge/contribution.d.ts +47 -0
  107. package/dist/purge/contribution.d.ts.map +1 -0
  108. package/dist/purge/contribution.js +141 -0
  109. package/dist/purge/retryPolicy.d.ts +22 -0
  110. package/dist/purge/retryPolicy.d.ts.map +1 -0
  111. package/dist/purge/retryPolicy.js +26 -0
  112. package/dist/purge/run.d.ts +88 -0
  113. package/dist/purge/run.d.ts.map +1 -0
  114. package/dist/purge/run.js +102 -0
  115. package/dist/purge/specs.d.ts +71 -0
  116. package/dist/purge/specs.d.ts.map +1 -0
  117. package/dist/purge/specs.js +72 -0
  118. package/dist/purge/start.d.ts +42 -0
  119. package/dist/purge/start.d.ts.map +1 -0
  120. package/dist/purge/start.js +37 -0
  121. package/dist/purge/workflow.d.ts +58 -0
  122. package/dist/purge/workflow.d.ts.map +1 -0
  123. package/dist/purge/workflow.js +96 -0
  124. package/dist/test-utils/accountFootprint.d.ts +10 -0
  125. package/dist/test-utils/accountFootprint.d.ts.map +1 -0
  126. package/dist/test-utils/accountFootprint.js +44 -0
  127. package/dist/test-utils/liveApp.d.ts +21 -0
  128. package/dist/test-utils/liveApp.d.ts.map +1 -1
  129. package/dist/test-utils/liveApp.js +1 -0
  130. package/dist/test-utils/scopedBackend.d.ts +21 -0
  131. package/dist/test-utils/scopedBackend.d.ts.map +1 -1
  132. package/dist/test-utils/scopedBackend.js +7 -1
  133. package/dist/version.generated.d.ts +1 -1
  134. package/dist/version.generated.d.ts.map +1 -1
  135. package/dist/version.generated.js +1 -1
  136. package/docs/account-lifecycle.md +217 -0
  137. package/docs/apple-signin.md +7 -1
  138. package/docs/facebook-oauth.md +7 -1
  139. package/docs/github-oauth.md +7 -1
  140. package/docs/google-oauth.md +7 -1
  141. package/docs/microsoft-oauth.md +177 -0
  142. package/package.json +5 -5
  143. package/pithy.manifest.json +17 -3
  144. package/src/audit/actions.ts +42 -0
  145. package/src/audit/emit.ts +4 -2
  146. package/src/capability.ts +170 -52
  147. package/src/client/lifecycle.ts +27 -0
  148. package/src/client/projection.ts +4 -0
  149. package/src/data/betterAuth.ts +21 -1
  150. package/src/data/kitFields.ts +27 -0
  151. package/src/data/tables.ts +4 -2
  152. package/src/data/userLifecycle.ts +83 -0
  153. package/src/http/adminRoutes.ts +398 -2
  154. package/src/http/guards.ts +61 -1
  155. package/src/http/lifecycleGate.ts +78 -0
  156. package/src/http/middleware.ts +104 -2
  157. package/src/http/providerRefusal.ts +10 -0
  158. package/src/http/resolve.ts +8 -3
  159. package/src/http/responses.ts +245 -0
  160. package/src/http/routes.ts +93 -4
  161. package/src/http/schemas.ts +110 -0
  162. package/src/http/views.ts +147 -2
  163. package/src/instance/auth.ts +74 -2
  164. package/src/instance/microsoftEmail.ts +111 -0
  165. package/src/instance/providerSignInGate.ts +7 -6
  166. package/src/instance/providers.ts +8 -4
  167. package/src/instance/secrets.ts +59 -5
  168. package/src/lifecycle/audited.ts +104 -0
  169. package/src/lifecycle/enforce.ts +139 -0
  170. package/src/lifecycle/hooks.ts +54 -0
  171. package/src/lifecycle/reason.ts +11 -0
  172. package/src/lifecycle/request.ts +39 -0
  173. package/src/lifecycle/state.ts +101 -0
  174. package/src/lifecycle/transitions.ts +872 -0
  175. package/src/migrations/0004_user_lifecycle.ts +68 -0
  176. package/src/migrations/0005_purge_once.ts +42 -0
  177. package/src/migrations/pluginTables.ts +19 -1
  178. package/src/migrations/set.ts +5 -1
  179. package/src/purge/contribution.ts +191 -0
  180. package/src/purge/retryPolicy.ts +26 -0
  181. package/src/purge/run.ts +185 -0
  182. package/src/purge/specs.ts +95 -0
  183. package/src/purge/start.ts +79 -0
  184. package/src/purge/workflow.ts +144 -0
  185. package/src/test-utils/accountFootprint.ts +95 -0
  186. package/src/test-utils/liveApp.ts +2 -1
  187. package/src/test-utils/scopedBackend.ts +2 -1
  188. package/src/version.generated.ts +1 -1
@@ -1,9 +1,11 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
+ import { JsonDate } from "@pithy-sh/core/src/data/codecs";
4
5
  import { MAX_PAGE_SIZE } from "@pithy-sh/core/src/data/cursor";
5
6
  import { z } from "zod";
6
7
  import { DevicePlatform } from "../data/device";
8
+ import { MAX_REASON } from "../lifecycle/reason";
7
9
 
8
10
  /**
9
11
  * The request schemas for the auth routes Pithy owns. Validation happens at the HTTP boundary
@@ -116,3 +118,111 @@ export const RevokeSessionBody = z
116
118
  })
117
119
  .describe("The body identifying which single session to revoke.");
118
120
  export type RevokeSessionBody = z.output<typeof RevokeSessionBody>;
121
+
122
+ /**
123
+ * Why an account's access is changing — required on both lifecycle routes (#621).
124
+ *
125
+ * Trimmed, then bounded by the same constant the transition enforces, so a reason the transition would refuse
126
+ * is a 400 here rather than a conflict later. Required rather than defaulted: a suspension nobody explained is
127
+ * a lockout the person cannot answer, and the trail would record nothing about why.
128
+ */
129
+ const LifecycleReason = z
130
+ .string()
131
+ .trim()
132
+ .min(1)
133
+ .max(MAX_REASON)
134
+ .describe(
135
+ "Why, in a sentence written for the person. A suspension's reason is what every refused sign-in shows them.",
136
+ );
137
+
138
+ /** Whether the person is mailed. */
139
+ const Notify = z
140
+ .boolean()
141
+ .optional()
142
+ .describe(
143
+ "Whether to mail the person. Absent is true. The config can turn a lifecycle mail off for every call; this turns it off for one.",
144
+ );
145
+
146
+ /** The body of `POST /admin/users/:userId/suspend`. */
147
+ export const SuspendUserBody = z
148
+ .object({
149
+ reason: LifecycleReason,
150
+ until: JsonDate.optional().describe(
151
+ "When the suspension ends by itself, as an ISO-8601 timestamp. Must be in the future. Absent lasts until a reinstatement. Nothing is written when it passes.",
152
+ ),
153
+ notify: Notify,
154
+ })
155
+ .describe(
156
+ "A suspension: why, until when, and whether to tell the person. Suspending a suspended account restates the reason and the end.",
157
+ );
158
+ export type SuspendUserBody = z.output<typeof SuspendUserBody>;
159
+
160
+ /** The body of `POST /admin/users/:userId/reinstate`. */
161
+ export const ReinstateUserBody = z
162
+ .object({ reason: LifecycleReason, notify: Notify })
163
+ .describe("A reinstatement: why, and whether to tell the person. It restores no session.");
164
+ export type ReinstateUserBody = z.output<typeof ReinstateUserBody>;
165
+
166
+ /**
167
+ * How a deletion runs (#622). `soft` is the default and the only thing an omission reaches: the account is shut
168
+ * now and erased once the window closes, restorable until then. `hard` starts the purge at once, with no
169
+ * window, and is reached only by naming it — a typo is a 400, never either mode.
170
+ */
171
+ export const DeletionMode = z
172
+ .enum(["soft", "hard"])
173
+ .describe(
174
+ "`soft` (the default): the account is shut now and its data erased once `retention.purgeAfterDays` have passed; it can be restored until then. `hard`: the purge starts now, with no window and nothing to restore.",
175
+ );
176
+ export type DeletionMode = z.output<typeof DeletionMode>;
177
+
178
+ /** The body of `DELETE /admin/users/:userId`. */
179
+ export const DeleteUserBody = z
180
+ .object({
181
+ mode: DeletionMode.default("soft").describe(
182
+ "`soft` unless named: the window, then the purge. `hard` purges now. Anything else is refused.",
183
+ ),
184
+ reason: LifecycleReason,
185
+ notify: z
186
+ .boolean()
187
+ .optional()
188
+ .describe(
189
+ "Whether to mail the person. Absent is true. It silences the mail this call sends: the deletion-scheduled notice for `soft`, the deletion-complete notice for `hard`.",
190
+ ),
191
+ })
192
+ .describe("A deletion: soft or hard, why, and whether to tell the person.");
193
+ export type DeleteUserBody = z.output<typeof DeleteUserBody>;
194
+
195
+ /** The body of `POST /admin/users/:userId/restore`. */
196
+ export const RestoreUserBody = z
197
+ .object({ reason: LifecycleReason })
198
+ .describe("A restoration inside the purge window: why. It restores no session; the person signs in again.");
199
+ export type RestoreUserBody = z.output<typeof RestoreUserBody>;
200
+
201
+ /**
202
+ * The query of `GET /admin/users/:userId/export`. A disclosure of everything the kit holds about one person
203
+ * says why, like every lifecycle call: the reason goes on the trail beside who asked.
204
+ */
205
+ export const ExportUserQuery = z
206
+ .object({
207
+ reason: LifecycleReason.describe(
208
+ "Why this person's data is being exported — the access request it answers. Recorded on the audit trail.",
209
+ ),
210
+ })
211
+ .describe("An export: why it is being made.");
212
+ export type ExportUserQuery = z.output<typeof ExportUserQuery>;
213
+
214
+ /**
215
+ * The body of `DELETE /account`, the signed-in person deleting their own account (#622).
216
+ *
217
+ * The confirmation is the literal `true`, so a client must say it on purpose: a stray `DELETE` with an empty
218
+ * body, or a form posting `"false"`, deletes nothing. There is no field naming an account — the subject is the
219
+ * session's own, always — and a key that tries is dropped.
220
+ */
221
+ export const DeleteAccountBody = z
222
+ .object({
223
+ confirm: z
224
+ .literal(true)
225
+ .describe("Must be `true`. The person confirmed, in your app, that they want their account deleted."),
226
+ })
227
+ .describe("A self-service deletion: the person's own confirmation. Always soft, on the configured window.");
228
+ export type DeleteAccountBody = z.output<typeof DeleteAccountBody>;
package/src/http/views.ts CHANGED
@@ -1,9 +1,29 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
- import type { Session, User } from "../data/betterAuth";
4
+ import type { PurgeExportEntry } from "@pithy-sh/core/src/capability/purge";
5
+ import type { Account, Session, User } from "../data/betterAuth";
5
6
  import type { Device } from "../data/device";
6
- import type { AdminDeviceView, AdminSessionView, AdminUserView } from "./responses";
7
+ import type { UserLifecycleEvent } from "../data/userLifecycle";
8
+ import type {
9
+ DeleteTransition,
10
+ DeletionMode,
11
+ LifecycleTransition,
12
+ RestoreTransition,
13
+ SuspendTransition,
14
+ } from "../lifecycle/transitions";
15
+ import type {
16
+ AccountDeleteResponse,
17
+ AdminDeviceView,
18
+ AdminSessionView,
19
+ AdminUserDeleteResponse,
20
+ AdminUserExportResponse,
21
+ AdminUserReinstateResponse,
22
+ AdminUserRestoreResponse,
23
+ AdminUserSuspendResponse,
24
+ AdminUserView,
25
+ AuthUserExport,
26
+ } from "./responses";
7
27
 
8
28
  /**
9
29
  * The admin projections — what a management client is shown of a user, a session, and a device.
@@ -91,3 +111,128 @@ export function deviceView(device: Device): AdminDeviceView {
91
111
  createdAt: device.createdAt.toISOString(),
92
112
  };
93
113
  }
114
+
115
+ /**
116
+ * The suspension projection (#621): the suspension the transition left in force, and the sessions the route
117
+ * revoked after it. Dates cross as ISO-8601, like every other response here.
118
+ */
119
+ export function suspensionView(
120
+ userId: string,
121
+ result: SuspendTransition,
122
+ sessionsRevoked: number,
123
+ ): AdminUserSuspendResponse {
124
+ return {
125
+ userId,
126
+ state: "suspended",
127
+ outcome: result.updated ? "updated" : "suspended",
128
+ suspendedAt: result.suspendedAt.toISOString(),
129
+ suspendedUntil: result.suspendedUntil?.toISOString() ?? null,
130
+ sessionsRevoked,
131
+ mailed: result.mailed,
132
+ };
133
+ }
134
+
135
+ /** The reinstatement projection (#621). A call that found no suspension in force is `unchanged`. */
136
+ export function reinstatementView(userId: string, result: LifecycleTransition): AdminUserReinstateResponse {
137
+ return {
138
+ userId,
139
+ state: "active",
140
+ outcome: result.changed ? "reinstated" : "unchanged",
141
+ mailed: result.mailed,
142
+ };
143
+ }
144
+
145
+ /** What became of a deletion's purge: due later, started by the call, or due with nothing bound to start it. */
146
+ export type PurgeDisposition = AdminUserDeleteResponse["purge"];
147
+
148
+ /**
149
+ * The deletion projection (#622): the deletion the transition left in force, the sessions the route revoked
150
+ * after it, and what became of the purge.
151
+ */
152
+ export function deletionView(
153
+ userId: string,
154
+ mode: DeletionMode,
155
+ result: DeleteTransition,
156
+ purge: PurgeDisposition,
157
+ sessionsRevoked: number,
158
+ ): AdminUserDeleteResponse {
159
+ return {
160
+ userId,
161
+ state: "deleted",
162
+ mode,
163
+ outcome: result.outcome,
164
+ deletedAt: result.deletedAt.toISOString(),
165
+ purgeAfter: result.purgeAfter.toISOString(),
166
+ purge,
167
+ sessionsRevoked,
168
+ mailed: result.mailed,
169
+ };
170
+ }
171
+
172
+ /** The restoration projection (#622). A call that found the account not deleted is `unchanged`. */
173
+ export function restorationView(userId: string, result: RestoreTransition): AdminUserRestoreResponse {
174
+ return { userId, state: result.state, outcome: result.changed ? "restored" : "unchanged" };
175
+ }
176
+
177
+ /** The self-service deletion projection (#622). */
178
+ export function accountDeletionView(result: DeleteTransition): AccountDeleteResponse {
179
+ return { state: "deleted", purgeAfter: result.purgeAfter.toISOString(), mailed: result.mailed };
180
+ }
181
+
182
+ /** A date as the wire carries it, or null. */
183
+ function iso(date: Date | null | undefined): string | null {
184
+ return date ? date.toISOString() : null;
185
+ }
186
+
187
+ /**
188
+ * What auth holds about one account, as its export carries it (#622) — the person's own data, projected through
189
+ * the same views a support pane sees, so a session token, a provider token and a push token are absent here by
190
+ * the same construction that keeps them out of every other response. The operator who made a transition is
191
+ * theirs to disclose, not the person's, so the history carries the kind of actor and not its id.
192
+ */
193
+ export function authUserExportView(input: {
194
+ user: User;
195
+ sessions: readonly Session[];
196
+ accounts: readonly Pick<Account, "providerId" | "createdAt">[];
197
+ devices: readonly Device[];
198
+ history: readonly UserLifecycleEvent[];
199
+ plugins?: Record<string, Record<string, unknown>[]>;
200
+ }): AuthUserExport {
201
+ const { user } = input;
202
+ return {
203
+ user: {
204
+ ...userView(user),
205
+ suspendedAt: iso(user.suspendedAt),
206
+ suspendedUntil: iso(user.suspendedUntil),
207
+ deletedAt: iso(user.deletedAt),
208
+ purgeAfter: iso(user.purgeAfter),
209
+ },
210
+ sessions: input.sessions.map(sessionView),
211
+ providers: input.accounts.map((account) => ({
212
+ providerId: account.providerId,
213
+ createdAt: account.createdAt.toISOString(),
214
+ })),
215
+ devices: input.devices.map(deviceView),
216
+ history: input.history.map((event) => ({
217
+ action: event.action,
218
+ actorType: event.actorType,
219
+ reason: event.reason,
220
+ suspendedUntil: iso(event.suspendedUntil),
221
+ createdAt: event.createdAt.toISOString(),
222
+ })),
223
+ plugins: input.plugins ?? {},
224
+ };
225
+ }
226
+
227
+ /** The export document (#622): who it is about, when it was read, and every capability's part. */
228
+ export function exportView(
229
+ userId: string,
230
+ exportedAt: Date,
231
+ entries: readonly PurgeExportEntry[],
232
+ ): AdminUserExportResponse {
233
+ return {
234
+ subject: { type: "user", id: userId },
235
+ exportedAt: exportedAt.toISOString(),
236
+ capabilities: entries.map((entry) => ({ ...entry })),
237
+ };
238
+ }
@@ -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 { admitsDeletionSignIn, 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,
@@ -105,9 +108,39 @@ export function socialProviders(deps: AuthInstanceDeps): Record<string, unknown>
105
108
  ...signUpOption(deps.providerSignUp.github),
106
109
  };
107
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
+ }
108
130
  return Object.keys(providers).length > 0 ? providers : undefined;
109
131
  }
110
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
+
111
144
  /**
112
145
  * The seeding guard: a new account may be created only for an email a provider has **verified**.
113
146
  *
@@ -137,10 +170,37 @@ function refuseUnsafeProfileFields(user: { name?: unknown; image?: unknown }): v
137
170
  throw new APIError("BAD_REQUEST", { code: "INVALID_PROFILE_FIELD", message: refusal.message });
138
171
  }
139
172
 
140
- /** 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. */
141
174
  interface HookContext {
142
175
  headers?: Headers;
143
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;
144
204
  }
145
205
 
146
206
  /**
@@ -457,6 +517,18 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
457
517
  * `deviceId` by override for the same reason.
458
518
  */
459
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
+ //
526
+ // **One exception: a suspended account that signs in to delete itself (#622).** The app stores
527
+ // require that a person can always leave, and a suspension has already revoked every session the
528
+ // account held. The session this admits is still a suspended account's, so every request it makes
529
+ // is refused except `DELETE /auth/account` — see `admitsDeletionSignIn`.
530
+ const refusal = await lifecycleRefusalFor(deps.db, session.userId, null, new Date());
531
+ if (refusal && !admitsDeletionSignIn(refusal, ctx?.headers)) refuseSession(refusal, ctx);
460
532
  // **`undefined` and `null` are different answers here, and collapsing them is a hole.**
461
533
  // Absent means nobody supplied one, which is a sign-in: stamp it. Present-and-null is a
462
534
  // rotation of a session written before the column existed, and it must stay null so the gate
@@ -614,7 +686,7 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
614
686
  accountLinking: {
615
687
  enabled: true,
616
688
  // Link a social sign-in to an existing magic-link user when the verified emails match.
617
- trustedProviders: ["google", "apple"],
689
+ trustedProviders: [...TRUSTED_PROVIDERS],
618
690
  /**
619
691
  * **A signed-in user may attach a provider whose email differs from their account's.**
620
692
  *
@@ -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
+ }
@@ -65,14 +65,15 @@ import { NEUTRAL_PROVIDER_REFUSAL } from "../http/providerRefusal";
65
65
  * ## Why a wrapper, and not a `getUserInfo` supplied in the config block
66
66
  *
67
67
  * `options.getUserInfo` short-circuits each provider's own resolver on its first line
68
- * (`social-providers/google.mjs:118`, `facebook.mjs:93`, `apple.mjs:62`, `github.mjs:65`), so supplying
69
- * one means reimplementing the profile fetch it replaced — Google's id-token decode, Facebook's
70
- * access-token-owner check. `./githubUserInfo.ts` already records what that costs: replacing GitHub's
71
- * resolver silently dropped `name` and `image`, which had to be re-derived. Wrapping calls the
72
- * 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.
73
74
  *
74
75
  * **And it is the wrapping that makes the predicate read the right flag.** `mapProfileToUser` is applied
75
- * *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
76
77
  * `emailVerified` it computed — so the value this module reads is by construction the **effective** flag.
77
78
  * Facebook is the trap that makes this load-bearing: it sits outside `trustedProviders` like GitHub, but
78
79
  * `./auth.ts` asserts its address as verified with a documented reason, and its OAuth response carries no
@@ -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
  /**