@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,112 @@
1
+ /**
2
+ * What "your data" and "delete my account" mean, as a contract.
3
+ *
4
+ * The *implementation* of both is unavoidably per-app — every app has its own
5
+ * Prisma schema, and an export is a walk over it. What must not be per-app is
6
+ * the shape of the answer, because that is the bit a person receives, a
7
+ * regulator reads, and a second app has to stay consistent with.
8
+ *
9
+ * Two decisions are encoded here rather than left to each app to rediscover:
10
+ *
11
+ * 1. **An export summarises authored work rather than including it.** A note
12
+ * somebody wrote about a customer is the customer's personal data with an
13
+ * author attached. Shipping the contents would turn a subject access request
14
+ * into a way for one employee to walk out with the whole customer book.
15
+ * Counts, dates and the owning organisation instead — enough to know the
16
+ * records exist and to ask for them specifically.
17
+ *
18
+ * 2. **Deletion follows the schema, not a hand-written list.** `onDelete:
19
+ * Cascade` is the app already saying "this is personal and goes with them";
20
+ * `onDelete: SetNull` is it saying "this is a business record that outlives
21
+ * them". Invoices have to survive — HMRC wants six years — and an audit trail
22
+ * erasable by its subject was never an audit trail. Re-deciding that in code
23
+ * is how the two drift apart.
24
+ */
25
+
26
+ /** Bumped when the export shape changes, so an old file stays readable. */
27
+ export const ACCOUNT_EXPORT_SCHEMA_VERSION = 1;
28
+
29
+ export const ACCOUNT_EXPORT_NOTICE =
30
+ "This file contains the personal data we hold about you. Work you authored — notes, interactions, " +
31
+ "expenses — belongs to the organisation it was created in and is summarised rather than included. " +
32
+ "Ask an owner of that organisation for the records themselves.";
33
+
34
+ /** A count of something the person authored. Never the contents. */
35
+ export interface AuthoredSummary {
36
+ /** Human-readable, e.g. "Customer notes". Shown verbatim in the file. */
37
+ type: string;
38
+ count: number;
39
+ earliest: Date | string | null;
40
+ latest: Date | string | null;
41
+ }
42
+
43
+ export interface AccountExportSignIn {
44
+ hasPassword: boolean;
45
+ /** Provider ids only. Never tokens — an export is not a credential dump. */
46
+ socialProviders: string[];
47
+ twoFactorEnabled: boolean;
48
+ passkeys: { name: string | null; deviceType: string; createdAt: Date | string }[];
49
+ }
50
+
51
+ export interface AccountExport {
52
+ exportedAt: string;
53
+ schemaVersion: typeof ACCOUNT_EXPORT_SCHEMA_VERSION;
54
+ notice: string;
55
+ /** The user row, minus anything secret and minus the preference fields below. */
56
+ profile: Record<string, unknown>;
57
+ organisations: { name: string; role: string; joinedAt: Date | string }[];
58
+ signIn: AccountExportSignIn;
59
+ sessions: {
60
+ createdAt: Date | string;
61
+ expiresAt: Date | string;
62
+ ipAddress: string | null;
63
+ userAgent: string | null;
64
+ }[];
65
+ preferences: Record<string, unknown>;
66
+ authored: AuthoredSummary[];
67
+ /**
68
+ * Sections only this app has — Quickie's saved views, a school's linked
69
+ * pupils. Kept as a named bag rather than widened into the contract, so that
70
+ * what every app owes a person stays legible and one app's furniture does not
71
+ * become everyone's obligation.
72
+ */
73
+ extras?: Record<string, unknown>;
74
+ }
75
+
76
+ /* ── deletion ───────────────────────────────────────────────────────────── */
77
+
78
+ export interface DeletionBlocker {
79
+ id: string;
80
+ name: string;
81
+ otherMembers: number;
82
+ }
83
+
84
+ export interface DeletionPreflight {
85
+ canDelete: boolean;
86
+ /** Organisations destroyed along with the account — the person is their only member. */
87
+ organisationsToDelete: { id: string; name: string }[];
88
+ /** Organisations they solely own that still have members. Each one blocks deletion. */
89
+ blockedBy: DeletionBlocker[];
90
+ /** Rows removed outright, by kind. Everything else is orphaned, not deleted. */
91
+ willRemove: { type: string; count: number }[];
92
+ }
93
+
94
+ /**
95
+ * Why a deletion was refused, in words the person can act on.
96
+ *
97
+ * Shared so that every app phrases the sole-owner case the same way. It is the
98
+ * one refusal people actually hit, and "you can't do that" without saying what
99
+ * to do instead is how a support ticket gets written.
100
+ */
101
+ export function deletionBlockedMessage(blockers: DeletionBlocker[]): string {
102
+ const names = blockers.map((b) => b.name).join(", ");
103
+ return (
104
+ `You are the only owner of ${names}. Make someone else an owner, or remove the other members, ` +
105
+ "before deleting your account."
106
+ );
107
+ }
108
+
109
+ /** True when the person is about to destroy an organisation, not just leave one. */
110
+ export function deletionDestroysOrganisations(preflight: DeletionPreflight): boolean {
111
+ return preflight.organisationsToDelete.length > 0;
112
+ }
@@ -0,0 +1,11 @@
1
+ export {
2
+ ACCOUNT_EXPORT_NOTICE,
3
+ ACCOUNT_EXPORT_SCHEMA_VERSION,
4
+ deletionBlockedMessage,
5
+ deletionDestroysOrganisations,
6
+ type AccountExport,
7
+ type AccountExportSignIn,
8
+ type AuthoredSummary,
9
+ type DeletionBlocker,
10
+ type DeletionPreflight,
11
+ } from "./data-contract.js";
@@ -0,0 +1,267 @@
1
+ import { DEFAULT_ADMIN_PROOF_PREFIX, sessionProofReader, type AuthWithProofs } from "./proof.js";
2
+
3
+ /**
4
+ * Whether this request may use administration — one decision for every app with platform administrators.
5
+ *
6
+ * Six apps wrote it, and they agreed on the rule while disagreeing on its words, its order and what they checked:
7
+ *
8
+ * 1. **An administrator** — read from the database on every request, never from the session payload, which a
9
+ * cookie cache can serve minutes after a demotion (AltEd).
10
+ * 2. **Two-factor is on** for the account.
11
+ * 3. **The session is still live** — read from the session store, always. Better Auth serves a session from its
12
+ * cookie cache for minutes after it was revoked, and the proof below outlives a revoked session; AltEd and Quickie
13
+ * checked this, PharmaLine and PM Tool did not.
14
+ * 4. **This sign-in used the second factor** — the authenticator code, a backup code or a passkey, recorded per
15
+ * session by `adminSecondFactorSessions()` at the moment the session is made.
16
+ * 5. **Not while viewing as somebody.** For as long as a view lasts the administrator is not one: that is what stops
17
+ * the admin panel being reached from inside a view that promised to be read-only (Quickie).
18
+ *
19
+ * Fail-closed throughout: only `true` counts for any fact, so a lookup that answers `undefined` refuses, and a lookup
20
+ * that throws fails the request rather than letting it through.
21
+ */
22
+ export type AdminRefusalReason =
23
+ "signed-out" | "not-admin" | "two-factor-off" | "sign-in-without-second-factor" | "session-ended" | "viewing-as";
24
+
25
+ export const ADMIN_REFUSAL_REASONS: readonly AdminRefusalReason[] = [
26
+ "signed-out",
27
+ "not-admin",
28
+ "two-factor-off",
29
+ "sign-in-without-second-factor",
30
+ "session-ended",
31
+ "viewing-as",
32
+ ];
33
+
34
+ export interface AdminRefusal {
35
+ ok: false;
36
+ reason: AdminRefusalReason;
37
+ /** The sentence for the page and the 403 alike, so the reason is the same wherever it is met. */
38
+ message: string;
39
+ /** Where to put it right, or null where there is nothing to go to. */
40
+ fixHref: string | null;
41
+ /** 401 when nobody usable is signed in; 403 otherwise. */
42
+ status: 401 | 403;
43
+ }
44
+
45
+ export type AdminAccessDecision = { ok: true } | AdminRefusal;
46
+
47
+ /** What is known about the request. `null` for nobody signed in. */
48
+ export interface AdminAccessFacts {
49
+ isAdmin: boolean;
50
+ twoFactorEnabled: boolean;
51
+ /** The session's sign-in used the second factor (the plugin's record). */
52
+ sessionProven: boolean;
53
+ /** The session still exists in the session store. */
54
+ sessionLive: boolean;
55
+ /** The request is a "view as". */
56
+ viewingAs: boolean;
57
+ }
58
+
59
+ export interface AdminRefusalWording {
60
+ message?: string;
61
+ fixHref?: string | null;
62
+ }
63
+
64
+ /** Per reason, the words and the link an app wants instead of the house's. */
65
+ export type AdminRefusalWords = Partial<Record<AdminRefusalReason, AdminRefusalWording>>;
66
+
67
+ export const DEFAULT_ADMIN_REFUSAL_WORDS: Record<AdminRefusalReason, Required<AdminRefusalWording>> = {
68
+ "signed-out": { message: "Sign in to use administration.", fixHref: "/sign-in" },
69
+ "session-ended": {
70
+ message: "This sign-in has ended. Sign in again to use administration.",
71
+ fixHref: "/sign-in",
72
+ },
73
+ "not-admin": { message: "Only an administrator can do that.", fixHref: null },
74
+ "two-factor-off": {
75
+ message:
76
+ "Administration needs two-factor authentication on your account. Turn it on in Settings › Account & security, then come back.",
77
+ fixHref: "/settings?admin=two-factor-off#two-factor",
78
+ },
79
+ "sign-in-without-second-factor": {
80
+ message:
81
+ "Administration needs a sign-in that used your authenticator code or a passkey, and this one didn’t. Sign out, then sign in with your email, password and code — or with a passkey.",
82
+ fixHref: "/settings?admin=sign-in-without-second-factor#two-factor",
83
+ },
84
+ "viewing-as": {
85
+ message: "You’re viewing as somebody else. Stop viewing as them to use administration.",
86
+ fixHref: null,
87
+ },
88
+ };
89
+
90
+ const STATUS: Record<AdminRefusalReason, 401 | 403> = {
91
+ "signed-out": 401,
92
+ "session-ended": 401,
93
+ "not-admin": 403,
94
+ "two-factor-off": 403,
95
+ "sign-in-without-second-factor": 403,
96
+ "viewing-as": 403,
97
+ };
98
+
99
+ /** The refusal for a reason, in the app's words where it has them. */
100
+ export function adminRefusal(reason: AdminRefusalReason, words: AdminRefusalWords = {}): AdminRefusal {
101
+ const own = words[reason];
102
+ const fallback = DEFAULT_ADMIN_REFUSAL_WORDS[reason];
103
+ return {
104
+ ok: false,
105
+ reason,
106
+ message: own?.message ?? fallback.message,
107
+ fixHref: own && "fixHref" in own && own.fixHref !== undefined ? own.fixHref : fallback.fixHref,
108
+ status: STATUS[reason],
109
+ };
110
+ }
111
+
112
+ /**
113
+ * The decision, from what is known. Pure, so every refusal is testable without a database.
114
+ *
115
+ * The order is the order the person can act on: who they are, then whether this sign-in still exists, then the
116
+ * account's setup, then this sign-in's, then what the request is doing.
117
+ */
118
+ export function decideAdminAccess(facts: AdminAccessFacts | null | undefined, words?: AdminRefusalWords) {
119
+ const decide = (): AdminRefusalReason | null => {
120
+ if (!facts) return "signed-out";
121
+ if (facts.isAdmin !== true) return "not-admin";
122
+ if (facts.sessionLive !== true) return "session-ended";
123
+ if (facts.twoFactorEnabled !== true) return "two-factor-off";
124
+ if (facts.sessionProven !== true) return "sign-in-without-second-factor";
125
+ if (facts.viewingAs !== false) return "viewing-as";
126
+ return null;
127
+ };
128
+ const reason = decide();
129
+ return reason ? adminRefusal(reason, words) : ({ ok: true } as const);
130
+ }
131
+
132
+ type Answer = boolean | null | undefined;
133
+
134
+ /** The app's reads. Each is asked only when the answer can still change the decision. */
135
+ export interface AdminAccessLookups {
136
+ /** From the database, every request — never the session payload. */
137
+ isAdmin(userId: string): Answer | Promise<Answer>;
138
+ twoFactorEnabled(userId: string): Answer | Promise<Answer>;
139
+ /** From the session store, every request — the session row exists for this user and has not expired. */
140
+ sessionLive(sessionId: string, userId: string): Answer | Promise<Answer>;
141
+ /** Default: the plugin's record, read through `options.auth`. */
142
+ sessionProven?(sessionId: string, userId: string): Answer | Promise<Answer>;
143
+ }
144
+
145
+ export interface AdminAccessOptions {
146
+ /** The Better Auth instance, to read the plugin's record when `sessionProven` is not given. */
147
+ auth?: AuthWithProofs;
148
+ /** The plugin's `recordPrefix`, when it is not the default. */
149
+ recordPrefix?: string;
150
+ words?: AdminRefusalWords;
151
+ }
152
+
153
+ /** Who is asking: the app's user with its `sessionId`, `{ userId, sessionId }`, or Better Auth's `getSession` answer. */
154
+ export type SignedIn =
155
+ | { id: string; sessionId: string }
156
+ | { userId: string; sessionId: string }
157
+ | { user: { id: string }; session: { id: string } }
158
+ | null
159
+ | undefined;
160
+
161
+ function normalise(signedIn: SignedIn): { userId: string; sessionId: string } | null {
162
+ if (!signedIn) return null;
163
+ if ("user" in signedIn) {
164
+ const userId = signedIn.user?.id;
165
+ const sessionId = signedIn.session?.id;
166
+ return userId && sessionId ? { userId, sessionId } : null;
167
+ }
168
+ const userId = "userId" in signedIn ? signedIn.userId : signedIn.id;
169
+ return userId && signedIn.sessionId ? { userId, sessionId: signedIn.sessionId } : null;
170
+ }
171
+
172
+ export interface AdminAccess {
173
+ /** The decision for this request. `viewingAs` is whether the request is a "view as". */
174
+ check(signedIn: SignedIn, context?: { viewingAs?: boolean }): Promise<AdminAccessDecision>;
175
+ /** The facts the decision was made from, or null for nobody signed in. */
176
+ facts(signedIn: SignedIn, context?: { viewingAs?: boolean }): Promise<AdminAccessFacts | null>;
177
+ /** The app's own `isAdmin`, for the view-as rule that an administrator is never a target. */
178
+ isAdmin(userId: string): Promise<boolean>;
179
+ /** The refusal for a reason in this app's words — for a page that reads `?admin=`. */
180
+ refusal(reason: AdminRefusalReason): AdminRefusal;
181
+ readonly words: AdminRefusalWords;
182
+ }
183
+
184
+ export function adminAccess(lookups: AdminAccessLookups, options: AdminAccessOptions = {}): AdminAccess {
185
+ const words = options.words ?? {};
186
+ const proven =
187
+ lookups.sessionProven?.bind(lookups) ??
188
+ (options.auth ? sessionProofReader(options.auth, options.recordPrefix ?? DEFAULT_ADMIN_PROOF_PREFIX) : null);
189
+ if (!proven) {
190
+ throw new Error(
191
+ "[admin] adminAccess needs either `sessionProven` or `auth` (the Better Auth instance, to read the record " +
192
+ "adminSecondFactorSessions() writes).",
193
+ );
194
+ }
195
+
196
+ const isAdmin = async (userId: string) => (await lookups.isAdmin(userId)) === true;
197
+
198
+ async function facts(signedIn: SignedIn, context: { viewingAs?: boolean } = {}): Promise<AdminAccessFacts | null> {
199
+ const who = normalise(signedIn);
200
+ if (!who) return null;
201
+ const viewingAs = context.viewingAs === true;
202
+ if (!(await isAdmin(who.userId))) {
203
+ return { isAdmin: false, twoFactorEnabled: false, sessionLive: false, sessionProven: false, viewingAs };
204
+ }
205
+ // One round trip: the three reads run together.
206
+ const [twoFactorEnabled, sessionLive, sessionProven] = await Promise.all([
207
+ lookups.twoFactorEnabled(who.userId),
208
+ lookups.sessionLive(who.sessionId, who.userId),
209
+ proven!(who.sessionId, who.userId),
210
+ ]);
211
+ return {
212
+ isAdmin: true,
213
+ twoFactorEnabled: twoFactorEnabled === true,
214
+ sessionLive: sessionLive === true,
215
+ sessionProven: sessionProven === true,
216
+ viewingAs,
217
+ };
218
+ }
219
+
220
+ return {
221
+ facts,
222
+ async check(signedIn, context) {
223
+ return decideAdminAccess(await facts(signedIn, context), words);
224
+ },
225
+ isAdmin,
226
+ refusal: (reason) => adminRefusal(reason, words),
227
+ words,
228
+ };
229
+ }
230
+
231
+ /**
232
+ * The refusal named by a page's `?admin=` parameter, for the settings page an administrator is sent to — so it says
233
+ * why in the same words the admin routes refuse with. Anything that is not a reason (`toString`, an array) is null.
234
+ */
235
+ export function adminRefusalFromParam(
236
+ param: string | string[] | null | undefined,
237
+ words?: AdminRefusalWords,
238
+ ): AdminRefusal | null {
239
+ if (typeof param !== "string" || !(ADMIN_REFUSAL_REASONS as readonly string[]).includes(param)) return null;
240
+ return adminRefusal(param as AdminRefusalReason, words);
241
+ }
242
+
243
+ /**
244
+ * A refusal as an error, for code that answers by throwing. Each app's error handler maps it to its own envelope
245
+ * with `status` and `message`; or pass `makeError` where the house functions take one, to throw the app's own class.
246
+ */
247
+ export class AdminRefusalError extends Error {
248
+ readonly refusal: AdminRefusal;
249
+ readonly status: 401 | 403;
250
+ readonly reason: AdminRefusalReason;
251
+
252
+ constructor(refusal: AdminRefusal, options?: { cause?: unknown }) {
253
+ super(refusal.message, options);
254
+ this.name = "AdminRefusalError";
255
+ this.refusal = refusal;
256
+ this.status = refusal.status;
257
+ this.reason = refusal.reason;
258
+ }
259
+ }
260
+
261
+ /** The decision's user, or a thrown refusal: `assertAdminAccess(await access.check(session))`. */
262
+ export function assertAdminAccess(
263
+ decision: AdminAccessDecision,
264
+ makeError: (refusal: AdminRefusal) => Error = (refusal) => new AdminRefusalError(refusal),
265
+ ): void {
266
+ if (!decision.ok) throw makeError(decision);
267
+ }
@@ -0,0 +1,238 @@
1
+ /**
2
+ * What an administrator did, in one shape every app maps to its own `AuditLog`.
3
+ *
4
+ * The apps' trails agree on the columns — actor id, name and role, a dotted action, the entity, a summary under 300
5
+ * characters, a sanitised `changes` — and disagree on scope: AltEd has no tenants, Quickie and PM Tool record
6
+ * platform actions with a null `organizationId`, and nobody recorded an administrator signing in, starting a view,
7
+ * or being granted the role by script. So the event says its scope outright (`platform`, or one tenant), the actor
8
+ * carries their standing at the time, and a "view as" names both people — the administrator stays the actor, so an
9
+ * entry never reads as though the person being viewed did it.
10
+ *
11
+ * The house writes no table. An app passes an `AdminAuditSink` that maps the event to its own row.
12
+ */
13
+
14
+ export interface AdminAuditActor {
15
+ id: string;
16
+ name: string;
17
+ /** The actor's standing when they acted: `"platform-admin"`, `"ADMIN"`, an org role — the app's own word. */
18
+ standing: string;
19
+ }
20
+
21
+ export type AdminAuditScope = { kind: "platform" } | { kind: "tenant"; tenantId: string };
22
+
23
+ export interface AdminAuditEvent {
24
+ /** Dotted, e.g. `admin.signed_in`, `user.role_changed`, `admin.view_as_started`. */
25
+ action: string;
26
+ /** Null for a script or the system: the bootstrap script has nobody to name. */
27
+ actor: AdminAuditActor | null;
28
+ /** Set while the actor is viewing as somebody: who. */
29
+ viewingAs?: { id: string; name: string } | null;
30
+ scope: AdminAuditScope;
31
+ entity: { type: string; id: string | null };
32
+ /** At most 300 characters — the apps' column. The builders trim it. */
33
+ summary: string;
34
+ changes?: Record<string, unknown>;
35
+ at: Date;
36
+ ip?: string | null;
37
+ userAgent?: string | null;
38
+ }
39
+
40
+ export type AdminAuditSink = (event: AdminAuditEvent) => void | Promise<void>;
41
+
42
+ export const PLATFORM_SCOPE: AdminAuditScope = { kind: "platform" };
43
+
44
+ export const SUMMARY_MAX = 300;
45
+
46
+ /** Where the request came from: the first `x-forwarded-for` hop, and the user agent. */
47
+ export interface RequestMeta {
48
+ ip?: string | null;
49
+ userAgent?: string | null;
50
+ }
51
+
52
+ /** `{ ip, userAgent }` from a `Request` or its `Headers`. */
53
+ export function requestMeta(source: Request | Headers | null | undefined): RequestMeta {
54
+ const headers = source instanceof Headers ? source : source?.headers;
55
+ if (!headers) return {};
56
+ const forwarded = headers.get("x-forwarded-for")?.split(",")[0]?.trim();
57
+ const ip = forwarded || headers.get("x-real-ip") || null;
58
+ return { ip, userAgent: headers.get("user-agent") };
59
+ }
60
+
61
+ const trim = (summary: string) => (summary.length > SUMMARY_MAX ? `${summary.slice(0, SUMMARY_MAX - 1)}…` : summary);
62
+
63
+ interface Common extends RequestMeta {
64
+ at?: Date;
65
+ }
66
+
67
+ function event(base: Omit<AdminAuditEvent, "at" | "summary"> & { summary: string } & Common): AdminAuditEvent {
68
+ const { at, ip, userAgent, ...rest } = base;
69
+ return {
70
+ ...rest,
71
+ summary: trim(rest.summary),
72
+ at: at ?? new Date(),
73
+ ...(ip !== undefined ? { ip } : {}),
74
+ ...(userAgent !== undefined ? { userAgent } : {}),
75
+ };
76
+ }
77
+
78
+ /**
79
+ * How a sign-in was made. The first four prove the second factor; the rest do not, and an administrator signed in
80
+ * that way is refused administration until they sign in again.
81
+ */
82
+ export type AdminSignInMethod =
83
+ "code" | "backup-code" | "passkey" | "trusted-device" | "password" | "email-link" | "social" | "other";
84
+
85
+ const METHOD_WORDS: Record<AdminSignInMethod, string> = {
86
+ code: "their authenticator code",
87
+ "backup-code": "a backup code",
88
+ passkey: "a passkey",
89
+ "trusted-device": "a password on a trusted device",
90
+ password: "a password, without a second factor",
91
+ "email-link": "an email link, without a second factor",
92
+ social: "a social sign-in, without a second factor",
93
+ other: "a sign-in that did not use a second factor",
94
+ };
95
+
96
+ export function adminSignedIn(
97
+ input: {
98
+ actor: AdminAuditActor;
99
+ sessionId: string;
100
+ method: AdminSignInMethod;
101
+ /** Whether the session counts for administration — its sign-in used the second factor. */
102
+ proven: boolean;
103
+ scope?: AdminAuditScope;
104
+ } & Common,
105
+ ): AdminAuditEvent {
106
+ return event({
107
+ action: "admin.signed_in",
108
+ actor: input.actor,
109
+ scope: input.scope ?? PLATFORM_SCOPE,
110
+ entity: { type: "session", id: input.sessionId },
111
+ summary: `${input.actor.name} signed in with ${METHOD_WORDS[input.method]}`,
112
+ changes: { method: input.method, proven: input.proven },
113
+ at: input.at,
114
+ ip: input.ip,
115
+ userAgent: input.userAgent,
116
+ });
117
+ }
118
+
119
+ export function roleChanged(
120
+ input: {
121
+ /** Null for a script. */
122
+ actor: AdminAuditActor | null;
123
+ target: { id: string; name?: string | null; email?: string | null };
124
+ /** The standing before and after: `"user"` → `"platform-admin"`, `"MEMBER"` → `"ADMIN"`. Null for none. */
125
+ from: string | null;
126
+ to: string | null;
127
+ scope?: AdminAuditScope;
128
+ /** What made the change when it was not a screen: `"bootstrap-admin"`. */
129
+ via?: string;
130
+ changes?: Record<string, unknown>;
131
+ } & Common,
132
+ ): AdminAuditEvent {
133
+ const who = input.target.name || input.target.email || input.target.id;
134
+ const by = input.via ? ` (${input.via})` : "";
135
+ const summary =
136
+ input.to === null
137
+ ? `Removed ${who}'s ${input.from ?? "role"} standing${by}`
138
+ : `Changed ${who} from ${input.from ?? "no role"} to ${input.to}${by}`;
139
+ return event({
140
+ action: "user.role_changed",
141
+ actor: input.actor,
142
+ scope: input.scope ?? PLATFORM_SCOPE,
143
+ entity: { type: "user", id: input.target.id },
144
+ summary,
145
+ changes: { from: input.from, to: input.to, ...(input.via ? { via: input.via } : {}), ...input.changes },
146
+ at: input.at,
147
+ ip: input.ip,
148
+ userAgent: input.userAgent,
149
+ });
150
+ }
151
+
152
+ export function viewAsStarted(
153
+ input: {
154
+ actor: AdminAuditActor;
155
+ target: { id: string; name: string };
156
+ expiresAt: Date;
157
+ scope?: AdminAuditScope;
158
+ } & Common,
159
+ ): AdminAuditEvent {
160
+ return event({
161
+ action: "admin.view_as_started",
162
+ actor: input.actor,
163
+ viewingAs: input.target,
164
+ scope: input.scope ?? PLATFORM_SCOPE,
165
+ entity: { type: "user", id: input.target.id },
166
+ summary: `${input.actor.name} started viewing as ${input.target.name}`,
167
+ changes: { until: input.expiresAt.toISOString() },
168
+ at: input.at,
169
+ ip: input.ip,
170
+ userAgent: input.userAgent,
171
+ });
172
+ }
173
+
174
+ export function viewAsStopped(
175
+ input: {
176
+ actor: AdminAuditActor;
177
+ target: { id: string; name: string };
178
+ scope?: AdminAuditScope;
179
+ } & Common,
180
+ ): AdminAuditEvent {
181
+ return event({
182
+ action: "admin.view_as_stopped",
183
+ actor: input.actor,
184
+ viewingAs: input.target,
185
+ scope: input.scope ?? PLATFORM_SCOPE,
186
+ entity: { type: "user", id: input.target.id },
187
+ summary: `${input.actor.name} stopped viewing as ${input.target.name}`,
188
+ at: input.at,
189
+ ip: input.ip,
190
+ userAgent: input.userAgent,
191
+ });
192
+ }
193
+
194
+ /** An operator's action across the platform — comps, AI rates, re-pricing — with no tenant of its own. */
195
+ export function platformAction(
196
+ input: {
197
+ actor: AdminAuditActor;
198
+ action: string;
199
+ entity: { type: string; id?: string | null };
200
+ summary: string;
201
+ changes?: Record<string, unknown>;
202
+ viewingAs?: { id: string; name: string } | null;
203
+ } & Common,
204
+ ): AdminAuditEvent {
205
+ return event({
206
+ action: input.action,
207
+ actor: input.actor,
208
+ ...(input.viewingAs ? { viewingAs: input.viewingAs } : {}),
209
+ scope: PLATFORM_SCOPE,
210
+ entity: { type: input.entity.type, id: input.entity.id ?? null },
211
+ summary: input.summary,
212
+ ...(input.changes ? { changes: input.changes } : {}),
213
+ at: input.at,
214
+ ip: input.ip,
215
+ userAgent: input.userAgent,
216
+ });
217
+ }
218
+
219
+ export interface AuditLogger {
220
+ error(message: string, ...args: unknown[]): void;
221
+ }
222
+
223
+ /**
224
+ * Recording an event must never break the thing being recorded: an error from the sink is logged and swallowed.
225
+ * Used wherever the house emits an event beside an action that already happened (a sign-in, a view starting).
226
+ */
227
+ export async function emitSafely(
228
+ sink: AdminAuditSink | undefined,
229
+ auditEvent: AdminAuditEvent,
230
+ logger: AuditLogger = console,
231
+ ): Promise<void> {
232
+ if (!sink) return;
233
+ try {
234
+ await sink(auditEvent);
235
+ } catch (error) {
236
+ logger.error(`[admin] could not record ${auditEvent.action}`, error);
237
+ }
238
+ }