@connextar/house 0.23.1 → 0.23.3

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 (180) hide show
  1. package/README.md +22 -3
  2. package/dist/analytics/browser.d.ts +1 -0
  3. package/dist/analytics/browser.d.ts.map +1 -1
  4. package/dist/analytics/browser.js +20 -3
  5. package/dist/analytics/browser.js.map +1 -1
  6. package/dist/analytics/config.d.ts +5 -0
  7. package/dist/analytics/config.d.ts.map +1 -1
  8. package/dist/analytics/config.js +4 -1
  9. package/dist/analytics/config.js.map +1 -1
  10. package/dist/analytics/react.d.ts.map +1 -1
  11. package/dist/analytics/react.js +4 -2
  12. package/dist/analytics/react.js.map +1 -1
  13. package/dist/analytics/redact.d.ts.map +1 -1
  14. package/dist/analytics/redact.js +6 -1
  15. package/dist/analytics/redact.js.map +1 -1
  16. package/package.json +5 -2
  17. package/src/account/data-contract.ts +112 -0
  18. package/src/account/index.ts +11 -0
  19. package/src/admin/access.ts +267 -0
  20. package/src/admin/audit.ts +238 -0
  21. package/src/admin/bootstrap.ts +220 -0
  22. package/src/admin/client-index.ts +19 -0
  23. package/src/admin/client.tsx +187 -0
  24. package/src/admin/index.ts +91 -0
  25. package/src/admin/proof.ts +155 -0
  26. package/src/admin/second-factor-index.ts +16 -0
  27. package/src/admin/second-factor.ts +403 -0
  28. package/src/admin/testing-index.ts +13 -0
  29. package/src/admin/testing.ts +299 -0
  30. package/src/admin/view-as.ts +511 -0
  31. package/src/ai/config-index.ts +40 -0
  32. package/src/ai/config.ts +176 -0
  33. package/src/ai/images.ts +18 -0
  34. package/src/ai/index.ts +21 -0
  35. package/src/ai/pricing.ts +107 -0
  36. package/src/ai/provider.ts +403 -0
  37. package/src/analytics/browser.ts +400 -0
  38. package/src/analytics/client-index.ts +12 -0
  39. package/src/analytics/config.ts +89 -0
  40. package/src/analytics/index.ts +17 -0
  41. package/src/analytics/ingest.ts +81 -0
  42. package/src/analytics/react-index.ts +16 -0
  43. package/src/analytics/react.tsx +241 -0
  44. package/src/analytics/redact.ts +146 -0
  45. package/src/analytics/server-index.ts +17 -0
  46. package/src/analytics/server.ts +277 -0
  47. package/src/auth/index.ts +30 -0
  48. package/src/auth/second-factor-index.ts +16 -0
  49. package/src/auth/second-factor-next.ts +136 -0
  50. package/src/auth/second-factor-routes.ts +40 -0
  51. package/src/auth/second-factor.ts +226 -0
  52. package/src/auth/step-up-client-index.ts +13 -0
  53. package/src/auth/step-up-client.ts +23 -0
  54. package/src/auth/step-up-index.ts +19 -0
  55. package/src/auth/step-up-routes.ts +99 -0
  56. package/src/auth/step-up.ts +432 -0
  57. package/src/auth/two-factor-policy.ts +112 -0
  58. package/src/changelog/changelog.tsx +367 -0
  59. package/src/changelog/index.ts +12 -0
  60. package/src/editor/block-handle.tsx +312 -0
  61. package/src/editor/blocks.ts +169 -0
  62. package/src/editor/bubble-toolbar.tsx +208 -0
  63. package/src/editor/collapsible.ts +159 -0
  64. package/src/editor/content-index.ts +1 -0
  65. package/src/editor/content.tsx +343 -0
  66. package/src/editor/editor.tsx +333 -0
  67. package/src/editor/emoji-index.ts +1 -0
  68. package/src/editor/emoji-picker.tsx +114 -0
  69. package/src/editor/emoji.ts +436 -0
  70. package/src/editor/index.ts +6 -0
  71. package/src/editor/sections.ts +83 -0
  72. package/src/editor/suggestion-popup.tsx +136 -0
  73. package/src/editor/suggestions.ts +309 -0
  74. package/src/editor/ui.tsx +171 -0
  75. package/src/errors/error-shell.tsx +72 -0
  76. package/src/errors/global-error-shell.tsx +116 -0
  77. package/src/errors/index.ts +2 -0
  78. package/src/grid/columns.ts +48 -0
  79. package/src/grid/compare.ts +35 -0
  80. package/src/grid/hidden-columns.ts +95 -0
  81. package/src/grid/index.ts +27 -0
  82. package/src/grid/use-grid.ts +282 -0
  83. package/src/grid/views.ts +70 -0
  84. package/src/guides/guide-article.tsx +92 -0
  85. package/src/guides/guide-figure-zoom.tsx +533 -0
  86. package/src/guides/guide-figure.tsx +68 -0
  87. package/src/guides/guide-toc.tsx +133 -0
  88. package/src/guides/guides-landing.tsx +57 -0
  89. package/src/guides/guides-search.tsx +160 -0
  90. package/src/guides/guides-shell.tsx +60 -0
  91. package/src/guides/guides-sidebar.tsx +93 -0
  92. package/src/guides/index.ts +28 -0
  93. package/src/guides/library.ts +165 -0
  94. package/src/health/health.ts +115 -0
  95. package/src/health/index.ts +11 -0
  96. package/src/internal/cx.ts +4 -0
  97. package/src/internal/next-link.ts +23 -0
  98. package/src/jobs/counts.ts +151 -0
  99. package/src/jobs/cron-auth.ts +60 -0
  100. package/src/jobs/health.ts +315 -0
  101. package/src/jobs/idle.ts +86 -0
  102. package/src/jobs/index.ts +120 -0
  103. package/src/jobs/job-health-list.tsx +316 -0
  104. package/src/jobs/next-index.ts +4 -0
  105. package/src/jobs/next.ts +65 -0
  106. package/src/jobs/prisma-index.ts +12 -0
  107. package/src/jobs/prisma.ts +170 -0
  108. package/src/jobs/prune.ts +79 -0
  109. package/src/jobs/react-index.ts +35 -0
  110. package/src/jobs/registry.ts +189 -0
  111. package/src/jobs/scheduler.ts +437 -0
  112. package/src/jobs/store.ts +212 -0
  113. package/src/jobs/windows.ts +157 -0
  114. package/src/maintenance/core.ts +270 -0
  115. package/src/maintenance/gate.ts +171 -0
  116. package/src/maintenance/index.ts +40 -0
  117. package/src/maintenance/page.ts +76 -0
  118. package/src/maintenance/proxy.ts +88 -0
  119. package/src/maintenance/react-index.ts +7 -0
  120. package/src/maintenance/react.tsx +190 -0
  121. package/src/maintenance/route.ts +82 -0
  122. package/src/maintenance/unavailable.ts +61 -0
  123. package/src/markdown/figure.tsx +132 -0
  124. package/src/markdown/figures.ts +237 -0
  125. package/src/markdown/guide.tsx +536 -0
  126. package/src/markdown/index.ts +53 -0
  127. package/src/markdown/table-view.tsx +74 -0
  128. package/src/markdown/table.ts +90 -0
  129. package/src/password/common.ts +58 -0
  130. package/src/password/estimate-index.ts +18 -0
  131. package/src/password/estimate.ts +715 -0
  132. package/src/password/index.ts +40 -0
  133. package/src/password/password-input.tsx +116 -0
  134. package/src/password/password-strength.tsx +157 -0
  135. package/src/password/reveal.ts +151 -0
  136. package/src/rate-limit/better-auth.ts +94 -0
  137. package/src/rate-limit/index.ts +32 -0
  138. package/src/rate-limit/keys.ts +110 -0
  139. package/src/rate-limit/limiter.ts +276 -0
  140. package/src/rate-limit/prisma-index.ts +12 -0
  141. package/src/rate-limit/prisma.ts +157 -0
  142. package/src/rate-limit/store.ts +47 -0
  143. package/src/release/changelog.ts +364 -0
  144. package/src/release/index.ts +32 -0
  145. package/src/release/version.ts +64 -0
  146. package/src/setup-guide/bits.tsx +420 -0
  147. package/src/setup-guide/card.tsx +358 -0
  148. package/src/setup-guide/class-names.ts +144 -0
  149. package/src/setup-guide/context.tsx +239 -0
  150. package/src/setup-guide/guide.ts +271 -0
  151. package/src/setup-guide/index.ts +76 -0
  152. package/src/setup-guide/launcher.tsx +207 -0
  153. package/src/setup-guide/strip.tsx +127 -0
  154. package/src/styles/house.css +384 -0
  155. package/src/trail/index.ts +12 -0
  156. package/src/trail/rules.ts +84 -0
  157. package/src/trail/trail.tsx +367 -0
  158. package/src/ux/errors.ts +32 -0
  159. package/src/ux/feedback.tsx +41 -0
  160. package/src/ux/index.ts +44 -0
  161. package/src/ux/navigation-index.ts +16 -0
  162. package/src/ux/navigation-progress.tsx +270 -0
  163. package/src/ux/optimistic.ts +415 -0
  164. package/src/ux/use-action.ts +155 -0
  165. package/src/ux/use-optimistic-list.ts +227 -0
  166. package/src/ux/use-optimistic-value.ts +136 -0
  167. package/src/web-search/index.ts +13 -0
  168. package/src/web-search/providers.ts +177 -0
  169. package/src/web-search/types.ts +98 -0
  170. package/src/whats-new/body.tsx +190 -0
  171. package/src/whats-new/index.ts +43 -0
  172. package/src/whats-new/seen.ts +40 -0
  173. package/src/whats-new/select.ts +230 -0
  174. package/src/whats-new/use-whats-new.ts +109 -0
  175. package/src/wizard/index.ts +61 -0
  176. package/src/wizard/invalid.ts +152 -0
  177. package/src/wizard/react-hook-form-index.ts +11 -0
  178. package/src/wizard/rhf-adapter.ts +67 -0
  179. package/src/wizard/rules.ts +137 -0
  180. package/src/wizard/wizard.tsx +442 -0
@@ -0,0 +1,432 @@
1
+ import type { BetterAuthPlugin, User } from "better-auth";
2
+ import {
3
+ APIError,
4
+ createAuthEndpoint,
5
+ createAuthMiddleware,
6
+ getAuthoritativeSessionFromCtx,
7
+ isAPIError,
8
+ sensitiveSessionMiddleware,
9
+ } from "better-auth/api";
10
+ import * as z from "zod";
11
+
12
+ import {
13
+ DEFAULT_STEP_UP_MAX_ATTEMPTS,
14
+ DEFAULT_STEP_UP_WINDOW_SECONDS,
15
+ STEP_UP_CODE_ROUTES,
16
+ STEP_UP_ERROR_CODES,
17
+ STEP_UP_ID,
18
+ STEP_UP_PASSKEY_ROUTES,
19
+ STEP_UP_REQUIRED_GENERIC_MESSAGE,
20
+ type StepUpNeeds,
21
+ type StepUpStatus,
22
+ } from "./step-up-routes.js";
23
+
24
+ /**
25
+ * A new way in needs a recent proof of an existing one.
26
+ *
27
+ * `@better-auth/passkey` lets any session under a day old (`session.freshAge`) register a passkey — no password, no
28
+ * code. A passkey then signs in in one step, skips the second factor on purpose, and survives a password reset
29
+ * (which revokes sessions, not passkeys). So a stolen or borrowed session becomes a durable way in. `stepUp()` puts a
30
+ * recent confirmation in front of `/passkey/generate-register-options` and `/passkey/verify-registration`. What
31
+ * confirms depends on the account:
32
+ *
33
+ * - **two-factor on** → the authenticator code or a backup code, entered now. The client calls Better Auth's own
34
+ * `/two-factor/verify-totp` or `/two-factor/verify-backup-code` with its live session: Better Auth checks the code
35
+ * and creates nothing, and this plugin records a confirmation for that session when the check succeeds. Nothing of
36
+ * the two-factor plugin is copied — no secret, no decryption. Only an account that already had two-factor on
37
+ * before the call counts: on an unenrolled account the same call is the end of enrolment, which proves only that
38
+ * the person holds the authenticator they have just added.
39
+ * - **no two-factor, a password** → the password, at `POST /step-up/password`, checked by Better Auth's own
40
+ * `ctx.context.password.checkPassword`.
41
+ * - **neither** (email link or social only) → a sign-in within the window: the session itself is younger than
42
+ * `windowSeconds`. Nothing to type; the screen asks them to sign in again.
43
+ *
44
+ * A confirmation is a row in Better Auth's `verification` table (`step-up:<session id>`, the user id as its value,
45
+ * expiring after the window). It belongs to that one session, is not used up by the routes it unlocks, and never
46
+ * counts for another session or another user.
47
+ *
48
+ * **Wrong answers.** Better Auth's two-factor lockout and attempt limit apply only to a sign-in; a code checked with a
49
+ * live session is limited by nothing but the rate limiter. So one session gets `maxAttempts` wrong answers, codes and
50
+ * passwords together, before it has to sign in again — and once it has spent them, its live code checks are refused
51
+ * too, so a stolen session cannot keep guessing.
52
+ *
53
+ * Passkey deletion is not gated: removing a way in is not a new one. An app's own administrator second-factor proof
54
+ * (`second-factor-session`) is unchanged and applies on top; either refusal can stop a registration.
55
+ *
56
+ * **Order**: list it after `twoFactor()` and `passkey()`, and before `nextCookies()`.
57
+ */
58
+ export interface StepUpOptions {
59
+ /** Turn the refusal off for this app (`false`) while keeping the plugin and its endpoints. Default `true`. */
60
+ enabled?: boolean;
61
+ /** How long a confirmation lasts, and how young a session must be to count as a recent sign-in. Default 600. */
62
+ windowSeconds?: number;
63
+ /**
64
+ * The routes that need a confirmation. Default {@link STEP_UP_PASSKEY_ROUTES}; to add a route, keep those:
65
+ * `routes: [...STEP_UP_PASSKEY_ROUTES, "/my/route"]`.
66
+ *
67
+ * Only endpoints reached through Better Auth's router have a path to match. A server-only method has none —
68
+ * `auth.api.setPassword` among them — so listing "/set-password" here matches nothing and guards nothing. Check
69
+ * in the caller instead: `auth.api.stepUpStatus({ headers })` before the call, and refuse when not confirmed.
70
+ */
71
+ routes?: readonly string[];
72
+ /** Wrong answers (codes and passwords together) one session may give before it must sign in again. Default 5. */
73
+ maxAttempts?: number;
74
+ /**
75
+ * Called once a passkey has been added (`/passkey/verify-registration` succeeded) — to email "A passkey was added
76
+ * to your account" with the app's own mailer. It cannot fail or undo the registration: an error is logged and the
77
+ * passkey stays. With Better Auth's `advanced.backgroundTasks` set, it runs in the background.
78
+ */
79
+ onPasskeyAdded?: (data: PasskeyAddedData) => Promise<void> | void;
80
+ }
81
+
82
+ export interface PasskeyAddedData {
83
+ user: User;
84
+ passkey: { id: string; name?: string; createdAt?: Date };
85
+ /** The registration request, when there was one (not for a server-side `auth.api` call). */
86
+ request?: Request;
87
+ }
88
+
89
+ type Hooks = NonNullable<BetterAuthPlugin["hooks"]>;
90
+ type AfterHook = NonNullable<Hooks["after"]>[number];
91
+ type BeforeHook = NonNullable<Hooks["before"]>[number];
92
+ type HookContext = Parameters<Parameters<typeof createAuthMiddleware>[0]>[0];
93
+ type AuthContext = HookContext["context"];
94
+
95
+ interface LiveSession {
96
+ session: { id: string; token: string; userId: string; createdAt: Date | string; expiresAt: Date | string };
97
+ user: User & { twoFactorEnabled?: boolean | null };
98
+ }
99
+
100
+ /** What the before-hook on a code check learnt, for the after-hook to act on. */
101
+ interface PendingCodeCheck {
102
+ session: LiveSession["session"];
103
+ }
104
+
105
+ const confirmationKey = (sessionId: string) => `${STEP_UP_ID}:${sessionId}`;
106
+ const attemptsKey = (sessionId: string) => `${STEP_UP_ID}-attempts:${sessionId}`;
107
+ /** How long a session's wrong answers are remembered: longer than any session lasts without signing in again. */
108
+ const ATTEMPTS_KEPT_MS = 400 * 86_400_000;
109
+
110
+ const PASSKEY_VERIFY_REGISTRATION = "/passkey/verify-registration";
111
+
112
+ function jsonBody(response: unknown): unknown {
113
+ // `ctx.json()` answers the plain object inside hooks, and a `{ _flag: "json", body }` wrapper when the caller
114
+ // asked for a Response; accept either.
115
+ if (response && typeof response === "object" && (response as { _flag?: unknown })._flag === "json") {
116
+ return (response as { body?: unknown }).body;
117
+ }
118
+ return response;
119
+ }
120
+
121
+ const toDate = (value: Date | string) => (value instanceof Date ? value : new Date(value));
122
+
123
+ function endpointPaths(plugin: BetterAuthPlugin | undefined): Set<string> {
124
+ return new Set(
125
+ Object.values(plugin?.endpoints ?? {}).map((endpoint) => (endpoint as { path?: string } | undefined)?.path ?? ""),
126
+ );
127
+ }
128
+
129
+ export function stepUp(options: StepUpOptions = {}) {
130
+ const enabled = options.enabled !== false;
131
+ const windowSeconds = options.windowSeconds ?? DEFAULT_STEP_UP_WINDOW_SECONDS;
132
+ const maxAttempts = options.maxAttempts ?? DEFAULT_STEP_UP_MAX_ATTEMPTS;
133
+ const routes = new Set<string>(options.routes ?? STEP_UP_PASSKEY_ROUTES);
134
+ const passkeyRoutes: readonly string[] = STEP_UP_PASSKEY_ROUTES;
135
+ const codeRoutes: readonly string[] = STEP_UP_CODE_ROUTES;
136
+
137
+ if (!Number.isFinite(windowSeconds) || windowSeconds <= 0) {
138
+ throw new Error(`[step-up] windowSeconds must be a positive number of seconds, got ${String(windowSeconds)}.`);
139
+ }
140
+ if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {
141
+ throw new Error(`[step-up] maxAttempts must be a whole number of at least 1, got ${String(maxAttempts)}.`);
142
+ }
143
+
144
+ /** Code checks under way, keyed by the request's own context object (shared by its before- and after-hooks). */
145
+ const pending = new WeakMap<object, PendingCodeCheck>();
146
+
147
+ function twoFactorInstalled(context: AuthContext): boolean {
148
+ return (context.options.plugins ?? []).some((plugin) => plugin.id === "two-factor");
149
+ }
150
+
151
+ async function needsFor(context: AuthContext, user: LiveSession["user"]): Promise<StepUpNeeds> {
152
+ if (user.twoFactorEnabled === true && twoFactorInstalled(context)) return "code";
153
+ // `findAccounts` rather than 1.7's `findCredentialAccount`: 1.6 has only the former.
154
+ const accounts = await context.internalAdapter.findAccounts(user.id);
155
+ if (accounts.some((account) => account.providerId === "credential" && !!account.password)) return "password";
156
+ return "recent-sign-in";
157
+ }
158
+
159
+ async function attemptsUsed(context: AuthContext, sessionId: string): Promise<number> {
160
+ const row = await context.internalAdapter.findVerificationValue(attemptsKey(sessionId));
161
+ if (!row || toDate(row.expiresAt).getTime() <= Date.now()) return 0;
162
+ const used = Number(row.value);
163
+ return Number.isInteger(used) && used > 0 ? used : 0;
164
+ }
165
+
166
+ async function recordWrongAnswer(context: AuthContext, session: LiveSession["session"]): Promise<void> {
167
+ const used = await attemptsUsed(context, session.id);
168
+ await context.internalAdapter.deleteVerificationByIdentifier(attemptsKey(session.id));
169
+ // Kept well past the session: Better Auth moves a session's expiry on as it's used, so a count kept only until
170
+ // the session's expiry at the time would lapse (or be tidied away) while the session lives on, and the budget
171
+ // would refill. A session that outlives this has been in use, without signing in again, for over a year.
172
+ const lasts = Math.max(toDate(session.expiresAt).getTime(), Date.now() + ATTEMPTS_KEPT_MS);
173
+ await context.internalAdapter.createVerificationValue({
174
+ identifier: attemptsKey(session.id),
175
+ value: String(used + 1),
176
+ expiresAt: new Date(lasts),
177
+ });
178
+ }
179
+
180
+ async function recordConfirmation(context: AuthContext, session: LiveSession["session"]): Promise<Date> {
181
+ const expiresAt = new Date(Date.now() + windowSeconds * 1000);
182
+ await context.internalAdapter.deleteVerificationByIdentifier(confirmationKey(session.id));
183
+ await context.internalAdapter.createVerificationValue({
184
+ identifier: confirmationKey(session.id),
185
+ value: session.userId,
186
+ expiresAt,
187
+ });
188
+ return expiresAt;
189
+ }
190
+
191
+ async function statusFor(context: AuthContext, live: LiveSession): Promise<StepUpStatus> {
192
+ const needs = await needsFor(context, live.user);
193
+ const locked = needs !== "recent-sign-in" && (await attemptsUsed(context, live.session.id)) >= maxAttempts;
194
+ const now = Date.now();
195
+ // The passkey plugin's own freshSessionMiddleware rule, so a screen can say "sign in again" before it asks
196
+ // for a password the passkey routes would then refuse anyway.
197
+ const freshAge = context.sessionConfig.freshAge;
198
+ const sessionFresh = freshAge === 0 || now - toDate(live.session.createdAt).getTime() < freshAge * 1000;
199
+
200
+ const row = await context.internalAdapter.findVerificationValue(confirmationKey(live.session.id));
201
+ if (row && row.value === live.session.userId && row.value === live.user.id) {
202
+ const until = toDate(row.expiresAt);
203
+ if (until.getTime() > now) {
204
+ return { needs, confirmed: true, confirmedUntil: until.toISOString(), locked, sessionFresh };
205
+ }
206
+ }
207
+ if (needs === "recent-sign-in") {
208
+ const until = new Date(toDate(live.session.createdAt).getTime() + windowSeconds * 1000);
209
+ if (until.getTime() > now) {
210
+ return { needs, confirmed: true, confirmedUntil: until.toISOString(), locked, sessionFresh };
211
+ }
212
+ }
213
+ return { needs, confirmed: false, confirmedUntil: null, locked, sessionFresh };
214
+ }
215
+
216
+ /** The session as the session store has it now — never the cookie cache, which can outlive a revoked session. */
217
+ async function liveSession(ctx: HookContext): Promise<LiveSession | null> {
218
+ const current = (await getAuthoritativeSessionFromCtx(ctx)) as LiveSession | null;
219
+ return current?.session ? current : null;
220
+ }
221
+
222
+ function passkeyFirstRegistration(context: AuthContext, path: string): boolean {
223
+ if (!passkeyRoutes.includes(path)) return false;
224
+ const passkey = (context.options.plugins ?? []).find((plugin) => plugin.id === "passkey") as
225
+ { options?: { registration?: { requireSession?: boolean } } } | undefined;
226
+ return passkey?.options?.registration?.requireSession === false;
227
+ }
228
+
229
+ const gate: BeforeHook = {
230
+ matcher: (ctx) => enabled && routes.has(ctx.path ?? ""),
231
+ handler: createAuthMiddleware(async (ctx) => {
232
+ const live = await liveSession(ctx);
233
+ if (!live) {
234
+ // A passkey-first sign-up (`registration.requireSession: false`) adds a passkey to an account that has no
235
+ // other way in yet: there is nothing to prove, and the passkey plugin's own rules apply.
236
+ if (passkeyFirstRegistration(ctx.context, ctx.path)) return;
237
+ // Refuse here rather than leave it to the route, whose own check accepts the session cookie cache for a few
238
+ // minutes — long enough for a just-revoked session to slip a passkey through.
239
+ throw new APIError("UNAUTHORIZED", { message: "Unauthorized", code: "UNAUTHORIZED" });
240
+ }
241
+ const status = await statusFor(ctx.context, live);
242
+ if (status.confirmed) return;
243
+ throw new APIError("FORBIDDEN", {
244
+ code: STEP_UP_ERROR_CODES.STEP_UP_REQUIRED.code,
245
+ message: passkeyRoutes.includes(ctx.path)
246
+ ? STEP_UP_ERROR_CODES.STEP_UP_REQUIRED.message
247
+ : STEP_UP_REQUIRED_GENERIC_MESSAGE,
248
+ needs: status.needs,
249
+ });
250
+ }),
251
+ };
252
+
253
+ const beforeCodeCheck: BeforeHook = {
254
+ matcher: (ctx) => enabled && codeRoutes.includes(ctx.path ?? ""),
255
+ handler: createAuthMiddleware(async (ctx) => {
256
+ const live = await liveSession(ctx);
257
+ // No live session: a sign-in finishing with its code. Two-factor off: enrolment. Neither confirms anything.
258
+ if (!live || live.user.twoFactorEnabled !== true) return;
259
+ if ((await attemptsUsed(ctx.context, live.session.id)) >= maxAttempts) {
260
+ throw new APIError("FORBIDDEN", { ...STEP_UP_ERROR_CODES.STEP_UP_LOCKED, needs: "code" });
261
+ }
262
+ pending.set(ctx.context, { session: live.session });
263
+ }),
264
+ };
265
+
266
+ const afterCodeCheck: AfterHook = {
267
+ matcher: (ctx) => enabled && codeRoutes.includes(ctx.path ?? ""),
268
+ handler: createAuthMiddleware(async (ctx) => {
269
+ const check = pending.get(ctx.context);
270
+ if (!check) return;
271
+ pending.delete(ctx.context);
272
+ try {
273
+ const returned = ctx.context.returned;
274
+ if (isAPIError(returned)) {
275
+ // In the live-session branch a 401 means one thing: the code was wrong.
276
+ const wrong = (returned as { statusCode?: number }).statusCode === 401;
277
+ if (wrong) await recordWrongAnswer(ctx.context, check.session);
278
+ return;
279
+ }
280
+ // Better Auth's live-session branch answers with the session it was called with, and creates none. Anything
281
+ // else (a new session, a different token) is not the call this was told about: it proves nothing here.
282
+ const token = (jsonBody(returned) as { token?: unknown } | null | undefined)?.token;
283
+ if (token !== check.session.token) return;
284
+ await recordConfirmation(ctx.context, check.session);
285
+ } catch (error) {
286
+ // Failing to record only means being asked again — the safe way round — and must not fail the code check.
287
+ ctx.context.logger.error("[step-up] could not record a code check", error);
288
+ }
289
+ }),
290
+ };
291
+
292
+ const afterPasskeyAdded: AfterHook = {
293
+ matcher: (ctx) => !!options.onPasskeyAdded && ctx.path === PASSKEY_VERIFY_REGISTRATION,
294
+ handler: createAuthMiddleware(async (ctx) => {
295
+ const notify = options.onPasskeyAdded;
296
+ if (!notify || isAPIError(ctx.context.returned)) return;
297
+ try {
298
+ type PasskeyRow = { id?: unknown; name?: unknown; createdAt?: unknown; userId?: unknown };
299
+ // Both lines answer with the stored row (1.7 adds `session` and `user` when asked to create a session).
300
+ let row = jsonBody(ctx.context.returned) as PasskeyRow | null | undefined;
301
+ if (typeof row?.id !== "string" || typeof row.userId !== "string") {
302
+ const userId = (ctx.context.session as LiveSession | null)?.user?.id;
303
+ if (!userId) return;
304
+ const [newest] = await ctx.context.adapter.findMany<PasskeyRow>({
305
+ model: "passkey",
306
+ where: [{ field: "userId", value: userId }],
307
+ sortBy: { field: "createdAt", direction: "desc" },
308
+ limit: 1,
309
+ });
310
+ row = newest;
311
+ }
312
+ if (typeof row?.id !== "string" || typeof row.userId !== "string") return;
313
+ const user = await ctx.context.internalAdapter.findUserById(row.userId);
314
+ if (!user) return;
315
+ const createdAt =
316
+ row.createdAt instanceof Date || typeof row.createdAt === "string" ? toDate(row.createdAt) : undefined;
317
+ const passkey = {
318
+ id: row.id,
319
+ ...(typeof row.name === "string" && row.name ? { name: row.name } : {}),
320
+ ...(createdAt ? { createdAt } : {}),
321
+ };
322
+ const logger = ctx.context.logger;
323
+ const run = (async () => {
324
+ try {
325
+ await notify({ user, passkey, ...(ctx.request ? { request: ctx.request } : {}) });
326
+ } catch (error) {
327
+ logger.error("[step-up] onPasskeyAdded failed; the passkey was added", error);
328
+ }
329
+ })();
330
+ await ctx.context.runInBackgroundOrAwait(run);
331
+ } catch (error) {
332
+ ctx.context.logger.error("[step-up] could not read the passkey that was added", error);
333
+ }
334
+ }),
335
+ };
336
+
337
+ return {
338
+ id: STEP_UP_ID,
339
+ options: { ...options, enabled, windowSeconds, maxAttempts, routes: [...routes] },
340
+ init(ctx) {
341
+ if (!enabled) return;
342
+ const plugins = ctx.options.plugins ?? [];
343
+ const twoFactor = plugins.find((plugin) => plugin.id === "two-factor");
344
+ if (twoFactor) {
345
+ const paths = endpointPaths(twoFactor);
346
+ const missing = codeRoutes.filter((path) => !paths.has(path));
347
+ if (missing.length) {
348
+ throw new Error(
349
+ `[step-up] Better Auth's twoFactor() plugin no longer exposes ${missing.join(" and ")}, which is how an ` +
350
+ "account with two-factor on confirms it's them. This Better Auth version changed it — check " +
351
+ "@connextar/house's supported Better Auth range.",
352
+ );
353
+ }
354
+ }
355
+ if ((twoFactor?.options as { allowPasswordless?: boolean } | undefined)?.allowPasswordless) {
356
+ ctx.logger.warn(
357
+ "[step-up] twoFactor({ allowPasswordless: true }) lets a session alone re-key two-factor on an account " +
358
+ "without a password, so for those accounts a code proves no more than the session does.",
359
+ );
360
+ }
361
+ const passkey = plugins.find((plugin) => plugin.id === "passkey");
362
+ if (passkey) {
363
+ const paths = endpointPaths(passkey);
364
+ const missing = passkeyRoutes.filter((path) => !paths.has(path));
365
+ if (missing.length) {
366
+ throw new Error(
367
+ `[step-up] the passkey plugin no longer registers passkeys at ${missing.join(" and ")}, so the refusal ` +
368
+ "would guard nothing. Check @connextar/house's supported Better Auth range.",
369
+ );
370
+ }
371
+ } else if (passkeyRoutes.some((path) => routes.has(path))) {
372
+ ctx.logger.warn("[step-up] no passkey() plugin is installed, so there is no passkey registration to guard.");
373
+ }
374
+ const ownIndex = plugins.findIndex((plugin) => plugin.id === STEP_UP_ID);
375
+ const nextCookiesIndex = plugins.findIndex((plugin) => plugin.id === "next-cookies");
376
+ if (nextCookiesIndex !== -1 && nextCookiesIndex < ownIndex) {
377
+ ctx.logger.warn("[step-up] is listed after nextCookies(); list it before, so the cookies it sets reach Next.");
378
+ }
379
+ },
380
+ endpoints: {
381
+ stepUpStatus: createAuthEndpoint(
382
+ "/step-up/status",
383
+ { method: "GET", use: [sensitiveSessionMiddleware] },
384
+ async (ctx) => ctx.json(await statusFor(ctx.context, ctx.context.session as LiveSession)),
385
+ ),
386
+ stepUpPassword: createAuthEndpoint(
387
+ "/step-up/password",
388
+ { method: "POST", body: z.object({ password: z.string() }), use: [sensitiveSessionMiddleware] },
389
+ async (ctx) => {
390
+ const live = ctx.context.session as LiveSession;
391
+ const needs = await needsFor(ctx.context, live.user);
392
+ if (needs !== "password") {
393
+ throw new APIError("BAD_REQUEST", {
394
+ code: STEP_UP_ERROR_CODES.STEP_UP_PASSWORD_NOT_ACCEPTED.code,
395
+ message:
396
+ needs === "code"
397
+ ? "Enter the code from your authenticator app instead."
398
+ : "This account has no password. Sign in again to confirm it's you.",
399
+ needs,
400
+ });
401
+ }
402
+ if ((await attemptsUsed(ctx.context, live.session.id)) >= maxAttempts) {
403
+ throw new APIError("FORBIDDEN", { ...STEP_UP_ERROR_CODES.STEP_UP_LOCKED, needs });
404
+ }
405
+ try {
406
+ // Better Auth's own check: the credential account's hash, its configured verifier, a constant-time
407
+ // answer when there is none, and a 400 INVALID_PASSWORD when it does not match.
408
+ await ctx.context.password.checkPassword(live.user.id, ctx);
409
+ } catch (error) {
410
+ if (isAPIError(error)) await recordWrongAnswer(ctx.context, live.session);
411
+ throw error;
412
+ }
413
+ const until = await recordConfirmation(ctx.context, live.session);
414
+ return ctx.json({
415
+ ...(await statusFor(ctx.context, live)),
416
+ confirmed: true,
417
+ confirmedUntil: until.toISOString(),
418
+ locked: false,
419
+ } satisfies StepUpStatus);
420
+ },
421
+ ),
422
+ },
423
+ hooks: {
424
+ before: [gate, beforeCodeCheck],
425
+ after: [afterCodeCheck, afterPasskeyAdded],
426
+ },
427
+ // As strict as Better Auth's own two-factor routes: three tries in ten seconds. Better Auth applies it only where
428
+ // its rate limiter is on (production, by default).
429
+ rateLimit: [{ pathMatcher: (path: string) => path === "/step-up/password", window: 10, max: 3 }],
430
+ $ERROR_CODES: STEP_UP_ERROR_CODES,
431
+ } satisfies BetterAuthPlugin;
432
+ }
@@ -0,0 +1,112 @@
1
+ import { SECOND_FACTOR_EVERYWHERE_ID } from "./second-factor-routes.js";
2
+
3
+ /**
4
+ * Which sign-in routes need the second factor enforced by hand.
5
+ *
6
+ * Better Auth's `twoFactor` plugin hooks `/sign-in/email`, `/sign-in/username`
7
+ * and `/sign-in/phone-number` and nothing else. Every other sign-in route issues
8
+ * a session outright, second factor or not. That is fine for most of them and
9
+ * emphatically not fine for one:
10
+ *
11
+ * - **Magic link** — a link in an inbox, and strictly weaker than the password
12
+ * it stands in for. Allowing it while two-factor is on means a stolen mailbox
13
+ * is still enough, which is exactly what the feature is sold as preventing.
14
+ * **Refused.**
15
+ * - **Passkey** — already possession of a device, and phishing-resistant. At
16
+ * least as strong as password + TOTP. Allowed.
17
+ * - **Social** — delegates to a provider that enforces its own second factor.
18
+ * Allowed.
19
+ *
20
+ * This lives in the package rather than in each app because it is a security
21
+ * decision that has to be the same everywhere, and because getting it wrong is
22
+ * silent: two-factor keeps *looking* enabled while doing nothing.
23
+ *
24
+ * **Superseded by `secondFactorEverywhere()`** (`@connextar/house/auth/second-factor`),
25
+ * which instead puts the code screen after a magic link *and* after a social
26
+ * sign-in, so neither needs refusing. Pass the hook's `ctx.context` to
27
+ * {@link shouldBlockForTwoFactor} and the refusal retires itself while that plugin
28
+ * is live — see {@link magicLinkRefusalRetired}.
29
+ */
30
+
31
+ export const TWO_FACTOR_BLOCKED_PATHS = ["/sign-in/magic-link"] as const;
32
+
33
+ export type TwoFactorBlockedPath = (typeof TWO_FACTOR_BLOCKED_PATHS)[number];
34
+
35
+ export const TWO_FACTOR_BLOCKED_MESSAGE =
36
+ "This account uses two-factor authentication. Sign in with your email and password, " +
37
+ "then enter the code from your authenticator app.";
38
+
39
+ export function isTwoFactorBlockedPath(path: string): boolean {
40
+ return (TWO_FACTOR_BLOCKED_PATHS as readonly string[]).includes(path);
41
+ }
42
+
43
+ /** Answers "does this address have a second factor turned on?". Supplied by the app. */
44
+ export type TwoFactorLookup = (email: string) => Promise<boolean>;
45
+
46
+ /**
47
+ * True when this sign-in attempt must be refused because it would hand out a
48
+ * session without the second factor.
49
+ *
50
+ * The lookup is injected rather than imported: every app has its own Prisma
51
+ * client and its own user table, and a package that reached for one would be
52
+ * useless to the next app along.
53
+ *
54
+ * Unknown addresses return false. The refusal must not become an oracle
55
+ * answering "does this account exist, and does it have two-factor on?" for
56
+ * anyone with an email address and a spare minute.
57
+ */
58
+ export async function shouldBlockForTwoFactor(
59
+ path: string,
60
+ email: string | undefined | null,
61
+ lookup: TwoFactorLookup,
62
+ /**
63
+ * The hook's `ctx.context`. Passing it retires the refusal once `secondFactorEverywhere()` is installed and
64
+ * challenging magic links — see {@link magicLinkRefusalRetired}.
65
+ */
66
+ authContext?: AuthContextLike | null,
67
+ ): Promise<boolean> {
68
+ if (!isTwoFactorBlockedPath(path) || !email) return false;
69
+ if (authContext && magicLinkRefusalRetired(authContext)) return false;
70
+ return lookup(email.toLowerCase());
71
+ }
72
+
73
+ /** The slice of Better Auth's `ctx.context` (or `auth.options`) this reads. */
74
+ export interface AuthContextLike {
75
+ options?: { plugins?: readonly unknown[] | null } | null;
76
+ plugins?: readonly unknown[] | null;
77
+ }
78
+
79
+ /**
80
+ * True when refusing magic links for two-factor accounts is no longer needed, because
81
+ * `secondFactorEverywhere()` from `@connextar/house/auth/second-factor` is installed, enabled, and puts the code
82
+ * screen behind `/magic-link/verify`.
83
+ *
84
+ * This is how an app retires its old before-hook refusal *safely*: the refusal steps aside exactly while its
85
+ * replacement is live, and comes back on its own if the replacement is ever switched off (`enabled: false`) or
86
+ * removed — so turning the challenge off can never quietly reopen the magic-link hole. Pass `ctx.context` from a
87
+ * hook, or `auth.options`.
88
+ */
89
+ export function magicLinkRefusalRetired(authContext: AuthContextLike): boolean {
90
+ const plugins = authContext.options?.plugins ?? authContext.plugins ?? [];
91
+ return plugins.some((plugin) => {
92
+ if (!plugin || typeof plugin !== "object") return false;
93
+ const { id, options } = plugin as { id?: unknown; options?: { enabled?: unknown; routes?: unknown } };
94
+ if (id !== SECOND_FACTOR_EVERYWHERE_ID) return false;
95
+ if (options?.enabled === false) return false;
96
+ const routes = options?.routes;
97
+ return !Array.isArray(routes) || routes.includes("/magic-link/verify");
98
+ });
99
+ }
100
+
101
+ /**
102
+ * Pull the shared secret out of an `otpauth://` URI, for the "can't scan it?"
103
+ * manual-entry path during enrolment.
104
+ *
105
+ * Returns null rather than throwing on a malformed URI — a missing manual-entry
106
+ * fallback is a worse enrolment screen, not a broken one.
107
+ */
108
+ export function totpSecretFromUri(totpUri: string): string | null {
109
+ const query = totpUri.split("?")[1];
110
+ if (!query) return null;
111
+ return new URLSearchParams(query).get("secret");
112
+ }