create-ailk 0.19.0 → 0.19.1

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 (91) hide show
  1. package/dist/add-module.js +7 -2
  2. package/dist/index.d.ts +1 -1
  3. package/dist/index.js +1 -1
  4. package/dist/lib/scaffold-render-sweep.d.ts +23 -0
  5. package/dist/lib/scaffold-render-sweep.js +52 -0
  6. package/dist/module-architecture.js +9 -3
  7. package/dist/programmatic.js +8 -1
  8. package/dist/site-roster.js +21 -4
  9. package/dist/surfaces.d.ts +14 -0
  10. package/dist/surfaces.js +31 -1
  11. package/dist/topology.js +29 -1
  12. package/package.json +3 -3
  13. package/templates/apps/api/.env.example +17 -1
  14. package/templates/apps/api/CLAUDE.md +10 -4
  15. package/templates/apps/api/src/__tests__/factories/in-memory-prisma.ts +19 -0
  16. package/templates/apps/api/src/__tests__/stripe-boot.test.ts +132 -0
  17. package/templates/apps/api/src/lib/__mocks__/prisma.ts +8 -0
  18. package/templates/apps/api/src/lib/__tests__/consent-ledger-double.ts +237 -0
  19. package/templates/apps/api/src/lib/__tests__/consent-store.test.ts +334 -0
  20. package/templates/apps/api/src/lib/__tests__/stripe-admission.test.ts +217 -0
  21. package/templates/apps/api/src/lib/__tests__/stripe.test.ts +7 -0
  22. package/templates/apps/api/src/lib/consent-store.ts +335 -0
  23. package/templates/apps/api/src/lib/stripe.ts +97 -5
  24. package/templates/apps/api/src/middleware/__tests__/auth.hub-session-path.test.ts +10 -4
  25. package/templates/apps/api/src/middleware/__tests__/rate-limit.test.ts +51 -0
  26. package/templates/apps/api/src/middleware/auth.ts +11 -3
  27. package/templates/apps/api/src/middleware/rate-limit.ts +5 -0
  28. package/templates/apps/api/src/routes/checkout/__tests__/live-key.test.ts +167 -0
  29. package/templates/apps/api/src/routes/checkout/session.ts +3 -3
  30. package/templates/apps/api/src/routes/checkout/sessions.ts +6 -4
  31. package/templates/apps/api/src/routes/consent/cookie.ts +90 -0
  32. package/templates/apps/api/src/routes/consent/index.ts +18 -0
  33. package/templates/apps/api/src/routes/consent/unsubscribe.ts +127 -0
  34. package/templates/apps/api/src/routes/leads/index.ts +15 -0
  35. package/templates/apps/api/src/routes/project-listings/__tests__/drafts.test.ts +5 -0
  36. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-flow-checkout.test.ts +17 -4
  37. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-idempotency.test.ts +2 -0
  38. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-livemode-live.test.ts +159 -0
  39. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-livemode.test.ts +158 -0
  40. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-rate-limit.test.ts +2 -0
  41. package/templates/apps/api/src/routes/webhooks/stripe.ts +17 -0
  42. package/templates/apps/api/src/server.ts +111 -16
  43. package/templates/apps/api/src/services/__tests__/consent-ledger.test.ts +503 -0
  44. package/templates/apps/api/src/services/__tests__/consent.test.ts +18 -3
  45. package/templates/apps/api/src/services/__tests__/lead-routing.test.ts +115 -4
  46. package/templates/apps/api/src/services/__tests__/person.test.ts +392 -0
  47. package/templates/apps/api/src/services/__tests__/request-confirm.test.ts +87 -0
  48. package/templates/apps/api/src/services/__tests__/revalidation.test.ts +57 -17
  49. package/templates/apps/api/src/services/consent.ts +488 -3
  50. package/templates/apps/api/src/services/lead-routing.ts +105 -12
  51. package/templates/apps/api/src/services/person.ts +501 -1
  52. package/templates/apps/api/src/services/project-listings.ts +7 -2
  53. package/templates/apps/api/src/services/request-confirm.ts +52 -0
  54. package/templates/apps/api/src/services/revalidation.ts +11 -1
  55. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/account-frame-sign-out.test.tsx +175 -0
  56. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/billing.test.tsx +17 -3
  57. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/general.test.tsx +156 -0
  58. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/hub-mode.test.tsx +89 -14
  59. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout-sign-out.test.tsx +146 -0
  60. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout.test.tsx +122 -18
  61. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/notifications.test.tsx +15 -1
  62. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/security.test.tsx +290 -20
  63. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/settings.test.tsx +55 -0
  64. package/templates/apps/web/app/[locale]/(authed)/account/account-frame.tsx +74 -4
  65. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/page.tsx +4 -7
  66. package/templates/apps/web/app/[locale]/(authed)/account/billing/page.tsx +3 -3
  67. package/templates/apps/web/app/[locale]/(authed)/account/general/contact-actions.ts +81 -0
  68. package/templates/apps/web/app/[locale]/(authed)/account/general/page.tsx +66 -4
  69. package/templates/apps/web/app/[locale]/(authed)/account/layout.tsx +26 -3
  70. package/templates/apps/web/app/[locale]/(authed)/account/notifications/page.tsx +2 -2
  71. package/templates/apps/web/app/[locale]/(authed)/account/security/page.tsx +89 -37
  72. package/templates/apps/web/app/[locale]/(authed)/account/security/security-panel.tsx +102 -0
  73. package/templates/apps/web/app/[locale]/(authed)/account/security/security-source.ts +62 -0
  74. package/templates/apps/web/app/[locale]/(authed)/account/settings-frame.tsx +41 -33
  75. package/templates/apps/web/app/[locale]/(authed)/account/sign-in-method.ts +1 -1
  76. package/templates/apps/web/auth.ts +20 -1
  77. package/templates/apps/web/lib/__tests__/auth-email.test.ts +84 -0
  78. package/templates/apps/web/lib/auth-email.ts +45 -10
  79. package/templates/apps/web/lib/topology.generated.ts +9 -0
  80. package/templates/apps/web/messages/en.json +54 -14
  81. package/templates/database/CHANGELOG.md +16 -0
  82. package/templates/database/__tests__/consent-ledger.db.test.ts +345 -0
  83. package/templates/database/__tests__/fence-fan-out.db.test.ts +6 -2
  84. package/templates/database/__tests__/fixtures/person-contact-backfill.json +182 -0
  85. package/templates/database/__tests__/person-contact.db.test.ts +563 -0
  86. package/templates/database/__tests__/person.db.test.ts +3 -1
  87. package/templates/database/inbox/schema.prisma +76 -10
  88. package/templates/database/migrations/20261014120000_consent_ledger/migration.sql +122 -0
  89. package/templates/database/migrations/20261014120000_person_contact/migration.sql +231 -0
  90. package/templates/database/package.json +1 -1
  91. package/versions.json +35 -35
@@ -29,16 +29,32 @@
29
29
  * rather than replacing it. Declines are written as `granted: false` (D8).
30
30
  */
31
31
 
32
- import { createHash } from "node:crypto";
32
+ import { createHash, createHmac, timingSafeEqual } from "node:crypto";
33
33
 
34
+ import type { Prisma } from "@working-theory/database";
34
35
  import { logger } from "@working-theory/observability";
35
36
  import {
37
+ consentPolicyHref,
36
38
  consentPurposeById,
39
+ consentPurposeKind,
40
+ consentVisitorIdSchema,
41
+ cookiePurpose,
37
42
  resolveConsentStatement,
43
+ resolveLocalizedString,
38
44
  SITE_CONSENT_CONFIG_DEFAULTS,
45
+ type ConsentSource,
46
+ type MemberConsentPurpose,
39
47
  type SiteConsentConfig,
40
48
  } from "@working-theory/validation";
41
49
 
50
+ import {
51
+ anySourceConsentRows,
52
+ effectiveConsent,
53
+ latestVisitorChoice,
54
+ ownConsentRows,
55
+ userPlatformRows,
56
+ type PurposeConsentState,
57
+ } from "../lib/consent-store.js";
42
58
  import { prisma } from "../lib/prisma.js";
43
59
 
44
60
  /**
@@ -54,7 +70,10 @@ export interface ConsentWriteClient {
54
70
  };
55
71
  }
56
72
 
57
- interface ConsentGrantRow {
73
+ /** The sources a writer may name — `legacy` is the migration's alone (D1). */
74
+ export type ConsentWriteSource = Exclude<ConsentSource, "legacy">;
75
+
76
+ export interface ConsentGrantRow {
58
77
  siteId: string;
59
78
  /**
60
79
  * #6374 — the tenancy fence's isolation key, equal to `siteId` by
@@ -72,6 +91,14 @@ interface ConsentGrantRow {
72
91
  locale: string;
73
92
  statement: string;
74
93
  statementHash: string;
94
+ /** #8438 D2 — the Person this row counts toward; `null` for a visitor, listing or user subject. */
95
+ personId: string | null;
96
+ /** #8438 D2 — where the answer came from. Required: every writer must say. */
97
+ source: ConsentWriteSource;
98
+ /** #8438 D2 — the magnet slug for `magnet`; `spoke:<id>` for a hub-credential write. */
99
+ sourceRef: string | null;
100
+ /** #8438 D2 — the registry's policy version the person read. */
101
+ policyVersion: number;
75
102
  }
76
103
 
77
104
  /**
@@ -134,7 +161,12 @@ export function requiredConsentUnmet(
134
161
  consents: Record<string, boolean>,
135
162
  ): string | undefined {
136
163
  for (const purpose of config.purposes) {
137
- if (purpose.required && consents[purpose.id] !== true) return purpose.id;
164
+ // A `signUp` agreement is asked on the member sign-up form (#8438 D13),
165
+ // never on a lead or listing form — a form that cannot show it cannot
166
+ // be refused for lacking it.
167
+ if (purpose.required && !purpose.signUp && consents[purpose.id] !== true) {
168
+ return purpose.id;
169
+ }
138
170
  }
139
171
  return undefined;
140
172
  }
@@ -144,6 +176,12 @@ export interface RecordConsentInput {
144
176
  /** e.g. `project_listing`, `subscriber` — a plain scalar, no relation (D10). */
145
177
  subjectType: string;
146
178
  subjectId: string;
179
+ /** The Person the answers count toward, when the writer knows one (#8438 D3). */
180
+ personId: string | null;
181
+ /** Where the answers came from — required, so every caller must say (#8438 D3). */
182
+ source: ConsentWriteSource;
183
+ /** The magnet slug for `source: "magnet"`. */
184
+ sourceRef?: string;
147
185
  /** The locale the statements were RENDERED in; the served locale is what gets recorded. */
148
186
  locale: string;
149
187
  config: SiteConsentConfig;
@@ -191,6 +229,10 @@ export async function recordConsent(
191
229
  locale,
192
230
  statement,
193
231
  statementHash: consentStatementHash(statement),
232
+ personId: input.personId,
233
+ source: input.source,
234
+ sourceRef: input.sourceRef ?? null,
235
+ policyVersion: purpose.policyVersion,
194
236
  });
195
237
  }
196
238
 
@@ -215,6 +257,8 @@ export interface RecordLegacyConsentInput {
215
257
  siteId: string;
216
258
  subjectType: string;
217
259
  subjectId: string;
260
+ /** Where the legacy `consent: true` came from (#8438 D3). */
261
+ source: ConsentWriteSource;
218
262
  config: SiteConsentConfig;
219
263
  }
220
264
 
@@ -247,8 +291,449 @@ export async function recordLegacyConsent(
247
291
  locale: UNRECOVERABLE_CONSENT_LOCALE,
248
292
  statement: UNRECOVERABLE_CONSENT_STATEMENT,
249
293
  statementHash: consentStatementHash(UNRECOVERABLE_CONSENT_STATEMENT),
294
+ personId: null,
295
+ source: input.source,
296
+ sourceRef: null,
297
+ policyVersion: purpose.policyVersion,
250
298
  },
251
299
  ],
252
300
  });
253
301
  return result.count;
254
302
  }
303
+
304
+ // ─── #8438 — the person, banner, link and unsubscribe writers ───────────────
305
+
306
+ type Tx = Prisma.TransactionClient;
307
+
308
+ /**
309
+ * The advisory lock every read-then-append below takes first (the member
310
+ * writes' `ailk:member-inbound:<personId>` pattern): two identical requests
311
+ * at the same moment write one row, not two.
312
+ */
313
+ async function lockConsent(tx: Tx, key: string): Promise<void> {
314
+ await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${key}, 0))`;
315
+ }
316
+
317
+ function oneRow(args: {
318
+ workspaceId: string;
319
+ subjectType: string;
320
+ subjectId: string;
321
+ personId: string | null;
322
+ purposeId: string;
323
+ granted: boolean;
324
+ source: ConsentWriteSource;
325
+ sourceRef: string | null;
326
+ policyVersion: number;
327
+ statement: string;
328
+ locale: string;
329
+ }): ConsentGrantRow {
330
+ return {
331
+ siteId: args.workspaceId,
332
+ workspaceId: args.workspaceId,
333
+ subjectType: args.subjectType,
334
+ subjectId: args.subjectId,
335
+ purposeId: args.purposeId,
336
+ granted: args.granted,
337
+ locale: args.locale,
338
+ statement: args.statement,
339
+ statementHash: consentStatementHash(args.statement),
340
+ personId: args.personId,
341
+ source: args.source,
342
+ sourceRef: args.sourceRef,
343
+ policyVersion: args.policyVersion,
344
+ };
345
+ }
346
+
347
+ export type RecordCookieChoiceInput = {
348
+ workspaceId: string;
349
+ visitorId: string;
350
+ choice: "accepted" | "declined";
351
+ locale: string;
352
+ };
353
+
354
+ /**
355
+ * The cookie banner's log (D3): one row per CHANGE of a visitor's choice,
356
+ * subject `visitor` / `visitorId`, source `cookie_banner`. Writes nothing
357
+ * when the registry declares no cookie purpose, and nothing when the
358
+ * visitor's newest row already records the same choice at the same policy
359
+ * version — a replayed choice adds no row (SEC-8438-2).
360
+ */
361
+ export async function recordCookieChoice(
362
+ input: RecordCookieChoiceInput,
363
+ config?: SiteConsentConfig,
364
+ ): Promise<{ recorded: boolean }> {
365
+ const registry = config ?? (await consentConfigForSite(input.workspaceId));
366
+ const purpose = cookiePurpose(registry);
367
+ if (!purpose) return { recorded: false };
368
+ const granted = input.choice === "accepted";
369
+ const { statement, locale } = resolveConsentStatement(purpose, input.locale);
370
+
371
+ return prisma.$transaction(async (tx) => {
372
+ await lockConsent(
373
+ tx,
374
+ `ailk:consent:${input.workspaceId}:visitor:${input.visitorId}:${purpose.id}`,
375
+ );
376
+ const latest = await latestVisitorChoice(
377
+ input.workspaceId,
378
+ input.visitorId,
379
+ purpose.id,
380
+ tx,
381
+ );
382
+ if (
383
+ latest !== null &&
384
+ latest.granted === granted &&
385
+ latest.policyVersion === purpose.policyVersion
386
+ ) {
387
+ return { recorded: false };
388
+ }
389
+ await tx.consentGrant.createMany({
390
+ data: [
391
+ oneRow({
392
+ workspaceId: input.workspaceId,
393
+ subjectType: "visitor",
394
+ subjectId: input.visitorId,
395
+ personId: null,
396
+ purposeId: purpose.id,
397
+ granted,
398
+ source: "cookie_banner",
399
+ sourceRef: null,
400
+ policyVersion: purpose.policyVersion,
401
+ statement,
402
+ locale,
403
+ }),
404
+ ],
405
+ });
406
+ return { recorded: true };
407
+ });
408
+ }
409
+
410
+ export interface RecordPersonConsentInput {
411
+ workspaceId: string;
412
+ /** The Person the answer counts toward; `null` for the owner's platform consents (subject `user`). */
413
+ personId: string | null;
414
+ purposeId: string;
415
+ granted: boolean;
416
+ source: ConsentWriteSource;
417
+ /** `spoke:<id>` for a hub-credential write (SEC-8438-16); the magnet slug otherwise. */
418
+ sourceRef?: string;
419
+ locale: string;
420
+ config: SiteConsentConfig;
421
+ /** The subject the row names: `person`/`personId` for a member, `user`/`userId` for the owner. */
422
+ subject: { subjectType: string; subjectId: string };
423
+ }
424
+
425
+ export type RecordPersonConsentResult =
426
+ | { ok: true; changed: boolean }
427
+ | {
428
+ ok: false;
429
+ code: "purpose_unknown" | "agreement_not_withdrawable" | "cookie_purpose";
430
+ };
431
+
432
+ /**
433
+ * The settings, unsubscribe and sign-up write (D3). It appends a row only
434
+ * when the answer changes the reading it is checked against:
435
+ *
436
+ * - settings and sign-up are checked against the person's OWN reading;
437
+ * - an unsubscribe is checked against BOTH readings and is skipped only
438
+ * when each already says "not granted", so a newer anonymous decline
439
+ * can never hide a member's own grant;
440
+ * - an agreement writes only when no grant exists at the purpose's current
441
+ * policy version;
442
+ * - the owner's platform consents (no Person) are checked against the
443
+ * owner's own `user` rows.
444
+ *
445
+ * So a double click, a re-clicked link or a mail scanner adds no rows. It
446
+ * refuses withdrawing an agreement and any write to the cookie purpose (the
447
+ * banner owns cookies). The read and the append share one transaction whose
448
+ * first statement is an advisory lock on the (subject, purpose) pair.
449
+ */
450
+ export async function recordPersonConsent(
451
+ input: RecordPersonConsentInput,
452
+ ): Promise<RecordPersonConsentResult> {
453
+ const purpose = consentPurposeById(input.config, input.purposeId);
454
+ if (!purpose) return { ok: false, code: "purpose_unknown" };
455
+ if (purpose.area === "cookies") return { ok: false, code: "cookie_purpose" };
456
+ const kind = consentPurposeKind(purpose);
457
+ if (kind === "agreement" && !input.granted) {
458
+ return { ok: false, code: "agreement_not_withdrawable" };
459
+ }
460
+ const { statement, locale } = resolveConsentStatement(purpose, input.locale);
461
+
462
+ return prisma.$transaction(async (tx) => {
463
+ await lockConsent(
464
+ tx,
465
+ `ailk:consent:${input.workspaceId}:${input.subject.subjectType}:${input.subject.subjectId}:${purpose.id}`,
466
+ );
467
+ const rows =
468
+ input.personId === null
469
+ ? await userPlatformRows(input.workspaceId, input.subject.subjectId, tx)
470
+ : await ownConsentRows(input.workspaceId, input.personId, tx);
471
+ const current = rows.find((row) => row.purposeId === purpose.id) ?? null;
472
+ // An unsubscribe is also checked against the any-source reading: an
473
+ // anonymous form's newer decline must not hide a member's own grant, so a
474
+ // withdrawal is skipped only when BOTH readings already say "not granted".
475
+ const anyCurrent =
476
+ input.source === "email_unsubscribe" && input.personId !== null
477
+ ? ((
478
+ await anySourceConsentRows(input.workspaceId, input.personId, tx)
479
+ ).find((row) => row.purposeId === purpose.id) ?? null)
480
+ : current;
481
+
482
+ const unchanged =
483
+ kind === "agreement"
484
+ ? current?.granted === true && current.policyVersion === purpose.policyVersion
485
+ : input.granted === effectiveConsent(kind, current) &&
486
+ input.granted === effectiveConsent(kind, anyCurrent);
487
+ if (unchanged) return { ok: true as const, changed: false };
488
+
489
+ await tx.consentGrant.createMany({
490
+ data: [
491
+ oneRow({
492
+ workspaceId: input.workspaceId,
493
+ subjectType: input.subject.subjectType,
494
+ subjectId: input.subject.subjectId,
495
+ personId: input.personId,
496
+ purposeId: purpose.id,
497
+ granted: input.granted,
498
+ source: input.source,
499
+ sourceRef: input.sourceRef ?? null,
500
+ policyVersion: purpose.policyVersion,
501
+ statement,
502
+ locale,
503
+ }),
504
+ ],
505
+ });
506
+ return { ok: true as const, changed: true };
507
+ });
508
+ }
509
+
510
+ /**
511
+ * One registry purpose as a settings screen reads it (D6): the wording in
512
+ * `locale`, the policy link, and the caller's OWN state. `state` is `null`
513
+ * when no own row exists; `effective` is what that means now.
514
+ */
515
+ export function consentPurposeView(
516
+ config: SiteConsentConfig,
517
+ state: PurposeConsentState,
518
+ locale: string,
519
+ ): MemberConsentPurpose {
520
+ const purpose = consentPurposeById(config, state.purposeId);
521
+ if (!purpose) throw new Error("consentPurposeView: purpose not in registry");
522
+ return {
523
+ id: purpose.id,
524
+ kind: state.kind,
525
+ area: purpose.area ?? null,
526
+ required: purpose.required,
527
+ signUp: purpose.signUp,
528
+ description:
529
+ purpose.description === undefined
530
+ ? purpose.id
531
+ : resolveLocalizedString(purpose.description, locale, "en"),
532
+ statement: resolveConsentStatement(purpose, locale).statement,
533
+ policyHref: consentPolicyHref(config, purpose) ?? null,
534
+ policyVersion: purpose.policyVersion,
535
+ state:
536
+ state.row === null
537
+ ? null
538
+ : {
539
+ granted: state.row.granted,
540
+ at: state.row.at.toISOString(),
541
+ source: state.row.source,
542
+ policyVersion: state.row.policyVersion,
543
+ },
544
+ effective: state.effective,
545
+ };
546
+ }
547
+
548
+ /** The request header a site's own server forwards the banner visitor id in (D11, D12). */
549
+ export const CONSENT_VISITOR_HEADER = "x-ailk-consent-visitor";
550
+
551
+ /**
552
+ * The visitor id a request carries, or `undefined`. Only a v4 UUID counts: a
553
+ * malformed or repeated header is ignored (and so links nothing), never
554
+ * echoed and never logged (D11).
555
+ */
556
+ export function consentVisitorFromHeader(value: unknown): string | undefined {
557
+ return typeof value === "string" && consentVisitorIdSchema.safeParse(value).success
558
+ ? value
559
+ : undefined;
560
+ }
561
+
562
+ /** The delegate a visitor link is written through (an insert-or-ignore). */
563
+ export interface ConsentLinkWriteClient {
564
+ consentVisitorLink: {
565
+ createMany(args: {
566
+ data: Array<{
567
+ workspaceId: string;
568
+ visitorId: string;
569
+ personId: string;
570
+ source: string;
571
+ }>;
572
+ skipDuplicates: true;
573
+ }): Promise<{ count: number }>;
574
+ };
575
+ }
576
+
577
+ /**
578
+ * Link a banner visitor to the Person a later form or sign-in identifies
579
+ * (C5): an insert-or-ignore on the unique key, so a repeat link is a no-op.
580
+ * Never throws — a failure is logged `{ event, outcome }` and swallowed,
581
+ * because a link must never fail a lead.
582
+ */
583
+ export async function linkConsentVisitor(
584
+ input: {
585
+ workspaceId: string;
586
+ visitorId: string;
587
+ personId: string;
588
+ source: "magnet" | "api" | "account_settings";
589
+ },
590
+ db: ConsentLinkWriteClient = prisma,
591
+ ): Promise<void> {
592
+ try {
593
+ await db.consentVisitorLink.createMany({
594
+ data: [
595
+ {
596
+ workspaceId: input.workspaceId,
597
+ visitorId: input.visitorId,
598
+ personId: input.personId,
599
+ source: input.source,
600
+ },
601
+ ],
602
+ skipDuplicates: true,
603
+ });
604
+ } catch {
605
+ logger.warn(
606
+ { event: "consent-visitor-link", outcome: "failed" },
607
+ "[consent] visitor link not written",
608
+ );
609
+ }
610
+ }
611
+
612
+ /** Whether `personId` is a Person of `workspaceId` (the unsubscribe route's check, D9). */
613
+ export async function consentPersonExists(
614
+ workspaceId: string,
615
+ personId: string,
616
+ db: Pick<Tx, "person"> = prisma,
617
+ ): Promise<boolean> {
618
+ const found = await db.person.findFirst({
619
+ where: { id: personId, workspaceId },
620
+ select: { id: true },
621
+ });
622
+ return found !== null;
623
+ }
624
+
625
+ // ─── The unsubscribe link (D3, D9, SEC-8438-9) ──────────────────────────────
626
+
627
+ /** Raised when a link is minted with no usable `AILK_CONSENT_LINK_SECRET`. */
628
+ export class ConsentLinkSecretMissing extends Error {
629
+ constructor() {
630
+ super(
631
+ "AILK_CONSENT_LINK_SECRET is unset or shorter than 32 bytes — no unsubscribe link can be minted",
632
+ );
633
+ this.name = "ConsentLinkSecretMissing";
634
+ }
635
+ }
636
+
637
+ /** A token older than this is refused. */
638
+ export const CONSENT_LINK_MAX_AGE_DAYS = 400;
639
+ const CONSENT_LINK_VERSION = "v1";
640
+
641
+ function linkSecret(): Buffer | null {
642
+ const secret = process.env["AILK_CONSENT_LINK_SECRET"];
643
+ if (secret === undefined || Buffer.byteLength(secret) < 32) return null;
644
+ return Buffer.from(secret);
645
+ }
646
+
647
+ /** Whether a usable link secret is configured (the route answers 503 otherwise). */
648
+ export function consentLinkSecretConfigured(): boolean {
649
+ return linkSecret() !== null;
650
+ }
651
+
652
+ function signLink(secret: Buffer, body: string): string {
653
+ return createHmac("sha256", secret).update(body).digest("base64url");
654
+ }
655
+
656
+ export interface ConsentLinkClaims {
657
+ workspaceId: string;
658
+ personId: string;
659
+ purposeId: string;
660
+ }
661
+
662
+ /**
663
+ * Mint the signed token an email's unsubscribe link carries:
664
+ * `v1.<base64url(JSON {w,p,u,iat})>.<base64url(HMAC-SHA256)>`. `v1` names the
665
+ * key generation, so a later rotation adds `v2` beside it. Throws
666
+ * `ConsentLinkSecretMissing` with no usable secret — a sender therefore
667
+ * cannot silently send an email without its link. The ids in the payload are
668
+ * readable, not secret; they grant nothing without the HMAC.
669
+ */
670
+ export function consentUnsubscribeToken(
671
+ claims: ConsentLinkClaims,
672
+ now: Date = new Date(),
673
+ ): string {
674
+ const secret = linkSecret();
675
+ if (secret === null) throw new ConsentLinkSecretMissing();
676
+ const payload = Buffer.from(
677
+ JSON.stringify({
678
+ w: claims.workspaceId,
679
+ p: claims.personId,
680
+ u: claims.purposeId,
681
+ iat: Math.floor(now.getTime() / 1000),
682
+ }),
683
+ ).toString("base64url");
684
+ const body = `${CONSENT_LINK_VERSION}.${payload}`;
685
+ return `${body}.${signLink(secret, body)}`;
686
+ }
687
+
688
+ const LINK_WORKSPACE_ID = /^wksp_[0-9a-f-]{36}$/;
689
+ const LINK_PERSON_ID = /^person_[0-9a-f-]{36}$/;
690
+ const LINK_PURPOSE_ID = /^[a-z][a-z0-9_]{0,63}$/;
691
+
692
+ /**
693
+ * Verify a token. Constant-time, and `null` on ANY defect — a wrong version,
694
+ * a flipped character, a malformed payload, a token older than 400 days or
695
+ * dated in the future, or an unset secret.
696
+ */
697
+ export function verifyConsentUnsubscribeToken(
698
+ token: string,
699
+ now: Date = new Date(),
700
+ ): ConsentLinkClaims | null {
701
+ const secret = linkSecret();
702
+ if (secret === null) return null;
703
+ const parts = token.split(".");
704
+ if (parts.length !== 3) return null;
705
+ const [version, payload, signature] = parts as [string, string, string];
706
+ if (version !== CONSENT_LINK_VERSION) return null;
707
+ const expected = Buffer.from(
708
+ signLink(secret, `${version}.${payload}`),
709
+ "utf8",
710
+ );
711
+ const given = Buffer.from(signature, "utf8");
712
+ if (given.length !== expected.length || !timingSafeEqual(given, expected)) {
713
+ return null;
714
+ }
715
+ let claims: unknown;
716
+ try {
717
+ claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
718
+ } catch {
719
+ return null;
720
+ }
721
+ if (typeof claims !== "object" || claims === null) return null;
722
+ const { w, p, u, iat } = claims as Record<string, unknown>;
723
+ if (
724
+ typeof w !== "string" ||
725
+ typeof p !== "string" ||
726
+ typeof u !== "string" ||
727
+ typeof iat !== "number" ||
728
+ !LINK_WORKSPACE_ID.test(w) ||
729
+ !LINK_PERSON_ID.test(p) ||
730
+ !LINK_PURPOSE_ID.test(u)
731
+ ) {
732
+ return null;
733
+ }
734
+ const ageMs = now.getTime() - iat * 1000;
735
+ if (ageMs > CONSENT_LINK_MAX_AGE_DAYS * 86_400_000 || ageMs < -300_000) {
736
+ return null;
737
+ }
738
+ return { workspaceId: w, personId: p, purposeId: u };
739
+ }