@aglyn/plugins-outreach 1.12.0 → 1.13.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/plugins-outreach",
3
- "version": "1.12.0",
3
+ "version": "1.13.0",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,19 +25,19 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.12.0",
29
- "@aglyn/shared-data-mdi": "1.12.0",
30
- "@aglyn/shared-ui-email-campaigns": "1.12.0",
31
- "@aglyn/shared-ui-jsx": "1.12.0",
32
- "@aglyn/shared-ui-next": "1.12.0",
33
- "@aglyn/shared-ui-snackstack": "1.12.0",
34
- "@aglyn/shared-util-email": "1.12.0",
35
- "@aglyn/shared-util-http": "1.12.0",
36
- "@aglyn/shared-util-timestamp": "1.12.0",
37
- "@aglyn/shared-util-tools": "1.12.0",
38
- "@aglyn/tenant-data-admin": "1.12.0",
39
- "@aglyn/tenant-feature-instance": "1.12.0",
40
- "@aglyn/tenant-runtime": "1.12.0",
28
+ "@aglyn/aglyn": "1.13.0",
29
+ "@aglyn/shared-data-mdi": "1.13.0",
30
+ "@aglyn/shared-ui-email-campaigns": "1.13.0",
31
+ "@aglyn/shared-ui-jsx": "1.13.0",
32
+ "@aglyn/shared-ui-next": "1.13.0",
33
+ "@aglyn/shared-ui-snackstack": "1.13.0",
34
+ "@aglyn/shared-util-email": "1.13.0",
35
+ "@aglyn/shared-util-http": "1.13.0",
36
+ "@aglyn/shared-util-timestamp": "1.13.0",
37
+ "@aglyn/shared-util-tools": "1.13.0",
38
+ "@aglyn/tenant-data-admin": "1.13.0",
39
+ "@aglyn/tenant-feature-instance": "1.13.0",
40
+ "@aglyn/tenant-runtime": "1.13.0",
41
41
  "@swc/helpers": "0.5.23"
42
42
  },
43
43
  "peerDependencies": {
@@ -21,7 +21,7 @@ export declare function OutreachLoading(props: {
21
21
  label: string;
22
22
  }): import("react").JSX.Element;
23
23
  /** The words a refused read shows when the route gave none of its own. */
24
- export declare const OUTREACH_REFUSED_MESSAGE = "You don't have access to this in Sequences. Ask an organization owner or admin for the Use Sequences permission.";
24
+ export declare const OUTREACH_REFUSED_MESSAGE = "Your role does not include \"Use Sequences\" \u2014 ask an organization admin";
25
25
  /**
26
26
  * What a failed or refused read shows. A refusal is a statement about the
27
27
  * reader, not a fault, so it reads as information and offers no retry.
@@ -102,7 +102,7 @@ export function OutreachEnrollmentStatusChip(props) {
102
102
  ]
103
103
  });
104
104
  }
105
- /** The words a refused read shows when the route gave none of its own. */ export const OUTREACH_REFUSED_MESSAGE = "You don't have access to this in Sequences. Ask an organization owner or admin for the Use Sequences permission.";
105
+ /** The words a refused read shows when the route gave none of its own. */ export const OUTREACH_REFUSED_MESSAGE = 'Your role does not include "Use Sequences" — ask an organization admin';
106
106
  /**
107
107
  * What a failed or refused read shows. A refusal is a statement about the
108
108
  * reader, not a fault, so it reads as information and offers no retry.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/components/outreach-ui.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport {\n Alert,\n Button,\n Chip,\n type ChipProps,\n CircularProgress,\n Link,\n Stack,\n Typography,\n} from '@mui/material'\nimport { useRouter } from 'next/navigation'\nimport type { MouseEvent, ReactNode } from 'react'\nimport type {\n OutreachEnrollmentStatus,\n OutreachSequenceStatus,\n OutreachStopReason,\n} from '../model/outreach.types'\nimport type { OutreachLoadStatus } from './use-outreach-data'\n\n/**\n * The pieces every Outreach page shares (AGL-2980): the words for each\n * status, the states a read can be in, and a link that navigates inside the\n * console without reloading it.\n */\n\nexport const OUTREACH_SEQUENCE_STATUS_LABELS: Record<\n OutreachSequenceStatus,\n string\n> = {\n draft: 'Draft',\n active: 'Active',\n paused: 'Paused',\n archived: 'Archived',\n}\n\nconst SEQUENCE_STATUS_COLORS: Record<\n OutreachSequenceStatus,\n ChipProps['color']\n> = {\n draft: 'default',\n active: 'success',\n paused: 'warning',\n archived: 'default',\n}\n\nexport const OUTREACH_ENROLLMENT_STATUS_LABELS: Record<\n OutreachEnrollmentStatus,\n string\n> = {\n active: 'Active',\n paused: 'Paused',\n finished: 'Finished',\n replied: 'Replied',\n bounced: 'Bounced',\n opted_out: 'Opted out',\n stopped: 'Stopped',\n failed: 'Failed',\n}\n\nconst ENROLLMENT_STATUS_COLORS: Record<\n OutreachEnrollmentStatus,\n ChipProps['color']\n> = {\n active: 'success',\n paused: 'warning',\n finished: 'default',\n replied: 'info',\n bounced: 'error',\n opted_out: 'default',\n stopped: 'default',\n failed: 'error',\n}\n\n/** Why an enrollment is not active, as the table says it. */\nexport const OUTREACH_STOP_REASON_LABELS: Record<OutreachStopReason, string> = {\n reply: 'They replied',\n hard_bounce: 'The address bounced',\n opt_out_reply: 'They asked not to be emailed',\n unsubscribe: 'They unsubscribed',\n do_not_contact: 'On the do-not-contact list',\n gate: 'No longer eligible',\n manual: 'By a member',\n gateway_blocked_here: 'Held — gateway refused this sender twice',\n sequence_archived: 'The sequence was archived',\n send_failed: \"An email couldn't be sent\",\n}\n\nexport function OutreachSequenceStatusChip(props: {\n status: OutreachSequenceStatus\n}) {\n return (\n <Chip\n size=\"small\"\n label={OUTREACH_SEQUENCE_STATUS_LABELS[props.status]}\n color={SEQUENCE_STATUS_COLORS[props.status]}\n variant={props.status === 'archived' ? 'outlined' : 'filled'}\n />\n )\n}\n\nexport function OutreachEnrollmentStatusChip(props: {\n status: OutreachEnrollmentStatus\n}) {\n return (\n <Chip\n size=\"small\"\n label={OUTREACH_ENROLLMENT_STATUS_LABELS[props.status]}\n color={ENROLLMENT_STATUS_COLORS[props.status]}\n />\n )\n}\n\n/** Progress for a read still on its way. */\nexport function OutreachLoading(props: { label: string }) {\n return (\n <Stack\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center', py: 2 }}\n role=\"status\"\n >\n <CircularProgress size={18} />\n <Typography variant=\"body2\" color=\"text.secondary\">\n {props.label}\n </Typography>\n </Stack>\n )\n}\n\n/** The words a refused read shows when the route gave none of its own. */\nexport const OUTREACH_REFUSED_MESSAGE =\n \"You don't have access to this in Sequences. Ask an organization owner or admin for the Use Sequences permission.\"\n\n/**\n * What a failed or refused read shows. A refusal is a statement about the\n * reader, not a fault, so it reads as information and offers no retry.\n */\nexport function OutreachLoadProblem(props: {\n status: Extract<OutreachLoadStatus, 'error' | 'refused'>\n /** What could not be read, for the error sentence. */\n what: string\n message?: string | null\n onRetry?: () => void\n}) {\n if (props.status === 'refused') {\n return (\n <Alert severity=\"info\">{props.message || OUTREACH_REFUSED_MESSAGE}</Alert>\n )\n }\n return (\n <Alert\n severity=\"error\"\n action={\n props.onRetry ? (\n <Button color=\"inherit\" size=\"small\" onClick={props.onRetry}>\n Try again\n </Button>\n ) : undefined\n }\n >\n {props.message ||\n `The ${props.what} could not be loaded. Reload the page to try again.`}\n </Alert>\n )\n}\n\n/** Navigation inside the console, without reloading it. */\nexport function useOutreachNavigate(): (href: string) => void {\n const router = useRouter()\n return (href: string) => router.push(href)\n}\n\n/**\n * A link inside the console: a real anchor, so it opens in a new tab when\n * asked to, and a client navigation otherwise.\n */\nexport function OutreachLink(props: {\n href: string\n children: ReactNode\n underline?: 'hover' | 'always' | 'none'\n}) {\n const navigate = useOutreachNavigate()\n const onClick = (event: MouseEvent<HTMLAnchorElement>) => {\n if (\n event.defaultPrevented ||\n event.button !== 0 ||\n event.metaKey ||\n event.ctrlKey ||\n event.shiftKey ||\n event.altKey\n ) {\n return\n }\n event.preventDefault()\n navigate(props.href)\n }\n return (\n <Link\n href={props.href}\n onClick={onClick}\n underline={props.underline ?? 'hover'}\n >\n {props.children}\n </Link>\n )\n}\n\n/**\n * A moment as a reader in `timeZone` reads it — \"Sep 22, 9:14 AM CDT\" — or\n * in the reader's own zone when none is known.\n */\nexport function formatOutreachTime(\n ms: number | null | undefined,\n timeZone?: string | null,\n): string {\n if (typeof ms !== 'number' || !Number.isFinite(ms)) return '—'\n const options: Intl.DateTimeFormatOptions = {\n month: 'short',\n day: 'numeric',\n hour: 'numeric',\n minute: '2-digit',\n timeZoneName: 'short',\n }\n try {\n return new Intl.DateTimeFormat('en-US', {\n ...options,\n ...(timeZone ? { timeZone } : {}),\n }).format(ms)\n } catch {\n return new Intl.DateTimeFormat('en-US', options).format(ms)\n }\n}\n"],"names":["Alert","Button","Chip","CircularProgress","Link","Stack","Typography","useRouter","OUTREACH_SEQUENCE_STATUS_LABELS","draft","active","paused","archived","SEQUENCE_STATUS_COLORS","OUTREACH_ENROLLMENT_STATUS_LABELS","finished","replied","bounced","opted_out","stopped","failed","ENROLLMENT_STATUS_COLORS","OUTREACH_STOP_REASON_LABELS","reply","hard_bounce","opt_out_reply","unsubscribe","do_not_contact","gate","manual","gateway_blocked_here","sequence_archived","send_failed","OutreachSequenceStatusChip","props","size","label","status","color","variant","OutreachEnrollmentStatusChip","OutreachLoading","direction","spacing","sx","alignItems","py","role","OUTREACH_REFUSED_MESSAGE","OutreachLoadProblem","severity","message","action","onRetry","onClick","undefined","what","useOutreachNavigate","router","href","push","OutreachLink","navigate","event","defaultPrevented","button","metaKey","ctrlKey","shiftKey","altKey","preventDefault","underline","children","formatOutreachTime","ms","timeZone","Number","isFinite","options","month","day","hour","minute","timeZoneName","Intl","DateTimeFormat","format"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA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AAO,SAASC,mBACdC,EAA6B,EAC7BC,QAAwB;IAExB,IAAI,OAAOD,OAAO,YAAY,CAACE,OAAOC,QAAQ,CAACH,KAAK,OAAO;IAC3D,MAAMI,UAAsC;QAC1CC,OAAO;QACPC,KAAK;QACLC,MAAM;QACNC,QAAQ;QACRC,cAAc;IAChB;IACA,IAAI;QACF,OAAO,IAAIC,KAAKC,cAAc,CAAC,SAAS,aACnCP,SACCH,WAAW;YAAEA;QAAS,IAAI,CAAC,IAC9BW,MAAM,CAACZ;IACZ,EAAE,eAAM;QACN,OAAO,IAAIU,KAAKC,cAAc,CAAC,SAASP,SAASQ,MAAM,CAACZ;IAC1D;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/components/outreach-ui.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport {\n Alert,\n Button,\n Chip,\n type ChipProps,\n CircularProgress,\n Link,\n Stack,\n Typography,\n} from '@mui/material'\nimport { useRouter } from 'next/navigation'\nimport type { MouseEvent, ReactNode } from 'react'\nimport type {\n OutreachEnrollmentStatus,\n OutreachSequenceStatus,\n OutreachStopReason,\n} from '../model/outreach.types'\nimport type { OutreachLoadStatus } from './use-outreach-data'\n\n/**\n * The pieces every Outreach page shares (AGL-2980): the words for each\n * status, the states a read can be in, and a link that navigates inside the\n * console without reloading it.\n */\n\nexport const OUTREACH_SEQUENCE_STATUS_LABELS: Record<\n OutreachSequenceStatus,\n string\n> = {\n draft: 'Draft',\n active: 'Active',\n paused: 'Paused',\n archived: 'Archived',\n}\n\nconst SEQUENCE_STATUS_COLORS: Record<\n OutreachSequenceStatus,\n ChipProps['color']\n> = {\n draft: 'default',\n active: 'success',\n paused: 'warning',\n archived: 'default',\n}\n\nexport const OUTREACH_ENROLLMENT_STATUS_LABELS: Record<\n OutreachEnrollmentStatus,\n string\n> = {\n active: 'Active',\n paused: 'Paused',\n finished: 'Finished',\n replied: 'Replied',\n bounced: 'Bounced',\n opted_out: 'Opted out',\n stopped: 'Stopped',\n failed: 'Failed',\n}\n\nconst ENROLLMENT_STATUS_COLORS: Record<\n OutreachEnrollmentStatus,\n ChipProps['color']\n> = {\n active: 'success',\n paused: 'warning',\n finished: 'default',\n replied: 'info',\n bounced: 'error',\n opted_out: 'default',\n stopped: 'default',\n failed: 'error',\n}\n\n/** Why an enrollment is not active, as the table says it. */\nexport const OUTREACH_STOP_REASON_LABELS: Record<OutreachStopReason, string> = {\n reply: 'They replied',\n hard_bounce: 'The address bounced',\n opt_out_reply: 'They asked not to be emailed',\n unsubscribe: 'They unsubscribed',\n do_not_contact: 'On the do-not-contact list',\n gate: 'No longer eligible',\n manual: 'By a member',\n gateway_blocked_here: 'Held — gateway refused this sender twice',\n sequence_archived: 'The sequence was archived',\n send_failed: \"An email couldn't be sent\",\n}\n\nexport function OutreachSequenceStatusChip(props: {\n status: OutreachSequenceStatus\n}) {\n return (\n <Chip\n size=\"small\"\n label={OUTREACH_SEQUENCE_STATUS_LABELS[props.status]}\n color={SEQUENCE_STATUS_COLORS[props.status]}\n variant={props.status === 'archived' ? 'outlined' : 'filled'}\n />\n )\n}\n\nexport function OutreachEnrollmentStatusChip(props: {\n status: OutreachEnrollmentStatus\n}) {\n return (\n <Chip\n size=\"small\"\n label={OUTREACH_ENROLLMENT_STATUS_LABELS[props.status]}\n color={ENROLLMENT_STATUS_COLORS[props.status]}\n />\n )\n}\n\n/** Progress for a read still on its way. */\nexport function OutreachLoading(props: { label: string }) {\n return (\n <Stack\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center', py: 2 }}\n role=\"status\"\n >\n <CircularProgress size={18} />\n <Typography variant=\"body2\" color=\"text.secondary\">\n {props.label}\n </Typography>\n </Stack>\n )\n}\n\n/** The words a refused read shows when the route gave none of its own. */\nexport const OUTREACH_REFUSED_MESSAGE =\n 'Your role does not include \"Use Sequences\" — ask an organization admin'\n\n/**\n * What a failed or refused read shows. A refusal is a statement about the\n * reader, not a fault, so it reads as information and offers no retry.\n */\nexport function OutreachLoadProblem(props: {\n status: Extract<OutreachLoadStatus, 'error' | 'refused'>\n /** What could not be read, for the error sentence. */\n what: string\n message?: string | null\n onRetry?: () => void\n}) {\n if (props.status === 'refused') {\n return (\n <Alert severity=\"info\">{props.message || OUTREACH_REFUSED_MESSAGE}</Alert>\n )\n }\n return (\n <Alert\n severity=\"error\"\n action={\n props.onRetry ? (\n <Button color=\"inherit\" size=\"small\" onClick={props.onRetry}>\n Try again\n </Button>\n ) : undefined\n }\n >\n {props.message ||\n `The ${props.what} could not be loaded. Reload the page to try again.`}\n </Alert>\n )\n}\n\n/** Navigation inside the console, without reloading it. */\nexport function useOutreachNavigate(): (href: string) => void {\n const router = useRouter()\n return (href: string) => router.push(href)\n}\n\n/**\n * A link inside the console: a real anchor, so it opens in a new tab when\n * asked to, and a client navigation otherwise.\n */\nexport function OutreachLink(props: {\n href: string\n children: ReactNode\n underline?: 'hover' | 'always' | 'none'\n}) {\n const navigate = useOutreachNavigate()\n const onClick = (event: MouseEvent<HTMLAnchorElement>) => {\n if (\n event.defaultPrevented ||\n event.button !== 0 ||\n event.metaKey ||\n event.ctrlKey ||\n event.shiftKey ||\n event.altKey\n ) {\n return\n }\n event.preventDefault()\n navigate(props.href)\n }\n return (\n <Link\n href={props.href}\n onClick={onClick}\n underline={props.underline ?? 'hover'}\n >\n {props.children}\n </Link>\n )\n}\n\n/**\n * A moment as a reader in `timeZone` reads it — \"Sep 22, 9:14 AM CDT\" — or\n * in the reader's own zone when none is known.\n */\nexport function formatOutreachTime(\n ms: number | null | undefined,\n timeZone?: string | null,\n): string {\n if (typeof ms !== 'number' || !Number.isFinite(ms)) return '—'\n const options: Intl.DateTimeFormatOptions = {\n month: 'short',\n day: 'numeric',\n hour: 'numeric',\n minute: '2-digit',\n timeZoneName: 'short',\n }\n try {\n return new Intl.DateTimeFormat('en-US', {\n ...options,\n ...(timeZone ? { timeZone } : {}),\n }).format(ms)\n } catch {\n return new Intl.DateTimeFormat('en-US', options).format(ms)\n }\n}\n"],"names":["Alert","Button","Chip","CircularProgress","Link","Stack","Typography","useRouter","OUTREACH_SEQUENCE_STATUS_LABELS","draft","active","paused","archived","SEQUENCE_STATUS_COLORS","OUTREACH_ENROLLMENT_STATUS_LABELS","finished","replied","bounced","opted_out","stopped","failed","ENROLLMENT_STATUS_COLORS","OUTREACH_STOP_REASON_LABELS","reply","hard_bounce","opt_out_reply","unsubscribe","do_not_contact","gate","manual","gateway_blocked_here","sequence_archived","send_failed","OutreachSequenceStatusChip","props","size","label","status","color","variant","OutreachEnrollmentStatusChip","OutreachLoading","direction","spacing","sx","alignItems","py","role","OUTREACH_REFUSED_MESSAGE","OutreachLoadProblem","severity","message","action","onRetry","onClick","undefined","what","useOutreachNavigate","router","href","push","OutreachLink","navigate","event","defaultPrevented","button","metaKey","ctrlKey","shiftKey","altKey","preventDefault","underline","children","formatOutreachTime","ms","timeZone","Number","isFinite","options","month","day","hour","minute","timeZoneName","Intl","DateTimeFormat","format"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SACEA,KAAK,EACLC,MAAM,EACNC,IAAI,EAEJC,gBAAgB,EAChBC,IAAI,EACJC,KAAK,EACLC,UAAU,QACL,gBAAe;AACtB,SAASC,SAAS,QAAQ,kBAAiB;AAS3C;;;;CAIC,GAED,OAAO,MAAMC,kCAGT;IACFC,OAAO;IACPC,QAAQ;IACRC,QAAQ;IACRC,UAAU;AACZ,EAAC;AAED,MAAMC,yBAGF;IACFJ,OAAO;IACPC,QAAQ;IACRC,QAAQ;IACRC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9BW,MAAM,CAACZ;IACZ,EAAE,eAAM;QACN,OAAO,IAAIU,KAAKC,cAAc,CAAC,SAASP,SAASQ,MAAM,CAACZ;IAC1D;AACF"}
@@ -302,7 +302,7 @@ import { outreachHeader } from "./thread-message.js";
302
302
  if (!input.mayUseMailbox) {
303
303
  return {
304
304
  code: 'permission',
305
- message: `Only the member who connected ${address}, or an organization owner or admin, can answer from it.`
305
+ message: `Only the member who connected ${address}, or a member holding "Manage everyone’s Sequences", can answer from it.`
306
306
  };
307
307
  }
308
308
  return null;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/engine/manual-reply.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * ANSWERING A PERSON WHO WROTE BACK (AGL-4020).\n *\n * A person who answers a sequence email is answered from the same mailbox,\n * in the same thread, by a member: the reply is a one-to-one email, never a\n * step of the sequence. This module is the engine's half of it — what the\n * person wrote, as the enrollment keeps it, and the answer, as the\n * transport sends it — and decides nothing about storage or delivery.\n *\n * ## What the person wrote\n *\n * {@link outreachInboundMessagesOf} keeps the messages of a thread the\n * classifier reads as theirs: a reply, an automatic answer, an opt-out. Each\n * carries its sender, its time, its `Message-ID` and `References` (what an\n * answer threads by), and its text with the quoted history trimmed, the way\n * the record's timeline keeps it (`emailExcerpt`).\n *\n * ## The answer\n *\n * {@link composeOutreachManualReply} writes it as every mail client writes a\n * reply: `Re:` the subject of the message it answers, `In-Reply-To` that\n * message's `Message-ID`, and `References` the whole chain — the sequence's\n * own sends, what the person's message already named, and the message\n * itself — so it lands in the same thread in the person's mailbox and in\n * ours. Plain text, the member's words first and the message answered quoted\n * beneath. No footer and no `List-Unsubscribe`: the person wrote first, and\n * this is the answer a person would type in their own mail client.\n *\n * On a sequence that tracks link clicks, the links in the member's words go\n * out as the same short links a step's do (AGL-4022), through the caller's\n * minter — never the links in the quoted message, which are theirs.\n *\n * ## What still refuses\n *\n * {@link outreachManualReplyRefusal}: an address or a domain on the\n * do-not-contact list, a person who opted out or whose address bounced, and\n * a mailbox that is paused, waiting to be reconnected, or gone. The cold\n * rules — the allowed countries, the company-domain rule, the personal line,\n * the daily cap — do not apply to someone who wrote first, and are not\n * asked.\n *==========================================*/\n\nimport { normalizeContactEmail } from '@aglyn/aglyn/app-utils/contacts'\nimport { CRM_EMAIL_SUBJECT_MAX } from '@aglyn/aglyn/app-utils/crm'\nimport { emailAddressOf, emailExcerpt, threadSubject } from '@aglyn/aglyn/app-utils/email-text'\nimport {\n OUTREACH_INBOUND_KINDS,\n OUTREACH_INBOUND_MESSAGES_MAX,\n type OutreachEnrollment,\n type OutreachInboundKind,\n type OutreachInboundMessage,\n type OutreachMailbox,\n} from '../model/outreach.types'\nimport { rewriteOutreachBodyLinks } from './click-tracking'\nimport { outreachMessageIdHeader } from './compose'\nimport { outreachEmailDomain } from './do-not-contact-domain'\nimport { classifyOutreachMessage, type OutreachMessageContext } from './thread-classification'\nimport { outreachHeader, type OutreachThreadMessage } from './thread-message'\n\n/** The most a member may write in one answer. */\nexport const OUTREACH_MANUAL_REPLY_BODY_MAX = 10_000\n\n/** The most of an answer the enrollment and the record keep: the timeline's excerpt length. */\nexport const OUTREACH_MANUAL_REPLY_STORED_MAX = 4_000\n\n/** The most `Message-ID`s one answer's `References` names: the first, and the latest. */\nconst REFERENCES_MAX = 20\n\n/** The display name in a `From` value — `\"Ada Lovelace\" <ada@example.com>` answers `Ada Lovelace` — or `''`. */\nexport function outreachDisplayNameOf(value: unknown): string {\n const raw = String(value ?? '').trim()\n const angled = raw.lastIndexOf('<')\n if (angled <= 0) return ''\n return raw\n .slice(0, angled)\n .trim()\n .replace(/^\"(.*)\"$/, '$1')\n .replace(/\\\\(.)/g, '$1')\n .trim()\n}\n\n/** Every `Message-ID` a `References` or `In-Reply-To` value names, in header form, in order, once each. */\nexport function outreachMessageIdList(value: unknown): string[] {\n const found: string[] = []\n for (const match of String(value ?? '').matchAll(/<[^<>\\s]+>/g)) {\n const id = outreachMessageIdHeader(match[0])\n if (id && !found.includes(id)) found.push(id)\n }\n return found\n}\n\n/** A message's text as the record keeps it: the text part, else the HTML's words, else the preview. */\nfunction bodyOf(message: OutreachThreadMessage): string {\n return emailExcerpt(message.textBody ?? '', message.htmlBody ?? '') || emailExcerpt(message.snippet ?? '')\n}\n\n/**\n * The person's own messages among a thread's — see the module note — oldest\n * first. A message with no sender address is left out: it could be neither\n * shown as theirs nor answered.\n */\nexport function outreachInboundMessagesOf(\n messages: readonly OutreachThreadMessage[],\n context: OutreachMessageContext,\n): OutreachInboundMessage[] {\n const kept: OutreachInboundMessage[] = []\n for (const message of messages) {\n if (!message?.id) continue\n const classification = classifyOutreachMessage(message, context)\n if (!(OUTREACH_INBOUND_KINDS as readonly string[]).includes(classification.kind)) continue\n const from = emailAddressOf(message.from)\n if (!from) continue\n const replyTo = emailAddressOf(outreachHeader(message, 'Reply-To'))\n kept.push({\n id: message.id,\n threadId: message.threadId ?? null,\n messageId: outreachMessageIdHeader(outreachHeader(message, 'Message-ID')),\n references: outreachMessageIdList(outreachHeader(message, 'References')),\n from,\n fromName: outreachDisplayNameOf(message.from),\n replyTo: replyTo && replyTo !== from ? replyTo : null,\n subject: String(message.subject ?? '').replace(/\\s+/g, ' ').trim(),\n atMs: classification.atMs,\n kind: classification.kind as OutreachInboundKind,\n body: bodyOf(message),\n })\n }\n return kept.sort((a, b) => a.atMs - b.atMs)\n}\n\n/**\n * What an enrollment keeps once more of the person's messages are read: one\n * entry per message — a re-read replaces the earlier copy — oldest first,\n * the last {@link OUTREACH_INBOUND_MESSAGES_MAX}.\n */\nexport function mergeOutreachInboundMessages(\n stored: readonly OutreachInboundMessage[] | null | undefined,\n found: readonly OutreachInboundMessage[],\n): OutreachInboundMessage[] {\n const byId = new Map<string, OutreachInboundMessage>()\n for (const message of [...(stored ?? []), ...found]) byId.set(message.id, message)\n return [...byId.values()].sort((a, b) => a.atMs - b.atMs).slice(-OUTREACH_INBOUND_MESSAGES_MAX)\n}\n\n/**\n * The message an answer replies to: the one named, when the enrollment\n * kept it, else the newest the person wrote. `null` when they wrote nothing\n * the enrollment kept.\n */\nexport function outreachMessageToAnswer(\n inbound: readonly OutreachInboundMessage[] | null | undefined,\n id?: string | null,\n): OutreachInboundMessage | null {\n const messages = [...(inbound ?? [])].sort((a, b) => a.atMs - b.atMs)\n if (id) return messages.find((message) => message.id === id) ?? null\n return messages.at(-1) ?? null\n}\n\n/** Whether a member may answer this enrollment at all: the person wrote something it kept, or a reply stopped it. */\nexport function outreachEnrollmentHasInbound(\n enrollment: Pick<OutreachEnrollment, 'inboundMessages' | 'stopReason' | 'status'>,\n): boolean {\n return Boolean(enrollment.inboundMessages?.length) || enrollment.stopReason === 'reply' || enrollment.status === 'replied'\n}\n\n/**\n * The answer's `References` — see the module note: the sequence's own sends,\n * then what the answered message named, then the message itself, each once.\n * A long chain keeps its first id and its latest, as RFC 5322 §3.6.4 allows.\n */\nexport function outreachReplyReferences(\n sentMessageIds: readonly string[],\n answering: Pick<OutreachInboundMessage, 'references' | 'messageId'>,\n): string[] {\n const chain: string[] = []\n for (const id of [...sentMessageIds, ...answering.references, answering.messageId]) {\n const header = outreachMessageIdHeader(id)\n if (header && !chain.includes(header)) chain.push(header)\n }\n return chain.length > REFERENCES_MAX ? [chain[0], ...chain.slice(-(REFERENCES_MAX - 1))] : chain\n}\n\n/** `Re:` the subject of the message answered, else of the thread the sequence started. */\nexport function outreachReplySubject(\n answering: Pick<OutreachInboundMessage, 'subject'>,\n enrollmentThreadSubject: string | null | undefined,\n): string {\n const base = threadSubject(answering.subject) || threadSubject(enrollmentThreadSubject)\n return (base ? `Re: ${base}` : 'Re:').slice(0, CRM_EMAIL_SUBJECT_MAX)\n}\n\n/** \"Tue, Oct 21, 2026, 8:02 AM\", in the mailbox's zone. */\nfunction quotedTime(atMs: number, timeZone: string | null | undefined): string {\n const options: Intl.DateTimeFormatOptions = {\n weekday: 'short',\n month: 'short',\n day: 'numeric',\n year: 'numeric',\n hour: 'numeric',\n minute: '2-digit',\n }\n // Plain spaces: newer ICU puts a narrow no-break space before \"AM\".\n const format = (zone: string) =>\n new Intl.DateTimeFormat('en-US', { ...options, timeZone: zone }).format(atMs).replace(/[\\u00a0\\u202f]/g, ' ')\n try {\n return format(timeZone || 'UTC')\n } catch {\n return format('UTC')\n }\n}\n\n/** The answered message beneath the answer, quoted the way mail clients quote: `On …, … wrote:` and `> ` lines. */\nexport function outreachReplyQuote(\n answering: Pick<OutreachInboundMessage, 'atMs' | 'from' | 'fromName' | 'body'>,\n timeZone: string | null | undefined,\n): string {\n const who = answering.fromName ? `${answering.fromName} <${answering.from}>` : answering.from\n const lines = answering.body.split('\\n').map((line) => (line ? `> ${line}` : '>'))\n return [`On ${quotedTime(answering.atMs, timeZone)}, ${who} wrote:`, ...lines].join('\\n')\n}\n\n/** An answer, written: what the transport sends and the records keep. */\nexport interface OutreachManualReply {\n to: string\n subject: string\n /** The whole text sent: the member's words, then the quote. */\n text: string\n /** The member's words alone, as sent — tracked links in place — bounded, as the records keep them. */\n body: string\n /**\n * The destinations the minter rewrote, in the order a short link's\n * `linkIndex` names them (AGL-4022). Empty when nothing was rewritten.\n */\n trackedLinks: string[]\n /** The provider thread it is filed into; `null` lets the provider thread it by its headers. */\n threadId: string | null\n /** The answered message's `Message-ID`; `null` when it carried none. */\n inReplyTo: string | null\n references: string[]\n}\n\nexport type OutreachManualReplyErrorCode = 'empty' | 'too_long' | 'invalid_recipient'\n\nexport interface OutreachManualReplyCompose {\n reply: OutreachManualReply | null\n error: { code: OutreachManualReplyErrorCode; message: string } | null\n}\n\n/** Writes the answer — see the module note. */\nexport function composeOutreachManualReply(input: {\n enrollment: Pick<OutreachEnrollment, 'messageIds' | 'threadSubject'>\n answering: OutreachInboundMessage\n body: unknown\n /** The mailbox's zone, for the quote's time. */\n timeZone: string | null | undefined\n /**\n * Mints the short link for the link at `index` in the member's words, or\n * `null` to leave it as written (AGL-4022). Absent — a sequence that does\n * not track clicks — sends every link as written.\n */\n rewriteLink?: ((link: { url: string; index: number }) => string | null) | null\n}): OutreachManualReplyCompose {\n const words = String(input.body ?? '')\n .replace(/\\r\\n?/g, '\\n')\n .replace(/[ \\t]+$/gm, '')\n .replace(/^\\n+|\\n+$/g, '')\n if (!words.trim()) return { reply: null, error: { code: 'empty', message: 'Write your answer before sending it.' } }\n if (words.length > OUTREACH_MANUAL_REPLY_BODY_MAX) {\n return {\n reply: null,\n error: {\n code: 'too_long',\n message: `An answer can be at most ${OUTREACH_MANUAL_REPLY_BODY_MAX.toLocaleString('en-US')} characters.`,\n },\n }\n }\n const to = normalizeContactEmail(input.answering.replyTo ?? input.answering.from)\n if (!to) {\n return { reply: null, error: { code: 'invalid_recipient', message: 'Their message names no address to answer.' } }\n }\n const rewritten = input.rewriteLink ? rewriteOutreachBodyLinks(words, input.rewriteLink) : { text: words, links: [] }\n return {\n reply: {\n to,\n subject: outreachReplySubject(input.answering, input.enrollment.threadSubject),\n text: `${rewritten.text}\\n\\n${outreachReplyQuote(input.answering, input.timeZone)}`,\n body: rewritten.text.slice(0, OUTREACH_MANUAL_REPLY_STORED_MAX),\n trackedLinks: rewritten.links,\n threadId: input.answering.threadId,\n inReplyTo: input.answering.messageId,\n references: outreachReplyReferences(input.enrollment.messageIds ?? [], input.answering),\n },\n error: null,\n }\n}\n\nexport type OutreachManualReplyRefusalCode =\n | 'opted-out'\n | 'bounced'\n | 'do-not-contact'\n | 'unchecked'\n | 'mailbox-unavailable'\n | 'permission'\n\nexport interface OutreachManualReplyRefusal {\n code: OutreachManualReplyRefusalCode\n message: string\n}\n\n/** The address a mailbox sends as. */\nexport const outreachMailboxAddress = (mailbox: Pick<OutreachMailbox, 'sendAs' | 'email'>): string =>\n mailbox.sendAs || mailbox.email\n\n/**\n * Why an answer cannot go now, in the member's words, or `null` — see the\n * module note. The person's own state first, then the lists, then the\n * mailbox, then who may send from it.\n */\nexport function outreachManualReplyRefusal(input: {\n enrollment: Pick<OutreachEnrollment, 'status' | 'email'>\n /** Every address the answer would reach, each looked up. */\n doNotContact: boolean | null\n doNotContactDomain: boolean | null\n mailbox: Pick<OutreachMailbox, 'status' | 'sendAs' | 'email'> | null\n /** The member is the mailbox's own, or an organization owner or admin. */\n mayUseMailbox: boolean\n}): OutreachManualReplyRefusal | null {\n const { enrollment, mailbox } = input\n if (enrollment.status === 'opted_out') {\n return { code: 'opted-out', message: 'They asked not to be emailed, so no answer can be sent to them.' }\n }\n if (enrollment.status === 'bounced') {\n return { code: 'bounced', message: 'Their address bounced, so an answer would not reach them.' }\n }\n if (input.doNotContact === true) {\n return {\n code: 'do-not-contact',\n message: `${enrollment.email} is on your do-not-contact list. Take it off the list on the Compliance page to answer them.`,\n }\n }\n if (input.doNotContactDomain === true) {\n const domain = outreachEmailDomain(enrollment.email) ?? 'Their domain'\n return {\n code: 'do-not-contact',\n message: `${domain} is on your do-not-contact list. Take it off the list on the Compliance page to answer them.`,\n }\n }\n if (input.doNotContact === null || input.doNotContactDomain === null) {\n return { code: 'unchecked', message: 'The do-not-contact list could not be checked. Try again in a moment.' }\n }\n if (!mailbox) {\n return {\n code: 'mailbox-unavailable',\n message: 'The mailbox that wrote to them is no longer connected, so the answer cannot go from it.',\n }\n }\n const address = outreachMailboxAddress(mailbox)\n if (mailbox.status === 'paused') {\n return {\n code: 'mailbox-unavailable',\n message: `${address} is paused. Resume it on the Mailboxes page to answer from it.`,\n }\n }\n if (mailbox.status !== 'connected') {\n return {\n code: 'mailbox-unavailable',\n message: `${address} needs to be connected again. Reconnect it on the Mailboxes page to answer from it.`,\n }\n }\n if (!input.mayUseMailbox) {\n return {\n code: 'permission',\n message: `Only the member who connected ${address}, or an organization owner or admin, can answer from it.`,\n }\n }\n return null\n}\n"],"names":["normalizeContactEmail","CRM_EMAIL_SUBJECT_MAX","emailAddressOf","emailExcerpt","threadSubject","OUTREACH_INBOUND_KINDS","OUTREACH_INBOUND_MESSAGES_MAX","rewriteOutreachBodyLinks","outreachMessageIdHeader","outreachEmailDomain","classifyOutreachMessage","outreachHeader","OUTREACH_MANUAL_REPLY_BODY_MAX","OUTREACH_MANUAL_REPLY_STORED_MAX","REFERENCES_MAX","outreachDisplayNameOf","value","raw","String","trim","angled","lastIndexOf","slice","replace","outreachMessageIdList","found","match","matchAll","id","includes","push","bodyOf","message","textBody","htmlBody","snippet","outreachInboundMessagesOf","messages","context","kept","classification","kind","from","replyTo","threadId","messageId","references","fromName","subject","atMs","body","sort","a","b","mergeOutreachInboundMessages","stored","byId","Map","set","values","outreachMessageToAnswer","inbound","find","at","outreachEnrollmentHasInbound","enrollment","Boolean","inboundMessages","length","stopReason","status","outreachReplyReferences","sentMessageIds","answering","chain","header","outreachReplySubject","enrollmentThreadSubject","base","quotedTime","timeZone","options","weekday","month","day","year","hour","minute","format","zone","Intl","DateTimeFormat","outreachReplyQuote","who","lines","split","map","line","join","composeOutreachManualReply","input","words","reply","error","code","toLocaleString","to","rewritten","rewriteLink","text","links","trackedLinks","inReplyTo","messageIds","outreachMailboxAddress","mailbox","sendAs","email","outreachManualReplyRefusal","doNotContact","doNotContactDomain","domain","address","mayUseMailbox"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;4CAwC4C,GAE5C,SAASA,qBAAqB,QAAQ,kCAAiC;AACvE,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,cAAc,EAAEC,YAAY,EAAEC,aAAa,QAAQ,oCAAmC;AAC/F,SACEC,sBAAsB,EACtBC,6BAA6B,QAKxB,6BAAy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../libs/plugins/outreach/src/lib/engine/manual-reply.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * ANSWERING A PERSON WHO WROTE BACK (AGL-4020).\n *\n * A person who answers a sequence email is answered from the same mailbox,\n * in the same thread, by a member: the reply is a one-to-one email, never a\n * step of the sequence. This module is the engine's half of it — what the\n * person wrote, as the enrollment keeps it, and the answer, as the\n * transport sends it — and decides nothing about storage or delivery.\n *\n * ## What the person wrote\n *\n * {@link outreachInboundMessagesOf} keeps the messages of a thread the\n * classifier reads as theirs: a reply, an automatic answer, an opt-out. Each\n * carries its sender, its time, its `Message-ID` and `References` (what an\n * answer threads by), and its text with the quoted history trimmed, the way\n * the record's timeline keeps it (`emailExcerpt`).\n *\n * ## The answer\n *\n * {@link composeOutreachManualReply} writes it as every mail client writes a\n * reply: `Re:` the subject of the message it answers, `In-Reply-To` that\n * message's `Message-ID`, and `References` the whole chain — the sequence's\n * own sends, what the person's message already named, and the message\n * itself — so it lands in the same thread in the person's mailbox and in\n * ours. Plain text, the member's words first and the message answered quoted\n * beneath. No footer and no `List-Unsubscribe`: the person wrote first, and\n * this is the answer a person would type in their own mail client.\n *\n * On a sequence that tracks link clicks, the links in the member's words go\n * out as the same short links a step's do (AGL-4022), through the caller's\n * minter — never the links in the quoted message, which are theirs.\n *\n * ## What still refuses\n *\n * {@link outreachManualReplyRefusal}: an address or a domain on the\n * do-not-contact list, a person who opted out or whose address bounced, and\n * a mailbox that is paused, waiting to be reconnected, or gone. The cold\n * rules — the allowed countries, the company-domain rule, the personal line,\n * the daily cap — do not apply to someone who wrote first, and are not\n * asked.\n *==========================================*/\n\nimport { normalizeContactEmail } from '@aglyn/aglyn/app-utils/contacts'\nimport { CRM_EMAIL_SUBJECT_MAX } from '@aglyn/aglyn/app-utils/crm'\nimport { emailAddressOf, emailExcerpt, threadSubject } from '@aglyn/aglyn/app-utils/email-text'\nimport {\n OUTREACH_INBOUND_KINDS,\n OUTREACH_INBOUND_MESSAGES_MAX,\n type OutreachEnrollment,\n type OutreachInboundKind,\n type OutreachInboundMessage,\n type OutreachMailbox,\n} from '../model/outreach.types'\nimport { rewriteOutreachBodyLinks } from './click-tracking'\nimport { outreachMessageIdHeader } from './compose'\nimport { outreachEmailDomain } from './do-not-contact-domain'\nimport { classifyOutreachMessage, type OutreachMessageContext } from './thread-classification'\nimport { outreachHeader, type OutreachThreadMessage } from './thread-message'\n\n/** The most a member may write in one answer. */\nexport const OUTREACH_MANUAL_REPLY_BODY_MAX = 10_000\n\n/** The most of an answer the enrollment and the record keep: the timeline's excerpt length. */\nexport const OUTREACH_MANUAL_REPLY_STORED_MAX = 4_000\n\n/** The most `Message-ID`s one answer's `References` names: the first, and the latest. */\nconst REFERENCES_MAX = 20\n\n/** The display name in a `From` value — `\"Ada Lovelace\" <ada@example.com>` answers `Ada Lovelace` — or `''`. */\nexport function outreachDisplayNameOf(value: unknown): string {\n const raw = String(value ?? '').trim()\n const angled = raw.lastIndexOf('<')\n if (angled <= 0) return ''\n return raw\n .slice(0, angled)\n .trim()\n .replace(/^\"(.*)\"$/, '$1')\n .replace(/\\\\(.)/g, '$1')\n .trim()\n}\n\n/** Every `Message-ID` a `References` or `In-Reply-To` value names, in header form, in order, once each. */\nexport function outreachMessageIdList(value: unknown): string[] {\n const found: string[] = []\n for (const match of String(value ?? '').matchAll(/<[^<>\\s]+>/g)) {\n const id = outreachMessageIdHeader(match[0])\n if (id && !found.includes(id)) found.push(id)\n }\n return found\n}\n\n/** A message's text as the record keeps it: the text part, else the HTML's words, else the preview. */\nfunction bodyOf(message: OutreachThreadMessage): string {\n return emailExcerpt(message.textBody ?? '', message.htmlBody ?? '') || emailExcerpt(message.snippet ?? '')\n}\n\n/**\n * The person's own messages among a thread's — see the module note — oldest\n * first. A message with no sender address is left out: it could be neither\n * shown as theirs nor answered.\n */\nexport function outreachInboundMessagesOf(\n messages: readonly OutreachThreadMessage[],\n context: OutreachMessageContext,\n): OutreachInboundMessage[] {\n const kept: OutreachInboundMessage[] = []\n for (const message of messages) {\n if (!message?.id) continue\n const classification = classifyOutreachMessage(message, context)\n if (!(OUTREACH_INBOUND_KINDS as readonly string[]).includes(classification.kind)) continue\n const from = emailAddressOf(message.from)\n if (!from) continue\n const replyTo = emailAddressOf(outreachHeader(message, 'Reply-To'))\n kept.push({\n id: message.id,\n threadId: message.threadId ?? null,\n messageId: outreachMessageIdHeader(outreachHeader(message, 'Message-ID')),\n references: outreachMessageIdList(outreachHeader(message, 'References')),\n from,\n fromName: outreachDisplayNameOf(message.from),\n replyTo: replyTo && replyTo !== from ? replyTo : null,\n subject: String(message.subject ?? '').replace(/\\s+/g, ' ').trim(),\n atMs: classification.atMs,\n kind: classification.kind as OutreachInboundKind,\n body: bodyOf(message),\n })\n }\n return kept.sort((a, b) => a.atMs - b.atMs)\n}\n\n/**\n * What an enrollment keeps once more of the person's messages are read: one\n * entry per message — a re-read replaces the earlier copy — oldest first,\n * the last {@link OUTREACH_INBOUND_MESSAGES_MAX}.\n */\nexport function mergeOutreachInboundMessages(\n stored: readonly OutreachInboundMessage[] | null | undefined,\n found: readonly OutreachInboundMessage[],\n): OutreachInboundMessage[] {\n const byId = new Map<string, OutreachInboundMessage>()\n for (const message of [...(stored ?? []), ...found]) byId.set(message.id, message)\n return [...byId.values()].sort((a, b) => a.atMs - b.atMs).slice(-OUTREACH_INBOUND_MESSAGES_MAX)\n}\n\n/**\n * The message an answer replies to: the one named, when the enrollment\n * kept it, else the newest the person wrote. `null` when they wrote nothing\n * the enrollment kept.\n */\nexport function outreachMessageToAnswer(\n inbound: readonly OutreachInboundMessage[] | null | undefined,\n id?: string | null,\n): OutreachInboundMessage | null {\n const messages = [...(inbound ?? [])].sort((a, b) => a.atMs - b.atMs)\n if (id) return messages.find((message) => message.id === id) ?? null\n return messages.at(-1) ?? null\n}\n\n/** Whether a member may answer this enrollment at all: the person wrote something it kept, or a reply stopped it. */\nexport function outreachEnrollmentHasInbound(\n enrollment: Pick<OutreachEnrollment, 'inboundMessages' | 'stopReason' | 'status'>,\n): boolean {\n return Boolean(enrollment.inboundMessages?.length) || enrollment.stopReason === 'reply' || enrollment.status === 'replied'\n}\n\n/**\n * The answer's `References` — see the module note: the sequence's own sends,\n * then what the answered message named, then the message itself, each once.\n * A long chain keeps its first id and its latest, as RFC 5322 §3.6.4 allows.\n */\nexport function outreachReplyReferences(\n sentMessageIds: readonly string[],\n answering: Pick<OutreachInboundMessage, 'references' | 'messageId'>,\n): string[] {\n const chain: string[] = []\n for (const id of [...sentMessageIds, ...answering.references, answering.messageId]) {\n const header = outreachMessageIdHeader(id)\n if (header && !chain.includes(header)) chain.push(header)\n }\n return chain.length > REFERENCES_MAX ? [chain[0], ...chain.slice(-(REFERENCES_MAX - 1))] : chain\n}\n\n/** `Re:` the subject of the message answered, else of the thread the sequence started. */\nexport function outreachReplySubject(\n answering: Pick<OutreachInboundMessage, 'subject'>,\n enrollmentThreadSubject: string | null | undefined,\n): string {\n const base = threadSubject(answering.subject) || threadSubject(enrollmentThreadSubject)\n return (base ? `Re: ${base}` : 'Re:').slice(0, CRM_EMAIL_SUBJECT_MAX)\n}\n\n/** \"Tue, Oct 21, 2026, 8:02 AM\", in the mailbox's zone. */\nfunction quotedTime(atMs: number, timeZone: string | null | undefined): string {\n const options: Intl.DateTimeFormatOptions = {\n weekday: 'short',\n month: 'short',\n day: 'numeric',\n year: 'numeric',\n hour: 'numeric',\n minute: '2-digit',\n }\n // Plain spaces: newer ICU puts a narrow no-break space before \"AM\".\n const format = (zone: string) =>\n new Intl.DateTimeFormat('en-US', { ...options, timeZone: zone }).format(atMs).replace(/[\\u00a0\\u202f]/g, ' ')\n try {\n return format(timeZone || 'UTC')\n } catch {\n return format('UTC')\n }\n}\n\n/** The answered message beneath the answer, quoted the way mail clients quote: `On …, … wrote:` and `> ` lines. */\nexport function outreachReplyQuote(\n answering: Pick<OutreachInboundMessage, 'atMs' | 'from' | 'fromName' | 'body'>,\n timeZone: string | null | undefined,\n): string {\n const who = answering.fromName ? `${answering.fromName} <${answering.from}>` : answering.from\n const lines = answering.body.split('\\n').map((line) => (line ? `> ${line}` : '>'))\n return [`On ${quotedTime(answering.atMs, timeZone)}, ${who} wrote:`, ...lines].join('\\n')\n}\n\n/** An answer, written: what the transport sends and the records keep. */\nexport interface OutreachManualReply {\n to: string\n subject: string\n /** The whole text sent: the member's words, then the quote. */\n text: string\n /** The member's words alone, as sent — tracked links in place — bounded, as the records keep them. */\n body: string\n /**\n * The destinations the minter rewrote, in the order a short link's\n * `linkIndex` names them (AGL-4022). Empty when nothing was rewritten.\n */\n trackedLinks: string[]\n /** The provider thread it is filed into; `null` lets the provider thread it by its headers. */\n threadId: string | null\n /** The answered message's `Message-ID`; `null` when it carried none. */\n inReplyTo: string | null\n references: string[]\n}\n\nexport type OutreachManualReplyErrorCode = 'empty' | 'too_long' | 'invalid_recipient'\n\nexport interface OutreachManualReplyCompose {\n reply: OutreachManualReply | null\n error: { code: OutreachManualReplyErrorCode; message: string } | null\n}\n\n/** Writes the answer — see the module note. */\nexport function composeOutreachManualReply(input: {\n enrollment: Pick<OutreachEnrollment, 'messageIds' | 'threadSubject'>\n answering: OutreachInboundMessage\n body: unknown\n /** The mailbox's zone, for the quote's time. */\n timeZone: string | null | undefined\n /**\n * Mints the short link for the link at `index` in the member's words, or\n * `null` to leave it as written (AGL-4022). Absent — a sequence that does\n * not track clicks — sends every link as written.\n */\n rewriteLink?: ((link: { url: string; index: number }) => string | null) | null\n}): OutreachManualReplyCompose {\n const words = String(input.body ?? '')\n .replace(/\\r\\n?/g, '\\n')\n .replace(/[ \\t]+$/gm, '')\n .replace(/^\\n+|\\n+$/g, '')\n if (!words.trim()) return { reply: null, error: { code: 'empty', message: 'Write your answer before sending it.' } }\n if (words.length > OUTREACH_MANUAL_REPLY_BODY_MAX) {\n return {\n reply: null,\n error: {\n code: 'too_long',\n message: `An answer can be at most ${OUTREACH_MANUAL_REPLY_BODY_MAX.toLocaleString('en-US')} characters.`,\n },\n }\n }\n const to = normalizeContactEmail(input.answering.replyTo ?? input.answering.from)\n if (!to) {\n return { reply: null, error: { code: 'invalid_recipient', message: 'Their message names no address to answer.' } }\n }\n const rewritten = input.rewriteLink ? rewriteOutreachBodyLinks(words, input.rewriteLink) : { text: words, links: [] }\n return {\n reply: {\n to,\n subject: outreachReplySubject(input.answering, input.enrollment.threadSubject),\n text: `${rewritten.text}\\n\\n${outreachReplyQuote(input.answering, input.timeZone)}`,\n body: rewritten.text.slice(0, OUTREACH_MANUAL_REPLY_STORED_MAX),\n trackedLinks: rewritten.links,\n threadId: input.answering.threadId,\n inReplyTo: input.answering.messageId,\n references: outreachReplyReferences(input.enrollment.messageIds ?? [], input.answering),\n },\n error: null,\n }\n}\n\nexport type OutreachManualReplyRefusalCode =\n | 'opted-out'\n | 'bounced'\n | 'do-not-contact'\n | 'unchecked'\n | 'mailbox-unavailable'\n | 'permission'\n\nexport interface OutreachManualReplyRefusal {\n code: OutreachManualReplyRefusalCode\n message: string\n}\n\n/** The address a mailbox sends as. */\nexport const outreachMailboxAddress = (mailbox: Pick<OutreachMailbox, 'sendAs' | 'email'>): string =>\n mailbox.sendAs || mailbox.email\n\n/**\n * Why an answer cannot go now, in the member's words, or `null` — see the\n * module note. The person's own state first, then the lists, then the\n * mailbox, then who may send from it.\n */\nexport function outreachManualReplyRefusal(input: {\n enrollment: Pick<OutreachEnrollment, 'status' | 'email'>\n /** Every address the answer would reach, each looked up. */\n doNotContact: boolean | null\n doNotContactDomain: boolean | null\n mailbox: Pick<OutreachMailbox, 'status' | 'sendAs' | 'email'> | null\n /** The member is the mailbox's own, or an organization owner or admin. */\n mayUseMailbox: boolean\n}): OutreachManualReplyRefusal | null {\n const { enrollment, mailbox } = input\n if (enrollment.status === 'opted_out') {\n return { code: 'opted-out', message: 'They asked not to be emailed, so no answer can be sent to them.' }\n }\n if (enrollment.status === 'bounced') {\n return { code: 'bounced', message: 'Their address bounced, so an answer would not reach them.' }\n }\n if (input.doNotContact === true) {\n return {\n code: 'do-not-contact',\n message: `${enrollment.email} is on your do-not-contact list. Take it off the list on the Compliance page to answer them.`,\n }\n }\n if (input.doNotContactDomain === true) {\n const domain = outreachEmailDomain(enrollment.email) ?? 'Their domain'\n return {\n code: 'do-not-contact',\n message: `${domain} is on your do-not-contact list. Take it off the list on the Compliance page to answer them.`,\n }\n }\n if (input.doNotContact === null || input.doNotContactDomain === null) {\n return { code: 'unchecked', message: 'The do-not-contact list could not be checked. Try again in a moment.' }\n }\n if (!mailbox) {\n return {\n code: 'mailbox-unavailable',\n message: 'The mailbox that wrote to them is no longer connected, so the answer cannot go from it.',\n }\n }\n const address = outreachMailboxAddress(mailbox)\n if (mailbox.status === 'paused') {\n return {\n code: 'mailbox-unavailable',\n message: `${address} is paused. Resume it on the Mailboxes page to answer from it.`,\n }\n }\n if (mailbox.status !== 'connected') {\n return {\n code: 'mailbox-unavailable',\n message: `${address} needs to be connected again. Reconnect it on the Mailboxes page to answer from it.`,\n }\n }\n if (!input.mayUseMailbox) {\n return {\n code: 'permission',\n message: `Only the member who connected ${address}, or a member holding \"Manage everyone’s Sequences\", can answer from it.`,\n }\n }\n return null\n}\n"],"names":["normalizeContactEmail","CRM_EMAIL_SUBJECT_MAX","emailAddressOf","emailExcerpt","threadSubject","OUTREACH_INBOUND_KINDS","OUTREACH_INBOUND_MESSAGES_MAX","rewriteOutreachBodyLinks","outreachMessageIdHeader","outreachEmailDomain","classifyOutreachMessage","outreachHeader","OUTREACH_MANUAL_REPLY_BODY_MAX","OUTREACH_MANUAL_REPLY_STORED_MAX","REFERENCES_MAX","outreachDisplayNameOf","value","raw","String","trim","angled","lastIndexOf","slice","replace","outreachMessageIdList","found","match","matchAll","id","includes","push","bodyOf","message","textBody","htmlBody","snippet","outreachInboundMessagesOf","messages","context","kept","classification","kind","from","replyTo","threadId","messageId","references","fromName","subject","atMs","body","sort","a","b","mergeOutreachInboundMessages","stored","byId","Map","set","values","outreachMessageToAnswer","inbound","find","at","outreachEnrollmentHasInbound","enrollment","Boolean","inboundMessages","length","stopReason","status","outreachReplyReferences","sentMessageIds","answering","chain","header","outreachReplySubject","enrollmentThreadSubject","base","quotedTime","timeZone","options","weekday","month","day","year","hour","minute","format","zone","Intl","DateTimeFormat","outreachReplyQuote","who","lines","split","map","line","join","composeOutreachManualReply","input","words","reply","error","code","toLocaleString","to","rewritten","rewriteLink","text","links","trackedLinks","inReplyTo","messageIds","outreachMailboxAddress","mailbox","sendAs","email","outreachManualReplyRefusal","doNotContact","doNotContactDomain","domain","address","mayUseMailbox"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;4CAwC4C,GAE5C,SAASA,qBAAqB,QAAQ,kCAAiC;AACvE,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,cAAc,EAAEC,YAAY,EAAEC,aAAa,QAAQ,oCAAmC;AAC/F,SACEC,sBAAsB,EACtBC,6BAA6B,QAKxB,6BAAyB;AAChC,SAASC,wBAAwB,QAAQ,sBAAkB;AAC3D,SAASC,uBAAuB,QAAQ,eAAW;AACnD,SAASC,mBAAmB,QAAQ,6BAAyB;AAC7D,SAASC,uBAAuB,QAAqC,6BAAyB;AAC9F,SAASC,cAAc,QAAoC,sBAAkB;AAE7E,+CAA+C,GAC/C,OAAO,MAAMC,iCAAiC,MAAM;AAEpD,6FAA6F,GAC7F,OAAO,MAAMC,mCAAmC,KAAK;AAErD,uFAAuF,GACvF,MAAMC,iBAAiB;AAEvB,8GAA8G,GAC9G,OAAO,SAASC,sBAAs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FAA4F,CAAC;QAC5H;IACF;IACA,IAAIjB,MAAMoB,kBAAkB,KAAK,MAAM;YACtB/G;QAAf,MAAMgH,UAAShH,uBAAAA,oBAAoBwD,WAAWoD,KAAK,aAApC5G,uBAAyC;QACxD,OAAO;YACL+F,MAAM;YACNxE,SAAS,GAAGyF,OAAO,4FAA4F,CAAC;QAClH;IACF;IACA,IAAIrB,MAAMmB,YAAY,KAAK,QAAQnB,MAAMoB,kBAAkB,KAAK,MAAM;QACpE,OAAO;YAAEhB,MAAM;YAAaxE,SAAS;QAAuE;IAC9G;IACA,IAAI,CAACmF,SAAS;QACZ,OAAO;YACLX,MAAM;YACNxE,SAAS;QACX;IACF;IACA,MAAM0F,UAAUR,uBAAuBC;IACvC,IAAIA,QAAQ7C,MAAM,KAAK,UAAU;QAC/B,OAAO;YACLkC,MAAM;YACNxE,SAAS,GAAG0F,QAAQ,8DAA8D,CAAC;QACrF;IACF;IACA,IAAIP,QAAQ7C,MAAM,KAAK,aAAa;QAClC,OAAO;YACLkC,MAAM;YACNxE,SAAS,GAAG0F,QAAQ,mFAAmF,CAAC;QAC1G;IACF;IACA,IAAI,CAACtB,MAAMuB,aAAa,EAAE;QACxB,OAAO;YACLnB,MAAM;YACNxE,SAAS,CAAC,8BAA8B,EAAE0F,QAAQ,wEAAwE,CAAC;QAC7H;IACF;IACA,OAAO;AACT"}
@@ -92,7 +92,7 @@ export function createOutreachMailboxRoutes(deps) {
92
92
  if (!mailbox) return refusal(404, 'mailbox-not-found', 'That mailbox is not connected to this organization.');
93
93
  const own = mailbox.connectedByUid === gate.uid;
94
94
  if (!own && !(who === 'member-or-admin' && gate.isOrgAdmin)) {
95
- return refusal(403, 'not-your-mailbox', who === 'member' ? 'Only the member who connected this mailbox can do that.' : 'Only the member who connected this mailbox, or an organization owner or admin, can change it.');
95
+ return refusal(403, 'not-your-mailbox', who === 'member' ? 'Only the member who connected this mailbox can do that.' : 'Only the member who connected this mailbox, or a member holding "Manage everyone’s Sequences", can change it.');
96
96
  }
97
97
  return {
98
98
  gate,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/mailboxes/mailbox-routes.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { normalizeContactEmail } from '@aglyn/aglyn/app-utils/contacts'\nimport type { PluginWebApiHandler } from '@aglyn/aglyn/server'\nimport {\n googleMailboxSenderExpectation,\n microsoftMailboxSenderExpectation,\n type SenderReadiness,\n type SenderReadinessExpectation,\n} from '@aglyn/shared-util-email'\nimport type { SecretBoxKeyring } from '@aglyn/shared-util-tools/secret-box'\nimport {\n OUTREACH_MAILBOX_PROVIDERS,\n type OutreachMailbox,\n type OutreachMailboxProvider,\n type OutreachMailboxStatus,\n type OutreachSendAsAddress,\n} from '../model/outreach.types'\nimport { createGmailClient } from '../transport/gmail-client'\nimport { createGraphClient, type GraphProfile } from '../transport/graph-client'\nimport { GmailTransportError, googleFailureAnswer } from '../transport/gmail-errors'\nimport {\n buildGoogleAuthorizationUrl,\n exchangeGoogleAuthorizationCode,\n grantedScopesInclude,\n OUTREACH_REQUIRED_GRANTED_SCOPES,\n pkceChallenge,\n readGoogleIdToken,\n type GoogleTokenResponse,\n} from '../transport/google-oauth'\nimport type { TransportDeps } from '../transport/http'\nimport {\n buildMicrosoftAuthorizationUrl,\n exchangeMicrosoftAuthorizationCode,\n microsoftScopesInclude,\n readMicrosoftIdToken,\n type MicrosoftTokenResponse,\n} from '../transport/microsoft-oauth'\nimport { Rfc5322MessageError } from '../transport/rfc5322'\nimport { sendOutreachMessage } from '../transport/send-message'\nimport {\n buildConnectReturnFragment,\n type OutreachApiRefusalReason,\n type OutreachConnectReturn,\n type OutreachMailboxAvailability,\n type OutreachMailboxAvailabilityGate,\n type OutreachMailboxDisconnectResponse,\n type OutreachMailboxReadinessResponse,\n} from './mailbox-api'\nimport {\n mailboxCredentialsRef,\n mailboxRef,\n outreachMailboxId,\n readMailboxCredentials,\n sealMailboxRefreshToken,\n type OutreachStoredMailboxCredentials,\n} from './mailbox-credentials'\nimport { revokeMailboxGrant } from './mailbox-revoke'\nimport {\n outreachMemberGate,\n refusal,\n type OutreachGateContext,\n type OutreachGateDeps,\n} from './mailbox-gate'\nimport {\n defaultSendAs,\n isValidTimezone,\n OUTREACH_DEFAULT_DAILY_CAP,\n OUTREACH_DEFAULT_WINDOW,\n OUTREACH_MAX_MAILBOXES_PER_MEMBER,\n validateDailyCap,\n validateDisplayName,\n validateSendWindow,\n verifiedSendAsAddresses,\n} from './mailbox-settings'\nimport {\n markOutreachMailboxReconnectRequired,\n openOutreachMailboxClient,\n} from './mailbox-transport'\nimport {\n consumeOutreachOAuthState,\n mintOutreachOAuthState,\n outreachOidcNonce,\n outreachPkceVerifier,\n readOutreachOAuthState,\n recordOutreachOAuthState,\n type OutreachOAuthStateClaims,\n} from './oauth-state'\nimport {\n outreachNotConfiguredMessage,\n readOutreachMicrosoftConfig,\n type OutreachGoogleConfigResult,\n type OutreachMicrosoftConfigResult,\n} from './outreach-config'\n\n/**\n * THE MAILBOX ROUTES (AGL-2978): connect a rep's Google or Microsoft 365\n * mailbox, keep its settings, pause it, test it, and disconnect it.\n *\n * A connect names its provider (AGL-3489). Both providers' consent screens\n * return to the one callback; the signed state says which one a connect went\n * to, and `connect/complete` redeems the code with that provider. Everything\n * after the provider has named the account — the mailbox limit, the mailbox\n * and its sealed grant, the activity row — is the same for both.\n *\n * ## The connect, end to end\n *\n * 1. `connect` (the member's session) mints a signed, single-use state bound\n * to the member and the organization, records its pending entry, and\n * answers Google's consent address — offline access, the consent prompt,\n * a PKCE challenge and an OpenID nonce, both derived from the state.\n * 2. Google redirects the browser to `oauth/callback`. That request carries\n * no bearer token, so it DOES nothing: it verifies the state's signature,\n * finds the organization's console path, and redirects to the Mailboxes\n * page with the code in the URL FRAGMENT, where no server and no `Referer`\n * sees it. Its release gate was asked about the organization and the\n * member the state names (the route's declared subject).\n * 3. The page takes the code out of the address bar and posts it to\n * `connect/complete` with the member's own session. That is where the\n * state is consumed, where it is refused if it was minted for anyone else,\n * and where the code is exchanged. So a consent screen someone else was\n * tricked into completing cannot connect THEIR mailbox to the member who\n * started it: the code arrives in the wrong browser, whose session is not\n * the state's member.\n *\n * ## Refusals, in order, on `connect/complete`\n *\n * A state that is invalid, minted for another member or organization,\n * expired, already used or superseded; a code Google refuses; a grant with no\n * refresh token; a grant missing `gmail.send` or `gmail.readonly` (the consent\n * screen lets a person untick them); an ID token that is not about this\n * exchange or whose address Google has not verified; an account with no Gmail\n * service (a Workspace user whose Gmail is off, or not yet provisioned) or one\n * Google bars from the Gmail API; a Gmail profile whose address is not the ID\n * token's; and a member at their mailbox limit. Each is a 4xx: only a Google\n * outage, or a request Google calls malformed, answers 502.\n *\n * A grant refused after the code exchange is dropped, not revoked. Google's\n * revocation ends the whole grant this client holds for the account, and the\n * same account may already be connected — by this member in another\n * organization, or by a teammate — so revoking a token this route merely\n * declines to keep could disconnect a mailbox that is working.\n *\n * ## Who may do what\n *\n * Every route but the callback climbs `outreachMemberGate`. The member who\n * connected a mailbox manages it; an organization owner or admin may also\n * change its settings, pause it and disconnect it — a departing rep's mailbox\n * has to be stoppable by somebody. Only its own member can send a test from\n * it, since the test lands in their inbox.\n */\n\nexport interface OutreachMailboxRouteDeps {\n firestore(): FirebaseFirestore.Firestore\n gate: OutreachGateDeps\n readConfig(): OutreachGoogleConfigResult\n /** The Microsoft app registration (AGL-3489); the environment's when omitted. */\n readMicrosoftConfig?(): OutreachMicrosoftConfigResult\n /** Whether the signing secret the OAuth state needs is configured. */\n stateSigningConfigured(): boolean\n redirectUri(requestUrl: string): string | null\n now(): number\n /** The network and retry policy every Google call uses. */\n transport: TransportDeps\n consumeRateLimit(key: string, options: { limit: number; windowMs: number }): Promise<{ allowed: boolean }>\n logOrgActivity(\n orgId: string,\n actor: { uid: string; email?: string | null },\n action: string,\n target: { type: typeof OUTREACH_MAILBOX_ACTIVITY_TARGET; id: string; name: string },\n ): Promise<void>\n confirmAliasesByProvider(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; uid: string; addresses: readonly string[]; nowMs: number },\n ): Promise<{ ok: boolean; confirmed?: string[] }>\n /** SPF, DKIM and DMARC for one sender, looked up and briefly remembered. */\n readSenderReadiness(expectation: SenderReadinessExpectation, options: { fresh?: boolean }): Promise<SenderReadiness>\n}\n\nexport interface OutreachMailboxRoutes {\n availability: PluginWebApiHandler\n connect: PluginWebApiHandler\n oauthCallback: PluginWebApiHandler\n connectComplete: PluginWebApiHandler\n settings: PluginWebApiHandler\n status: PluginWebApiHandler\n test: PluginWebApiHandler\n disconnect: PluginWebApiHandler\n readiness: PluginWebApiHandler\n}\n\n/** Test sends one mailbox may make in an hour. */\nexport const OUTREACH_TEST_SENDS_PER_HOUR = 5\n\n/**\n * The org activity target a mailbox's rows are filed under: Outreach's own\n * namespaced resource, which the feed reads as \"Mailbox\".\n */\nexport const OUTREACH_MAILBOX_ACTIVITY_TARGET = 'outreach:mailbox'\n\nconst MAILBOX_ID = /^[A-Za-z0-9_-]{1,128}$/\nconst MAX_CODE_CHARS = 2048\n\nconst noStore = { 'Cache-Control': 'no-store' }\n\nconst ok = (body: unknown) => Response.json(body, { status: 200, headers: noStore })\n\nfunction methodNotAllowed(allow: string): Response {\n return Response.json(\n { error: 'Method not allowed', reason: 'method-not-allowed' satisfies OutreachApiRefusalReason },\n { status: 405, headers: { ...noStore, Allow: allow } },\n )\n}\n\nasync function readBody(request: Request): Promise<Record<string, unknown>> {\n const body = await request.json().catch(() => null)\n return body && typeof body === 'object' && !Array.isArray(body) ? (body as Record<string, unknown>) : {}\n}\n\nfunction notConfigured(provider: OutreachMailboxProvider = 'google'): Response {\n return refusal(503, 'not-configured', outreachNotConfiguredMessage(provider))\n}\n\n/** The provider a request names; Google when it names none, `null` for one that is not a provider. */\nfunction readProvider(value: unknown): OutreachMailboxProvider | null {\n if (value === undefined || value === null || value === '') return 'google'\n return (OUTREACH_MAILBOX_PROVIDERS as readonly unknown[]).includes(value) ? (value as OutreachMailboxProvider) : null\n}\n\nconst providerName = (provider: OutreachMailboxProvider) => (provider === 'microsoft' ? 'Microsoft' : 'Google')\n\n/** What a provider's sign-in established about the account a connect is for. */\ninterface ConnectedAccount {\n provider: OutreachMailboxProvider\n providerAccountId: string\n email: string\n sendAsOptions: OutreachSendAsAddress[]\n scopes: string[]\n refreshToken: string\n keyring: SecretBoxKeyring\n}\n\n/** A mailbox document read defensively into the model shape. */\nfunction readMailbox(id: string, data: Record<string, unknown> | undefined): OutreachMailbox | null {\n if (!data) return null\n return { ...(data as unknown as OutreachMailbox), id }\n}\n\nconst activityName = (mailbox: Pick<OutreachMailbox, 'email'>) => mailbox.email\n\nexport function createOutreachMailboxRoutes(deps: OutreachMailboxRouteDeps): OutreachMailboxRoutes {\n const readMicrosoftConfig = () => (deps.readMicrosoftConfig ?? readOutreachMicrosoftConfig)()\n /** Whether a provider's client and the token key are configured here. */\n const providerConfigured = (provider: OutreachMailboxProvider) =>\n provider === 'microsoft' ? readMicrosoftConfig().configured : deps.readConfig().configured\n\n /** The gate, then the mailbox the body names, then who may touch it. */\n async function loadManagedMailbox(\n request: Request,\n body: Record<string, unknown>,\n who: 'member-or-admin' | 'member',\n ): Promise<Response | { gate: OutreachGateContext; mailbox: OutreachMailbox }> {\n const gate = await outreachMemberGate(request, body['orgId'], deps.gate)\n if (gate instanceof Response) return gate\n const mailboxId = typeof body['mailboxId'] === 'string' ? body['mailboxId'] : ''\n if (!MAILBOX_ID.test(mailboxId)) return refusal(400, 'invalid-request', 'Name the mailbox.')\n const snapshot = await mailboxRef(deps.firestore(), gate.orgId, mailboxId).get()\n const mailbox = readMailbox(mailboxId, snapshot.exists ? snapshot.data() : undefined)\n if (!mailbox) return refusal(404, 'mailbox-not-found', 'That mailbox is not connected to this organization.')\n const own = mailbox.connectedByUid === gate.uid\n if (!own && !(who === 'member-or-admin' && gate.isOrgAdmin)) {\n return refusal(\n 403,\n 'not-your-mailbox',\n who === 'member'\n ? 'Only the member who connected this mailbox can do that.'\n : 'Only the member who connected this mailbox, or an organization owner or admin, can change it.',\n )\n }\n return { gate, mailbox }\n }\n\n const availability: PluginWebApiHandler = async (request) => {\n if (request.method !== 'GET') return methodNotAllowed('GET')\n const gate = await outreachMemberGate(request, new URL(request.url).searchParams.get('orgId'), deps.gate)\n if (gate instanceof Response) return gate\n // Every gate is named, not the first: an operator fixing a deployment\n // should see the whole list once rather than one variable per redeploy.\n const missing: OutreachMailboxAvailabilityGate[] = []\n const config = deps.readConfig()\n const microsoft = readMicrosoftConfig()\n if (config.configured === false) missing.push({ gate: 'google', missing: config.missing })\n if (microsoft.configured === false) missing.push({ gate: 'microsoft', missing: microsoft.missing })\n const shared = deps.stateSigningConfigured() && Boolean(deps.redirectUri(request.url))\n if (!deps.stateSigningConfigured()) missing.push({ gate: 'state' })\n if (!deps.redirectUri(request.url)) missing.push({ gate: 'redirect' })\n const providers = { google: shared && config.configured, microsoft: shared && microsoft.configured }\n return ok({\n // Google's readiness, as this field has always meant; `providers` says each.\n configured: providers.google,\n providers,\n canManageAll: gate.isOrgAdmin,\n ...(missing.length ? { missing } : {}),\n } satisfies OutreachMailboxAvailability)\n }\n\n const connect: PluginWebApiHandler = async (request) => {\n if (request.method !== 'POST') return methodNotAllowed('POST')\n const body = await readBody(request)\n const gate = await outreachMemberGate(request, body['orgId'], deps.gate)\n if (gate instanceof Response) return gate\n const provider = readProvider(body['provider'])\n if (!provider) return refusal(400, 'invalid-request', 'Choose Google or Microsoft.')\n const redirectUri = deps.redirectUri(request.url)\n if (!redirectUri || !deps.stateSigningConfigured()) return notConfigured(provider)\n\n if (provider === 'microsoft') {\n const microsoft = readMicrosoftConfig()\n if (!microsoft.configured) return notConfigured(provider)\n const nowMs = deps.now()\n const { state, claims } = mintOutreachOAuthState({ orgId: gate.orgId, uid: gate.uid, nowMs, provider })\n await recordOutreachOAuthState(deps.firestore(), { claims, redirectUri, nowMs })\n const url = buildMicrosoftAuthorizationUrl({\n clientId: microsoft.config.clientId,\n tenant: microsoft.config.tenant,\n redirectUri,\n state,\n codeChallenge: pkceChallenge(outreachPkceVerifier(claims.nonce)),\n nonce: outreachOidcNonce(claims.nonce),\n loginHint: typeof body['loginHint'] === 'string' ? normalizeContactEmail(body['loginHint']) : null,\n })\n return ok({ url })\n }\n\n const config = deps.readConfig()\n if (!config.configured) return notConfigured()\n const nowMs = deps.now()\n const { state, claims } = mintOutreachOAuthState({ orgId: gate.orgId, uid: gate.uid, nowMs })\n await recordOutreachOAuthState(deps.firestore(), { claims, redirectUri, nowMs })\n const url = buildGoogleAuthorizationUrl({\n clientId: config.config.clientId,\n redirectUri,\n state,\n codeChallenge: pkceChallenge(outreachPkceVerifier(claims.nonce)),\n nonce: outreachOidcNonce(claims.nonce),\n loginHint: gate.email,\n })\n return ok({ url })\n }\n\n const oauthCallback: PluginWebApiHandler = async (request) => {\n if (request.method !== 'GET') return methodNotAllowed('GET')\n const params = new URL(request.url).searchParams\n const read = readOutreachOAuthState(params.get('state'), deps.now())\n const plain = (status: number, text: string) =>\n new Response(text, {\n status,\n headers: { ...noStore, 'Content-Type': 'text/plain; charset=utf-8', 'Referrer-Policy': 'no-referrer' },\n })\n if (read.ok === false && read.refusal === 'state-invalid') {\n return plain(400, 'This connection link is not valid. Return to the console and connect the mailbox again.')\n }\n const claims = read.ok ? read.claims : (read as { claims: OutreachOAuthStateClaims }).claims\n const org = await deps.gate.readOrg(claims.orgId)\n const slug = typeof org?.['slug'] === 'string' ? org['slug'] : ''\n if (!slug) return plain(404, 'That organization could not be found.')\n\n let fragment: OutreachConnectReturn\n const providerError = params.get('error')\n const code = params.get('code') ?? ''\n // An error fragment names a Microsoft connect, so the page says whose screen it was.\n const named = claims.provider === 'microsoft' ? { provider: claims.provider } : {}\n if (providerError) {\n fragment = { kind: 'error', reason: providerError === 'access_denied' ? 'access_denied' : 'google_error', ...named }\n } else if (!read.ok) {\n fragment = { kind: 'error', reason: 'expired', ...named }\n } else if (!code || code.length > MAX_CODE_CHARS) {\n fragment = { kind: 'error', reason: 'google_error', ...named }\n } else {\n fragment = { kind: 'code', code, state: params.get('state') ?? '' }\n }\n // A RELATIVE location on the callback's own origin: the path is built from\n // the organization's slug, never from anything the request supplied.\n return new Response(null, {\n status: 303,\n headers: {\n ...noStore,\n 'Referrer-Policy': 'no-referrer',\n Location: `/${encodeURIComponent(slug)}/outreach/mailboxes#${buildConnectReturnFragment(fragment)}`,\n },\n })\n }\n\n const connectComplete: PluginWebApiHandler = async (request) => {\n if (request.method !== 'POST') return methodNotAllowed('POST')\n const body = await readBody(request)\n const gate = await outreachMemberGate(request, body['orgId'], deps.gate)\n if (gate instanceof Response) return gate\n if (!deps.stateSigningConfigured()) return notConfigured()\n if (!deps.readConfig().configured && !readMicrosoftConfig().configured) return notConfigured()\n const code = typeof body['code'] === 'string' ? body['code'] : ''\n if (!code || code.length > MAX_CODE_CHARS) return refusal(400, 'invalid-request', 'The connection did not return a code.')\n\n const firestore = deps.firestore()\n const nowMs = deps.now()\n const read = readOutreachOAuthState(body['state'], nowMs)\n if (read.ok === false && read.refusal === 'state-invalid') {\n return refusal(400, 'state-invalid', 'This connection could not be verified. Connect the mailbox again.')\n }\n const claims = read.ok ? read.claims : (read as { claims: typeof read.claims }).claims\n if (claims.uid !== gate.uid) {\n return refusal(\n 403,\n 'state-user-mismatch',\n 'This connection was started by another member. Sign in as that member, or connect the mailbox again.',\n )\n }\n if (claims.orgId !== gate.orgId) {\n return refusal(400, 'state-org-mismatch', 'This connection was started in another organization.')\n }\n if (!read.ok) return refusal(410, 'state-expired', 'This connection took too long. Connect the mailbox again.')\n if (!providerConfigured(claims.provider)) return notConfigured(claims.provider)\n\n const consumed = await consumeOutreachOAuthState(firestore, { claims, nowMs })\n if (consumed.ok === false) {\n if (consumed.refusal === 'state-expired') {\n return refusal(410, 'state-expired', 'This connection took too long. Connect the mailbox again.')\n }\n return refusal(\n 409,\n consumed.refusal,\n consumed.refusal === 'state-superseded'\n ? 'A newer connection was started. Finish that one, or connect the mailbox again.'\n : 'This connection was already used. Connect the mailbox again.',\n )\n }\n\n const account =\n claims.provider === 'microsoft'\n ? await redeemMicrosoftCode({ code, claims, redirectUri: consumed.redirectUri, nowMs })\n : await redeemGoogleCode({ code, claims, redirectUri: consumed.redirectUri, nowMs })\n if (account instanceof Response) return account\n return storeConnectedMailbox({ gate, body, account, nowMs })\n }\n\n /** Google's half of a connect: the code redeemed, the grant and the account checked. */\n async function redeemGoogleCode(input: {\n code: string\n claims: OutreachOAuthStateClaims\n redirectUri: string\n nowMs: number\n }): Promise<Response | ConnectedAccount> {\n const { code, claims, nowMs } = input\n const config = deps.readConfig()\n if (!config.configured) return notConfigured()\n let grant: GoogleTokenResponse\n try {\n grant = await exchangeGoogleAuthorizationCode(\n {\n clientId: config.config.clientId,\n clientSecret: config.config.clientSecret,\n code,\n redirectUri: input.redirectUri,\n codeVerifier: outreachPkceVerifier(claims.nonce),\n },\n deps.transport,\n )\n } catch (error) {\n if (error instanceof GmailTransportError && error.code === 'invalid_grant') {\n return refusal(400, 'code-rejected', \"Google's sign-in expired or was already used. Connect the mailbox again.\")\n }\n if (error instanceof GmailTransportError && error.code === 'client_misconfigured') {\n return refusal(503, 'not-configured', \"Google refused this deployment's OAuth client.\")\n }\n if (error instanceof GmailTransportError && error.code === 'insufficient_scope') {\n return refusal(\n 422,\n 'scopes-missing',\n 'Sequences needs permission to send and to read your mail. Connect again and allow both.',\n )\n }\n return googleFailure(error, 'connect/complete token exchange')\n }\n if (!grant.refreshToken) {\n return refusal(\n 422,\n 'refresh-token-missing',\n 'Google did not grant offline access, so the mailbox could not send later. Connect it again.',\n )\n }\n if (!grantedScopesInclude(grant.scope, OUTREACH_REQUIRED_GRANTED_SCOPES)) {\n return refusal(\n 422,\n 'scopes-missing',\n 'Sequences needs permission to send and to read your mail. Connect again and allow both.',\n )\n }\n const identity = readGoogleIdToken(grant.idToken, {\n clientId: config.config.clientId,\n nonce: outreachOidcNonce(claims.nonce),\n nowMs,\n })\n if (identity.ok === false) {\n return refusal(\n 422,\n 'identity-unverified',\n identity.refusal === 'email-unverified'\n ? \"Google has not verified this account's email address.\"\n : \"Google's answer could not be verified. Connect the mailbox again.\",\n )\n }\n\n const client = createGmailClient({\n ...deps.transport,\n clientId: config.config.clientId,\n clientSecret: config.config.clientSecret,\n refreshToken: grant.refreshToken,\n })\n let profileEmail: string\n let sendAsOptions: ReturnType<typeof verifiedSendAsAddresses>\n try {\n const [profile, sendAs] = await Promise.all([client.getProfile(), client.listSendAs()])\n profileEmail = profile.emailAddress\n sendAsOptions = verifiedSendAsAddresses(sendAs)\n } catch (error) {\n if (error instanceof GmailTransportError && error.reconnectRequired) {\n return refusal(\n 422,\n 'scopes-missing',\n 'Sequences needs permission to send and to read your mail. Connect again and allow both.',\n )\n }\n return googleFailure(error, 'connect/complete Gmail profile')\n }\n if (profileEmail !== identity.identity.email) {\n return refusal(422, 'account-mismatch', 'The Gmail account and the Google sign-in did not match. Connect again.')\n }\n if (!sendAsOptions.some((option) => option.email === profileEmail)) {\n sendAsOptions = [\n { email: profileEmail, displayName: '', isPrimary: true, isDefault: !sendAsOptions.some((o) => o.isDefault) },\n ...sendAsOptions,\n ]\n }\n\n return {\n provider: 'google',\n providerAccountId: identity.identity.sub,\n email: profileEmail,\n sendAsOptions,\n scopes: grant.scope.split(/\\s+/).filter(Boolean),\n refreshToken: grant.refreshToken,\n keyring: config.config.keyring,\n }\n }\n\n /**\n * Microsoft's half of a connect (AGL-3489): the code redeemed, the grant's\n * permissions checked, the ID token read, and the account read back from\n * Graph — the same account the sign-in named, by its directory id.\n */\n async function redeemMicrosoftCode(input: {\n code: string\n claims: OutreachOAuthStateClaims\n redirectUri: string\n nowMs: number\n }): Promise<Response | ConnectedAccount> {\n const { code, claims, nowMs } = input\n const config = readMicrosoftConfig()\n if (!config.configured) return notConfigured('microsoft')\n const scopesMissing = () =>\n refusal(\n 422,\n 'scopes-missing',\n 'Sequences needs permission to send and to read your mail. Connect again and allow both.',\n )\n let grant: MicrosoftTokenResponse\n try {\n grant = await exchangeMicrosoftAuthorizationCode(\n {\n clientId: config.config.clientId,\n clientSecret: config.config.clientSecret,\n tenant: config.config.tenant,\n code,\n redirectUri: input.redirectUri,\n codeVerifier: outreachPkceVerifier(claims.nonce),\n },\n deps.transport,\n )\n } catch (error) {\n if (error instanceof GmailTransportError && error.code === 'invalid_grant') {\n return refusal(400, 'code-rejected', \"Microsoft's sign-in expired or was already used. Connect the mailbox again.\")\n }\n if (error instanceof GmailTransportError && error.code === 'client_misconfigured') {\n return refusal(503, 'not-configured', \"Microsoft refused this deployment's app registration.\")\n }\n if (error instanceof GmailTransportError && error.code === 'insufficient_scope') return scopesMissing()\n return googleFailure(error, 'connect/complete Microsoft token exchange')\n }\n if (!grant.refreshToken) {\n return refusal(\n 422,\n 'refresh-token-missing',\n 'Microsoft did not grant offline access, so the mailbox could not send later. Connect it again.',\n )\n }\n if (!microsoftScopesInclude(grant.scope)) return scopesMissing()\n const identity = readMicrosoftIdToken(grant.idToken, {\n clientId: config.config.clientId,\n nonce: outreachOidcNonce(claims.nonce),\n nowMs,\n })\n if (identity.ok === false) {\n return refusal(422, 'identity-unverified', \"Microsoft's answer could not be verified. Connect the mailbox again.\")\n }\n const client = createGraphClient({\n ...deps.transport,\n clientId: config.config.clientId,\n clientSecret: config.config.clientSecret,\n tenant: config.config.tenant,\n refreshToken: grant.refreshToken,\n accessToken: { token: grant.accessToken, expiresInSeconds: grant.expiresInSeconds },\n })\n let profile: GraphProfile\n try {\n profile = await client.getProfile()\n } catch (error) {\n if (error instanceof GmailTransportError && error.reconnectRequired) return scopesMissing()\n return googleFailure(error, 'connect/complete Microsoft profile')\n }\n if (profile.id !== identity.identity.oid || !profile.emailAddress) {\n return refusal(\n 422,\n 'account-mismatch',\n 'The Microsoft 365 mailbox and the Microsoft sign-in did not match. Connect again.',\n )\n }\n return {\n provider: 'microsoft',\n providerAccountId: identity.identity.sub,\n email: profile.emailAddress,\n sendAsOptions: [\n { email: profile.emailAddress, displayName: profile.displayName, isPrimary: true, isDefault: true },\n ],\n scopes: grant.scope.split(/\\s+/).filter(Boolean),\n refreshToken: grant.refreshToken,\n keyring: config.config.keyring,\n }\n }\n\n /**\n * The connect's end, whichever provider named the account: the member's\n * mailbox limit, the mailbox (new, or a reconnect that keeps its\n * settings), its sealed grant, the aliases the provider confirmed, and the\n * activity row.\n */\n async function storeConnectedMailbox(input: {\n gate: OutreachGateContext\n body: Record<string, unknown>\n account: ConnectedAccount\n nowMs: number\n }): Promise<Response> {\n const { gate, body, account, nowMs } = input\n const { provider, email: profileEmail, sendAsOptions } = account\n const firestore = deps.firestore()\n const mailboxId = outreachMailboxId(gate.orgId, gate.uid, account.providerAccountId, provider)\n const mailboxDoc = mailboxRef(firestore, gate.orgId, mailboxId)\n const credentialDoc = mailboxCredentialsRef(firestore, mailboxId)\n const [existingMailbox, existingCredential] = await Promise.all([mailboxDoc.get(), credentialDoc.get()])\n const current = readMailbox(mailboxId, existingMailbox.exists ? existingMailbox.data() : undefined)\n if (!current) {\n const mine = await firestore\n .collection('orgs')\n .doc(gate.orgId)\n .collection('outreachMailboxes')\n .where('connectedByUid', '==', gate.uid)\n .limit(OUTREACH_MAX_MAILBOXES_PER_MEMBER)\n .get()\n if (mine.size >= OUTREACH_MAX_MAILBOXES_PER_MEMBER) {\n return refusal(\n 409,\n 'mailbox-limit',\n `You can connect up to ${OUTREACH_MAX_MAILBOXES_PER_MEMBER} mailboxes. Disconnect one before connecting another.`,\n )\n }\n }\n\n const defaultOption = sendAsOptions.find((option) => option.email === defaultSendAs(sendAsOptions, profileEmail))\n let mailbox: OutreachMailbox\n /** On a reconnect, only the fields a connect decides — see the write below. */\n let reconnected: Partial<OutreachMailbox> | null = null\n if (current) {\n const keepSendAs = sendAsOptions.some((option) => option.email === current.sendAs)\n reconnected = {\n provider,\n email: profileEmail,\n sendAs: keepSendAs ? current.sendAs : (defaultOption?.email ?? profileEmail),\n sendAsOptions,\n // A reconnect restores a mailbox the provider had cut off, and leaves a\n // mailbox its member paused paused.\n status: (current.status === 'paused' ? 'paused' : 'connected') satisfies OutreachMailboxStatus,\n connectedAtMs: nowMs,\n updatedAtMs: nowMs,\n }\n mailbox = { ...current, ...reconnected }\n } else {\n const timezone = isValidTimezone(body['timezone']) ? String(body['timezone']) : 'UTC'\n const displayName = validateDisplayName(defaultOption?.displayName || gate.name || '')\n mailbox = {\n id: mailboxId,\n provider,\n email: profileEmail,\n sendAs: defaultOption?.email ?? profileEmail,\n sendAsOptions,\n displayName: typeof displayName === 'string' ? displayName : '',\n status: 'connected',\n dailyCap: OUTREACH_DEFAULT_DAILY_CAP,\n window: { ...OUTREACH_DEFAULT_WINDOW, days: [...OUTREACH_DEFAULT_WINDOW.days] },\n timezone,\n rampStartedAtMs: nowMs,\n health: {\n sentToday: 0,\n sentOnDay: null,\n bounces: 0,\n replies: 0,\n lastSentAtMs: null,\n lastErrorAtMs: null,\n lastErrorCode: null,\n daily: {},\n },\n connectedByUid: gate.uid,\n connectedAtMs: nowMs,\n createdAtMs: nowMs,\n updatedAtMs: nowMs,\n }\n }\n const credential: OutreachStoredMailboxCredentials = {\n id: mailboxId,\n orgId: gate.orgId,\n mailboxId,\n provider,\n connectedByUid: gate.uid,\n providerAccountId: account.providerAccountId,\n email: profileEmail,\n scopes: account.scopes,\n ...sealMailboxRefreshToken(account.refreshToken, mailboxId, account.keyring),\n createdAtMs: Number(existingCredential.exists ? existingCredential.get('createdAtMs') : 0) || nowMs,\n updatedAtMs: nowMs,\n }\n const batch = firestore.batch()\n // A reconnect MERGES only what a connect decides, so the settings a member\n // chose and the health counters the sending runtime increments are never\n // written back from a read that may already be stale.\n if (reconnected) batch.set(mailboxDoc, reconnected, { merge: true })\n else batch.set(mailboxDoc, mailbox)\n batch.set(credentialDoc, credential)\n await batch.commit()\n\n const aliases: { ok: boolean; confirmed?: string[] } = await deps\n .confirmAliasesByProvider(firestore, {\n orgId: gate.orgId,\n uid: gate.uid,\n addresses: sendAsOptions.map((option) => option.email),\n nowMs,\n })\n .catch((error: unknown) => {\n console.error('[outreach] confirming member aliases from send-as failed', error)\n return { ok: false }\n })\n await deps.logOrgActivity(\n gate.orgId,\n { uid: gate.uid, email: gate.email },\n current ? 'Reconnected a mailbox in Sequences' : 'Connected a mailbox in Sequences',\n { type: OUTREACH_MAILBOX_ACTIVITY_TARGET, id: mailboxId, name: activityName(mailbox) },\n )\n return ok({\n ok: true,\n mailbox,\n created: !current,\n confirmedAliases: aliases.ok ? (aliases.confirmed ?? []) : [],\n })\n }\n\n const settings: PluginWebApiHandler = async (request) => {\n if (request.method !== 'POST') return methodNotAllowed('POST')\n const body = await readBody(request)\n const loaded = await loadManagedMailbox(request, body, 'member-or-admin')\n if (loaded instanceof Response) return loaded\n const { gate, mailbox } = loaded\n const update: Partial<OutreachMailbox> = {}\n const invalid = (message: string) => refusal(400, 'invalid-settings', message)\n\n if (body['sendAs'] !== undefined) {\n const sendAs = typeof body['sendAs'] === 'string' ? body['sendAs'].trim().toLowerCase() : ''\n if (!(mailbox.sendAsOptions ?? []).some((option) => option.email === sendAs)) {\n return invalid('Choose one of the addresses the provider has verified for this account.')\n }\n update.sendAs = sendAs\n }\n if (body['displayName'] !== undefined) {\n const name = validateDisplayName(body['displayName'])\n if (typeof name !== 'string') return invalid(name.message)\n update.displayName = name\n }\n if (body['dailyCap'] !== undefined) {\n const cap = validateDailyCap(body['dailyCap'])\n if (typeof cap !== 'number') return invalid(cap.message)\n update.dailyCap = cap\n }\n if (body['window'] !== undefined) {\n const window = validateSendWindow(body['window'])\n if (!('days' in window)) return invalid(window.message)\n update.window = window\n }\n if (body['timezone'] !== undefined) {\n if (!isValidTimezone(body['timezone'])) return invalid('Choose a timezone from the list.')\n update.timezone = body['timezone']\n }\n if (body['warmUp'] !== undefined) {\n /*\n * The ramp guards a NEW sender's reputation; a mailbox that has sent\n * mail for years has one already, and ramping it to ten a day guards\n * nothing (AGL-3228). Its member decides. Turning the ramp back on\n * starts a fresh one from today, which is what \"warm up\" means.\n */\n if (typeof body['warmUp'] !== 'boolean') return invalid('Say whether to warm the mailbox up gradually.')\n const running = typeof mailbox.rampStartedAtMs === 'number'\n if (body['warmUp'] && !running) update.rampStartedAtMs = deps.now()\n if (!body['warmUp'] && running) update.rampStartedAtMs = null\n }\n if (!Object.keys(update).length) return ok({ ok: true, mailbox })\n const nowMs = deps.now()\n await mailboxRef(deps.firestore(), gate.orgId, mailbox.id).update({ ...update, updatedAtMs: nowMs })\n return ok({ ok: true, mailbox: { ...mailbox, ...update, updatedAtMs: nowMs } })\n }\n\n const status: PluginWebApiHandler = async (request) => {\n if (request.method !== 'POST') return methodNotAllowed('POST')\n const body = await readBody(request)\n if (typeof body['paused'] !== 'boolean') return refusal(400, 'invalid-request', 'Say whether to pause the mailbox.')\n const loaded = await loadManagedMailbox(request, body, 'member-or-admin')\n if (loaded instanceof Response) return loaded\n const { gate, mailbox } = loaded\n if (mailbox.status === 'reconnect_required' || mailbox.status === 'disconnected') {\n return refusal(409, 'reconnect-required', 'Reconnect this mailbox before pausing or resuming it.')\n }\n const next: OutreachMailboxStatus = body['paused'] ? 'paused' : 'connected'\n if (mailbox.status === next) return ok({ ok: true, mailbox })\n const nowMs = deps.now()\n // A member's pause or resume answers an automatic pause (AGL-2981): its\n // reason goes, and the next bounce is judged as new evidence.\n await mailboxRef(deps.firestore(), gate.orgId, mailbox.id).update({\n status: next,\n autoPause: null,\n updatedAtMs: nowMs,\n })\n await deps.logOrgActivity(\n gate.orgId,\n { uid: gate.uid, email: gate.email },\n next === 'paused' ? 'Paused a mailbox in Sequences' : 'Resumed a mailbox in Sequences',\n { type: OUTREACH_MAILBOX_ACTIVITY_TARGET, id: mailbox.id, name: activityName(mailbox) },\n )\n return ok({ ok: true, mailbox: { ...mailbox, status: next, autoPause: null, updatedAtMs: nowMs } })\n }\n\n const test: PluginWebApiHandler = async (request) => {\n if (request.method !== 'POST') return methodNotAllowed('POST')\n const body = await readBody(request)\n const loaded = await loadManagedMailbox(request, body, 'member')\n if (loaded instanceof Response) return loaded\n const { gate, mailbox } = loaded\n if (mailbox.status === 'reconnect_required' || mailbox.status === 'disconnected') {\n return refusal(409, 'reconnect-required', 'Reconnect this mailbox before sending from it.')\n }\n const provider: OutreachMailboxProvider = mailbox.provider === 'microsoft' ? 'microsoft' : 'google'\n if (!providerConfigured(provider)) return notConfigured(provider)\n const limited = await deps.consumeRateLimit(`outreach-mailbox-test:${mailbox.id}`, {\n limit: OUTREACH_TEST_SENDS_PER_HOUR,\n windowMs: 60 * 60 * 1000,\n })\n if (!limited.allowed) {\n return refusal(429, 'rate-limited', `A mailbox can send ${OUTREACH_TEST_SENDS_PER_HOUR} tests an hour. Try again later.`)\n }\n /*\n * To the member's own address unless they name another (AGL-3228). A\n * test to oneself never leaves the provider, so it arrives with no\n * Authentication-Results at all and cannot show whether the send-as\n * domain's DKIM and DMARC hold; an outside mailbox the member can read\n * is the only place that can be seen. The rate limit above is the\n * whole guard on who may be written to — it is the member's own\n * account sending, as it could from its own compose window.\n */\n const named = body['to']\n const to =\n named === undefined || named === null || String(named).trim() === ''\n ? mailbox.email\n : normalizeContactEmail(String(named))\n if (!to) {\n return refusal(400, 'invalid-request', `\"${String(named).trim()}\" isn't a valid email address.`)\n }\n const firestore = deps.firestore()\n const nowMs = deps.now()\n const opened = await openOutreachMailboxClient(\n firestore,\n { mailboxId: mailbox.id },\n { ...deps.transport, readConfig: deps.readConfig, readMicrosoftConfig, now: deps.now },\n )\n if (opened.ok === false) {\n if (opened.reason === 'not-configured') return notConfigured(provider)\n await markOutreachMailboxReconnectRequired(firestore, {\n orgId: gate.orgId,\n mailboxId: mailbox.id,\n errorCode: opened.reason,\n nowMs,\n })\n return refusal(409, 'reconnect-required', 'This mailbox needs to be connected again before it can send.')\n }\n try {\n const sent = await sendOutreachMessage(opened.client, {\n from: { address: mailbox.sendAs, name: mailbox.displayName },\n to,\n subject: 'Sequences test message',\n text: [\n 'This is a test message from Sequences.',\n '',\n `It was sent through the connected mailbox ${mailbox.email} as ${mailbox.sendAs}. ` +\n 'If it reached the inbox, this mailbox can send.',\n ...(to === mailbox.email\n ? []\n : [\n '',\n 'To read whether the sender is authenticated, open this message\\u2019s original source ' +\n 'and look for dkim=pass, spf=pass and dmarc=pass in Authentication-Results.',\n ]),\n ].join('\\n'),\n })\n return ok({ ok: true, sentTo: to, gmailMessageId: sent.gmailMessageId, sentAtMs: nowMs })\n } catch (error) {\n if (error instanceof GmailTransportError && error.reconnectRequired) {\n await markOutreachMailboxReconnectRequired(firestore, {\n orgId: gate.orgId,\n mailboxId: mailbox.id,\n errorCode: error.code,\n nowMs,\n })\n return refusal(\n 409,\n 'reconnect-required',\n `${providerName(provider)} refused this mailbox’s access. Connect it again.`,\n )\n }\n if (error instanceof Rfc5322MessageError) {\n return refusal(400, 'invalid-settings', `The test could not be written: ${error.message}`)\n }\n return googleFailure(error, 'test send')\n }\n }\n\n const disconnect: PluginWebApiHandler = async (request) => {\n if (request.method !== 'POST') return methodNotAllowed('POST')\n const body = await readBody(request)\n const loaded = await loadManagedMailbox(request, body, 'member-or-admin')\n if (loaded instanceof Response) return loaded\n const { gate, mailbox } = loaded\n const firestore = deps.firestore()\n const credentialDoc = mailboxCredentialsRef(firestore, mailbox.id)\n const snapshot = await credentialDoc.get()\n const credential = readMailboxCredentials(snapshot.exists ? snapshot.data() : null)\n const revocation = credential\n ? await revokeMailboxGrant(firestore, credential, deps)\n : ('already-invalid' as const)\n const batch = firestore.batch()\n batch.delete(credentialDoc)\n batch.delete(mailboxRef(firestore, gate.orgId, mailbox.id))\n await batch.commit()\n await deps.logOrgActivity(\n gate.orgId,\n { uid: gate.uid, email: gate.email },\n 'Disconnected a mailbox in Sequences',\n { type: OUTREACH_MAILBOX_ACTIVITY_TARGET, id: mailbox.id, name: activityName(mailbox) },\n )\n return ok({ ok: true, revocation } satisfies OutreachMailboxDisconnectResponse)\n }\n\n /**\n * How receivers judge mail from the address a mailbox sends as. Any member\n * who can see the mailbox can read it: it is a reading of public DNS about\n * the organization's own domain, and changes nothing.\n */\n const readiness: PluginWebApiHandler = async (request) => {\n if (request.method !== 'POST') return methodNotAllowed('POST')\n const body = await readBody(request)\n const gate = await outreachMemberGate(request, body['orgId'], deps.gate)\n if (gate instanceof Response) return gate\n const mailboxId = typeof body['mailboxId'] === 'string' ? body['mailboxId'] : ''\n if (!MAILBOX_ID.test(mailboxId)) return refusal(400, 'invalid-request', 'Name the mailbox.')\n const snapshot = await mailboxRef(deps.firestore(), gate.orgId, mailboxId).get()\n const mailbox = readMailbox(mailboxId, snapshot.exists ? snapshot.data() : undefined)\n if (!mailbox) return refusal(404, 'mailbox-not-found', 'That mailbox is not connected to this organization.')\n const sendAs = mailbox.sendAs || mailbox.email\n const expectation =\n mailbox.provider === 'microsoft'\n ? microsoftMailboxSenderExpectation(sendAs)\n : googleMailboxSenderExpectation(sendAs)\n const read = expectation\n ? await deps.readSenderReadiness(expectation, { fresh: body['fresh'] === true }).catch(() => null)\n : null\n return ok({ ok: true, sendAs, readiness: read } satisfies OutreachMailboxReadinessResponse)\n }\n\n return { availability, connect, oauthCallback, connectComplete, settings, status, test, disconnect, readiness }\n}\n\n/** A Google failure the route could not handle itself, as the refusal {@link googleFailureAnswer} decides. */\nfunction googleFailure(error: unknown, route: string): Response {\n const answer = googleFailureAnswer(error, route)\n return refusal(answer.status, answer.reason, answer.error)\n}\n"],"names":["normalizeContactEmail","googleMailboxSenderExpectation","microsoftMailboxSenderExpectation","OUTREACH_MAILBOX_PROVIDERS","createGmailClient","createGraphClient","GmailTransportError","googleFailureAnswer","buildGoogleAuthorizationUrl","exchangeGoogleAuthorizationCode","grantedScopesInclude","OUTREACH_REQUIRED_GRANTED_SCOPES","pkceChallenge","readGoogleIdToken","buildMicrosoftAuthorizationUrl","exchangeMicrosoftAuthorizationCode","microsoftScopesInclude","readMicrosoftIdToken","Rfc5322MessageError","sendOutreachMessage","buildConnectReturnFragment","mailboxCredentialsRef","mailboxRef","outreachMailboxId","readMailboxCredentials","sealMailboxRefreshToken","revokeMailboxGrant","outreachMemberGate","refusal","defaultSendAs","isValidTimezone","OUTREACH_DEFAULT_DAILY_CAP","OUTREACH_DEFAULT_WINDOW","OUTREACH_MAX_MAILBOXES_PER_MEMBER","validateDailyCap","validateDisplayName","validateSendWindow","verifiedSendAsAddresses","markOutreachMailboxReconnectRequired","openOutreachMailboxClient","consumeOutreachOAuthState","mintOutreachOAuthState","outreachOidcNonce","outreachPkceVerifier","readOutreachOAuthState","recordOutreachOAuthState","outreachNotConfiguredMessage","readOutreachMicrosoftConfig","OUTREACH_TEST_SENDS_PER_HOUR","OUTREACH_MAILBOX_ACTIVITY_TARGET","MAILBOX_ID","MAX_CODE_CHARS","noStore","ok","body","Response","json","status","headers","methodNotAllowed","allow","error","reason","Allow","readBody","request","catch","Array","isArray","notConfigured","provider","readProvider","value","undefined","includes","providerName","readMailbox","id","data","activityName","mailbox","email","createOutreachMailboxRoutes","deps","readMicrosoftConfig","providerConfigured","configured","readConfig","loadManagedMailbox","who","gate","mailboxId","test","snapshot","firestore","orgId","get","exists","own","connectedByUid","uid","isOrgAdmin","availability","method","URL","url","searchParams","missing","config","microsoft","push","shared","stateSigningConfigured","Boolean","redirectUri","providers","google","canManageAll","length","connect","nowMs","now","state","claims","clientId","tenant","codeChallenge","nonce","loginHint","oauthCallback","params","read","plain","text","org","readOrg","slug","fragment","providerError","code","named","kind","Location","encodeURIComponent","connectComplete","consumed","account","redeemMicrosoftCode","redeemGoogleCode","storeConnectedMailbox","input","grant","clientSecret","codeVerifier","transport","googleFailure","refreshToken","scope","identity","idToken","client","profileEmail","sendAsOptions","profile","sendAs","Promise","all","getProfile","listSendAs","emailAddress","reconnectRequired","some","option","displayName","isPrimary","isDefault","o","providerAccountId","sub","scopes","split","filter","keyring","scopesMissing","accessToken","token","expiresInSeconds","oid","aliases","mailboxDoc","credentialDoc","existingMailbox","existingCredential","current","mine","collection","doc","where","limit","size","defaultOption","find","reconnected","keepSendAs","connectedAtMs","updatedAtMs","timezone","String","name","dailyCap","window","days","rampStartedAtMs","health","sentToday","sentOnDay","bounces","replies","lastSentAtMs","lastErrorAtMs","lastErrorCode","daily","createdAtMs","credential","Number","batch","set","merge","commit","confirmAliasesByProvider","addresses","map","console","logOrgActivity","type","created","confirmedAliases","confirmed","settings","loaded","update","invalid","message","trim","toLowerCase","cap","running","Object","keys","next","autoPause","limited","consumeRateLimit","windowMs","allowed","to","opened","errorCode","sent","from","address","subject","join","sentTo","gmailMessageId","sentAtMs","disconnect","revocation","delete","readiness","expectation","readSenderReadiness","fresh","route","answer"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,qBAAqB,QAAQ,kCAAiC;AAEvE,SACEC,8BAA8B,EAC9BC,iCAAiC,QAG5B,2BAA0B;AAEjC,SACEC,0BAA0B,QAKrB,6BAAyB;AAChC,SAASC,iBAAiB,QAAQ,+BAA2B;AAC7D,SAASC,iBAAiB,QAA2B,+BAA2B;AAChF,SAASC,mBAAmB,EAAEC,mBAAmB,QAAQ,+BAA2B;AACpF,SACEC,2BAA2B,EAC3BC,+BAA+B,EAC/BC,oBAAoB,EACpBC,gCAAgC,EAChCC,aAAa,EACbC,iBAAiB,QAEZ,+BAA2B;AAElC,SACEC,8BAA8B,EAC9BC,kCAAkC,EAClCC,sBAAsB,EACtBC,oBAAoB,QAEf,kCAA8B;AACrC,SAASC,mBAAmB,QAAQ,0BAAsB;AAC1D,SAASC,mBAAmB,QAAQ,+BAA2B;AAC/D,SACEC,0BAA0B,QAOrB,mBAAe;AACtB,SACEC,qBAAqB,EACrBC,U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,KAAK,mBAAmB;QACxE,MAAMiE,WAAW,MAAMvE,WAAW6D,KAAKW,SAAS,IAAIJ,KAAKK,KAAK,EAAEJ,WAAWK,GAAG;QAC9E,MAAMhB,UAAUJ,YAAYe,WAAWE,SAASI,MAAM,GAAGJ,SAASf,IAAI,KAAKL;QAC3E,IAAI,CAACO,SAAS,OAAOpD,QAAQ,KAAK,qBAAqB;QACvD,MAAMwI,SAASpF,QAAQoF,MAAM,IAAIpF,QAAQC,KAAK;QAC9C,MAAM6L,cACJ9L,QAAQV,QAAQ,KAAK,cACjBpE,kCAAkCkK,UAClCnK,+BAA+BmK;QACrC,MAAMjC,OAAO2I,cACT,MAAM3L,KAAK4L,mBAAmB,CAACD,aAAa;YAAEE,OAAO1N,IAAI,CAAC,QAAQ,KAAK;QAAK,GAAGY,KAAK,CAAC,IAAM,QAC3F;QACJ,OAAOb,GAAG;YAAEA,IAAI;YAAM+G;YAAQyG,WAAW1I;QAAK;IAChD;IAEA,OAAO;QAAE7B;QAAciB;QAASU;QAAee;QAAiB8F;QAAUrL;QAAQmC;QAAM8K;QAAYG;IAAU;AAChH;AAEA,4GAA4G,GAC5G,SAASlH,cAAc9F,KAAc,EAAEoN,KAAa;IAClD,MAAMC,SAAS3Q,oBAAoBsD,OAAOoN;IAC1C,OAAOrP,QAAQsP,OAAOzN,MAAM,EAAEyN,OAAOpN,MAAM,EAAEoN,OAAOrN,KAAK;AAC3D"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/mailboxes/mailbox-routes.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { normalizeContactEmail } from '@aglyn/aglyn/app-utils/contacts'\nimport type { PluginWebApiHandler } from '@aglyn/aglyn/server'\nimport {\n googleMailboxSenderExpectation,\n microsoftMailboxSenderExpectation,\n type SenderReadiness,\n type SenderReadinessExpectation,\n} from '@aglyn/shared-util-email'\nimport type { SecretBoxKeyring } from '@aglyn/shared-util-tools/secret-box'\nimport {\n OUTREACH_MAILBOX_PROVIDERS,\n type OutreachMailbox,\n type OutreachMailboxProvider,\n type OutreachMailboxStatus,\n type OutreachSendAsAddress,\n} from '../model/outreach.types'\nimport { createGmailClient } from '../transport/gmail-client'\nimport { createGraphClient, type GraphProfile } from '../transport/graph-client'\nimport { GmailTransportError, googleFailureAnswer } from '../transport/gmail-errors'\nimport {\n buildGoogleAuthorizationUrl,\n exchangeGoogleAuthorizationCode,\n grantedScopesInclude,\n OUTREACH_REQUIRED_GRANTED_SCOPES,\n pkceChallenge,\n readGoogleIdToken,\n type GoogleTokenResponse,\n} from '../transport/google-oauth'\nimport type { TransportDeps } from '../transport/http'\nimport {\n buildMicrosoftAuthorizationUrl,\n exchangeMicrosoftAuthorizationCode,\n microsoftScopesInclude,\n readMicrosoftIdToken,\n type MicrosoftTokenResponse,\n} from '../transport/microsoft-oauth'\nimport { Rfc5322MessageError } from '../transport/rfc5322'\nimport { sendOutreachMessage } from '../transport/send-message'\nimport {\n buildConnectReturnFragment,\n type OutreachApiRefusalReason,\n type OutreachConnectReturn,\n type OutreachMailboxAvailability,\n type OutreachMailboxAvailabilityGate,\n type OutreachMailboxDisconnectResponse,\n type OutreachMailboxReadinessResponse,\n} from './mailbox-api'\nimport {\n mailboxCredentialsRef,\n mailboxRef,\n outreachMailboxId,\n readMailboxCredentials,\n sealMailboxRefreshToken,\n type OutreachStoredMailboxCredentials,\n} from './mailbox-credentials'\nimport { revokeMailboxGrant } from './mailbox-revoke'\nimport {\n outreachMemberGate,\n refusal,\n type OutreachGateContext,\n type OutreachGateDeps,\n} from './mailbox-gate'\nimport {\n defaultSendAs,\n isValidTimezone,\n OUTREACH_DEFAULT_DAILY_CAP,\n OUTREACH_DEFAULT_WINDOW,\n OUTREACH_MAX_MAILBOXES_PER_MEMBER,\n validateDailyCap,\n validateDisplayName,\n validateSendWindow,\n verifiedSendAsAddresses,\n} from './mailbox-settings'\nimport {\n markOutreachMailboxReconnectRequired,\n openOutreachMailboxClient,\n} from './mailbox-transport'\nimport {\n consumeOutreachOAuthState,\n mintOutreachOAuthState,\n outreachOidcNonce,\n outreachPkceVerifier,\n readOutreachOAuthState,\n recordOutreachOAuthState,\n type OutreachOAuthStateClaims,\n} from './oauth-state'\nimport {\n outreachNotConfiguredMessage,\n readOutreachMicrosoftConfig,\n type OutreachGoogleConfigResult,\n type OutreachMicrosoftConfigResult,\n} from './outreach-config'\n\n/**\n * THE MAILBOX ROUTES (AGL-2978): connect a rep's Google or Microsoft 365\n * mailbox, keep its settings, pause it, test it, and disconnect it.\n *\n * A connect names its provider (AGL-3489). Both providers' consent screens\n * return to the one callback; the signed state says which one a connect went\n * to, and `connect/complete` redeems the code with that provider. Everything\n * after the provider has named the account — the mailbox limit, the mailbox\n * and its sealed grant, the activity row — is the same for both.\n *\n * ## The connect, end to end\n *\n * 1. `connect` (the member's session) mints a signed, single-use state bound\n * to the member and the organization, records its pending entry, and\n * answers Google's consent address — offline access, the consent prompt,\n * a PKCE challenge and an OpenID nonce, both derived from the state.\n * 2. Google redirects the browser to `oauth/callback`. That request carries\n * no bearer token, so it DOES nothing: it verifies the state's signature,\n * finds the organization's console path, and redirects to the Mailboxes\n * page with the code in the URL FRAGMENT, where no server and no `Referer`\n * sees it. Its release gate was asked about the organization and the\n * member the state names (the route's declared subject).\n * 3. The page takes the code out of the address bar and posts it to\n * `connect/complete` with the member's own session. That is where the\n * state is consumed, where it is refused if it was minted for anyone else,\n * and where the code is exchanged. So a consent screen someone else was\n * tricked into completing cannot connect THEIR mailbox to the member who\n * started it: the code arrives in the wrong browser, whose session is not\n * the state's member.\n *\n * ## Refusals, in order, on `connect/complete`\n *\n * A state that is invalid, minted for another member or organization,\n * expired, already used or superseded; a code Google refuses; a grant with no\n * refresh token; a grant missing `gmail.send` or `gmail.readonly` (the consent\n * screen lets a person untick them); an ID token that is not about this\n * exchange or whose address Google has not verified; an account with no Gmail\n * service (a Workspace user whose Gmail is off, or not yet provisioned) or one\n * Google bars from the Gmail API; a Gmail profile whose address is not the ID\n * token's; and a member at their mailbox limit. Each is a 4xx: only a Google\n * outage, or a request Google calls malformed, answers 502.\n *\n * A grant refused after the code exchange is dropped, not revoked. Google's\n * revocation ends the whole grant this client holds for the account, and the\n * same account may already be connected — by this member in another\n * organization, or by a teammate — so revoking a token this route merely\n * declines to keep could disconnect a mailbox that is working.\n *\n * ## Who may do what\n *\n * Every route but the callback climbs `outreachMemberGate`. The member who\n * connected a mailbox manages it; an organization owner or admin may also\n * change its settings, pause it and disconnect it — a departing rep's mailbox\n * has to be stoppable by somebody. Only its own member can send a test from\n * it, since the test lands in their inbox.\n */\n\nexport interface OutreachMailboxRouteDeps {\n firestore(): FirebaseFirestore.Firestore\n gate: OutreachGateDeps\n readConfig(): OutreachGoogleConfigResult\n /** The Microsoft app registration (AGL-3489); the environment's when omitted. */\n readMicrosoftConfig?(): OutreachMicrosoftConfigResult\n /** Whether the signing secret the OAuth state needs is configured. */\n stateSigningConfigured(): boolean\n redirectUri(requestUrl: string): string | null\n now(): number\n /** The network and retry policy every Google call uses. */\n transport: TransportDeps\n consumeRateLimit(key: string, options: { limit: number; windowMs: number }): Promise<{ allowed: boolean }>\n logOrgActivity(\n orgId: string,\n actor: { uid: string; email?: string | null },\n action: string,\n target: { type: typeof OUTREACH_MAILBOX_ACTIVITY_TARGET; id: string; name: string },\n ): Promise<void>\n confirmAliasesByProvider(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; uid: string; addresses: readonly string[]; nowMs: number },\n ): Promise<{ ok: boolean; confirmed?: string[] }>\n /** SPF, DKIM and DMARC for one sender, looked up and briefly remembered. */\n readSenderReadiness(expectation: SenderReadinessExpectation, options: { fresh?: boolean }): Promise<SenderReadiness>\n}\n\nexport interface OutreachMailboxRoutes {\n availability: PluginWebApiHandler\n connect: PluginWebApiHandler\n oauthCallback: PluginWebApiHandler\n connectComplete: PluginWebApiHandler\n settings: PluginWebApiHandler\n status: PluginWebApiHandler\n test: PluginWebApiHandler\n disconnect: PluginWebApiHandler\n readiness: PluginWebApiHandler\n}\n\n/** Test sends one mailbox may make in an hour. */\nexport const OUTREACH_TEST_SENDS_PER_HOUR = 5\n\n/**\n * The org activity target a mailbox's rows are filed under: Outreach's own\n * namespaced resource, which the feed reads as \"Mailbox\".\n */\nexport const OUTREACH_MAILBOX_ACTIVITY_TARGET = 'outreach:mailbox'\n\nconst MAILBOX_ID = /^[A-Za-z0-9_-]{1,128}$/\nconst MAX_CODE_CHARS = 2048\n\nconst noStore = { 'Cache-Control': 'no-store' }\n\nconst ok = (body: unknown) => Response.json(body, { status: 200, headers: noStore })\n\nfunction methodNotAllowed(allow: string): Response {\n return Response.json(\n { error: 'Method not allowed', reason: 'method-not-allowed' satisfies OutreachApiRefusalReason },\n { status: 405, headers: { ...noStore, Allow: allow } },\n )\n}\n\nasync function readBody(request: Request): Promise<Record<string, unknown>> {\n const body = await request.json().catch(() => null)\n return body && typeof body === 'object' && !Array.isArray(body) ? (body as Record<string, unknown>) : {}\n}\n\nfunction notConfigured(provider: OutreachMailboxProvider = 'google'): Response {\n return refusal(503, 'not-configured', outreachNotConfiguredMessage(provider))\n}\n\n/** The provider a request names; Google when it names none, `null` for one that is not a provider. */\nfunction readProvider(value: unknown): OutreachMailboxProvider | null {\n if (value === undefined || value === null || value === '') return 'google'\n return (OUTREACH_MAILBOX_PROVIDERS as readonly unknown[]).includes(value) ? (value as OutreachMailboxProvider) : null\n}\n\nconst providerName = (provider: OutreachMailboxProvider) => (provider === 'microsoft' ? 'Microsoft' : 'Google')\n\n/** What a provider's sign-in established about the account a connect is for. */\ninterface ConnectedAccount {\n provider: OutreachMailboxProvider\n providerAccountId: string\n email: string\n sendAsOptions: OutreachSendAsAddress[]\n scopes: string[]\n refreshToken: string\n keyring: SecretBoxKeyring\n}\n\n/** A mailbox document read defensively into the model shape. */\nfunction readMailbox(id: string, data: Record<string, unknown> | undefined): OutreachMailbox | null {\n if (!data) return null\n return { ...(data as unknown as OutreachMailbox), id }\n}\n\nconst activityName = (mailbox: Pick<OutreachMailbox, 'email'>) => mailbox.email\n\nexport function createOutreachMailboxRoutes(deps: OutreachMailboxRouteDeps): OutreachMailboxRoutes {\n const readMicrosoftConfig = () => (deps.readMicrosoftConfig ?? readOutreachMicrosoftConfig)()\n /** Whether a provider's client and the token key are configured here. */\n const providerConfigured = (provider: OutreachMailboxProvider) =>\n provider === 'microsoft' ? readMicrosoftConfig().configured : deps.readConfig().configured\n\n /** The gate, then the mailbox the body names, then who may touch it. */\n async function loadManagedMailbox(\n request: Request,\n body: Record<string, unknown>,\n who: 'member-or-admin' | 'member',\n ): Promise<Response | { gate: OutreachGateContext; mailbox: OutreachMailbox }> {\n const gate = await outreachMemberGate(request, body['orgId'], deps.gate)\n if (gate instanceof Response) return gate\n const mailboxId = typeof body['mailboxId'] === 'string' ? body['mailboxId'] : ''\n if (!MAILBOX_ID.test(mailboxId)) return refusal(400, 'invalid-request', 'Name the mailbox.')\n const snapshot = await mailboxRef(deps.firestore(), gate.orgId, mailboxId).get()\n const mailbox = readMailbox(mailboxId, snapshot.exists ? snapshot.data() : undefined)\n if (!mailbox) return refusal(404, 'mailbox-not-found', 'That mailbox is not connected to this organization.')\n const own = mailbox.connectedByUid === gate.uid\n if (!own && !(who === 'member-or-admin' && gate.isOrgAdmin)) {\n return refusal(\n 403,\n 'not-your-mailbox',\n who === 'member'\n ? 'Only the member who connected this mailbox can do that.'\n : 'Only the member who connected this mailbox, or a member holding \"Manage everyone’s Sequences\", can change it.',\n )\n }\n return { gate, mailbox }\n }\n\n const availability: PluginWebApiHandler = async (request) => {\n if (request.method !== 'GET') return methodNotAllowed('GET')\n const gate = await outreachMemberGate(request, new URL(request.url).searchParams.get('orgId'), deps.gate)\n if (gate instanceof Response) return gate\n // Every gate is named, not the first: an operator fixing a deployment\n // should see the whole list once rather than one variable per redeploy.\n const missing: OutreachMailboxAvailabilityGate[] = []\n const config = deps.readConfig()\n const microsoft = readMicrosoftConfig()\n if (config.configured === false) missing.push({ gate: 'google', missing: config.missing })\n if (microsoft.configured === false) missing.push({ gate: 'microsoft', missing: microsoft.missing })\n const shared = deps.stateSigningConfigured() && Boolean(deps.redirectUri(request.url))\n if (!deps.stateSigningConfigured()) missing.push({ gate: 'state' })\n if (!deps.redirectUri(request.url)) missing.push({ gate: 'redirect' })\n const providers = { google: shared && config.configured, microsoft: shared && microsoft.configured }\n return ok({\n // Google's readiness, as this field has always meant; `providers` says each.\n configured: providers.google,\n providers,\n canManageAll: gate.isOrgAdmin,\n ...(missing.length ? { missing } : {}),\n } satisfies OutreachMailboxAvailability)\n }\n\n const connect: PluginWebApiHandler = async (request) => {\n if (request.method !== 'POST') return methodNotAllowed('POST')\n const body = await readBody(request)\n const gate = await outreachMemberGate(request, body['orgId'], deps.gate)\n if (gate instanceof Response) return gate\n const provider = readProvider(body['provider'])\n if (!provider) return refusal(400, 'invalid-request', 'Choose Google or Microsoft.')\n const redirectUri = deps.redirectUri(request.url)\n if (!redirectUri || !deps.stateSigningConfigured()) return notConfigured(provider)\n\n if (provider === 'microsoft') {\n const microsoft = readMicrosoftConfig()\n if (!microsoft.configured) return notConfigured(provider)\n const nowMs = deps.now()\n const { state, claims } = mintOutreachOAuthState({ orgId: gate.orgId, uid: gate.uid, nowMs, provider })\n await recordOutreachOAuthState(deps.firestore(), { claims, redirectUri, nowMs })\n const url = buildMicrosoftAuthorizationUrl({\n clientId: microsoft.config.clientId,\n tenant: microsoft.config.tenant,\n redirectUri,\n state,\n codeChallenge: pkceChallenge(outreachPkceVerifier(claims.nonce)),\n nonce: outreachOidcNonce(claims.nonce),\n loginHint: typeof body['loginHint'] === 'string' ? normalizeContactEmail(body['loginHint']) : null,\n })\n return ok({ url })\n }\n\n const config = deps.readConfig()\n if (!config.configured) return notConfigured()\n const nowMs = deps.now()\n const { state, claims } = mintOutreachOAuthState({ orgId: gate.orgId, uid: gate.uid, nowMs })\n await recordOutreachOAuthState(deps.firestore(), { claims, redirectUri, nowMs })\n const url = buildGoogleAuthorizationUrl({\n clientId: config.config.clientId,\n redirectUri,\n state,\n codeChallenge: pkceChallenge(outreachPkceVerifier(claims.nonce)),\n nonce: outreachOidcNonce(claims.nonce),\n loginHint: gate.email,\n })\n return ok({ url })\n }\n\n const oauthCallback: PluginWebApiHandler = async (request) => {\n if (request.method !== 'GET') return methodNotAllowed('GET')\n const params = new URL(request.url).searchParams\n const read = readOutreachOAuthState(params.get('state'), deps.now())\n const plain = (status: number, text: string) =>\n new Response(text, {\n status,\n headers: { ...noStore, 'Content-Type': 'text/plain; charset=utf-8', 'Referrer-Policy': 'no-referrer' },\n })\n if (read.ok === false && read.refusal === 'state-invalid') {\n return plain(400, 'This connection link is not valid. Return to the console and connect the mailbox again.')\n }\n const claims = read.ok ? read.claims : (read as { claims: OutreachOAuthStateClaims }).claims\n const org = await deps.gate.readOrg(claims.orgId)\n const slug = typeof org?.['slug'] === 'string' ? org['slug'] : ''\n if (!slug) return plain(404, 'That organization could not be found.')\n\n let fragment: OutreachConnectReturn\n const providerError = params.get('error')\n const code = params.get('code') ?? ''\n // An error fragment names a Microsoft connect, so the page says whose screen it was.\n const named = claims.provider === 'microsoft' ? { provider: claims.provider } : {}\n if (providerError) {\n fragment = { kind: 'error', reason: providerError === 'access_denied' ? 'access_denied' : 'google_error', ...named }\n } else if (!read.ok) {\n fragment = { kind: 'error', reason: 'expired', ...named }\n } else if (!code || code.length > MAX_CODE_CHARS) {\n fragment = { kind: 'error', reason: 'google_error', ...named }\n } else {\n fragment = { kind: 'code', code, state: params.get('state') ?? '' }\n }\n // A RELATIVE location on the callback's own origin: the path is built from\n // the organization's slug, never from anything the request supplied.\n return new Response(null, {\n status: 303,\n headers: {\n ...noStore,\n 'Referrer-Policy': 'no-referrer',\n Location: `/${encodeURIComponent(slug)}/outreach/mailboxes#${buildConnectReturnFragment(fragment)}`,\n },\n })\n }\n\n const connectComplete: PluginWebApiHandler = async (request) => {\n if (request.method !== 'POST') return methodNotAllowed('POST')\n const body = await readBody(request)\n const gate = await outreachMemberGate(request, body['orgId'], deps.gate)\n if (gate instanceof Response) return gate\n if (!deps.stateSigningConfigured()) return notConfigured()\n if (!deps.readConfig().configured && !readMicrosoftConfig().configured) return notConfigured()\n const code = typeof body['code'] === 'string' ? body['code'] : ''\n if (!code || code.length > MAX_CODE_CHARS) return refusal(400, 'invalid-request', 'The connection did not return a code.')\n\n const firestore = deps.firestore()\n const nowMs = deps.now()\n const read = readOutreachOAuthState(body['state'], nowMs)\n if (read.ok === false && read.refusal === 'state-invalid') {\n return refusal(400, 'state-invalid', 'This connection could not be verified. Connect the mailbox again.')\n }\n const claims = read.ok ? read.claims : (read as { claims: typeof read.claims }).claims\n if (claims.uid !== gate.uid) {\n return refusal(\n 403,\n 'state-user-mismatch',\n 'This connection was started by another member. Sign in as that member, or connect the mailbox again.',\n )\n }\n if (claims.orgId !== gate.orgId) {\n return refusal(400, 'state-org-mismatch', 'This connection was started in another organization.')\n }\n if (!read.ok) return refusal(410, 'state-expired', 'This connection took too long. Connect the mailbox again.')\n if (!providerConfigured(claims.provider)) return notConfigured(claims.provider)\n\n const consumed = await consumeOutreachOAuthState(firestore, { claims, nowMs })\n if (consumed.ok === false) {\n if (consumed.refusal === 'state-expired') {\n return refusal(410, 'state-expired', 'This connection took too long. Connect the mailbox again.')\n }\n return refusal(\n 409,\n consumed.refusal,\n consumed.refusal === 'state-superseded'\n ? 'A newer connection was started. Finish that one, or connect the mailbox again.'\n : 'This connection was already used. Connect the mailbox again.',\n )\n }\n\n const account =\n claims.provider === 'microsoft'\n ? await redeemMicrosoftCode({ code, claims, redirectUri: consumed.redirectUri, nowMs })\n : await redeemGoogleCode({ code, claims, redirectUri: consumed.redirectUri, nowMs })\n if (account instanceof Response) return account\n return storeConnectedMailbox({ gate, body, account, nowMs })\n }\n\n /** Google's half of a connect: the code redeemed, the grant and the account checked. */\n async function redeemGoogleCode(input: {\n code: string\n claims: OutreachOAuthStateClaims\n redirectUri: string\n nowMs: number\n }): Promise<Response | ConnectedAccount> {\n const { code, claims, nowMs } = input\n const config = deps.readConfig()\n if (!config.configured) return notConfigured()\n let grant: GoogleTokenResponse\n try {\n grant = await exchangeGoogleAuthorizationCode(\n {\n clientId: config.config.clientId,\n clientSecret: config.config.clientSecret,\n code,\n redirectUri: input.redirectUri,\n codeVerifier: outreachPkceVerifier(claims.nonce),\n },\n deps.transport,\n )\n } catch (error) {\n if (error instanceof GmailTransportError && error.code === 'invalid_grant') {\n return refusal(400, 'code-rejected', \"Google's sign-in expired or was already used. Connect the mailbox again.\")\n }\n if (error instanceof GmailTransportError && error.code === 'client_misconfigured') {\n return refusal(503, 'not-configured', \"Google refused this deployment's OAuth client.\")\n }\n if (error instanceof GmailTransportError && error.code === 'insufficient_scope') {\n return refusal(\n 422,\n 'scopes-missing',\n 'Sequences needs permission to send and to read your mail. Connect again and allow both.',\n )\n }\n return googleFailure(error, 'connect/complete token exchange')\n }\n if (!grant.refreshToken) {\n return refusal(\n 422,\n 'refresh-token-missing',\n 'Google did not grant offline access, so the mailbox could not send later. Connect it again.',\n )\n }\n if (!grantedScopesInclude(grant.scope, OUTREACH_REQUIRED_GRANTED_SCOPES)) {\n return refusal(\n 422,\n 'scopes-missing',\n 'Sequences needs permission to send and to read your mail. Connect again and allow both.',\n )\n }\n const identity = readGoogleIdToken(grant.idToken, {\n clientId: config.config.clientId,\n nonce: outreachOidcNonce(claims.nonce),\n nowMs,\n })\n if (identity.ok === false) {\n return refusal(\n 422,\n 'identity-unverified',\n identity.refusal === 'email-unverified'\n ? \"Google has not verified this account's email address.\"\n : \"Google's answer could not be verified. Connect the mailbox again.\",\n )\n }\n\n const client = createGmailClient({\n ...deps.transport,\n clientId: config.config.clientId,\n clientSecret: config.config.clientSecret,\n refreshToken: grant.refreshToken,\n })\n let profileEmail: string\n let sendAsOptions: ReturnType<typeof verifiedSendAsAddresses>\n try {\n const [profile, sendAs] = await Promise.all([client.getProfile(), client.listSendAs()])\n profileEmail = profile.emailAddress\n sendAsOptions = verifiedSendAsAddresses(sendAs)\n } catch (error) {\n if (error instanceof GmailTransportError && error.reconnectRequired) {\n return refusal(\n 422,\n 'scopes-missing',\n 'Sequences needs permission to send and to read your mail. Connect again and allow both.',\n )\n }\n return googleFailure(error, 'connect/complete Gmail profile')\n }\n if (profileEmail !== identity.identity.email) {\n return refusal(422, 'account-mismatch', 'The Gmail account and the Google sign-in did not match. Connect again.')\n }\n if (!sendAsOptions.some((option) => option.email === profileEmail)) {\n sendAsOptions = [\n { email: profileEmail, displayName: '', isPrimary: true, isDefault: !sendAsOptions.some((o) => o.isDefault) },\n ...sendAsOptions,\n ]\n }\n\n return {\n provider: 'google',\n providerAccountId: identity.identity.sub,\n email: profileEmail,\n sendAsOptions,\n scopes: grant.scope.split(/\\s+/).filter(Boolean),\n refreshToken: grant.refreshToken,\n keyring: config.config.keyring,\n }\n }\n\n /**\n * Microsoft's half of a connect (AGL-3489): the code redeemed, the grant's\n * permissions checked, the ID token read, and the account read back from\n * Graph — the same account the sign-in named, by its directory id.\n */\n async function redeemMicrosoftCode(input: {\n code: string\n claims: OutreachOAuthStateClaims\n redirectUri: string\n nowMs: number\n }): Promise<Response | ConnectedAccount> {\n const { code, claims, nowMs } = input\n const config = readMicrosoftConfig()\n if (!config.configured) return notConfigured('microsoft')\n const scopesMissing = () =>\n refusal(\n 422,\n 'scopes-missing',\n 'Sequences needs permission to send and to read your mail. Connect again and allow both.',\n )\n let grant: MicrosoftTokenResponse\n try {\n grant = await exchangeMicrosoftAuthorizationCode(\n {\n clientId: config.config.clientId,\n clientSecret: config.config.clientSecret,\n tenant: config.config.tenant,\n code,\n redirectUri: input.redirectUri,\n codeVerifier: outreachPkceVerifier(claims.nonce),\n },\n deps.transport,\n )\n } catch (error) {\n if (error instanceof GmailTransportError && error.code === 'invalid_grant') {\n return refusal(400, 'code-rejected', \"Microsoft's sign-in expired or was already used. Connect the mailbox again.\")\n }\n if (error instanceof GmailTransportError && error.code === 'client_misconfigured') {\n return refusal(503, 'not-configured', \"Microsoft refused this deployment's app registration.\")\n }\n if (error instanceof GmailTransportError && error.code === 'insufficient_scope') return scopesMissing()\n return googleFailure(error, 'connect/complete Microsoft token exchange')\n }\n if (!grant.refreshToken) {\n return refusal(\n 422,\n 'refresh-token-missing',\n 'Microsoft did not grant offline access, so the mailbox could not send later. Connect it again.',\n )\n }\n if (!microsoftScopesInclude(grant.scope)) return scopesMissing()\n const identity = readMicrosoftIdToken(grant.idToken, {\n clientId: config.config.clientId,\n nonce: outreachOidcNonce(claims.nonce),\n nowMs,\n })\n if (identity.ok === false) {\n return refusal(422, 'identity-unverified', \"Microsoft's answer could not be verified. Connect the mailbox again.\")\n }\n const client = createGraphClient({\n ...deps.transport,\n clientId: config.config.clientId,\n clientSecret: config.config.clientSecret,\n tenant: config.config.tenant,\n refreshToken: grant.refreshToken,\n accessToken: { token: grant.accessToken, expiresInSeconds: grant.expiresInSeconds },\n })\n let profile: GraphProfile\n try {\n profile = await client.getProfile()\n } catch (error) {\n if (error instanceof GmailTransportError && error.reconnectRequired) return scopesMissing()\n return googleFailure(error, 'connect/complete Microsoft profile')\n }\n if (profile.id !== identity.identity.oid || !profile.emailAddress) {\n return refusal(\n 422,\n 'account-mismatch',\n 'The Microsoft 365 mailbox and the Microsoft sign-in did not match. Connect again.',\n )\n }\n return {\n provider: 'microsoft',\n providerAccountId: identity.identity.sub,\n email: profile.emailAddress,\n sendAsOptions: [\n { email: profile.emailAddress, displayName: profile.displayName, isPrimary: true, isDefault: true },\n ],\n scopes: grant.scope.split(/\\s+/).filter(Boolean),\n refreshToken: grant.refreshToken,\n keyring: config.config.keyring,\n }\n }\n\n /**\n * The connect's end, whichever provider named the account: the member's\n * mailbox limit, the mailbox (new, or a reconnect that keeps its\n * settings), its sealed grant, the aliases the provider confirmed, and the\n * activity row.\n */\n async function storeConnectedMailbox(input: {\n gate: OutreachGateContext\n body: Record<string, unknown>\n account: ConnectedAccount\n nowMs: number\n }): Promise<Response> {\n const { gate, body, account, nowMs } = input\n const { provider, email: profileEmail, sendAsOptions } = account\n const firestore = deps.firestore()\n const mailboxId = outreachMailboxId(gate.orgId, gate.uid, account.providerAccountId, provider)\n const mailboxDoc = mailboxRef(firestore, gate.orgId, mailboxId)\n const credentialDoc = mailboxCredentialsRef(firestore, mailboxId)\n const [existingMailbox, existingCredential] = await Promise.all([mailboxDoc.get(), credentialDoc.get()])\n const current = readMailbox(mailboxId, existingMailbox.exists ? existingMailbox.data() : undefined)\n if (!current) {\n const mine = await firestore\n .collection('orgs')\n .doc(gate.orgId)\n .collection('outreachMailboxes')\n .where('connectedByUid', '==', gate.uid)\n .limit(OUTREACH_MAX_MAILBOXES_PER_MEMBER)\n .get()\n if (mine.size >= OUTREACH_MAX_MAILBOXES_PER_MEMBER) {\n return refusal(\n 409,\n 'mailbox-limit',\n `You can connect up to ${OUTREACH_MAX_MAILBOXES_PER_MEMBER} mailboxes. Disconnect one before connecting another.`,\n )\n }\n }\n\n const defaultOption = sendAsOptions.find((option) => option.email === defaultSendAs(sendAsOptions, profileEmail))\n let mailbox: OutreachMailbox\n /** On a reconnect, only the fields a connect decides — see the write below. */\n let reconnected: Partial<OutreachMailbox> | null = null\n if (current) {\n const keepSendAs = sendAsOptions.some((option) => option.email === current.sendAs)\n reconnected = {\n provider,\n email: profileEmail,\n sendAs: keepSendAs ? current.sendAs : (defaultOption?.email ?? profileEmail),\n sendAsOptions,\n // A reconnect restores a mailbox the provider had cut off, and leaves a\n // mailbox its member paused paused.\n status: (current.status === 'paused' ? 'paused' : 'connected') satisfies OutreachMailboxStatus,\n connectedAtMs: nowMs,\n updatedAtMs: nowMs,\n }\n mailbox = { ...current, ...reconnected }\n } else {\n const timezone = isValidTimezone(body['timezone']) ? String(body['timezone']) : 'UTC'\n const displayName = validateDisplayName(defaultOption?.displayName || gate.name || '')\n mailbox = {\n id: mailboxId,\n provider,\n email: profileEmail,\n sendAs: defaultOption?.email ?? profileEmail,\n sendAsOptions,\n displayName: typeof displayName === 'string' ? displayName : '',\n status: 'connected',\n dailyCap: OUTREACH_DEFAULT_DAILY_CAP,\n window: { ...OUTREACH_DEFAULT_WINDOW, days: [...OUTREACH_DEFAULT_WINDOW.days] },\n timezone,\n rampStartedAtMs: nowMs,\n health: {\n sentToday: 0,\n sentOnDay: null,\n bounces: 0,\n replies: 0,\n lastSentAtMs: null,\n lastErrorAtMs: null,\n lastErrorCode: null,\n daily: {},\n },\n connectedByUid: gate.uid,\n connectedAtMs: nowMs,\n createdAtMs: nowMs,\n updatedAtMs: nowMs,\n }\n }\n const credential: OutreachStoredMailboxCredentials = {\n id: mailboxId,\n orgId: gate.orgId,\n mailboxId,\n provider,\n connectedByUid: gate.uid,\n providerAccountId: account.providerAccountId,\n email: profileEmail,\n scopes: account.scopes,\n ...sealMailboxRefreshToken(account.refreshToken, mailboxId, account.keyring),\n createdAtMs: Number(existingCredential.exists ? existingCredential.get('createdAtMs') : 0) || nowMs,\n updatedAtMs: nowMs,\n }\n const batch = firestore.batch()\n // A reconnect MERGES only what a connect decides, so the settings a member\n // chose and the health counters the sending runtime increments are never\n // written back from a read that may already be stale.\n if (reconnected) batch.set(mailboxDoc, reconnected, { merge: true })\n else batch.set(mailboxDoc, mailbox)\n batch.set(credentialDoc, credential)\n await batch.commit()\n\n const aliases: { ok: boolean; confirmed?: string[] } = await deps\n .confirmAliasesByProvider(firestore, {\n orgId: gate.orgId,\n uid: gate.uid,\n addresses: sendAsOptions.map((option) => option.email),\n nowMs,\n })\n .catch((error: unknown) => {\n console.error('[outreach] confirming member aliases from send-as failed', error)\n return { ok: false }\n })\n await deps.logOrgActivity(\n gate.orgId,\n { uid: gate.uid, email: gate.email },\n current ? 'Reconnected a mailbox in Sequences' : 'Connected a mailbox in Sequences',\n { type: OUTREACH_MAILBOX_ACTIVITY_TARGET, id: mailboxId, name: activityName(mailbox) },\n )\n return ok({\n ok: true,\n mailbox,\n created: !current,\n confirmedAliases: aliases.ok ? (aliases.confirmed ?? []) : [],\n })\n }\n\n const settings: PluginWebApiHandler = async (request) => {\n if (request.method !== 'POST') return methodNotAllowed('POST')\n const body = await readBody(request)\n const loaded = await loadManagedMailbox(request, body, 'member-or-admin')\n if (loaded instanceof Response) return loaded\n const { gate, mailbox } = loaded\n const update: Partial<OutreachMailbox> = {}\n const invalid = (message: string) => refusal(400, 'invalid-settings', message)\n\n if (body['sendAs'] !== undefined) {\n const sendAs = typeof body['sendAs'] === 'string' ? body['sendAs'].trim().toLowerCase() : ''\n if (!(mailbox.sendAsOptions ?? []).some((option) => option.email === sendAs)) {\n return invalid('Choose one of the addresses the provider has verified for this account.')\n }\n update.sendAs = sendAs\n }\n if (body['displayName'] !== undefined) {\n const name = validateDisplayName(body['displayName'])\n if (typeof name !== 'string') return invalid(name.message)\n update.displayName = name\n }\n if (body['dailyCap'] !== undefined) {\n const cap = validateDailyCap(body['dailyCap'])\n if (typeof cap !== 'number') return invalid(cap.message)\n update.dailyCap = cap\n }\n if (body['window'] !== undefined) {\n const window = validateSendWindow(body['window'])\n if (!('days' in window)) return invalid(window.message)\n update.window = window\n }\n if (body['timezone'] !== undefined) {\n if (!isValidTimezone(body['timezone'])) return invalid('Choose a timezone from the list.')\n update.timezone = body['timezone']\n }\n if (body['warmUp'] !== undefined) {\n /*\n * The ramp guards a NEW sender's reputation; a mailbox that has sent\n * mail for years has one already, and ramping it to ten a day guards\n * nothing (AGL-3228). Its member decides. Turning the ramp back on\n * starts a fresh one from today, which is what \"warm up\" means.\n */\n if (typeof body['warmUp'] !== 'boolean') return invalid('Say whether to warm the mailbox up gradually.')\n const running = typeof mailbox.rampStartedAtMs === 'number'\n if (body['warmUp'] && !running) update.rampStartedAtMs = deps.now()\n if (!body['warmUp'] && running) update.rampStartedAtMs = null\n }\n if (!Object.keys(update).length) return ok({ ok: true, mailbox })\n const nowMs = deps.now()\n await mailboxRef(deps.firestore(), gate.orgId, mailbox.id).update({ ...update, updatedAtMs: nowMs })\n return ok({ ok: true, mailbox: { ...mailbox, ...update, updatedAtMs: nowMs } })\n }\n\n const status: PluginWebApiHandler = async (request) => {\n if (request.method !== 'POST') return methodNotAllowed('POST')\n const body = await readBody(request)\n if (typeof body['paused'] !== 'boolean') return refusal(400, 'invalid-request', 'Say whether to pause the mailbox.')\n const loaded = await loadManagedMailbox(request, body, 'member-or-admin')\n if (loaded instanceof Response) return loaded\n const { gate, mailbox } = loaded\n if (mailbox.status === 'reconnect_required' || mailbox.status === 'disconnected') {\n return refusal(409, 'reconnect-required', 'Reconnect this mailbox before pausing or resuming it.')\n }\n const next: OutreachMailboxStatus = body['paused'] ? 'paused' : 'connected'\n if (mailbox.status === next) return ok({ ok: true, mailbox })\n const nowMs = deps.now()\n // A member's pause or resume answers an automatic pause (AGL-2981): its\n // reason goes, and the next bounce is judged as new evidence.\n await mailboxRef(deps.firestore(), gate.orgId, mailbox.id).update({\n status: next,\n autoPause: null,\n updatedAtMs: nowMs,\n })\n await deps.logOrgActivity(\n gate.orgId,\n { uid: gate.uid, email: gate.email },\n next === 'paused' ? 'Paused a mailbox in Sequences' : 'Resumed a mailbox in Sequences',\n { type: OUTREACH_MAILBOX_ACTIVITY_TARGET, id: mailbox.id, name: activityName(mailbox) },\n )\n return ok({ ok: true, mailbox: { ...mailbox, status: next, autoPause: null, updatedAtMs: nowMs } })\n }\n\n const test: PluginWebApiHandler = async (request) => {\n if (request.method !== 'POST') return methodNotAllowed('POST')\n const body = await readBody(request)\n const loaded = await loadManagedMailbox(request, body, 'member')\n if (loaded instanceof Response) return loaded\n const { gate, mailbox } = loaded\n if (mailbox.status === 'reconnect_required' || mailbox.status === 'disconnected') {\n return refusal(409, 'reconnect-required', 'Reconnect this mailbox before sending from it.')\n }\n const provider: OutreachMailboxProvider = mailbox.provider === 'microsoft' ? 'microsoft' : 'google'\n if (!providerConfigured(provider)) return notConfigured(provider)\n const limited = await deps.consumeRateLimit(`outreach-mailbox-test:${mailbox.id}`, {\n limit: OUTREACH_TEST_SENDS_PER_HOUR,\n windowMs: 60 * 60 * 1000,\n })\n if (!limited.allowed) {\n return refusal(429, 'rate-limited', `A mailbox can send ${OUTREACH_TEST_SENDS_PER_HOUR} tests an hour. Try again later.`)\n }\n /*\n * To the member's own address unless they name another (AGL-3228). A\n * test to oneself never leaves the provider, so it arrives with no\n * Authentication-Results at all and cannot show whether the send-as\n * domain's DKIM and DMARC hold; an outside mailbox the member can read\n * is the only place that can be seen. The rate limit above is the\n * whole guard on who may be written to — it is the member's own\n * account sending, as it could from its own compose window.\n */\n const named = body['to']\n const to =\n named === undefined || named === null || String(named).trim() === ''\n ? mailbox.email\n : normalizeContactEmail(String(named))\n if (!to) {\n return refusal(400, 'invalid-request', `\"${String(named).trim()}\" isn't a valid email address.`)\n }\n const firestore = deps.firestore()\n const nowMs = deps.now()\n const opened = await openOutreachMailboxClient(\n firestore,\n { mailboxId: mailbox.id },\n { ...deps.transport, readConfig: deps.readConfig, readMicrosoftConfig, now: deps.now },\n )\n if (opened.ok === false) {\n if (opened.reason === 'not-configured') return notConfigured(provider)\n await markOutreachMailboxReconnectRequired(firestore, {\n orgId: gate.orgId,\n mailboxId: mailbox.id,\n errorCode: opened.reason,\n nowMs,\n })\n return refusal(409, 'reconnect-required', 'This mailbox needs to be connected again before it can send.')\n }\n try {\n const sent = await sendOutreachMessage(opened.client, {\n from: { address: mailbox.sendAs, name: mailbox.displayName },\n to,\n subject: 'Sequences test message',\n text: [\n 'This is a test message from Sequences.',\n '',\n `It was sent through the connected mailbox ${mailbox.email} as ${mailbox.sendAs}. ` +\n 'If it reached the inbox, this mailbox can send.',\n ...(to === mailbox.email\n ? []\n : [\n '',\n 'To read whether the sender is authenticated, open this message\\u2019s original source ' +\n 'and look for dkim=pass, spf=pass and dmarc=pass in Authentication-Results.',\n ]),\n ].join('\\n'),\n })\n return ok({ ok: true, sentTo: to, gmailMessageId: sent.gmailMessageId, sentAtMs: nowMs })\n } catch (error) {\n if (error instanceof GmailTransportError && error.reconnectRequired) {\n await markOutreachMailboxReconnectRequired(firestore, {\n orgId: gate.orgId,\n mailboxId: mailbox.id,\n errorCode: error.code,\n nowMs,\n })\n return refusal(\n 409,\n 'reconnect-required',\n `${providerName(provider)} refused this mailbox’s access. Connect it again.`,\n )\n }\n if (error instanceof Rfc5322MessageError) {\n return refusal(400, 'invalid-settings', `The test could not be written: ${error.message}`)\n }\n return googleFailure(error, 'test send')\n }\n }\n\n const disconnect: PluginWebApiHandler = async (request) => {\n if (request.method !== 'POST') return methodNotAllowed('POST')\n const body = await readBody(request)\n const loaded = await loadManagedMailbox(request, body, 'member-or-admin')\n if (loaded instanceof Response) return loaded\n const { gate, mailbox } = loaded\n const firestore = deps.firestore()\n const credentialDoc = mailboxCredentialsRef(firestore, mailbox.id)\n const snapshot = await credentialDoc.get()\n const credential = readMailboxCredentials(snapshot.exists ? snapshot.data() : null)\n const revocation = credential\n ? await revokeMailboxGrant(firestore, credential, deps)\n : ('already-invalid' as const)\n const batch = firestore.batch()\n batch.delete(credentialDoc)\n batch.delete(mailboxRef(firestore, gate.orgId, mailbox.id))\n await batch.commit()\n await deps.logOrgActivity(\n gate.orgId,\n { uid: gate.uid, email: gate.email },\n 'Disconnected a mailbox in Sequences',\n { type: OUTREACH_MAILBOX_ACTIVITY_TARGET, id: mailbox.id, name: activityName(mailbox) },\n )\n return ok({ ok: true, revocation } satisfies OutreachMailboxDisconnectResponse)\n }\n\n /**\n * How receivers judge mail from the address a mailbox sends as. Any member\n * who can see the mailbox can read it: it is a reading of public DNS about\n * the organization's own domain, and changes nothing.\n */\n const readiness: PluginWebApiHandler = async (request) => {\n if (request.method !== 'POST') return methodNotAllowed('POST')\n const body = await readBody(request)\n const gate = await outreachMemberGate(request, body['orgId'], deps.gate)\n if (gate instanceof Response) return gate\n const mailboxId = typeof body['mailboxId'] === 'string' ? body['mailboxId'] : ''\n if (!MAILBOX_ID.test(mailboxId)) return refusal(400, 'invalid-request', 'Name the mailbox.')\n const snapshot = await mailboxRef(deps.firestore(), gate.orgId, mailboxId).get()\n const mailbox = readMailbox(mailboxId, snapshot.exists ? snapshot.data() : undefined)\n if (!mailbox) return refusal(404, 'mailbox-not-found', 'That mailbox is not connected to this organization.')\n const sendAs = mailbox.sendAs || mailbox.email\n const expectation =\n mailbox.provider === 'microsoft'\n ? microsoftMailboxSenderExpectation(sendAs)\n : googleMailboxSenderExpectation(sendAs)\n const read = expectation\n ? await deps.readSenderReadiness(expectation, { fresh: body['fresh'] === true }).catch(() => null)\n : null\n return ok({ ok: true, sendAs, readiness: read } satisfies OutreachMailboxReadinessResponse)\n }\n\n return { availability, connect, oauthCallback, connectComplete, settings, status, test, disconnect, readiness }\n}\n\n/** A Google failure the route could not handle itself, as the refusal {@link googleFailureAnswer} decides. */\nfunction googleFailure(error: unknown, route: string): Response {\n const answer = googleFailureAnswer(error, route)\n return refusal(answer.status, answer.reason, answer.error)\n}\n"],"names":["normalizeContactEmail","googleMailboxSenderExpectation","microsoftMailboxSenderExpectation","OUTREACH_MAILBOX_PROVIDERS","createGmailClient","createGraphClient","GmailTransportError","googleFailureAnswer","buildGoogleAuthorizationUrl","exchangeGoogleAuthorizationCode","grantedScopesInclude","OUTREACH_REQUIRED_GRANTED_SCOPES","pkceChallenge","readGoogleIdToken","buildMicrosoftAuthorizationUrl","exchangeMicrosoftAuthorizationCode","microsoftScopesInclude","readMicrosoftIdToken","Rfc5322MessageError","sendOutreachMessage","buildConnectReturnFragment","mailboxCredentialsRef","mailboxRef","outreachMailboxId","readMailboxCredentials","sealMailboxRefreshToken","revokeMailboxGrant","outreachMemberGate","refusal","defaultSendAs","isValidTimezone","OUTREACH_DEFAULT_DAILY_CAP","OUTREACH_DEFAULT_WINDOW","OUTREACH_MAX_MAILBOXES_PER_MEMBER","validateDailyCap","validateDisplayName","validateSendWindow","verifiedSendAsAddresses","markOutreachMailboxReconnectRequired","openOutreachMailboxClient","consumeOutreachOAuthState","mintOutreachOAuthState","outreachOidcNonce","outreachPkceVerifier","readOutreachOAuthState","recordOutreachOAuthState","outreachNotConfiguredMessage","readOutreachMicrosoftConfig","OUTREACH_TEST_SENDS_PER_HOUR","OUTREACH_MAILBOX_ACTIVITY_TARGET","MAILBOX_ID","MAX_CODE_CHARS","noStore","ok","body","Response","json","status","headers","methodNotAllowed","allow","error","reason","Allow","readBody","request","catch","Array","isArray","notConfigured","provider","readProvider","value","undefined","includes","providerName","readMailbox","id","data","activityName","mailbox","email","createOutreachMailboxRoutes","deps","readMicrosoftConfig","providerConfigured","configured","readConfig","loadManagedMailbox","who","gate","mailboxId","test","snapshot","firestore","orgId","get","exists","own","connectedByUid","uid","isOrgAdmin","availability","method","URL","url","searchParams","missing","config","microsoft","push","shared","stateSigningConfigured","Boolean","redirectUri","providers","google","canManageAll","length","connect","nowMs","now","state","claims","clientId","tenant","codeChallenge","nonce","loginHint","oauthCallback","params","read","plain","text","org","readOrg","slug","fragment","providerError","code","named","kind","Location","encodeURIComponent","connectComplete","consumed","account","redeemMicrosoftCode","redeemGoogleCode","storeConnectedMailbox","input","grant","clientSecret","codeVerifier","transport","googleFailure","refreshToken","scope","identity","idToken","client","profileEmail","sendAsOptions","profile","sendAs","Promise","all","getProfile","listSendAs","emailAddress","reconnectRequired","some","option","displayName","isPrimary","isDefault","o","providerAccountId","sub","scopes","split","filter","keyring","scopesMissing","accessToken","token","expiresInSeconds","oid","aliases","mailboxDoc","credentialDoc","existingMailbox","existingCredential","current","mine","collection","doc","where","limit","size","defaultOption","find","reconnected","keepSendAs","connectedAtMs","updatedAtMs","timezone","String","name","dailyCap","window","days","rampStartedAtMs","health","sentToday","sentOnDay","bounces","replies","lastSentAtMs","lastErrorAtMs","lastErrorCode","daily","createdAtMs","credential","Number","batch","set","merge","commit","confirmAliasesByProvider","addresses","map","console","logOrgActivity","type","created","confirmedAliases","confirmed","settings","loaded","update","invalid","message","trim","toLowerCase","cap","running","Object","keys","next","autoPause","limited","consumeRateLimit","windowMs","allowed","to","opened","errorCode","sent","from","address","subject","join","sentTo","gmailMessageId","sentAtMs","disconnect","revocation","delete","readiness","expectation","readSenderReadiness","fresh","route","answer"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,qBAAqB,QAAQ,kCAAiC;AAEvE,SACEC,8BAA8B,EAC9BC,iCAAiC,QAG5B,2BAA0B;AAEjC,SACEC,0BAA0B,QAKrB,6BAAyB;AAChC,SAASC,iBAAiB,QAAQ,+BAA2B;AAC7D,SAASC,iBAAiB,QAA2B,+BAA2B;AAChF,SAASC,mBAAmB,EAAEC,mBAAmB,QAAQ,+BAA2B;AACpF,SACEC,2BAA2B,EAC3BC,+BAA+B,EAC/BC,oBAAoB,EACpBC,gCAAgC,EAChCC,aAAa,EACbC,iBAAiB,QAEZ,+BAA2B;AAElC,SACEC,8BAA8B,EAC9BC,kCAAkC,EAClCC,sBAAsB,EACtBC,oBAAoB,QAEf,kCAA8B;AACrC,SAASC,mBAAmB,QAAQ,0BAAsB;AAC1D,SAASC,mBAAmB,QAAQ,+BAA2B;AAC/D,SACEC,0BAA0B,QAOrB,mBAAe;AACtB,SACEC,qBAAqB,EACrBC,UAAU,EACVC,iBAAiB,EACjBC,sBAAsB,EACtBC,uBAAuB,QAElB,2BAAuB;AAC9B,SAASC,kBAAkB,QAAQ,sBAAkB;AACrD,SACEC,kBAAkB,EAClBC,OAAO,QAGF,oBAAgB;AACvB,SACEC,aAAa,EACbC,eAAe,EACfC,0BAA0B,EAC1BC,uBAAuB,EACvBC,iCAAiC,EACjCC,gBAAgB,EAChBC,mBAAmB,EACnBC,kBAAkB,EAClBC,uBAAuB,QAClB,wBAAoB;AAC3B,SACEC,oCAAoC,EACpCC,yBAAyB,QACpB,yBAAqB;AAC5B,SACEC,yBAAyB,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+BmK;QACrC,MAAMjC,OAAO2I,cACT,MAAM3L,KAAK4L,mBAAmB,CAACD,aAAa;YAAEE,OAAO1N,IAAI,CAAC,QAAQ,KAAK;QAAK,GAAGY,KAAK,CAAC,IAAM,QAC3F;QACJ,OAAOb,GAAG;YAAEA,IAAI;YAAM+G;YAAQyG,WAAW1I;QAAK;IAChD;IAEA,OAAO;QAAE7B;QAAciB;QAASU;QAAee;QAAiB8F;QAAUrL;QAAQmC;QAAM8K;QAAYG;IAAU;AAChH;AAEA,4GAA4G,GAC5G,SAASlH,cAAc9F,KAAc,EAAEoN,KAAa;IAClD,MAAMC,SAAS3Q,oBAAoBsD,OAAOoN;IAC1C,OAAOrP,QAAQsP,OAAOzN,MAAM,EAAEyN,OAAOpN,MAAM,EAAEoN,OAAOrN,KAAK;AAC3D"}
@@ -101,7 +101,7 @@ export function createOutreachLinkDomainsRoute(deps, links) {
101
101
  return outreachRefusal(400, 'invalid-request', 'Say whether to set the link domain up, check it, or remove it.');
102
102
  }
103
103
  if (action !== 'check' && !gate.isOrgAdmin) {
104
- return outreachRefusal(403, 'permission', 'Only an owner or an admin can change link domains.');
104
+ return outreachRefusal(403, 'permission', 'Your role does not include "Manage everyone’s Sequences" — ask an organization admin');
105
105
  }
106
106
  const checked = validateTrackingHostDomain(String((_body_domain = body['domain']) != null ? _body_domain : ''));
107
107
  if (!checked.domain) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/routes/link-domain-routes.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PluginWebApiHandler } from '@aglyn/aglyn/server'\nimport {\n sendingTrackingHost,\n TRACKING_HOST_DETAIL,\n trackingHostDnsRecords,\n trackingHostLinkOrigin,\n validateTrackingHostDomain,\n type TrackingHostRecord,\n type TrackingHostResult,\n} from '@aglyn/shared-util-email'\nimport { OUTREACH_SHORT_LINK_PATH } from '../runtime/click-link'\nimport type {\n OutreachLinkDomain,\n OutreachLinkDomainRequest,\n OutreachLinkDomainResponse,\n OutreachLinkDomainsResponse,\n} from '../model/outreach-api'\nimport { OUTREACH_COLLECTIONS } from '../model/outreach.types'\nimport { readStoredOutreachMailbox } from '../model/stored-records'\nimport type { OutreachRouteDeps } from './route-deps'\nimport { outreachRouteGate, type OutreachRouteCaller } from './route-gate'\nimport {\n outreachMethodNotAllowed,\n outreachOk,\n outreachRefusal,\n readOutreachJsonBody,\n} from './route-http'\n\n/**\n * THE LINK DOMAINS ROUTE (AGL-3306): `outreach/link-domains`.\n *\n * A tracked sequence link reads `https://links.<the mailbox's domain>/<id>`\n * once the organization has set that host up and it has verified — the same\n * `links.` label, the same CNAME-and-check process, as a sending domain's\n * campaign click tracking, with this deployment in place of the mail\n * provider (`tracking-host.ts`). Until then it reads the console's own\n * `/api/outreach/l/<id>`, as it always has.\n *\n * `GET ?orgId` lists one row per sending domain of the organization's\n * connected mailboxes, plus any host still set up for a domain no mailbox\n * sends as any more (so it can be removed). `POST` sets one up — the domain\n * driver attaches the host — checks it, or removes it. Only a domain a\n * mailbox of the organization sends as may be set up: the host is a claim\n * about mail the organization actually sends.\n *\n * Setting up and removing change what this deployment serves, so they are\n * an owner's or an admin's; checking changes nothing but the verdict, and\n * the list is everyone's who may use Sequences.\n */\n\n/** The platform's tracking-host store (`@aglyn/tenant-data-admin`); specs build their own. */\nexport interface OutreachTrackingHosts {\n list(firestore: FirebaseFirestore.Firestore, orgId: string): Promise<TrackingHostRecord[]>\n setUp(input: HostInput): Promise<TrackingHostResult>\n verify(input: HostInput): Promise<TrackingHostResult>\n remove(input: HostInput): Promise<TrackingHostResult>\n}\n\ninterface HostInput {\n firestore: FirebaseFirestore.Firestore\n orgId: string\n domain: string\n nowMs: number\n}\n\nexport interface OutreachLinkDomainRouteDeps {\n hosts(): Promise<OutreachTrackingHosts>\n /** The console's own HTTPS origin, for the link prefix a domain without a host uses. */\n consoleOrigin(): string | null\n}\n\n/** The activity lines a change writes. */\nexport const OUTREACH_LINK_DOMAIN_ACTIVITY = {\n 'set-up': (host: string) => `Set up ${host} as a Sequences link domain`,\n remove: (host: string) => `Removed ${host} as a Sequences link domain`,\n} as const\n\n/** The sending domain of every connected mailbox, alphabetically. */\nasync function mailboxDomains(firestore: FirebaseFirestore.Firestore, orgId: string): Promise<string[]> {\n const snapshot = await firestore.collection('orgs').doc(orgId).collection(OUTREACH_COLLECTIONS.mailboxes).get()\n const domains = new Set<string>()\n for (const doc of snapshot.docs) {\n const mailbox = readStoredOutreachMailbox(doc.id, doc.data())\n if (!mailbox) continue\n const domain = validateTrackingHostDomain(mailbox.sendAs || mailbox.email).domain\n if (domain) domains.add(domain)\n }\n return [...domains].sort()\n}\n\nfunction row(domain: string, record: TrackingHostRecord | null, consoleOrigin: string | null): OutreachLinkDomain {\n const origin = trackingHostLinkOrigin(record)\n const detailKey = record?.lastDetail as keyof typeof TRACKING_HOST_DETAIL | null | undefined\n return {\n domain,\n host: record?.host ?? sendingTrackingHost(domain),\n status: record?.status ?? 'not-set-up',\n records: record\n ? trackingHostDnsRecords(record).map(({ type, name, value, required, note }) => ({\n type,\n name,\n value,\n required,\n note,\n }))\n : [],\n detail: detailKey && detailKey in TRACKING_HOST_DETAIL ? TRACKING_HOST_DETAIL[detailKey] : null,\n linkPrefix: origin ? `${origin}/` : consoleOrigin ? `${consoleOrigin}${OUTREACH_SHORT_LINK_PATH}/` : null,\n checkedAtMs: record?.lastCheckedAtMs ?? null,\n verifiedAtMs: record?.verifiedAtMs ?? null,\n }\n}\n\nasync function listing(\n deps: OutreachRouteDeps,\n links: OutreachLinkDomainRouteDeps,\n gate: OutreachRouteCaller,\n): Promise<OutreachLinkDomainsResponse> {\n const firestore = deps.firestore()\n const [domains, records] = await Promise.all([\n mailboxDomains(firestore, gate.orgId),\n (await links.hosts()).list(firestore, gate.orgId),\n ])\n const byDomain = new Map(records.map((record) => [record.domain, record]))\n const all = [...new Set([...domains, ...byDomain.keys()])].sort()\n const consoleOrigin = links.consoleOrigin()\n return {\n ok: true,\n domains: all.map((domain) => row(domain, byDomain.get(domain) ?? null, consoleOrigin)),\n canManage: gate.isOrgAdmin,\n }\n}\n\nexport function createOutreachLinkDomainsRoute(\n deps: OutreachRouteDeps,\n links: OutreachLinkDomainRouteDeps,\n): PluginWebApiHandler {\n return async (request) => {\n if (request.method === 'GET') {\n const gate = await outreachRouteGate(request, new URL(request.url).searchParams.get('orgId'), deps.gate)\n if (gate instanceof Response) return gate\n return outreachOk(await listing(deps, links, gate))\n }\n if (request.method !== 'POST') return outreachMethodNotAllowed('GET, POST')\n\n const body = await readOutreachJsonBody(request)\n const gate = await outreachRouteGate(request, body['orgId'], deps.gate)\n if (gate instanceof Response) return gate\n const action = body['action'] as OutreachLinkDomainRequest['action']\n if (action !== 'set-up' && action !== 'check' && action !== 'remove') {\n return outreachRefusal(400, 'invalid-request', 'Say whether to set the link domain up, check it, or remove it.')\n }\n if (action !== 'check' && !gate.isOrgAdmin) {\n return outreachRefusal(403, 'permission', 'Only an owner or an admin can change link domains.')\n }\n const checked = validateTrackingHostDomain(String(body['domain'] ?? ''))\n if (!checked.domain) {\n return outreachRefusal(400, 'invalid-domain', checked.error ?? 'Type a domain, such as example.com.')\n }\n const domain = checked.domain\n const firestore = deps.firestore()\n if (action === 'set-up' && !(await mailboxDomains(firestore, gate.orgId)).includes(domain)) {\n return outreachRefusal(\n 400,\n 'invalid-domain',\n `No connected mailbox sends as ${domain}. A link domain follows the address your sequences send from.`,\n )\n }\n\n const hosts = await links.hosts()\n const input = { firestore, orgId: gate.orgId, domain, nowMs: deps.now() }\n const result =\n action === 'set-up' ? await hosts.setUp(input) : action === 'check' ? await hosts.verify(input) : await hosts.remove(input)\n if (result.error) {\n return outreachRefusal(result.status >= 400 ? result.status : 409, 'link-domain-refused', result.error)\n }\n if (action !== 'check') {\n await deps.logOrgActivity(\n gate.orgId,\n { uid: gate.uid, email: gate.email },\n OUTREACH_LINK_DOMAIN_ACTIVITY[action](sendingTrackingHost(domain)),\n { type: 'org', id: gate.orgId },\n )\n }\n return outreachOk({ ...(await listing(deps, links, gate)), domain } satisfies OutreachLinkDomainResponse)\n }\n}\n"],"names":["sendingTrackingHost","TRACKING_HOST_DETAIL","trackingHostDnsRecords","trackingHostLinkOrigin","validateTrackingHostDomain","OUTREACH_SHORT_LINK_PATH","OUTREACH_COLLECTIONS","readStoredOutreachMailbox","outreachRouteGate","outreachMethodNotAllowed","outreachOk","outreachRefusal","readOutreachJsonBody","OUTREACH_LINK_DOMAIN_ACTIVITY","host","remove","mailboxDomains","firestore","orgId","snapshot","collection","doc","mailboxes","get","domains","Set","docs","mailbox","id","data","domain","sendAs","email","add","sort","row","record","consoleOrigin","origin","detailKey","lastDetail","status","records","map","type","name","value","required","note","detail","linkPrefix","checkedAtMs","lastCheckedAtMs","verifiedAtMs","listing","deps","links","gate","Promise","all","hosts","list","byDomain","Map","keys","ok","canManage","isOrgAdmin","createOutreachLinkDomainsRoute","request","body","method","URL","url","searchParams","Response","action","checked","String","error","includes","input","nowMs","now","result","setUp","verify","logOrgActivity","uid"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SACEA,mBAAmB,EACnBC,oBAAoB,EACpBC,sBAAsB,EACtBC,sBAAsB,EACtBC,0BAA0B,QAGrB,2BAA0B;AACjC,SAASC,wBAAwB,QAAQ,2BAAuB;AAOhE,SAASC,oBAAoB,QAAQ,6BAAyB;AAC9D,SAASC,yBAAyB,QAAQ,6BAAyB;AAEnE,SAASC,iBAAiB,QAAkC,kBAAc;AAC1E,SACEC,wBAAwB,EACxBC,UAAU,EAC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,SAASL,WAAW,UAAU,MAAMhB,MAAM0B,MAAM,CAACL,SAAS,MAAMrB,MAAM7C,MAAM,CAACkE;QACvH,IAAIG,OAAOL,KAAK,EAAE;YAChB,OAAOpE,gBAAgByE,OAAO3C,MAAM,IAAI,MAAM2C,OAAO3C,MAAM,GAAG,KAAK,uBAAuB2C,OAAOL,KAAK;QACxG;QACA,IAAIH,WAAW,SAAS;YACtB,MAAMrB,KAAKgC,cAAc,CACvB9B,KAAKvC,KAAK,EACV;gBAAEsE,KAAK/B,KAAK+B,GAAG;gBAAExD,OAAOyB,KAAKzB,KAAK;YAAC,GACnCnB,6BAA6B,CAAC+D,OAAO,CAAC5E,oBAAoB8B,UAC1D;gBAAEc,MAAM;gBAAOhB,IAAI6B,KAAKvC,KAAK;YAAC;QAElC;QACA,OAAOR,WAAW,aAAM,MAAM4C,QAAQC,MAAMC,OAAOC;YAAQ3B;;IAC7D;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/routes/link-domain-routes.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PluginWebApiHandler } from '@aglyn/aglyn/server'\nimport {\n sendingTrackingHost,\n TRACKING_HOST_DETAIL,\n trackingHostDnsRecords,\n trackingHostLinkOrigin,\n validateTrackingHostDomain,\n type TrackingHostRecord,\n type TrackingHostResult,\n} from '@aglyn/shared-util-email'\nimport { OUTREACH_SHORT_LINK_PATH } from '../runtime/click-link'\nimport type {\n OutreachLinkDomain,\n OutreachLinkDomainRequest,\n OutreachLinkDomainResponse,\n OutreachLinkDomainsResponse,\n} from '../model/outreach-api'\nimport { OUTREACH_COLLECTIONS } from '../model/outreach.types'\nimport { readStoredOutreachMailbox } from '../model/stored-records'\nimport type { OutreachRouteDeps } from './route-deps'\nimport { outreachRouteGate, type OutreachRouteCaller } from './route-gate'\nimport {\n outreachMethodNotAllowed,\n outreachOk,\n outreachRefusal,\n readOutreachJsonBody,\n} from './route-http'\n\n/**\n * THE LINK DOMAINS ROUTE (AGL-3306): `outreach/link-domains`.\n *\n * A tracked sequence link reads `https://links.<the mailbox's domain>/<id>`\n * once the organization has set that host up and it has verified — the same\n * `links.` label, the same CNAME-and-check process, as a sending domain's\n * campaign click tracking, with this deployment in place of the mail\n * provider (`tracking-host.ts`). Until then it reads the console's own\n * `/api/outreach/l/<id>`, as it always has.\n *\n * `GET ?orgId` lists one row per sending domain of the organization's\n * connected mailboxes, plus any host still set up for a domain no mailbox\n * sends as any more (so it can be removed). `POST` sets one up — the domain\n * driver attaches the host — checks it, or removes it. Only a domain a\n * mailbox of the organization sends as may be set up: the host is a claim\n * about mail the organization actually sends.\n *\n * Setting up and removing change what this deployment serves, so they are\n * an owner's or an admin's; checking changes nothing but the verdict, and\n * the list is everyone's who may use Sequences.\n */\n\n/** The platform's tracking-host store (`@aglyn/tenant-data-admin`); specs build their own. */\nexport interface OutreachTrackingHosts {\n list(firestore: FirebaseFirestore.Firestore, orgId: string): Promise<TrackingHostRecord[]>\n setUp(input: HostInput): Promise<TrackingHostResult>\n verify(input: HostInput): Promise<TrackingHostResult>\n remove(input: HostInput): Promise<TrackingHostResult>\n}\n\ninterface HostInput {\n firestore: FirebaseFirestore.Firestore\n orgId: string\n domain: string\n nowMs: number\n}\n\nexport interface OutreachLinkDomainRouteDeps {\n hosts(): Promise<OutreachTrackingHosts>\n /** The console's own HTTPS origin, for the link prefix a domain without a host uses. */\n consoleOrigin(): string | null\n}\n\n/** The activity lines a change writes. */\nexport const OUTREACH_LINK_DOMAIN_ACTIVITY = {\n 'set-up': (host: string) => `Set up ${host} as a Sequences link domain`,\n remove: (host: string) => `Removed ${host} as a Sequences link domain`,\n} as const\n\n/** The sending domain of every connected mailbox, alphabetically. */\nasync function mailboxDomains(firestore: FirebaseFirestore.Firestore, orgId: string): Promise<string[]> {\n const snapshot = await firestore.collection('orgs').doc(orgId).collection(OUTREACH_COLLECTIONS.mailboxes).get()\n const domains = new Set<string>()\n for (const doc of snapshot.docs) {\n const mailbox = readStoredOutreachMailbox(doc.id, doc.data())\n if (!mailbox) continue\n const domain = validateTrackingHostDomain(mailbox.sendAs || mailbox.email).domain\n if (domain) domains.add(domain)\n }\n return [...domains].sort()\n}\n\nfunction row(domain: string, record: TrackingHostRecord | null, consoleOrigin: string | null): OutreachLinkDomain {\n const origin = trackingHostLinkOrigin(record)\n const detailKey = record?.lastDetail as keyof typeof TRACKING_HOST_DETAIL | null | undefined\n return {\n domain,\n host: record?.host ?? sendingTrackingHost(domain),\n status: record?.status ?? 'not-set-up',\n records: record\n ? trackingHostDnsRecords(record).map(({ type, name, value, required, note }) => ({\n type,\n name,\n value,\n required,\n note,\n }))\n : [],\n detail: detailKey && detailKey in TRACKING_HOST_DETAIL ? TRACKING_HOST_DETAIL[detailKey] : null,\n linkPrefix: origin ? `${origin}/` : consoleOrigin ? `${consoleOrigin}${OUTREACH_SHORT_LINK_PATH}/` : null,\n checkedAtMs: record?.lastCheckedAtMs ?? null,\n verifiedAtMs: record?.verifiedAtMs ?? null,\n }\n}\n\nasync function listing(\n deps: OutreachRouteDeps,\n links: OutreachLinkDomainRouteDeps,\n gate: OutreachRouteCaller,\n): Promise<OutreachLinkDomainsResponse> {\n const firestore = deps.firestore()\n const [domains, records] = await Promise.all([\n mailboxDomains(firestore, gate.orgId),\n (await links.hosts()).list(firestore, gate.orgId),\n ])\n const byDomain = new Map(records.map((record) => [record.domain, record]))\n const all = [...new Set([...domains, ...byDomain.keys()])].sort()\n const consoleOrigin = links.consoleOrigin()\n return {\n ok: true,\n domains: all.map((domain) => row(domain, byDomain.get(domain) ?? null, consoleOrigin)),\n canManage: gate.isOrgAdmin,\n }\n}\n\nexport function createOutreachLinkDomainsRoute(\n deps: OutreachRouteDeps,\n links: OutreachLinkDomainRouteDeps,\n): PluginWebApiHandler {\n return async (request) => {\n if (request.method === 'GET') {\n const gate = await outreachRouteGate(request, new URL(request.url).searchParams.get('orgId'), deps.gate)\n if (gate instanceof Response) return gate\n return outreachOk(await listing(deps, links, gate))\n }\n if (request.method !== 'POST') return outreachMethodNotAllowed('GET, POST')\n\n const body = await readOutreachJsonBody(request)\n const gate = await outreachRouteGate(request, body['orgId'], deps.gate)\n if (gate instanceof Response) return gate\n const action = body['action'] as OutreachLinkDomainRequest['action']\n if (action !== 'set-up' && action !== 'check' && action !== 'remove') {\n return outreachRefusal(400, 'invalid-request', 'Say whether to set the link domain up, check it, or remove it.')\n }\n if (action !== 'check' && !gate.isOrgAdmin) {\n return outreachRefusal(403, 'permission', 'Your role does not include \"Manage everyone’s Sequences\" — ask an organization admin')\n }\n const checked = validateTrackingHostDomain(String(body['domain'] ?? ''))\n if (!checked.domain) {\n return outreachRefusal(400, 'invalid-domain', checked.error ?? 'Type a domain, such as example.com.')\n }\n const domain = checked.domain\n const firestore = deps.firestore()\n if (action === 'set-up' && !(await mailboxDomains(firestore, gate.orgId)).includes(domain)) {\n return outreachRefusal(\n 400,\n 'invalid-domain',\n `No connected mailbox sends as ${domain}. A link domain follows the address your sequences send from.`,\n )\n }\n\n const hosts = await links.hosts()\n const input = { firestore, orgId: gate.orgId, domain, nowMs: deps.now() }\n const result =\n action === 'set-up' ? await hosts.setUp(input) : action === 'check' ? await hosts.verify(input) : await hosts.remove(input)\n if (result.error) {\n return outreachRefusal(result.status >= 400 ? result.status : 409, 'link-domain-refused', result.error)\n }\n if (action !== 'check') {\n await deps.logOrgActivity(\n gate.orgId,\n { uid: gate.uid, email: gate.email },\n OUTREACH_LINK_DOMAIN_ACTIVITY[action](sendingTrackingHost(domain)),\n { type: 'org', id: gate.orgId },\n )\n }\n return outreachOk({ ...(await listing(deps, links, gate)), domain } satisfies OutreachLinkDomainResponse)\n }\n}\n"],"names":["sendingTrackingHost","TRACKING_HOST_DETAIL","trackingHostDnsRecords","trackingHostLinkOrigin","validateTrackingHostDomain","OUTREACH_SHORT_LINK_PATH","OUTREACH_COLLECTIONS","readStoredOutreachMailbox","outreachRouteGate","outreachMethodNotAllowed","outreachOk","outreachRefusal","readOutreachJsonBody","OUTREACH_LINK_DOMAIN_ACTIVITY","host","remove","mailboxDomains","firestore","orgId","snapshot","collection","doc","mailboxes","get","domains","Set","docs","mailbox","id","data","domain","sendAs","email","add","sort","row","record","consoleOrigin","origin","detailKey","lastDetail","status","records","map","type","name","value","required","note","detail","linkPrefix","checkedAtMs","lastCheckedAtMs","verifiedAtMs","listing","deps","links","gate","Promise","all","hosts","list","byDomain","Map","keys","ok","canManage","isOrgAdmin","createOutreachLinkDomainsRoute","request","body","method","URL","url","searchParams","Response","action","checked","String","error","includes","input","nowMs","now","result","setUp","verify","logOrgActivity","uid"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SACEA,mBAAmB,EACnBC,oBAAoB,EACpBC,sBAAsB,EACtBC,sBAAsB,EACtBC,0BAA0B,QAGrB,2BAA0B;AACjC,SAASC,wBAAwB,QAAQ,2BAAuB;AAOhE,SAASC,oBAAoB,QAAQ,6BAAyB;AAC9D,SAASC,yBAAyB,QAAQ,6BAAyB;AAEnE,SAASC,iBAAiB,QAAkC,kBAAc;AAC1E,SACEC,wBAAwB,EACxBC,UAAU,EACVC,eAAe,EACfC,oBAAoB,QACf,kBAAc;AA6CrB,wCAAwC,GACxC,OAAO,MAAMC,gCAAgC;IAC3C,UAAU,CAACC,OAAiB,CAAC,OAAO,EAAEA,KAAK,2BAA2B,CAAC;IACvEC,QAAQ,CAACD,OAAiB,CAAC,QAAQ,EAAEA,KAAK,2BAA2B,CAAC;AACxE,EAAU;AAEV,mEAAmE,GACnE,eAAeE,eAAeC,SAAsC,EAAEC,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c,CACvB9B,KAAKvC,KAAK,EACV;gBAAEsE,KAAK/B,KAAK+B,GAAG;gBAAExD,OAAOyB,KAAKzB,KAAK;YAAC,GACnCnB,6BAA6B,CAAC+D,OAAO,CAAC5E,oBAAoB8B,UAC1D;gBAAEc,MAAM;gBAAOhB,IAAI6B,KAAKvC,KAAK;YAAC;QAElC;QACA,OAAOR,WAAW,aAAM,MAAM4C,QAAQC,MAAMC,OAAOC;YAAQ3B;;IAC7D;AACF"}
@@ -188,7 +188,7 @@ draft, options = {}) {
188
188
  }
189
189
  if (mailbox.connectedByUid !== caller.uid && !caller.isOrgAdmin) {
190
190
  return [
191
- issue(path, 'mailbox_not_yours', 'Only the member who connected this mailbox, or an organization owner or admin, can send from it.')
191
+ issue(path, 'mailbox_not_yours', 'Only the member who connected this mailbox, or a member holding "Manage everyone’s Sequences", can send from it.')
192
192
  ];
193
193
  }
194
194
  return [];
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/routes/sequence-routes.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { normalizeContainerIds } from '@aglyn/aglyn/app-utils/container-membership'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { nameSearchFields } from '@aglyn/aglyn/app-utils/name-search'\nimport type { PluginWebApiHandler } from '@aglyn/aglyn/server'\nimport { readOrgContainers } from '@aglyn/tenant-data-admin/server/org-containers'\nimport { applyOutreachEnrollmentEvent } from '../engine/enrollment-state'\nimport {\n validateOutreachSequence,\n validateOutreachSequenceActivation,\n} from '../engine/sequence-validation'\nimport type {\n OutreachSequenceAction,\n OutreachSequenceSaveResponse,\n OutreachSequenceStatusResponse,\n} from '../model/outreach-api'\nimport { OUTREACH_OPEN_ENROLLMENT_STATUSES } from '../engine/gates'\nimport type { OutreachMailbox, OutreachSequence, OutreachSequenceStatus } from '../model/outreach.types'\nimport {\n outreachEnrolledSequenceIssues,\n outreachMailboxActivationIssue,\n readOutreachSequenceDraft,\n type OutreachSequenceDraft,\n type OutreachSequenceIssue,\n} from '../model/sequence-draft'\nimport { readOutreachComplianceSettingsDoc } from '../storage/compliance-settings-store'\nimport {\n outreachOrgCollection,\n readStoredOutreachEnrollment,\n readStoredOutreachMailbox,\n readStoredOutreachSequence,\n} from '../storage/outreach-records'\nimport { OUTREACH_SEQUENCE_ACTIVITY_TARGET, type OutreachRouteDeps } from './route-deps'\nimport { outreachRouteGate, type OutreachRouteCaller } from './route-gate'\nimport type { OutreachRouteRefusalReason } from '../model/outreach-api'\nimport {\n outreachMethodNotAllowed,\n outreachOk,\n outreachRefusal,\n readOutreachDocumentId,\n readOutreachJsonBody,\n} from './route-http'\n\n/**\n * THE SEQUENCE ROUTES (AGL-2980): save, activate, pause, archive, delete.\n *\n * ## Who may change a sequence\n *\n * A sequence sends as the member whose mailbox it names, so it is theirs to\n * change: the member who connected the mailbox, or an organization owner or\n * admin, may save it, activate it and send from it — the same two the\n * mailbox's own routes let manage the mailbox. Anyone with `outreach.use`\n * may pause or archive any sequence, because stopping mail is never the act\n * that needs guarding.\n *\n * ## Saving\n *\n * The draft is read with the editor's reader and judged by the engine's\n * validator, so the save refuses exactly what the editor showed beside a\n * field. On top of that, the site must be one of the organization's, the\n * mailbox one of its connected mailboxes, the countries ones the\n * organization allows, and — once anyone is enrolled — the steps, site and\n * mailbox fixed (`outreachEnrolledSequenceIssues`). A new sequence is a\n * draft; an edit keeps the status it had, and an active sequence stays\n * active only because the edit passed the same validator activation does.\n *\n * ## Activating\n *\n * `validateOutreachSequenceActivation`: everything a save refuses on, and an\n * organization whose footer cannot be written — no legal name, or no postal\n * address. And its mailbox must be sending (`outreachMailboxActivationIssue`):\n * chosen, still connected, not paused, and not waiting to be reconnected —\n * the same words the sequence page shows beside its disabled Activate.\n *\n * ## Archiving\n *\n * Final. Every person still active or paused in the sequence is stopped\n * with `sequence_archived`, in batches, so no archived sequence goes on\n * sending.\n */\n\n/** A batch holds 500 writes; a page of enrollments stops this many. */\nconst ARCHIVE_PAGE = 400\n\n/** The activity line each lifecycle act writes. */\nexport const OUTREACH_SEQUENCE_ACTIVITY = {\n create: 'Created a sequence',\n activate: 'Activated a sequence',\n pause: 'Paused a sequence',\n archive: 'Archived a sequence',\n delete: 'Deleted a sequence',\n} as const\n\n/** Where each action may start, and where it ends. */\nconst TRANSITIONS: Record<\n OutreachSequenceAction,\n { from: readonly OutreachSequenceStatus[]; to: OutreachSequenceStatus }\n> = {\n activate: { from: ['draft', 'paused'], to: 'active' },\n pause: { from: ['active'], to: 'paused' },\n archive: { from: ['draft', 'active', 'paused'], to: 'archived' },\n}\n\nconst ACTION_REFUSALS: Record<OutreachSequenceAction, string> = {\n activate: 'Only a draft or paused sequence can be activated.',\n pause: 'Only an active sequence can be paused.',\n archive: 'This sequence is already archived.',\n}\n\nexport interface OutreachSequenceRoutes {\n save: PluginWebApiHandler\n status: PluginWebApiHandler\n remove: PluginWebApiHandler\n}\n\ntype Firestore = FirebaseFirestore.Firestore\n\nasync function loadSequence(\n firestore: Firestore,\n orgId: string,\n sequenceId: string,\n): Promise<OutreachSequence | null> {\n const snapshot = await outreachOrgCollection(firestore, orgId, 'sequences').doc(sequenceId).get()\n return readStoredOutreachSequence(sequenceId, snapshot.exists ? snapshot.data() : undefined)\n}\n\n/** Whether anyone was ever enrolled in the sequence. */\nasync function hasEnrollments(firestore: Firestore, orgId: string, sequenceId: string): Promise<boolean> {\n const found = await outreachOrgCollection(firestore, orgId, 'enrollments')\n .where('sequenceId', '==', sequenceId)\n .limit(1)\n .get()\n return !found.empty\n}\n\nconst issue = (\n path: string,\n code: OutreachSequenceIssue['code'],\n message: string,\n): OutreachSequenceIssue => ({ path, code, message, severity: 'error' })\n\n/**\n * The organization-level facts a draft has to agree with: its site is the\n * organization's, its mailbox is connected and the caller may send from it,\n * and its countries are ones the organization allows. `activating` adds\n * that the mailbox is sending now — chosen, and neither paused nor waiting\n * to be reconnected.\n */\nasync function draftPlacementIssues(\n firestore: Firestore,\n caller: OutreachRouteCaller,\n // A draft, or a stored sequence being activated, which may predate the\n // campaign field (AGL-3254).\n draft: Pick<OutreachSequenceDraft, 'hostId' | 'mailboxId' | 'mailboxIds' | 'settings'> &\n Pick<OutreachSequence, 'campaignIds'>,\n options: { activating?: boolean } = {},\n): Promise<OutreachSequenceIssue[]> {\n const issues: OutreachSequenceIssue[] = []\n const campaignIds = normalizeContainerIds(draft.campaignIds)\n if (draft.hostId) {\n const host = readOutreachDocumentId(draft.hostId)\n ? await firestore.collection('hosts').doc(draft.hostId).get()\n : null\n if (!host?.exists || host.get('orgId') !== caller.orgId) {\n issues.push(issue('hostId', 'host_unknown', \"Choose one of this organization's sites.\"))\n }\n } else {\n issues.push(issue('hostId', 'host_unknown', \"Choose the site whose contacts this sequence emails.\"))\n }\n const mailbox = draft.mailboxId ? await loadMailbox(firestore, caller.orgId, draft.mailboxId) : null\n const activation = options.activating ? outreachMailboxActivationIssue(draft.mailboxId, mailbox) : null\n if (draft.mailboxId) {\n const placement = mailboxIssues(caller, mailbox)\n // A mailbox that is gone is refused once, in activation's words when\n // activating: they say what to do next.\n issues.push(\n ...(activation?.code === 'mailbox_unknown'\n ? placement.filter((entry) => entry.code !== 'mailbox_unknown')\n : placement),\n )\n }\n if (activation && !issues.some((entry) => entry.code === 'mailbox_not_yours')) issues.push(activation)\n // The mailboxes it rotates through (AGL-3489) stand where its own does:\n // connected here, and the caller's to send from. One that is paused or\n // waiting to be reconnected is passed over at enroll time, not refused.\n for (const rotationId of draft.mailboxIds ?? []) {\n const rotation = await loadMailbox(firestore, caller.orgId, rotationId)\n issues.push(...mailboxIssues(caller, rotation, 'mailboxIds'))\n }\n const settings = await readOutreachComplianceSettingsDoc(firestore, caller.orgId)\n const outside = draft.settings.allowedCountries.filter(\n (code) => !settings.allowedCountries.includes(code),\n )\n if (outside.length) {\n issues.push(\n issue(\n 'settings.allowedCountries',\n 'country_not_in_org',\n `${outside.join(', ')} ${outside.length === 1 ? \"isn't\" : \"aren't\"} among the countries your organization allows. Add ${outside.length === 1 ? 'it' : 'them'} in Sequences compliance settings first.`,\n ),\n )\n }\n /*\n * The campaigns must be the ORGANIZATION's live containers of the\n * `campaign` kind (AGL-3254): a request can claim any id,\n * and a sequence filed under another org's campaign, or under one the\n * console soft-deleted, would credit its outcomes to a page nobody here\n * can open. A sequence is an org record, so any live campaign of the org\n * qualifies, whichever sites it is placed on.\n */\n if (campaignIds.length) {\n const found = await readOrgContainers(\n firestore,\n 'campaign',\n caller.orgId,\n campaignIds.map((campaignId) => readOutreachDocumentId(campaignId) ?? ''),\n )\n const unknown = campaignIds.filter(\n (campaignId, index) => !readOutreachDocumentId(campaignId) || !found[index]?.live,\n )\n if (unknown.length) {\n issues.push(\n issue(\n 'campaignIds',\n 'campaign_unknown',\n unknown.length === 1\n ? \"One of the campaigns picked isn't one of this organization's campaigns any more. Pick it again.\"\n : \"Some of the campaigns picked aren't this organization's campaigns any more. Pick them again.\",\n ),\n )\n }\n }\n return issues\n}\n\n/** A mailbox of this organization's, as stored; `null` when there is none by that id. */\nasync function loadMailbox(firestore: Firestore, orgId: string, mailboxId: string): Promise<OutreachMailbox | null> {\n const snapshot = readOutreachDocumentId(mailboxId)\n ? await outreachOrgCollection(firestore, orgId, 'mailboxes').doc(mailboxId).get()\n : null\n return readStoredOutreachMailbox(mailboxId, snapshot?.exists ? snapshot.data() : undefined)\n}\n\n/** Whether the mailbox is connected here, and the caller may send from it. */\nfunction mailboxIssues(\n caller: OutreachRouteCaller,\n mailbox: OutreachMailbox | null,\n path: 'mailboxId' | 'mailboxIds' = 'mailboxId',\n): OutreachSequenceIssue[] {\n if (!mailbox || mailbox.status === 'disconnected') {\n return [\n issue(\n path,\n 'mailbox_unknown',\n path === 'mailboxIds'\n ? 'One of the mailboxes it rotates through is not connected to this organization. Remove it.'\n : 'That mailbox is not connected to this organization.',\n ),\n ]\n }\n if (mailbox.connectedByUid !== caller.uid && !caller.isOrgAdmin) {\n return [\n issue(\n path,\n 'mailbox_not_yours',\n 'Only the member who connected this mailbox, or an organization owner or admin, can send from it.',\n ),\n ]\n }\n return []\n}\n\n/** One issue per field and code: activation and the engine can both ask for a mailbox. */\nfunction distinctIssues(issues: readonly OutreachSequenceIssue[]): OutreachSequenceIssue[] {\n const seen = new Set<string>()\n return issues.filter((entry) => {\n const key = `${entry.path}|${entry.code}`\n if (seen.has(key)) return false\n seen.add(key)\n return true\n })\n}\n\n/** What saving a sequence came to: the stored sequence, or the refusal the route answers with. */\nexport type OutreachSequenceSaveOutcome =\n | { ok: true; sequence: OutreachSequence; created: boolean; warnings: OutreachSequenceIssue[] }\n | { ok: false; status: number; code: OutreachRouteRefusalReason; message: string; issues?: OutreachSequenceIssue[] }\n\n/**\n * Saves a sequence the way the editor's Save does (see \"Saving\" above):\n * the editor's validator, the organization's placement rules and — once\n * anyone is enrolled — the fixed steps, site and mailbox. A new sequence is\n * a draft; an edit keeps its status. The save route and the package import\n * (AGL-3535) both write through here. `newId` names a new sequence's id\n * (an import keeps the package's); `judgeOnly` answers the verdict without\n * writing, for an import's dry run.\n */\nexport async function saveOutreachSequence(\n deps: Pick<OutreachRouteDeps, 'firestore' | 'now' | 'logOrgActivity'>,\n caller: OutreachRouteCaller,\n input: { sequenceId: string | null; draft: OutreachSequenceDraft; newId?: string; judgeOnly?: boolean },\n): Promise<OutreachSequenceSaveOutcome> {\n const firestore = deps.firestore()\n const { sequenceId, draft } = input\n const existing = sequenceId ? await loadSequence(firestore, caller.orgId, sequenceId) : null\n if (sequenceId && !existing && !input.newId) {\n return { ok: false, status: 404, code: 'sequence-not-found', message: 'That sequence no longer exists.' }\n }\n if (existing?.status === 'archived') {\n return { ok: false, status: 409, code: 'sequence-archived', message: \"An archived sequence can't be edited.\" }\n }\n // A sequence sends as its mailbox's member, so it is theirs (or an\n // admin's) to change — the stored mailbox as well as a new one: moving\n // a colleague's sequence onto your own mailbox is still changing theirs.\n if (existing?.mailboxId && existing.mailboxId !== draft.mailboxId) {\n const stored = mailboxIssues(caller, await loadMailbox(firestore, caller.orgId, existing.mailboxId))\n const refused = stored.find((entry) => entry.code === 'mailbox_not_yours')\n if (refused) return { ok: false, status: 403, code: 'permission', message: refused.message }\n }\n const judged: OutreachSequenceIssue[] = [\n ...validateOutreachSequence(draft),\n ...(await draftPlacementIssues(firestore, caller, draft)),\n ]\n const ownership = judged.find((entry) => entry.code === 'mailbox_not_yours')\n if (ownership) return { ok: false, status: 403, code: 'permission', message: ownership.message }\n if (existing && (await hasEnrollments(firestore, caller.orgId, existing.id))) {\n judged.push(...outreachEnrolledSequenceIssues(existing, draft))\n }\n const errors = judged.filter((entry) => entry.severity === 'error')\n if (errors.length) {\n return { ok: false, status: 400, code: 'invalid-sequence', message: errors[0].message, issues: judged }\n }\n\n const nowMs = deps.now()\n const ref = outreachOrgCollection(firestore, caller.orgId, 'sequences').doc(\n existing?.id ?? input.newId ?? createResourceUid(),\n )\n const sequence: OutreachSequence = {\n id: ref.id,\n ...draft,\n status: existing?.status ?? 'draft',\n /*\n * Carried through explicitly, because the write below REPLACES the\n * document (AGL-3239). The counters are the runtime's and the click\n * route's, never the editor's, and a member renaming a sequence must\n * not reset what it measured.\n */\n ...(existing?.stats ? { stats: existing.stats } : {}),\n createdAtMs: existing?.createdAtMs || nowMs,\n updatedAtMs: nowMs,\n }\n const warnings = judged.filter((entry) => entry.severity === 'warning')\n if (input.judgeOnly) return { ok: true, sequence, created: !existing, warnings }\n /*\n * The list's search fields ride with every write of the name (AGL-3321):\n * the sequences list asks Firestore for them, and a sequence missing\n * them would list normally and never be found.\n */\n await ref.set({ ...sequence, ...nameSearchFields(sequence.name) })\n if (!existing) {\n await deps.logOrgActivity(caller.orgId, { uid: caller.uid, email: caller.email }, OUTREACH_SEQUENCE_ACTIVITY.create, {\n type: OUTREACH_SEQUENCE_ACTIVITY_TARGET,\n id: sequence.id,\n name: sequence.name,\n })\n }\n return { ok: true, sequence, created: !existing, warnings }\n}\n\n/**\n * Deletes a draft nobody was ever enrolled in — the only sequence that may\n * be deleted: what people were sent, and why they stopped, is the record of\n * what the organization did. The delete route and a package import's undo\n * (AGL-3535) both delete through here.\n */\nexport async function removeOutreachSequence(\n deps: Pick<OutreachRouteDeps, 'firestore' | 'logOrgActivity'>,\n caller: Pick<OutreachRouteCaller, 'orgId' | 'uid' | 'email'>,\n sequenceId: string,\n): Promise<{ ok: true } | { ok: false; status: number; code: OutreachRouteRefusalReason; message: string }> {\n const firestore = deps.firestore()\n const sequence = await loadSequence(firestore, caller.orgId, sequenceId)\n if (!sequence) return { ok: false, status: 404, code: 'sequence-not-found', message: 'That sequence no longer exists.' }\n if (sequence.status !== 'draft' || (await hasEnrollments(firestore, caller.orgId, sequence.id))) {\n return {\n ok: false,\n status: 409,\n code: 'delete-refused',\n message: 'Only a draft nobody was enrolled in can be deleted. Archive this sequence instead.',\n }\n }\n await outreachOrgCollection(firestore, caller.orgId, 'sequences').doc(sequence.id).delete()\n await deps.logOrgActivity(caller.orgId, { uid: caller.uid, email: caller.email }, OUTREACH_SEQUENCE_ACTIVITY.delete, {\n type: OUTREACH_SEQUENCE_ACTIVITY_TARGET,\n id: sequence.id,\n name: sequence.name,\n })\n return { ok: true }\n}\n\nexport function createOutreachSequenceRoutes(deps: OutreachRouteDeps): OutreachSequenceRoutes {\n const activity = (caller: OutreachRouteCaller, action: string, sequence: Pick<OutreachSequence, 'id' | 'name'>) =>\n deps.logOrgActivity(caller.orgId, { uid: caller.uid, email: caller.email }, action, {\n type: OUTREACH_SEQUENCE_ACTIVITY_TARGET,\n id: sequence.id,\n name: sequence.name,\n })\n\n const save: PluginWebApiHandler = async (request) => {\n if (request.method !== 'POST') return outreachMethodNotAllowed('POST')\n const body = await readOutreachJsonBody(request)\n const caller = await outreachRouteGate(request, body['orgId'], deps.gate)\n if (caller instanceof Response) return caller\n\n const rawId = body['sequenceId']\n const sequenceId = rawId === undefined || rawId === null || rawId === '' ? null : readOutreachDocumentId(rawId)\n if (rawId && !sequenceId) return outreachRefusal(400, 'invalid-request', 'Name the sequence to save.')\n const outcome = await saveOutreachSequence(deps, caller, {\n sequenceId,\n draft: readOutreachSequenceDraft(body['sequence']),\n })\n if (outcome.ok === false) {\n return outreachRefusal(outcome.status, outcome.code, outcome.message, outcome.issues ? { issues: outcome.issues } : undefined)\n }\n return outreachOk({\n ok: true,\n sequence: outcome.sequence,\n created: outcome.created,\n warnings: outcome.warnings,\n } satisfies OutreachSequenceSaveResponse)\n }\n\n const status: PluginWebApiHandler = async (request) => {\n if (request.method !== 'POST') return outreachMethodNotAllowed('POST')\n const body = await readOutreachJsonBody(request)\n const caller = await outreachRouteGate(request, body['orgId'], deps.gate)\n if (caller instanceof Response) return caller\n const action = body['action'] as OutreachSequenceAction\n const sequenceId = readOutreachDocumentId(body['sequenceId'])\n if (!sequenceId || !Object.prototype.hasOwnProperty.call(TRANSITIONS, action)) {\n return outreachRefusal(400, 'invalid-request', 'Name the sequence, and activate, pause or archive.')\n }\n const firestore = deps.firestore()\n const sequence = await loadSequence(firestore, caller.orgId, sequenceId)\n if (!sequence) return outreachRefusal(404, 'sequence-not-found', 'That sequence no longer exists.')\n const transition = TRANSITIONS[action]\n if (sequence.status === transition.to) {\n return outreachOk({ ok: true, sequence, stoppedEnrollments: 0 } satisfies OutreachSequenceStatusResponse)\n }\n if (!transition.from.includes(sequence.status)) {\n return outreachRefusal(409, 'transition-refused', ACTION_REFUSALS[action])\n }\n\n if (action === 'activate') {\n const orgSettings = await readOutreachComplianceSettingsDoc(firestore, caller.orgId)\n const judged: OutreachSequenceIssue[] = distinctIssues([\n ...validateOutreachSequenceActivation(sequence, orgSettings),\n ...(await draftPlacementIssues(firestore, caller, sequence, { activating: true })),\n ]).filter((entry) => entry.severity === 'error')\n if (judged.length) {\n const ownership = judged.find((entry) => entry.code === 'mailbox_not_yours')\n return ownership\n ? outreachRefusal(403, 'permission', ownership.message)\n : outreachRefusal(409, 'activation-refused', judged[0].message, { issues: judged })\n }\n }\n\n const nowMs = deps.now()\n const next: OutreachSequence = { ...sequence, status: transition.to, updatedAtMs: nowMs }\n await outreachOrgCollection(firestore, caller.orgId, 'sequences')\n .doc(sequence.id)\n .update({ status: next.status, updatedAtMs: nowMs })\n const stoppedEnrollments =\n action === 'archive' ? await stopOpenEnrollments(firestore, caller, sequence.id, nowMs) : 0\n await activity(caller, OUTREACH_SEQUENCE_ACTIVITY[action], sequence)\n return outreachOk({ ok: true, sequence: next, stoppedEnrollments } satisfies OutreachSequenceStatusResponse)\n }\n\n const remove: PluginWebApiHandler = async (request) => {\n if (request.method !== 'POST') return outreachMethodNotAllowed('POST')\n const body = await readOutreachJsonBody(request)\n const caller = await outreachRouteGate(request, body['orgId'], deps.gate)\n if (caller instanceof Response) return caller\n const sequenceId = readOutreachDocumentId(body['sequenceId'])\n if (!sequenceId) return outreachRefusal(400, 'invalid-request', 'Name the sequence to delete.')\n const outcome = await removeOutreachSequence(deps, caller, sequenceId)\n if (outcome.ok === false) return outreachRefusal(outcome.status, outcome.code, outcome.message)\n return outreachOk({ ok: true })\n }\n\n return { save, status, remove }\n}\n\n/**\n * Stops everyone still active or paused in an archived sequence, a page at\n * a time, through the engine's own transition. Returns how many it stopped.\n */\nasync function stopOpenEnrollments(\n firestore: Firestore,\n caller: OutreachRouteCaller,\n sequenceId: string,\n nowMs: number,\n): Promise<number> {\n const enrollments = outreachOrgCollection(firestore, caller.orgId, 'enrollments')\n let stopped = 0\n let after: FirebaseFirestore.QueryDocumentSnapshot | null = null\n for (;;) {\n let page = enrollments.where('sequenceId', '==', sequenceId).orderBy('__name__').limit(ARCHIVE_PAGE)\n if (after) page = page.startAfter(after)\n const snapshot = await page.get()\n if (snapshot.empty) break\n const batch = firestore.batch()\n let writes = 0\n for (const doc of snapshot.docs) {\n const enrollment = readStoredOutreachEnrollment(doc.id, doc.data())\n if (!enrollment || !OUTREACH_OPEN_ENROLLMENT_STATUSES.includes(enrollment.status)) continue\n const { patch } = applyOutreachEnrollmentEvent(enrollment, {\n type: 'stop',\n reason: 'sequence_archived',\n atMs: nowMs,\n byUid: caller.uid,\n })\n if (!patch) continue\n batch.update(doc.ref, { ...patch, updatedAtMs: nowMs })\n writes += 1\n }\n if (writes) await batch.commit()\n stopped += writes\n after = snapshot.docs[snapshot.docs.length - 1]\n if (snapshot.size < ARCHIVE_PAGE) break\n }\n return stopped\n}\n"],"names":["normalizeContainerIds","createResourceUid","nameSearchFields","readOrgContainers","applyOutreachEnrollmentEvent","validateOutreachSequence","validateOutreachSequenceActivation","OUTREACH_OPEN_ENROLLMENT_STATUSES","outreachEnrolledSequenceIssues","outreachMailboxActivationIssue","readOutreachSequenceDraft","readOutreachComplianceSettingsDoc","outreachOrgCollection","readStoredOutreachEnrollment","readStoredOutreachMailbox","readStoredOutreachSequence","OUTREACH_SEQUENCE_ACTIVITY_TARGET","outreachRouteGate","outreachMethodNotAllowed","outreachOk","outreachRefusal","readOutreachDocumentId","readOutreachJsonBody","ARCHIVE_PAGE","OUTREACH_SEQUENCE_ACTIVITY","create","activate","pause","archive","delete","TRANSITIONS","from","to","ACTION_REFUSALS","loadSequence","firestore","orgId","sequenceId","snapshot","doc","get","exists","data","undefined","hasEnrollments","found","where","limit","empty","issue","path","code","message","severity","draftPlacementIssues","caller","draft","options","issues","campaignIds","hostId","host","collection","push","mailbox","mailboxId","loadMailbox","activation","activating","placement","mailboxIssues","filter","entry","some","rotationId","mailboxIds","rotation","settings","outside","allowedCountries","includes","length","join","map","campaignId","unknown","index","live","status","connectedByUid","uid","isOrgAdmin","distinctIssues","seen","Set","key","has","add","saveOutreachSequence","deps","input","existing","newId","ok","stored","refused","find","judged","ownership","id","errors","nowMs","now","ref","sequence","stats","createdAtMs","updatedAtMs","warnings","judgeOnly","created","set","name","logOrgActivity","email","type","removeOutreachSequence","createOutreachSequenceRoutes","activity","action","save","request","method","body","gate","Response","rawId","outcome","Object","prototype","hasOwnProperty","call","transition","stoppedEnrollments","orgSettings","next","update","stopOpenEnrollments","remove","enrollments","stopped","after","page","orderBy","startAfter","batch","writes","docs","enrollment","patch","reason","atMs","byUid","commit","size"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,qBAAqB,QAAQ,8CAA6C;AACnF,SAASC,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,gBAAgB,QAAQ,qCAAoC;AAErE,SAASC,iBAAiB,QAAQ,iDAAgD;AAClF,SAASC,4BAA4B,QAAQ,gCAA4B;AACzE,SACEC,wBAAwB,EACxBC,kCAAkC,QAC7B,mCAA+B;AAMtC,SAASC,iCAAiC,QAAQ,qBAAiB;AAEnE,SACEC,8BAA8B,EAC9BC,8BAA8B,EAC9BC,yBAAyB,QAGpB,6BAAyB;AAChC,SAASC,iCAAiC,QAAQ,0CAAsC;AACxF,SACEC,qBAAqB,EACrBC,4BAA4B,EAC5BC,yBAAyB,EACzBC,0BAA0B,QACrB,iCAA6B;AACpC,SAASC,iCAAiC,QAAgC,kBAAc;AACxF,SAASC,iBAAiB,QAAkC,kBAAc;AAE1E,SACEC,wBAAwB,EACxBC,UAAU,EACVC,eAAe,EACfC,sBAAsB,EACtBC,oBAAoB,QACf,kBAAc;AAErB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAoCC,GAED,qEAAqE,GACrE,MAAMC,eAAe;AAErB,iDAAiD,GACjD,OAAO,MAAMC,6BAA6B;IACxCC,QAAQ;IACRC,UAAU;IACVC,OAAO;IACPC,SAAS;IACTC,QAAQ;AACV,EAAU;AAEV,oDAAoD,GACpD,MAAMC,cAGF;IACFJ,UAAU;QAAEK,MAAM;YAAC;YAAS;SAAS;QAAEC,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WM;QACXL,QAAQjH,SAASuH,IAAI,CAACvH,SAASuH,IAAI,CAAC5E,MAAM,GAAG,EAAE;QAC/C,IAAI3C,SAAS8H,IAAI,GAAG7I,cAAc;IACpC;IACA,OAAO+H;AACT"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/routes/sequence-routes.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { normalizeContainerIds } from '@aglyn/aglyn/app-utils/container-membership'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { nameSearchFields } from '@aglyn/aglyn/app-utils/name-search'\nimport type { PluginWebApiHandler } from '@aglyn/aglyn/server'\nimport { readOrgContainers } from '@aglyn/tenant-data-admin/server/org-containers'\nimport { applyOutreachEnrollmentEvent } from '../engine/enrollment-state'\nimport {\n validateOutreachSequence,\n validateOutreachSequenceActivation,\n} from '../engine/sequence-validation'\nimport type {\n OutreachSequenceAction,\n OutreachSequenceSaveResponse,\n OutreachSequenceStatusResponse,\n} from '../model/outreach-api'\nimport { OUTREACH_OPEN_ENROLLMENT_STATUSES } from '../engine/gates'\nimport type { OutreachMailbox, OutreachSequence, OutreachSequenceStatus } from '../model/outreach.types'\nimport {\n outreachEnrolledSequenceIssues,\n outreachMailboxActivationIssue,\n readOutreachSequenceDraft,\n type OutreachSequenceDraft,\n type OutreachSequenceIssue,\n} from '../model/sequence-draft'\nimport { readOutreachComplianceSettingsDoc } from '../storage/compliance-settings-store'\nimport {\n outreachOrgCollection,\n readStoredOutreachEnrollment,\n readStoredOutreachMailbox,\n readStoredOutreachSequence,\n} from '../storage/outreach-records'\nimport { OUTREACH_SEQUENCE_ACTIVITY_TARGET, type OutreachRouteDeps } from './route-deps'\nimport { outreachRouteGate, type OutreachRouteCaller } from './route-gate'\nimport type { OutreachRouteRefusalReason } from '../model/outreach-api'\nimport {\n outreachMethodNotAllowed,\n outreachOk,\n outreachRefusal,\n readOutreachDocumentId,\n readOutreachJsonBody,\n} from './route-http'\n\n/**\n * THE SEQUENCE ROUTES (AGL-2980): save, activate, pause, archive, delete.\n *\n * ## Who may change a sequence\n *\n * A sequence sends as the member whose mailbox it names, so it is theirs to\n * change: the member who connected the mailbox, or an organization owner or\n * admin, may save it, activate it and send from it — the same two the\n * mailbox's own routes let manage the mailbox. Anyone with `outreach.use`\n * may pause or archive any sequence, because stopping mail is never the act\n * that needs guarding.\n *\n * ## Saving\n *\n * The draft is read with the editor's reader and judged by the engine's\n * validator, so the save refuses exactly what the editor showed beside a\n * field. On top of that, the site must be one of the organization's, the\n * mailbox one of its connected mailboxes, the countries ones the\n * organization allows, and — once anyone is enrolled — the steps, site and\n * mailbox fixed (`outreachEnrolledSequenceIssues`). A new sequence is a\n * draft; an edit keeps the status it had, and an active sequence stays\n * active only because the edit passed the same validator activation does.\n *\n * ## Activating\n *\n * `validateOutreachSequenceActivation`: everything a save refuses on, and an\n * organization whose footer cannot be written — no legal name, or no postal\n * address. And its mailbox must be sending (`outreachMailboxActivationIssue`):\n * chosen, still connected, not paused, and not waiting to be reconnected —\n * the same words the sequence page shows beside its disabled Activate.\n *\n * ## Archiving\n *\n * Final. Every person still active or paused in the sequence is stopped\n * with `sequence_archived`, in batches, so no archived sequence goes on\n * sending.\n */\n\n/** A batch holds 500 writes; a page of enrollments stops this many. */\nconst ARCHIVE_PAGE = 400\n\n/** The activity line each lifecycle act writes. */\nexport const OUTREACH_SEQUENCE_ACTIVITY = {\n create: 'Created a sequence',\n activate: 'Activated a sequence',\n pause: 'Paused a sequence',\n archive: 'Archived a sequence',\n delete: 'Deleted a sequence',\n} as const\n\n/** Where each action may start, and where it ends. */\nconst TRANSITIONS: Record<\n OutreachSequenceAction,\n { from: readonly OutreachSequenceStatus[]; to: OutreachSequenceStatus }\n> = {\n activate: { from: ['draft', 'paused'], to: 'active' },\n pause: { from: ['active'], to: 'paused' },\n archive: { from: ['draft', 'active', 'paused'], to: 'archived' },\n}\n\nconst ACTION_REFUSALS: Record<OutreachSequenceAction, string> = {\n activate: 'Only a draft or paused sequence can be activated.',\n pause: 'Only an active sequence can be paused.',\n archive: 'This sequence is already archived.',\n}\n\nexport interface OutreachSequenceRoutes {\n save: PluginWebApiHandler\n status: PluginWebApiHandler\n remove: PluginWebApiHandler\n}\n\ntype Firestore = FirebaseFirestore.Firestore\n\nasync function loadSequence(\n firestore: Firestore,\n orgId: string,\n sequenceId: string,\n): Promise<OutreachSequence | null> {\n const snapshot = await outreachOrgCollection(firestore, orgId, 'sequences').doc(sequenceId).get()\n return readStoredOutreachSequence(sequenceId, snapshot.exists ? snapshot.data() : undefined)\n}\n\n/** Whether anyone was ever enrolled in the sequence. */\nasync function hasEnrollments(firestore: Firestore, orgId: string, sequenceId: string): Promise<boolean> {\n const found = await outreachOrgCollection(firestore, orgId, 'enrollments')\n .where('sequenceId', '==', sequenceId)\n .limit(1)\n .get()\n return !found.empty\n}\n\nconst issue = (\n path: string,\n code: OutreachSequenceIssue['code'],\n message: string,\n): OutreachSequenceIssue => ({ path, code, message, severity: 'error' })\n\n/**\n * The organization-level facts a draft has to agree with: its site is the\n * organization's, its mailbox is connected and the caller may send from it,\n * and its countries are ones the organization allows. `activating` adds\n * that the mailbox is sending now — chosen, and neither paused nor waiting\n * to be reconnected.\n */\nasync function draftPlacementIssues(\n firestore: Firestore,\n caller: OutreachRouteCaller,\n // A draft, or a stored sequence being activated, which may predate the\n // campaign field (AGL-3254).\n draft: Pick<OutreachSequenceDraft, 'hostId' | 'mailboxId' | 'mailboxIds' | 'settings'> &\n Pick<OutreachSequence, 'campaignIds'>,\n options: { activating?: boolean } = {},\n): Promise<OutreachSequenceIssue[]> {\n const issues: OutreachSequenceIssue[] = []\n const campaignIds = normalizeContainerIds(draft.campaignIds)\n if (draft.hostId) {\n const host = readOutreachDocumentId(draft.hostId)\n ? await firestore.collection('hosts').doc(draft.hostId).get()\n : null\n if (!host?.exists || host.get('orgId') !== caller.orgId) {\n issues.push(issue('hostId', 'host_unknown', \"Choose one of this organization's sites.\"))\n }\n } else {\n issues.push(issue('hostId', 'host_unknown', \"Choose the site whose contacts this sequence emails.\"))\n }\n const mailbox = draft.mailboxId ? await loadMailbox(firestore, caller.orgId, draft.mailboxId) : null\n const activation = options.activating ? outreachMailboxActivationIssue(draft.mailboxId, mailbox) : null\n if (draft.mailboxId) {\n const placement = mailboxIssues(caller, mailbox)\n // A mailbox that is gone is refused once, in activation's words when\n // activating: they say what to do next.\n issues.push(\n ...(activation?.code === 'mailbox_unknown'\n ? placement.filter((entry) => entry.code !== 'mailbox_unknown')\n : placement),\n )\n }\n if (activation && !issues.some((entry) => entry.code === 'mailbox_not_yours')) issues.push(activation)\n // The mailboxes it rotates through (AGL-3489) stand where its own does:\n // connected here, and the caller's to send from. One that is paused or\n // waiting to be reconnected is passed over at enroll time, not refused.\n for (const rotationId of draft.mailboxIds ?? []) {\n const rotation = await loadMailbox(firestore, caller.orgId, rotationId)\n issues.push(...mailboxIssues(caller, rotation, 'mailboxIds'))\n }\n const settings = await readOutreachComplianceSettingsDoc(firestore, caller.orgId)\n const outside = draft.settings.allowedCountries.filter(\n (code) => !settings.allowedCountries.includes(code),\n )\n if (outside.length) {\n issues.push(\n issue(\n 'settings.allowedCountries',\n 'country_not_in_org',\n `${outside.join(', ')} ${outside.length === 1 ? \"isn't\" : \"aren't\"} among the countries your organization allows. Add ${outside.length === 1 ? 'it' : 'them'} in Sequences compliance settings first.`,\n ),\n )\n }\n /*\n * The campaigns must be the ORGANIZATION's live containers of the\n * `campaign` kind (AGL-3254): a request can claim any id,\n * and a sequence filed under another org's campaign, or under one the\n * console soft-deleted, would credit its outcomes to a page nobody here\n * can open. A sequence is an org record, so any live campaign of the org\n * qualifies, whichever sites it is placed on.\n */\n if (campaignIds.length) {\n const found = await readOrgContainers(\n firestore,\n 'campaign',\n caller.orgId,\n campaignIds.map((campaignId) => readOutreachDocumentId(campaignId) ?? ''),\n )\n const unknown = campaignIds.filter(\n (campaignId, index) => !readOutreachDocumentId(campaignId) || !found[index]?.live,\n )\n if (unknown.length) {\n issues.push(\n issue(\n 'campaignIds',\n 'campaign_unknown',\n unknown.length === 1\n ? \"One of the campaigns picked isn't one of this organization's campaigns any more. Pick it again.\"\n : \"Some of the campaigns picked aren't this organization's campaigns any more. Pick them again.\",\n ),\n )\n }\n }\n return issues\n}\n\n/** A mailbox of this organization's, as stored; `null` when there is none by that id. */\nasync function loadMailbox(firestore: Firestore, orgId: string, mailboxId: string): Promise<OutreachMailbox | null> {\n const snapshot = readOutreachDocumentId(mailboxId)\n ? await outreachOrgCollection(firestore, orgId, 'mailboxes').doc(mailboxId).get()\n : null\n return readStoredOutreachMailbox(mailboxId, snapshot?.exists ? snapshot.data() : undefined)\n}\n\n/** Whether the mailbox is connected here, and the caller may send from it. */\nfunction mailboxIssues(\n caller: OutreachRouteCaller,\n mailbox: OutreachMailbox | null,\n path: 'mailboxId' | 'mailboxIds' = 'mailboxId',\n): OutreachSequenceIssue[] {\n if (!mailbox || mailbox.status === 'disconnected') {\n return [\n issue(\n path,\n 'mailbox_unknown',\n path === 'mailboxIds'\n ? 'One of the mailboxes it rotates through is not connected to this organization. Remove it.'\n : 'That mailbox is not connected to this organization.',\n ),\n ]\n }\n if (mailbox.connectedByUid !== caller.uid && !caller.isOrgAdmin) {\n return [\n issue(\n path,\n 'mailbox_not_yours',\n 'Only the member who connected this mailbox, or a member holding \"Manage everyone’s Sequences\", can send from it.',\n ),\n ]\n }\n return []\n}\n\n/** One issue per field and code: activation and the engine can both ask for a mailbox. */\nfunction distinctIssues(issues: readonly OutreachSequenceIssue[]): OutreachSequenceIssue[] {\n const seen = new Set<string>()\n return issues.filter((entry) => {\n const key = `${entry.path}|${entry.code}`\n if (seen.has(key)) return false\n seen.add(key)\n return true\n })\n}\n\n/** What saving a sequence came to: the stored sequence, or the refusal the route answers with. */\nexport type OutreachSequenceSaveOutcome =\n | { ok: true; sequence: OutreachSequence; created: boolean; warnings: OutreachSequenceIssue[] }\n | { ok: false; status: number; code: OutreachRouteRefusalReason; message: string; issues?: OutreachSequenceIssue[] }\n\n/**\n * Saves a sequence the way the editor's Save does (see \"Saving\" above):\n * the editor's validator, the organization's placement rules and — once\n * anyone is enrolled — the fixed steps, site and mailbox. A new sequence is\n * a draft; an edit keeps its status. The save route and the package import\n * (AGL-3535) both write through here. `newId` names a new sequence's id\n * (an import keeps the package's); `judgeOnly` answers the verdict without\n * writing, for an import's dry run.\n */\nexport async function saveOutreachSequence(\n deps: Pick<OutreachRouteDeps, 'firestore' | 'now' | 'logOrgActivity'>,\n caller: OutreachRouteCaller,\n input: { sequenceId: string | null; draft: OutreachSequenceDraft; newId?: string; judgeOnly?: boolean },\n): Promise<OutreachSequenceSaveOutcome> {\n const firestore = deps.firestore()\n const { sequenceId, draft } = input\n const existing = sequenceId ? await loadSequence(firestore, caller.orgId, sequenceId) : null\n if (sequenceId && !existing && !input.newId) {\n return { ok: false, status: 404, code: 'sequence-not-found', message: 'That sequence no longer exists.' }\n }\n if (existing?.status === 'archived') {\n return { ok: false, status: 409, code: 'sequence-archived', message: \"An archived sequence can't be edited.\" }\n }\n // A sequence sends as its mailbox's member, so it is theirs (or an\n // admin's) to change — the stored mailbox as well as a new one: moving\n // a colleague's sequence onto your own mailbox is still changing theirs.\n if (existing?.mailboxId && existing.mailboxId !== draft.mailboxId) {\n const stored = mailboxIssues(caller, await loadMailbox(firestore, caller.orgId, existing.mailboxId))\n const refused = stored.find((entry) => entry.code === 'mailbox_not_yours')\n if (refused) return { ok: false, status: 403, code: 'permission', message: refused.message }\n }\n const judged: OutreachSequenceIssue[] = [\n ...validateOutreachSequence(draft),\n ...(await draftPlacementIssues(firestore, caller, draft)),\n ]\n const ownership = judged.find((entry) => entry.code === 'mailbox_not_yours')\n if (ownership) return { ok: false, status: 403, code: 'permission', message: ownership.message }\n if (existing && (await hasEnrollments(firestore, caller.orgId, existing.id))) {\n judged.push(...outreachEnrolledSequenceIssues(existing, draft))\n }\n const errors = judged.filter((entry) => entry.severity === 'error')\n if (errors.length) {\n return { ok: false, status: 400, code: 'invalid-sequence', message: errors[0].message, issues: judged }\n }\n\n const nowMs = deps.now()\n const ref = outreachOrgCollection(firestore, caller.orgId, 'sequences').doc(\n existing?.id ?? input.newId ?? createResourceUid(),\n )\n const sequence: OutreachSequence = {\n id: ref.id,\n ...draft,\n status: existing?.status ?? 'draft',\n /*\n * Carried through explicitly, because the write below REPLACES the\n * document (AGL-3239). The counters are the runtime's and the click\n * route's, never the editor's, and a member renaming a sequence must\n * not reset what it measured.\n */\n ...(existing?.stats ? { stats: existing.stats } : {}),\n createdAtMs: existing?.createdAtMs || nowMs,\n updatedAtMs: nowMs,\n }\n const warnings = judged.filter((entry) => entry.severity === 'warning')\n if (input.judgeOnly) return { ok: true, sequence, created: !existing, warnings }\n /*\n * The list's search fields ride with every write of the name (AGL-3321):\n * the sequences list asks Firestore for them, and a sequence missing\n * them would list normally and never be found.\n */\n await ref.set({ ...sequence, ...nameSearchFields(sequence.name) })\n if (!existing) {\n await deps.logOrgActivity(caller.orgId, { uid: caller.uid, email: caller.email }, OUTREACH_SEQUENCE_ACTIVITY.create, {\n type: OUTREACH_SEQUENCE_ACTIVITY_TARGET,\n id: sequence.id,\n name: sequence.name,\n })\n }\n return { ok: true, sequence, created: !existing, warnings }\n}\n\n/**\n * Deletes a draft nobody was ever enrolled in — the only sequence that may\n * be deleted: what people were sent, and why they stopped, is the record of\n * what the organization did. The delete route and a package import's undo\n * (AGL-3535) both delete through here.\n */\nexport async function removeOutreachSequence(\n deps: Pick<OutreachRouteDeps, 'firestore' | 'logOrgActivity'>,\n caller: Pick<OutreachRouteCaller, 'orgId' | 'uid' | 'email'>,\n sequenceId: string,\n): Promise<{ ok: true } | { ok: false; status: number; code: OutreachRouteRefusalReason; message: string }> {\n const firestore = deps.firestore()\n const sequence = await loadSequence(firestore, caller.orgId, sequenceId)\n if (!sequence) return { ok: false, status: 404, code: 'sequence-not-found', message: 'That sequence no longer exists.' }\n if (sequence.status !== 'draft' || (await hasEnrollments(firestore, caller.orgId, sequence.id))) {\n return {\n ok: false,\n status: 409,\n code: 'delete-refused',\n message: 'Only a draft nobody was enrolled in can be deleted. Archive this sequence instead.',\n }\n }\n await outreachOrgCollection(firestore, caller.orgId, 'sequences').doc(sequence.id).delete()\n await deps.logOrgActivity(caller.orgId, { uid: caller.uid, email: caller.email }, OUTREACH_SEQUENCE_ACTIVITY.delete, {\n type: OUTREACH_SEQUENCE_ACTIVITY_TARGET,\n id: sequence.id,\n name: sequence.name,\n })\n return { ok: true }\n}\n\nexport function createOutreachSequenceRoutes(deps: OutreachRouteDeps): OutreachSequenceRoutes {\n const activity = (caller: OutreachRouteCaller, action: string, sequence: Pick<OutreachSequence, 'id' | 'name'>) =>\n deps.logOrgActivity(caller.orgId, { uid: caller.uid, email: caller.email }, action, {\n type: OUTREACH_SEQUENCE_ACTIVITY_TARGET,\n id: sequence.id,\n name: sequence.name,\n })\n\n const save: PluginWebApiHandler = async (request) => {\n if (request.method !== 'POST') return outreachMethodNotAllowed('POST')\n const body = await readOutreachJsonBody(request)\n const caller = await outreachRouteGate(request, body['orgId'], deps.gate)\n if (caller instanceof Response) return caller\n\n const rawId = body['sequenceId']\n const sequenceId = rawId === undefined || rawId === null || rawId === '' ? null : readOutreachDocumentId(rawId)\n if (rawId && !sequenceId) return outreachRefusal(400, 'invalid-request', 'Name the sequence to save.')\n const outcome = await saveOutreachSequence(deps, caller, {\n sequenceId,\n draft: readOutreachSequenceDraft(body['sequence']),\n })\n if (outcome.ok === false) {\n return outreachRefusal(outcome.status, outcome.code, outcome.message, outcome.issues ? { issues: outcome.issues } : undefined)\n }\n return outreachOk({\n ok: true,\n sequence: outcome.sequence,\n created: outcome.created,\n warnings: outcome.warnings,\n } satisfies OutreachSequenceSaveResponse)\n }\n\n const status: PluginWebApiHandler = async (request) => {\n if (request.method !== 'POST') return outreachMethodNotAllowed('POST')\n const body = await readOutreachJsonBody(request)\n const caller = await outreachRouteGate(request, body['orgId'], deps.gate)\n if (caller instanceof Response) return caller\n const action = body['action'] as OutreachSequenceAction\n const sequenceId = readOutreachDocumentId(body['sequenceId'])\n if (!sequenceId || !Object.prototype.hasOwnProperty.call(TRANSITIONS, action)) {\n return outreachRefusal(400, 'invalid-request', 'Name the sequence, and activate, pause or archive.')\n }\n const firestore = deps.firestore()\n const sequence = await loadSequence(firestore, caller.orgId, sequenceId)\n if (!sequence) return outreachRefusal(404, 'sequence-not-found', 'That sequence no longer exists.')\n const transition = TRANSITIONS[action]\n if (sequence.status === transition.to) {\n return outreachOk({ ok: true, sequence, stoppedEnrollments: 0 } satisfies OutreachSequenceStatusResponse)\n }\n if (!transition.from.includes(sequence.status)) {\n return outreachRefusal(409, 'transition-refused', ACTION_REFUSALS[action])\n }\n\n if (action === 'activate') {\n const orgSettings = await readOutreachComplianceSettingsDoc(firestore, caller.orgId)\n const judged: OutreachSequenceIssue[] = distinctIssues([\n ...validateOutreachSequenceActivation(sequence, orgSettings),\n ...(await draftPlacementIssues(firestore, caller, sequence, { activating: true })),\n ]).filter((entry) => entry.severity === 'error')\n if (judged.length) {\n const ownership = judged.find((entry) => entry.code === 'mailbox_not_yours')\n return ownership\n ? outreachRefusal(403, 'permission', ownership.message)\n : outreachRefusal(409, 'activation-refused', judged[0].message, { issues: judged })\n }\n }\n\n const nowMs = deps.now()\n const next: OutreachSequence = { ...sequence, status: transition.to, updatedAtMs: nowMs }\n await outreachOrgCollection(firestore, caller.orgId, 'sequences')\n .doc(sequence.id)\n .update({ status: next.status, updatedAtMs: nowMs })\n const stoppedEnrollments =\n action === 'archive' ? await stopOpenEnrollments(firestore, caller, sequence.id, nowMs) : 0\n await activity(caller, OUTREACH_SEQUENCE_ACTIVITY[action], sequence)\n return outreachOk({ ok: true, sequence: next, stoppedEnrollments } satisfies OutreachSequenceStatusResponse)\n }\n\n const remove: PluginWebApiHandler = async (request) => {\n if (request.method !== 'POST') return outreachMethodNotAllowed('POST')\n const body = await readOutreachJsonBody(request)\n const caller = await outreachRouteGate(request, body['orgId'], deps.gate)\n if (caller instanceof Response) return caller\n const sequenceId = readOutreachDocumentId(body['sequenceId'])\n if (!sequenceId) return outreachRefusal(400, 'invalid-request', 'Name the sequence to delete.')\n const outcome = await removeOutreachSequence(deps, caller, sequenceId)\n if (outcome.ok === false) return outreachRefusal(outcome.status, outcome.code, outcome.message)\n return outreachOk({ ok: true })\n }\n\n return { save, status, remove }\n}\n\n/**\n * Stops everyone still active or paused in an archived sequence, a page at\n * a time, through the engine's own transition. Returns how many it stopped.\n */\nasync function stopOpenEnrollments(\n firestore: Firestore,\n caller: OutreachRouteCaller,\n sequenceId: string,\n nowMs: number,\n): Promise<number> {\n const enrollments = outreachOrgCollection(firestore, caller.orgId, 'enrollments')\n let stopped = 0\n let after: FirebaseFirestore.QueryDocumentSnapshot | null = null\n for (;;) {\n let page = enrollments.where('sequenceId', '==', sequenceId).orderBy('__name__').limit(ARCHIVE_PAGE)\n if (after) page = page.startAfter(after)\n const snapshot = await page.get()\n if (snapshot.empty) break\n const batch = firestore.batch()\n let writes = 0\n for (const doc of snapshot.docs) {\n const enrollment = readStoredOutreachEnrollment(doc.id, doc.data())\n if (!enrollment || !OUTREACH_OPEN_ENROLLMENT_STATUSES.includes(enrollment.status)) continue\n const { patch } = applyOutreachEnrollmentEvent(enrollment, {\n type: 'stop',\n reason: 'sequence_archived',\n atMs: nowMs,\n byUid: caller.uid,\n })\n if (!patch) continue\n batch.update(doc.ref, { ...patch, updatedAtMs: nowMs })\n writes += 1\n }\n if (writes) await batch.commit()\n stopped += writes\n after = snapshot.docs[snapshot.docs.length - 1]\n if (snapshot.size < ARCHIVE_PAGE) break\n }\n return stopped\n}\n"],"names":["normalizeContainerIds","createResourceUid","nameSearchFields","readOrgContainers","applyOutreachEnrollmentEvent","validateOutreachSequence","validateOutreachSequenceActivation","OUTREACH_OPEN_ENROLLMENT_STATUSES","outreachEnrolledSequenceIssues","outreachMailboxActivationIssue","readOutreachSequenceDraft","readOutreachComplianceSettingsDoc","outreachOrgCollection","readStoredOutreachEnrollment","readStoredOutreachMailbox","readStoredOutreachSequence","OUTREACH_SEQUENCE_ACTIVITY_TARGET","outreachRouteGate","outreachMethodNotAllowed","outreachOk","outreachRefusal","readOutreachDocumentId","readOutreachJsonBody","ARCHIVE_PAGE","OUTREACH_SEQUENCE_ACTIVITY","create","activate","pause","archive","delete","TRANSITIONS","from","to","ACTION_REFUSALS","loadSequence","firestore","orgId","sequenceId","snapshot","doc","get","exists","data","undefined","hasEnrollments","found","where","limit","empty","issue","path","code","message","severity","draftPlacementIssues","caller","draft","options","issues","campaignIds","hostId","host","collection","push","mailbox","mailboxId","loadMailbox","activation","activating","placement","mailboxIssues","filter","entry","some","rotationId","mailboxIds","rotation","settings","outside","allowedCountries","includes","length","join","map","campaignId","unknown","index","live","status","connectedByUid","uid","isOrgAdmin","distinctIssues","seen","Set","key","has","add","saveOutreachSequence","deps","input","existing","newId","ok","stored","refused","find","judged","ownership","id","errors","nowMs","now","ref","sequence","stats","createdAtMs","updatedAtMs","warnings","judgeOnly","created","set","name","logOrgActivity","email","type","removeOutreachSequence","createOutreachSequenceRoutes","activity","action","save","request","method","body","gate","Response","rawId","outcome","Object","prototype","hasOwnProperty","call","transition","stoppedEnrollments","orgSettings","next","update","stopOpenEnrollments","remove","enrollments","stopped","after","page","orderBy","startAfter","batch","writes","docs","enrollment","patch","reason","atMs","byUid","commit","size"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,qBAAqB,QAAQ,8CAA6C;AACnF,SAASC,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,gBA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d,IAAIC,QAAwD;IAC5D,OAAS;QACP,IAAIC,OAAOH,YAAYvG,KAAK,CAAC,cAAc,MAAMT,YAAYoH,OAAO,CAAC,YAAY1G,KAAK,CAACxB;QACvF,IAAIgI,OAAOC,OAAOA,KAAKE,UAAU,CAACH;QAClC,MAAMjH,WAAW,MAAMkH,KAAKhH,GAAG;QAC/B,IAAIF,SAASU,KAAK,EAAE;QACpB,MAAM2G,QAAQxH,UAAUwH,KAAK;QAC7B,IAAIC,SAAS;QACb,KAAK,MAAMrH,OAAOD,SAASuH,IAAI,CAAE;YAC/B,MAAMC,aAAajJ,6BAA6B0B,IAAIsE,EAAE,EAAEtE,IAAIG,IAAI;YAChE,IAAI,CAACoH,cAAc,CAACvJ,kCAAkCyE,QAAQ,CAAC8E,WAAWtE,MAAM,GAAG;YACnF,MAAM,EAAEuE,KAAK,EAAE,GAAG3J,6BAA6B0J,YAAY;gBACzDjC,MAAM;gBACNmC,QAAQ;gBACRC,MAAMlD;gBACNmD,OAAO3G,OAAOmC,GAAG;YACnB;YACA,IAAI,CAACqE,OAAO;YACZJ,MAAMT,MAAM,CAAC3G,IAAI0E,GAAG,EAAE,aAAK8C;gBAAO1C,aAAaN;;YAC/C6C,UAAU;QACZ;QACA,IAAIA,QAAQ,MAAMD,MAAMQ,MAAM;QAC9Bb,WAAWM;QACXL,QAAQjH,SAASuH,IAAI,CAACvH,SAASuH,IAAI,CAAC5E,MAAM,GAAG,EAAE;QAC/C,IAAI3C,SAAS8H,IAAI,GAAG7I,cAAc;IACpC;IACA,OAAO+H;AACT"}
@@ -97,7 +97,7 @@ export function createOutreachStepTestRoute(deps, testDeps) {
97
97
  const refusedBy = mailboxRefusal(mailbox);
98
98
  if (refusedBy || !mailbox) return outreachRefusal(409, 'mailbox-unavailable', refusedBy != null ? refusedBy : RECONNECT_SENTENCE);
99
99
  if (mailbox.connectedByUid !== caller.uid && !caller.isOrgAdmin) {
100
- return outreachRefusal(403, 'permission', "Only the member who connected this sequence's mailbox, or an organization owner or admin, can send a test from it.");
100
+ return outreachRefusal(403, 'permission', `Only the member who connected this sequence's mailbox, or a member holding "Manage everyone’s Sequences", can send a test from it.`);
101
101
  }
102
102
  const to = typed != null ? typed : caller.email;
103
103
  if (!to) return outreachRefusal(400, 'invalid-request', 'Type an address to send the test to.');
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/routes/step-test-routes.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { normalizeContactEmail } from '@aglyn/aglyn/app-utils/contacts'\nimport type { PluginWebApiHandler } from '@aglyn/aglyn/server'\nimport type { ComposedOutreachEmail } from '../engine/compose'\nimport { hasOutreachValidationErrors, validateOutreachSteps } from '../engine/sequence-validation'\nimport { mailboxRef } from '../mailboxes/mailbox-credentials'\nimport { outreachLocalDay } from '../mailboxes/mailbox-settings'\nimport {\n markOutreachMailboxReconnectRequired,\n type OpenedOutreachMailbox,\n} from '../mailboxes/mailbox-transport'\nimport type { OutreachStepTestResponse } from '../model/outreach-api'\nimport { OUTREACH_COLLECTIONS, type OutreachMailbox } from '../model/outreach.types'\nimport { previewOutreachStep } from '../model/step-preview'\nimport {\n newOutreachLinkId,\n OUTREACH_TEST_LINK_ENROLLMENT,\n outreachStoredLink,\n outreachStoredOpen,\n type OutreachStoredLink,\n type OutreachStoredOpen,\n} from '../runtime/click-link'\nimport { readStoredOutreachMailbox } from '../storage/outreach-records'\nimport { GmailTransportError, googleFailureAnswer } from '../transport/gmail-errors'\nimport { Rfc5322MessageError } from '../transport/rfc5322'\nimport { sendComposedOutreachEmail } from '../transport/send-message'\nimport { readOutreachStepRender } from './preview-routes'\nimport type { OutreachRouteDeps } from './route-deps'\nimport { outreachMethodNotAllowed, outreachOk, outreachRefusal, readOutreachJsonBody } from './route-http'\n\n/**\n * A TEST OF ONE STEP, IN A REAL INBOX (AGL-3325): `outreach/steps/test`.\n *\n * The Mailboxes page's test proves a mailbox can send; this proves what a\n * step LOOKS like once it has been through Gmail. It is the preview's email\n * — the same reader, the same person or sample person, the same personal\n * line, the same footer — sent through the sequence's mailbox to the member\n * who asked, or to an address they typed, with `[Test] ` in front of the\n * subject so it never reads as real mail.\n *\n * ## Rendered as a send, sent as a test\n *\n * A later step in a thread is written as `Re:` the thread's subject, as the\n * preview writes it, but sent as a new message: there is no thread to\n * answer, and the preview's placeholder message id must not leave the\n * server. When the sequence counts clicks, every link is rewritten to a\n * short link as a real send's would be, so the member sees the link their\n * recipients will see — but each is stored as a TEST link, which the click\n * route follows and never records (`click-link.ts`). A member clicking their\n * own test must not move the sequence's `clicks` or `machineClicks`.\n *\n * Merge fields the person has nothing for are sent empty and named in the\n * answer, where a real send would pause: the point of a test is to see the\n * gap, not to be refused it.\n *\n * ## Counted on nothing but the mailbox's tests\n *\n * A test is a real Gmail send and spends the account's own limits. It is\n * not a person emailed: it moves neither the sequence's `stats` nor the\n * mailbox's `health.daily.<day>.sent`, it reserves nothing of the daily cap,\n * it files nothing on anyone's record, and it enrolls nobody. It is tallied\n * on `health.daily.<day>.tests`, which the Mailboxes card shows as \"Tests\n * today\", and held to {@link OUTREACH_STEP_TESTS_PER_HOUR} a mailbox.\n *\n * ## Who, and from what\n *\n * The mailbox's own member, or an organization owner or admin — the people\n * who may edit and activate the sequence. A paused mailbox, or one waiting\n * to be reconnected, refuses and says which; a member who cannot send is\n * told where to fix it rather than shown a Google error.\n */\n\n/** Tests one mailbox may send in an hour: a few steps for a few people. */\nexport const OUTREACH_STEP_TESTS_PER_HOUR = 20\n\n/** What every test's subject starts with. */\nexport const OUTREACH_TEST_SUBJECT_PREFIX = '[Test] '\n\n/** The route's reach beyond the shared route deps: the mailbox's Gmail, the limit, the links. */\nexport interface OutreachStepTestDeps {\n /** Opens a mailbox's Gmail client from its sealed grant. */\n openMailbox(mailboxId: string): Promise<OpenedOutreachMailbox>\n consumeRateLimit(key: string, options: { limit: number; windowMs: number }): Promise<{ allowed: boolean }>\n /** The short tracking link for a stored link's id, or `null` when none can be made. */\n clickLinkUrl(linkId: string, trackingOrigin?: string | null): string | null\n /** The click-tracking origin for mail sent as `senderAddress` (AGL-3306), or `null` for the console's. */\n clickLinkOrigin?(input: { orgId: string; senderAddress: string }): Promise<string | null>\n}\n\n/** What the route answers: the response the console reads, and the fields the test sent empty. */\nexport interface OutreachStepTestAnswer extends OutreachStepTestResponse {\n unresolvedFields: string[]\n}\n\nconst RECONNECT_SENTENCE =\n \"This sequence's mailbox needs to be connected again before it can send. Reconnect it on the Mailboxes page.\"\n\n/** Why the mailbox cannot send a test now, in a sentence, or `null`. */\nfunction mailboxRefusal(mailbox: OutreachMailbox | null): string | null {\n if (!mailbox) return 'This sequence has no mailbox. Choose one and save before sending a test.'\n if (mailbox.status === 'paused') {\n return \"This sequence's mailbox is paused. Resume it on the Mailboxes page before sending a test.\"\n }\n if (mailbox.status === 'reconnect_required' || mailbox.status === 'disconnected') return RECONNECT_SENTENCE\n return null\n}\n\nexport function createOutreachStepTestRoute(\n deps: OutreachRouteDeps,\n testDeps: OutreachStepTestDeps,\n): PluginWebApiHandler {\n return async (request) => {\n if (request.method !== 'POST') return outreachMethodNotAllowed('POST')\n const body = await readOutreachJsonBody(request)\n // The address the member typed, when they typed one — read before any\n // record, so a typo is answered before a Gmail call.\n const named = typeof body['to'] === 'string' ? body['to'].trim() : ''\n const typed = named ? normalizeContactEmail(named) : null\n if (named && !typed) {\n return outreachRefusal(400, 'invalid-request', `\"${named}\" isn't a valid email address.`)\n }\n const loaded = await readOutreachStepRender(deps, request, body)\n if (loaded instanceof Response) return loaded\n const { caller, sequence, stepIndex, mailbox } = loaded\n\n const refusedBy = mailboxRefusal(mailbox)\n if (refusedBy || !mailbox) return outreachRefusal(409, 'mailbox-unavailable', refusedBy ?? RECONNECT_SENTENCE)\n if (mailbox.connectedByUid !== caller.uid && !caller.isOrgAdmin) {\n return outreachRefusal(\n 403,\n 'permission',\n \"Only the member who connected this sequence's mailbox, or an organization owner or admin, can send a test from it.\",\n )\n }\n const to = typed ?? caller.email\n if (!to) return outreachRefusal(400, 'invalid-request', 'Type an address to send the test to.')\n // The rules every sequence email keeps, asked of the stored steps: a\n // sequence saved under an older rule is refused rather than sent broken.\n const issues = validateOutreachSteps(sequence.steps)\n if (hasOutreachValidationErrors(issues)) {\n return outreachRefusal(400, 'invalid-sequence', \"Fix the sequence's steps before sending a test.\", { issues })\n }\n const limited = await testDeps.consumeRateLimit(`outreach-step-test:${mailbox.id}`, {\n limit: OUTREACH_STEP_TESTS_PER_HOUR,\n windowMs: 60 * 60 * 1000,\n })\n if (!limited.allowed) {\n return outreachRefusal(\n 429,\n 'rate-limited',\n `A mailbox can send ${OUTREACH_STEP_TESTS_PER_HOUR} tests an hour. Try again later.`,\n )\n }\n\n const firestore = deps.firestore()\n const nowMs = deps.now()\n const sender = { address: mailbox.sendAs || mailbox.email, name: mailbox.displayName || null }\n /*\n * The links, as a real send would rewrite them (AGL-3239, AGL-3297) and\n * marked as a test's: the member sees what a recipient sees, and their\n * own click counts for nothing.\n */\n let linkOrigin: string | null = null\n if ((sequence.settings.trackClicks || sequence.settings.countOpens) && testDeps.clickLinkOrigin) {\n linkOrigin = await testDeps\n .clickLinkOrigin({ orgId: caller.orgId, senderAddress: sender.address })\n .catch(() => null)\n }\n const shortLinks: Array<{ id: string; doc: OutreachStoredLink }> = []\n const rewriteLink = sequence.settings.trackClicks\n ? (link: { url: string; index: number }) => {\n const doc = outreachStoredLink(\n {\n orgId: caller.orgId,\n enrollmentId: OUTREACH_TEST_LINK_ENROLLMENT,\n stepIndex,\n linkIndex: link.index,\n url: link.url,\n test: true,\n },\n nowMs,\n )\n const id = newOutreachLinkId()\n const url = doc ? testDeps.clickLinkUrl(id, linkOrigin) : null\n if (!doc || !url) return null\n shortLinks.push({ id, doc: { ...doc, sequenceId: sequence.id } })\n return url\n }\n : null\n /*\n * The tracking image (AGL-3395), as a real send would carry it and\n * marked as a test's: the member sees both parts a recipient gets, and\n * their own open is recorded nowhere.\n */\n let pixel: { id: string; doc: OutreachStoredOpen; url: string } | null = null\n if (sequence.settings.countOpens) {\n const doc = outreachStoredOpen(\n { orgId: caller.orgId, enrollmentId: OUTREACH_TEST_LINK_ENROLLMENT, stepIndex, test: true },\n nowMs,\n )\n const id = newOutreachLinkId()\n const url = doc ? testDeps.clickLinkUrl(id, linkOrigin) : null\n if (doc && url) pixel = { id, doc: { ...doc, sequenceId: sequence.id }, url }\n }\n let composed = previewOutreachStep({ ...loaded.input, rewriteLink, openPixelUrl: pixel?.url ?? null })\n if (composed.error || !composed.email) {\n return outreachRefusal(409, 'invalid-sequence', composed.error?.message ?? \"This email can't be written yet.\")\n }\n if (shortLinks.length || pixel) {\n try {\n const batch = firestore.batch()\n for (const link of shortLinks) {\n batch.create(firestore.collection(OUTREACH_COLLECTIONS.links).doc(link.id), link.doc)\n }\n if (pixel) batch.create(firestore.collection(OUTREACH_COLLECTIONS.links).doc(pixel.id), pixel.doc)\n await batch.commit()\n } catch (error) {\n // A link that resolves nowhere is worse than one shown as written:\n // the test goes out with the step's own links, as plain text.\n console.error('[outreach] the test links could not be stored; the test carries the links as written', error)\n composed = previewOutreachStep({ ...loaded.input, rewriteLink: null })\n if (composed.error || !composed.email) {\n return outreachRefusal(409, 'invalid-sequence', composed.error?.message ?? \"This email can't be written yet.\")\n }\n }\n }\n\n const opened = await testDeps.openMailbox(mailbox.id)\n if (opened.ok === false) {\n if (opened.reason === 'not-configured') {\n return outreachRefusal(503, 'mailbox-unavailable', \"Google mailboxes aren't set up on this deployment.\")\n }\n await markOutreachMailboxReconnectRequired(firestore, {\n orgId: caller.orgId,\n mailboxId: mailbox.id,\n errorCode: opened.reason,\n nowMs,\n })\n return outreachRefusal(409, 'mailbox-unavailable', RECONNECT_SENTENCE)\n }\n /*\n * The preview's email, addressed to the member: `[Test]` in front, and a\n * `Re:` step sent as a new message — no thread id, no `In-Reply-To`, no\n * `References` — since the thread it answers exists only on screen. The\n * unsubscribe header is left off: it names an enrollment, and there is\n * none.\n */\n const email: ComposedOutreachEmail = {\n to,\n subject: `${OUTREACH_TEST_SUBJECT_PREFIX}${composed.email.subject}`,\n text: composed.email.text,\n ...(composed.email.html ? { html: composed.email.html } : {}),\n trackedLinks: composed.email.trackedLinks,\n }\n let subject: string\n try {\n subject = (await sendComposedOutreachEmail(opened.client, email, sender)).subject\n } catch (error) {\n if (error instanceof GmailTransportError && error.reconnectRequired) {\n await markOutreachMailboxReconnectRequired(firestore, {\n orgId: caller.orgId,\n mailboxId: mailbox.id,\n errorCode: error.code,\n nowMs,\n })\n return outreachRefusal(409, 'mailbox-unavailable', 'Google refused this mailbox’s access. Connect it again.')\n }\n if (error instanceof Rfc5322MessageError) {\n return outreachRefusal(400, 'invalid-request', `The test could not be written: ${error.message}`)\n }\n const answer = googleFailureAnswer(error, 'step test send')\n return outreachRefusal(answer.status, answer.reason, answer.error)\n }\n\n const testsToday = await countTest(firestore, caller.orgId, mailbox, nowMs)\n return outreachOk({\n ok: true,\n stepIndex,\n sentTo: to,\n subject,\n sentAtMs: nowMs,\n testsToday,\n unresolvedFields: composed.unresolvedFields,\n } satisfies OutreachStepTestAnswer)\n }\n}\n\n/**\n * One more test on the mailbox's local day, in `health.daily.<day>.tests`\n * beside the day's sends and never in them. Bookkeeping beside the act: the\n * email has left, so a failure is logged and answered as no count.\n */\nasync function countTest(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n mailbox: OutreachMailbox,\n nowMs: number,\n): Promise<number> {\n const ref = mailboxRef(firestore, orgId, mailbox.id)\n try {\n return await firestore.runTransaction(async (transaction) => {\n const snapshot = await transaction.get(ref)\n const stored = readStoredOutreachMailbox(mailbox.id, snapshot.exists ? snapshot.data() : undefined)\n if (!stored) return 0\n const day = outreachLocalDay(nowMs, stored.timezone)\n const counts = stored.health?.daily?.[day] ?? { sent: 0, bounces: 0, replies: 0 }\n const tests = Math.max(0, Number(counts.tests) || 0) + 1\n transaction.update(ref, { [`health.daily.${day}`]: { ...counts, tests }, updatedAtMs: nowMs })\n return tests\n })\n } catch (error) {\n console.warn('[outreach] a test send could not be counted on its mailbox', error)\n return 0\n }\n}\n"],"names":["normalizeContactEmail","hasOutreachValidationErrors","validateOutreachSteps","mailboxRef","outreachLocalDay","markOutreachMailboxReconnectRequired","OUTREACH_COLLECTIONS","previewOutreachStep","newOutreachLinkId","OUTREACH_TEST_LINK_ENROLLMENT","outreachStoredLink","outreachStoredOpen","readStoredOutreachMailbox","GmailTransportError","googleFailureAnswer","Rfc5322MessageError","sendComposedOutreachEmail","readOutreachStepRender","outreachMethodNotAllowed","outreachOk","outreachRefusal","readOutreachJsonBody","OUTREACH_STEP_TESTS_PER_HOUR","OUTREACH_TEST_SUBJECT_PREFIX","RECONNECT_SENTENCE","mailboxRefusal","mailbox","status","createOutreachStepTestRoute","deps","testDeps","request","method","body","named","trim","typed","loaded","Response","caller","sequence","stepIndex","refusedBy","connectedByUid","uid","isOrgAdmin","to","email","issues","steps","limited","consumeRateLimit","id","limit","windowMs","allowed","firestore","nowMs","now","sender","address","sendAs","name","displayName","linkOrigin","settings","trackClicks","countOpens","clickLinkOrigin","orgId","senderAddress","catch","shortLinks","rewriteLink","link","doc","enrollmentId","linkIndex","index","url","test","clickLinkUrl","push","sequenceId","pixel","composed","input","openPixelUrl","error","message","length","batch","create","collection","links","commit","console","opened","openMailbox","ok","reason","mailboxId","errorCode","subject","text","html","trackedLinks","client","reconnectRequired","code","answer","testsToday","countTest","sentTo","sentAtMs","unresolvedFields","ref","runTransaction","transaction","stored","snapshot","get","exists","data","undefined","day","timezone","counts","health","daily","sent","bounces","replies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/plugins/outreach/src/lib/routes/step-test-routes.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { normalizeContactEmail } from '@aglyn/aglyn/app-utils/contacts'\nimport type { PluginWebApiHandler } from '@aglyn/aglyn/server'\nimport type { ComposedOutreachEmail } from '../engine/compose'\nimport { hasOutreachValidationErrors, validateOutreachSteps } from '../engine/sequence-validation'\nimport { mailboxRef } from '../mailboxes/mailbox-credentials'\nimport { outreachLocalDay } from '../mailboxes/mailbox-settings'\nimport {\n markOutreachMailboxReconnectRequired,\n type OpenedOutreachMailbox,\n} from '../mailboxes/mailbox-transport'\nimport type { OutreachStepTestResponse } from '../model/outreach-api'\nimport { OUTREACH_COLLECTIONS, type OutreachMailbox } from '../model/outreach.types'\nimport { previewOutreachStep } from '../model/step-preview'\nimport {\n newOutreachLinkId,\n OUTREACH_TEST_LINK_ENROLLMENT,\n outreachStoredLink,\n outreachStoredOpen,\n type OutreachStoredLink,\n type OutreachStoredOpen,\n} from '../runtime/click-link'\nimport { readStoredOutreachMailbox } from '../storage/outreach-records'\nimport { GmailTransportError, googleFailureAnswer } from '../transport/gmail-errors'\nimport { Rfc5322MessageError } from '../transport/rfc5322'\nimport { sendComposedOutreachEmail } from '../transport/send-message'\nimport { readOutreachStepRender } from './preview-routes'\nimport type { OutreachRouteDeps } from './route-deps'\nimport { outreachMethodNotAllowed, outreachOk, outreachRefusal, readOutreachJsonBody } from './route-http'\n\n/**\n * A TEST OF ONE STEP, IN A REAL INBOX (AGL-3325): `outreach/steps/test`.\n *\n * The Mailboxes page's test proves a mailbox can send; this proves what a\n * step LOOKS like once it has been through Gmail. It is the preview's email\n * — the same reader, the same person or sample person, the same personal\n * line, the same footer — sent through the sequence's mailbox to the member\n * who asked, or to an address they typed, with `[Test] ` in front of the\n * subject so it never reads as real mail.\n *\n * ## Rendered as a send, sent as a test\n *\n * A later step in a thread is written as `Re:` the thread's subject, as the\n * preview writes it, but sent as a new message: there is no thread to\n * answer, and the preview's placeholder message id must not leave the\n * server. When the sequence counts clicks, every link is rewritten to a\n * short link as a real send's would be, so the member sees the link their\n * recipients will see — but each is stored as a TEST link, which the click\n * route follows and never records (`click-link.ts`). A member clicking their\n * own test must not move the sequence's `clicks` or `machineClicks`.\n *\n * Merge fields the person has nothing for are sent empty and named in the\n * answer, where a real send would pause: the point of a test is to see the\n * gap, not to be refused it.\n *\n * ## Counted on nothing but the mailbox's tests\n *\n * A test is a real Gmail send and spends the account's own limits. It is\n * not a person emailed: it moves neither the sequence's `stats` nor the\n * mailbox's `health.daily.<day>.sent`, it reserves nothing of the daily cap,\n * it files nothing on anyone's record, and it enrolls nobody. It is tallied\n * on `health.daily.<day>.tests`, which the Mailboxes card shows as \"Tests\n * today\", and held to {@link OUTREACH_STEP_TESTS_PER_HOUR} a mailbox.\n *\n * ## Who, and from what\n *\n * The mailbox's own member, or an organization owner or admin — the people\n * who may edit and activate the sequence. A paused mailbox, or one waiting\n * to be reconnected, refuses and says which; a member who cannot send is\n * told where to fix it rather than shown a Google error.\n */\n\n/** Tests one mailbox may send in an hour: a few steps for a few people. */\nexport const OUTREACH_STEP_TESTS_PER_HOUR = 20\n\n/** What every test's subject starts with. */\nexport const OUTREACH_TEST_SUBJECT_PREFIX = '[Test] '\n\n/** The route's reach beyond the shared route deps: the mailbox's Gmail, the limit, the links. */\nexport interface OutreachStepTestDeps {\n /** Opens a mailbox's Gmail client from its sealed grant. */\n openMailbox(mailboxId: string): Promise<OpenedOutreachMailbox>\n consumeRateLimit(key: string, options: { limit: number; windowMs: number }): Promise<{ allowed: boolean }>\n /** The short tracking link for a stored link's id, or `null` when none can be made. */\n clickLinkUrl(linkId: string, trackingOrigin?: string | null): string | null\n /** The click-tracking origin for mail sent as `senderAddress` (AGL-3306), or `null` for the console's. */\n clickLinkOrigin?(input: { orgId: string; senderAddress: string }): Promise<string | null>\n}\n\n/** What the route answers: the response the console reads, and the fields the test sent empty. */\nexport interface OutreachStepTestAnswer extends OutreachStepTestResponse {\n unresolvedFields: string[]\n}\n\nconst RECONNECT_SENTENCE =\n \"This sequence's mailbox needs to be connected again before it can send. Reconnect it on the Mailboxes page.\"\n\n/** Why the mailbox cannot send a test now, in a sentence, or `null`. */\nfunction mailboxRefusal(mailbox: OutreachMailbox | null): string | null {\n if (!mailbox) return 'This sequence has no mailbox. Choose one and save before sending a test.'\n if (mailbox.status === 'paused') {\n return \"This sequence's mailbox is paused. Resume it on the Mailboxes page before sending a test.\"\n }\n if (mailbox.status === 'reconnect_required' || mailbox.status === 'disconnected') return RECONNECT_SENTENCE\n return null\n}\n\nexport function createOutreachStepTestRoute(\n deps: OutreachRouteDeps,\n testDeps: OutreachStepTestDeps,\n): PluginWebApiHandler {\n return async (request) => {\n if (request.method !== 'POST') return outreachMethodNotAllowed('POST')\n const body = await readOutreachJsonBody(request)\n // The address the member typed, when they typed one — read before any\n // record, so a typo is answered before a Gmail call.\n const named = typeof body['to'] === 'string' ? body['to'].trim() : ''\n const typed = named ? normalizeContactEmail(named) : null\n if (named && !typed) {\n return outreachRefusal(400, 'invalid-request', `\"${named}\" isn't a valid email address.`)\n }\n const loaded = await readOutreachStepRender(deps, request, body)\n if (loaded instanceof Response) return loaded\n const { caller, sequence, stepIndex, mailbox } = loaded\n\n const refusedBy = mailboxRefusal(mailbox)\n if (refusedBy || !mailbox) return outreachRefusal(409, 'mailbox-unavailable', refusedBy ?? RECONNECT_SENTENCE)\n if (mailbox.connectedByUid !== caller.uid && !caller.isOrgAdmin) {\n return outreachRefusal(\n 403,\n 'permission',\n `Only the member who connected this sequence's mailbox, or a member holding \"Manage everyone’s Sequences\", can send a test from it.`,\n )\n }\n const to = typed ?? caller.email\n if (!to) return outreachRefusal(400, 'invalid-request', 'Type an address to send the test to.')\n // The rules every sequence email keeps, asked of the stored steps: a\n // sequence saved under an older rule is refused rather than sent broken.\n const issues = validateOutreachSteps(sequence.steps)\n if (hasOutreachValidationErrors(issues)) {\n return outreachRefusal(400, 'invalid-sequence', \"Fix the sequence's steps before sending a test.\", { issues })\n }\n const limited = await testDeps.consumeRateLimit(`outreach-step-test:${mailbox.id}`, {\n limit: OUTREACH_STEP_TESTS_PER_HOUR,\n windowMs: 60 * 60 * 1000,\n })\n if (!limited.allowed) {\n return outreachRefusal(\n 429,\n 'rate-limited',\n `A mailbox can send ${OUTREACH_STEP_TESTS_PER_HOUR} tests an hour. Try again later.`,\n )\n }\n\n const firestore = deps.firestore()\n const nowMs = deps.now()\n const sender = { address: mailbox.sendAs || mailbox.email, name: mailbox.displayName || null }\n /*\n * The links, as a real send would rewrite them (AGL-3239, AGL-3297) and\n * marked as a test's: the member sees what a recipient sees, and their\n * own click counts for nothing.\n */\n let linkOrigin: string | null = null\n if ((sequence.settings.trackClicks || sequence.settings.countOpens) && testDeps.clickLinkOrigin) {\n linkOrigin = await testDeps\n .clickLinkOrigin({ orgId: caller.orgId, senderAddress: sender.address })\n .catch(() => null)\n }\n const shortLinks: Array<{ id: string; doc: OutreachStoredLink }> = []\n const rewriteLink = sequence.settings.trackClicks\n ? (link: { url: string; index: number }) => {\n const doc = outreachStoredLink(\n {\n orgId: caller.orgId,\n enrollmentId: OUTREACH_TEST_LINK_ENROLLMENT,\n stepIndex,\n linkIndex: link.index,\n url: link.url,\n test: true,\n },\n nowMs,\n )\n const id = newOutreachLinkId()\n const url = doc ? testDeps.clickLinkUrl(id, linkOrigin) : null\n if (!doc || !url) return null\n shortLinks.push({ id, doc: { ...doc, sequenceId: sequence.id } })\n return url\n }\n : null\n /*\n * The tracking image (AGL-3395), as a real send would carry it and\n * marked as a test's: the member sees both parts a recipient gets, and\n * their own open is recorded nowhere.\n */\n let pixel: { id: string; doc: OutreachStoredOpen; url: string } | null = null\n if (sequence.settings.countOpens) {\n const doc = outreachStoredOpen(\n { orgId: caller.orgId, enrollmentId: OUTREACH_TEST_LINK_ENROLLMENT, stepIndex, test: true },\n nowMs,\n )\n const id = newOutreachLinkId()\n const url = doc ? testDeps.clickLinkUrl(id, linkOrigin) : null\n if (doc && url) pixel = { id, doc: { ...doc, sequenceId: sequence.id }, url }\n }\n let composed = previewOutreachStep({ ...loaded.input, rewriteLink, openPixelUrl: pixel?.url ?? null })\n if (composed.error || !composed.email) {\n return outreachRefusal(409, 'invalid-sequence', composed.error?.message ?? \"This email can't be written yet.\")\n }\n if (shortLinks.length || pixel) {\n try {\n const batch = firestore.batch()\n for (const link of shortLinks) {\n batch.create(firestore.collection(OUTREACH_COLLECTIONS.links).doc(link.id), link.doc)\n }\n if (pixel) batch.create(firestore.collection(OUTREACH_COLLECTIONS.links).doc(pixel.id), pixel.doc)\n await batch.commit()\n } catch (error) {\n // A link that resolves nowhere is worse than one shown as written:\n // the test goes out with the step's own links, as plain text.\n console.error('[outreach] the test links could not be stored; the test carries the links as written', error)\n composed = previewOutreachStep({ ...loaded.input, rewriteLink: null })\n if (composed.error || !composed.email) {\n return outreachRefusal(409, 'invalid-sequence', composed.error?.message ?? \"This email can't be written yet.\")\n }\n }\n }\n\n const opened = await testDeps.openMailbox(mailbox.id)\n if (opened.ok === false) {\n if (opened.reason === 'not-configured') {\n return outreachRefusal(503, 'mailbox-unavailable', \"Google mailboxes aren't set up on this deployment.\")\n }\n await markOutreachMailboxReconnectRequired(firestore, {\n orgId: caller.orgId,\n mailboxId: mailbox.id,\n errorCode: opened.reason,\n nowMs,\n })\n return outreachRefusal(409, 'mailbox-unavailable', RECONNECT_SENTENCE)\n }\n /*\n * The preview's email, addressed to the member: `[Test]` in front, and a\n * `Re:` step sent as a new message — no thread id, no `In-Reply-To`, no\n * `References` — since the thread it answers exists only on screen. The\n * unsubscribe header is left off: it names an enrollment, and there is\n * none.\n */\n const email: ComposedOutreachEmail = {\n to,\n subject: `${OUTREACH_TEST_SUBJECT_PREFIX}${composed.email.subject}`,\n text: composed.email.text,\n ...(composed.email.html ? { html: composed.email.html } : {}),\n trackedLinks: composed.email.trackedLinks,\n }\n let subject: string\n try {\n subject = (await sendComposedOutreachEmail(opened.client, email, sender)).subject\n } catch (error) {\n if (error instanceof GmailTransportError && error.reconnectRequired) {\n await markOutreachMailboxReconnectRequired(firestore, {\n orgId: caller.orgId,\n mailboxId: mailbox.id,\n errorCode: error.code,\n nowMs,\n })\n return outreachRefusal(409, 'mailbox-unavailable', 'Google refused this mailbox’s access. Connect it again.')\n }\n if (error instanceof Rfc5322MessageError) {\n return outreachRefusal(400, 'invalid-request', `The test could not be written: ${error.message}`)\n }\n const answer = googleFailureAnswer(error, 'step test send')\n return outreachRefusal(answer.status, answer.reason, answer.error)\n }\n\n const testsToday = await countTest(firestore, caller.orgId, mailbox, nowMs)\n return outreachOk({\n ok: true,\n stepIndex,\n sentTo: to,\n subject,\n sentAtMs: nowMs,\n testsToday,\n unresolvedFields: composed.unresolvedFields,\n } satisfies OutreachStepTestAnswer)\n }\n}\n\n/**\n * One more test on the mailbox's local day, in `health.daily.<day>.tests`\n * beside the day's sends and never in them. Bookkeeping beside the act: the\n * email has left, so a failure is logged and answered as no count.\n */\nasync function countTest(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n mailbox: OutreachMailbox,\n nowMs: number,\n): Promise<number> {\n const ref = mailboxRef(firestore, orgId, mailbox.id)\n try {\n return await firestore.runTransaction(async (transaction) => {\n const snapshot = await transaction.get(ref)\n const stored = readStoredOutreachMailbox(mailbox.id, snapshot.exists ? snapshot.data() : undefined)\n if (!stored) return 0\n const day = outreachLocalDay(nowMs, stored.timezone)\n const counts = stored.health?.daily?.[day] ?? { sent: 0, bounces: 0, replies: 0 }\n const tests = Math.max(0, Number(counts.tests) || 0) + 1\n transaction.update(ref, { [`health.daily.${day}`]: { ...counts, tests }, updatedAtMs: nowMs })\n return tests\n })\n } catch (error) {\n console.warn('[outreach] a test send could not be counted on its mailbox', error)\n return 0\n }\n}\n"],"names":["normalizeContactEmail","hasOutreachValidationErrors","validateOutreachSteps","mailboxRef","outreachLocalDay","markOutreachMailboxReconnectRequired","OUTREACH_COLLECTIONS","previewOutreachStep","newOutreachLinkId","OUTREACH_TEST_LINK_ENROLLMENT","outreachStoredLink","outreachStoredOpen","readStoredOutreachMailbox","GmailTransportError","googleFailureAnswer","Rfc5322MessageError","sendComposedOutreachEmail","readOutreachStepRender","outreachMethodNotAllowed","outreachOk","outreachRefusal","readOutreachJsonBody","OUTREACH_STEP_TESTS_PER_HOUR","OUTREACH_TEST_SUBJECT_PREFIX","RECONNECT_SENTENCE","mailboxRefusal","mailbox","status","createOutreachStepTestRoute","deps","testDeps","request","method","body","named","trim","typed","loaded","Response","caller","sequence","stepIndex","refusedBy","connectedByUid","uid","isOrgAdmin","to","email","issues","steps","limited","consumeRateLimit","id","limit","windowMs","allowed","firestore","nowMs","now","sender","address","sendAs","name","displayName","linkOrigin","settings","trackClicks","countOpens","clickLinkOrigin","orgId","senderAddress","catch","shortLinks","rewriteLink","link","doc","enrollmentId","linkIndex","index","url","test","clickLinkUrl","push","sequenceId","pixel","composed","input","openPixelUrl","error","message","length","batch","create","collection","links","commit","console","opened","openMailbox","ok","reason","mailboxId","errorCode","subject","text","html","trackedLinks","client","reconnectRequired","code","answer","testsToday","countTest","sentTo","sentAtMs","unresolvedFields","ref","runTransaction","transaction","stored","snapshot","get","exists","data","undefined","day","timezone","counts","health","daily","sent","bounces","replies","tests","Math","max","Number","update","updatedAtMs","warn"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,qBAAqB,QAAQ,kCAAiC;AAGvE,SAASC,2BAA2B,EAAEC,qBAAqB,QAAQ,mCAA+B;AAClG,SAASC,UAAU,QAAQ,sCAAkC;AAC7D,SAASC,gBAAgB,QAAQ,mCA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