@connextar/house 0.23.1 → 0.24.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 (186) hide show
  1. package/README.md +55 -13
  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 +22 -5
  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/posthog-extensions.d.ts +19 -0
  11. package/dist/analytics/posthog-extensions.d.ts.map +1 -0
  12. package/dist/analytics/posthog-extensions.js +19 -0
  13. package/dist/analytics/posthog-extensions.js.map +1 -0
  14. package/dist/analytics/react.d.ts.map +1 -1
  15. package/dist/analytics/react.js +4 -2
  16. package/dist/analytics/react.js.map +1 -1
  17. package/dist/analytics/redact.d.ts.map +1 -1
  18. package/dist/analytics/redact.js +6 -1
  19. package/dist/analytics/redact.js.map +1 -1
  20. package/dist/house.css +19 -0
  21. package/package.json +17 -3
  22. package/src/account/data-contract.ts +112 -0
  23. package/src/account/index.ts +11 -0
  24. package/src/admin/access.ts +267 -0
  25. package/src/admin/audit.ts +238 -0
  26. package/src/admin/bootstrap.ts +220 -0
  27. package/src/admin/client-index.ts +19 -0
  28. package/src/admin/client.tsx +187 -0
  29. package/src/admin/index.ts +91 -0
  30. package/src/admin/proof.ts +155 -0
  31. package/src/admin/second-factor-index.ts +16 -0
  32. package/src/admin/second-factor.ts +403 -0
  33. package/src/admin/testing-index.ts +13 -0
  34. package/src/admin/testing.ts +299 -0
  35. package/src/admin/view-as.ts +511 -0
  36. package/src/ai/config-index.ts +40 -0
  37. package/src/ai/config.ts +176 -0
  38. package/src/ai/images.ts +18 -0
  39. package/src/ai/index.ts +21 -0
  40. package/src/ai/pricing.ts +107 -0
  41. package/src/ai/provider.ts +403 -0
  42. package/src/analytics/browser.ts +400 -0
  43. package/src/analytics/client-index.ts +12 -0
  44. package/src/analytics/config.ts +89 -0
  45. package/src/analytics/index.ts +17 -0
  46. package/src/analytics/ingest.ts +81 -0
  47. package/src/analytics/posthog-extensions.ts +19 -0
  48. package/src/analytics/react-index.ts +16 -0
  49. package/src/analytics/react.tsx +241 -0
  50. package/src/analytics/redact.ts +146 -0
  51. package/src/analytics/server-index.ts +17 -0
  52. package/src/analytics/server.ts +277 -0
  53. package/src/auth/index.ts +30 -0
  54. package/src/auth/second-factor-index.ts +16 -0
  55. package/src/auth/second-factor-next.ts +136 -0
  56. package/src/auth/second-factor-routes.ts +40 -0
  57. package/src/auth/second-factor.ts +226 -0
  58. package/src/auth/step-up-client-index.ts +13 -0
  59. package/src/auth/step-up-client.ts +23 -0
  60. package/src/auth/step-up-index.ts +19 -0
  61. package/src/auth/step-up-routes.ts +99 -0
  62. package/src/auth/step-up.ts +432 -0
  63. package/src/auth/two-factor-policy.ts +112 -0
  64. package/src/changelog/changelog.tsx +367 -0
  65. package/src/changelog/index.ts +12 -0
  66. package/src/editor/block-handle.tsx +312 -0
  67. package/src/editor/blocks.ts +169 -0
  68. package/src/editor/bubble-toolbar.tsx +208 -0
  69. package/src/editor/collapsible.ts +159 -0
  70. package/src/editor/content-index.ts +1 -0
  71. package/src/editor/content.tsx +343 -0
  72. package/src/editor/editor.tsx +333 -0
  73. package/src/editor/emoji-index.ts +1 -0
  74. package/src/editor/emoji-picker.tsx +114 -0
  75. package/src/editor/emoji.ts +436 -0
  76. package/src/editor/index.ts +6 -0
  77. package/src/editor/sections.ts +83 -0
  78. package/src/editor/suggestion-popup.tsx +136 -0
  79. package/src/editor/suggestions.ts +309 -0
  80. package/src/editor/ui.tsx +171 -0
  81. package/src/errors/error-shell.tsx +72 -0
  82. package/src/errors/global-error-shell.tsx +116 -0
  83. package/src/errors/index.ts +2 -0
  84. package/src/grid/columns.ts +48 -0
  85. package/src/grid/compare.ts +35 -0
  86. package/src/grid/hidden-columns.ts +95 -0
  87. package/src/grid/index.ts +27 -0
  88. package/src/grid/use-grid.ts +282 -0
  89. package/src/grid/views.ts +70 -0
  90. package/src/guides/guide-article.tsx +92 -0
  91. package/src/guides/guide-figure-zoom.tsx +533 -0
  92. package/src/guides/guide-figure.tsx +68 -0
  93. package/src/guides/guide-toc.tsx +133 -0
  94. package/src/guides/guides-landing.tsx +57 -0
  95. package/src/guides/guides-search.tsx +160 -0
  96. package/src/guides/guides-shell.tsx +60 -0
  97. package/src/guides/guides-sidebar.tsx +93 -0
  98. package/src/guides/index.ts +28 -0
  99. package/src/guides/library.ts +165 -0
  100. package/src/health/health.ts +115 -0
  101. package/src/health/index.ts +11 -0
  102. package/src/internal/cx.ts +4 -0
  103. package/src/internal/next-link.ts +23 -0
  104. package/src/jobs/counts.ts +151 -0
  105. package/src/jobs/cron-auth.ts +60 -0
  106. package/src/jobs/health.ts +315 -0
  107. package/src/jobs/idle.ts +86 -0
  108. package/src/jobs/index.ts +120 -0
  109. package/src/jobs/job-health-list.tsx +316 -0
  110. package/src/jobs/next-index.ts +4 -0
  111. package/src/jobs/next.ts +65 -0
  112. package/src/jobs/prisma-index.ts +12 -0
  113. package/src/jobs/prisma.ts +170 -0
  114. package/src/jobs/prune.ts +79 -0
  115. package/src/jobs/react-index.ts +35 -0
  116. package/src/jobs/registry.ts +189 -0
  117. package/src/jobs/scheduler.ts +437 -0
  118. package/src/jobs/store.ts +212 -0
  119. package/src/jobs/windows.ts +157 -0
  120. package/src/maintenance/core.ts +270 -0
  121. package/src/maintenance/gate.ts +171 -0
  122. package/src/maintenance/index.ts +40 -0
  123. package/src/maintenance/page.ts +76 -0
  124. package/src/maintenance/proxy.ts +88 -0
  125. package/src/maintenance/react-index.ts +7 -0
  126. package/src/maintenance/react.tsx +190 -0
  127. package/src/maintenance/route.ts +82 -0
  128. package/src/maintenance/unavailable.ts +61 -0
  129. package/src/markdown/figure.tsx +132 -0
  130. package/src/markdown/figures.ts +237 -0
  131. package/src/markdown/guide.tsx +536 -0
  132. package/src/markdown/index.ts +53 -0
  133. package/src/markdown/table-view.tsx +74 -0
  134. package/src/markdown/table.ts +90 -0
  135. package/src/password/common.ts +58 -0
  136. package/src/password/estimate-index.ts +18 -0
  137. package/src/password/estimate.ts +715 -0
  138. package/src/password/index.ts +40 -0
  139. package/src/password/password-input.tsx +116 -0
  140. package/src/password/password-strength.tsx +157 -0
  141. package/src/password/reveal.ts +151 -0
  142. package/src/rate-limit/better-auth.ts +94 -0
  143. package/src/rate-limit/index.ts +32 -0
  144. package/src/rate-limit/keys.ts +110 -0
  145. package/src/rate-limit/limiter.ts +276 -0
  146. package/src/rate-limit/prisma-index.ts +12 -0
  147. package/src/rate-limit/prisma.ts +157 -0
  148. package/src/rate-limit/store.ts +47 -0
  149. package/src/release/changelog.ts +364 -0
  150. package/src/release/index.ts +32 -0
  151. package/src/release/version.ts +64 -0
  152. package/src/setup-guide/bits.tsx +420 -0
  153. package/src/setup-guide/card.tsx +358 -0
  154. package/src/setup-guide/class-names.ts +144 -0
  155. package/src/setup-guide/context.tsx +239 -0
  156. package/src/setup-guide/guide.ts +271 -0
  157. package/src/setup-guide/index.ts +76 -0
  158. package/src/setup-guide/launcher.tsx +207 -0
  159. package/src/setup-guide/strip.tsx +127 -0
  160. package/src/styles/house.css +403 -0
  161. package/src/trail/index.ts +12 -0
  162. package/src/trail/rules.ts +84 -0
  163. package/src/trail/trail.tsx +367 -0
  164. package/src/ux/errors.ts +32 -0
  165. package/src/ux/feedback.tsx +41 -0
  166. package/src/ux/index.ts +44 -0
  167. package/src/ux/navigation-index.ts +16 -0
  168. package/src/ux/navigation-progress.tsx +270 -0
  169. package/src/ux/optimistic.ts +415 -0
  170. package/src/ux/use-action.ts +155 -0
  171. package/src/ux/use-optimistic-list.ts +227 -0
  172. package/src/ux/use-optimistic-value.ts +136 -0
  173. package/src/web-search/index.ts +13 -0
  174. package/src/web-search/providers.ts +177 -0
  175. package/src/web-search/types.ts +98 -0
  176. package/src/whats-new/body.tsx +190 -0
  177. package/src/whats-new/index.ts +43 -0
  178. package/src/whats-new/seen.ts +40 -0
  179. package/src/whats-new/select.ts +230 -0
  180. package/src/whats-new/use-whats-new.ts +109 -0
  181. package/src/wizard/index.ts +61 -0
  182. package/src/wizard/invalid.ts +152 -0
  183. package/src/wizard/react-hook-form-index.ts +11 -0
  184. package/src/wizard/rhf-adapter.ts +67 -0
  185. package/src/wizard/rules.ts +137 -0
  186. package/src/wizard/wizard.tsx +442 -0
@@ -0,0 +1,403 @@
1
+ import type { BetterAuthPlugin } from "better-auth";
2
+ import {
3
+ APIError,
4
+ createAuthMiddleware,
5
+ getAuthoritativeSessionFromCtx,
6
+ getSessionFromCtx,
7
+ isAPIError,
8
+ } from "better-auth/api";
9
+
10
+ import { adminSignedIn, type AdminAuditEvent, type AdminAuditScope, type AdminSignInMethod } from "./audit.js";
11
+ import {
12
+ DEFAULT_ADMIN_PROOF_PREFIX,
13
+ adminProofIdentifier,
14
+ isLiveProof,
15
+ readVerificationValue,
16
+ type ProofContext,
17
+ type ProofRow,
18
+ } from "./proof.js";
19
+
20
+ /**
21
+ * Which administrators' sessions were made with a second factor — one Better Auth plugin for the six apps that each
22
+ * wrote their own (AltEd's `admin-second-factor.ts`, Quickie's `operator-access.ts`, and `second-factor-session.ts` in
23
+ * PharmaLine, PM Tool, senco and FB Web).
24
+ *
25
+ * Nothing on a Better Auth session says how it was made, so the plugin writes it down at the one moment it is known —
26
+ * Better Auth's own `session.create` database hook, which runs inside the endpoint creating the session — as a row in
27
+ * the `verification` table: `<recordPrefix><session id>`, the user's id as its value, expiring with the session as it
28
+ * was issued (not with its rolling extensions, so an administrator proves the factor again at least once a session
29
+ * lifetime). No request can write one. `adminAccess` reads it back.
30
+ *
31
+ * A session made by one of these proves the second factor, for an administrator:
32
+ *
33
+ * - `/two-factor/verify-totp` and `/two-factor/verify-backup-code` — the code at sign-in, after a password, an email
34
+ * link or a social sign-in (`secondFactorEverywhere()`); and the code that ends enrolment, which replaces the
35
+ * enrolling session with a new one;
36
+ * - `/passkey/verify-authentication` — possession of a device, and phishing-resistant;
37
+ * - `/sign-in/email` for an account with two-factor on (`trustedDeviceCounts`, default on — AltEd's rule): the
38
+ * two-factor plugin deletes that session straight after it is made unless the browser carries the trusted-device
39
+ * cookie, which only a correct code issues. A record for a deleted session matches nothing;
40
+ * - `/change-password` **inherits** the proof of the session it replaces (the request's own), and never outlives it.
41
+ *
42
+ * Anything else proves nothing — `/two-factor/verify-otp` (an emailed code is no second factor where email is already
43
+ * a way in), an email link or social sign-in on a trusted device, `/verify-email`, and any sign-in route a later
44
+ * Better Auth adds. Fail-closed by construction: no record, no administration.
45
+ *
46
+ * **Only `/change-password` inherits.** Every other route that mints a session for a signed-in account —
47
+ * `/passkey/verify-registration` with `createSession: true` (1.7), `/two-factor/disable`, `/two-factor/enable` with
48
+ * `skipVerificationOnEnable`, a social or email-link sign-in on a trusted device — proves nothing. FB Web's plugin
49
+ * let any of them inherit with a fresh lifetime, and a passkey registration's new session opened its admin tools.
50
+ *
51
+ * **A revoked session is refused on the factor-change routes, for everyone (401).** The routes' own checks believe the
52
+ * five-minute cookie cache, so a signed-out administrator's kept cookies could read the authenticator's secret.
53
+ *
54
+ * **The back door.** From a session without the record, an administrator's factors cannot change: re-keying two-factor
55
+ * (`/two-factor/enable` once it is on), reading its key (`/two-factor/get-totp-uri`), new backup codes, turning it off,
56
+ * or adding a passkey. Each would hand whoever holds a Google account or a mailbox — and the password — a factor that
57
+ * then writes the record. Turning two-factor on for the first time stays open, or nobody could get out of the
58
+ * refusal. An administrator adds a passkey only from a recorded session, so with two-factor still off, only after a
59
+ * passkey sign-in. `stepUp()` still applies on top, to everybody; either refusal stops a registration.
60
+ *
61
+ * **Order**: list it after `twoFactor()` and `secondFactorEverywhere()` — `onAdminSignedIn` must see the session
62
+ * their hooks leave standing, and `init` refuses to start otherwise — and before `stepUp()` and `nextCookies()`.
63
+ * Listed after `stepUp()`, step-up answers first, and an unproven administrator is asked to confirm it is them only
64
+ * to be refused straight after (AltEd).
65
+ */
66
+ export interface AdminSecondFactorSessionsOptions {
67
+ /** Whether this account is an administrator now — from the database, never the session payload. */
68
+ isAdmin: (userId: string) => boolean | null | undefined | Promise<boolean | null | undefined>;
69
+ /** The record's prefix. Default `admin-second-factor:`. An adopting app passes its own, so its records keep counting. */
70
+ recordPrefix?: string;
71
+ /** A password sign-in that a trusted device let skip the code counts, for an account with two-factor on. Default true. */
72
+ trustedDeviceCounts?: boolean;
73
+ /**
74
+ * Called for each session an administrator signs in with — proven or not — that is still standing when the response
75
+ * leaves; never for a password change or a two-factor change rotating the session. Cannot fail the sign-in: an error
76
+ * is logged. Runs in the background with Better Auth's `advanced.backgroundTasks`.
77
+ */
78
+ onAdminSignedIn?: (event: AdminAuditEvent, signIn: AdminSignIn) => void | Promise<void>;
79
+ /** The actor's standing in the sign-in event. Default `"admin"`. */
80
+ standing?: string;
81
+ /** The sign-in event's scope. Default platform. */
82
+ scope?: AdminAuditScope;
83
+ /** The refusals' words. */
84
+ messages?: { factorChange?: string; passkeyNeedsTwoFactor?: string };
85
+ }
86
+
87
+ export interface AdminSignIn {
88
+ userId: string;
89
+ sessionId: string;
90
+ method: AdminSignInMethod;
91
+ proven: boolean;
92
+ path: string;
93
+ request?: Request;
94
+ }
95
+
96
+ export const ADMIN_SECOND_FACTOR_SESSIONS_ID = "admin-second-factor-sessions";
97
+
98
+ /** Routes that create a session only after Better Auth has checked a second factor or a passkey. */
99
+ export const ADMIN_PROVING_PATHS: readonly string[] = [
100
+ "/two-factor/verify-totp",
101
+ "/two-factor/verify-backup-code",
102
+ "/passkey/verify-authentication",
103
+ ];
104
+
105
+ const PASSWORD_SIGN_IN = "/sign-in/email";
106
+ const CHANGE_PASSWORD = "/change-password";
107
+ const ENABLE = "/two-factor/enable";
108
+
109
+ /** Two-factor routes that change or read an administrator's factor. `enable` counts only once two-factor is on. */
110
+ export const ADMIN_TWO_FACTOR_CHANGE_PATHS: readonly string[] = [
111
+ ENABLE,
112
+ "/two-factor/disable",
113
+ "/two-factor/get-totp-uri",
114
+ "/two-factor/generate-backup-codes",
115
+ ];
116
+
117
+ export const ADMIN_PASSKEY_ADD_PATHS: readonly string[] = [
118
+ "/passkey/generate-register-options",
119
+ "/passkey/verify-registration",
120
+ ];
121
+
122
+ export const ADMIN_SECOND_FACTOR_ERROR_CODES = {
123
+ ADMIN_SECOND_FACTOR_REQUIRED: {
124
+ code: "ADMIN_SECOND_FACTOR_REQUIRED",
125
+ message:
126
+ "Changing an administrator’s two-factor or passkeys needs a sign-in that used your authenticator code or a passkey. Sign out, then sign in with your email, password and code — or with a passkey — and try again.",
127
+ },
128
+ ADMIN_PASSKEY_NEEDS_TWO_FACTOR: {
129
+ code: "ADMIN_PASSKEY_NEEDS_TWO_FACTOR",
130
+ message:
131
+ "Administrators add passkeys once two-factor authentication is on. Turn it on first, then sign in with your code and add the passkey.",
132
+ },
133
+ } as const;
134
+
135
+ const SOCIAL_PATHS = new Set(["/callback/:id", "/oauth2/callback/:providerId", "/sign-in/social", "/one-tap/callback"]);
136
+
137
+ function methodOf(path: string, proven: boolean): AdminSignInMethod {
138
+ switch (path) {
139
+ case "/two-factor/verify-totp":
140
+ return "code";
141
+ case "/two-factor/verify-backup-code":
142
+ return "backup-code";
143
+ case "/passkey/verify-authentication":
144
+ return "passkey";
145
+ case PASSWORD_SIGN_IN:
146
+ return proven ? "trusted-device" : "password";
147
+ case "/magic-link/verify":
148
+ return "email-link";
149
+ default:
150
+ return SOCIAL_PATHS.has(path) ? "social" : "other";
151
+ }
152
+ }
153
+
154
+ type Hooks = NonNullable<BetterAuthPlugin["hooks"]>;
155
+ type BeforeHook = NonNullable<Hooks["before"]>[number];
156
+ type AfterHook = NonNullable<Hooks["after"]>[number];
157
+ type InitContext = Parameters<NonNullable<BetterAuthPlugin["init"]>>[0];
158
+
159
+ interface SessionRow {
160
+ id: string;
161
+ userId: string;
162
+ expiresAt: Date | string;
163
+ ipAddress?: string | null;
164
+ userAgent?: string | null;
165
+ }
166
+
167
+ /** The slice of the endpoint context Better Auth hands a database hook that this reads. */
168
+ interface CreatingEndpoint {
169
+ path?: string;
170
+ context?: { session?: { session?: { id?: string; userId?: string } | null } | null } | null;
171
+ }
172
+
173
+ const toDate = (value: Date | string) => (value instanceof Date ? value : new Date(value));
174
+
175
+ /** An error the route answered with. A redirect — an email link landing, an OAuth callback — is an APIError too. */
176
+ function failed(returned: unknown): boolean {
177
+ if (!isAPIError(returned)) return false;
178
+ const status = (returned as { statusCode?: number }).statusCode ?? 500;
179
+ return status < 300 || status >= 400;
180
+ }
181
+
182
+ export function adminSecondFactorSessions(options: AdminSecondFactorSessionsOptions) {
183
+ if (typeof options?.isAdmin !== "function") {
184
+ throw new Error("[admin-second-factor] adminSecondFactorSessions needs `isAdmin(userId)`.");
185
+ }
186
+ const prefix = options.recordPrefix ?? DEFAULT_ADMIN_PROOF_PREFIX;
187
+ const trustedDeviceCounts = options.trustedDeviceCounts !== false;
188
+ const standing = options.standing ?? "admin";
189
+ const key = (sessionId: string) => adminProofIdentifier(prefix, sessionId);
190
+ const isAdmin = async (userId: string) => (await options.isAdmin(userId)) === true;
191
+
192
+ let auth: InitContext | null = null;
193
+
194
+ async function proofOf(sessionId: string, userId: string): Promise<ProofRow | null> {
195
+ // Read-only, like adminAccess: Better Auth's own reader deletes expired rows as it goes.
196
+ const row = await readVerificationValue(auth as unknown as ProofContext, key(sessionId));
197
+ return isLiveProof(row, userId) ? row : null;
198
+ }
199
+
200
+ /** Better Auth's `session.create.after`: write the record when the creating route proved the second factor. */
201
+ async function record(session: SessionRow, endpoint: CreatingEndpoint | null | undefined): Promise<void> {
202
+ const path = endpoint?.path;
203
+ if (!path || !auth) return;
204
+ const proving = ADMIN_PROVING_PATHS.includes(path);
205
+ const trusted = trustedDeviceCounts && path === PASSWORD_SIGN_IN;
206
+ const inherits = path === CHANGE_PASSWORD;
207
+ if (!proving && !trusted && !inherits) return;
208
+ try {
209
+ if (!(await isAdmin(session.userId))) return;
210
+
211
+ let expiresAt = toDate(session.expiresAt);
212
+ if (trusted) {
213
+ const user = (await auth.internalAdapter.findUserById(session.userId)) as {
214
+ twoFactorEnabled?: boolean | null;
215
+ } | null;
216
+ if (user?.twoFactorEnabled !== true) return;
217
+ }
218
+ if (inherits) {
219
+ // The session being replaced — the request's own — is already deleted by now, so its record is what's asked,
220
+ // not whether it is still live. Inherited, it lasts no longer than the proof it came from.
221
+ const previous = endpoint?.context?.session?.session;
222
+ if (!previous?.id || previous.userId !== session.userId || previous.id === session.id) return;
223
+ const proof = await proofOf(previous.id, session.userId);
224
+ if (!proof) return;
225
+ const until = toDate(proof.expiresAt);
226
+ if (until < expiresAt) expiresAt = until;
227
+ }
228
+
229
+ await auth.internalAdapter.createVerificationValue({
230
+ identifier: key(session.id),
231
+ value: session.userId,
232
+ expiresAt,
233
+ });
234
+ await sweep(session.userId);
235
+ } catch (error) {
236
+ // Without the record the administrator is asked to sign in again; failing the sign-in over a bookkeeping row
237
+ // would lock every account out instead.
238
+ auth.logger.error("[admin-second-factor] could not record how an administrator's session was made", error);
239
+ }
240
+ }
241
+
242
+ /** Sessions end on their own; their records are cleared here rather than by a job. */
243
+ async function sweep(userId: string): Promise<void> {
244
+ try {
245
+ await auth!.adapter.deleteMany({
246
+ model: "verification",
247
+ where: [
248
+ { field: "identifier", operator: "starts_with", value: prefix },
249
+ { field: "value", value: userId },
250
+ { field: "expiresAt", operator: "lte", value: new Date() },
251
+ ],
252
+ });
253
+ } catch {
254
+ // Housekeeping only.
255
+ }
256
+ }
257
+
258
+ const refuseFactorChange: BeforeHook = {
259
+ matcher: (ctx) => {
260
+ const path = ctx.path ?? "";
261
+ return ADMIN_TWO_FACTOR_CHANGE_PATHS.includes(path) || ADMIN_PASSKEY_ADD_PATHS.includes(path);
262
+ },
263
+ handler: createAuthMiddleware(async (ctx) => {
264
+ const live = (await getAuthoritativeSessionFromCtx(ctx)) as {
265
+ session: { id: string };
266
+ user: { id: string; twoFactorEnabled?: boolean | null };
267
+ } | null;
268
+ if (!live?.session) {
269
+ // The routes' own session checks (`sessionMiddleware`, `freshSessionMiddleware`) believe the cookie cache for
270
+ // minutes after a session is revoked or signed out — long enough for kept cookies to read the authenticator's
271
+ // secret, mint backup codes, re-key two-factor or register a passkey. So a cookie whose session row is gone or
272
+ // expired is refused here, for everyone. Only a request with no session at all (a passkey-first sign-up) is
273
+ // left to the route's own rules.
274
+ const cached = await getSessionFromCtx(ctx).catch(() => null);
275
+ if (cached?.session) {
276
+ throw new APIError("UNAUTHORIZED", { message: "Unauthorized", code: "UNAUTHORIZED" });
277
+ }
278
+ return;
279
+ }
280
+ if (!(await isAdmin(live.user.id))) return;
281
+
282
+ const twoFactorOn = live.user.twoFactorEnabled === true;
283
+ const addsPasskey = ADMIN_PASSKEY_ADD_PATHS.includes(ctx.path);
284
+ // Turning two-factor on for the first time is how an administrator gets out of administration's refusal.
285
+ if (ctx.path === ENABLE && !twoFactorOn) return;
286
+ if (await proofOf(live.session.id, live.user.id)) return;
287
+
288
+ const refusal =
289
+ addsPasskey && !twoFactorOn
290
+ ? ADMIN_SECOND_FACTOR_ERROR_CODES.ADMIN_PASSKEY_NEEDS_TWO_FACTOR
291
+ : ADMIN_SECOND_FACTOR_ERROR_CODES.ADMIN_SECOND_FACTOR_REQUIRED;
292
+ const message =
293
+ refusal.code === "ADMIN_PASSKEY_NEEDS_TWO_FACTOR"
294
+ ? (options.messages?.passkeyNeedsTwoFactor ?? refusal.message)
295
+ : (options.messages?.factorChange ?? refusal.message);
296
+ throw new APIError("FORBIDDEN", { code: refusal.code, message });
297
+ }),
298
+ };
299
+
300
+ const signedIn: AfterHook = {
301
+ matcher: () => !!options.onAdminSignedIn,
302
+ handler: createAuthMiddleware(async (ctx) => {
303
+ const notify = options.onAdminSignedIn;
304
+ // `newSession` is what the request leaves standing: the two-factor plugin (and `secondFactorEverywhere()`)
305
+ // clear it when they take the session away for the code screen.
306
+ const made = ctx.context.newSession as {
307
+ session: SessionRow;
308
+ user: { id: string; name?: string | null; email?: string; twoFactorEnabled?: boolean | null };
309
+ } | null;
310
+ if (!notify || !made?.session || failed(ctx.context.returned)) return;
311
+ const previous = (ctx.context.session as { session?: { id?: string }; user?: { id?: string } } | null) ?? null;
312
+ // A refresh keeps its id; a password or two-factor change rotates a signed-in session. Neither is a sign-in.
313
+ if (previous?.session?.id === made.session.id) return;
314
+ if (previous?.user?.id === made.session.userId && !ADMIN_PROVING_PATHS.includes(ctx.path)) return;
315
+ try {
316
+ if (!(await isAdmin(made.session.userId))) return;
317
+ // By the record's own rule rather than by reading the record: Better Auth 1.6 runs database after-hooks once
318
+ // the endpoint has finished, after this hook. A password change, the one inheriting route, is not reported.
319
+ const proven =
320
+ ADMIN_PROVING_PATHS.includes(ctx.path) ||
321
+ (trustedDeviceCounts && ctx.path === PASSWORD_SIGN_IN && made.user.twoFactorEnabled === true);
322
+ const method = methodOf(ctx.path, proven);
323
+ const event = adminSignedIn({
324
+ actor: { id: made.session.userId, name: made.user.name || made.user.email || made.session.userId, standing },
325
+ sessionId: made.session.id,
326
+ method,
327
+ proven,
328
+ ...(options.scope ? { scope: options.scope } : {}),
329
+ ip: made.session.ipAddress ?? null,
330
+ userAgent: made.session.userAgent ?? null,
331
+ });
332
+ const detail: AdminSignIn = {
333
+ userId: made.session.userId,
334
+ sessionId: made.session.id,
335
+ method,
336
+ proven,
337
+ path: ctx.path,
338
+ ...(ctx.request ? { request: ctx.request } : {}),
339
+ };
340
+ const logger = ctx.context.logger;
341
+ const run = (async () => {
342
+ try {
343
+ await notify(event, detail);
344
+ } catch (error) {
345
+ logger.error("[admin-second-factor] onAdminSignedIn failed; the sign-in stands", error);
346
+ }
347
+ })();
348
+ await ctx.context.runInBackgroundOrAwait(run);
349
+ } catch (error) {
350
+ ctx.context.logger.error("[admin-second-factor] could not describe an administrator's sign-in", error);
351
+ }
352
+ }),
353
+ };
354
+
355
+ return {
356
+ id: ADMIN_SECOND_FACTOR_SESSIONS_ID,
357
+ options: { ...options, recordPrefix: prefix, trustedDeviceCounts },
358
+ init(ctx) {
359
+ auth = ctx;
360
+ const plugins = ctx.options.plugins ?? [];
361
+ const own = plugins.findIndex((plugin) => plugin.id === ADMIN_SECOND_FACTOR_SESSIONS_ID);
362
+ const twoFactor = plugins.findIndex((plugin) => plugin.id === "two-factor");
363
+ const everywhere = plugins.findIndex((plugin) => plugin.id === "second-factor-everywhere");
364
+ if (twoFactor === -1) {
365
+ ctx.logger.warn(
366
+ "[admin-second-factor] no twoFactor() plugin is installed: only a passkey sign-in can prove the second factor.",
367
+ );
368
+ }
369
+ if (
370
+ options.onAdminSignedIn &&
371
+ ((twoFactor !== -1 && twoFactor > own) || (everywhere !== -1 && everywhere > own))
372
+ ) {
373
+ throw new Error(
374
+ "[admin-second-factor] list adminSecondFactorSessions() after twoFactor() and secondFactorEverywhere(): " +
375
+ "onAdminSignedIn has to see the session their hooks leave standing, or it would record a sign-in that is " +
376
+ "still waiting for its code.",
377
+ );
378
+ }
379
+ const nextCookies = plugins.findIndex((plugin) => plugin.id === "next-cookies");
380
+ if (nextCookies !== -1 && nextCookies < own) {
381
+ ctx.logger.warn("[admin-second-factor] is listed after nextCookies(); list it before.");
382
+ }
383
+ return {
384
+ options: {
385
+ databaseHooks: {
386
+ session: {
387
+ create: {
388
+ after: async (session: SessionRow, endpoint: unknown) => {
389
+ await record(session, endpoint as CreatingEndpoint | null);
390
+ },
391
+ },
392
+ },
393
+ },
394
+ },
395
+ };
396
+ },
397
+ hooks: {
398
+ before: [refuseFactorChange],
399
+ after: [signedIn],
400
+ },
401
+ $ERROR_CODES: ADMIN_SECOND_FACTOR_ERROR_CODES,
402
+ } satisfies BetterAuthPlugin;
403
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * `@connextar/house/admin/testing` — Node helpers for an app's own tests: the guard-coverage sweep, and a cookie store
3
+ * for exercising "view as". Reads the file system, so it belongs in tests and nowhere else.
4
+ */
5
+ export {
6
+ AdminGuardCoverageError,
7
+ assertAdminGuardCoverage,
8
+ checkAdminGuardCoverage,
9
+ memoryCookieJar,
10
+ stripComments,
11
+ type AdminGuardCoverageOptions,
12
+ type AdminGuardCoverageReport,
13
+ } from "./testing.js";