@teamscala/service-boot 0.23.284

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 (138) hide show
  1. package/package.json +1016 -0
  2. package/src/agreement-gate.test.ts +118 -0
  3. package/src/agreement-gate.ts +887 -0
  4. package/src/asset-cache-key.ts +59 -0
  5. package/src/asset-optimize.ts +93 -0
  6. package/src/asset-proxy.ts +148 -0
  7. package/src/asset-social-card.ts +58 -0
  8. package/src/attach-agreement-magic.ts +62 -0
  9. package/src/attach-portal-members.ts +107 -0
  10. package/src/attach-proposal-accept.ts +123 -0
  11. package/src/attach-proposal-magic.ts +55 -0
  12. package/src/attach-transfers-upload.ts +100 -0
  13. package/src/auth-gate.ts +385 -0
  14. package/src/bind-page-handler.ts +223 -0
  15. package/src/build-client-assets/input-hashing.ts +206 -0
  16. package/src/build-client-assets/source-candidates.ts +115 -0
  17. package/src/build-client-assets.test.ts +216 -0
  18. package/src/build-client-assets.ts +962 -0
  19. package/src/compose-page-title.test.ts +88 -0
  20. package/src/compose-page-title.ts +73 -0
  21. package/src/content-gate/access.ts +89 -0
  22. package/src/content-gate/config-types.ts +108 -0
  23. package/src/content-gate/gate.ts +74 -0
  24. package/src/content-gate/parse-cookie.ts +23 -0
  25. package/src/content-gate/token.test.ts +70 -0
  26. package/src/content-gate/token.ts +148 -0
  27. package/src/content-page-floor.test.ts +127 -0
  28. package/src/content-page-floor.ts +70 -0
  29. package/src/discover-blocks.ts +228 -0
  30. package/src/expand-roster.ts +197 -0
  31. package/src/fn-routers/agreement-completion-email.ts +115 -0
  32. package/src/fn-routers/agreement-send-router.ts +303 -0
  33. package/src/fn-routers/ai-health-router.ts +64 -0
  34. package/src/fn-routers/auth-router.ts +131 -0
  35. package/src/fn-routers/cache-admin-router.ts +50 -0
  36. package/src/fn-routers/chat-session-router.ts +455 -0
  37. package/src/fn-routers/email-defaults.ts +22 -0
  38. package/src/fn-routers/email-link-ttl.ts +23 -0
  39. package/src/fn-routers/index.ts +70 -0
  40. package/src/fn-routers/panel-data-router.ts +93 -0
  41. package/src/fn-routers/persist-chat-messages.test.ts +86 -0
  42. package/src/fn-routers/persist-chat-messages.ts +96 -0
  43. package/src/fn-routers/plans-router.ts +141 -0
  44. package/src/fn-routers/proposal-send-router.ts +207 -0
  45. package/src/fn-routers/public-agreement-router.ts +865 -0
  46. package/src/fn-routers/public-assessment-router.ts +421 -0
  47. package/src/fn-routers/public-gpt-session-router.ts +373 -0
  48. package/src/fn-routers/sign-in-flow-router.ts +196 -0
  49. package/src/fn-routers/task-sync-bind.test.ts +105 -0
  50. package/src/fn-routers/task-sync-classify.test.ts +109 -0
  51. package/src/fn-routers/task-sync-dispatch.test.ts +44 -0
  52. package/src/fn-routers/task-sync-dispatch.ts +124 -0
  53. package/src/fn-routers/task-sync-router.test.ts +279 -0
  54. package/src/fn-routers/task-sync-router.ts +1036 -0
  55. package/src/fn-routers/tasks-router.ts +77 -0
  56. package/src/fn-routers/user-preferences-router.ts +139 -0
  57. package/src/fn-routers/work-items-router.ts +341 -0
  58. package/src/gate-ttls.ts +56 -0
  59. package/src/gpt-gate.ts +76 -0
  60. package/src/handlers/bun-stable-watch.ts +89 -0
  61. package/src/handlers/projects-digest.ts +198 -0
  62. package/src/handlers/prune-stale-data.ts +110 -0
  63. package/src/handlers/registry-stale-inactive-sweep.ts +82 -0
  64. package/src/handlers/scala-tools-currency-watch.test.ts +60 -0
  65. package/src/handlers/scala-tools-currency-watch.ts +171 -0
  66. package/src/handlers/scheduled-browser-tests.ts +85 -0
  67. package/src/handlers/sweep-event-log.ts +98 -0
  68. package/src/handlers/sweep-host-cache.ts +211 -0
  69. package/src/handlers/upstream-issue-sync.ts +210 -0
  70. package/src/handlers/whatsapp-liveness-handler.test.ts +59 -0
  71. package/src/handlers/whatsapp-liveness-logic.ts +53 -0
  72. package/src/handlers/whatsapp-liveness.test.ts +78 -0
  73. package/src/handlers/whatsapp-liveness.ts +125 -0
  74. package/src/hono-error-handler.ts +55 -0
  75. package/src/install-harness.ts +80 -0
  76. package/src/install-logging.ts +182 -0
  77. package/src/load-service-install-row.ts +98 -0
  78. package/src/load-service-prisma-client.ts +53 -0
  79. package/src/mount-orpc-router.ts +148 -0
  80. package/src/mount-server-packages.ts +155 -0
  81. package/src/mount.ts +18 -0
  82. package/src/mutable-app-ref.ts +68 -0
  83. package/src/page-route-shell-types.ts +16 -0
  84. package/src/page-server-orpc/audit-revert-router.ts +102 -0
  85. package/src/page-server-orpc/hub-mcp-client.ts +20 -0
  86. package/src/page-server-orpc/portal-diagnostics-router.ts +170 -0
  87. package/src/page-server-orpc/puck-pages-router.ts +272 -0
  88. package/src/page-server-orpc/server-client.ts +31 -0
  89. package/src/page-server-orpc/templates-router.ts +116 -0
  90. package/src/page-server-orpc/user-preferences-router.ts +132 -0
  91. package/src/pg-boss-handler-registry.ts +36 -0
  92. package/src/pg-boss-mount.ts +295 -0
  93. package/src/proposal-authorized-emails.ts +65 -0
  94. package/src/proposal-chat-inject.ts +141 -0
  95. package/src/proposal-gate.ts +175 -0
  96. package/src/read-html-template.test.ts +74 -0
  97. package/src/read-html-template.ts +102 -0
  98. package/src/read-viewport-from-request.ts +36 -0
  99. package/src/readiness-gate.ts +39 -0
  100. package/src/register-api-routes.ts +127 -0
  101. package/src/register-crash-handlers.ts +39 -0
  102. package/src/register-page-routes.ts +62 -0
  103. package/src/register-page-server-client.ts +109 -0
  104. package/src/register-registry-page-route/ai-chat-prefetch.ts +106 -0
  105. package/src/register-registry-page-route/graph-cache.test.ts +84 -0
  106. package/src/register-registry-page-route/graph-cache.ts +90 -0
  107. package/src/register-registry-page-route/meta-title.ts +73 -0
  108. package/src/register-registry-page-route/proposal-approval-email-token.ts +78 -0
  109. package/src/register-registry-page-route/proposal-brand-stamping.ts +60 -0
  110. package/src/register-registry-page-route/resolve-page-data.ts +518 -0
  111. package/src/register-registry-page-route.ts +765 -0
  112. package/src/register-static-assets.ts +180 -0
  113. package/src/register-ws-routes.ts +180 -0
  114. package/src/resolve-app-base-url.ts +28 -0
  115. package/src/resolve-brand-favicon.ts +65 -0
  116. package/src/resolve-from-loader-config.test.ts +44 -0
  117. package/src/resolve-from-loader-config.ts +291 -0
  118. package/src/resolve-service-context.ts +67 -0
  119. package/src/resolve-theme-mode.ts +61 -0
  120. package/src/resolvers/fetch-org-brand.ts +28 -0
  121. package/src/resolvers/portal-route-paths.test.ts +102 -0
  122. package/src/resolvers/portal-route-paths.ts +83 -0
  123. package/src/resolvers/website-by-host-map.ts +49 -0
  124. package/src/resource-chat-inject.ts +168 -0
  125. package/src/resource-not-found.ts +263 -0
  126. package/src/run-boot-hook-list.ts +75 -0
  127. package/src/run-boot-hooks.ts +97 -0
  128. package/src/scala-tools-currency-watchdog.ts +160 -0
  129. package/src/security-headers.ts +59 -0
  130. package/src/serve/serve-ws.test.ts +135 -0
  131. package/src/serve/serve.ts +190 -0
  132. package/src/server-error-page.test.ts +102 -0
  133. package/src/server-error-page.ts +95 -0
  134. package/src/start-scheduled-jobs.ts +84 -0
  135. package/src/two-phase-boot.ts +449 -0
  136. package/src/types.ts +52 -0
  137. package/src/ui-service.ts +171 -0
  138. package/src/ws-boot-self-test.ts +114 -0
@@ -0,0 +1,887 @@
1
+ /**
2
+ * @system service-boot
3
+ * @status handwritten
4
+ * @edit edit directly
5
+ *
6
+ * The AGREEMENT content gate, expressed as config for the content-gate primitive
7
+ * (content-gate/). The agreement-specific bits: which resource (the placed
8
+ * SignIn gate block's id), who's authorized (the signer roster), what to seed
9
+ * (the verified signer's signing session into every SignatureField), and how to
10
+ * withhold (strip the gate region to gate-only + strip {{agreement.*}} chrome).
11
+ * The engine handles cookie/token/verify/orchestration.
12
+ *
13
+ * The signing logic (buildSigningSession, seedSigningBlocks, roster expansion,
14
+ * placeholder strip) is preserved verbatim from the former gate-agreement-
15
+ * content.ts — only the cookie/token orchestration moved into the shared engine.
16
+ */
17
+
18
+ import { getAppLogger } from "@teamscala/logger/app-loggers";
19
+ import { queryRows } from "@teamscala/db/query-rows";
20
+ import { createCache } from "@teamscala/cache/create-cache";
21
+ import type { AccessConfig, ContentGateConfig } from "./content-gate/config-types.ts";
22
+ import {
23
+ signAgreementAccessToken,
24
+ verifyAgreementAccessToken,
25
+ } from "@teamscala/document-signing/agreement-access-token";
26
+ import {
27
+ type PublicAgreementParty,
28
+ parseAgreementParties,
29
+ toPublicParties,
30
+ } from "@teamscala/document-signing/agreement-parties";
31
+ import { expandRosterTemplates } from "./expand-roster.ts";
32
+ import { injectResourceChatLauncher } from "./resource-chat-inject.ts";
33
+ import { agTtlMs } from "./gate-ttls.ts";
34
+ import {
35
+ buildCertificateData,
36
+ type CertificateData,
37
+ } from "./fn-routers/public-agreement-router.ts";
38
+ import { loadRegistryConfig } from "@teamscala/db/registry/load-config";
39
+ import * as v from "valibot";
40
+
41
+ const AG_COOKIE = "ag_token";
42
+
43
+ /**
44
+ * Agreement gate display + behaviour, DB-driven (config/content-gate-agreement),
45
+ * never hardcoded — mirrors proposal-gate's loadProposalGateSettings. requireOtp
46
+ * is the per-gate OTP switch (agreements default ON: a signer verifies identity
47
+ * before signing). title is the fallback used when no agreement name resolves. A
48
+ * missing/invalid row falls back to these defaults so the gate UI ALWAYS renders.
49
+ */
50
+ interface AgreementGateSettings {
51
+ title: string;
52
+ subtitle: string;
53
+ submitLabel: string;
54
+ requireOtp: boolean;
55
+ }
56
+
57
+ const AGREEMENT_GATE_DEFAULTS: AgreementGateSettings = {
58
+ title: "Private document",
59
+ subtitle: "Verify your email to view and sign this document.",
60
+ submitLabel: "Access document",
61
+ requireOtp: true,
62
+ };
63
+
64
+ const AgreementGateSettingsSchema = v.object({
65
+ title: v.optional(v.string(), AGREEMENT_GATE_DEFAULTS.title),
66
+ subtitle: v.optional(v.string(), AGREEMENT_GATE_DEFAULTS.subtitle),
67
+ submitLabel: v.optional(v.string(), AGREEMENT_GATE_DEFAULTS.submitLabel),
68
+ requireOtp: v.optional(v.boolean(), AGREEMENT_GATE_DEFAULTS.requireOtp),
69
+ });
70
+
71
+ /** Gate copy/behaviour, or null when the config row is absent/broken. Null is
72
+ * the absent signal — callers default explicitly so a missing row neither 500s
73
+ * the page nor masks as a populated value (protective-layers-fail-explicitly). */
74
+ async function loadAgreementGateSettings(): Promise<AgreementGateSettings | null> {
75
+ try {
76
+ return await loadRegistryConfig(
77
+ "config",
78
+ "content-gate-agreement",
79
+ AgreementGateSettingsSchema,
80
+ );
81
+ } catch {
82
+ return null;
83
+ }
84
+ }
85
+
86
+ /**
87
+ * Cache for the page→agreement association (new-flow pages that have no
88
+ * pre-placed gate block). The association changes rarely (only when a new
89
+ * agreement is created or a page is rebound), so a 30s TTL avoids a DB query
90
+ * per request while staying fresh enough for just-created agreements to appear.
91
+ * Negative results are cached too (id="") so non-agreement pages never re-query.
92
+ */
93
+ const pageAgreementCache = createCache<{ id: string; name: string }>(
94
+ "agreement-gate:page-association",
95
+ { maxSize: 256, ttlMs: 30_000 },
96
+ );
97
+
98
+ /**
99
+ * Cache for the owning org's member directory (org id → lowercased email → name),
100
+ * used to grant VIEW-ONLY access to an agreement to any member of the org that
101
+ * owns it (signing stays roster-bound). Membership changes on human timescales,
102
+ * so a 30s TTL keeps the per-request authorize cheap (hot-path-resolutions-are-cached).
103
+ */
104
+ const orgMemberCache = createCache<Map<string, string>>(
105
+ "agreement-gate:org-members",
106
+ { maxSize: 256, ttlMs: 30_000 },
107
+ );
108
+
109
+ /**
110
+ * The owning org's member directory: lowercased email → display name, for every
111
+ * member of `organisationId`. Empty when the org is unknown or has no members.
112
+ *
113
+ * Resolved via a parameterized raw join over better_auth_member + "user" rather
114
+ * than `getPrisma().member`: `member` is a shared @@map'd Prisma model, and each
115
+ * service's per-service client is generated by live DB introspection from only
116
+ * the tables its service_schema declares — so `getPrisma().member` is UNDEFINED
117
+ * on a service (scala-sign, scala-proposals) that doesn't list better_auth_member.
118
+ * A read-only raw query needs no model declaration and works on every client,
119
+ * which is what makes org-member VIEW access actually resolve (the typed access
120
+ * silently crashed → caught → empty directory → org members wrongly challenged).
121
+ */
122
+ async function resolveOrgMemberDirectory(
123
+ organisationId: string | null,
124
+ ): Promise<Map<string, string>> {
125
+ if (!organisationId) return new Map();
126
+ const cached = orgMemberCache.get(organisationId);
127
+ if (cached !== undefined) return cached;
128
+ const directory = new Map<string, string>();
129
+ try {
130
+ const { getPrisma } = await import("@teamscala/db/prisma-registry");
131
+ const rows = await queryRows`
132
+ SELECT u.email AS email, u.name AS name
133
+ FROM better_auth_member m
134
+ JOIN "user" u ON u.id = m.user_id
135
+ WHERE m.organization_id = ${organisationId}
136
+ ` as
137
+ Array<{ email: string | null; name: string | null }>
138
+ ;
139
+ for (const r of rows) {
140
+ const email = typeof r.email === "string" ? r.email.trim().toLowerCase() : "";
141
+ if (email) directory.set(email, String(r.name ?? r.email));
142
+ }
143
+ orgMemberCache.set(organisationId, directory);
144
+ return directory;
145
+ } catch (err) {
146
+ getAppLogger().error(
147
+ `[agreement-gate] org-member resolve failed: ${err instanceof Error ? err.message : String(err)}`,
148
+ );
149
+ return directory;
150
+ }
151
+ }
152
+
153
+ /**
154
+ * The combined member directory for EVERY org an agreement's parties represent
155
+ * (each party's `organisationId`) plus the agreement's owning org. Any of these
156
+ * members may VIEW the agreement; signing stays restricted to the designated
157
+ * signer (the party email). Usually 1 org (one of our orgs + an external party),
158
+ * so the loop is over a 1-2 element set, each entry cached.
159
+ */
160
+ async function resolveAgreementViewerDirectory(
161
+ orgIds: Iterable<string | null | undefined>,
162
+ ): Promise<Map<string, string>> {
163
+ const out = new Map<string, string>();
164
+ const unique = new Set(
165
+ [...orgIds].filter((id): id is string => typeof id === "string" && id.length > 0),
166
+ );
167
+ for (const orgId of unique) {
168
+ const dir = await resolveOrgMemberDirectory(orgId);
169
+ for (const [email, name] of dir) if (!out.has(email)) out.set(email, name);
170
+ }
171
+ return out;
172
+ }
173
+
174
+ interface ContentBlock {
175
+ type?: string;
176
+ props?: Record<string, unknown>;
177
+ }
178
+
179
+ interface SigningSession {
180
+ authedRole: string;
181
+ authedName: string;
182
+ authedEmail: string;
183
+ agreementUuid: string;
184
+ parties: PublicAgreementParty[];
185
+ agreementName: string;
186
+ agreementRef: string;
187
+ completedAt: string | null;
188
+ orgName: string | null;
189
+ organisationId: string | null;
190
+ /** Certificate of Completion data (built for a party signer via
191
+ * buildCertificateData); null for view-only recipients. Seeded into the
192
+ * SignatureField so the certificate renders inline, immediately. */
193
+ certificate: CertificateData | null;
194
+ }
195
+
196
+ /** Every resolved region's content[] array, paired with its puck_data holder. */
197
+ function* regionContents(
198
+ resolved: Record<string, unknown>,
199
+ ): Generator<{ pd: { content?: unknown[] }; content: ContentBlock[] }> {
200
+ for (const value of Object.values(resolved)) {
201
+ const pd = (value as { puck_data?: { content?: unknown[] } } | null)?.puck_data;
202
+ const content = pd?.content;
203
+ if (pd && Array.isArray(content)) {
204
+ yield { pd, content: content as ContentBlock[] };
205
+ }
206
+ }
207
+ }
208
+
209
+ /**
210
+ * Locate the agreement gate block(s) across regions. A gate is the SignIn block
211
+ * in `gate` mode whose field is NOT "proposalId" (that field marks a proposal
212
+ * gate); the agreement id lives in `gateContextValue`.
213
+ */
214
+ function findAgreementGate(resolved: Record<string, unknown>): {
215
+ agreementUuid: string;
216
+ gateRegions: { pd: { content?: unknown[] }; content: ContentBlock[]; gateIdx: number }[];
217
+ } {
218
+ let agreementUuid = "";
219
+ const gateRegions: {
220
+ pd: { content?: unknown[] };
221
+ content: ContentBlock[];
222
+ gateIdx: number;
223
+ }[] = [];
224
+ for (const { pd, content } of regionContents(resolved)) {
225
+ const gateIdx = content.findIndex(
226
+ (b) =>
227
+ b?.type === "SignIn" &&
228
+ b?.props?.mode === "gate" &&
229
+ b?.props?.gateContextField !== "proposalId",
230
+ );
231
+ if (gateIdx < 0) continue;
232
+ const uuid = content[gateIdx].props?.gateContextValue;
233
+ if (typeof uuid === "string" && uuid) agreementUuid = uuid;
234
+ gateRegions.push({ pd, content, gateIdx });
235
+ }
236
+ return { agreementUuid, gateRegions };
237
+ }
238
+
239
+ /** Build the verified signer's session from the agreement's parties roster. */
240
+ async function buildSigningSession(
241
+ agreementUuid: string,
242
+ verifiedEmail: string,
243
+ ): Promise<SigningSession | null> {
244
+ const log = getAppLogger();
245
+ const lower = verifiedEmail.trim().toLowerCase();
246
+ try {
247
+ const { getPrisma } = await import("@teamscala/db/prisma-registry");
248
+ const agreement = await getPrisma().agreements.findFirst({
249
+ where: { id: agreementUuid },
250
+ select: {
251
+ name: true,
252
+ signer_name: true,
253
+ signed_at: true,
254
+ signature_data: true,
255
+ organisation_id: true,
256
+ },
257
+ });
258
+ if (!agreement) return null;
259
+
260
+ const meta = {
261
+ agreementName: String(agreement.name ?? "Agreement"),
262
+ agreementRef: agreementUuid.split("-")[0] ?? agreementUuid,
263
+ completedAt: agreement.signed_at
264
+ ? new Date(agreement.signed_at as unknown as string).toISOString()
265
+ : null,
266
+ orgName: null as string | null,
267
+ organisationId:
268
+ typeof agreement.organisation_id === "string"
269
+ ? agreement.organisation_id
270
+ : null,
271
+ };
272
+
273
+ const parties = parseAgreementParties(agreement.signature_data);
274
+ if (parties) {
275
+ const me = parties.find((p) => p.email.trim().toLowerCase() === lower);
276
+ if (me) {
277
+ // Only a "signer" recipient gets a signing session (authedRole = its
278
+ // party key, which the SignatureField matches to render its sign slot).
279
+ // A named "viewer"/"cc" recipient — like an org member below — is
280
+ // view-only: authedRole "viewer" matches no party key, so no slot.
281
+ // Certificate data is built only for a party signer (same email-must-
282
+ // be-a-party gate as publicAgreement.certificate) and seeded for inline
283
+ // render; a view-only recipient gets null (and the cell never shows it).
284
+ const isSigner = me.recipientRole === "signer";
285
+ const cert = isSigner
286
+ ? await buildCertificateData(agreementUuid, verifiedEmail)
287
+ : null;
288
+ return {
289
+ authedRole: isSigner ? me.key : "viewer",
290
+ authedName: me.name,
291
+ authedEmail: verifiedEmail,
292
+ agreementUuid,
293
+ parties: toPublicParties(parties),
294
+ certificate: cert && cert.ok ? cert : null,
295
+ ...meta,
296
+ };
297
+ }
298
+ // Not a roster party — admit any member of an org this agreement's parties
299
+ // represent (each party's organisationId ∪ the owning org) as a VIEW-ONLY
300
+ // viewer. authedRole "viewer" matches no party key, so every SignatureField
301
+ // renders read-only "Awaiting <name>" — no signature slot. Only the
302
+ // designated signer (the party email matched above) ever signs.
303
+ const directory = await resolveAgreementViewerDirectory([
304
+ meta.organisationId,
305
+ ...parties.map((p) => p.organisationId),
306
+ ]);
307
+ const viewerName = directory.get(lower);
308
+ if (viewerName !== undefined) {
309
+ return {
310
+ authedRole: "viewer",
311
+ authedName: viewerName,
312
+ authedEmail: verifiedEmail,
313
+ agreementUuid,
314
+ parties: toPublicParties(parties),
315
+ certificate: null,
316
+ ...meta,
317
+ };
318
+ }
319
+ return null;
320
+ }
321
+
322
+ const name = String(agreement.signer_name ?? "");
323
+ const cert = await buildCertificateData(agreementUuid, verifiedEmail);
324
+ return {
325
+ authedRole: "signer",
326
+ authedName: name,
327
+ authedEmail: verifiedEmail,
328
+ agreementUuid,
329
+ parties: [
330
+ {
331
+ key: "signer",
332
+ role: name || "Signer",
333
+ recipientRole: "signer",
334
+ name,
335
+ title: null,
336
+ company: null,
337
+ signedAt: null,
338
+ signature: null,
339
+ },
340
+ ],
341
+ certificate: cert && cert.ok ? cert : null,
342
+ ...meta,
343
+ };
344
+ } catch (err) {
345
+ log.error(
346
+ `[agreement-gate] session build failed: ${err instanceof Error ? err.message : String(err)}`,
347
+ );
348
+ return null;
349
+ }
350
+ }
351
+
352
+ const SIGNING_BLOCK_TYPES = new Set(["SignatureField"]);
353
+
354
+ /** Seed the verified session into every signing block across all regions. */
355
+ function seedSigningBlocks(
356
+ resolved: Record<string, unknown>,
357
+ session: SigningSession,
358
+ ): void {
359
+ const seed = {
360
+ authed: true,
361
+ authedRole: session.authedRole,
362
+ authedName: session.authedName,
363
+ authedEmail: session.authedEmail,
364
+ agreementUuid: session.agreementUuid,
365
+ parties: session.parties,
366
+ agreementName: session.agreementName,
367
+ agreementRef: session.agreementRef,
368
+ completedAt: session.completedAt,
369
+ orgName: session.orgName,
370
+ certificate: session.certificate,
371
+ };
372
+ const seedBlock = (block: ContentBlock): void => {
373
+ if (block?.type && SIGNING_BLOCK_TYPES.has(block.type)) {
374
+ block.props = { ...(block.props ?? {}), ...seed };
375
+ }
376
+ const props = block?.props;
377
+ if (!props) return;
378
+ for (const propVal of Object.values(props)) {
379
+ if (!Array.isArray(propVal)) continue;
380
+ for (const child of propVal) {
381
+ if (child && typeof child === "object") seedBlock(child as ContentBlock);
382
+ }
383
+ }
384
+ };
385
+ for (const { content } of regionContents(resolved)) {
386
+ for (const block of content) seedBlock(block);
387
+ }
388
+ }
389
+
390
+ /** True if any of the block's OWN string props carries an {{agreement.*}} token. */
391
+ function blockHasAgreementPlaceholder(block: ContentBlock): boolean {
392
+ const props = block.props;
393
+ if (!props) return false;
394
+ for (const propVal of Object.values(props)) {
395
+ if (typeof propVal === "string" && /\{\{\s*agreement\./.test(propVal)) return true;
396
+ }
397
+ return false;
398
+ }
399
+
400
+ /** Drop blocks whose own text still holds an {{agreement.*}} token, recursively. */
401
+ function stripAgreementPlaceholderBlocks(content: ContentBlock[]): ContentBlock[] {
402
+ const out: ContentBlock[] = [];
403
+ for (const block of content) {
404
+ if (blockHasAgreementPlaceholder(block)) continue;
405
+ const props = block.props;
406
+ if (props) {
407
+ for (const [k, propVal] of Object.entries(props)) {
408
+ if (Array.isArray(propVal)) {
409
+ props[k] = stripAgreementPlaceholderBlocks(propVal as ContentBlock[]);
410
+ }
411
+ }
412
+ }
413
+ out.push(block);
414
+ }
415
+ return out;
416
+ }
417
+
418
+ /** The org's display name (for the footer audit line), from the resolved brand. */
419
+ function brandOrgName(resolved: Record<string, unknown>): string | null {
420
+ const brand = resolved.brand as
421
+ | { companyFriendlyName?: unknown; companyName?: unknown }
422
+ | undefined;
423
+ const name = brand?.companyFriendlyName ?? brand?.companyName;
424
+ return typeof name === "string" && name ? name : null;
425
+ }
426
+
427
+ // ─── New-flow signing-shell injection (no pre-placed gate required) ──────────
428
+ // When a Puck page has no pre-placed SignIn gate block, the machinery resolves
429
+ // the agreement from the page→agreement association and injects the full
430
+ // signing shell (gate when unauthed; title + execution + signature panel +
431
+ // print + audit when authed). The Puck page holds ONLY document content.
432
+
433
+ /** Agreement metadata stashed on resolved during getResourceId. */
434
+ const AGREEMENT_META_KEY = "_agreementMeta";
435
+
436
+ function stashAgreementMeta(
437
+ resolved: Record<string, unknown>,
438
+ id: string,
439
+ name: string,
440
+ ): void {
441
+ resolved[AGREEMENT_META_KEY] = { id, name };
442
+ }
443
+
444
+ /**
445
+ * The body content array for the agreement. The public shell composes the body
446
+ * region FROM resolved.page (register-registry-page-route.ts Branch 2:
447
+ * `bodyPuck = extractPuckData(resolved.page)`, returned un-cloned), so this IS
448
+ * the live array whose mutation reaches the SSR render. Header/footer are
449
+ * separate region sources (resolved.header / resolved.footer) — never the body.
450
+ *
451
+ * A prior version scored every region by top-level non-shell block count and
452
+ * picked the highest. That misroutes when the body wraps its clauses inside a
453
+ * Container (body's top-level count is ~2 while its nested clause count is ~40):
454
+ * a /header region with more top-level blocks out-scores the body, so
455
+ * onUnauthorized cleared the HEADER and injected the gate there, leaving the
456
+ * entire agreement body visible past the gate. The body is the resource page —
457
+ * identified, not heuristically guessed.
458
+ */
459
+ function getBodyContentArray(
460
+ resolved: Record<string, unknown>,
461
+ ): ContentBlock[] | null {
462
+ const pd = (
463
+ resolved.page as { puck_data?: { content?: unknown[] } } | undefined
464
+ )?.puck_data;
465
+ if (!pd || !Array.isArray(pd.content)) return null;
466
+ return pd.content as ContentBlock[];
467
+ }
468
+
469
+ /** Construct the SignIn gate block for injection. */
470
+ function buildGateBlock(
471
+ agreementUuid: string,
472
+ title: string,
473
+ settings: AgreementGateSettings,
474
+ ): ContentBlock {
475
+ return {
476
+ type: "SignIn",
477
+ props: {
478
+ id: `agreement-gate-${agreementUuid}`,
479
+ mode: "gate",
480
+ title: title || settings.title,
481
+ subtitle: settings.subtitle,
482
+ gateAction: "/api/agreement-access",
483
+ showBackToHome: true,
484
+ gateContextField: "agreementId",
485
+ gateContextValue: agreementUuid,
486
+ gateSubmitLabel: settings.submitLabel,
487
+ // Require OTP is DB-driven (config/content-gate-agreement.requireOtp).
488
+ // String "true"/"false" (not boolean) to match the select-field enum the
489
+ // render validates against — a boolean is stripped before reaching the
490
+ // component (the same coercion that bit the pre-placed gate block).
491
+ gateRequireOtp: settings.requireOtp ? "true" : "false",
492
+ },
493
+ };
494
+ }
495
+
496
+ /**
497
+ * Construct the signing shell blocks that wrap the body content when authed:
498
+ * [0] title ({{agreement.name}}), [1] execution clause, [2] signature panel
499
+ * (grid Container holding a per-party SignatureField template), [3] print
500
+ * button, [4] audit footer. The title is unshift'd before body; the rest are
501
+ * pushed after. expandRosterTemplates expands the SignatureField per party;
502
+ * seedSigningBlocks seeds each cell with the verified session.
503
+ */
504
+ const AGREEMENT_SIGNING_SHELL_DEFAULT: ContentBlock[] = [
505
+ {
506
+ type: "Text",
507
+ props: {
508
+ id: "agreement-title",
509
+ text: "{{agreement.name}}",
510
+ size: "xl",
511
+ weight: "bold",
512
+ align: "left",
513
+ element: "h1",
514
+ },
515
+ },
516
+ {
517
+ type: "Text",
518
+ props: {
519
+ id: "agreement-execution",
520
+ text: "IN WITNESS WHEREOF, the parties have executed this Agreement as of the date(s) of signature below.",
521
+ size: "sm",
522
+ weight: "normal",
523
+ align: "left",
524
+ element: "p",
525
+ },
526
+ },
527
+ {
528
+ type: "Container",
529
+ props: {
530
+ id: "agreement-signature-panel",
531
+ layout: "grid",
532
+ columns: 2,
533
+ direction: "column",
534
+ gap: "md",
535
+ padding: "md",
536
+ mobileBehavior: "stack",
537
+ content: [
538
+ {
539
+ type: "SignatureField",
540
+ props: {
541
+ id: "agreement-signature-field",
542
+ label: "",
543
+ },
544
+ },
545
+ ],
546
+ },
547
+ },
548
+ // Print button — preset:"action-primary" is the single styling knob: it
549
+ // resolves (button-presets config) to variant:primary → brand-coloured
550
+ // background. NO explicit `variant` prop: button-styles.ts does
551
+ // `variant ?? preset.variant`, so any explicit variant overrides the preset
552
+ // (a stray variant:"secondary" — not a real variant — fell back to a
553
+ // transparent ghost; that was the bare-text bug). icon:"lucide:printer"
554
+ // renders the printer glyph (baseStyle provides the icon↔label gap).
555
+ {
556
+ type: "Button",
557
+ props: {
558
+ id: "agreement-print",
559
+ label: "Print",
560
+ icon: "lucide:printer",
561
+ actionType: "print",
562
+ preset: "action-primary",
563
+ size: "default",
564
+ borderColor: "var(--border-color-default)",
565
+ borderWidth: "var(--border-width-default)",
566
+ borderRadius: "var(--radius-md)",
567
+ fullWidth: false,
568
+ pushRight: false,
569
+ href: "",
570
+ target: "_self",
571
+ },
572
+ },
573
+ {
574
+ type: "Text",
575
+ props: {
576
+ id: "agreement-audit",
577
+ text: "Secured electronic signature · {{agreement.org}}",
578
+ size: "xs",
579
+ align: "center",
580
+ element: "p",
581
+ },
582
+ },
583
+ ];
584
+
585
+ const SigningShellSchema = v.object({ blocks: v.array(v.unknown()) });
586
+
587
+ /**
588
+ * The signing-shell block tree, DB-driven (config/agreement-signing-shell) so the
589
+ * clauses, labels, and structure are editable without a deploy. Deep-cloned per
590
+ * call because injection (expandRosterTemplates/seedSigningBlocks) mutates the
591
+ * tree. Falls back to AGREEMENT_SIGNING_SHELL_DEFAULT so signing ALWAYS renders.
592
+ */
593
+ async function buildSigningShellBlocks(): Promise<ContentBlock[]> {
594
+ try {
595
+ const cfg = await loadRegistryConfig(
596
+ "config",
597
+ "agreement-signing-shell",
598
+ SigningShellSchema,
599
+ );
600
+ const blocks = cfg?.blocks as ContentBlock[] | undefined;
601
+ if (Array.isArray(blocks) && blocks.length > 0) {
602
+ return structuredClone(blocks);
603
+ }
604
+ } catch {
605
+ // fall through to the default so the signing shell ALWAYS renders
606
+ }
607
+ return structuredClone(AGREEMENT_SIGNING_SHELL_DEFAULT);
608
+ }
609
+
610
+ /** True if the page has a pre-placed SignIn gate block (old-flow page). */
611
+ function hasPrePlacedGate(resolved: Record<string, unknown>): boolean {
612
+ return findAgreementGate(resolved).agreementUuid !== "";
613
+ }
614
+
615
+ export const agreementGateConfig: ContentGateConfig = {
616
+ cookieName: AG_COOKIE,
617
+ async getResourceId(resolved) {
618
+ // Old-flow pages: a pre-placed SignIn gate block carries the UUID.
619
+ const gate = findAgreementGate(resolved);
620
+ if (gate.agreementUuid) {
621
+ const gateRegion = gate.gateRegions[0];
622
+ const gateBlock = gateRegion?.content[gateRegion.gateIdx];
623
+ const name =
624
+ (gateBlock?.props?.title as string | undefined) ?? "Agreement";
625
+ stashAgreementMeta(resolved, gate.agreementUuid, name);
626
+ return gate.agreementUuid;
627
+ }
628
+
629
+ // New-flow pages: resolve UUID from the page→agreement association.
630
+ const pageId = (resolved.page as { id?: string } | undefined)?.id;
631
+ if (!pageId) return "";
632
+
633
+ const cached = pageAgreementCache.get(pageId);
634
+ if (cached !== undefined) {
635
+ if (cached.id) stashAgreementMeta(resolved, cached.id, cached.name);
636
+ return cached.id;
637
+ }
638
+
639
+ try {
640
+ const { getPrisma } = await import("@teamscala/db/prisma-registry");
641
+ const agreement = await getPrisma().agreements.findFirst({
642
+ where: { page_id: pageId },
643
+ select: { id: true, name: true },
644
+ });
645
+ if (agreement) {
646
+ pageAgreementCache.set(pageId, {
647
+ id: agreement.id,
648
+ name: agreement.name,
649
+ });
650
+ stashAgreementMeta(resolved, agreement.id, agreement.name);
651
+ return agreement.id;
652
+ }
653
+ // Cache negative so non-agreement pages never re-query.
654
+ pageAgreementCache.set(pageId, { id: "", name: "" });
655
+ return "";
656
+ } catch (err) {
657
+ getAppLogger().error(
658
+ `[agreement-gate] page association lookup failed: ${err instanceof Error ? err.message : String(err)}`,
659
+ );
660
+ return "";
661
+ }
662
+ },
663
+ // Baked-in unified auth (engine default): a logged-in viewer whose session
664
+ // email is in the authorized set (signer roster ∪ owning/party-org members)
665
+ // is released with no per-gate OTP — session verify is local, works on
666
+ // Railway. Just exposing the resolver opts into the platform-wide behaviour.
667
+ resolveAuthorizedEmails: resolveAgreementAuthorizedEmails,
668
+ verifyToken(token, resourceId, nowMs) {
669
+ const email = verifyAgreementAccessToken(token, resourceId, nowMs);
670
+ return email ? { email } : null;
671
+ },
672
+ async onAuthorized(resolved, agreementUuid, { email }) {
673
+ const session = await buildSigningSession(agreementUuid, email);
674
+ if (!session) {
675
+ // Session build failed — withhold content as if unauthorized.
676
+ if (!hasPrePlacedGate(resolved)) {
677
+ const content = getBodyContentArray(resolved);
678
+ if (content) {
679
+ const settings =
680
+ (await loadAgreementGateSettings()) ?? AGREEMENT_GATE_DEFAULTS;
681
+ content.length = 0;
682
+ content.push(
683
+ buildGateBlock(agreementUuid, "Private document", settings),
684
+ );
685
+ }
686
+ }
687
+ return;
688
+ }
689
+
690
+ session.orgName = brandOrgName(resolved);
691
+ const signedCount = session.parties.filter((p) => p.signedAt).length;
692
+ const completedDate = session.completedAt
693
+ ? new Date(session.completedAt).toLocaleDateString("en-AU", {
694
+ day: "numeric",
695
+ month: "long",
696
+ year: "numeric",
697
+ })
698
+ : "";
699
+
700
+ // New-flow pages: inject the signing shell BEFORE roster expansion so
701
+ // the SignatureField template is expanded per party. Old-flow pages
702
+ // already have pre-placed blocks — skip injection.
703
+ if (!hasPrePlacedGate(resolved)) {
704
+ const content = getBodyContentArray(resolved);
705
+ if (content) {
706
+ const shell = await buildSigningShellBlocks();
707
+ const bodyBlocks = [...content];
708
+ content.length = 0;
709
+ content.push(shell[0], ...bodyBlocks, ...shell.slice(1));
710
+ }
711
+ }
712
+
713
+ // Expand roster templates + bind agreement-meta placeholders (both flows).
714
+ expandRosterTemplates(resolved, session.parties, {
715
+ name: session.agreementName,
716
+ ref: session.agreementRef,
717
+ org: session.orgName ?? "",
718
+ signer: session.authedName,
719
+ // Role-aware verb for the header status line. authedRole is a party key
720
+ // for a designated signer, or the literal "viewer" for a view-only
721
+ // recipient (an org member who isn't on the signer roster). So the
722
+ // header reads "Viewing as <name>" for a viewer, "Signing as <name>"
723
+ // for a signer — never implying a viewer can sign.
724
+ signerVerb: session.authedRole === "viewer" ? "Viewing" : "Signing",
725
+ signedCount: String(signedCount),
726
+ total: String(session.parties.length),
727
+ completedDate,
728
+ });
729
+ // Seed the verified session into every SignatureField (both flows).
730
+ seedSigningBlocks(resolved, session);
731
+
732
+ // Floating "Ask about this agreement" GPT bubble — the generic
733
+ // ResourceChatLauncher (one-ai-chat-system), strictly behind the email
734
+ // gate. The agreement's clause text becomes the chat's runtime context.
735
+ await injectResourceChatLauncher(resolved, email, {
736
+ resourceKey: "agreement",
737
+ agentConfigSlug: "agreement-assistant-agent",
738
+ organisationId: session.organisationId ?? undefined,
739
+ title: "Agreement Assistant",
740
+ launchLabel: "Ask about this agreement",
741
+ welcomeMessage:
742
+ "Hi! Ask me anything about this agreement — clauses, fees, the schedules, or how signing works.",
743
+ placeholder: "Ask about this agreement…",
744
+ conversationStarters: [
745
+ "What are the key terms?",
746
+ "Summarise the fees and payment terms.",
747
+ "What's in Schedule A and Schedule B?",
748
+ "How do I sign this?",
749
+ ],
750
+ });
751
+
752
+ // Old-flow only: drop the pre-placed gate block (new flow has none).
753
+ if (hasPrePlacedGate(resolved)) {
754
+ const { gateRegions } = findAgreementGate(resolved);
755
+ for (const { pd, content, gateIdx } of gateRegions) {
756
+ pd.content = content.filter((_, i) => i !== gateIdx);
757
+ }
758
+ }
759
+ },
760
+ async onUnauthorized(resolved, agreementUuid) {
761
+ if (hasPrePlacedGate(resolved)) {
762
+ // Old flow: strip region to gate-only.
763
+ const { gateRegions } = findAgreementGate(resolved);
764
+ for (const { pd, content, gateIdx } of gateRegions) {
765
+ pd.content = [content[gateIdx]];
766
+ }
767
+ } else {
768
+ // New flow: inject gate, withhold all body content.
769
+ const meta = resolved[AGREEMENT_META_KEY] as
770
+ | { name?: string }
771
+ | undefined;
772
+ const content = getBodyContentArray(resolved);
773
+ if (content) {
774
+ const settings =
775
+ (await loadAgreementGateSettings()) ?? AGREEMENT_GATE_DEFAULTS;
776
+ content.length = 0;
777
+ content.push(
778
+ buildGateBlock(
779
+ agreementUuid,
780
+ meta?.name ?? "Private document",
781
+ settings,
782
+ ),
783
+ );
784
+ }
785
+ }
786
+
787
+ // Common: strip agreement-placeholder blocks + neutralize page meta.
788
+ for (const value of Object.values(resolved)) {
789
+ const pd = (
790
+ value as { puck_data?: { content?: unknown[] } } | null
791
+ )?.puck_data;
792
+ if (pd && Array.isArray(pd.content)) {
793
+ pd.content = stripAgreementPlaceholderBlocks(
794
+ pd.content as ContentBlock[],
795
+ );
796
+ }
797
+ }
798
+ const page = resolved.page as
799
+ | { meta_title?: unknown; meta_description?: unknown; name?: unknown }
800
+ | null
801
+ | undefined;
802
+ if (page) {
803
+ page.meta_title = "Private document";
804
+ page.meta_description = "";
805
+ page.name = "Private document";
806
+ }
807
+ },
808
+ };
809
+
810
+ /** The agreement's authorized email set (its signer roster) for the access endpoint. */
811
+ async function resolveAgreementSignerEmails(
812
+ agreementId: string,
813
+ ): Promise<Set<string>> {
814
+ const emails = new Set<string>();
815
+ try {
816
+ const { getPrisma } = await import("@teamscala/db/prisma-registry");
817
+ const agreement = await getPrisma().agreements.findFirst({
818
+ where: { id: agreementId },
819
+ select: { signer_email: true, signature_data: true },
820
+ });
821
+ if (!agreement) return emails;
822
+ const parties = parseAgreementParties(agreement.signature_data);
823
+ if (parties) {
824
+ for (const p of parties) {
825
+ if (p.email) emails.add(p.email.trim().toLowerCase());
826
+ }
827
+ }
828
+ if (agreement.signer_email) {
829
+ emails.add(String(agreement.signer_email).trim().toLowerCase());
830
+ }
831
+ return emails;
832
+ } catch (err) {
833
+ getAppLogger().error(
834
+ `[agreement-gate] signer-email resolve failed: ${err instanceof Error ? err.message : String(err)}`,
835
+ );
836
+ return emails;
837
+ }
838
+ }
839
+
840
+ /**
841
+ * Every email allowed PAST the gate: the signer roster (who may sign) UNION every
842
+ * member of the owning org (who may VIEW). Signing authority stays roster-only —
843
+ * buildSigningSession gives a non-party org member a view-only session. This is
844
+ * what the access endpoint and session-authorize check.
845
+ */
846
+ async function resolveAgreementAuthorizedEmails(
847
+ agreementId: string,
848
+ ): Promise<Set<string>> {
849
+ const emails = await resolveAgreementSignerEmails(agreementId);
850
+ try {
851
+ const { getPrisma } = await import("@teamscala/db/prisma-registry");
852
+ const agreement = await getPrisma().agreements.findFirst({
853
+ where: { id: agreementId },
854
+ select: { organisation_id: true, signature_data: true },
855
+ });
856
+ // View-orgs = each party's organisationId (self-describing model) ∪ the
857
+ // agreement's owning org (also included for agreements that predate
858
+ // per-party org). Members of any of these may view; signing stays designated-signer-only.
859
+ const orgIds = new Set<string | null | undefined>();
860
+ if (typeof agreement?.organisation_id === "string") {
861
+ orgIds.add(agreement.organisation_id);
862
+ }
863
+ for (const p of parseAgreementParties(agreement?.signature_data) ?? []) {
864
+ if (p.organisationId) orgIds.add(p.organisationId);
865
+ }
866
+ const directory = await resolveAgreementViewerDirectory(orgIds);
867
+ for (const email of directory.keys()) emails.add(email);
868
+ } catch (err) {
869
+ getAppLogger().error(
870
+ `[agreement-gate] authorized-emails resolve failed: ${err instanceof Error ? err.message : String(err)}`,
871
+ );
872
+ }
873
+ return emails;
874
+ }
875
+
876
+ export const agreementAccessConfig: AccessConfig = {
877
+ path: "/api/agreement-access",
878
+ cookieName: AG_COOKIE,
879
+ get ttlMs() {
880
+ return agTtlMs();
881
+ },
882
+ recordIdField: "agreementId",
883
+ resolveAuthorizedEmails: resolveAgreementAuthorizedEmails,
884
+ signToken(resourceId, email, nowMs) {
885
+ return signAgreementAccessToken(resourceId, email, nowMs);
886
+ },
887
+ };