@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,220 @@
1
+ import { roleChanged, type AdminAuditEvent, type AdminAuditScope, type AdminAuditSink } from "./audit.js";
2
+
3
+ /**
4
+ * Grant — or revoke — the first administrator, from a script.
5
+ *
6
+ * Nothing inside a product can make an administrator, deliberately: sign-up cannot ask for the flag and no screen
7
+ * grants it to yourself. That leaves exactly one gap, a fresh deployment with nobody to open the door, and every app
8
+ * closes it with a script. AltEd's and PM Tool's disagreed on the part that matters:
9
+ *
10
+ * - **An administrator already exists → refused**, unless forced. A second one is ordinary work for the first,
11
+ * through a screen where it is audited and attributed. Both.
12
+ * - **The account must already have two-factor on → refused otherwise** (PM Tool). An administrator account without a
13
+ * second factor can be enrolled by whoever first holds its mailbox or a session, and the code they enrolled would
14
+ * then open administration. So the person signs up and turns two-factor on first, then this is run. AltEd promoted
15
+ * anybody, and created the account if it was missing.
16
+ * - **The account must exist, be verified, and not be deleted** (PM Tool). An unverified row may be somebody else's
17
+ * sign-up with this address and a password of their choosing.
18
+ * - **Every run is recorded** — the grant, the revoke, and the refusal. AltEd recorded its grant; PM Tool nothing.
19
+ *
20
+ * `allowWithoutTwoFactor` is the documented first-run escape, for a deployment whose only way to turn two-factor on is
21
+ * behind administration. It works only while there is no administrator at all, and the event says it was used.
22
+ * `adminAccess` still refuses that administrator until they turn two-factor on and sign in with it.
23
+ */
24
+
25
+ export interface BootstrapUser {
26
+ id: string;
27
+ email: string;
28
+ name?: string | null;
29
+ isAdmin: boolean;
30
+ /** Omit when the app has no verification step. */
31
+ emailVerified?: boolean | null;
32
+ /** Soft-deleted. */
33
+ deleted?: boolean | null;
34
+ }
35
+
36
+ export interface BootstrapAdminDeps {
37
+ /** By email, lower-cased. */
38
+ findUser(email: string): Promise<BootstrapUser | null | undefined>;
39
+ /** Administrators that exist now, not counting deleted accounts. */
40
+ countAdmins(): Promise<number>;
41
+ setAdmin(userId: string, isAdmin: boolean): Promise<void>;
42
+ twoFactorEnabled(userId: string): Promise<boolean | null | undefined>;
43
+ audit: AdminAuditSink;
44
+ }
45
+
46
+ export interface BootstrapAdminRequest {
47
+ email: string;
48
+ /** Grant although an administrator exists. */
49
+ force?: boolean;
50
+ /** Take the standing away instead. */
51
+ revoke?: boolean;
52
+ /** The first-run escape. See above. */
53
+ allowWithoutTwoFactor?: boolean;
54
+ /** The standing's name in the event: `"platform-admin"`, `"ADMIN"`. Default `"admin"`. */
55
+ standing?: string;
56
+ /** What the account had before, in the event. Default `"user"`. */
57
+ previousStanding?: string;
58
+ /** Default platform. */
59
+ scope?: AdminAuditScope;
60
+ /** The script's name in the event. Default `"bootstrap-admin"`. */
61
+ via?: string;
62
+ }
63
+
64
+ export type BootstrapRefusalReason =
65
+ | "invalid-email"
66
+ | "no-account"
67
+ | "deleted"
68
+ | "unverified"
69
+ | "already-admin"
70
+ | "not-admin"
71
+ | "admin-exists"
72
+ | "two-factor-off"
73
+ | "escape-not-first-run";
74
+
75
+ export type BootstrapAdminResult =
76
+ | { ok: true; outcome: "granted" | "revoked"; user: BootstrapUser; message: string; event: AdminAuditEvent }
77
+ | { ok: false; reason: BootstrapRefusalReason; message: string; event: AdminAuditEvent };
78
+
79
+ export async function bootstrapAdmin(
80
+ deps: BootstrapAdminDeps,
81
+ request: BootstrapAdminRequest,
82
+ ): Promise<BootstrapAdminResult> {
83
+ const email = request.email?.trim().toLowerCase() ?? "";
84
+ const standing = request.standing ?? "admin";
85
+ const previous = request.previousStanding ?? "user";
86
+ const via = request.via ?? "bootstrap-admin";
87
+ const scope = request.scope ?? { kind: "platform" as const };
88
+
89
+ async function refuse(
90
+ reason: BootstrapRefusalReason,
91
+ message: string,
92
+ user?: BootstrapUser | null,
93
+ ): Promise<BootstrapAdminResult> {
94
+ const event: AdminAuditEvent = {
95
+ action: "admin.bootstrap_refused",
96
+ actor: null,
97
+ scope,
98
+ entity: { type: "user", id: user?.id ?? null },
99
+ summary:
100
+ `Refused to ${request.revoke ? "revoke" : "grant"} ${standing} for ${email || "(no email)"} (${via}): ${reason}`.slice(
101
+ 0,
102
+ 300,
103
+ ),
104
+ changes: { reason, email, revoke: !!request.revoke, force: !!request.force, via },
105
+ at: new Date(),
106
+ };
107
+ await record(event);
108
+ return { ok: false, reason, message, event };
109
+ }
110
+
111
+ async function record(event: AdminAuditEvent) {
112
+ try {
113
+ await deps.audit(event);
114
+ } catch (error) {
115
+ // A script is run by a person watching it: say so loudly, rather than swallow it as a request would.
116
+ throw new Error(
117
+ `[admin] ${event.action} could not be recorded in the audit trail: ${error instanceof Error ? error.message : String(error)}`,
118
+ { cause: error },
119
+ );
120
+ }
121
+ }
122
+
123
+ if (!email || !/^[^\s@]+@[^\s@]+$/.test(email)) {
124
+ return refuse("invalid-email", "Give the email address of the account to make an administrator.");
125
+ }
126
+
127
+ const user = await deps.findUser(email);
128
+ if (!user) {
129
+ return refuse(
130
+ "no-account",
131
+ `No account for ${email}. They sign up first, turn on two-factor authentication in their security settings, then run this again.`,
132
+ );
133
+ }
134
+ if (user.deleted) return refuse("deleted", `${email} belongs to a deleted account. Restore it first.`, user);
135
+
136
+ if (request.revoke) {
137
+ if (!user.isAdmin) return refuse("not-admin", `${email} is not an administrator.`, user);
138
+ await deps.setAdmin(user.id, false);
139
+ const event = roleChanged({ actor: null, target: user, from: standing, to: previous, scope, via });
140
+ await record(event);
141
+ return { ok: true, outcome: "revoked", user, message: `${email} is no longer an administrator.`, event };
142
+ }
143
+
144
+ if (user.isAdmin) return refuse("already-admin", `${email} is already an administrator. Nothing was changed.`, user);
145
+ if (user.emailVerified === false) {
146
+ return refuse(
147
+ "unverified",
148
+ `${email} has not been verified. Sign in once with a link to that address, then run this again.`,
149
+ user,
150
+ );
151
+ }
152
+
153
+ const admins = await deps.countAdmins();
154
+ if (admins > 0 && !request.force) {
155
+ return refuse(
156
+ "admin-exists",
157
+ `This deployment already has ${admins} administrator${admins === 1 ? "" : "s"}. Grant further administrators ` +
158
+ "from the screen built for it, where the change is audited. Pass --force only if you are locked out.",
159
+ user,
160
+ );
161
+ }
162
+
163
+ const twoFactor = (await deps.twoFactorEnabled(user.id)) === true;
164
+ const escape = !twoFactor && request.allowWithoutTwoFactor === true;
165
+ if (!twoFactor) {
166
+ if (!request.allowWithoutTwoFactor) {
167
+ return refuse(
168
+ "two-factor-off",
169
+ `${email} hasn't turned on two-factor authentication. They turn it on first, then run this again.`,
170
+ user,
171
+ );
172
+ }
173
+ if (admins > 0) {
174
+ return refuse(
175
+ "escape-not-first-run",
176
+ "--allow-without-two-factor is only for the first administrator of a deployment, and this one has one.",
177
+ user,
178
+ );
179
+ }
180
+ }
181
+
182
+ await deps.setAdmin(user.id, true);
183
+ const event = roleChanged({
184
+ actor: null,
185
+ target: user,
186
+ from: previous,
187
+ to: standing,
188
+ scope,
189
+ via,
190
+ changes: { forced: !!request.force, ...(escape ? { withoutTwoFactor: true } : {}) },
191
+ });
192
+ await record(event);
193
+ return {
194
+ ok: true,
195
+ outcome: "granted",
196
+ user,
197
+ message: escape
198
+ ? `${email} is now an administrator, without two-factor (first-run escape). Administration stays closed to them until they turn it on and sign in with it.`
199
+ : `${email} is now an administrator. They sign in with their password and code, or a passkey, to open administration.`,
200
+ event,
201
+ };
202
+ }
203
+
204
+ /**
205
+ * The script's arguments: `you@example.com`, `--force`, `--revoke`, `--allow-without-two-factor`. Anything else
206
+ * starting with `--` is an error, so a typo never quietly grants without the flag that was meant.
207
+ */
208
+ export function bootstrapAdminArgs(argv: readonly string[]): BootstrapAdminRequest & { rest: string[] } {
209
+ const flags = new Set(["--force", "--revoke", "--allow-without-two-factor"]);
210
+ const unknown = argv.filter((arg) => arg.startsWith("--") && !flags.has(arg));
211
+ if (unknown.length) throw new Error(`Unknown option${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}`);
212
+ const [email = "", ...rest] = argv.filter((arg) => !arg.startsWith("--"));
213
+ return {
214
+ email,
215
+ force: argv.includes("--force"),
216
+ revoke: argv.includes("--revoke"),
217
+ allowWithoutTwoFactor: argv.includes("--allow-without-two-factor"),
218
+ rest,
219
+ };
220
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * `@connextar/house/admin/client` — the refusal notice and the "view as" banner, on the shared theme tokens. Imports
3
+ * nothing of the server half at runtime: the refusal's type only.
4
+ */
5
+ export {
6
+ ADMIN_REFUSAL_ACTION_LABELS,
7
+ ADMIN_REFUSAL_NOTICE_CLASS_NAMES,
8
+ ADMIN_REFUSAL_TITLES,
9
+ AdminRefusalNotice,
10
+ VIEWING_AS_BANNER_CLASS_NAMES,
11
+ VIEWING_AS_BANNER_LABELS,
12
+ ViewingAsBanner,
13
+ type AdminRefusalNoticeClassNames,
14
+ type AdminRefusalNoticeProps,
15
+ type ViewingAsBannerClassNames,
16
+ type ViewingAsBannerLabels,
17
+ type ViewingAsBannerProps,
18
+ } from "./client.js";
19
+ export type { AdminRefusal, AdminRefusalReason } from "./access.js";
@@ -0,0 +1,187 @@
1
+ "use client";
2
+
3
+ import { Eye, ShieldAlert } from "lucide-react";
4
+ import * as React from "react";
5
+
6
+ import { cx } from "../internal/cx.js";
7
+ import { useActionReporter } from "../ux/feedback.js";
8
+ import type { AdminRefusal, AdminRefusalReason } from "./access.js";
9
+
10
+ /** What the notice's link says, per reason. */
11
+ export const ADMIN_REFUSAL_ACTION_LABELS: Record<AdminRefusalReason, string> = {
12
+ "signed-out": "Sign in",
13
+ "session-ended": "Sign in again",
14
+ "not-admin": "Go back",
15
+ "two-factor-off": "Set up two-factor",
16
+ "sign-in-without-second-factor": "Sign in with your code",
17
+ "viewing-as": "Stop viewing",
18
+ };
19
+
20
+ export const ADMIN_REFUSAL_TITLES: Record<AdminRefusalReason, string> = {
21
+ "signed-out": "You’re signed out",
22
+ "session-ended": "This sign-in has ended",
23
+ "not-admin": "Administrators only",
24
+ "two-factor-off": "Administration needs two-factor",
25
+ "sign-in-without-second-factor": "Sign in with your second factor",
26
+ "viewing-as": "You’re viewing as somebody else",
27
+ };
28
+
29
+ export interface AdminRefusalNoticeClassNames {
30
+ root: string;
31
+ icon: string;
32
+ body: string;
33
+ title: string;
34
+ message: string;
35
+ action: string;
36
+ }
37
+
38
+ /** The house look, on the shared theme tokens. */
39
+ export const ADMIN_REFUSAL_NOTICE_CLASS_NAMES: AdminRefusalNoticeClassNames = {
40
+ root: "flex items-start gap-3 rounded-lg border border-destructive/40 bg-destructive/5 p-4 text-sm",
41
+ icon: "mt-0.5 size-4 shrink-0 text-destructive",
42
+ body: "flex min-w-0 flex-1 flex-col gap-1",
43
+ title: "font-medium text-foreground",
44
+ message: "text-muted-foreground",
45
+ action:
46
+ "mt-1 inline-flex w-fit items-center rounded-md border border-border px-2.5 py-1 text-xs font-medium text-foreground transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",
47
+ };
48
+
49
+ export interface AdminRefusalNoticeProps {
50
+ /** From `adminAccess().check()`, `adminRefusalFromParam(searchParams.admin)`, or a refused route's answer. */
51
+ refusal: Pick<AdminRefusal, "reason" | "message" | "fixHref"> | null | undefined;
52
+ /** The link's words, per reason. */
53
+ labels?: Partial<Record<AdminRefusalReason, string>>;
54
+ /** The heading, per reason. */
55
+ titles?: Partial<Record<AdminRefusalReason, string>>;
56
+ className?: string;
57
+ classNames?: Partial<AdminRefusalNoticeClassNames>;
58
+ }
59
+
60
+ /**
61
+ * Why administration is refused, in the same words the routes refuse with, and the one thing to do about it. Draws
62
+ * nothing without a refusal, so a settings page can render it unconditionally from its `?admin=` parameter.
63
+ */
64
+ export function AdminRefusalNotice({ refusal, labels, titles, className, classNames }: AdminRefusalNoticeProps) {
65
+ if (!refusal) return null;
66
+ const c: AdminRefusalNoticeClassNames = { ...ADMIN_REFUSAL_NOTICE_CLASS_NAMES, ...classNames };
67
+ const title = titles?.[refusal.reason] ?? ADMIN_REFUSAL_TITLES[refusal.reason];
68
+ const label = labels?.[refusal.reason] ?? ADMIN_REFUSAL_ACTION_LABELS[refusal.reason];
69
+ return (
70
+ <div role="alert" data-reason={refusal.reason} className={cx(c.root, className)}>
71
+ <ShieldAlert aria-hidden="true" className={c.icon} />
72
+ <div className={c.body}>
73
+ <p className={c.title}>{title}</p>
74
+ <p className={c.message}>{refusal.message}</p>
75
+ {refusal.fixHref ? (
76
+ <a href={refusal.fixHref} className={c.action}>
77
+ {label}
78
+ </a>
79
+ ) : null}
80
+ </div>
81
+ </div>
82
+ );
83
+ }
84
+
85
+ export interface ViewingAsBannerClassNames {
86
+ root: string;
87
+ icon: string;
88
+ message: string;
89
+ until: string;
90
+ stop: string;
91
+ }
92
+
93
+ export const VIEWING_AS_BANNER_CLASS_NAMES: ViewingAsBannerClassNames = {
94
+ root: "sticky top-0 z-50 flex flex-wrap items-center justify-center gap-x-3 gap-y-1 border-b border-primary/30 bg-primary px-4 py-2 text-sm text-primary-foreground print:hidden",
95
+ icon: "size-4 shrink-0",
96
+ message: "font-medium",
97
+ until: "text-primary-foreground/80",
98
+ stop: "inline-flex items-center rounded-md border border-primary-foreground/40 px-2.5 py-0.5 text-xs font-medium transition-colors hover:bg-primary-foreground/10 focus-visible:ring-2 focus-visible:ring-primary-foreground focus-visible:outline-none disabled:pointer-events-none disabled:opacity-60",
99
+ };
100
+
101
+ export interface ViewingAsBannerLabels {
102
+ /** Default: "You’re viewing as {name}. Nothing can be changed until you stop." */
103
+ message: (name: string) => string;
104
+ /** Default: "Ends at {time}". */
105
+ until: (time: string) => string;
106
+ stop: string;
107
+ stopping: string;
108
+ /** The error toast's title when stopping fails. */
109
+ failed: string;
110
+ }
111
+
112
+ export const VIEWING_AS_BANNER_LABELS: ViewingAsBannerLabels = {
113
+ message: (name) => `You’re viewing as ${name}. Nothing can be changed until you stop.`,
114
+ until: (time) => `Ends at ${time}`,
115
+ stop: "Stop viewing",
116
+ stopping: "Stopping…",
117
+ failed: "Could not stop viewing",
118
+ };
119
+
120
+ export interface ViewingAsBannerProps {
121
+ /** The person being viewed. */
122
+ name: string;
123
+ /** When the view lapses on its own. */
124
+ expiresAt?: Date | string | null;
125
+ /**
126
+ * End the view — `DELETE /api/admin/view-as`, then a reload or `router.refresh()`. Throw to refuse: the banner stays
127
+ * and the reason is reported through the app's `ActionFeedbackProvider`.
128
+ */
129
+ onStop: () => void | Promise<void>;
130
+ labels?: Partial<ViewingAsBannerLabels>;
131
+ /** For the end time. Default the browser's. */
132
+ locale?: string;
133
+ timeZone?: string;
134
+ className?: string;
135
+ classNames?: Partial<ViewingAsBannerClassNames>;
136
+ }
137
+
138
+ /**
139
+ * Above every page while a view is in force, and it cannot be dismissed: the only way to make it go is to stop.
140
+ * Loud on purpose — the screens below look exactly like the person's own.
141
+ */
142
+ export function ViewingAsBanner({
143
+ name,
144
+ expiresAt,
145
+ onStop,
146
+ labels,
147
+ locale,
148
+ timeZone,
149
+ className,
150
+ classNames,
151
+ }: ViewingAsBannerProps) {
152
+ const c: ViewingAsBannerClassNames = { ...VIEWING_AS_BANNER_CLASS_NAMES, ...classNames };
153
+ const words: ViewingAsBannerLabels = { ...VIEWING_AS_BANNER_LABELS, ...labels };
154
+ const report = useActionReporter();
155
+ const [stopping, setStopping] = React.useState(false);
156
+ const until = expiresAt ? new Date(expiresAt) : null;
157
+ const time =
158
+ until && !Number.isNaN(until.getTime())
159
+ ? until.toLocaleTimeString(locale, { hour: "numeric", minute: "2-digit", ...(timeZone ? { timeZone } : {}) })
160
+ : null;
161
+
162
+ async function stop() {
163
+ setStopping(true);
164
+ try {
165
+ await onStop();
166
+ } catch (error) {
167
+ report({
168
+ tone: "error",
169
+ title: words.failed,
170
+ ...(error instanceof Error && error.message ? { description: error.message } : {}),
171
+ });
172
+ } finally {
173
+ setStopping(false);
174
+ }
175
+ }
176
+
177
+ return (
178
+ <div role="status" aria-live="polite" data-viewing-as="" className={cx(c.root, className)}>
179
+ <Eye aria-hidden="true" className={c.icon} />
180
+ <span className={c.message}>{words.message(name)}</span>
181
+ {time ? <span className={c.until}>{words.until(time)}</span> : null}
182
+ <button type="button" className={c.stop} onClick={() => void stop()} disabled={stopping} aria-busy={stopping}>
183
+ {stopping ? words.stopping : words.stop}
184
+ </button>
185
+ </div>
186
+ );
187
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * `@connextar/house/admin` — the server half of administration: who may use it, "view as", the audit event shape and
3
+ * the bootstrap script's rules. Imports no Better Auth and no Prisma — every lookup is injected — and nothing but
4
+ * `node:crypto`, so an app with its own auth (Canisters) takes the decision, the audit shape and "view as" as they
5
+ * are. The Better Auth plugin that records second-factor sign-ins is `@connextar/house/admin/second-factor`; the
6
+ * notice and the banner are `@connextar/house/admin/client`; the guard-coverage sweep is `@connextar/house/admin/testing`.
7
+ */
8
+ export {
9
+ ADMIN_REFUSAL_REASONS,
10
+ AdminRefusalError,
11
+ DEFAULT_ADMIN_REFUSAL_WORDS,
12
+ adminAccess,
13
+ adminRefusal,
14
+ adminRefusalFromParam,
15
+ assertAdminAccess,
16
+ decideAdminAccess,
17
+ type AdminAccess,
18
+ type AdminAccessDecision,
19
+ type AdminAccessFacts,
20
+ type AdminAccessLookups,
21
+ type AdminAccessOptions,
22
+ type AdminRefusal,
23
+ type AdminRefusalReason,
24
+ type AdminRefusalWording,
25
+ type AdminRefusalWords,
26
+ type SignedIn,
27
+ } from "./access.js";
28
+ export {
29
+ PLATFORM_SCOPE,
30
+ SUMMARY_MAX,
31
+ adminSignedIn,
32
+ emitSafely,
33
+ platformAction,
34
+ requestMeta,
35
+ roleChanged,
36
+ viewAsStarted,
37
+ viewAsStopped,
38
+ type AdminAuditActor,
39
+ type AdminAuditEvent,
40
+ type AdminAuditScope,
41
+ type AdminAuditSink,
42
+ type AdminSignInMethod,
43
+ type AuditLogger,
44
+ type RequestMeta,
45
+ } from "./audit.js";
46
+ export {
47
+ bootstrapAdmin,
48
+ bootstrapAdminArgs,
49
+ type BootstrapAdminDeps,
50
+ type BootstrapAdminRequest,
51
+ type BootstrapAdminResult,
52
+ type BootstrapRefusalReason,
53
+ type BootstrapUser,
54
+ } from "./bootstrap.js";
55
+ export {
56
+ DEFAULT_ADMIN_PROOF_PREFIX,
57
+ adminProofIdentifier,
58
+ isLiveProof,
59
+ readVerificationValue,
60
+ sessionProofReader,
61
+ type AuthWithProofs,
62
+ type ProofContext,
63
+ type ProofRow,
64
+ type StoreIdentifierOption,
65
+ } from "./proof.js";
66
+ export {
67
+ PRISMA_WRITE_OPERATIONS,
68
+ allowWhileViewing,
69
+ cookieJarFromHeaders,
70
+ refuseWhileViewingAs,
71
+ viewAs,
72
+ viewAsWriteGuard,
73
+ viewingAsGate,
74
+ viewingAsMessage,
75
+ type CookieJar,
76
+ type MaybeViewing,
77
+ type PrismaOperationParams,
78
+ type RealAdmin,
79
+ type RefuseWhileViewingAsOptions,
80
+ type ViewAs,
81
+ type ViewAsCookieOptions,
82
+ type ViewAsOptions,
83
+ type ViewAsStartRefusal,
84
+ type ViewAsStartResult,
85
+ type ViewAsWriteGuardOptions,
86
+ type ViewingAs,
87
+ type ViewingAsGate,
88
+ type ViewingAsGateOptions,
89
+ type ViewingAsWords,
90
+ type ViewingLookup,
91
+ } from "./view-as.js";
@@ -0,0 +1,155 @@
1
+ /**
2
+ * The record that says a session was made with a second factor — shared by the Better Auth plugin that writes it
3
+ * (`@connextar/house/admin/second-factor`) and `adminAccess`, which reads it. Nothing here imports Better Auth: the
4
+ * reader takes the instance structurally, so `@connextar/house/admin` loads in an app without it.
5
+ *
6
+ * It is a row in Better Auth's own `verification` table — `<prefix><session id>`, the user's id as its value,
7
+ * expiring with the session it was written for — the table, and the shape, Better Auth keeps its trusted-device
8
+ * records in. Six apps wrote one each, under three prefixes; an app adopting the shared plugin passes its own prefix,
9
+ * so the sessions it already recorded keep counting.
10
+ *
11
+ * **Read-only.** Better Auth's own `internalAdapter.findVerificationValue` deletes every expired verification row each
12
+ * time it reads one (its cleanup, unless `verification.disableCleanup`). Under "view as" the write guard refuses that
13
+ * delete, so the administrator's check failed with "You're viewing as …" and the view could never be honoured — PM
14
+ * Tool, senco and MAS each read the row from Prisma themselves to get round it. The reader here asks the same places
15
+ * Better Auth would, in the same order, and never writes.
16
+ */
17
+
18
+ /** AltEd's and PharmaLine's prefix. Quickie's is `operator-second-factor-`; senco's, PM Tool's and FB Web's `second-factor-session:`. */
19
+ export const DEFAULT_ADMIN_PROOF_PREFIX = "admin-second-factor:";
20
+
21
+ export const adminProofIdentifier = (prefix: string, sessionId: string) => `${prefix}${sessionId}`;
22
+
23
+ /** A `verification` row, as Better Auth's adapter answers it. */
24
+ export interface ProofRow {
25
+ value: string;
26
+ expiresAt: Date | string;
27
+ }
28
+
29
+ type Where = { field: string; value: string };
30
+
31
+ /** How Better Auth stores a verification identifier: `verification.storeIdentifier`. */
32
+ export type StoreIdentifierOption =
33
+ | "plain"
34
+ | "hashed"
35
+ | { hash: (identifier: string) => string | Promise<string> }
36
+ | {
37
+ default: StoreIdentifierOption;
38
+ overrides?: Record<string, StoreIdentifierOption>;
39
+ };
40
+
41
+ /** The parts of Better Auth's context the reader uses — all present on 1.6 and 1.7. */
42
+ export interface ProofContext {
43
+ /** The database adapter. Only `findMany` is called. */
44
+ adapter: {
45
+ findMany(query: {
46
+ model: string;
47
+ where: Where[];
48
+ sortBy?: { field: string; direction: "asc" | "desc" };
49
+ limit?: number;
50
+ }): Promise<unknown[]>;
51
+ };
52
+ /** Better Auth's `secondaryStorage`, when the app has one. Only `get` is called. */
53
+ secondaryStorage?: { get(key: string): unknown } | null;
54
+ /** Better Auth's options; `verification.storeIdentifier` and `verification.storeInDatabase` are read. */
55
+ options?: unknown;
56
+ }
57
+
58
+ interface VerificationOptions {
59
+ verification?: { storeIdentifier?: StoreIdentifierOption; storeInDatabase?: boolean } | null;
60
+ }
61
+
62
+ /** The part of a Better Auth instance the reader needs: `auth.$context` — the instance itself, or `ctx.context`. */
63
+ export interface AuthWithProofs {
64
+ $context: PromiseLike<ProofContext>;
65
+ }
66
+
67
+ const toTime = (value: Date | string) => (value instanceof Date ? value.getTime() : new Date(value).getTime());
68
+
69
+ /** Whether a row is a live proof for this user: it names them and has not expired. */
70
+ export function isLiveProof(row: ProofRow | null | undefined, userId: string, now = Date.now()): boolean {
71
+ return !!row && row.value === userId && toTime(row.expiresAt) > now;
72
+ }
73
+
74
+ function storageOption(
75
+ identifier: string,
76
+ config: StoreIdentifierOption | undefined,
77
+ ): StoreIdentifierOption | undefined {
78
+ if (!config) return undefined;
79
+ if (typeof config === "object" && "default" in config) {
80
+ for (const [prefix, option] of Object.entries(config.overrides ?? {})) {
81
+ if (identifier.startsWith(prefix)) return option;
82
+ }
83
+ return config.default;
84
+ }
85
+ return config;
86
+ }
87
+
88
+ /** Better Auth's `processIdentifier`: SHA-256, base64url without padding, for `"hashed"`. */
89
+ async function stored(identifier: string, option: StoreIdentifierOption | undefined): Promise<string> {
90
+ if (!option || option === "plain") return identifier;
91
+ if (option === "hashed") {
92
+ // Web Crypto, as Better Auth hashes: no `node:crypto`, so `/admin/second-factor` reaches Better Auth and nothing else.
93
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(identifier));
94
+ return btoa(String.fromCharCode(...new Uint8Array(digest)))
95
+ .replace(/\+/g, "-")
96
+ .replace(/\//g, "_")
97
+ .replace(/=+$/, "");
98
+ }
99
+ if (typeof option === "object" && "hash" in option) return option.hash(identifier);
100
+ return identifier;
101
+ }
102
+
103
+ function parse(cached: unknown): ProofRow | null {
104
+ if (!cached) return null;
105
+ if (typeof cached === "object") return cached as ProofRow;
106
+ if (typeof cached !== "string") return null;
107
+ try {
108
+ return JSON.parse(cached) as ProofRow;
109
+ } catch {
110
+ return null;
111
+ }
112
+ }
113
+
114
+ /**
115
+ * One verification row by identifier, as `findVerificationValue` finds it — the secondary storage first, then the
116
+ * newest database row, under the stored (possibly hashed) identifier and then the plain one — without its cleanup.
117
+ */
118
+ export async function readVerificationValue(context: ProofContext, identifier: string): Promise<ProofRow | null> {
119
+ const verification = (context.options as VerificationOptions | null | undefined)?.verification ?? undefined;
120
+ const option = storageOption(identifier, verification?.storeIdentifier);
121
+ const storedIdentifier = await stored(identifier, option);
122
+ const hashed = !!option && option !== "plain";
123
+
124
+ if (context.secondaryStorage) {
125
+ const cached = parse(await context.secondaryStorage.get(`verification:${storedIdentifier}`));
126
+ if (cached) return cached;
127
+ if (hashed) {
128
+ const plain = parse(await context.secondaryStorage.get(`verification:${identifier}`));
129
+ if (plain) return plain;
130
+ }
131
+ if (!verification?.storeInDatabase) return null;
132
+ }
133
+
134
+ const find = async (id: string) =>
135
+ (await context.adapter.findMany({
136
+ model: "verification",
137
+ where: [{ field: "identifier", value: id }],
138
+ sortBy: { field: "createdAt", direction: "desc" },
139
+ limit: 1,
140
+ })) as ProofRow[];
141
+ let rows = await find(storedIdentifier);
142
+ if (!rows.length && hashed) rows = await find(identifier);
143
+ return rows[0] ?? null;
144
+ }
145
+
146
+ /**
147
+ * `sessionProven(sessionId, userId)` read from the plugin's record, from where Better Auth keeps it — and only read:
148
+ * it is asked under "view as", where the write guard refuses Better Auth's cleanup of expired rows.
149
+ */
150
+ export function sessionProofReader(auth: AuthWithProofs, recordPrefix: string = DEFAULT_ADMIN_PROOF_PREFIX) {
151
+ return async (sessionId: string, userId: string): Promise<boolean> => {
152
+ const context = await auth.$context;
153
+ return isLiveProof(await readVerificationValue(context, adminProofIdentifier(recordPrefix, sessionId)), userId);
154
+ };
155
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * `@connextar/house/admin/second-factor` — the Better Auth plugin that records which administrators' sessions were
3
+ * made with a second factor, and refuses an administrator's factor change from a session that wasn't. Its own entry
4
+ * point so `@connextar/house/admin` stays free of Better Auth for an app with its own auth.
5
+ */
6
+ export {
7
+ ADMIN_PASSKEY_ADD_PATHS,
8
+ ADMIN_PROVING_PATHS,
9
+ ADMIN_SECOND_FACTOR_ERROR_CODES,
10
+ ADMIN_SECOND_FACTOR_SESSIONS_ID,
11
+ ADMIN_TWO_FACTOR_CHANGE_PATHS,
12
+ adminSecondFactorSessions,
13
+ type AdminSecondFactorSessionsOptions,
14
+ type AdminSignIn,
15
+ } from "./second-factor.js";
16
+ export { DEFAULT_ADMIN_PROOF_PREFIX, adminProofIdentifier, sessionProofReader } from "./proof.js";