@aglyn/plugins-outreach 1.11.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 +14 -14
- package/src/lib/components/outreach-ui.d.ts +1 -1
- package/src/lib/components/outreach-ui.js +1 -1
- package/src/lib/components/outreach-ui.js.map +1 -1
- package/src/lib/engine/manual-reply.js +1 -1
- package/src/lib/engine/manual-reply.js.map +1 -1
- package/src/lib/mailboxes/mailbox-gate.d.ts +0 -1
- package/src/lib/mailboxes/mailbox-gate.js +1 -1
- package/src/lib/mailboxes/mailbox-gate.js.map +1 -1
- package/src/lib/mailboxes/mailbox-routes.js +1 -1
- package/src/lib/mailboxes/mailbox-routes.js.map +1 -1
- package/src/lib/routes/link-domain-routes.js +1 -1
- package/src/lib/routes/link-domain-routes.js.map +1 -1
- package/src/lib/routes/route-gate.d.ts +0 -1
- package/src/lib/routes/route-gate.js +1 -1
- package/src/lib/routes/route-gate.js.map +1 -1
- package/src/lib/routes/sequence-routes.js +1 -1
- package/src/lib/routes/sequence-routes.js.map +1 -1
- package/src/lib/routes/step-test-routes.js +1 -1
- package/src/lib/routes/step-test-routes.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aglyn/plugins-outreach",
|
|
3
|
-
"version": "1.
|
|
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.
|
|
29
|
-
"@aglyn/shared-data-mdi": "1.
|
|
30
|
-
"@aglyn/shared-ui-email-campaigns": "1.
|
|
31
|
-
"@aglyn/shared-ui-jsx": "1.
|
|
32
|
-
"@aglyn/shared-ui-next": "1.
|
|
33
|
-
"@aglyn/shared-ui-snackstack": "1.
|
|
34
|
-
"@aglyn/shared-util-email": "1.
|
|
35
|
-
"@aglyn/shared-util-http": "1.
|
|
36
|
-
"@aglyn/shared-util-timestamp": "1.
|
|
37
|
-
"@aglyn/shared-util-tools": "1.
|
|
38
|
-
"@aglyn/tenant-data-admin": "1.
|
|
39
|
-
"@aglyn/tenant-feature-instance": "1.
|
|
40
|
-
"@aglyn/tenant-runtime": "1.
|
|
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 = "
|
|
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 =
|
|
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,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,UAAU;AACZ;AAEA,OAA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,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,UAAU;AACZ;AAEA,OAAO,MAAME,oCAGT;IACFJ,QAAQ;IACRC,QAAQ;IACRI,UAAU;IACVC,SAAS;IACTC,SAAS;IACTC,WAAW;IACXC,SAAS;IACTC,QAAQ;AACV,EAAC;AAED,MAAMC,2BAGF;IACFX,QAAQ;IACRC,QAAQ;IACRI,UAAU;IACVC,SAAS;IACTC,SAAS;IACTC,WAAW;IACXC,SAAS;IACTC,QAAQ;AACV;AAEA,2DAA2D,GAC3D,OAAO,MAAME,8BAAkE;IAC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AAmD,CAAC;;AAG9E;AAEA,yDAAyD,GACzD,OAAO,SAASC;IACd,MAAMC,SAASnD;IACf,OAAO,CAACoD,OAAiBD,OAAOE,IAAI,CAACD;AACvC;AAEA;;;CAGC,GACD,OAAO,SAASE,aAAa3B,KAI5B;QAoBgBA;IAnBf,MAAM4B,WAAWL;IACjB,MAAMH,UAAU,CAACS;QACf,IACEA,MAAMC,gBAAgB,IACtBD,MAAME,MAAM,KAAK,KACjBF,MAAMG,OAAO,IACbH,MAAMI,OAAO,IACbJ,MAAMK,QAAQ,IACdL,MAAMM,MAAM,EACZ;YACA;QACF;QACAN,MAAMO,cAAc;QACpBR,SAAS5B,MAAMyB,IAAI;IACrB;IACA,qBACE,KAACvD;QACCuD,MAAMzB,MAAMyB,IAAI;QAChBL,SAASA;QACTiB,SAAS,GAAErC,mBAAAA,MAAMqC,SAAS,YAAfrC,mBAAmB;kBAE7BA,MAAMsC,QAAQ;;AAGrB;AAEA;;;CAGC,GACD,OAAO,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"}
|
|
@@ -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
|
|
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,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,MAA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MAAMmB,YAAY,KAAK,MAAM;QAC/B,OAAO;YACLf,MAAM;YACNxE,SAAS,GAAGiC,WAAWoD,KAAK,CAAC,4FAA4F,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,wDAAwD,CAAC;QAC7G;IACF;IACA,OAAO;AACT"}
|
|
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 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,sBAAsBC,KAAc;IAClD,MAAMC,MAAMC,OAAOF,gBAAAA,QAAS,IAAIG,IAAI;IACpC,MAAMC,SAASH,IAAII,WAAW,CAAC;IAC/B,IAAID,UAAU,GAAG,OAAO;IACxB,OAAOH,IACJK,KAAK,CAAC,GAAGF,QACTD,IAAI,GACJI,OAAO,CAAC,YAAY,MACpBA,OAAO,CAAC,UAAU,MAClBJ,IAAI;AACT;AAEA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K,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"}
|
|
@@ -45,7 +45,6 @@ export interface OutreachGateDeps {
|
|
|
45
45
|
orgId: string | null;
|
|
46
46
|
/** `null` when the account is not on the organization's roster. */
|
|
47
47
|
role: string | null;
|
|
48
|
-
isOwner: boolean;
|
|
49
48
|
orgWide: boolean;
|
|
50
49
|
permissions: Partial<Record<string, boolean | undefined>>;
|
|
51
50
|
}>;
|
|
@@ -92,7 +92,7 @@ export async function outreachMemberGate(request, rawOrgId, deps) {
|
|
|
92
92
|
orgId,
|
|
93
93
|
org,
|
|
94
94
|
// "Manage everyone's Sequences" (AGL-4047), whose default is the owner
|
|
95
|
-
// and admin
|
|
95
|
+
// and admin.
|
|
96
96
|
isOrgAdmin: membership.permissions[OUTREACH_MANAGE_ALL_PERMISSION] === true
|
|
97
97
|
};
|
|
98
98
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/mailboxes/mailbox-gate.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 { checkEntitlement } from '@aglyn/aglyn/server'\nimport {\n isEmailVerified,\n isImpersonationSession,\n} from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport { invalidIdTokenResponse } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport type { DecodedIdToken } from 'firebase-admin/auth'\nimport { OUTREACH_MANAGE_ALL_PERMISSION, OUTREACH_USE_PERMISSION } from '../constants/bundle-common'\nimport type { OutreachApiRefusalReason } from './mailbox-api'\n\n/**\n * THE GATE EVERY AUTHENTICATED MAILBOX ROUTE CLIMBS (AGL-2978).\n *\n * The console dispatcher has already refused a request while\n * `release_outreach` is off for the organization it names, an unverified\n * account's token, a lockdown with no org in scope, and a caller over the\n * console rate limit. What it cannot know is anything about the member, so\n * each rung below is this plugin's:\n *\n * 401 no bearer token, or one the verifier refused\n * 403 the account's address is unverified (an impersonation session is exempt)\n * 400 the request did not name an organization\n * 403 not a member of it, a site collaborator without org-wide reach, or\n * without `outreach.use`\n * 403 the organization does not hold the `outreach` entitlement\n * 423 lockdown, now with the organization and the account in scope\n *\n * `resolveOrgPermissions` is always given the concrete org id. Called without\n * one it resolves a caller with no org at all as that future org's owner,\n * which is right for a fresh signup and wrong for every question asked here.\n */\n\nexport interface OutreachGateDeps {\n verifyIdToken(idToken: string): Promise<DecodedIdToken>\n resolveOrgPermissions(\n uid: string,\n context: { orgId: string },\n ): Promise<{\n orgId: string | null\n /** `null` when the account is not on the organization's roster. */\n role: string | null\n
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/mailboxes/mailbox-gate.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 { checkEntitlement } from '@aglyn/aglyn/server'\nimport {\n isEmailVerified,\n isImpersonationSession,\n} from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport { invalidIdTokenResponse } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport type { DecodedIdToken } from 'firebase-admin/auth'\nimport { OUTREACH_MANAGE_ALL_PERMISSION, OUTREACH_USE_PERMISSION } from '../constants/bundle-common'\nimport type { OutreachApiRefusalReason } from './mailbox-api'\n\n/**\n * THE GATE EVERY AUTHENTICATED MAILBOX ROUTE CLIMBS (AGL-2978).\n *\n * The console dispatcher has already refused a request while\n * `release_outreach` is off for the organization it names, an unverified\n * account's token, a lockdown with no org in scope, and a caller over the\n * console rate limit. What it cannot know is anything about the member, so\n * each rung below is this plugin's:\n *\n * 401 no bearer token, or one the verifier refused\n * 403 the account's address is unverified (an impersonation session is exempt)\n * 400 the request did not name an organization\n * 403 not a member of it, a site collaborator without org-wide reach, or\n * without `outreach.use`\n * 403 the organization does not hold the `outreach` entitlement\n * 423 lockdown, now with the organization and the account in scope\n *\n * `resolveOrgPermissions` is always given the concrete org id. Called without\n * one it resolves a caller with no org at all as that future org's owner,\n * which is right for a fresh signup and wrong for every question asked here.\n */\n\nexport interface OutreachGateDeps {\n verifyIdToken(idToken: string): Promise<DecodedIdToken>\n resolveOrgPermissions(\n uid: string,\n context: { orgId: string },\n ): Promise<{\n orgId: string | null\n /** `null` when the account is not on the organization's roster. */\n role: string | null\n orgWide: boolean\n permissions: Partial<Record<string, boolean | undefined>>\n }>\n readOrg(orgId: string): Promise<Record<string, unknown> | null>\n lockdownRefusal(options: {\n request: Request\n staff: boolean\n uid: string\n org: Record<string, unknown>\n }): Promise<Response | null>\n}\n\nexport interface OutreachGateContext {\n uid: string\n /** The account's sign-in address, lower-cased, when the token carries one. */\n email: string | null\n /** The account's name, when the token carries one. */\n name: string | null\n staff: boolean\n orgId: string\n org: Record<string, unknown>\n /** An owner or admin of the organization, who may manage every mailbox. */\n isOrgAdmin: boolean\n}\n\n/** A refusal in the one shape every mailbox route answers with. */\nexport function refusal(status: number, reason: OutreachApiRefusalReason, error: string): Response {\n return Response.json({ error, reason }, { status, headers: { 'Cache-Control': 'no-store' } })\n}\n\n/** An organization id as a request may name one: a plain document id. */\nconst ORG_ID = /^[A-Za-z0-9_-]{1,128}$/\n\nexport function readOrgId(value: unknown): string | null {\n const orgId = typeof value === 'string' ? value.trim() : ''\n return ORG_ID.test(orgId) ? orgId : null\n}\n\nfunction bearer(request: Request): string | null {\n const authorization = request.headers.get('authorization') ?? ''\n return authorization.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : null\n}\n\nexport async function outreachMemberGate(\n request: Request,\n rawOrgId: unknown,\n deps: OutreachGateDeps,\n): Promise<Response | OutreachGateContext> {\n const token = bearer(request)\n if (!token) return refusal(401, 'unauthenticated', 'Sign in to manage your connected mailboxes.')\n let decoded: DecodedIdToken\n try {\n decoded = await deps.verifyIdToken(token)\n } catch (error) {\n // A refused credential is the caller's; an Auth outage is ours and\n // propagates, so it answers 500 instead of \"sign in again\".\n if (invalidIdTokenResponse(error)) {\n return refusal(401, 'unauthenticated', 'Your sign-in could not be confirmed. Sign in again.')\n }\n throw error\n }\n if (!isEmailVerified(decoded) && !isImpersonationSession(decoded)) {\n return refusal(403, 'email-unverified', 'Verify your email address before connecting a mailbox.')\n }\n\n const orgId = readOrgId(rawOrgId)\n if (!orgId) return refusal(400, 'org-required', 'Open an organization before managing its mailboxes.')\n\n const membership = await deps.resolveOrgPermissions(decoded.uid, { orgId })\n // A targeted org the account is not on answers with that org's id and no\n // role — as does a lookup that failed closed — so the role is the test.\n if (!membership.role || membership.orgId !== orgId) {\n return refusal(403, 'not-a-member', 'You are not a member of that organization.')\n }\n if (!membership.orgWide) {\n return refusal(403, 'not-org-wide', 'Sequences covers the whole organization, and your access is to particular sites.')\n }\n if (membership.permissions[OUTREACH_USE_PERMISSION] !== true) {\n return refusal(403, 'permission', 'Your role does not include Use Sequences.')\n }\n\n const org = (await deps.readOrg(orgId)) ?? {}\n if (!checkEntitlement(org, 'outreach')) {\n return refusal(403, 'entitlement', \"Sequences isn't available to this workspace yet.\")\n }\n const staff = decoded['staff'] === true\n const locked = await deps.lockdownRefusal({ request, staff, uid: decoded.uid, org })\n if (locked) return locked\n\n return {\n uid: decoded.uid,\n email: typeof decoded.email === 'string' ? decoded.email.trim().toLowerCase() : null,\n name: typeof decoded['name'] === 'string' ? String(decoded['name']) : null,\n staff,\n orgId,\n org,\n // \"Manage everyone's Sequences\" (AGL-4047), whose default is the owner\n // and admin.\n isOrgAdmin: membership.permissions[OUTREACH_MANAGE_ALL_PERMISSION] === true,\n }\n}\n"],"names":["checkEntitlement","isEmailVerified","isImpersonationSession","invalidIdTokenResponse","OUTREACH_MANAGE_ALL_PERMISSION","OUTREACH_USE_PERMISSION","refusal","status","reason","error","Response","json","headers","ORG_ID","readOrgId","value","orgId","trim","test","bearer","request","authorization","get","startsWith","slice","length","outreachMemberGate","rawOrgId","deps","token","decoded","verifyIdToken","membership","resolveOrgPermissions","uid","role","orgWide","permissions","org","readOrg","staff","locked","lockdownRefusal","email","toLowerCase","name","String","isOrgAdmin"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,QAAQ,sBAAqB;AACtD,SACEC,eAAe,EACfC,sBAAsB,QACjB,iDAAgD;AACvD,SAASC,sBAAsB,QAAQ,mDAAkD;AAEzF,SAASC,8BAA8B,EAAEC,uBAAuB,QAAQ,gCAA4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I,CAACgB,WAAWG,IAAI,IAAIH,WAAWhB,KAAK,KAAKA,OAAO;QAClD,OAAOV,QAAQ,KAAK,gBAAgB;IACtC;IACA,IAAI,CAAC0B,WAAWI,OAAO,EAAE;QACvB,OAAO9B,QAAQ,KAAK,gBAAgB;IACtC;IACA,IAAI0B,WAAWK,WAAW,CAAChC,wBAAwB,KAAK,MAAM;QAC5D,OAAOC,QAAQ,KAAK,cAAc;IACpC;IAEA,MAAMgC,OAAO,OAAA,MAAMV,KAAKW,OAAO,CAACvB,kBAAnB,OAA8B,CAAC;IAC5C,IAAI,CAAChB,iBAAiBsC,KAAK,aAAa;QACtC,OAAOhC,QAAQ,KAAK,eAAe;IACrC;IACA,MAAMkC,QAAQV,OAAO,CAAC,QAAQ,KAAK;IACnC,MAAMW,SAAS,MAAMb,KAAKc,eAAe,CAAC;QAAEtB;QAASoB;QAAON,KAAKJ,QAAQI,GAAG;QAAEI;IAAI;IAClF,IAAIG,QAAQ,OAAOA;IAEnB,OAAO;QACLP,KAAKJ,QAAQI,GAAG;QAChBS,OAAO,OAAOb,QAAQa,KAAK,KAAK,WAAWb,QAAQa,KAAK,CAAC1B,IAAI,GAAG2B,WAAW,KAAK;QAChFC,MAAM,OAAOf,OAAO,CAAC,OAAO,KAAK,WAAWgB,OAAOhB,OAAO,CAAC,OAAO,IAAI;QACtEU;QACAxB;QACAsB;QACA,uEAAuE;QACvE,aAAa;QACbS,YAAYf,WAAWK,WAAW,CAACjC,+BAA+B,KAAK;IACzE;AACF"}
|
|
@@ -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
|
|
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,
|