create-ailk 0.19.0 → 0.20.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 (197) hide show
  1. package/README.md +64 -7
  2. package/dist/add-module.js +7 -2
  3. package/dist/cli.js +35 -0
  4. package/dist/copy.d.ts +41 -0
  5. package/dist/copy.js +87 -21
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.js +1 -1
  8. package/dist/lib/fetch-template-snapshot.d.ts +21 -0
  9. package/dist/lib/fetch-template-snapshot.js +205 -0
  10. package/dist/lib/merge-three-way.d.ts +31 -0
  11. package/dist/lib/merge-three-way.js +65 -0
  12. package/dist/lib/scaffold-render-sweep.d.ts +23 -0
  13. package/dist/lib/scaffold-render-sweep.js +52 -0
  14. package/dist/module-architecture.js +64 -5
  15. package/dist/programmatic.d.ts +7 -1
  16. package/dist/programmatic.js +40 -3
  17. package/dist/site-roster.js +21 -4
  18. package/dist/spoke-checkout.d.ts +7 -0
  19. package/dist/spoke-checkout.js +8 -1
  20. package/dist/surfaces.d.ts +14 -0
  21. package/dist/surfaces.js +98 -3
  22. package/dist/template-record.d.ts +59 -0
  23. package/dist/template-record.js +183 -0
  24. package/dist/topology.js +29 -1
  25. package/dist/update.d.ts +48 -0
  26. package/dist/update.js +504 -0
  27. package/package.json +3 -3
  28. package/templates/.claude/cloudparity-repo-hooks.json +9 -0
  29. package/templates/.claude/hooks/architecture-check.sh +8 -0
  30. package/templates/.claude/rules/loop-contract.md +129 -0
  31. package/templates/.claude/settings.json +3 -2
  32. package/templates/.env.example +13 -0
  33. package/templates/CLAUDE.md +1 -1
  34. package/templates/CONVENTIONS.md +3 -2
  35. package/templates/_gitignore +162 -0
  36. package/templates/apps/api/.env.example +17 -1
  37. package/templates/apps/api/CLAUDE.md +18 -8
  38. package/templates/apps/api/package.json +2 -1
  39. package/templates/apps/api/src/__tests__/factories/in-memory-prisma.ts +41 -2
  40. package/templates/apps/api/src/__tests__/setup.ts +7 -0
  41. package/templates/apps/api/src/__tests__/stripe-boot.test.ts +132 -0
  42. package/templates/apps/api/src/bin/__tests__/rate-limit-probe.test.ts +184 -0
  43. package/templates/apps/api/src/bin/rate-limit-probe.ts +53 -0
  44. package/templates/apps/api/src/lib/__mocks__/prisma.ts +8 -0
  45. package/templates/apps/api/src/lib/__tests__/consent-ledger-double.ts +237 -0
  46. package/templates/apps/api/src/lib/__tests__/consent-store.test.ts +334 -0
  47. package/templates/apps/api/src/lib/__tests__/stripe-admission.test.ts +217 -0
  48. package/templates/apps/api/src/lib/__tests__/stripe.test.ts +7 -0
  49. package/templates/apps/api/src/lib/consent-store.ts +335 -0
  50. package/templates/apps/api/src/lib/proposal-paid-store.ts +49 -0
  51. package/templates/apps/api/src/lib/rate-limit-probe.ts +165 -0
  52. package/templates/apps/api/src/lib/rate-limit-store.ts +142 -0
  53. package/templates/apps/api/src/lib/stripe.ts +97 -5
  54. package/templates/apps/api/src/middleware/__tests__/auth.hub-session-path.test.ts +13 -4
  55. package/templates/apps/api/src/middleware/__tests__/default-tenant.test.ts +2 -0
  56. package/templates/apps/api/src/middleware/__tests__/rate-limit-cross-isolate.db.test.ts +220 -0
  57. package/templates/apps/api/src/middleware/__tests__/rate-limit-store.test.ts +430 -0
  58. package/templates/apps/api/src/middleware/__tests__/rate-limit.test.ts +72 -14
  59. package/templates/apps/api/src/middleware/auth.ts +16 -4
  60. package/templates/apps/api/src/middleware/default-tenant.ts +9 -0
  61. package/templates/apps/api/src/middleware/rate-limit.ts +295 -82
  62. package/templates/apps/api/src/routes/checkout/__tests__/live-key.test.ts +167 -0
  63. package/templates/apps/api/src/routes/checkout/session.ts +3 -3
  64. package/templates/apps/api/src/routes/checkout/sessions.ts +6 -4
  65. package/templates/apps/api/src/routes/consent/cookie.ts +90 -0
  66. package/templates/apps/api/src/routes/consent/index.ts +18 -0
  67. package/templates/apps/api/src/routes/consent/unsubscribe.ts +127 -0
  68. package/templates/apps/api/src/routes/leads/index.ts +15 -0
  69. package/templates/apps/api/src/routes/project-listings/__tests__/drafts.test.ts +5 -0
  70. package/templates/apps/api/src/routes/webhooks/README.md +33 -5
  71. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-flow-checkout.test.ts +17 -4
  72. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-idempotency.test.ts +2 -0
  73. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-livemode-live.test.ts +159 -0
  74. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-livemode.test.ts +158 -0
  75. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-proposal-paid.test.ts +369 -0
  76. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-rate-limit.test.ts +2 -0
  77. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-site-filter.test.ts +442 -0
  78. package/templates/apps/api/src/routes/webhooks/stripe.ts +201 -6
  79. package/templates/apps/api/src/server.ts +125 -18
  80. package/templates/apps/api/src/services/__tests__/audit-log.test.ts +91 -0
  81. package/templates/apps/api/src/services/__tests__/consent-ledger.test.ts +503 -0
  82. package/templates/apps/api/src/services/__tests__/consent.test.ts +18 -3
  83. package/templates/apps/api/src/services/__tests__/lead-routing.test.ts +115 -4
  84. package/templates/apps/api/src/services/__tests__/person.test.ts +392 -0
  85. package/templates/apps/api/src/services/__tests__/request-confirm.test.ts +87 -0
  86. package/templates/apps/api/src/services/__tests__/revalidation.test.ts +57 -17
  87. package/templates/apps/api/src/services/audit-log.ts +72 -10
  88. package/templates/apps/api/src/services/consent.ts +488 -3
  89. package/templates/apps/api/src/services/default-tenant.ts +12 -3
  90. package/templates/apps/api/src/services/hub-sign-in.ts +2 -1
  91. package/templates/apps/api/src/services/lead-routing.ts +105 -12
  92. package/templates/apps/api/src/services/person.ts +501 -1
  93. package/templates/apps/api/src/services/project-listings.ts +7 -2
  94. package/templates/apps/api/src/services/public-site-resolver.ts +21 -2
  95. package/templates/apps/api/src/services/request-confirm.ts +52 -0
  96. package/templates/apps/api/src/services/revalidation.ts +11 -1
  97. package/templates/apps/api/vercel.json +1 -1
  98. package/templates/apps/mcp/CLAUDE.md +19 -7
  99. package/templates/apps/mcp/__tests__/catalog-drift.test.ts +95 -8
  100. package/templates/apps/mcp/src/tools/person_notes.ts +25 -0
  101. package/templates/apps/mcp/src/tools/proposals.ts +27 -0
  102. package/templates/apps/mcp/src/workspace-server.ts +16 -0
  103. package/templates/apps/web/_gitignore +6 -0
  104. package/templates/apps/web/app/[locale]/(auth)/sign-up/__tests__/sign-up-card.test.tsx +165 -0
  105. package/templates/apps/web/app/[locale]/(auth)/sign-up/page.tsx +19 -0
  106. package/templates/apps/web/app/[locale]/(auth)/sign-up/sign-up-card.tsx +106 -23
  107. package/templates/apps/web/app/[locale]/(auth)/sign-up/sign-up.actions.ts +125 -0
  108. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/account-frame-sign-out.test.tsx +175 -0
  109. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/agreements-prompt.test.tsx +281 -0
  110. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/billing.test.tsx +17 -3
  111. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/general.test.tsx +154 -53
  112. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/hub-mode.test.tsx +116 -27
  113. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/item.test.tsx +57 -2
  114. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout-sign-out.test.tsx +146 -0
  115. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout.test.tsx +124 -18
  116. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/notifications.test.tsx +116 -18
  117. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/onboarding.test.tsx +323 -0
  118. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/privacy.test.tsx +365 -0
  119. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/security.test.tsx +290 -20
  120. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/settings.test.tsx +56 -0
  121. package/templates/apps/web/app/[locale]/(authed)/account/account-frame.tsx +74 -4
  122. package/templates/apps/web/app/[locale]/(authed)/account/actions.ts +8 -0
  123. package/templates/apps/web/app/[locale]/(authed)/account/agreements-actions.ts +170 -0
  124. package/templates/apps/web/app/[locale]/(authed)/account/agreements-prompt.tsx +181 -0
  125. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/page.tsx +88 -3
  126. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/pay-form.tsx +65 -0
  127. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/review-form.tsx +27 -0
  128. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/__tests__/page.test.tsx +176 -3
  129. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/__tests__/pay.test.tsx +193 -0
  130. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/__tests__/review.test.tsx +188 -0
  131. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/artifact-actions.ts +65 -4
  132. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/artifact-data.ts +17 -0
  133. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/page.tsx +15 -9
  134. package/templates/apps/web/app/[locale]/(authed)/account/billing/page.tsx +3 -3
  135. package/templates/apps/web/app/[locale]/(authed)/account/general/contact-actions.ts +81 -0
  136. package/templates/apps/web/app/[locale]/(authed)/account/general/page.tsx +70 -27
  137. package/templates/apps/web/app/[locale]/(authed)/account/layout.tsx +26 -3
  138. package/templates/apps/web/app/[locale]/(authed)/account/notifications/page.tsx +65 -19
  139. package/templates/apps/web/app/[locale]/(authed)/account/onboarding/actions.ts +120 -0
  140. package/templates/apps/web/app/[locale]/(authed)/account/onboarding/onboarding-form.tsx +322 -0
  141. package/templates/apps/web/app/[locale]/(authed)/account/onboarding/page.tsx +126 -0
  142. package/templates/apps/web/app/[locale]/(authed)/account/page.tsx +43 -1
  143. package/templates/apps/web/app/[locale]/(authed)/account/privacy/actions.ts +65 -0
  144. package/templates/apps/web/app/[locale]/(authed)/account/privacy/page.tsx +226 -0
  145. package/templates/apps/web/app/[locale]/(authed)/account/security/page.tsx +89 -37
  146. package/templates/apps/web/app/[locale]/(authed)/account/security/security-panel.tsx +102 -0
  147. package/templates/apps/web/app/[locale]/(authed)/account/security/security-source.ts +62 -0
  148. package/templates/apps/web/app/[locale]/(authed)/account/settings-frame.tsx +44 -34
  149. package/templates/apps/web/app/[locale]/(authed)/account/sign-in-method.ts +1 -1
  150. package/templates/apps/web/app/[locale]/consent-banner.tsx +32 -0
  151. package/templates/apps/web/app/[locale]/consent.actions.ts +71 -0
  152. package/templates/apps/web/app/[locale]/contact/contact.actions.ts +13 -1
  153. package/templates/apps/web/app/[locale]/flows/[slug]/flow.actions.ts +25 -3
  154. package/templates/apps/web/app/[locale]/layout.tsx +23 -2
  155. package/templates/apps/web/app/[locale]/newsletter/newsletter.actions.ts +12 -1
  156. package/templates/apps/web/app/[locale]/unsubscribe/__tests__/unsubscribe-rsc-boundary.test.tsx +209 -0
  157. package/templates/apps/web/app/[locale]/unsubscribe/__tests__/unsubscribe.test.tsx +158 -0
  158. package/templates/apps/web/app/[locale]/unsubscribe/page.tsx +54 -0
  159. package/templates/apps/web/app/[locale]/unsubscribe/unsubscribe-button.tsx +73 -0
  160. package/templates/apps/web/app/[locale]/unsubscribe/unsubscribe.actions.ts +55 -0
  161. package/templates/apps/web/app/robots.txt/route.ts +13 -10
  162. package/templates/apps/web/auth.ts +20 -1
  163. package/templates/apps/web/jest.config.cjs +3 -0
  164. package/templates/apps/web/lib/__tests__/auth-email.test.ts +84 -0
  165. package/templates/apps/web/lib/__tests__/consent-visitor.test.ts +163 -0
  166. package/templates/apps/web/lib/__tests__/relay.test.ts +49 -0
  167. package/templates/apps/web/lib/__tests__/structured-data.test.tsx +96 -7
  168. package/templates/apps/web/lib/account-config.ts +31 -16
  169. package/templates/apps/web/lib/auth-email.ts +45 -10
  170. package/templates/apps/web/lib/consent-visitor.ts +103 -0
  171. package/templates/apps/web/lib/relay.ts +20 -0
  172. package/templates/apps/web/lib/topology.generated.ts +9 -0
  173. package/templates/apps/web/messages/en.json +121 -18
  174. package/templates/apps/web/next.config.mjs +8 -2
  175. package/templates/database/CHANGELOG.md +55 -0
  176. package/templates/database/__tests__/consent-ledger.db.test.ts +345 -0
  177. package/templates/database/__tests__/fence-fan-out.db.test.ts +6 -2
  178. package/templates/database/__tests__/fixtures/person-contact-backfill.json +182 -0
  179. package/templates/database/__tests__/outbound-message-action.db.test.ts +80 -0
  180. package/templates/database/__tests__/person-contact.db.test.ts +563 -0
  181. package/templates/database/__tests__/person-notes.db.test.ts +249 -0
  182. package/templates/database/__tests__/person.db.test.ts +3 -1
  183. package/templates/database/__tests__/piece-kind-migration.test.ts +67 -0
  184. package/templates/database/__tests__/piece-kind.db.test.ts +208 -0
  185. package/templates/database/_gitignore +8 -0
  186. package/templates/database/inbox/schema.prisma +114 -22
  187. package/templates/database/migrations/20261014120000_consent_ledger/migration.sql +122 -0
  188. package/templates/database/migrations/20261014120000_person_contact/migration.sql +231 -0
  189. package/templates/database/migrations/20261015120000_person_notes/migration.sql +77 -0
  190. package/templates/database/migrations/20261015120000_rate_limit_counters/migration.sql +43 -0
  191. package/templates/database/migrations/20261016120000_piece_kind/migration.sql +95 -0
  192. package/templates/database/migrations/20261017120000_outbound_message_action/migration.sql +30 -0
  193. package/templates/database/ops/schema.prisma +16 -0
  194. package/templates/database/package.json +1 -1
  195. package/templates/project.yaml +6 -3
  196. package/versions.json +35 -35
  197. package/templates/.claude/rules/preserve-existing-style.md +0 -51
@@ -99,8 +99,8 @@ import { isUniqueViolation, type TenantContext } from "./default-tenant.js";
99
99
  // ─── Types ──────────────────────────────────────────────────────────────────
100
100
 
101
101
  /** The full actor-kind vocabulary the model comments (not a DB CHECK). This
102
- * file writes `"user"` and `"agent"` (#3591 D8); `"system"` is kept so a
103
- * future writer for that actor shares one union. */
102
+ * file writes `"user"` and `"agent"` (#3591 D8), and `"system"` for Stripe's
103
+ * payment outcome (#8516 D14, `recordWorkspaceAuditAction`). */
104
104
  export type AuditActorType = "user" | "agent" | "system";
105
105
 
106
106
  /**
@@ -210,6 +210,12 @@ export interface RecordAuditActionInput {
210
210
  targetId?: string;
211
211
  }
212
212
 
213
+ /** Every member of a row's input but who and where — shared by both writers. */
214
+ type AuditRowInput = Omit<RecordAuditActionInput, "tenant" | "actor">;
215
+
216
+ /** Every actor a row can name: a tenant caller's, or a tenant-less one's (D14). */
217
+ type WriterActor = AuditActor | { type: "system"; systemId: "stripe" };
218
+
213
219
  export type RecordAuditActionResult =
214
220
  | { ok: true; outcome: "recorded" | "duplicate"; id: Id<"auditLog"> }
215
221
  | {
@@ -487,7 +493,7 @@ function classifyError(error: unknown): { code: string; name: string } {
487
493
  interface ValidatedFields {
488
494
  workspaceId: string;
489
495
  actorId: string;
490
- actorType: "user" | "agent";
496
+ actorType: AuditActorType;
491
497
  onBehalfOf: string | undefined;
492
498
  tool: string;
493
499
  targetType: string | undefined;
@@ -547,15 +553,24 @@ function actorIdRefusal(id: string, field: string): string | undefined {
547
553
  * (never a silent rewrite of an identifier field) rather than as a
548
554
  * redaction, unlike `summary` / `failureReason`.
549
555
  */
550
- function validateInput(input: RecordAuditActionInput): ValidationResult {
551
- if (!zWorkspaceId.safeParse(input.tenant.workspaceId).success) {
556
+ function validateInput(
557
+ workspaceId: string,
558
+ workspaceField: string,
559
+ actor: WriterActor,
560
+ input: AuditRowInput,
561
+ ): ValidationResult {
562
+ if (!zWorkspaceId.safeParse(workspaceId).success) {
552
563
  return {
553
564
  ok: false,
554
- message: "tenant.workspaceId is not a valid workspace id",
565
+ message: `${workspaceField} is not a valid workspace id`,
555
566
  };
556
567
  }
557
- const { actor } = input;
558
- const actorId = actor.type === "agent" ? actor.agentId : actor.userId;
568
+ const actorId =
569
+ actor.type === "agent"
570
+ ? actor.agentId
571
+ : actor.type === "system"
572
+ ? actor.systemId
573
+ : actor.userId;
559
574
  const actorRefusal = actorIdRefusal(actorId, "actorId");
560
575
  if (actorRefusal !== undefined) {
561
576
  return { ok: false, message: actorRefusal };
@@ -628,7 +643,7 @@ function validateInput(input: RecordAuditActionInput): ValidationResult {
628
643
  return {
629
644
  ok: true,
630
645
  value: {
631
- workspaceId: input.tenant.workspaceId,
646
+ workspaceId,
632
647
  actorId,
633
648
  actorType: actor.type,
634
649
  onBehalfOf,
@@ -674,7 +689,54 @@ export async function recordAuditAction(
674
689
  input: RecordAuditActionInput,
675
690
  db: AuditWriteClient = prisma,
676
691
  ): Promise<RecordAuditActionResult> {
677
- const validated = validateInput(input);
692
+ const { tenant, actor, ...row } = input;
693
+ return writeAuditRow(tenant.workspaceId, "tenant.workspaceId", actor, row, db);
694
+ }
695
+
696
+ /**
697
+ * Who acted on a tenant-less row (#8516 D14): a client — a signed-in person
698
+ * with no membership — or Stripe itself, reporting a payment outcome.
699
+ */
700
+ export type WorkspaceAuditActor =
701
+ | { type: "user"; userId: Id<"user"> }
702
+ | { type: "system"; systemId: "stripe" };
703
+
704
+ /** `recordWorkspaceAuditAction`'s input: a workspace id in place of a tenant. */
705
+ export type RecordWorkspaceAuditActionInput = AuditRowInput & {
706
+ workspaceId: string;
707
+ actor: WorkspaceAuditActor;
708
+ };
709
+
710
+ /**
711
+ * One `audit_logs` row for a caller that holds no `TenantContext` (#8516
712
+ * D14): a client acting in the member area, or a Stripe webhook. Writes the
713
+ * row `recordAuditAction` would for the same workspace and user actor; the
714
+ * system actor stores `actor_type` `system` and `actor_id` `stripe`. Never
715
+ * throws; never blocks the caller's action.
716
+ *
717
+ * CALLER OBLIGATION — `workspaceId` MUST come from `resolveMember`'s
718
+ * resolved workspace, or from a Stripe-signed event's server-written
719
+ * metadata matched to a stored row — NEVER from request input. A client
720
+ * actor's row says so in its `tool` and summary (`by: "client"`), so it is
721
+ * never read as a staff member's action.
722
+ */
723
+ export async function recordWorkspaceAuditAction(
724
+ input: RecordWorkspaceAuditActionInput,
725
+ db: AuditWriteClient = prisma,
726
+ ): Promise<RecordAuditActionResult> {
727
+ const { workspaceId, actor, ...row } = input;
728
+ return writeAuditRow(workspaceId, "workspaceId", actor, row, db);
729
+ }
730
+
731
+ /** The body of both writers: one validated, digested, idempotent insert. */
732
+ async function writeAuditRow(
733
+ workspaceIdInput: string,
734
+ workspaceField: string,
735
+ actor: WriterActor,
736
+ input: AuditRowInput,
737
+ db: AuditWriteClient,
738
+ ): Promise<RecordAuditActionResult> {
739
+ const validated = validateInput(workspaceIdInput, workspaceField, actor, input);
678
740
  if (!validated.ok) {
679
741
  return {
680
742
  ok: false,
@@ -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
+ }