create-safest-tools 0.6.0 → 0.7.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 (172) hide show
  1. package/README.md +3 -3
  2. package/package.json +2 -2
  3. package/src/config.mjs +2 -2
  4. package/src/update.mjs +10 -1
  5. package/template/README.md +2 -2
  6. package/template/console/README.md +2 -2
  7. package/template/console/analytics/AnalyticsWorkspace.tsx +49 -36
  8. package/template/console/analytics/controller.ts +10 -2
  9. package/template/console/analytics/types.ts +7 -0
  10. package/template/console/appeals/AppealFollowup.tsx +171 -0
  11. package/template/console/appeals/AppealWorkspace.tsx +33 -4
  12. package/template/console/appeals/RecordAppealDialog.tsx +42 -0
  13. package/template/console/appeals/appeal-corrections.css +29 -0
  14. package/template/console/appeals/controller.ts +40 -14
  15. package/template/console/appeals/events.ts +1 -0
  16. package/template/console/appeals/types.ts +6 -0
  17. package/template/console/appeals/useAppealDraftGuard.ts +12 -0
  18. package/template/console/assistant/AssistantWorkspace.tsx +28 -5
  19. package/template/console/command/CommandCentre.tsx +101 -64
  20. package/template/console/command/controller.ts +80 -70
  21. package/template/console/command/events.ts +1 -2
  22. package/template/console/command/presentation.ts +29 -0
  23. package/template/console/command/store.ts +4 -4
  24. package/template/console/command/types.ts +26 -21
  25. package/template/console/configuration/ConfigurationBuilders.tsx +101 -0
  26. package/template/console/configuration/ConfigurationDialog.tsx +28 -13
  27. package/template/console/configuration/ConfigurationWorkspace.tsx +21 -8
  28. package/template/console/configuration/types.ts +1 -1
  29. package/template/console/lib/priority.ts +13 -0
  30. package/template/console/operations/CaseEscalations.tsx +142 -0
  31. package/template/console/operations/OperationsWorkspace.tsx +2 -0
  32. package/template/console/operations/case-escalations.css +20 -0
  33. package/template/console/people/PeopleWorkspace.tsx +8 -4
  34. package/template/console/people/PersonAccessDialog.tsx +40 -0
  35. package/template/console/people/types.ts +1 -0
  36. package/template/console/profile/ProfileWorkspace.tsx +1 -1
  37. package/template/console/registry/IntegrationSetup.tsx +41 -0
  38. package/template/console/registry/IntegrationVerification.tsx +54 -0
  39. package/template/console/registry/RegistryDetailsDialog.tsx +2 -2
  40. package/template/console/registry/RegistryDialog.tsx +56 -27
  41. package/template/console/registry/RegistryWorkspace.tsx +10 -5
  42. package/template/console/registry/integration-verification.css +25 -0
  43. package/template/console/reports/CaseActions.tsx +81 -0
  44. package/template/console/reports/CaseContinuity.tsx +27 -0
  45. package/template/console/reports/CaseNotices.tsx +48 -0
  46. package/template/console/reports/CaseOwnership.tsx +78 -0
  47. package/template/console/reports/CaseReviewTasks.tsx +148 -0
  48. package/template/console/reports/EnrichmentFindings.tsx +148 -0
  49. package/template/console/reports/InvestigationBrief.tsx +29 -0
  50. package/template/console/reports/ReportDrawer.tsx +122 -67
  51. package/template/console/reports/ReportWorkspace.tsx +112 -23
  52. package/template/console/reports/controller.ts +125 -60
  53. package/template/console/reports/events.ts +9 -2
  54. package/template/console/reports/load-inbox.ts +17 -0
  55. package/template/console/reports/presence-presentation.ts +52 -0
  56. package/template/console/reports/private-drafts.ts +32 -0
  57. package/template/console/reports/store.ts +2 -2
  58. package/template/console/reports/types.ts +50 -2
  59. package/template/console/reports/use-editing-access.ts +13 -0
  60. package/template/console/settings/SettingsWorkspace.tsx +1 -1
  61. package/template/console/shell/WorkspaceShell.tsx +55 -29
  62. package/template/console/shell/WorkspaceUpdateNotice.tsx +48 -0
  63. package/template/console/shell/controller.ts +23 -16
  64. package/template/console/shell/navigation.ts +30 -39
  65. package/template/console/workflows/CreatePlaybookDialog.tsx +73 -0
  66. package/template/console/workflows/PlaybookExamples.tsx +160 -0
  67. package/template/console/workflows/PlaybookFields.tsx +109 -0
  68. package/template/console/workflows/PlaybookGuideEditor.tsx +125 -0
  69. package/template/console/workflows/PlaybookHistory.tsx +106 -0
  70. package/template/console/workflows/WorkflowDialogs.tsx +2 -1
  71. package/template/console/workflows/WorkflowStudio.tsx +108 -39
  72. package/template/console/workflows/WorkflowWorkspace.tsx +9 -7
  73. package/template/console/workflows/templates.ts +3 -3
  74. package/template/console/workflows/types.ts +11 -0
  75. package/template/migrations/0001_safest_resolve_baseline.sql +0 -1
  76. package/template/migrations/0002_playbook_publication_evidence.sql +36 -0
  77. package/template/migrations/0003_action_confirmation.sql +24 -0
  78. package/template/migrations/0004_notice_recovery.sql +22 -0
  79. package/template/migrations/0005_appeal_continuity.sql +17 -0
  80. package/template/migrations/0006_case_ownership.sql +23 -0
  81. package/template/migrations/0007_integration_verification.sql +21 -0
  82. package/template/migrations/0008_case_escalations.sql +135 -0
  83. package/template/migrations/0009_participant_continuation.sql +61 -0
  84. package/template/migrations/0010_appeal_corrections.sql +41 -0
  85. package/template/npm-shrinkwrap.json +8036 -0
  86. package/template/package.json +31 -22
  87. package/template/public/_headers +16 -1
  88. package/template/public/console/auth-shell.js +22151 -14847
  89. package/template/public/console/release.json +1 -0
  90. package/template/public/console/workspace-features.css +2 -0
  91. package/template/public/embed/embed.css +3 -0
  92. package/template/public/embed/embed.js +19 -1
  93. package/template/public/embed/index.html +2 -0
  94. package/template/public/index.html +9 -6
  95. package/template/public/participant.css +2 -0
  96. package/template/public/participant.html +13 -0
  97. package/template/public/participant.js +111 -0
  98. package/template/public/public-report.js +21 -1
  99. package/template/public/report/index.html +1 -1
  100. package/template/public/styles.css +599 -83
  101. package/template/public/workspace.css +124 -0
  102. package/template/scripts/reports-plan.mjs +1 -1
  103. package/template/shared/case-escalations.ts +31 -0
  104. package/template/shared/integration-progress.ts +27 -0
  105. package/template/shared/notice-inputs.ts +3 -0
  106. package/template/shared/playbook-resources.ts +14 -0
  107. package/template/shared/playbooks.ts +249 -0
  108. package/template/src/agent-executor.ts +25 -8
  109. package/template/src/ai-observability.ts +14 -13
  110. package/template/src/ai-registry-validation.ts +1 -1
  111. package/template/src/appeal-continuity.ts +75 -0
  112. package/template/src/appeal-correction-state.ts +46 -0
  113. package/template/src/appeal-corrections.ts +112 -0
  114. package/template/src/appeal-decisions.ts +85 -0
  115. package/template/src/assistant.ts +3 -4
  116. package/template/src/case-escalations.ts +223 -0
  117. package/template/src/case-investigator.ts +179 -0
  118. package/template/src/component-executor.ts +5 -4
  119. package/template/src/configuration-registry.ts +4 -1
  120. package/template/src/connection-oauth.ts +12 -3
  121. package/template/src/database-readiness.ts +14 -0
  122. package/template/src/human-tasks.ts +152 -55
  123. package/template/src/index.ts +191 -29
  124. package/template/src/installation-admin.ts +2 -1
  125. package/template/src/integration-progress.ts +45 -0
  126. package/template/src/integration-verification.ts +249 -0
  127. package/template/src/investigation-evidence.ts +95 -0
  128. package/template/src/investigator-fixture.ts +30 -0
  129. package/template/src/notice-delivery.ts +19 -0
  130. package/template/src/notice-recovery.ts +81 -0
  131. package/template/src/operator-scope.ts +31 -0
  132. package/template/src/participant-access.ts +163 -0
  133. package/template/src/participant-case.ts +87 -0
  134. package/template/src/participant-customer-access.ts +93 -0
  135. package/template/src/participant-recovery.ts +43 -0
  136. package/template/src/participant-routes.ts +67 -0
  137. package/template/src/platform-registry-validation.ts +25 -2
  138. package/template/src/platform-registry.ts +10 -7
  139. package/template/src/playbook-resources.ts +58 -0
  140. package/template/src/report-admin.ts +9 -2
  141. package/template/src/report-auth.ts +1 -28
  142. package/template/src/report-better-auth.ts +18 -6
  143. package/template/src/report-delivery.ts +149 -148
  144. package/template/src/report-email-inbound.ts +33 -22
  145. package/template/src/report-email-template.ts +5 -2
  146. package/template/src/report-email.ts +7 -30
  147. package/template/src/report-governance.ts +42 -45
  148. package/template/src/report-http.ts +37 -2
  149. package/template/src/report-operations.ts +30 -67
  150. package/template/src/report-operator-accounts.ts +7 -6
  151. package/template/src/report-ownership.ts +64 -0
  152. package/template/src/report-presence.ts +15 -9
  153. package/template/src/report-repository.ts +16 -7
  154. package/template/src/report-turnstile.ts +7 -3
  155. package/template/src/report-types.ts +1 -0
  156. package/template/src/report-workflow.ts +183 -249
  157. package/template/src/workflow-actions.ts +248 -156
  158. package/template/src/workflow-compiler.ts +63 -12
  159. package/template/src/workflow-dynamic-runtime.ts +20 -9
  160. package/template/src/workflow-effects.ts +117 -39
  161. package/template/src/workflow-event-transport.ts +16 -0
  162. package/template/src/workflow-expressions.ts +30 -0
  163. package/template/src/workflow-loader-code.ts +21 -0
  164. package/template/src/workflow-platform-types.ts +3 -0
  165. package/template/src/workflow-platform-validation.ts +23 -1
  166. package/template/src/workflow-repository.ts +131 -28
  167. package/template/src/workflow-runs.ts +61 -13
  168. package/template/src/workflow-simulator.ts +7 -4
  169. package/template/src/workspace-governance.ts +6 -4
  170. package/template/tsconfig.json +1 -0
  171. package/template/vite.console.config.ts +30 -2
  172. package/template/worker-configuration.d.ts +3 -2
@@ -1,10 +1,13 @@
1
1
  import { canonicalJson } from "./audit";
2
2
  import type { DeliveryJob } from "./report-types";
3
- import { decryptReportContact } from "./report-crypto";
3
+ import { decryptReportContact, sha256 } from "./report-crypto";
4
4
  import { BudgetControlError, reserveBudgets, settleBudgets } from "./budget-control";
5
5
  import { reporterEmailBinding, reporterEmailFrom, reporterEmailSubjectPrefix, reporterReplyAddress } from "./report-email";
6
6
  import { renderReporterEmail } from "./report-email-template";
7
+ import { ApiError, readBoundedBytes } from "./report-http";
7
8
  import { loadWorkspaceBrand } from "./workspace-branding";
9
+ import { signalNoticeDelivery } from "./notice-delivery";
10
+ import { issueParticipantAccessLink, lookupParticipantAccessLink } from "./participant-access";
8
11
 
9
12
  const MAX_ATTEMPTS = 8;
10
13
  const RESPONSE_LIMIT = 16 * 1024;
@@ -28,6 +31,8 @@ interface NotificationOutboxRow {
28
31
  payload_json: string;
29
32
  status: string;
30
33
  attempt_count: number;
34
+ attempt_limit: number;
35
+ message_id: string | null;
31
36
  audience: "reporter" | "affected_user";
32
37
  recipient_reference: string | null;
33
38
  contact_ciphertext: string | null;
@@ -40,6 +45,9 @@ interface EmailDeliveryRow {
40
45
  audience: "reporter" | "affected_user";
41
46
  state: string;
42
47
  attemptCount: number;
48
+ attemptLimit: number;
49
+ claimedAt: string;
50
+ recipientHash: string;
43
51
  recipientReference: string | null;
44
52
  contactCiphertext: string | null;
45
53
  body: string;
@@ -57,7 +65,7 @@ export class RetryableDeliveryError extends Error {
57
65
  }
58
66
 
59
67
  export class DeliveryConfigurationError extends Error {
60
- constructor(message: string) {
68
+ constructor(message: string, readonly code?: string) {
61
69
  super(message);
62
70
  this.name = "DeliveryConfigurationError";
63
71
  }
@@ -106,25 +114,11 @@ export async function boundedResponse(response: Response): Promise<Record<string
106
114
  await response.body?.cancel().catch(() => {});
107
115
  return null;
108
116
  }
109
- if (!response.body) return {};
110
- const reader = response.body.getReader();
111
- const chunks: Uint8Array[] = [];
112
- let length = 0;
113
- while (true) {
114
- const result = await reader.read();
115
- if (result.done) break;
116
- length += result.value.byteLength;
117
- if (length > RESPONSE_LIMIT) {
118
- await reader.cancel().catch(() => {});
119
- return null;
120
- }
121
- chunks.push(result.value);
122
- }
123
- const bytes = new Uint8Array(length);
124
- let offset = 0;
125
- for (const chunk of chunks) {
126
- bytes.set(chunk, offset);
127
- offset += chunk.byteLength;
117
+ let bytes: Uint8Array;
118
+ try {
119
+ bytes = await readBoundedBytes(response.body, RESPONSE_LIMIT, () => new Error("delivery_response_too_large"));
120
+ } catch {
121
+ return null;
128
122
  }
129
123
  if (!bytes.length) return {};
130
124
  try {
@@ -199,16 +193,16 @@ async function claimNotification(db: D1Database, id: string): Promise<Notificati
199
193
  UPDATE notification_outbox
200
194
  SET status = 'delivering', attempt_count = attempt_count + 1,
201
195
  lease_expires_at = ?2, updated_at = ?1
202
- WHERE id = ?3 AND terminal = 0 AND attempt_count < ?4
196
+ WHERE id = ?3 AND terminal = 0 AND attempt_count < attempt_limit
203
197
  AND (
204
198
  status = 'pending'
205
199
  OR (status = 'failed' AND next_attempt_at <= ?1)
206
200
  OR (status = 'delivering' AND lease_expires_at <= ?1)
207
201
  )
208
- `).bind(claimedAt, plusSeconds(claimedAt, 60), id, MAX_ATTEMPTS).run();
202
+ `).bind(claimedAt, plusSeconds(claimedAt, 60), id).run();
209
203
  if ((result.meta.changes ?? 0) < 1) return null;
210
204
  return db.prepare(`
211
- SELECT o.id, n.report_id, o.notice_id, o.idempotency_key, o.payload_json, o.status, o.attempt_count,
205
+ SELECT o.id, n.report_id, o.notice_id, o.idempotency_key, o.payload_json, o.status, o.attempt_count, o.attempt_limit, n.message_id,
212
206
  n.audience, p.reference AS recipient_reference, p.contact_ciphertext
213
207
  FROM notification_outbox o JOIN notices n ON n.id = o.notice_id
214
208
  LEFT JOIN report_participants p ON p.report_id = n.report_id AND p.audience = n.audience
@@ -221,14 +215,14 @@ async function claimEmail(db: D1Database, id: string): Promise<EmailDeliveryRow
221
215
  const staleAt = plusSeconds(claimedAt, -60);
222
216
  const result = await db.prepare(`
223
217
  UPDATE email_deliveries SET state = 'sending', attempt_count = attempt_count + 1,
224
- updated_at = ?2 WHERE id = ?1 AND attempt_count < ?3
218
+ updated_at = ?2 WHERE id = ?1 AND attempt_count < attempt_limit
225
219
  AND (state = 'pending' OR (state = 'failed' AND next_attempt_at <= ?2)
226
- OR (state = 'sending' AND updated_at <= ?4))
227
- `).bind(id, claimedAt, MAX_ATTEMPTS, staleAt).run();
220
+ OR (state = 'sending' AND updated_at <= ?3))
221
+ `).bind(id, claimedAt, staleAt).run();
228
222
  if ((result.meta.changes ?? 0) < 1) return null;
229
223
  return db.prepare(`
230
224
  SELECT e.id, m.report_id AS reportId, e.message_id AS messageId,
231
- e.audience, e.state, e.attempt_count AS attemptCount,
225
+ e.audience, e.state, e.attempt_count AS attemptCount, e.attempt_limit AS attemptLimit, e.updated_at AS claimedAt, e.recipient_hash AS recipientHash,
232
226
  p.reference AS recipientReference, p.contact_ciphertext AS contactCiphertext,
233
227
  m.body, m.template_version_id AS templateVersionId, r.public_reference AS reportReference,
234
228
  r.installation_id AS installationId, r.queue_id AS queueId
@@ -243,14 +237,17 @@ async function claimEmail(db: D1Database, id: string): Promise<EmailDeliveryRow
243
237
  function deliveryAudit(
244
238
  db: D1Database,
245
239
  input: { key: string; action: string; targetType: string; targetId: string; reportId: string; details: unknown; createdAt: string },
240
+ receipt?: { table: "notification_attempts" | "email_delivery_attempts"; id: string },
246
241
  ): D1PreparedStatement {
247
242
  return db.prepare(`
248
243
  INSERT OR IGNORE INTO audit_events (
249
244
  id, idempotency_key, action, actor_type, actor_id, target_type, target_id, details_json, created_at
250
- ) VALUES (?1, ?2, ?3, 'system', 'delivery-worker', ?4, ?5, ?6, ?7)
245
+ ) SELECT ?1, ?2, ?3, 'system', 'delivery-worker', ?4, ?5, ?6, ?7
246
+ ${receipt ? `WHERE EXISTS (SELECT 1 FROM ${receipt.table} WHERE id = ?8)` : ""}
251
247
  `).bind(
252
248
  crypto.randomUUID(), input.key, input.action, input.targetType, input.targetId,
253
249
  canonicalJson({ reportId: input.reportId, ...input.details as Record<string, unknown> }), input.createdAt,
250
+ ...(receipt ? [receipt.id] : []),
254
251
  );
255
252
  }
256
253
 
@@ -344,14 +341,14 @@ async function processAction(db: D1Database, outboxId: string, env: Env): Promis
344
341
  if (!terminal) throw new RetryableDeliveryError(retryDelay);
345
342
  }
346
343
 
347
- async function updateNoticeDelivery(db: D1Database, noticeId: string, state: "delivered" | "failed", timestamp: string): Promise<void> {
348
- await db.batch([
349
- db.prepare(`UPDATE notices SET delivery_state = ?2, updated_at = ?3 WHERE id = ?1`).bind(noticeId, state, timestamp),
350
- db.prepare(`
351
- UPDATE case_messages SET delivery_state = ?2
352
- WHERE id = (SELECT message_id FROM notices WHERE id = ?1)
353
- `).bind(noticeId, state),
354
- ]);
344
+ function localNotificationTransport(env: Env): typeof fetch | undefined {
345
+ // Only the disposable loopback demo can use its local customer service binding.
346
+ if (env.AI_LOCAL_FIXTURE_ENABLED !== "true" || env.NOTIFICATION_WEBHOOK_URL !== "https://safest-notice-harness.invalid/api/safest/notices") return;
347
+ try {if (!["localhost", "127.0.0.1"].includes(new URL(env.PUBLIC_BASE_URL).hostname)) return;} catch {return;}
348
+ const candidate: unknown = Reflect.get(env, "NOTICE_CUSTOMER");
349
+ if (!candidate || typeof candidate !== "object" || !("fetch" in candidate) || typeof candidate.fetch !== "function") return;
350
+ const binding = candidate as Fetcher;
351
+ return (input, init) => binding.fetch(input, init);
355
352
  }
356
353
 
357
354
  async function processNotification(db: D1Database, outboxId: string, env: Env): Promise<void> {
@@ -368,13 +365,29 @@ async function processNotification(db: D1Database, outboxId: string, env: Env):
368
365
  } catch {
369
366
  payload = {};
370
367
  }
368
+ if ("recipient_contact_fingerprint" in payload) {
369
+ const fingerprint = row.contact_ciphertext ? await sha256(row.contact_ciphertext) : null;
370
+ if (payload.recipient_contact_fingerprint !== fingerprint || (payload.recipient_reference ?? null) !== row.recipient_reference) throw new DeliveryConfigurationError("The participant identity changed after this notice was prepared.", "notice_recipient_changed");
371
+ delete payload.recipient_contact_fingerprint;
372
+ }
371
373
  const recipientEmail = row.contact_ciphertext
372
374
  ? (await decryptReportContact(env.CREDENTIAL_ENCRYPTION_KEY, row.contact_ciphertext, row.report_id, row.audience)).trim().toLowerCase()
373
375
  : null;
376
+ const accessInput = {
377
+ reportId: row.report_id, audience: row.audience, deliveryKey: `notice:${row.id}`,
378
+ expectedIdentity: { reference: row.recipient_reference, contactCiphertext: row.contact_ciphertext },
379
+ };
380
+ // Keep webhook retries byte-equivalent even for a notice first sent by an
381
+ // older build without a participant link. Existing grants reproduce the
382
+ // original link; an upgrade must never add a new credential to an old retry.
383
+ const participantUrl = row.attempt_count === 1
384
+ ? await issueParticipantAccessLink(env, accessInput)
385
+ : await lookupParticipantAccessLink(env, accessInput);
374
386
  const deliveryPayload = canonicalJson({
375
387
  ...payload,
376
388
  ...(row.recipient_reference ? { recipient_reference: row.recipient_reference } : {}),
377
389
  ...(recipientEmail ? { recipient_email: recipientEmail } : {}),
390
+ ...(participantUrl ? { participant_url: participantUrl } : {}),
378
391
  });
379
392
  const response = await sendWebhook({
380
393
  url: env.NOTIFICATION_WEBHOOK_URL,
@@ -383,76 +396,84 @@ async function processNotification(db: D1Database, outboxId: string, env: Env):
383
396
  event: "participant.notification.requested",
384
397
  idempotencyKey: row.idempotency_key,
385
398
  payload: deliveryPayload,
386
- });
399
+ }, localNotificationTransport(env));
387
400
  status = response.status;
388
401
  } catch (error) {
389
402
  errorCode = error instanceof DeliveryConfigurationError
390
- ? "webhook_configuration_error"
403
+ ? error.code ?? "webhook_configuration_error"
404
+ : error instanceof ApiError && error.code === "participant_access_unavailable" ? "notice_recipient_changed"
391
405
  : error instanceof DOMException && error.name === "AbortError" ? "webhook_timeout" : "webhook_network_error";
392
406
  }
393
407
  const finishedAt = now();
394
408
  const attemptId = crypto.randomUUID();
395
- if (status !== null && responseClass(status) === "success") {
396
- await db.batch([
397
- db.prepare(`
398
- UPDATE notification_outbox SET status = 'delivered', terminal = 1,
399
- lease_expires_at = NULL, last_error_code = NULL, updated_at = ?2 WHERE id = ?1
400
- `).bind(row.id, finishedAt),
401
- db.prepare(`
402
- INSERT INTO notification_attempts (
403
- id, notification_id, attempt_number, response_class, response_status, started_at, finished_at
404
- ) VALUES (?1, ?2, ?3, 'delivered', ?4, ?5, ?6)
405
- `).bind(attemptId, row.id, row.attempt_count, status, startedAt, finishedAt),
406
- deliveryAudit(db, {
407
- key: `notification-delivery:${row.id}:delivered`,
408
- action: "notification.delivered",
409
- targetType: "notification",
410
- targetId: row.id,
411
- reportId: row.report_id,
412
- details: { responseStatus: status, attemptCount: row.attempt_count },
413
- createdAt: finishedAt,
414
- }),
415
- ]);
416
- await updateNoticeDelivery(db, row.notice_id, "delivered", finishedAt);
417
- return;
418
- }
419
- if (status !== null) errorCode = `webhook_http_${status}`;
420
- const temporary = errorCode !== "webhook_configuration_error"
409
+ const delivered = status !== null && responseClass(status) === "success";
410
+ if (status !== null && !delivered) errorCode = `webhook_http_${status}`;
411
+ const temporary = errorCode !== "webhook_configuration_error" && errorCode !== "notice_recipient_changed"
421
412
  && (status === null || responseClass(status) === "temporary_failure");
422
- const terminal = !temporary || row.attempt_count >= MAX_ATTEMPTS;
413
+ const terminal = delivered || !temporary || row.attempt_count >= row.attempt_limit;
423
414
  const retryDelay = delay(row.attempt_count);
424
415
  const statements = [
425
- db.prepare(`
426
- UPDATE notification_outbox SET status = 'failed', terminal = ?2,
427
- next_attempt_at = ?3, lease_expires_at = NULL, last_error_code = ?4, updated_at = ?5
428
- WHERE id = ?1
429
- `).bind(row.id, terminal ? 1 : 0, plusSeconds(finishedAt, retryDelay), errorCode, finishedAt),
430
- db.prepare(`
431
- INSERT INTO notification_attempts (
432
- id, notification_id, attempt_number, response_class, response_status, error_code, started_at, finished_at
433
- ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
434
- `).bind(attemptId, row.id, row.attempt_count, terminal ? "permanent_failure" : "temporary_failure", status, errorCode, startedAt, finishedAt),
416
+ db.prepare(`UPDATE notification_outbox SET status = ?2, terminal = ?3,
417
+ next_attempt_at = ?4, lease_expires_at = NULL, last_error_code = ?5, updated_at = ?6
418
+ WHERE id = ?1 AND status = 'delivering' AND attempt_count = ?7 AND terminal = 0`)
419
+ .bind(row.id, delivered ? "delivered" : "failed", terminal ? 1 : 0, plusSeconds(finishedAt, retryDelay), delivered ? null : errorCode, finishedAt, row.attempt_count),
420
+ db.prepare(`INSERT INTO notification_attempts (id, notification_id, attempt_number, response_class, response_status, error_code, started_at, finished_at)
421
+ SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8 WHERE changes() = 1`)
422
+ .bind(attemptId, row.id, row.attempt_count, delivered ? "delivered" : terminal ? "permanent_failure" : "temporary_failure", status, delivered ? null : errorCode, startedAt, finishedAt),
435
423
  ];
436
- if (terminal) statements.push(deliveryAudit(db, {
437
- key: `notification-delivery:${row.id}:failed`,
438
- action: "notification.delivery_failed",
439
- targetType: "notification",
440
- targetId: row.id,
441
- reportId: row.report_id,
442
- details: { errorCode, responseStatus: status, attemptCount: row.attempt_count },
443
- createdAt: finishedAt,
444
- }));
445
- await db.batch(statements);
446
- if (terminal) await updateNoticeDelivery(db, row.notice_id, "failed", finishedAt);
424
+ if (terminal) statements.push(
425
+ db.prepare(`UPDATE notices SET delivery_state = ?2, updated_at = ?3 WHERE id = ?1
426
+ AND EXISTS (SELECT 1 FROM notification_attempts WHERE id = ?4)`)
427
+ .bind(row.notice_id, delivered ? "delivered" : "failed", finishedAt, attemptId),
428
+ db.prepare(`UPDATE case_messages SET delivery_state = ?2 WHERE id = (SELECT message_id FROM notices WHERE id = ?1)
429
+ AND EXISTS (SELECT 1 FROM notification_attempts WHERE id = ?3)`)
430
+ .bind(row.notice_id, delivered ? "delivered" : "failed", attemptId),
431
+ deliveryAudit(db, {
432
+ key: `notification-delivery:${row.id}:${row.attempt_count}:${delivered ? "delivered" : "failed"}`,
433
+ action: delivered ? "notification.delivered" : "notification.delivery_failed", targetType: "notification", targetId: row.id,
434
+ reportId: row.report_id, details: { responseStatus: status, attemptCount: row.attempt_count, errorCode: delivered ? null : errorCode }, createdAt: finishedAt,
435
+ }, {table: "notification_attempts", id: attemptId}),
436
+ );
437
+ const written = await db.batch(statements);
438
+ if (written[0]?.meta.changes !== 1) return;
439
+ if (terminal && row.message_id) await signalNoticeDelivery(env, row.message_id, `notification-${row.attempt_count}`);
447
440
  if (!terminal) throw new RetryableDeliveryError(retryDelay);
448
441
  }
449
442
 
443
+ async function commitEmailResult(db: D1Database, env: Env, row: EmailDeliveryRow, input: {
444
+ state: "delivered" | "failed" | "suppressed"; terminal: boolean; nextAttemptAt: string | null;
445
+ errorCode: string | null; providerMessageId?: string | null;
446
+ }): Promise<boolean> {
447
+ const timestamp = now(), attemptId = crypto.randomUUID();
448
+ const statements = [
449
+ db.prepare(`UPDATE email_deliveries SET state = ?2, provider_message_id = COALESCE(?3, provider_message_id),
450
+ last_error_code = ?4, next_attempt_at = ?5, delivered_at = CASE WHEN ?2 = 'delivered' THEN ?6 ELSE delivered_at END, updated_at = ?6
451
+ WHERE id = ?1 AND state = 'sending' AND attempt_count = ?7 AND updated_at = ?8`)
452
+ .bind(row.id, input.state, input.providerMessageId ?? null, input.errorCode, input.nextAttemptAt, timestamp, row.attemptCount, row.claimedAt),
453
+ db.prepare(`INSERT INTO email_delivery_attempts (id, delivery_id, attempt_number, result, provider_message_id, error_code, started_at, finished_at)
454
+ SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8 WHERE changes() = 1`)
455
+ .bind(attemptId, row.id, row.attemptCount, input.state, input.providerMessageId ?? null, input.errorCode, row.claimedAt, timestamp),
456
+ ];
457
+ if (input.terminal) statements.push(
458
+ db.prepare(`UPDATE case_messages SET delivery_state = ?2 WHERE id = ?1 AND EXISTS (SELECT 1 FROM email_delivery_attempts WHERE id = ?3)`)
459
+ .bind(row.messageId, input.state, attemptId),
460
+ db.prepare(`UPDATE notices SET delivery_state = ?2, updated_at = ?3 WHERE message_id = ?1 AND EXISTS (SELECT 1 FROM email_delivery_attempts WHERE id = ?4)`)
461
+ .bind(row.messageId, input.state, timestamp, attemptId),
462
+ deliveryAudit(db, {
463
+ key: `email-delivery:${row.id}:${row.attemptCount}:${input.state}`, action: input.state === "delivered" ? "email.delivered" : "email.delivery_failed",
464
+ targetType: "email_delivery", targetId: row.id, reportId: row.reportId,
465
+ details: {provider: "cloudflare_email_service", attemptCount: row.attemptCount, errorCode: input.errorCode}, createdAt: timestamp,
466
+ }, {table: "email_delivery_attempts", id: attemptId}),
467
+ );
468
+ const written = await db.batch(statements);
469
+ if (written[0]?.meta.changes !== 1) return false;
470
+ if (input.terminal) await signalNoticeDelivery(env, row.messageId, `email-${row.attemptCount}`);
471
+ return true;
472
+ }
473
+
450
474
  async function processEmail(db: D1Database, deliveryId: string, env: Env): Promise<void> {
451
475
  const row = await claimEmail(db, deliveryId);
452
476
  if (!row) return;
453
- const email = row.contactCiphertext
454
- ? (await decryptReportContact(env.CREDENTIAL_ENCRYPTION_KEY, row.contactCiphertext, row.reportId, row.audience)).trim().toLowerCase()
455
- : row.recipientReference?.trim().toLowerCase() ?? "";
456
477
  const from = reporterEmailFrom(env);
457
478
  const binding = reporterEmailBinding(env);
458
479
  let reservations;
@@ -465,29 +486,28 @@ async function processEmail(db: D1Database, deliveryId: string, env: Env): Promi
465
486
  });
466
487
  } catch (error) {
467
488
  if (!(error instanceof BudgetControlError)) throw error;
468
- const timestamp = now();
469
- if (error.retryable) {
470
- await db.prepare(`UPDATE email_deliveries SET state = 'failed', last_error_code = 'email_budget_deferred', next_attempt_at = ?2, updated_at = ?3 WHERE id = ?1`)
471
- .bind(row.id, plusSeconds(timestamp, error.delaySeconds), timestamp).run();
472
- throw new RetryableDeliveryError(error.delaySeconds);
473
- }
474
- await db.batch([
475
- db.prepare(`UPDATE email_deliveries SET state = 'suppressed', last_error_code = 'email_budget_exhausted', next_attempt_at = NULL, updated_at = ?2 WHERE id = ?1`).bind(row.id, timestamp),
476
- deliveryAudit(db, {
477
- key: `email-delivery:${row.id}:budget-suppressed`, action: "email.budget_exhausted",
478
- targetType: "email_delivery", targetId: row.id, reportId: row.reportId,
479
- details: { fallback: "customer_webhook", fallbackReference: error.fallbackReference }, createdAt: timestamp,
480
- }),
481
- ]);
489
+ const terminal = !error.retryable || row.attemptCount >= row.attemptLimit;
490
+ const committed = await commitEmailResult(db, env, row, {
491
+ state: terminal ? "suppressed" : "failed", terminal,
492
+ errorCode: terminal ? "email_budget_exhausted" : "email_budget_deferred",
493
+ nextAttemptAt: terminal ? null : plusSeconds(now(), error.delaySeconds),
494
+ });
495
+ if (committed && !terminal) throw new RetryableDeliveryError(error.delaySeconds);
482
496
  return;
483
497
  }
498
+
484
499
  let providerMessageId: string | null = null;
500
+ let providerAttempted = false;
485
501
  let errorCode: string | null = null;
486
502
  try {
503
+ const email = row.contactCiphertext
504
+ ? (await decryptReportContact(env.CREDENTIAL_ENCRYPTION_KEY, row.contactCiphertext, row.reportId, row.audience)).trim().toLowerCase()
505
+ : row.recipientReference?.trim().toLowerCase() ?? "";
487
506
  if (!binding) throw new DeliveryConfigurationError("The Cloudflare Email Service binding is unavailable.");
488
507
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(email) || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(from)) {
489
508
  throw new DeliveryConfigurationError("Email sender or recipient configuration is invalid.");
490
509
  }
510
+ if (row.recipientHash && row.recipientHash !== `sha256:${await sha256(`email-recipient-v1:${env.RATE_LIMIT_PEPPER}:${email}`)}`) throw new DeliveryConfigurationError("The participant address changed after this notice was prepared.", "notice_recipient_changed");
491
511
  const prefix = reporterEmailSubjectPrefix(env);
492
512
  const [brand, replyTo] = await Promise.all([
493
513
  loadWorkspaceBrand(db),
@@ -505,7 +525,12 @@ async function processEmail(db: D1Database, deliveryId: string, env: Env): Promi
505
525
  const rendered = renderReporterEmail({
506
526
  brand, body: row.body, reportReference: row.reportReference,
507
527
  templateVersionId: row.templateVersionId, subjectPrefix: prefix, audience: row.audience,
528
+ participantUrl: await issueParticipantAccessLink(env, {
529
+ reportId: row.reportId, audience: row.audience, deliveryKey: `email:${row.id}`,
530
+ expectedIdentity: { reference: row.recipientReference, contactCiphertext: row.contactCiphertext },
531
+ }),
508
532
  });
533
+ providerAttempted = true;
509
534
  const result = await binding.send({
510
535
  to: email,
511
536
  from: { email: from, name: `${brand.organization_name} Safety` },
@@ -518,46 +543,21 @@ async function processEmail(db: D1Database, deliveryId: string, env: Env): Promi
518
543
  providerMessageId = typeof result.messageId === "string" ? result.messageId.slice(0, 300) : null;
519
544
  } catch (error) {
520
545
  errorCode = error instanceof DeliveryConfigurationError
521
- ? "email_configuration_error"
546
+ ? error.code ?? "email_configuration_error"
547
+ : error instanceof ApiError && error.code === "participant_access_unavailable" ? "notice_recipient_changed"
522
548
  : typeof error === "object" && error !== null && "code" in error && typeof error.code === "string"
523
549
  ? `email_${error.code}`.slice(0, 100) : "email_provider_error";
524
550
  }
525
- const finishedAt = now();
526
- if (!errorCode) {
527
- await settleBudgets(db, reservations, true);
528
- await db.batch([
529
- db.prepare(`UPDATE email_deliveries SET state = 'delivered', provider_message_id = ?2, last_error_code = NULL, next_attempt_at = NULL, delivered_at = ?3, updated_at = ?3 WHERE id = ?1`)
530
- .bind(row.id, providerMessageId, finishedAt),
531
- db.prepare(`UPDATE case_messages SET delivery_state = 'delivered' WHERE id = ?1`).bind(row.messageId),
532
- db.prepare(`UPDATE notices SET delivery_state = 'delivered', updated_at = ?2 WHERE message_id = ?1`).bind(row.messageId, finishedAt),
533
- deliveryAudit(db, {
534
- key: `email-delivery:${row.id}:delivered`, action: "email.delivered",
535
- targetType: "email_delivery", targetId: row.id, reportId: row.reportId,
536
- details: { provider: "cloudflare_email_service", attemptCount: row.attemptCount }, createdAt: finishedAt,
537
- }),
538
- ]);
539
- return;
540
- }
541
- const terminal = errorCode === "email_configuration_error" || row.attemptCount >= MAX_ATTEMPTS;
542
- await settleBudgets(db, reservations, errorCode !== "email_configuration_error");
551
+ await settleBudgets(db, reservations, providerAttempted);
552
+ const configurationFailure = errorCode === "email_configuration_error" || errorCode === "notice_recipient_changed"
553
+ || errorCode === "email_contact_decryption_failed" || errorCode === "email_contact_encryption_unavailable";
554
+ const terminal = !errorCode || configurationFailure || row.attemptCount >= row.attemptLimit;
543
555
  const retryDelay = delay(row.attemptCount);
544
- const statements: D1PreparedStatement[] = [
545
- db.prepare(`UPDATE email_deliveries SET state = 'failed', last_error_code = ?2, next_attempt_at = ?3, updated_at = ?4 WHERE id = ?1`)
546
- .bind(row.id, errorCode, plusSeconds(finishedAt, retryDelay), finishedAt),
547
- ];
548
- if (terminal) {
549
- statements.push(
550
- db.prepare(`UPDATE case_messages SET delivery_state = 'failed' WHERE id = ?1 AND delivery_state != 'delivered'`).bind(row.messageId),
551
- db.prepare(`UPDATE notices SET delivery_state = 'failed', updated_at = ?2 WHERE message_id = ?1 AND delivery_state != 'delivered'`).bind(row.messageId, finishedAt),
552
- deliveryAudit(db, {
553
- key: `email-delivery:${row.id}:failed`, action: "email.delivery_failed",
554
- targetType: "email_delivery", targetId: row.id, reportId: row.reportId,
555
- details: { errorCode, attemptCount: row.attemptCount }, createdAt: finishedAt,
556
- }),
557
- );
558
- }
559
- await db.batch(statements);
560
- if (!terminal) throw new RetryableDeliveryError(retryDelay);
556
+ const committed = await commitEmailResult(db, env, row, {
557
+ state: errorCode ? "failed" : "delivered", terminal,
558
+ errorCode, providerMessageId, nextAttemptAt: terminal ? null : plusSeconds(now(), retryDelay),
559
+ });
560
+ if (committed && !terminal) throw new RetryableDeliveryError(retryDelay);
561
561
  }
562
562
 
563
563
  export async function processDeliveryJob(db: D1Database, job: DeliveryJob, env: Env): Promise<void> {
@@ -580,20 +580,21 @@ export async function pendingDeliveryJobs(db: D1Database, limit = 50): Promise<D
580
580
  `).bind(at, MAX_ATTEMPTS, boundedLimit).all<{ id: string }>(),
581
581
  db.prepare(`
582
582
  SELECT id FROM notification_outbox
583
- WHERE terminal = 0 AND attempt_count < ?2 AND (
583
+ WHERE terminal = 0 AND attempt_count < attempt_limit AND (
584
584
  (status IN ('pending', 'failed') AND next_attempt_at <= ?1)
585
585
  OR (status = 'delivering' AND lease_expires_at <= ?1)
586
586
  )
587
- ORDER BY next_attempt_at, id LIMIT ?3
588
- `).bind(at, MAX_ATTEMPTS, boundedLimit).all<{ id: string }>(),
587
+ ORDER BY next_attempt_at, id LIMIT ?2
588
+ `).bind(at, boundedLimit).all<{ id: string }>(),
589
589
  db.prepare(`
590
590
  SELECT id FROM email_deliveries
591
- WHERE attempt_count < ?2 AND (
592
- (state IN ('pending', 'failed') AND COALESCE(next_attempt_at, created_at) <= ?1)
593
- OR (state = 'sending' AND updated_at <= ?3)
591
+ WHERE attempt_count < attempt_limit AND (
592
+ (state = 'pending' AND COALESCE(next_attempt_at, created_at) <= ?1)
593
+ OR (state = 'failed' AND next_attempt_at IS NOT NULL AND next_attempt_at <= ?1)
594
+ OR (state = 'sending' AND updated_at <= ?2)
594
595
  )
595
- ORDER BY COALESCE(next_attempt_at, created_at), id LIMIT ?4
596
- `).bind(at, MAX_ATTEMPTS, plusSeconds(at, -60), boundedLimit).all<{ id: string }>(),
596
+ ORDER BY COALESCE(next_attempt_at, created_at), id LIMIT ?3
597
+ `).bind(at, plusSeconds(at, -60), boundedLimit).all<{ id: string }>(),
597
598
  ]);
598
599
  return [
599
600
  ...actions.results.map((row): DeliveryJob => ({ version: 1, jobId: `action:${row.id}`, type: "deliver_action", outboxId: row.id })),
@@ -2,14 +2,12 @@ import PostalMime from "postal-mime";
2
2
  import { canonicalJson } from "./audit";
3
3
  import { decryptReportContact, secretsEqual, sha256 } from "./report-crypto";
4
4
  import { reporterEmailFrom, verifyReporterReplyToken } from "./report-email";
5
- import type { ReportState } from "./report-types";
6
5
 
7
6
  const MAX_INBOUND_BYTES = 5 * 1024 * 1024;
8
7
  const MAX_MESSAGE_LENGTH = 8_000;
9
8
 
10
9
  interface ReplyReportRow {
11
10
  id: string;
12
- state: ReportState;
13
11
  participantId: string;
14
12
  contactCiphertext: string | null;
15
13
  audience: "reporter" | "affected_user";
@@ -79,12 +77,6 @@ async function recordUnmatchedEmail(db: D1Database, message: ForwardableEmailMes
79
77
  ).run();
80
78
  }
81
79
 
82
- function nextState(state: ReportState): ReportState {
83
- if (state === "awaiting_reporter") return "human_review";
84
- if (["resolved_by_human", "resolved_by_ai", "closed"].includes(state)) return "human_review_requested";
85
- return state;
86
- }
87
-
88
80
  export async function receiveReporterEmail(
89
81
  message: ForwardableEmailMessage,
90
82
  env: Env,
@@ -101,7 +93,7 @@ export async function receiveReporterEmail(
101
93
  return { reportId: null, stored: false };
102
94
  }
103
95
  const report = await env.DB.prepare(`
104
- SELECT r.id, r.state, p.id AS participantId, p.contact_ciphertext AS contactCiphertext,
96
+ SELECT r.id, p.id AS participantId, p.contact_ciphertext AS contactCiphertext,
105
97
  p.audience AS audience
106
98
  FROM reports r
107
99
  JOIN report_participants p ON p.report_id = r.id AND p.audience = ?2
@@ -146,7 +138,6 @@ export async function receiveReporterEmail(
146
138
  .bind(report.id, idempotencyKey).first<{ id: string }>();
147
139
  if (existing) return { reportId: report.id, stored: false };
148
140
  const receivedAt = now();
149
- const targetState = nextState(report.state);
150
141
  const messageId = crypto.randomUUID();
151
142
  const statements: D1PreparedStatement[] = [
152
143
  env.DB.prepare(`
@@ -155,23 +146,43 @@ export async function receiveReporterEmail(
155
146
  automated, delivery_state, created_at, idempotency_key, audience_checked_at
156
147
  ) VALUES (?1, ?2, ?3, 'inbound', ?3, ?4, ?5, 0, 'not_required', ?6, ?7, ?6)
157
148
  `).bind(messageId, report.id, report.audience, report.participantId, body, receivedAt, idempotencyKey),
158
- env.DB.prepare(`UPDATE reports SET state = ?2, updated_at = ?3 WHERE id = ?1`).bind(report.id, targetState, receivedAt),
149
+ env.DB.prepare(`
150
+ INSERT INTO report_state_history (
151
+ id, report_id, from_state, to_state, reason_code, actor_type, actor_id, created_at
152
+ )
153
+ SELECT ?1, r.id, r.state,
154
+ CASE
155
+ WHEN r.state = 'awaiting_reporter' THEN 'human_review'
156
+ ELSE 'human_review_requested'
157
+ END,
158
+ 'reporter_reply_received', 'participant', ?3, ?4
159
+ FROM reports r
160
+ WHERE r.id = ?2
161
+ AND r.state IN ('awaiting_reporter', 'resolved_by_human', 'resolved_by_ai', 'closed')
162
+ AND EXISTS (SELECT 1 FROM case_messages cm WHERE cm.id = ?5)
163
+ `).bind(crypto.randomUUID(), report.id, report.participantId, receivedAt, messageId),
164
+ env.DB.prepare(`
165
+ UPDATE reports
166
+ SET state = CASE
167
+ WHEN state = 'awaiting_reporter' THEN 'human_review'
168
+ WHEN state IN ('resolved_by_human', 'resolved_by_ai', 'closed') THEN 'human_review_requested'
169
+ ELSE state
170
+ END,
171
+ updated_at = ?2
172
+ WHERE id = ?1
173
+ AND EXISTS (SELECT 1 FROM case_messages cm WHERE cm.id = ?3)
174
+ `).bind(report.id, receivedAt, messageId),
159
175
  env.DB.prepare(`
160
176
  INSERT OR IGNORE INTO audit_events (
161
177
  id, idempotency_key, action, actor_type, actor_id, target_type, target_id, details_json, created_at
162
- ) VALUES (?1, ?2, 'report.reporter_reply_received', 'participant', ?3, 'report', ?4, ?5, ?6)
178
+ )
179
+ SELECT ?1, ?2, 'report.reporter_reply_received', 'participant', ?3, 'report', ?4, ?5, ?6
180
+ WHERE EXISTS (SELECT 1 FROM case_messages cm WHERE cm.id = ?7)
163
181
  `).bind(
164
182
  crypto.randomUUID(), `audit:${idempotencyKey}`, report.participantId, report.id,
165
- canonicalJson({ messageId, previousState: report.state, nextState: targetState, source: "email" }), receivedAt,
183
+ canonicalJson({ audience: report.audience, messageId, source: "email" }), receivedAt, messageId,
166
184
  ),
167
185
  ];
168
- if (targetState !== report.state) {
169
- statements.push(env.DB.prepare(`
170
- INSERT INTO report_state_history (
171
- id, report_id, from_state, to_state, reason_code, actor_type, actor_id, created_at
172
- ) VALUES (?1, ?2, ?3, ?4, 'reporter_reply_received', 'participant', ?5, ?6)
173
- `).bind(crypto.randomUUID(), report.id, report.state, targetState, report.participantId, receivedAt));
174
- }
175
- await env.DB.batch(statements);
176
- return { reportId: report.id, stored: true };
186
+ const results = await env.DB.batch(statements);
187
+ return { reportId: report.id, stored: (results[0]?.meta.changes ?? 0) === 1 };
177
188
  }
@@ -153,6 +153,7 @@ export function renderReporterEmail(input: {
153
153
  templateVersionId: string | null;
154
154
  subjectPrefix: string;
155
155
  audience?: CaseEmailAudience;
156
+ participantUrl?: string;
156
157
  }): RenderedEmail {
157
158
  const emailKind = caseKind(input.templateVersionId);
158
159
  const audience = input.audience ?? "reporter";
@@ -196,7 +197,8 @@ export function renderReporterEmail(input: {
196
197
  category: copy.category,
197
198
  heading: copy.heading,
198
199
  intro: copy.intro,
199
- contentHtml: `<div style="margin:24px 0 0;padding:20px;border-left:4px solid ${input.brand.accent_color};border-radius:${Math.min(input.brand.border_radius, 12)}px;background-color:${input.brand.background_color};color:${input.brand.text_color};font-size:16px;line-height:1.65">${messageHtml(input.body)}</div>`,
200
+ contentHtml: `<div style="margin:24px 0 0;padding:20px;border-left:4px solid ${input.brand.accent_color};border-radius:${Math.min(input.brand.border_radius, 12)}px;background-color:${input.brand.background_color};color:${input.brand.text_color};font-size:16px;line-height:1.65">${messageHtml(input.body)}</div>`
201
+ + (input.participantUrl ? `<p style="margin:24px 0"><a href="${escapeHtml(input.participantUrl)}" style="display:inline-block;padding:14px 20px;border-radius:8px;background:${actionColors(input.brand).background};color:${actionColors(input.brand).foreground};text-decoration:none;font-weight:700">Open your case</a></p><p style="font-size:14px;line-height:1.6">Read your conversation, add information or request an independent appeal. This private link is for you only; do not forward it. It opens once within 30 days. Request a fresh link from the case page if needed.</p>` : ""),
200
202
  details: [
201
203
  { label: "Report reference", value: input.reportReference },
202
204
  { label: "Status", value: copy.status },
@@ -206,7 +208,8 @@ export function renderReporterEmail(input: {
206
208
  return {
207
209
  subject: copy.subject,
208
210
  html,
209
- text: `${copy.heading}\n\n${copy.intro}\n\n${input.body}\n\nReport reference: ${input.reportReference}\nStatus: ${copy.status}\n\n${replyCopy}\n\nFor privacy, this email includes only the information needed for this update.`,
211
+ text: `${copy.heading}\n\n${copy.intro}\n\n${input.body}\n\nReport reference: ${input.reportReference}\nStatus: ${copy.status}\n\n${replyCopy}\n\nFor privacy, this email includes only the information needed for this update.`
212
+ + (input.participantUrl ? `\n\nOpen your case: ${input.participantUrl}\nRead your conversation, add information or request an independent appeal. This private link is for you only; do not forward it. It opens once within 30 days. Request a fresh link from the case page if needed.` : ""),
210
213
  };
211
214
  }
212
215