@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.
@@ -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,mBA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IAAI,CAAC,YAAY,GAAG;QAC9E,IAAI,CAACJ,WAAW0C,IAAI,CAACD,YAAY,OAAO/D,QAAQ,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,QA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C,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"}
@@ -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,QAA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O3B,KAAK4B,GAAG;QAAG;QACxE,MAAMC,SACJR,WAAW,WAAW,MAAMhB,MAAMyB,KAAK,CAACJ,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,EAA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AAK,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"}
@@ -50,7 +50,6 @@ export interface OutreachRouteGateDeps {
50
50
  orgId: string | null;
51
51
  /** `null` when the account is not on the organization's roster. */
52
52
  role: string | null;
53
- isOwner: boolean;
54
53
  orgWide: boolean;
55
54
  permissions: Partial<Record<string, boolean | undefined>>;
56
55
  }>;
@@ -71,7 +71,7 @@ export async function outreachRouteGate(request, rawOrgId, deps, extra = []) {
71
71
  orgId,
72
72
  org,
73
73
  // "Manage everyone's Sequences" (AGL-4047), whose default is the owner
74
- // and admin `isOwner` named.
74
+ // and admin.
75
75
  isOrgAdmin: membership.permissions[OUTREACH_MANAGE_ALL_PERMISSION] === true
76
76
  };
77
77
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/routes/route-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 { OUTREACH_MANAGE_ALL_PERMISSION } from '../constants/bundle-common'\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 { outreachEntitlementRefusal, outreachMembershipRefusal } from '../engine/outreach-access'\nimport { outreachRefusal, readOutreachDocumentId } from './route-http'\n\n/**\n * THE GATE EVERY SETTINGS, SEQUENCE AND ENROLLMENT ROUTE CLIMBS (AGL-2980).\n *\n * The console dispatcher has already refused a request while\n * `release_outreach` is off for it, an unverified account's token, a\n * lockdown with no org in scope, and a caller over the console rate limit —\n * every route here is registered under the `outreach/` prefix, which is what\n * puts it behind those. What the dispatcher cannot know is anything about\n * the member, so 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` — or without a permission the route adds\n * 403 the organization does not hold the `outreach` entitlement\n * 423 lockdown, now with the organization and the account in scope\n *\n * The reach is org-wide for the reason the rules give: a sequence enrolls\n * people from every site of the organization, so none of it is a fact\n * about the one site a collaborator was invited to.\n *\n * `resolveOrgPermissions` is always given the concrete org id. Called\n * without one it resolves a caller with no org at all as that future org's\n * owner, which is right for a fresh signup and wrong for every question\n * asked here.\n */\n\nexport interface OutreachRouteGateDeps {\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 isOwner: boolean\n orgWide: boolean\n permissions: Partial<Record<string, boolean | undefined>>\n }>\n /**\n * Whether the member holds a CATALOG permission (`data.manage`) as the\n * org's roles resolve it. Asked separately because the map\n * `resolveOrgPermissions` answers carries the legacy keys and the plugins'\n * own, never a catalog key: read there, a catalog key refuses everyone.\n */\n holdsOrgCatalogPermission(uid: string, orgId: string, key: string): Promise<boolean>\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\n/** Who is asking, once the gate let them through. */\nexport interface OutreachRouteCaller {\n uid: string\n /** The account's sign-in address, lower-cased, when the token carries one. */\n email: string | null\n staff: boolean\n orgId: string\n /** The organization document the entitlement was read from. */\n org: Record<string, unknown>\n /** An owner or admin of the organization, who may send from any member's mailbox. */\n isOrgAdmin: boolean\n}\n\n/**\n * A catalog permission a route asks for beyond `outreach.use`, with its\n * refusal — `data.manage` for a route that reads the CRM's people, which\n * the contacts' own rules gate on.\n */\nexport interface OutreachRouteExtraPermission {\n key: string\n /** Why the route needs it, as the refusal says it. */\n refusal: string\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 outreachRouteGate(\n request: Request,\n rawOrgId: unknown,\n deps: OutreachRouteGateDeps,\n extra: readonly OutreachRouteExtraPermission[] = [],\n): Promise<Response | OutreachRouteCaller> {\n const token = bearer(request)\n if (!token) return outreachRefusal(401, 'unauthenticated', 'Sign in to use Sequences.')\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 outreachRefusal(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 outreachRefusal(403, 'email-unverified', 'Verify your email address before using Sequences.')\n }\n\n const orgId = readOutreachDocumentId(rawOrgId)\n if (!orgId) return outreachRefusal(400, 'org-required', 'Open an organization before using Sequences.')\n\n const membership = await deps.resolveOrgPermissions(decoded.uid, { orgId })\n const refused = outreachMembershipRefusal(membership, orgId)\n if (refused) return outreachRefusal(refused.status, refused.code, refused.message)\n for (const permission of extra) {\n if (!(await deps.holdsOrgCatalogPermission(decoded.uid, orgId, permission.key))) {\n return outreachRefusal(403, 'permission', permission.refusal)\n }\n }\n\n const org = (await deps.readOrg(orgId)) ?? {}\n const unentitled = outreachEntitlementRefusal(org)\n if (unentitled) return outreachRefusal(unentitled.status, unentitled.code, unentitled.message)\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 staff,\n orgId,\n org,\n // \"Manage everyone's Sequences\" (AGL-4047), whose default is the owner\n // and admin `isOwner` named.\n isOrgAdmin: membership.permissions[OUTREACH_MANAGE_ALL_PERMISSION] === true,\n }\n}\n"],"names":["OUTREACH_MANAGE_ALL_PERMISSION","isEmailVerified","isImpersonationSession","invalidIdTokenResponse","outreachEntitlementRefusal","outreachMembershipRefusal","outreachRefusal","readOutreachDocumentId","bearer","request","authorization","headers","get","startsWith","slice","length","outreachRouteGate","rawOrgId","deps","extra","token","decoded","verifyIdToken","error","orgId","membership","resolveOrgPermissions","uid","refused","status","code","message","permission","holdsOrgCatalogPermission","key","refusal","org","readOrg","unentitled","staff","locked","lockdownRefusal","email","trim","toLowerCase","isOrgAdmin","permissions"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,8BAA8B,QAAQ,gCAA4B;AAC3E,SACEC,eAAe,EACfC,sBAAsB,QACjB,iDAAgD;AACvD,SAASC,sBAAsB,QAAQ,mDAAkD;AAEzF,SAASC,0BAA0B,EAAEC,yBAAyB,QAAQ,+BAA2B;AACjG,SAASC,eAAe,EAAEC,sBAAsB,QAAQ,kBAAc;AAmFtE,SAASC,OAAOC,OAAgB;QACRA;IAAtB,MAAMC,iBAAgBD,uBAAAA,QAAQE,OAAO,CAACC,GAAG,CAAC,4BAApBH,uBAAwC;IAC9D,OAAOC,cAAcG,UAAU,CAA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WAAWP,OAAO;IAC7F,MAAMQ,QAAQlB,OAAO,CAAC,QAAQ,KAAK;IACnC,MAAMmB,SAAS,MAAMtB,KAAKuB,eAAe,CAAC;QAAEhC;QAAS8B;QAAOZ,KAAKN,QAAQM,GAAG;QAAES;IAAI;IAClF,IAAII,QAAQ,OAAOA;IAEnB,OAAO;QACLb,KAAKN,QAAQM,GAAG;QAChBe,OAAO,OAAOrB,QAAQqB,KAAK,KAAK,WAAWrB,QAAQqB,KAAK,CAACC,IAAI,GAAGC,WAAW,KAAK;QAChFL;QACAf;QACAY;QACA,uEAAuE;QACvE,6BAA6B;QAC7BS,YAAYpB,WAAWqB,WAAW,CAAC9C,+BAA+B,KAAK;IACzE;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/routes/route-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 { OUTREACH_MANAGE_ALL_PERMISSION } from '../constants/bundle-common'\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 { outreachEntitlementRefusal, outreachMembershipRefusal } from '../engine/outreach-access'\nimport { outreachRefusal, readOutreachDocumentId } from './route-http'\n\n/**\n * THE GATE EVERY SETTINGS, SEQUENCE AND ENROLLMENT ROUTE CLIMBS (AGL-2980).\n *\n * The console dispatcher has already refused a request while\n * `release_outreach` is off for it, an unverified account's token, a\n * lockdown with no org in scope, and a caller over the console rate limit —\n * every route here is registered under the `outreach/` prefix, which is what\n * puts it behind those. What the dispatcher cannot know is anything about\n * the member, so 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` — or without a permission the route adds\n * 403 the organization does not hold the `outreach` entitlement\n * 423 lockdown, now with the organization and the account in scope\n *\n * The reach is org-wide for the reason the rules give: a sequence enrolls\n * people from every site of the organization, so none of it is a fact\n * about the one site a collaborator was invited to.\n *\n * `resolveOrgPermissions` is always given the concrete org id. Called\n * without one it resolves a caller with no org at all as that future org's\n * owner, which is right for a fresh signup and wrong for every question\n * asked here.\n */\n\nexport interface OutreachRouteGateDeps {\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 /**\n * Whether the member holds a CATALOG permission (`data.manage`) as the\n * org's roles resolve it. Asked separately because the map\n * `resolveOrgPermissions` answers carries the legacy keys and the plugins'\n * own, never a catalog key: read there, a catalog key refuses everyone.\n */\n holdsOrgCatalogPermission(uid: string, orgId: string, key: string): Promise<boolean>\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\n/** Who is asking, once the gate let them through. */\nexport interface OutreachRouteCaller {\n uid: string\n /** The account's sign-in address, lower-cased, when the token carries one. */\n email: string | null\n staff: boolean\n orgId: string\n /** The organization document the entitlement was read from. */\n org: Record<string, unknown>\n /** An owner or admin of the organization, who may send from any member's mailbox. */\n isOrgAdmin: boolean\n}\n\n/**\n * A catalog permission a route asks for beyond `outreach.use`, with its\n * refusal — `data.manage` for a route that reads the CRM's people, which\n * the contacts' own rules gate on.\n */\nexport interface OutreachRouteExtraPermission {\n key: string\n /** Why the route needs it, as the refusal says it. */\n refusal: string\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 outreachRouteGate(\n request: Request,\n rawOrgId: unknown,\n deps: OutreachRouteGateDeps,\n extra: readonly OutreachRouteExtraPermission[] = [],\n): Promise<Response | OutreachRouteCaller> {\n const token = bearer(request)\n if (!token) return outreachRefusal(401, 'unauthenticated', 'Sign in to use Sequences.')\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 outreachRefusal(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 outreachRefusal(403, 'email-unverified', 'Verify your email address before using Sequences.')\n }\n\n const orgId = readOutreachDocumentId(rawOrgId)\n if (!orgId) return outreachRefusal(400, 'org-required', 'Open an organization before using Sequences.')\n\n const membership = await deps.resolveOrgPermissions(decoded.uid, { orgId })\n const refused = outreachMembershipRefusal(membership, orgId)\n if (refused) return outreachRefusal(refused.status, refused.code, refused.message)\n for (const permission of extra) {\n if (!(await deps.holdsOrgCatalogPermission(decoded.uid, orgId, permission.key))) {\n return outreachRefusal(403, 'permission', permission.refusal)\n }\n }\n\n const org = (await deps.readOrg(orgId)) ?? {}\n const unentitled = outreachEntitlementRefusal(org)\n if (unentitled) return outreachRefusal(unentitled.status, unentitled.code, unentitled.message)\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 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":["OUTREACH_MANAGE_ALL_PERMISSION","isEmailVerified","isImpersonationSession","invalidIdTokenResponse","outreachEntitlementRefusal","outreachMembershipRefusal","outreachRefusal","readOutreachDocumentId","bearer","request","authorization","headers","get","startsWith","slice","length","outreachRouteGate","rawOrgId","deps","extra","token","decoded","verifyIdToken","error","orgId","membership","resolveOrgPermissions","uid","refused","status","code","message","permission","holdsOrgCatalogPermission","key","refusal","org","readOrg","unentitled","staff","locked","lockdownRefusal","email","trim","toLowerCase","isOrgAdmin","permissions"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,8BAA8B,QAAQ,gCAA4B;AAC3E,SACEC,eAAe,EACfC,sBAAsB,QACjB,iDAAgD;AACvD,SAASC,sBAAsB,QAAQ,mDAAkD;AAEzF,SAASC,0BAA0B,EAAEC,yBAAyB,QAAQ,+BAA2B;AACjG,SAASC,eAAe,EAAEC,sBAAsB,QAAQ,kBAAc;AAkFtE,SAASC,OAAOC,OAAgB;QACRA;IAAtB,MAAMC,iBAAgBD,uBAAAA,QAAQE,OAAO,CAACC,GAAG,CAAC,4BAApBH,uBAAwC;IAC9D,OAAOC,cAAcG,UAAU,CAAC,aAAaH,cAAcI,KAAK,CAAC,UAAUC,MAAM,IAAI;AACvF;AAEA,OAAO,eAAeC,kBACpBP,OAAgB,EAChBQ,QAAiB,EACjBC,IAA2B,EAC3BC,QAAiD,EAAE;QA+BtC;IA7Bb,MAAMC,QAAQZ,OAAOC;IACrB,IAAI,CAACW,OAAO,OAAOd,gBAAgB,KAAK,mBAAmB;IAC3D,IAAIe;IACJ,IAAI;QACFA,UAAU,MAAMH,KAAKI,aAAa,CAACF;IACrC,EAAE,OAAOG,OAAO;QACd,mEAAmE;QACnE,4DAA4D;QAC5D,IAAIpB,uBAAuB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;QACbS,YAAYpB,WAAWqB,WAAW,CAAC9C,+BAA+B,KAAK;IACzE;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 [];