@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,511 @@
1
+ import { createHmac, timingSafeEqual } from "node:crypto";
2
+
3
+ import { AdminRefusalError, adminRefusal, type AdminAccess, type AdminRefusal } from "./access.js";
4
+ import {
5
+ emitSafely,
6
+ viewAsStarted,
7
+ viewAsStopped,
8
+ type AdminAuditScope,
9
+ type AdminAuditSink,
10
+ type AuditLogger,
11
+ type RequestMeta,
12
+ } from "./audit.js";
13
+
14
+ /**
15
+ * "View as" — seeing the product through one person's account, AltEd's rules made safe by default.
16
+ *
17
+ * Support needs the shape of what somebody sees, not just their rows. An administrator can already read every record,
18
+ * so a view grants no new access: it changes which screens render, not what may be read. Five rules make it safe:
19
+ *
20
+ * 1. **Read-only.** Every write is refused while viewing, except the app's allow-list of writes that happen as a side
21
+ * effect of reading (`viewAsWriteGuard`). What reaches outside the database — Stripe, email, a rate-limit bucket —
22
+ * is refused in the route with `refuseWhileViewingAs`.
23
+ * 2. **Short.** The cookie lapses on its own (60 minutes by default), and the expiry is inside the signed value, so the
24
+ * server decides rather than the browser.
25
+ * 3. **The administrator's, and only while they are one.** The cookie names the administrator who started it, and is
26
+ * honoured only while the real session passes `adminAccess` — checked on every request, so a demotion, a revoked
27
+ * session or a sign-in without the second factor ends the view at once. A cookie is a browser's, not a session's,
28
+ * and `signOut` does not clear it: the next person to sign in on a shared machine inherits nothing.
29
+ * 4. **Never another administrator.** Their view is this one; viewing as them would let one administrator act with
30
+ * another's standing. Checked when it starts and on every read, so a promotion mid-view ends it.
31
+ * 5. **Recorded.** Starting and stopping are both audit events naming the administrator and the account.
32
+ *
33
+ * **Signed.** AltEd's cookie was unsigned by design — honoured only for an administrator, who could start any view
34
+ * anyway. That holds only while every reader checks the binding the same way; signing it costs one HMAC and makes a
35
+ * forged or edited cookie worthless whoever reads it.
36
+ */
37
+
38
+ /** The cookie store this writes to — Next's `cookies()` from `next/headers` fits it as it is. */
39
+ export interface CookieJar {
40
+ get(name: string): { value: string } | undefined;
41
+ set(name: string, value: string, options?: ViewAsCookieOptions): unknown;
42
+ delete(name: string): unknown;
43
+ }
44
+
45
+ export interface ViewAsCookieOptions {
46
+ httpOnly: boolean;
47
+ sameSite: "lax" | "strict";
48
+ secure: boolean;
49
+ path: string;
50
+ maxAge: number;
51
+ }
52
+
53
+ export interface ViewAsOptions {
54
+ cookieName: string;
55
+ /** At least 32 characters. The app's `BETTER_AUTH_SECRET` serves; the cookie name keeps the signature its own. */
56
+ secret: string;
57
+ /** How long a view lasts before it lapses on its own. Default 60. */
58
+ minutes?: number;
59
+ /** The request's cookie store: `cookies` from `next/headers`, or anything shaped like it. */
60
+ cookies: () => CookieJar | Promise<CookieJar>;
61
+ /** The app's `adminAccess`: the real session must pass it to start a view, and for the view to be honoured. */
62
+ access: AdminAccess;
63
+ /** Where start and stop are recorded. */
64
+ audit?: AdminAuditSink;
65
+ /** A name for the audit events when the caller does not pass one. */
66
+ names?: (userId: string) => string | null | undefined | Promise<string | null | undefined>;
67
+ /** The actor's standing in the audit events. Default `"admin"`. */
68
+ standing?: string;
69
+ /** The audit events' scope. Default platform. */
70
+ scope?: AdminAuditScope;
71
+ /** Default: `process.env.NODE_ENV === "production"`. */
72
+ secure?: boolean;
73
+ /** Default `"/"`. */
74
+ path?: string;
75
+ /** For the refusals `start` answers with. */
76
+ words?: { self?: string; targetIsAdmin?: string };
77
+ logger?: AuditLogger;
78
+ /** For tests. */
79
+ now?: () => number;
80
+ }
81
+
82
+ /** A view in force. */
83
+ export interface ViewingAs {
84
+ targetId: string;
85
+ adminId: string;
86
+ expiresAt: Date;
87
+ }
88
+
89
+ /** The administrator behind the request — the real session, never the account on screen. */
90
+ export interface RealAdmin {
91
+ id: string;
92
+ sessionId: string;
93
+ name?: string | null;
94
+ }
95
+
96
+ export type ViewAsStartRefusal =
97
+ { ok: false; reason: "self" | "target-is-admin"; message: string; status: 400 } | AdminRefusal;
98
+
99
+ export type ViewAsStartResult = { ok: true; view: ViewingAs; minutes: number } | ViewAsStartRefusal;
100
+
101
+ export interface ViewAs {
102
+ /** Start viewing as `target`, for this administrator. Refused unless their real session passes `adminAccess`. */
103
+ start(
104
+ admin: RealAdmin,
105
+ target: string | { id: string; name?: string | null },
106
+ meta?: RequestMeta,
107
+ ): Promise<ViewAsStartResult>;
108
+ /**
109
+ * End the view. Works for anybody signed in — while a view is in force the request presents as the person viewed,
110
+ * who is not an administrator and could not otherwise end it. Recorded when it was this administrator's view.
111
+ */
112
+ stop(
113
+ realAdmin?: { id: string; name?: string | null } | null,
114
+ meta?: RequestMeta,
115
+ ): Promise<{ stopped: ViewingAs | null }>;
116
+ /** The view in force for this administrator, or null. Never writes, so a server component can call it. */
117
+ read(realAdmin: RealAdmin | null | undefined): Promise<ViewingAs | null>;
118
+ readonly cookieName: string;
119
+ readonly minutes: number;
120
+ }
121
+
122
+ const DEFAULT_MINUTES = 60;
123
+ const MAX_COOKIE = 1024;
124
+
125
+ const b64 = (value: Buffer | string) => Buffer.from(value).toString("base64url");
126
+
127
+ export function viewAs(options: ViewAsOptions): ViewAs {
128
+ const { cookieName, secret, access } = options;
129
+ const minutes = options.minutes ?? DEFAULT_MINUTES;
130
+ const now = options.now ?? Date.now;
131
+ const logger = options.logger ?? console;
132
+ const standing = options.standing ?? "admin";
133
+
134
+ if (!cookieName || !/^[\w.-]+$/.test(cookieName)) {
135
+ throw new Error(`[admin] viewAs cookieName must be a plain cookie name, got "${cookieName}".`);
136
+ }
137
+ if (typeof secret !== "string" || secret.length < 32) {
138
+ throw new Error("[admin] viewAs needs a secret of at least 32 characters to sign its cookie.");
139
+ }
140
+ if (!Number.isFinite(minutes) || minutes <= 0 || minutes > 24 * 60) {
141
+ throw new Error(`[admin] viewAs minutes must be between 0 and a day, got ${String(minutes)}.`);
142
+ }
143
+
144
+ const sign = (payload: string) => createHmac("sha256", secret).update(`view-as:${cookieName}:${payload}`).digest();
145
+
146
+ function encode(view: ViewingAs): string {
147
+ const payload = b64(JSON.stringify({ v: 1, t: view.targetId, a: view.adminId, e: view.expiresAt.getTime() }));
148
+ return `${payload}.${b64(sign(payload))}`;
149
+ }
150
+
151
+ /** The signed view in the cookie, whoever it belongs to and whether or not it has lapsed. */
152
+ function decode(raw: string | undefined): ViewingAs | null {
153
+ if (!raw || raw.length > MAX_COOKIE) return null;
154
+ const [payload, signature, extra] = raw.split(".");
155
+ if (!payload || !signature || extra !== undefined) return null;
156
+ const given = Buffer.from(signature, "base64url");
157
+ const expected = sign(payload);
158
+ if (given.length !== expected.length || !timingSafeEqual(given, expected)) return null;
159
+ try {
160
+ const data = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as Record<string, unknown>;
161
+ if (data.v !== 1 || typeof data.t !== "string" || typeof data.a !== "string" || typeof data.e !== "number") {
162
+ return null;
163
+ }
164
+ if (!data.t || !data.a || !Number.isFinite(data.e)) return null;
165
+ return { targetId: data.t, adminId: data.a, expiresAt: new Date(data.e) };
166
+ } catch {
167
+ return null;
168
+ }
169
+ }
170
+
171
+ /** The view in the cookie if it is this administrator's and has not lapsed — the binding, before any lookup. */
172
+ async function bound(adminId: string): Promise<ViewingAs | null> {
173
+ const jar = await options.cookies();
174
+ const view = decode(jar.get(cookieName)?.value);
175
+ if (!view || view.adminId !== adminId || view.targetId === adminId) return null;
176
+ if (view.expiresAt.getTime() <= now()) return null;
177
+ return view;
178
+ }
179
+
180
+ async function nameOf(id: string, given?: string | null): Promise<string> {
181
+ if (given) return given;
182
+ try {
183
+ return (await options.names?.(id)) || id;
184
+ } catch {
185
+ return id;
186
+ }
187
+ }
188
+
189
+ return {
190
+ cookieName,
191
+ minutes,
192
+
193
+ async start(admin, target, meta = {}) {
194
+ const targetRef = typeof target === "string" ? { id: target } : target;
195
+ if (!targetRef.id || targetRef.id === admin.id) {
196
+ return { ok: false, reason: "self", status: 400, message: options.words?.self ?? "You are already yourself." };
197
+ }
198
+ const decision = await access.check(admin, { viewingAs: false });
199
+ if (!decision.ok) return decision;
200
+ if (await access.isAdmin(targetRef.id)) {
201
+ return {
202
+ ok: false,
203
+ reason: "target-is-admin",
204
+ status: 400,
205
+ message:
206
+ options.words?.targetIsAdmin ?? "Viewing as another administrator is not allowed — their view is this one.",
207
+ };
208
+ }
209
+
210
+ const view: ViewingAs = {
211
+ targetId: targetRef.id,
212
+ adminId: admin.id,
213
+ expiresAt: new Date(now() + minutes * 60_000),
214
+ };
215
+ const jar = await options.cookies();
216
+ jar.set(cookieName, encode(view), {
217
+ httpOnly: true,
218
+ sameSite: "lax",
219
+ secure: options.secure ?? process.env.NODE_ENV === "production",
220
+ path: options.path ?? "/",
221
+ maxAge: minutes * 60,
222
+ });
223
+ await emitSafely(
224
+ options.audit,
225
+ viewAsStarted({
226
+ actor: { id: admin.id, name: await nameOf(admin.id, admin.name), standing },
227
+ target: { id: view.targetId, name: await nameOf(view.targetId, "name" in targetRef ? targetRef.name : null) },
228
+ expiresAt: view.expiresAt,
229
+ ...(options.scope ? { scope: options.scope } : {}),
230
+ ...meta,
231
+ }),
232
+ logger,
233
+ );
234
+ return { ok: true, view, minutes };
235
+ },
236
+
237
+ async stop(realAdmin, meta = {}) {
238
+ const view = realAdmin ? await bound(realAdmin.id) : null;
239
+ const jar = await options.cookies();
240
+ jar.delete(cookieName);
241
+ if (view && realAdmin) {
242
+ await emitSafely(
243
+ options.audit,
244
+ viewAsStopped({
245
+ actor: { id: realAdmin.id, name: await nameOf(realAdmin.id, realAdmin.name), standing },
246
+ target: { id: view.targetId, name: await nameOf(view.targetId) },
247
+ ...(options.scope ? { scope: options.scope } : {}),
248
+ ...meta,
249
+ }),
250
+ logger,
251
+ );
252
+ }
253
+ return { stopped: view };
254
+ },
255
+
256
+ async read(realAdmin) {
257
+ if (!realAdmin?.id || !realAdmin.sessionId) return null;
258
+ const view = await bound(realAdmin.id);
259
+ if (!view) return null;
260
+ // Checked on every request rather than when the cookie was set: a demotion, a revoked session or a sign-in
261
+ // without the second factor has to end the view immediately.
262
+ if (!(await access.check(realAdmin, { viewingAs: false })).ok) return null;
263
+ if (await access.isAdmin(view.targetId)) return null;
264
+ return view;
265
+ },
266
+ };
267
+ }
268
+
269
+ /**
270
+ * A read-only cookie store over a request's `Cookie` header — for Better Auth's hooks and anything else that has the
271
+ * request's headers rather than Next's `cookies()`, so `view.read` can be asked there.
272
+ *
273
+ * Tolerant by contract: every cookie on the request is parsed, including ones a sibling `*.connextar.com` site or a
274
+ * stray script set, so nothing malformed may throw. A value that is not valid percent-encoding (`x=%zz`) is kept as
275
+ * it came; a pair without a name or `=` is skipped. PharmaLine's own parser had an unguarded `decodeURIComponent`,
276
+ * and one such cookie failed every sign-in, sign-out and two-factor request from that browser. The first of two
277
+ * cookies with one name wins, as browsers send the most specific path first. `set` throws — a header cannot be
278
+ * written back to — and `delete` does nothing.
279
+ */
280
+ export function cookieJarFromHeaders(
281
+ headers: Headers | Pick<Headers, "get"> | Record<string, string | string[] | undefined> | null | undefined,
282
+ ): CookieJar {
283
+ const values = new Map<string, string>();
284
+ for (const part of cookieHeader(headers).split(";")) {
285
+ const at = part.indexOf("=");
286
+ if (at <= 0) continue;
287
+ const name = part.slice(0, at).trim();
288
+ if (!name || values.has(name)) continue;
289
+ let value = part.slice(at + 1).trim();
290
+ if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) value = value.slice(1, -1);
291
+ values.set(name, safeDecode(value));
292
+ }
293
+ return {
294
+ get: (name) => (values.has(name) ? { value: values.get(name)! } : undefined),
295
+ set: () => {
296
+ throw new Error("[admin] a cookie jar read from request headers cannot set a cookie.");
297
+ },
298
+ delete: () => undefined,
299
+ };
300
+ }
301
+
302
+ function cookieHeader(headers: Parameters<typeof cookieJarFromHeaders>[0]): string {
303
+ try {
304
+ if (!headers) return "";
305
+ if (typeof (headers as Pick<Headers, "get">).get === "function") {
306
+ return (headers as Pick<Headers, "get">).get("cookie") ?? "";
307
+ }
308
+ const raw = (headers as Record<string, string | string[] | undefined>).cookie;
309
+ return Array.isArray(raw) ? raw.join("; ") : (raw ?? "");
310
+ } catch {
311
+ return "";
312
+ }
313
+ }
314
+
315
+ function safeDecode(value: string): string {
316
+ if (!value.includes("%")) return value;
317
+ try {
318
+ return decodeURIComponent(value);
319
+ } catch {
320
+ return value;
321
+ }
322
+ }
323
+
324
+ /** Whoever the request presents as: AltEd's and Quickie's `impersonatedBy`, or a `viewingAs`. */
325
+ export interface MaybeViewing {
326
+ name?: string | null;
327
+ impersonatedBy?: unknown;
328
+ viewingAs?: { name?: string | null } | boolean | null;
329
+ }
330
+
331
+ /**
332
+ * The app's words for a refusal under "view as". `appName` puts the app in the house's sentence — "You’re viewing
333
+ * Quickie as Pat. Stop viewing as them before sending an email." — and `message` replaces the sentence outright.
334
+ * Quickie rewrote the house's text with a regex, which would have stopped matching silently at the first changed
335
+ * character.
336
+ */
337
+ export interface ViewingAsWords {
338
+ appName?: string;
339
+ /** The whole sentence. `name` is null when the view's person has no name to give. */
340
+ message?: (refusal: { name: string | null; what: string; appName: string | null }) => string;
341
+ }
342
+
343
+ export interface RefuseWhileViewingAsOptions extends ViewingAsWords {
344
+ /** Throw the app's own error class: `(message) => new ForbiddenError(message)`. Default `AdminRefusalError`. */
345
+ makeError?: (message: string) => Error;
346
+ }
347
+
348
+ /** The sentence a refusal under "view as" says — the house's, with the app's name, or the app's own. */
349
+ export function viewingAsMessage(name: string | null | undefined, what: string, words: ViewingAsWords = {}): string {
350
+ const appName = words.appName?.trim() || null;
351
+ if (words.message) return words.message({ name: name || null, what, appName });
352
+ const viewing = appName ? `viewing ${appName} as` : "viewing as";
353
+ return `You’re ${viewing} ${name || "somebody else"}. Stop viewing as them before ${what}.`;
354
+ }
355
+
356
+ /**
357
+ * Refuse, under "view as", a request that acts for the viewed account where the write guard cannot see it: a Stripe
358
+ * call, an email, a rate-limit bucket. Call it first in the route, before anything is spent.
359
+ */
360
+ export function refuseWhileViewingAs(
361
+ user: MaybeViewing | null | undefined,
362
+ what: string,
363
+ options: RefuseWhileViewingAsOptions = {},
364
+ ): void {
365
+ if (!user || (!user.impersonatedBy && !user.viewingAs)) return;
366
+ const name = typeof user.viewingAs === "object" && user.viewingAs?.name ? user.viewingAs.name : user.name;
367
+ const message = viewingAsMessage(name, what, options);
368
+ if (options.makeError) throw options.makeError(message);
369
+ throw new AdminRefusalError(adminRefusal("viewing-as", { "viewing-as": { message } }));
370
+ }
371
+
372
+ /** The view this request is in, as the app's request-scoped actor has it: `{ name }`, `true`, or null when not. */
373
+ export type ViewingLookup = () =>
374
+ | { name?: string | null }
375
+ | boolean
376
+ | null
377
+ | undefined
378
+ | Promise<{ name?: string | null } | boolean | null | undefined>;
379
+
380
+ export interface ViewingAsGateOptions extends ViewingAsWords {
381
+ /** The same lookup the write guard takes — the app's request actor's `viewingAs`. */
382
+ getViewing: ViewingLookup;
383
+ makeError?: (message: string) => Error;
384
+ }
385
+
386
+ export interface ViewingAsGate {
387
+ isViewingAs(): Promise<boolean>;
388
+ /** Throws under "view as". Fail-closed: a lookup that throws refuses too. */
389
+ assertNotViewingAs(what: string): Promise<void>;
390
+ }
391
+
392
+ /**
393
+ * The fail-closed default for what reaches outside the database: call `assertNotViewingAs` once inside the app's own
394
+ * `sendEmail`, `sendSms`, Stripe, GoCardless, Xero and AI wrappers, and every route that uses them is covered —
395
+ * including the next one written. Quickie had to add `refuseWhileViewingAs` to thirty handlers by hand.
396
+ *
397
+ * It reads the app's request-scoped actor rather than keeping a store of its own. An `AsyncLocalStorage` set where the
398
+ * view is resolved — inside `getCurrentUser`, an awaited callee — does not reach the route's later calls: a store
399
+ * entered in a callee after its first await (the session read) never propagates back to the caller's continuation
400
+ * (`view-as.test.ts` pins it), and wrapping
401
+ * every handler in `withViewingAs(…, fn)` is the per-route step this exists to remove. Quickie's and AltEd's actor
402
+ * is keyed on the request itself (Next's `headers()` object), which every call in the request shares.
403
+ */
404
+ export function viewingAsGate(options: ViewingAsGateOptions): ViewingAsGate {
405
+ async function lookup() {
406
+ return options.getViewing();
407
+ }
408
+ return {
409
+ async isViewingAs() {
410
+ return !!(await lookup());
411
+ },
412
+ async assertNotViewingAs(what) {
413
+ let viewing: Awaited<ReturnType<ViewingLookup>>;
414
+ try {
415
+ viewing = await lookup();
416
+ } catch (error) {
417
+ const message = `Could not tell whether this request is a “view as”, so ${what} was refused.`;
418
+ if (options.makeError) throw options.makeError(message);
419
+ throw new AdminRefusalError(adminRefusal("viewing-as", { "viewing-as": { message } }), { cause: error });
420
+ }
421
+ if (!viewing) return;
422
+ const message = viewingAsMessage(typeof viewing === "object" ? viewing.name : null, what, options);
423
+ if (options.makeError) throw options.makeError(message);
424
+ throw new AdminRefusalError(adminRefusal("viewing-as", { "viewing-as": { message } }));
425
+ },
426
+ };
427
+ }
428
+
429
+ /** Every Prisma write operation. A read is never refused — that is the whole point of a view. */
430
+ export const PRISMA_WRITE_OPERATIONS: ReadonlySet<string> = new Set([
431
+ "create",
432
+ "createMany",
433
+ "createManyAndReturn",
434
+ "update",
435
+ "updateMany",
436
+ "updateManyAndReturn",
437
+ "upsert",
438
+ "delete",
439
+ "deleteMany",
440
+ ]);
441
+
442
+ /** `allow` from a map of model → operations: `allowWhileViewing({ Session: ["update", "updateMany"] })`. */
443
+ export function allowWhileViewing(
444
+ list: Record<string, readonly string[]>,
445
+ ): (model: string | undefined, operation: string) => boolean {
446
+ const sets = new Map(Object.entries(list).map(([model, operations]) => [model, new Set(operations)]));
447
+ return (model, operation) => !!model && !!sets.get(model)?.has(operation);
448
+ }
449
+
450
+ /** The arguments Prisma hands a `$allOperations` query extension. */
451
+ export interface PrismaOperationParams {
452
+ model?: string;
453
+ operation: string;
454
+ args: unknown;
455
+ query: (args: unknown) => Promise<unknown>;
456
+ }
457
+
458
+ export interface ViewAsWriteGuardOptions extends ViewingAsWords {
459
+ /** Which operations are writes. Default: {@link PRISMA_WRITE_OPERATIONS}. */
460
+ isWrite?: (operation: string) => boolean;
461
+ /**
462
+ * The writes that happen as a side effect of reading, and so stay allowed: Better Auth touching the session row,
463
+ * the rate limiter counting, the audit trail recording the view itself. Everything else is refused.
464
+ *
465
+ * Better Auth also deletes expired `verification` rows whenever it reads one through `findVerificationValue` — a
466
+ * trusted-device check, a two-factor cookie, an email link. The house's proof reader no longer goes that way, but
467
+ * an app's own call to it under "view as" meets the guard: allow `Verification: ["deleteMany"]` only if such a read
468
+ * has to work while viewing, or set Better Auth's `verification.disableCleanup` and prune the table from a job.
469
+ */
470
+ allow: (model: string | undefined, operation: string) => boolean;
471
+ /** The view this request is in, from the app's request actor: `{ name }`, `true`, or null when not viewing. */
472
+ getViewing: ViewingLookup;
473
+ makeError?: (message: string) => Error;
474
+ /** The extension's name. Default `"view-as-write-guard"`. */
475
+ name?: string;
476
+ }
477
+
478
+ /**
479
+ * Make "view as" read-only at the client: `prisma.$extends(viewAsWriteGuard({ … }))`. Every write that arrives while
480
+ * the request is viewing as somebody is refused, whichever handler made it, unless it is on the allow-list.
481
+ *
482
+ * The rule is inverted from "block what is audited", which AltEd learnt by running it: deleting an account ran
483
+ * `session.deleteMany` and `passkey.deleteMany` before it touched the user row, so the deletion was refused —
484
+ * correctly — after signing the family out of every device. So everything is refused except what is allowed.
485
+ *
486
+ * Typed structurally, so this package imports no Prisma. If an app's Prisma types object to it, wrap it:
487
+ * `Prisma.defineExtension(viewAsWriteGuard({ … }))`.
488
+ */
489
+ export function viewAsWriteGuard(options: ViewAsWriteGuardOptions) {
490
+ const isWrite = options.isWrite ?? ((operation: string) => PRISMA_WRITE_OPERATIONS.has(operation));
491
+ return {
492
+ name: options.name ?? "view-as-write-guard",
493
+ query: {
494
+ $allModels: {
495
+ async $allOperations({ model, operation, args, query }: PrismaOperationParams): Promise<unknown> {
496
+ if (isWrite(operation) && !options.allow(model, operation)) {
497
+ // Fail-closed: a `getViewing` that throws fails the write, rather than letting it through unchecked.
498
+ const viewing = await options.getViewing();
499
+ if (viewing) {
500
+ const name = typeof viewing === "object" ? viewing.name : null;
501
+ const message = viewingAsMessage(name, "changing anything", options);
502
+ if (options.makeError) throw options.makeError(message);
503
+ throw new AdminRefusalError(adminRefusal("viewing-as", { "viewing-as": { message } }));
504
+ }
505
+ }
506
+ return query(args);
507
+ },
508
+ },
509
+ },
510
+ };
511
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * `@connextar/house/ai/config` — everything in `ai` that never calls a provider.
3
+ *
4
+ * Provider names, the job table, status shapes, image types and prices: what a
5
+ * settings screen, an upload form or a price table in the browser needs. Its own
6
+ * entry point because `@connextar/house/ai` carries both provider SDKs, which no
7
+ * client bundle should — so AltEd and PharmaLine each kept a copy of the labels
8
+ * and image types for their client components instead. `package-exports.test.ts`
9
+ * fails if anything reachable from here imports an SDK or Zod.
10
+ */
11
+ export {
12
+ AI_PROVIDERS,
13
+ PROVIDER_KEY_VARS,
14
+ PROVIDER_LABELS,
15
+ aiStatus,
16
+ chooseProvider,
17
+ configuredProviders,
18
+ modelFor,
19
+ publicAiStatus,
20
+ resolveAi,
21
+ type AiEnv,
22
+ type AiModelSpec,
23
+ type AiProviderName,
24
+ type AiStatus,
25
+ type AiTaskSpec,
26
+ type AiTaskTable,
27
+ type ProviderChoice,
28
+ type PublicAiStatus,
29
+ type ResolvedAi,
30
+ } from "./config.js";
31
+ export { AI_IMAGE_TYPES, isAiImageType, type AiImage, type AiImageType } from "./images.js";
32
+ export {
33
+ DEFAULT_PRICES,
34
+ costUsd,
35
+ findPrice,
36
+ modelFamily,
37
+ type ModelPrice,
38
+ type PriceRates,
39
+ type TokenCounts,
40
+ } from "./pricing.js";