@aglyn/tenant-data-admin 1.0.0-beta.275 → 1.0.0-beta.282

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/package.json +7 -7
  2. package/src/lib/server/account-emails.js +18 -4
  3. package/src/lib/server/account-emails.js.map +1 -1
  4. package/src/lib/server/bundle-links.d.ts +5 -0
  5. package/src/lib/server/bundle-links.js +4 -2
  6. package/src/lib/server/bundle-links.js.map +1 -1
  7. package/src/lib/server/erase.js +9 -0
  8. package/src/lib/server/erase.js.map +1 -1
  9. package/src/lib/server/media-strong-digest.js +33 -5
  10. package/src/lib/server/media-strong-digest.js.map +1 -1
  11. package/src/lib/server/organizations.js +20 -0
  12. package/src/lib/server/organizations.js.map +1 -1
  13. package/src/lib/server/owner-handoff-emails.d.ts +43 -0
  14. package/src/lib/server/owner-handoff-emails.js +134 -0
  15. package/src/lib/server/owner-handoff-emails.js.map +1 -0
  16. package/src/lib/server/personal-data-export.js +18 -4
  17. package/src/lib/server/personal-data-export.js.map +1 -1
  18. package/src/lib/server/render-monitor.d.ts +8 -4
  19. package/src/lib/server/render-monitor.js +12 -8
  20. package/src/lib/server/render-monitor.js.map +1 -1
  21. package/src/lib/server/site-care-inbound.d.ts +75 -4
  22. package/src/lib/server/site-care-inbound.js +236 -26
  23. package/src/lib/server/site-care-inbound.js.map +1 -1
  24. package/src/lib/server/site-care-reconcile.d.ts +36 -2
  25. package/src/lib/server/site-care-reconcile.js +219 -54
  26. package/src/lib/server/site-care-reconcile.js.map +1 -1
  27. package/src/lib/server/site-care-requests.d.ts +43 -1
  28. package/src/lib/server/site-care-requests.js +117 -6
  29. package/src/lib/server/site-care-requests.js.map +1 -1
  30. package/src/lib/server/upgrade-proposal.d.ts +6 -1
  31. package/src/lib/server/upgrade-proposal.js.map +1 -1
  32. package/src/lib/server/upload-cors-reconcile.d.ts +2 -2
  33. package/src/lib/server/upload-cors-reconcile.js +2 -2
  34. package/src/lib/server/upload-cors-reconcile.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/render-monitor.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 { TENANT_APEX } from '@aglyn/aglyn/app-utils/tenant-apex'\nimport type { OperatorHealthStateDoc } from './operator-health'\n\n/**\n * THE RENDER MONITOR (AGL-3568): does a published site still render a page\n * that was not already in a cache?\n *\n * On 2026-10-05 every uncached page render on the published-site runtime\n * hung to the platform's 60 s limit for 28 minutes, and nothing alerted. The\n * three monitors that existed each missed it for its own reason:\n *\n * - the GitHub uptime probe is scheduled every 15 minutes and GitHub ran it\n * four times that day, none of them during the outage;\n * - its page rows fetch `/`, which the ISR cache answers, so a visitor's\n * page that was cached still loaded and the row stayed green;\n * - `/api/health/render/site` runs the page LOADER in-process and never the\n * site layout, which is where the request was stuck.\n *\n * So this fetches pages over HTTP, from the console (a different deployment\n * from the one it watches), on Cloud Scheduler every five minutes, and asks\n * for two pages no cache can answer:\n *\n * - `dynamic` — `/search`, a route every site has that renders on every\n * request (`force-dynamic`) inside the full site layout. A 200 that is a\n * complete document proves the layout and head ran just now.\n * - `isr` — a path nobody has ever requested, under the catch-all page.\n * A never-seen path is the one request the ISR cache cannot answer, so it\n * renders in the same static context every published page renders in,\n * which is the context the 2026-09-09 outage only appeared in. It is a\n * 404 by construction, and the site's own not-found page is drawn inside\n * the same layout, so a complete 404 document is a pass.\n *\n * A site that fails `threshold` runs in a row raises\n * `system.siteRenderFailing` once; the first passing run after that raises\n * `system.siteRenderRecovered` once.\n *\n * ## A challenge is not a failed render (AGL-3580)\n *\n * When bot protection answers instead of the site, this run saw nothing about\n * the site at all. On 2026-10-05 the console had no `AGLYN_PROBE_TOKEN`, every\n * `/search` probe got the 429 checkpoint for three hours, and the monitor told\n * the operator \"Pages are not rendering on aglyn.com\" and then \"rendering\n * again after 3 h\" about a site that was serving pages the whole time. So a\n * run whose only failures are challenges is BLIND: it leaves the site's\n * verdict and failure count exactly as they were, and `threshold` blind runs\n * in a row raise `system.renderMonitorBlind` once, which names the setup\n * problem instead of an outage. A run with a real failure beside a challenge\n * is still a failure, because the real one is evidence. The state lives in\n * `operatorHealthState/render-monitor--<host>`, beside every other health\n * check, so Staff → Operator alerts lists it with its status and since when.\n *\n * Nothing here names an Aglyn host for anyone else: the default target is the\n * install's own demonstration site label under its own tenant apex, the\n * convention the middleware and the render canaries already follow. The one\n * exception is `PLATFORM_RENDER_PAGES` below, which applies on Aglyn's own\n * console deployment and nowhere else.\n *\n * ## Real pages, rendered fresh (AGL-3571)\n *\n * The two probes above draw the layout. They do not draw a page BODY, and\n * beta.223 hung only on page bodies with an image in them (an ancestor walk\n * looped on the page root, AGL-3565): `demo` has no images and the not-found\n * page has no body, so this monitor read green through it. So a third probe,\n * `page`, renders a real published page through the full ISR path — through\n * the tenant's `*.vercel.app` production domain (`RENDER_MONITOR_RENDER_ORIGIN`),\n * which honors `?tenantHost=` and sits behind Deployment Protection, naming\n * the site with a spelling no cache holds (`freshHostSpelling`). The cache key\n * includes the `[host]` segment, and `normalizeHostAlias` resolves every\n * spelling to the same site. Without the automation bypass the render origin\n * answers its sign-in redirect, so no `page` probe is made at all.\n *\n * One page per site per run, rotating through that site's list: a platform\n * break fails every page with an image, so every run, and alerts as fast as\n * before; a break on one page alone is seen on its turn.\n *\n * ## Layout probes take turns past the first site\n *\n * A fresh layout reads the site's whole screen and collection lists, and a\n * large site makes that the most expensive request the platform serves: the\n * marketing site's 109 screens made this monitor a fifth of the project's\n * Firestore reads. Every site draws them on its turn, one site per run (see\n * {@link renderMonitorProbesLayout}), and the sites' pages take turns the\n * same way, one page per run across every watched site (see\n * {@link renderMonitorPageTurn}): three fresh renders a run. A platform-wide\n * break fails whichever page and layout are drawn, so it is still seen on\n * the run it happens and alerted on the next; a break on one page alone is\n * seen on that page's turn. Without `page` probes (no render origin or no\n * bypass) the first target — the demonstration site — draws its layout on\n * every run instead, because nothing else would be looked at every run\n * (AGL-3928).\n */\n\n/** The state documents' collection: the health checks' own. */\nconst RENDER_MONITOR_COLLECTION = 'operatorHealthState'\n\n/** Every render monitor document id starts with this. */\nexport const RENDER_MONITOR_CHECK_PREFIX = 'render-monitor--'\n\n/** The beat id `/api/health/crons` reads for the scheduled run. */\nexport const RENDER_MONITOR_JOB_ID = 'render-monitor'\n\n/**\n * How long one page fetch may take. Well under the 60 s a platform function\n * may run, so a hung render is graded here as a timeout rather than waiting\n * for the platform's 504, and well under the route's own `maxDuration`.\n */\nexport const RENDER_MONITOR_TIMEOUT_MS = 25_000\n\n/** Failing runs in a row before the alert goes out. */\nexport const RENDER_MONITOR_DEFAULT_THRESHOLD = 2\n\n/**\n * The prefix of the never-requested path the `isr` probe asks for. A\n * lowercase slug on purpose: it must reach the catch-all page like any\n * screen slug would, not a reserved or rewritten route.\n */\nexport const RENDER_PROBE_ISR_PREFIX = '/aglyn-render-probe-'\n\nexport type RenderProbeKind = 'dynamic' | 'isr' | 'page'\n\nexport interface RenderProbeSpec {\n kind: RenderProbeKind\n /** The path to request, given a fresh nonce. */\n path: (nonce: string) => string\n /** The status a healthy render answers with. */\n expectStatus: number\n}\n\nexport const RENDER_PROBES: readonly RenderProbeSpec[] = [\n { kind: 'dynamic', path: () => '/search', expectStatus: 200 },\n {\n kind: 'isr',\n path: (nonce) => `${RENDER_PROBE_ISR_PREFIX}${nonce}`,\n expectStatus: 404,\n },\n]\n\n/** One fetched response, reduced to what grading reads. */\nexport interface RenderProbeResponse {\n status: number\n contentType?: string | null\n body?: string\n location?: string | null\n /** `x-vercel-cache` on Vercel, `x-nextjs-cache` on a plain `next start`. */\n cacheState?: string | null\n}\n\nexport interface RenderProbeVerdict {\n ok: boolean\n /** Bot protection answered instead of the site. */\n challenged: boolean\n /** A stable code; `ok` on a pass. */\n code: string\n detail: string\n}\n\n/** Vercel's challenge interstitial, matched on the body like the front doors. */\nconst CHECKPOINT_MARKER = /Vercel Security Checkpoint/i\n\n/**\n * Cache states that mean the bytes came out of a store. A probe meant to\n * prove a render cannot pass on one of these, whatever the status.\n */\nconst CACHED_STATES = new Set(['HIT', 'STALE', 'PRERENDER'])\n\n/**\n * Grade one probe response. Pure.\n *\n * The page markers are the front doors' (`tools/scripts/lib/front-door.mjs`)\n * and for their reason: structural, never site copy. `</html>` proves the\n * document finished streaming, `/_next/static/` that our build produced it.\n */\nexport function gradeRenderProbe(\n response: RenderProbeResponse,\n expectStatus: number,\n): RenderProbeVerdict {\n const body = response.body ?? ''\n if (CHECKPOINT_MARKER.test(body)) {\n return {\n ok: false,\n challenged: true,\n code: 'challenged',\n detail: `bot protection answered (HTTP ${response.status}) instead of the site; check AGLYN_PROBE_TOKEN on the console`,\n }\n }\n if (response.status >= 300 && response.status < 400) {\n return {\n ok: false,\n challenged: false,\n code: 'redirected',\n detail: `redirected to ${response.location ?? '?'}, so no page was rendered`,\n }\n }\n if (response.status !== expectStatus) {\n return {\n ok: false,\n challenged: false,\n code: `http-${response.status}`,\n detail: `HTTP ${response.status}`,\n }\n }\n if (!/text\\/html/i.test(response.contentType ?? '')) {\n return {\n ok: false,\n challenged: false,\n code: 'not-html',\n detail: `not HTML (${response.contentType || 'no content-type'})`,\n }\n }\n if (!body.includes('</html>')) {\n return {\n ok: false,\n challenged: false,\n code: 'incomplete',\n detail: 'the document never finished (no </html>)',\n }\n }\n if (!body.includes('/_next/static/')) {\n return {\n ok: false,\n challenged: false,\n code: 'not-our-render',\n detail: 'no Next asset references, so the app did not render it',\n }\n }\n const cache = String(response.cacheState ?? '').trim().toUpperCase()\n if (CACHED_STATES.has(cache)) {\n return {\n ok: false,\n challenged: false,\n code: 'served-from-cache',\n detail: `served from cache (${cache}), so it proves no render`,\n }\n }\n return { ok: true, challenged: false, code: 'ok', detail: 'rendered' }\n}\n\n/**\n * The pages Aglyn's own console renders fresh when `RENDER_MONITOR_PAGES` is\n * unset: the canary's real client pages (`tools/scripts/lib/prod-canary.mjs`\n * `DEFAULT_TENANT_HOSTS`), images, reusable components, repeats and a form\n * between them. Applied ONLY on that console deployment (`VERCEL_PROJECT_ID`),\n * so no other install ever requests them.\n */\nexport const PLATFORM_RENDER_PAGES = [\n 'ready-to-roll.aglyn.app/',\n 'edr-construction.aglyn.app/',\n 'edr-construction.aglyn.app/services',\n 'edr-construction.aglyn.app/contact',\n].join(' ')\n\n/** Aglyn's console project on Vercel, the one deployment the list above is for. */\nexport const PLATFORM_CONSOLE_VERCEL_PROJECT_ID = 'prj_gEzxEXc0Lhs81rmaXIg2a1GbsDfl'\n\n/**\n * The tenant's production project domain on Vercel: follows every promote and\n * rollback, honors `?tenantHost=`, and is reachable only with the bypass.\n */\nexport const PLATFORM_RENDER_ORIGIN = 'https://aglyn-tenant-aglyn.vercel.app'\n\n/** The middleware's custom-domain sentinel (`apps/tenant/utils/get-host.ts`). */\nconst CNAME_HOST_PREFIX = 'cname--'\n\n/** Letters past this are never recased, so the bit arithmetic stays in 32 bits. */\nconst MAX_SPELLING_BITS = 30\n\nfunction spellingLetters(host: string): number[] {\n return [...host.toLowerCase()]\n .map((char, index) => (/[a-z]/.test(char) ? index : -1))\n .filter((index) => index >= 0)\n .slice(0, MAX_SPELLING_BITS)\n}\n\n/**\n * Spelling number `n` of one site: a `?tenantHost=` value that resolves to\n * that site and is a `[host]` route segment no other number produces, so the\n * page it asks for has no cache entry to come from.\n *\n * - `{sub}.{apex}` → the full name, letters upper-cased by the bits of `n`,\n * then one trailing dot per exhausted round of cases.\n * - any other name → `cname--{name}`, recased the same way and cycling after\n * `2 ** letters` (that form keeps trailing dots), with the prefix left\n * lower-case because the canonical-domain redirect tests the raw segment.\n *\n * MUST stay identical to `freshHostSpelling` in\n * `tools/scripts/lib/prod-canary.mjs`; `apps/tenant/specs/probe-host-spelling.spec.ts`\n * pins both against `normalizeHostAlias`.\n */\nexport function freshHostSpelling(host: string, n: number, apex: string = TENANT_APEX): string {\n const subdomain = host.endsWith(`.${apex}`)\n const prefix = subdomain ? '' : CNAME_HOST_PREFIX\n const chars = [...host.toLowerCase()]\n const letters = spellingLetters(host)\n const capacity = 2 ** letters.length\n const value = Math.max(0, Math.floor(Number(n) || 0))\n const bits = value % capacity\n letters.forEach((index, bit) => {\n if (Math.floor(bits / 2 ** bit) % 2 === 1) chars[index] = chars[index].toUpperCase()\n })\n const dots = subdomain ? '.'.repeat(Math.floor(value / capacity)) : ''\n return `${prefix}${chars.join('')}${dots}`\n}\n\n/**\n * The spelling number for a run at `nowMs`: minutes since 2026-10-01, so it\n * never repeats on one deployment — a `{sub}.aglyn.app` name of 18 letters\n * gains its first trailing dot after half a year.\n */\nexport function renderSpellingNumber(nowMs: number): number {\n return Math.max(1, Math.floor((nowMs - Date.UTC(2026, 9, 1)) / 60_000))\n}\n\n/** One watched site's real pages. */\nexport interface RenderMonitorPages {\n /** The site's public origin, which keys its state document. */\n origin: string\n host: string\n paths: string[]\n}\n\n/**\n * `\"a.example.app b.example.app/services, https://b.example.app/contact\"` →\n * one entry per host, paths merged, `/` when an entry names none. Entries that\n * are not a hostname are dropped, as `RENDER_MONITOR_ORIGINS` drops them.\n */\nexport function parseRenderMonitorPages(text: string | undefined | null): RenderMonitorPages[] {\n const byHost = new Map<string, string[]>()\n for (const raw of String(text ?? '').split(/[\\s,]+/)) {\n const entry = raw.trim().replace(/^https?:\\/\\//i, '')\n if (!entry) continue\n const slash = entry.indexOf('/')\n const host = (slash === -1 ? entry : entry.slice(0, slash)).toLowerCase()\n if (!/^[a-z0-9-]+(\\.[a-z0-9-]+)+$/.test(host)) continue\n const path = slash === -1 ? '/' : entry.slice(slash).replace(/\\/+$/, '') || '/'\n const paths = byHost.get(host) ?? []\n if (!paths.includes(path)) paths.push(path)\n byHost.set(host, paths)\n }\n return [...byHost].map(([host, paths]) => ({ origin: `https://${host}`, host, paths }))\n}\n\n/**\n * Which real pages the monitor renders, and through which origin.\n *\n * `RENDER_MONITOR_PAGES` (same grammar as the canary's `CANARY_TENANT_HOSTS`)\n * and `RENDER_MONITOR_RENDER_ORIGIN`, else — on Aglyn's own console only —\n * `PLATFORM_RENDER_PAGES` through `PLATFORM_RENDER_ORIGIN`. `off` (here or in\n * `RENDER_MONITOR_ORIGINS`) renders none. No render origin, no pages.\n */\nexport function resolveRenderMonitorPages(\n env: Readonly<Record<string, string | undefined>>,\n): { renderOrigin: string; pages: RenderMonitorPages[] } {\n const off = /^(off|none|false|0)$/i\n const raw = String(env['RENDER_MONITOR_PAGES'] ?? '').trim()\n if (off.test(raw) || off.test(String(env['RENDER_MONITOR_ORIGINS'] ?? '').trim())) {\n return { renderOrigin: '', pages: [] }\n }\n const platform = env['VERCEL_PROJECT_ID'] === PLATFORM_CONSOLE_VERCEL_PROJECT_ID\n const renderOrigin =\n originOf(env['RENDER_MONITOR_RENDER_ORIGIN']) || (platform ? PLATFORM_RENDER_ORIGIN : '')\n const pages = parseRenderMonitorPages(raw || (platform ? PLATFORM_RENDER_PAGES : ''))\n return renderOrigin ? { renderOrigin, pages } : { renderOrigin: '', pages: [] }\n}\n\n/** A configured value as an origin, or '' when it is not one. */\nexport function originOf(value: string | undefined | null): string {\n const trimmed = String(value ?? '').trim().replace(/\\/+$/, '')\n return /^https?:\\/\\/[^/\\s?#]+$/i.test(trimmed) ? trimmed.toLowerCase() : ''\n}\n\n/**\n * Which sites the monitor renders, from the console's environment.\n *\n * 1. The install's demonstration site: `OPERATOR_HEALTH_TENANT_ORIGIN` when\n * set (the one published site the operator alerts tick already watches),\n * else `https://<AGLYN_TENANT_DEMO or demo>.<tenant apex>`.\n * 2. Plus every origin in `RENDER_MONITOR_ORIGINS`, comma separated.\n *\n * `RENDER_MONITOR_ORIGINS=off` watches nothing, for an install with no\n * published site to watch. Values that are not origins are dropped.\n */\nexport function resolveRenderMonitorTargets(\n env: Readonly<Record<string, string | undefined>>,\n): string[] {\n const raw = String(env['RENDER_MONITOR_ORIGINS'] ?? '').trim()\n if (/^(off|none|false|0)$/i.test(raw)) return []\n const apex =\n String(env['NEXT_PUBLIC_TENANT_DOMAIN'] ?? '').trim() || TENANT_APEX\n const label = String(env['AGLYN_TENANT_DEMO'] ?? '').trim() || 'demo'\n const demo =\n originOf(env['OPERATOR_HEALTH_TENANT_ORIGIN']) ||\n originOf(`https://${label}.${apex}`)\n const listed = raw\n .split(/[\\s,]+/)\n .map((value) => originOf(value))\n .filter(Boolean)\n // A site whose pages are rendered is watched whole: its layout probes too.\n const paged = resolveRenderMonitorPages(env).pages.map((page) => page.origin)\n return [...new Set([demo, ...listed, ...paged].filter(Boolean))]\n}\n\n/**\n * Whether the target at `index` (of `count`, in\n * {@link resolveRenderMonitorTargets} order) draws its layout probes in the\n * five-minute `slot`. With `firstEveryRun`, the first always and the rest\n * one per slot in turn; without it, one target per slot in turn, the first\n * included — the mode for a run that draws a real page anyway (AGL-3928).\n */\nexport function renderMonitorProbesLayout(\n index: number,\n count: number,\n slot: number,\n firstEveryRun = true,\n): boolean {\n if (count <= 1) return true\n if (!firstEveryRun) return Math.abs(slot) % count === index\n if (index <= 0 || count <= 2) return true\n return Math.abs(slot) % (count - 1) === index - 1\n}\n\n/** One site's page that the `page` probe renders this run. */\nexport interface RenderMonitorPageTurn {\n site: RenderMonitorPages\n path: string\n}\n\n/**\n * The page the five-minute `slot` renders: the sites' pages laid end to end\n * in {@link resolveRenderMonitorPages} order, one per slot in turn, so a\n * site with three pages is seen three times as often as a site with one and\n * every page comes round within `pages × 5` minutes. Null when there is\n * nothing to render.\n */\nexport function renderMonitorPageTurn(\n pages: readonly RenderMonitorPages[],\n slot: number,\n): RenderMonitorPageTurn | null {\n const turns = pages.flatMap((site) => site.paths.map((path) => ({ site, path })))\n if (!turns.length) return null\n return turns[Math.abs(slot) % turns.length] ?? null\n}\n\n/** The state document id for one origin. */\nexport function renderMonitorCheckId(origin: string): string {\n return renderMonitorHostCheckId(new URL(origin).host)\n}\n\n/** The state document id for one host, as {@link renderMonitorCheckId} names it. */\nexport function renderMonitorHostCheckId(host: string): string {\n return `${RENDER_MONITOR_CHECK_PREFIX}${host}`\n}\n\n/** One render monitor state document. */\nexport interface RenderMonitorStateDoc extends OperatorHealthStateDoc {\n origin: string\n /** Failing runs in a row, reset by any passing run. */\n consecutiveFailures: number\n /** When the current run of failures began; null while passing. */\n failingSinceMs: number | null\n lastOkAtMs: number | null\n /** Runs in a row where bot protection answered instead of the site. */\n consecutiveBlindRuns?: number\n /** When the current blind stretch began; null while the monitor can see. */\n blindSinceMs?: number | null\n /** When a run last saw the site itself: a pass or a real failure. */\n lastObservedAtMs?: number | null\n}\n\nexport type RenderMonitorTransition = 'failing' | 'recovered' | 'blind' | null\n\n/**\n * The next state for one site, given what this run saw. Pure.\n *\n * The status turns `degraded` only once `threshold` runs in a row have\n * failed, so one slow cold start or one dropped connection says nothing. It\n * turns back on the first passing run, because a render that works is\n * proof, and a recovery held back is a recovery nobody hears about.\n *\n * A BLIND observation (every failure was a bot-protection challenge) changes\n * nothing about the site: its status, failure count and since-time carry over\n * untouched, and only the blind count moves. It transitions to `blind` once,\n * on the `threshold`-th blind run in a row.\n */\nexport function nextRenderMonitorState(\n prior: Partial<RenderMonitorStateDoc> | null,\n observation: { ok: boolean; detail: string; blind?: boolean },\n context: { origin: string; label: string; threshold: number; now: number },\n): { next: RenderMonitorStateDoc; transition: RenderMonitorTransition } {\n const { origin, label, threshold, now } = context\n const checkId = renderMonitorCheckId(origin)\n const detail = String(observation.detail ?? '').slice(0, 1_000)\n const wasDegraded = prior?.status === 'degraded'\n if (!observation.ok && observation.blind) {\n const blindRuns = (prior?.consecutiveBlindRuns ?? 0) + 1\n return {\n next: {\n checkId,\n label,\n origin,\n status: wasDegraded ? 'degraded' : 'ok',\n sinceMs: prior?.sinceMs ?? now,\n detail: `The monitor cannot see this site: ${detail}`.slice(0, 1_000),\n updatedAtMs: now,\n consecutiveFailures: prior?.consecutiveFailures ?? 0,\n failingSinceMs: prior?.failingSinceMs ?? null,\n lastOkAtMs: prior?.lastOkAtMs ?? null,\n consecutiveBlindRuns: blindRuns,\n blindSinceMs: prior?.blindSinceMs ?? now,\n lastObservedAtMs: prior?.lastObservedAtMs ?? null,\n },\n transition: blindRuns === Math.max(1, threshold) ? 'blind' : null,\n }\n }\n const sighted = { consecutiveBlindRuns: 0, blindSinceMs: null, lastObservedAtMs: now }\n if (observation.ok) {\n return {\n next: {\n checkId,\n label,\n origin,\n status: 'ok',\n sinceMs: !wasDegraded && prior?.sinceMs ? prior.sinceMs : now,\n detail,\n updatedAtMs: now,\n consecutiveFailures: 0,\n failingSinceMs: null,\n lastOkAtMs: now,\n ...sighted,\n },\n transition: wasDegraded ? 'recovered' : null,\n }\n }\n const failures = (prior?.consecutiveFailures ?? 0) + 1\n const failingSinceMs = prior?.failingSinceMs ?? now\n const degraded = wasDegraded || failures >= Math.max(1, threshold)\n return {\n next: {\n checkId,\n label,\n origin,\n status: degraded ? 'degraded' : 'ok',\n sinceMs: degraded\n ? wasDegraded && prior?.sinceMs\n ? prior.sinceMs\n : failingSinceMs\n : (prior?.sinceMs ?? now),\n detail,\n updatedAtMs: now,\n consecutiveFailures: failures,\n failingSinceMs,\n lastOkAtMs: prior?.lastOkAtMs ?? null,\n ...sighted,\n },\n transition: degraded && !wasDegraded ? 'failing' : null,\n }\n}\n\n/** One probe as the report shows it. */\nexport interface RenderProbeRow extends RenderProbeVerdict {\n kind: RenderProbeKind\n url: string\n ms: number\n httpStatus: number | null\n}\n\n/** One site's result for a run. */\nexport interface RenderMonitorSiteResult {\n origin: string\n ok: boolean\n /** Every failure this run was a challenge, so it saw nothing of the site. */\n blind: boolean\n probes: RenderProbeRow[]\n /** The state written; absent on a dry run or a failed write. */\n status?: 'ok' | 'degraded'\n consecutiveFailures?: number\n transition?: RenderMonitorTransition\n error?: string\n}\n\nexport interface RenderMonitorReport {\n dryRun: boolean\n threshold: number\n sites: RenderMonitorSiteResult[]\n}\n\n/** The read-modify-write of one site's state, as one transaction. */\nexport type RenderMonitorStore = <T>(\n checkId: string,\n work: (prior: Partial<RenderMonitorStateDoc> | null) => {\n next: RenderMonitorStateDoc\n result: T\n },\n) => Promise<T>\n\n/**\n * How long a passing site's stored state may go without being rewritten.\n *\n * A run that changes nothing about a site's verdict — the common run — used\n * to rewrite its document anyway, three documents every five minutes\n * (AGL-3932). The `observation-stale` rule in {@link renderPagesHealth} reads\n * `updatedAtMs` against {@link RENDER_PAGES_STALE_MS}, so the document is\n * refreshed at half that, and on every change of verdict, count or blind\n * stretch.\n */\nexport const RENDER_MONITOR_STATE_REFRESH_MS = 10 * 60_000\n\n/**\n * Whether a run's state differs from the stored one in anything the reader\n * or the next run decides by, or the stored one is old enough to refresh.\n */\nexport function renderMonitorStateNeedsWrite(\n prior: Partial<RenderMonitorStateDoc> | null,\n next: RenderMonitorStateDoc,\n now: number,\n): boolean {\n if (!prior) return true\n const decided: Array<keyof RenderMonitorStateDoc> = [\n 'status',\n 'sinceMs',\n 'detail',\n 'consecutiveFailures',\n 'failingSinceMs',\n 'consecutiveBlindRuns',\n 'blindSinceMs',\n 'label',\n 'origin',\n ]\n if (decided.some((key) => (prior[key] ?? null) !== (next[key] ?? null))) return true\n const updatedAtMs = typeof prior.updatedAtMs === 'number' ? prior.updatedAtMs : 0\n return now - updatedAtMs >= RENDER_MONITOR_STATE_REFRESH_MS || now < updatedAtMs\n}\n\n/**\n * The default store: one Firestore transaction on the site's document, so\n * two overlapping runs cannot both decide they saw the edge. The document is\n * written only when {@link renderMonitorStateNeedsWrite} says so.\n */\nconst firestoreStore: RenderMonitorStore = async (checkId, work) => {\n const { default: firebaseAdmin } = await import('./firebase-admin')\n const db = firebaseAdmin.app().firestore()\n const ref = db.collection(RENDER_MONITOR_COLLECTION).doc(checkId)\n return db.runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n const prior = snapshot.exists\n ? (snapshot.data() as Partial<RenderMonitorStateDoc>)\n : null\n const { next, result } = work(prior)\n if (renderMonitorStateNeedsWrite(prior, next, next.updatedAtMs)) transaction.set(ref, next)\n return result\n })\n}\n\ntype RaiseAlert = (\n type: string,\n options: { dedupeKey?: string; context?: Record<string, string | number> },\n) => Promise<unknown>\n\nconst defaultRaise: RaiseAlert = async (type, options) => {\n const { raiseOperatorAlert } = await import('./operator-alerts')\n return raiseOperatorAlert(type, options)\n}\n\nfunction describeDuration(ms: number): string {\n const minutes = Math.max(1, Math.round(ms / 60_000))\n if (minutes < 60) return `${minutes} min`\n const hours = Math.floor(minutes / 60)\n const rest = minutes % 60\n return rest ? `${hours} h ${rest} min` : `${hours} h`\n}\n\n/**\n * The `page` probe's URL for one run: this run's page (see\n * {@link renderMonitorPageTurn}) under this run's spelling of its site.\n */\nexport function pageProbeUrl(\n renderOrigin: string,\n turn: RenderMonitorPageTurn,\n spelling: number,\n): string {\n const url = new URL(turn.path || '/', renderOrigin)\n url.searchParams.set('tenantHost', freshHostSpelling(turn.site.host, spelling))\n return url.toString()\n}\n\nfunction probeLine(row: RenderProbeRow): string {\n return `${row.kind} ${new URL(row.url).pathname}: ${row.detail} (${row.ms} ms)`\n}\n\n/** Fetch and grade one probe. Never throws. */\nasync function runProbe(\n url: string,\n spec: { kind: RenderProbeKind; expectStatus: number },\n options: {\n fetcher: typeof fetch\n headers: Record<string, string>\n timeoutMs: number\n clock: () => number\n },\n): Promise<RenderProbeRow> {\n const startedAt = options.clock()\n try {\n const response = await options.fetcher(url, {\n redirect: 'manual',\n cache: 'no-store',\n headers: {\n 'user-agent': 'aglyn-render-monitor',\n accept: 'text/html,application/xhtml+xml',\n ...options.headers,\n },\n signal: AbortSignal.timeout(options.timeoutMs),\n })\n const body = await response.text()\n const verdict = gradeRenderProbe(\n {\n status: response.status,\n contentType: response.headers.get('content-type'),\n body,\n location: response.headers.get('location'),\n cacheState:\n response.headers.get('x-vercel-cache') ??\n response.headers.get('x-nextjs-cache'),\n },\n spec.expectStatus,\n )\n return {\n kind: spec.kind,\n url,\n ms: options.clock() - startedAt,\n httpStatus: response.status,\n ...verdict,\n }\n } catch (error) {\n const name = (error as { name?: string } | null)?.name\n const timedOut = name === 'TimeoutError' || name === 'AbortError'\n return {\n kind: spec.kind,\n url,\n ms: options.clock() - startedAt,\n httpStatus: null,\n ok: false,\n challenged: false,\n code: timedOut ? 'timeout' : 'unreachable',\n detail: timedOut\n ? `no complete page in ${Math.round(options.timeoutMs / 1_000)} s`\n : `unreachable (${(error as { cause?: { code?: string } } | null)?.cause?.code ?? name ?? 'error'})`,\n }\n }\n}\n\n/**\n * One run: render every target, record each site's state, raise the edge.\n *\n * A dry run fetches and grades and writes nothing, so a person can ask\n * \"what would the monitor see right now\" without moving its state.\n */\nexport async function runRenderMonitor(\n options: {\n dryRun?: boolean\n env?: Readonly<Record<string, string | undefined>>\n fetcher?: typeof fetch\n /** Our own edge's bypass headers, from the caller's environment. */\n headers?: Record<string, string>\n now?: () => number\n nonce?: () => string\n timeoutMs?: number\n store?: RenderMonitorStore\n raise?: RaiseAlert\n } = {},\n): Promise<RenderMonitorReport> {\n const env = options.env ?? process.env\n const clock = options.now ?? Date.now\n const store = options.store ?? firestoreStore\n const raise = options.raise ?? defaultRaise\n const dryRun = Boolean(options.dryRun)\n const parsedThreshold = Number.parseInt(\n String(env['RENDER_MONITOR_FAILURE_THRESHOLD'] ?? ''),\n 10,\n )\n const threshold =\n Number.isFinite(parsedThreshold) && parsedThreshold >= 1\n ? parsedThreshold\n : RENDER_MONITOR_DEFAULT_THRESHOLD\n const nonce =\n options.nonce ??\n (() => `${clock().toString(36)}${Math.random().toString(36).slice(2, 8)}`)\n\n const probeOptions = {\n fetcher: options.fetcher ?? fetch,\n headers: options.headers ?? {},\n timeoutMs: options.timeoutMs ?? RENDER_MONITOR_TIMEOUT_MS,\n clock,\n }\n // Real pages need the render origin AND the bypass that gets past its\n // Deployment Protection; without both a `page` probe could only fail.\n const { renderOrigin, pages } = resolveRenderMonitorPages(env)\n const canRenderPages = Boolean(\n renderOrigin && probeOptions.headers['x-vercel-protection-bypass'],\n )\n const runAt = clock()\n const slot = Math.floor(runAt / 300_000)\n\n const targets = resolveRenderMonitorTargets(env)\n // One real page a run, across every watched site; with one, the layout\n // probes need no every-run site of their own.\n const turn = canRenderPages ? renderMonitorPageTurn(pages, slot) : null\n const due = targets\n .map((origin, index) => ({\n origin,\n layout: renderMonitorProbesLayout(index, targets.length, slot, !turn),\n page: turn && turn.site.origin === origin ? turn : undefined,\n }))\n // A site with nothing to draw this run keeps its state as it is.\n .filter((target) => target.layout || target.page)\n\n const sites = await Promise.all(\n due.map(\n async ({ origin, layout, page }): Promise<RenderMonitorSiteResult> => {\n const layoutProbes = layout\n ? RENDER_PROBES.map((spec) =>\n runProbe(`${origin}${spec.path(nonce())}`, spec, probeOptions),\n )\n : []\n const pageProbe = page\n ? [\n runProbe(\n pageProbeUrl(renderOrigin, page, renderSpellingNumber(runAt)),\n { kind: 'page', expectStatus: 200 },\n probeOptions,\n ),\n ]\n : []\n const probes = await Promise.all([...layoutProbes, ...pageProbe])\n const ok = probes.every((probe) => probe.ok)\n const failing = probes.filter((probe) => !probe.ok)\n const blind = !ok && failing.every((probe) => probe.challenged)\n const result: RenderMonitorSiteResult = { origin, ok, blind, probes }\n if (dryRun) return result\n const host = new URL(origin).host\n const detail = ok\n ? 'Fresh renders pass.'\n : failing.map(probeLine).join('; ')\n try {\n const now = clock()\n const { next, transition, failingSinceMs } = await store(\n renderMonitorCheckId(origin),\n (prior) => {\n const decided = nextRenderMonitorState(\n prior,\n { ok, detail, blind },\n {\n origin,\n label: `Page rendering on ${host}`,\n threshold,\n now,\n },\n )\n return {\n next: decided.next,\n result: {\n ...decided,\n // When the failures a recovery ends began.\n failingSinceMs: prior?.failingSinceMs ?? prior?.sinceMs ?? now,\n },\n }\n },\n )\n result.status = next.status\n result.consecutiveFailures = next.consecutiveFailures\n result.transition = transition\n if (transition === 'failing') {\n await raise('system.siteRenderFailing', {\n dedupeKey: host,\n context: {\n site: host,\n failures: next.consecutiveFailures,\n since: describeDuration(now - next.sinceMs),\n detail,\n },\n })\n } else if (transition === 'blind') {\n await raise('system.renderMonitorBlind', {\n dedupeKey: host,\n context: {\n site: host,\n runs: next.consecutiveBlindRuns ?? threshold,\n detail,\n },\n })\n } else if (transition === 'recovered') {\n await raise('system.siteRenderRecovered', {\n dedupeKey: host,\n context: {\n site: host,\n duration: describeDuration(now - failingSinceMs),\n },\n })\n }\n } catch (error) {\n result.error = error instanceof Error ? error.message : String(error)\n console.error(`[render-monitor] ${host} could not be recorded`, error)\n }\n return result\n },\n ),\n )\n return { dryRun, threshold, sites }\n}\n\n/**\n * One watched site as `/api/health/pages` reports it (AGL-3580).\n *\n * The shape of every other health check — `ok`, `ms`, a stable `code` — plus\n * when the monitor last saw the site, so a reader can tell a fresh verdict\n * from an old one without a second request.\n */\nexport interface RenderPagesCheck {\n ok: boolean\n ms: number\n code?: string\n /** When a run last rendered or failed this site's pages, ISO. */\n lastObservedAt: string | null\n /** When the site's current status began, ISO. */\n since: string | null\n}\n\n/**\n * A verdict older than this says the monitor stopped, not that the site did.\n * Four missed five-minute runs.\n */\nexport const RENDER_PAGES_STALE_MS = 20 * 60_000\n\n/** How many sites one `?site=` may ask about. */\nexport const RENDER_PAGES_MAX_SITES = 10\n\n/**\n * Which watched hosts a `?site=` asks about. Pure.\n *\n * Absent or empty asks about every watched site. A host that is not watched\n * is kept, so the caller can answer it red: a public monitor pointed at a\n * site nobody renders is a monitor that can never go red, which is the\n * mistake this door exists to undo.\n */\nexport function requestedRenderPagesHosts(\n query: string | null | undefined,\n watchedOrigins: readonly string[],\n): string[] {\n const asked = String(query ?? '')\n .split(/[\\s,]+/)\n .map((entry) => entry.trim().toLowerCase().replace(/^https?:\\/\\//, '').replace(/\\/.*$/, ''))\n .filter((entry) => /^[a-z0-9-]+(\\.[a-z0-9-]+)+$/.test(entry))\n const hosts = asked.length ? asked : watchedOrigins.map((origin) => new URL(origin).host)\n return [...new Set(hosts)].slice(0, RENDER_PAGES_MAX_SITES)\n}\n\n/**\n * The public verdict on real pages, per site, from the render monitor's\n * stored state (AGL-3580). Pure.\n *\n * This is what the status page's `Published sites` and `Marketing site`\n * monitors read. Before it they read `/api/health/render/*`, which builds a\n * node tree inside a route handler and never draws a page, and both stayed at\n * 100% through two outages on 2026-10-05 in which every fresh page hung.\n *\n * Red is reserved for the one thing a visitor would notice:\n *\n * - `not-rendering` — the monitor saw the site fail to render pages it could\n * not have served from a cache, `threshold` runs in a row.\n * - `not-watched` — the monitor renders nothing for this host, so this row\n * could never go red; fix the monitor's config or the URL.\n * - `state-unavailable` — the verdicts could not be read at all.\n *\n * Green with a code is a verdict this door cannot improve on, and is never\n * reported as an outage, because it is not one:\n *\n * - `awaiting-first-run` — a site added since the monitor last ran.\n * - `monitor-blind` — bot protection answered the monitor; the site's last\n * real verdict stands, and the operator alert says what to fix.\n * - `observation-stale` — no run in {@link RENDER_PAGES_STALE_MS}; the\n * monitor's own `render-monitor` row on `/api/health/crons` is what goes\n * red for that, so a stopped scheduler is never told as a site outage.\n */\nexport function renderPagesHealth(\n hosts: readonly string[],\n watchedOrigins: readonly string[],\n states: ReadonlyMap<string, Partial<RenderMonitorStateDoc>> | null,\n ms: number,\n now: number = Date.now(),\n): Record<string, RenderPagesCheck> {\n const watched = new Set(watchedOrigins.map((origin) => new URL(origin).host))\n const iso = (value: number | null | undefined) =>\n typeof value === 'number' && Number.isFinite(value) ? new Date(value).toISOString() : null\n const checks: Record<string, RenderPagesCheck> = {}\n if (!hosts.length) {\n checks['sites'] = { ok: false, ms, code: 'no-sites-watched', lastObservedAt: null, since: null }\n return checks\n }\n for (const host of hosts) {\n const blank = { ms, lastObservedAt: null, since: null }\n if (!watched.has(host)) {\n checks[host] = { ...blank, ok: false, code: 'not-watched' }\n continue\n }\n if (states === null) {\n checks[host] = { ...blank, ok: false, code: 'state-unavailable' }\n continue\n }\n const state = states.get(renderMonitorHostCheckId(host))\n if (!state) {\n checks[host] = { ...blank, ok: true, code: 'awaiting-first-run' }\n continue\n }\n const observed = state.lastObservedAtMs ?? state.lastOkAtMs ?? null\n const row = { ms, lastObservedAt: iso(observed), since: iso(state.sinceMs) }\n if (state.status === 'degraded') {\n checks[host] = { ...row, ok: false, code: 'not-rendering' }\n } else if ((state.consecutiveBlindRuns ?? 0) > 0) {\n checks[host] = { ...row, ok: true, code: 'monitor-blind' }\n } else if (now - (state.updatedAtMs ?? 0) > RENDER_PAGES_STALE_MS) {\n checks[host] = { ...row, ok: true, code: 'observation-stale' }\n } else {\n checks[host] = { ...row, ok: true }\n }\n }\n return checks\n}\n\n/**\n * Read the stored verdicts for `hosts`, one batched read. Null when the read\n * fails, which {@link renderPagesHealth} reports red rather than calm.\n */\nexport async function readRenderMonitorStates(\n hosts: readonly string[],\n): Promise<Map<string, Partial<RenderMonitorStateDoc>> | null> {\n try {\n const { default: firebaseAdmin } = await import('./firebase-admin')\n const db = firebaseAdmin.app().firestore()\n const refs = hosts.map((host) =>\n db.collection(RENDER_MONITOR_COLLECTION).doc(renderMonitorHostCheckId(host)),\n )\n const snapshots = refs.length ? await db.getAll(...refs) : []\n const states = new Map<string, Partial<RenderMonitorStateDoc>>()\n for (const snapshot of snapshots) {\n if (snapshot.exists) states.set(snapshot.id, snapshot.data() as Partial<RenderMonitorStateDoc>)\n }\n return states\n } catch (error) {\n console.error('[render-monitor] stored verdicts could not be read', error)\n return null\n }\n}\n"],"names":["TENANT_APEX","RENDER_MONITOR_COLLECTION","RENDER_MONITOR_CHECK_PREFIX","RENDER_MONITOR_JOB_ID","RENDER_MONITOR_TIMEOUT_MS","RENDER_MONITOR_DEFAULT_THRESHOLD","RENDER_PROBE_ISR_PREFIX","RENDER_PROBES","kind","path","expectStatus","nonce","CHECKPOINT_MARKER","CACHED_STATES","Set","gradeRenderProbe","response","body","test","ok","challenged","code","detail","status","location","contentType","includes","cache","String","cacheState","trim","toUpperCase","has","PLATFORM_RENDER_PAGES","join","PLATFORM_CONSOLE_VERCEL_PROJECT_ID","PLATFORM_RENDER_ORIGIN","CNAME_HOST_PREFIX","MAX_SPELLING_BITS","spellingLetters","host","toLowerCase","map","char","index","filter","slice","freshHostSpelling","n","apex","subdomain","endsWith","prefix","chars","letters","capacity","length","value","Math","max","floor","Number","bits","forEach","bit","dots","repeat","renderSpellingNumber","nowMs","Date","UTC","parseRenderMonitorPages","text","byHost","Map","raw","split","entry","replace","slash","indexOf","paths","get","push","set","origin","resolveRenderMonitorPages","env","off","renderOrigin","pages","platform","originOf","trimmed","resolveRenderMonitorTargets","label","demo","listed","Boolean","paged","page","renderMonitorProbesLayout","count","slot","firstEveryRun","abs","renderMonitorPageTurn","turns","flatMap","site","renderMonitorCheckId","renderMonitorHostCheckId","URL","nextRenderMonitorState","prior","observation","context","threshold","now","checkId","wasDegraded","blind","blindRuns","consecutiveBlindRuns","next","sinceMs","updatedAtMs","consecutiveFailures","failingSinceMs","lastOkAtMs","blindSinceMs","lastObservedAtMs","transition","sighted","failures","degraded","RENDER_MONITOR_STATE_REFRESH_MS","renderMonitorStateNeedsWrite","decided","some","key","firestoreStore","work","default","firebaseAdmin","db","app","firestore","ref","collection","doc","runTransaction","transaction","snapshot","exists","data","result","defaultRaise","type","options","raiseOperatorAlert","describeDuration","ms","minutes","round","hours","rest","pageProbeUrl","turn","spelling","url","searchParams","toString","probeLine","row","pathname","runProbe","spec","startedAt","clock","fetcher","redirect","headers","accept","signal","AbortSignal","timeout","timeoutMs","verdict","httpStatus","error","name","timedOut","cause","runRenderMonitor","process","store","raise","dryRun","parsedThreshold","parseInt","isFinite","random","probeOptions","fetch","canRenderPages","runAt","targets","due","layout","undefined","target","sites","Promise","all","layoutProbes","pageProbe","probes","every","probe","failing","dedupeKey","since","runs","duration","Error","message","console","RENDER_PAGES_STALE_MS","RENDER_PAGES_MAX_SITES","requestedRenderPagesHosts","query","watchedOrigins","asked","hosts","renderPagesHealth","states","watched","iso","toISOString","checks","lastObservedAt","state","blank","observed","readRenderMonitorStates","refs","snapshots","getAll","id"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,WAAW,QAAQ,qCAAoC;AAGhE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuFC,GAED,6DAA6D,GAC7D,MAAMC,4BAA4B;AAElC,uDAAuD,GACvD,OAAO,MAAMC,8BAA8B,mBAAkB;AAE7D,iEAAiE,GACjE,OAAO,MAAMC,wBAAwB,iBAAgB;AAErD;;;;CAIC,GACD,OAAO,MAAMC,4BAA4B,MAAM;AAE/C,qDAAqD,GACrD,OAAO,MAAMC,mCAAmC,EAAC;AAEjD;;;;CAIC,GACD,OAAO,MAAMC,0BAA0B,uBAAsB;AAY7D,OAAO,MAAMC,gBAA4C;IACvD;QAAEC,MAAM;QAAWC,MAAM,IAAM;QAAWC,cAAc;IAAI;IAC5D;QACEF,MAAM;QACNC,MAAM,CAACE,QAAU,GAAGL,0BAA0BK,OAAO;QACrDD,cAAc;IAChB;CACD,CAAA;AAqBD,+EAA+E,GAC/E,MAAME,oBAAoB;AAE1B;;;CAGC,GACD,MAAMC,gBAAgB,IAAIC,IAAI;IAAC;IAAO;IAAS;CAAY;AAE3D;;;;;;CAMC,GACD,OAAO,SAASC,iBACdC,QAA6B,EAC7BN,YAAoB;QAEPM,gBAyBWA,uBAwBHA;IAjDrB,MAAMC,QAAOD,iBAAAA,SAASC,IAAI,YAAbD,iBAAiB;IAC9B,IAAIJ,kBAAkBM,IAAI,CAACD,OAAO;QAChC,OAAO;YACLE,IAAI;YACJC,YAAY;YACZC,MAAM;YACNC,QAAQ,CAAC,8BAA8B,EAAEN,SAASO,MAAM,CAAC,6DAA6D,CAAC;QACzH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AG,CAACqE,SAASgG,EAAE,EAAEhG,SAASE,IAAI;QAC5D;QACA,OAAOiF;IACT,EAAE,OAAO9C,OAAO;QACdqC,QAAQrC,KAAK,CAAC,sDAAsDA;QACpE,OAAO;IACT;AACF"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/render-monitor.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 { TENANT_APEX } from '@aglyn/aglyn/app-utils/tenant-apex'\nimport type { OperatorHealthStateDoc } from './operator-health'\n\n/**\n * THE RENDER MONITOR (AGL-3568): does a published site still render a page\n * that was not already in a cache?\n *\n * On 2026-10-05 every uncached page render on the published-site runtime\n * hung to the platform's 60 s limit for 28 minutes, and nothing alerted. The\n * three monitors that existed each missed it for its own reason:\n *\n * - the GitHub uptime probe is scheduled every 15 minutes and GitHub ran it\n * four times that day, none of them during the outage;\n * - its page rows fetch `/`, which the ISR cache answers, so a visitor's\n * page that was cached still loaded and the row stayed green;\n * - `/api/health/render/site` runs the page LOADER in-process and never the\n * site layout, which is where the request was stuck.\n *\n * So this fetches pages over HTTP, from the console (a different deployment\n * from the one it watches), on Cloud Scheduler every five minutes, and asks\n * for two pages no cache can answer:\n *\n * - `dynamic` — `/search`, a route every site has that renders on every\n * request (`force-dynamic`) inside the full site layout. A 200 that is a\n * complete document proves the layout and head ran just now.\n * - `isr` — a path nobody has ever requested, under the catch-all page.\n * A never-seen path is the one request the ISR cache cannot answer, so it\n * renders in the same static context every published page renders in,\n * which is the context the 2026-09-09 outage only appeared in. It is a\n * 404 by construction, and the site's own not-found page is drawn inside\n * the same layout, so a complete 404 document is a pass.\n *\n * A site that fails `threshold` runs in a row raises\n * `system.siteRenderFailing` once; the first passing run after that raises\n * `system.siteRenderRecovered` once.\n *\n * ## A challenge is not a failed render (AGL-3580)\n *\n * When bot protection answers instead of the site, this run saw nothing about\n * the site at all. On 2026-10-05 the console had no `AGLYN_PROBE_TOKEN`, every\n * `/search` probe got the 429 checkpoint for three hours, and the monitor told\n * the operator \"Pages are not rendering on aglyn.com\" and then \"rendering\n * again after 3 h\" about a site that was serving pages the whole time. So a\n * run whose only failures are challenges is BLIND: it leaves the site's\n * verdict and failure count exactly as they were, and `threshold` blind runs\n * in a row raise `system.renderMonitorBlind` once, which names the setup\n * problem instead of an outage. A run with a real failure beside a challenge\n * is still a failure, because the real one is evidence. The state lives in\n * `operatorHealthState/render-monitor--<host>`, beside every other health\n * check, so Staff → Operator alerts lists it with its status and since when.\n *\n * Nothing here names an Aglyn host for anyone else: the default target is the\n * install's own demonstration site label under its own tenant apex, the\n * convention the middleware and the render canaries already follow. The one\n * exception is `PLATFORM_RENDER_PAGES` below, which applies on Aglyn's own\n * console deployment and nowhere else.\n *\n * ## Real pages, rendered fresh (AGL-3571)\n *\n * The two probes above draw the layout. They do not draw a page BODY, and\n * beta.223 hung only on page bodies with an image in them (an ancestor walk\n * looped on the page root, AGL-3565): `demo` has no images and the not-found\n * page has no body, so this monitor read green through it. So a third probe,\n * `page`, renders a real published page through the full ISR path — through\n * the tenant's `*.vercel.app` production domain (`RENDER_MONITOR_RENDER_ORIGIN`),\n * which honors `?tenantHost=` and sits behind Deployment Protection, naming\n * the site with a spelling no cache holds (`freshHostSpelling`). The cache key\n * includes the `[host]` segment, and `normalizeHostAlias` resolves every\n * spelling to the same site. Without the automation bypass the render origin\n * answers its sign-in redirect, so no `page` probe is made at all.\n *\n * One page per site per run, rotating through that site's list: a platform\n * break fails every page with an image, so every run, and alerts as fast as\n * before; a break on one page alone is seen on its turn.\n *\n * ## Layout probes take turns past the first site\n *\n * A fresh layout reads the site's whole screen and collection lists, and a\n * large site makes that the most expensive request the platform serves: the\n * marketing site's 109 screens made this monitor a fifth of the project's\n * Firestore reads. Every site draws them on its turn, one site per run (see\n * {@link renderMonitorProbesLayout}), and the sites' pages take turns the\n * same way, one page per run across every watched site (see\n * {@link renderMonitorPageTurn}): three fresh renders a run. A platform-wide\n * break fails whichever page and layout are drawn, so it is still seen on\n * the run it happens and alerted on the next; a break on one page alone is\n * seen on that page's turn. Without `page` probes (no render origin or no\n * bypass) the first target — the demonstration site — draws its layout on\n * every run instead, because nothing else would be looked at every run\n * (AGL-3928).\n */\n\n/** The state documents' collection: the health checks' own. */\nconst RENDER_MONITOR_COLLECTION = 'operatorHealthState'\n\n/** Every render monitor document id starts with this. */\nexport const RENDER_MONITOR_CHECK_PREFIX = 'render-monitor--'\n\n/** The beat id `/api/health/crons` reads for the scheduled run. */\nexport const RENDER_MONITOR_JOB_ID = 'render-monitor'\n\n/**\n * How long one page fetch may take. Well under the 60 s a platform function\n * may run, so a hung render is graded here as a timeout rather than waiting\n * for the platform's 504, and well under the route's own `maxDuration`.\n */\nexport const RENDER_MONITOR_TIMEOUT_MS = 25_000\n\n/** Failing runs in a row before the alert goes out. */\nexport const RENDER_MONITOR_DEFAULT_THRESHOLD = 2\n\n/**\n * The prefix of the never-requested path the `isr` probe asks for. A\n * lowercase slug on purpose: it must reach the catch-all page like any\n * screen slug would, not a reserved or rewritten route.\n */\nexport const RENDER_PROBE_ISR_PREFIX = '/aglyn-render-probe-'\n\nexport type RenderProbeKind = 'dynamic' | 'isr' | 'page'\n\nexport interface RenderProbeSpec {\n kind: RenderProbeKind\n /** The path to request, given a fresh nonce. */\n path: (nonce: string) => string\n /** The status a healthy render answers with. */\n expectStatus: number\n}\n\nexport const RENDER_PROBES: readonly RenderProbeSpec[] = [\n { kind: 'dynamic', path: () => '/search', expectStatus: 200 },\n {\n kind: 'isr',\n path: (nonce) => `${RENDER_PROBE_ISR_PREFIX}${nonce}`,\n expectStatus: 404,\n },\n]\n\n/** One fetched response, reduced to what grading reads. */\nexport interface RenderProbeResponse {\n status: number\n contentType?: string | null\n body?: string\n location?: string | null\n /** `x-vercel-cache` on Vercel, `x-nextjs-cache` on a plain `next start`. */\n cacheState?: string | null\n}\n\nexport interface RenderProbeVerdict {\n ok: boolean\n /** Bot protection answered instead of the site. */\n challenged: boolean\n /** A stable code; `ok` on a pass. */\n code: string\n detail: string\n}\n\n/** Vercel's challenge interstitial, matched on the body like the front doors. */\nconst CHECKPOINT_MARKER = /Vercel Security Checkpoint/i\n\n/**\n * Cache states that mean the bytes came out of a store. A probe meant to\n * prove a render cannot pass on one of these, whatever the status.\n */\nconst CACHED_STATES = new Set(['HIT', 'STALE', 'PRERENDER'])\n\n/**\n * Grade one probe response. Pure.\n *\n * The page markers are the front doors' (`tools/scripts/lib/front-door.mjs`)\n * and for their reason: structural, never site copy. `</html>` proves the\n * document finished streaming, `/_next/static/` that our build produced it.\n */\nexport function gradeRenderProbe(\n response: RenderProbeResponse,\n expectStatus: number,\n): RenderProbeVerdict {\n const body = response.body ?? ''\n if (CHECKPOINT_MARKER.test(body)) {\n return {\n ok: false,\n challenged: true,\n code: 'challenged',\n detail: `bot protection answered (HTTP ${response.status}) instead of the site; check AGLYN_PROBE_TOKEN on the console`,\n }\n }\n if (response.status >= 300 && response.status < 400) {\n return {\n ok: false,\n challenged: false,\n code: 'redirected',\n detail: `redirected to ${response.location ?? '?'}, so no page was rendered`,\n }\n }\n if (response.status !== expectStatus) {\n return {\n ok: false,\n challenged: false,\n code: `http-${response.status}`,\n detail: `HTTP ${response.status}`,\n }\n }\n if (!/text\\/html/i.test(response.contentType ?? '')) {\n return {\n ok: false,\n challenged: false,\n code: 'not-html',\n detail: `not HTML (${response.contentType || 'no content-type'})`,\n }\n }\n if (!body.includes('</html>')) {\n return {\n ok: false,\n challenged: false,\n code: 'incomplete',\n detail: 'the document never finished (no </html>)',\n }\n }\n if (!body.includes('/_next/static/')) {\n return {\n ok: false,\n challenged: false,\n code: 'not-our-render',\n detail: 'no Next asset references, so the app did not render it',\n }\n }\n const cache = String(response.cacheState ?? '').trim().toUpperCase()\n if (CACHED_STATES.has(cache)) {\n return {\n ok: false,\n challenged: false,\n code: 'served-from-cache',\n detail: `served from cache (${cache}), so it proves no render`,\n }\n }\n return { ok: true, challenged: false, code: 'ok', detail: 'rendered' }\n}\n\n/**\n * The pages Aglyn's own console renders fresh when `RENDER_MONITOR_PAGES` is\n * unset: Aglyn's own marketing pages, images and a form between them, the\n * same fallback as the canary's (`tools/scripts/lib/prod-canary.mjs`\n * `DEFAULT_TENANT_HOSTS`). Applied ONLY on that console deployment\n * (`VERCEL_PROJECT_ID`), so no other install ever requests them.\n *\n * The real client pages the platform watches are named in that console's\n * `RENDER_MONITOR_PAGES` environment variable, never here: this repository\n * is public, and a client's site address is theirs to publish, not ours.\n */\nexport const PLATFORM_RENDER_PAGES = [\n 'aglyn.com/',\n 'aglyn.com/press',\n 'aglyn.com/blog',\n 'aglyn.com/contact',\n].join(' ')\n\n/** Aglyn's console project on Vercel, the one deployment the list above is for. */\nexport const PLATFORM_CONSOLE_VERCEL_PROJECT_ID = 'prj_gEzxEXc0Lhs81rmaXIg2a1GbsDfl'\n\n/**\n * The tenant's production project domain on Vercel: follows every promote and\n * rollback, honors `?tenantHost=`, and is reachable only with the bypass.\n */\nexport const PLATFORM_RENDER_ORIGIN = 'https://aglyn-tenant-aglyn.vercel.app'\n\n/** The middleware's custom-domain sentinel (`apps/tenant/utils/get-host.ts`). */\nconst CNAME_HOST_PREFIX = 'cname--'\n\n/** Letters past this are never recased, so the bit arithmetic stays in 32 bits. */\nconst MAX_SPELLING_BITS = 30\n\nfunction spellingLetters(host: string): number[] {\n return [...host.toLowerCase()]\n .map((char, index) => (/[a-z]/.test(char) ? index : -1))\n .filter((index) => index >= 0)\n .slice(0, MAX_SPELLING_BITS)\n}\n\n/**\n * Spelling number `n` of one site: a `?tenantHost=` value that resolves to\n * that site and is a `[host]` route segment no other number produces, so the\n * page it asks for has no cache entry to come from.\n *\n * - `{sub}.{apex}` → the full name, letters upper-cased by the bits of `n`,\n * then one trailing dot per exhausted round of cases.\n * - any other name → `cname--{name}`, recased the same way and cycling after\n * `2 ** letters` (that form keeps trailing dots), with the prefix left\n * lower-case because the canonical-domain redirect tests the raw segment.\n *\n * MUST stay identical to `freshHostSpelling` in\n * `tools/scripts/lib/prod-canary.mjs`; `apps/tenant/specs/probe-host-spelling.spec.ts`\n * pins both against `normalizeHostAlias`.\n */\nexport function freshHostSpelling(host: string, n: number, apex: string = TENANT_APEX): string {\n const subdomain = host.endsWith(`.${apex}`)\n const prefix = subdomain ? '' : CNAME_HOST_PREFIX\n const chars = [...host.toLowerCase()]\n const letters = spellingLetters(host)\n const capacity = 2 ** letters.length\n const value = Math.max(0, Math.floor(Number(n) || 0))\n const bits = value % capacity\n letters.forEach((index, bit) => {\n if (Math.floor(bits / 2 ** bit) % 2 === 1) chars[index] = chars[index].toUpperCase()\n })\n const dots = subdomain ? '.'.repeat(Math.floor(value / capacity)) : ''\n return `${prefix}${chars.join('')}${dots}`\n}\n\n/**\n * The spelling number for a run at `nowMs`: minutes since 2026-10-01, so it\n * never repeats on one deployment — a `{sub}.aglyn.app` name of 18 letters\n * gains its first trailing dot after half a year.\n */\nexport function renderSpellingNumber(nowMs: number): number {\n return Math.max(1, Math.floor((nowMs - Date.UTC(2026, 9, 1)) / 60_000))\n}\n\n/** One watched site's real pages. */\nexport interface RenderMonitorPages {\n /** The site's public origin, which keys its state document. */\n origin: string\n host: string\n paths: string[]\n}\n\n/**\n * `\"a.example.app b.example.app/services, https://b.example.app/contact\"` →\n * one entry per host, paths merged, `/` when an entry names none. Entries that\n * are not a hostname are dropped, as `RENDER_MONITOR_ORIGINS` drops them.\n */\nexport function parseRenderMonitorPages(text: string | undefined | null): RenderMonitorPages[] {\n const byHost = new Map<string, string[]>()\n for (const raw of String(text ?? '').split(/[\\s,]+/)) {\n const entry = raw.trim().replace(/^https?:\\/\\//i, '')\n if (!entry) continue\n const slash = entry.indexOf('/')\n const host = (slash === -1 ? entry : entry.slice(0, slash)).toLowerCase()\n if (!/^[a-z0-9-]+(\\.[a-z0-9-]+)+$/.test(host)) continue\n const path = slash === -1 ? '/' : entry.slice(slash).replace(/\\/+$/, '') || '/'\n const paths = byHost.get(host) ?? []\n if (!paths.includes(path)) paths.push(path)\n byHost.set(host, paths)\n }\n return [...byHost].map(([host, paths]) => ({ origin: `https://${host}`, host, paths }))\n}\n\n/**\n * Which real pages the monitor renders, and through which origin.\n *\n * `RENDER_MONITOR_PAGES` (same grammar as the canary's `CANARY_TENANT_HOSTS`)\n * and `RENDER_MONITOR_RENDER_ORIGIN`, else — on Aglyn's own console only —\n * `PLATFORM_RENDER_PAGES` through `PLATFORM_RENDER_ORIGIN`. `off` (here or in\n * `RENDER_MONITOR_ORIGINS`) renders none. No render origin, no pages.\n */\nexport function resolveRenderMonitorPages(\n env: Readonly<Record<string, string | undefined>>,\n): { renderOrigin: string; pages: RenderMonitorPages[] } {\n const off = /^(off|none|false|0)$/i\n const raw = String(env['RENDER_MONITOR_PAGES'] ?? '').trim()\n if (off.test(raw) || off.test(String(env['RENDER_MONITOR_ORIGINS'] ?? '').trim())) {\n return { renderOrigin: '', pages: [] }\n }\n const platform = env['VERCEL_PROJECT_ID'] === PLATFORM_CONSOLE_VERCEL_PROJECT_ID\n const renderOrigin =\n originOf(env['RENDER_MONITOR_RENDER_ORIGIN']) || (platform ? PLATFORM_RENDER_ORIGIN : '')\n const pages = parseRenderMonitorPages(raw || (platform ? PLATFORM_RENDER_PAGES : ''))\n return renderOrigin ? { renderOrigin, pages } : { renderOrigin: '', pages: [] }\n}\n\n/** A configured value as an origin, or '' when it is not one. */\nexport function originOf(value: string | undefined | null): string {\n const trimmed = String(value ?? '').trim().replace(/\\/+$/, '')\n return /^https?:\\/\\/[^/\\s?#]+$/i.test(trimmed) ? trimmed.toLowerCase() : ''\n}\n\n/**\n * Which sites the monitor renders, from the console's environment.\n *\n * 1. The install's demonstration site: `OPERATOR_HEALTH_TENANT_ORIGIN` when\n * set (the one published site the operator alerts tick already watches),\n * else `https://<AGLYN_TENANT_DEMO or demo>.<tenant apex>`.\n * 2. Plus every origin in `RENDER_MONITOR_ORIGINS`, comma separated.\n *\n * `RENDER_MONITOR_ORIGINS=off` watches nothing, for an install with no\n * published site to watch. Values that are not origins are dropped.\n */\nexport function resolveRenderMonitorTargets(\n env: Readonly<Record<string, string | undefined>>,\n): string[] {\n const raw = String(env['RENDER_MONITOR_ORIGINS'] ?? '').trim()\n if (/^(off|none|false|0)$/i.test(raw)) return []\n const apex =\n String(env['NEXT_PUBLIC_TENANT_DOMAIN'] ?? '').trim() || TENANT_APEX\n const label = String(env['AGLYN_TENANT_DEMO'] ?? '').trim() || 'demo'\n const demo =\n originOf(env['OPERATOR_HEALTH_TENANT_ORIGIN']) ||\n originOf(`https://${label}.${apex}`)\n const listed = raw\n .split(/[\\s,]+/)\n .map((value) => originOf(value))\n .filter(Boolean)\n // A site whose pages are rendered is watched whole: its layout probes too.\n const paged = resolveRenderMonitorPages(env).pages.map((page) => page.origin)\n return [...new Set([demo, ...listed, ...paged].filter(Boolean))]\n}\n\n/**\n * Whether the target at `index` (of `count`, in\n * {@link resolveRenderMonitorTargets} order) draws its layout probes in the\n * five-minute `slot`. With `firstEveryRun`, the first always and the rest\n * one per slot in turn; without it, one target per slot in turn, the first\n * included — the mode for a run that draws a real page anyway (AGL-3928).\n */\nexport function renderMonitorProbesLayout(\n index: number,\n count: number,\n slot: number,\n firstEveryRun = true,\n): boolean {\n if (count <= 1) return true\n if (!firstEveryRun) return Math.abs(slot) % count === index\n if (index <= 0 || count <= 2) return true\n return Math.abs(slot) % (count - 1) === index - 1\n}\n\n/** One site's page that the `page` probe renders this run. */\nexport interface RenderMonitorPageTurn {\n site: RenderMonitorPages\n path: string\n}\n\n/**\n * The page the five-minute `slot` renders: the sites' pages laid end to end\n * in {@link resolveRenderMonitorPages} order, one per slot in turn, so a\n * site with three pages is seen three times as often as a site with one and\n * every page comes round within `pages × 5` minutes. Null when there is\n * nothing to render.\n */\nexport function renderMonitorPageTurn(\n pages: readonly RenderMonitorPages[],\n slot: number,\n): RenderMonitorPageTurn | null {\n const turns = pages.flatMap((site) => site.paths.map((path) => ({ site, path })))\n if (!turns.length) return null\n return turns[Math.abs(slot) % turns.length] ?? null\n}\n\n/** The state document id for one origin. */\nexport function renderMonitorCheckId(origin: string): string {\n return renderMonitorHostCheckId(new URL(origin).host)\n}\n\n/** The state document id for one host, as {@link renderMonitorCheckId} names it. */\nexport function renderMonitorHostCheckId(host: string): string {\n return `${RENDER_MONITOR_CHECK_PREFIX}${host}`\n}\n\n/** One render monitor state document. */\nexport interface RenderMonitorStateDoc extends OperatorHealthStateDoc {\n origin: string\n /** Failing runs in a row, reset by any passing run. */\n consecutiveFailures: number\n /** When the current run of failures began; null while passing. */\n failingSinceMs: number | null\n lastOkAtMs: number | null\n /** Runs in a row where bot protection answered instead of the site. */\n consecutiveBlindRuns?: number\n /** When the current blind stretch began; null while the monitor can see. */\n blindSinceMs?: number | null\n /** When a run last saw the site itself: a pass or a real failure. */\n lastObservedAtMs?: number | null\n}\n\nexport type RenderMonitorTransition = 'failing' | 'recovered' | 'blind' | null\n\n/**\n * The next state for one site, given what this run saw. Pure.\n *\n * The status turns `degraded` only once `threshold` runs in a row have\n * failed, so one slow cold start or one dropped connection says nothing. It\n * turns back on the first passing run, because a render that works is\n * proof, and a recovery held back is a recovery nobody hears about.\n *\n * A BLIND observation (every failure was a bot-protection challenge) changes\n * nothing about the site: its status, failure count and since-time carry over\n * untouched, and only the blind count moves. It transitions to `blind` once,\n * on the `threshold`-th blind run in a row.\n */\nexport function nextRenderMonitorState(\n prior: Partial<RenderMonitorStateDoc> | null,\n observation: { ok: boolean; detail: string; blind?: boolean },\n context: { origin: string; label: string; threshold: number; now: number },\n): { next: RenderMonitorStateDoc; transition: RenderMonitorTransition } {\n const { origin, label, threshold, now } = context\n const checkId = renderMonitorCheckId(origin)\n const detail = String(observation.detail ?? '').slice(0, 1_000)\n const wasDegraded = prior?.status === 'degraded'\n if (!observation.ok && observation.blind) {\n const blindRuns = (prior?.consecutiveBlindRuns ?? 0) + 1\n return {\n next: {\n checkId,\n label,\n origin,\n status: wasDegraded ? 'degraded' : 'ok',\n sinceMs: prior?.sinceMs ?? now,\n detail: `The monitor cannot see this site: ${detail}`.slice(0, 1_000),\n updatedAtMs: now,\n consecutiveFailures: prior?.consecutiveFailures ?? 0,\n failingSinceMs: prior?.failingSinceMs ?? null,\n lastOkAtMs: prior?.lastOkAtMs ?? null,\n consecutiveBlindRuns: blindRuns,\n blindSinceMs: prior?.blindSinceMs ?? now,\n lastObservedAtMs: prior?.lastObservedAtMs ?? null,\n },\n transition: blindRuns === Math.max(1, threshold) ? 'blind' : null,\n }\n }\n const sighted = { consecutiveBlindRuns: 0, blindSinceMs: null, lastObservedAtMs: now }\n if (observation.ok) {\n return {\n next: {\n checkId,\n label,\n origin,\n status: 'ok',\n sinceMs: !wasDegraded && prior?.sinceMs ? prior.sinceMs : now,\n detail,\n updatedAtMs: now,\n consecutiveFailures: 0,\n failingSinceMs: null,\n lastOkAtMs: now,\n ...sighted,\n },\n transition: wasDegraded ? 'recovered' : null,\n }\n }\n const failures = (prior?.consecutiveFailures ?? 0) + 1\n const failingSinceMs = prior?.failingSinceMs ?? now\n const degraded = wasDegraded || failures >= Math.max(1, threshold)\n return {\n next: {\n checkId,\n label,\n origin,\n status: degraded ? 'degraded' : 'ok',\n sinceMs: degraded\n ? wasDegraded && prior?.sinceMs\n ? prior.sinceMs\n : failingSinceMs\n : (prior?.sinceMs ?? now),\n detail,\n updatedAtMs: now,\n consecutiveFailures: failures,\n failingSinceMs,\n lastOkAtMs: prior?.lastOkAtMs ?? null,\n ...sighted,\n },\n transition: degraded && !wasDegraded ? 'failing' : null,\n }\n}\n\n/** One probe as the report shows it. */\nexport interface RenderProbeRow extends RenderProbeVerdict {\n kind: RenderProbeKind\n url: string\n ms: number\n httpStatus: number | null\n}\n\n/** One site's result for a run. */\nexport interface RenderMonitorSiteResult {\n origin: string\n ok: boolean\n /** Every failure this run was a challenge, so it saw nothing of the site. */\n blind: boolean\n probes: RenderProbeRow[]\n /** The state written; absent on a dry run or a failed write. */\n status?: 'ok' | 'degraded'\n consecutiveFailures?: number\n transition?: RenderMonitorTransition\n error?: string\n}\n\nexport interface RenderMonitorReport {\n dryRun: boolean\n threshold: number\n sites: RenderMonitorSiteResult[]\n}\n\n/** The read-modify-write of one site's state, as one transaction. */\nexport type RenderMonitorStore = <T>(\n checkId: string,\n work: (prior: Partial<RenderMonitorStateDoc> | null) => {\n next: RenderMonitorStateDoc\n result: T\n },\n) => Promise<T>\n\n/**\n * How long a passing site's stored state may go without being rewritten.\n *\n * A run that changes nothing about a site's verdict — the common run — used\n * to rewrite its document anyway, three documents every five minutes\n * (AGL-3932). The `observation-stale` rule in {@link renderPagesHealth} reads\n * `updatedAtMs` against {@link RENDER_PAGES_STALE_MS}, so the document is\n * refreshed at half that, and on every change of verdict, count or blind\n * stretch.\n */\nexport const RENDER_MONITOR_STATE_REFRESH_MS = 10 * 60_000\n\n/**\n * Whether a run's state differs from the stored one in anything the reader\n * or the next run decides by, or the stored one is old enough to refresh.\n */\nexport function renderMonitorStateNeedsWrite(\n prior: Partial<RenderMonitorStateDoc> | null,\n next: RenderMonitorStateDoc,\n now: number,\n): boolean {\n if (!prior) return true\n const decided: Array<keyof RenderMonitorStateDoc> = [\n 'status',\n 'sinceMs',\n 'detail',\n 'consecutiveFailures',\n 'failingSinceMs',\n 'consecutiveBlindRuns',\n 'blindSinceMs',\n 'label',\n 'origin',\n ]\n if (decided.some((key) => (prior[key] ?? null) !== (next[key] ?? null))) return true\n const updatedAtMs = typeof prior.updatedAtMs === 'number' ? prior.updatedAtMs : 0\n return now - updatedAtMs >= RENDER_MONITOR_STATE_REFRESH_MS || now < updatedAtMs\n}\n\n/**\n * The default store: one Firestore transaction on the site's document, so\n * two overlapping runs cannot both decide they saw the edge. The document is\n * written only when {@link renderMonitorStateNeedsWrite} says so.\n */\nconst firestoreStore: RenderMonitorStore = async (checkId, work) => {\n const { default: firebaseAdmin } = await import('./firebase-admin')\n const db = firebaseAdmin.app().firestore()\n const ref = db.collection(RENDER_MONITOR_COLLECTION).doc(checkId)\n return db.runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n const prior = snapshot.exists\n ? (snapshot.data() as Partial<RenderMonitorStateDoc>)\n : null\n const { next, result } = work(prior)\n if (renderMonitorStateNeedsWrite(prior, next, next.updatedAtMs)) transaction.set(ref, next)\n return result\n })\n}\n\ntype RaiseAlert = (\n type: string,\n options: { dedupeKey?: string; context?: Record<string, string | number> },\n) => Promise<unknown>\n\nconst defaultRaise: RaiseAlert = async (type, options) => {\n const { raiseOperatorAlert } = await import('./operator-alerts')\n return raiseOperatorAlert(type, options)\n}\n\nfunction describeDuration(ms: number): string {\n const minutes = Math.max(1, Math.round(ms / 60_000))\n if (minutes < 60) return `${minutes} min`\n const hours = Math.floor(minutes / 60)\n const rest = minutes % 60\n return rest ? `${hours} h ${rest} min` : `${hours} h`\n}\n\n/**\n * The `page` probe's URL for one run: this run's page (see\n * {@link renderMonitorPageTurn}) under this run's spelling of its site.\n */\nexport function pageProbeUrl(\n renderOrigin: string,\n turn: RenderMonitorPageTurn,\n spelling: number,\n): string {\n const url = new URL(turn.path || '/', renderOrigin)\n url.searchParams.set('tenantHost', freshHostSpelling(turn.site.host, spelling))\n return url.toString()\n}\n\nfunction probeLine(row: RenderProbeRow): string {\n return `${row.kind} ${new URL(row.url).pathname}: ${row.detail} (${row.ms} ms)`\n}\n\n/** Fetch and grade one probe. Never throws. */\nasync function runProbe(\n url: string,\n spec: { kind: RenderProbeKind; expectStatus: number },\n options: {\n fetcher: typeof fetch\n headers: Record<string, string>\n timeoutMs: number\n clock: () => number\n },\n): Promise<RenderProbeRow> {\n const startedAt = options.clock()\n try {\n const response = await options.fetcher(url, {\n redirect: 'manual',\n cache: 'no-store',\n headers: {\n 'user-agent': 'aglyn-render-monitor',\n accept: 'text/html,application/xhtml+xml',\n ...options.headers,\n },\n signal: AbortSignal.timeout(options.timeoutMs),\n })\n const body = await response.text()\n const verdict = gradeRenderProbe(\n {\n status: response.status,\n contentType: response.headers.get('content-type'),\n body,\n location: response.headers.get('location'),\n cacheState:\n response.headers.get('x-vercel-cache') ??\n response.headers.get('x-nextjs-cache'),\n },\n spec.expectStatus,\n )\n return {\n kind: spec.kind,\n url,\n ms: options.clock() - startedAt,\n httpStatus: response.status,\n ...verdict,\n }\n } catch (error) {\n const name = (error as { name?: string } | null)?.name\n const timedOut = name === 'TimeoutError' || name === 'AbortError'\n return {\n kind: spec.kind,\n url,\n ms: options.clock() - startedAt,\n httpStatus: null,\n ok: false,\n challenged: false,\n code: timedOut ? 'timeout' : 'unreachable',\n detail: timedOut\n ? `no complete page in ${Math.round(options.timeoutMs / 1_000)} s`\n : `unreachable (${(error as { cause?: { code?: string } } | null)?.cause?.code ?? name ?? 'error'})`,\n }\n }\n}\n\n/**\n * One run: render every target, record each site's state, raise the edge.\n *\n * A dry run fetches and grades and writes nothing, so a person can ask\n * \"what would the monitor see right now\" without moving its state.\n */\nexport async function runRenderMonitor(\n options: {\n dryRun?: boolean\n env?: Readonly<Record<string, string | undefined>>\n fetcher?: typeof fetch\n /** Our own edge's bypass headers, from the caller's environment. */\n headers?: Record<string, string>\n now?: () => number\n nonce?: () => string\n timeoutMs?: number\n store?: RenderMonitorStore\n raise?: RaiseAlert\n } = {},\n): Promise<RenderMonitorReport> {\n const env = options.env ?? process.env\n const clock = options.now ?? Date.now\n const store = options.store ?? firestoreStore\n const raise = options.raise ?? defaultRaise\n const dryRun = Boolean(options.dryRun)\n const parsedThreshold = Number.parseInt(\n String(env['RENDER_MONITOR_FAILURE_THRESHOLD'] ?? ''),\n 10,\n )\n const threshold =\n Number.isFinite(parsedThreshold) && parsedThreshold >= 1\n ? parsedThreshold\n : RENDER_MONITOR_DEFAULT_THRESHOLD\n const nonce =\n options.nonce ??\n (() => `${clock().toString(36)}${Math.random().toString(36).slice(2, 8)}`)\n\n const probeOptions = {\n fetcher: options.fetcher ?? fetch,\n headers: options.headers ?? {},\n timeoutMs: options.timeoutMs ?? RENDER_MONITOR_TIMEOUT_MS,\n clock,\n }\n // Real pages need the render origin AND the bypass that gets past its\n // Deployment Protection; without both a `page` probe could only fail.\n const { renderOrigin, pages } = resolveRenderMonitorPages(env)\n const canRenderPages = Boolean(\n renderOrigin && probeOptions.headers['x-vercel-protection-bypass'],\n )\n const runAt = clock()\n const slot = Math.floor(runAt / 300_000)\n\n const targets = resolveRenderMonitorTargets(env)\n // One real page a run, across every watched site; with one, the layout\n // probes need no every-run site of their own.\n const turn = canRenderPages ? renderMonitorPageTurn(pages, slot) : null\n const due = targets\n .map((origin, index) => ({\n origin,\n layout: renderMonitorProbesLayout(index, targets.length, slot, !turn),\n page: turn && turn.site.origin === origin ? turn : undefined,\n }))\n // A site with nothing to draw this run keeps its state as it is.\n .filter((target) => target.layout || target.page)\n\n const sites = await Promise.all(\n due.map(\n async ({ origin, layout, page }): Promise<RenderMonitorSiteResult> => {\n const layoutProbes = layout\n ? RENDER_PROBES.map((spec) =>\n runProbe(`${origin}${spec.path(nonce())}`, spec, probeOptions),\n )\n : []\n const pageProbe = page\n ? [\n runProbe(\n pageProbeUrl(renderOrigin, page, renderSpellingNumber(runAt)),\n { kind: 'page', expectStatus: 200 },\n probeOptions,\n ),\n ]\n : []\n const probes = await Promise.all([...layoutProbes, ...pageProbe])\n const ok = probes.every((probe) => probe.ok)\n const failing = probes.filter((probe) => !probe.ok)\n const blind = !ok && failing.every((probe) => probe.challenged)\n const result: RenderMonitorSiteResult = { origin, ok, blind, probes }\n if (dryRun) return result\n const host = new URL(origin).host\n const detail = ok\n ? 'Fresh renders pass.'\n : failing.map(probeLine).join('; ')\n try {\n const now = clock()\n const { next, transition, failingSinceMs } = await store(\n renderMonitorCheckId(origin),\n (prior) => {\n const decided = nextRenderMonitorState(\n prior,\n { ok, detail, blind },\n {\n origin,\n label: `Page rendering on ${host}`,\n threshold,\n now,\n },\n )\n return {\n next: decided.next,\n result: {\n ...decided,\n // When the failures a recovery ends began.\n failingSinceMs: prior?.failingSinceMs ?? prior?.sinceMs ?? now,\n },\n }\n },\n )\n result.status = next.status\n result.consecutiveFailures = next.consecutiveFailures\n result.transition = transition\n if (transition === 'failing') {\n await raise('system.siteRenderFailing', {\n dedupeKey: host,\n context: {\n site: host,\n failures: next.consecutiveFailures,\n since: describeDuration(now - next.sinceMs),\n detail,\n },\n })\n } else if (transition === 'blind') {\n await raise('system.renderMonitorBlind', {\n dedupeKey: host,\n context: {\n site: host,\n runs: next.consecutiveBlindRuns ?? threshold,\n detail,\n },\n })\n } else if (transition === 'recovered') {\n await raise('system.siteRenderRecovered', {\n dedupeKey: host,\n context: {\n site: host,\n duration: describeDuration(now - failingSinceMs),\n },\n })\n }\n } catch (error) {\n result.error = error instanceof Error ? error.message : String(error)\n console.error(`[render-monitor] ${host} could not be recorded`, error)\n }\n return result\n },\n ),\n )\n return { dryRun, threshold, sites }\n}\n\n/**\n * One watched site as `/api/health/pages` reports it (AGL-3580).\n *\n * The shape of every other health check — `ok`, `ms`, a stable `code` — plus\n * when the monitor last saw the site, so a reader can tell a fresh verdict\n * from an old one without a second request.\n */\nexport interface RenderPagesCheck {\n ok: boolean\n ms: number\n code?: string\n /** When a run last rendered or failed this site's pages, ISO. */\n lastObservedAt: string | null\n /** When the site's current status began, ISO. */\n since: string | null\n}\n\n/**\n * A verdict older than this says the monitor stopped, not that the site did.\n * Four missed five-minute runs.\n */\nexport const RENDER_PAGES_STALE_MS = 20 * 60_000\n\n/** How many sites one `?site=` may ask about. */\nexport const RENDER_PAGES_MAX_SITES = 10\n\n/**\n * Which watched hosts a `?site=` asks about. Pure.\n *\n * Absent or empty asks about every watched site. A host that is not watched\n * is kept, so the caller can answer it red: a public monitor pointed at a\n * site nobody renders is a monitor that can never go red, which is the\n * mistake this door exists to undo.\n */\nexport function requestedRenderPagesHosts(\n query: string | null | undefined,\n watchedOrigins: readonly string[],\n): string[] {\n const asked = String(query ?? '')\n .split(/[\\s,]+/)\n .map((entry) => entry.trim().toLowerCase().replace(/^https?:\\/\\//, '').replace(/\\/.*$/, ''))\n .filter((entry) => /^[a-z0-9-]+(\\.[a-z0-9-]+)+$/.test(entry))\n const hosts = asked.length ? asked : watchedOrigins.map((origin) => new URL(origin).host)\n return [...new Set(hosts)].slice(0, RENDER_PAGES_MAX_SITES)\n}\n\n/**\n * The public verdict on real pages, per site, from the render monitor's\n * stored state (AGL-3580). Pure.\n *\n * This is what the status page's `Published sites` and `Marketing site`\n * monitors read. Before it they read `/api/health/render/*`, which builds a\n * node tree inside a route handler and never draws a page, and both stayed at\n * 100% through two outages on 2026-10-05 in which every fresh page hung.\n *\n * Red is reserved for the one thing a visitor would notice:\n *\n * - `not-rendering` — the monitor saw the site fail to render pages it could\n * not have served from a cache, `threshold` runs in a row.\n * - `not-watched` — the monitor renders nothing for this host, so this row\n * could never go red; fix the monitor's config or the URL.\n * - `state-unavailable` — the verdicts could not be read at all.\n *\n * Green with a code is a verdict this door cannot improve on, and is never\n * reported as an outage, because it is not one:\n *\n * - `awaiting-first-run` — a site added since the monitor last ran.\n * - `monitor-blind` — bot protection answered the monitor; the site's last\n * real verdict stands, and the operator alert says what to fix.\n * - `observation-stale` — no run in {@link RENDER_PAGES_STALE_MS}; the\n * monitor's own `render-monitor` row on `/api/health/crons` is what goes\n * red for that, so a stopped scheduler is never told as a site outage.\n */\nexport function renderPagesHealth(\n hosts: readonly string[],\n watchedOrigins: readonly string[],\n states: ReadonlyMap<string, Partial<RenderMonitorStateDoc>> | null,\n ms: number,\n now: number = Date.now(),\n): Record<string, RenderPagesCheck> {\n const watched = new Set(watchedOrigins.map((origin) => new URL(origin).host))\n const iso = (value: number | null | undefined) =>\n typeof value === 'number' && Number.isFinite(value) ? new Date(value).toISOString() : null\n const checks: Record<string, RenderPagesCheck> = {}\n if (!hosts.length) {\n checks['sites'] = { ok: false, ms, code: 'no-sites-watched', lastObservedAt: null, since: null }\n return checks\n }\n for (const host of hosts) {\n const blank = { ms, lastObservedAt: null, since: null }\n if (!watched.has(host)) {\n checks[host] = { ...blank, ok: false, code: 'not-watched' }\n continue\n }\n if (states === null) {\n checks[host] = { ...blank, ok: false, code: 'state-unavailable' }\n continue\n }\n const state = states.get(renderMonitorHostCheckId(host))\n if (!state) {\n checks[host] = { ...blank, ok: true, code: 'awaiting-first-run' }\n continue\n }\n const observed = state.lastObservedAtMs ?? state.lastOkAtMs ?? null\n const row = { ms, lastObservedAt: iso(observed), since: iso(state.sinceMs) }\n if (state.status === 'degraded') {\n checks[host] = { ...row, ok: false, code: 'not-rendering' }\n } else if ((state.consecutiveBlindRuns ?? 0) > 0) {\n checks[host] = { ...row, ok: true, code: 'monitor-blind' }\n } else if (now - (state.updatedAtMs ?? 0) > RENDER_PAGES_STALE_MS) {\n checks[host] = { ...row, ok: true, code: 'observation-stale' }\n } else {\n checks[host] = { ...row, ok: true }\n }\n }\n return checks\n}\n\n/**\n * Read the stored verdicts for `hosts`, one batched read. Null when the read\n * fails, which {@link renderPagesHealth} reports red rather than calm.\n */\nexport async function readRenderMonitorStates(\n hosts: readonly string[],\n): Promise<Map<string, Partial<RenderMonitorStateDoc>> | null> {\n try {\n const { default: firebaseAdmin } = await import('./firebase-admin')\n const db = firebaseAdmin.app().firestore()\n const refs = hosts.map((host) =>\n db.collection(RENDER_MONITOR_COLLECTION).doc(renderMonitorHostCheckId(host)),\n )\n const snapshots = refs.length ? await db.getAll(...refs) : []\n const states = new Map<string, Partial<RenderMonitorStateDoc>>()\n for (const snapshot of snapshots) {\n if (snapshot.exists) states.set(snapshot.id, snapshot.data() as Partial<RenderMonitorStateDoc>)\n }\n return states\n } catch (error) {\n console.error('[render-monitor] stored verdicts could not be read', error)\n return null\n }\n}\n"],"names":["TENANT_APEX","RENDER_MONITOR_COLLECTION","RENDER_MONITOR_CHECK_PREFIX","RENDER_MONITOR_JOB_ID","RENDER_MONITOR_TIMEOUT_MS","RENDER_MONITOR_DEFAULT_THRESHOLD","RENDER_PROBE_ISR_PREFIX","RENDER_PROBES","kind","path","expectStatus","nonce","CHECKPOINT_MARKER","CACHED_STATES","Set","gradeRenderProbe","response","body","test","ok","challenged","code","detail","status","location","contentType","includes","cache","String","cacheState","trim","toUpperCase","has","PLATFORM_RENDER_PAGES","join","PLATFORM_CONSOLE_VERCEL_PROJECT_ID","PLATFORM_RENDER_ORIGIN","CNAME_HOST_PREFIX","MAX_SPELLING_BITS","spellingLetters","host","toLowerCase","map","char","index","filter","slice","freshHostSpelling","n","apex","subdomain","endsWith","prefix","chars","letters","capacity","length","value","Math","max","floor","Number","bits","forEach","bit","dots","repeat","renderSpellingNumber","nowMs","Date","UTC","parseRenderMonitorPages","text","byHost","Map","raw","split","entry","replace","slash","indexOf","paths","get","push","set","origin","resolveRenderMonitorPages","env","off","renderOrigin","pages","platform","originOf","trimmed","resolveRenderMonitorTargets","label","demo","listed","Boolean","paged","page","renderMonitorProbesLayout","count","slot","firstEveryRun","abs","renderMonitorPageTurn","turns","flatMap","site","renderMonitorCheckId","renderMonitorHostCheckId","URL","nextRenderMonitorState","prior","observation","context","threshold","now","checkId","wasDegraded","blind","blindRuns","consecutiveBlindRuns","next","sinceMs","updatedAtMs","consecutiveFailures","failingSinceMs","lastOkAtMs","blindSinceMs","lastObservedAtMs","transition","sighted","failures","degraded","RENDER_MONITOR_STATE_REFRESH_MS","renderMonitorStateNeedsWrite","decided","some","key","firestoreStore","work","default","firebaseAdmin","db","app","firestore","ref","collection","doc","runTransaction","transaction","snapshot","exists","data","result","defaultRaise","type","options","raiseOperatorAlert","describeDuration","ms","minutes","round","hours","rest","pageProbeUrl","turn","spelling","url","searchParams","toString","probeLine","row","pathname","runProbe","spec","startedAt","clock","fetcher","redirect","headers","accept","signal","AbortSignal","timeout","timeoutMs","verdict","httpStatus","error","name","timedOut","cause","runRenderMonitor","process","store","raise","dryRun","parsedThreshold","parseInt","isFinite","random","probeOptions","fetch","canRenderPages","runAt","targets","due","layout","undefined","target","sites","Promise","all","layoutProbes","pageProbe","probes","every","probe","failing","dedupeKey","since","runs","duration","Error","message","console","RENDER_PAGES_STALE_MS","RENDER_PAGES_MAX_SITES","requestedRenderPagesHosts","query","watchedOrigins","asked","hosts","renderPagesHealth","states","watched","iso","toISOString","checks","lastObservedAt","state","blank","observed","readRenderMonitorStates","refs","snapshots","getAll","id"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,WAAW,QAAQ,qCAAoC;AAGhE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuFC,GAED,6DAA6D,GAC7D,MAAMC,4BAA4B;AAElC,uDAAuD,GACvD,OAAO,MAAMC,8BAA8B,mBAAkB;AAE7D,iEAAiE,GACjE,OAAO,MAAMC,wBAAwB,iBAAgB;AAErD;;;;CAIC,GACD,OAAO,MAAMC,4BAA4B,MAAM;AAE/C,qDAAqD,GACrD,OAAO,MAAMC,mCAAmC,EAAC;AAEjD;;;;CAIC,GACD,OAAO,MAAMC,0BAA0B,uBAAsB;AAY7D,OAAO,MAAMC,gBAA4C;IACvD;QAAEC,MAAM;QAAWC,MAAM,IAAM;QAAWC,cAAc;IAAI;IAC5D;QACEF,MAAM;QACNC,MAAM,CAACE,QAAU,GAAGL,0BAA0BK,OAAO;QACrDD,cAAc;IAChB;CACD,CAAA;AAqBD,+EAA+E,GAC/E,MAAME,oBAAoB;AAE1B;;;CAGC,GACD,MAAMC,gBAAgB,IAAIC,IAAI;IAAC;IAAO;IAAS;CAAY;AAE3D;;;;;;CAMC,GACD,OAAO,SAASC,iBACdC,QAA6B,EAC7BN,YAAoB;QAEPM,gBAyBWA,uBAwBHA;IAjDrB,MAAMC,QAAOD,iBAAAA,SAASC,IAAI,YAAb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AYD,KAAK9L,MAAM,GAAG,MAAMyF,GAAGuG,MAAM,IAAIF,QAAQ,EAAE;QAC7D,MAAMV,SAAS,IAAIlK;QACnB,KAAK,MAAM+E,YAAY8F,UAAW;YAChC,IAAI9F,SAASC,MAAM,EAAEkF,OAAOxJ,GAAG,CAACqE,SAASgG,EAAE,EAAEhG,SAASE,IAAI;QAC5D;QACA,OAAOiF;IACT,EAAE,OAAO9C,OAAO;QACdqC,QAAQrC,KAAK,CAAC,sDAAsDA;QACpE,OAAO;IACT;AACF"}
@@ -14,6 +14,7 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */
17
+ import { type RosterMember } from '@aglyn/aglyn/app-utils/member-email-aliases';
17
18
  import { type ReceivedEmail } from '@aglyn/shared-util-email';
18
19
  import { type SiteCareDeps } from './site-care-requests';
19
20
  /**
@@ -28,6 +29,15 @@ import { type SiteCareDeps } from './site-care-requests';
28
29
  * any Site Care email goes to `support+<requestId>@…` and joins that
29
30
  * request's thread, when the sender is a member of its workspace.
30
31
  *
32
+ * The sender is matched as a mailbox, not as a string (AGL-4031): case does
33
+ * not matter, a `+tag` is dropped, Gmail's dots and its two domains are one
34
+ * mailbox, and an address a member confirmed (on their account, or in the
35
+ * workspace) counts as theirs. This is looser than the account and alias
36
+ * stores, which keep `a+b@x.com` and `a@x.com` apart on purpose, and it can
37
+ * afford to be: it only places mail from somebody already on a workspace's
38
+ * roster, grants nothing, and never crosses from one domain to another except
39
+ * between Gmail's two.
40
+ *
31
41
  * Everything else is acknowledged and left alone: nothing is filed and
32
42
  * nothing is sent back, and a message to the support address stays in the
33
43
  * support inbox as ordinary support mail. That includes the platform's own
@@ -76,13 +86,74 @@ export type SiteCareAccountLookup = (email: string) => Promise<{
76
86
  /**
77
87
  * Every pool, not only the project's: an owner who signs in through SSO is a
78
88
  * GCIP tenant user the project pool never returns (AGL-1122), and their mail
79
- * would be read as a stranger's.
89
+ * would be read as a stranger's. Then the account addresses people add to
90
+ * their account and CONFIRM (AGL-2486): a confirmed address is one of that
91
+ * account's sign-in identifiers, held by no other account, so mail from it is
92
+ * that person's (AGL-4031). An address only typed, never confirmed, is not in
93
+ * that index and is never read as anyone's.
80
94
  */
81
95
  export declare const findSiteCareAccount: SiteCareAccountLookup;
82
96
  /**
83
- * The Site Care workspace a sender belongs to: the account their address
84
- * signs in with (in any pool), then the workspaces it is a member of, the
85
- * first with Site Care in force (by id, so the choice is stable).
97
+ * The addresses a sender may be signed in under, in the order they are tried
98
+ * (AGL-4031). Each tier is tried only when every earlier one named nobody, so
99
+ * an address that is itself somebody's sign-in is never read as somebody
100
+ * else's that merely looks like it:
101
+ *
102
+ * 1. the address as written (compared lower-cased, as every member address is);
103
+ * 2. without its `+tag`: `avery+site@example.com` is `avery@example.com`'s
104
+ * mailbox wherever plus-addressing is offered, and the tag is how people
105
+ * sort mail, not a second identity;
106
+ * 3. for Gmail only, the same mailbox's other spellings: Gmail ignores the
107
+ * dots in a local part and delivers `gmail.com` and `googlemail.com` to one
108
+ * inbox. No other domain's dots are folded, and no tier ever leaves the
109
+ * sender's own domain except between those two.
110
+ */
111
+ export declare function siteCareSenderCandidates(sender: unknown): string[][];
112
+ /**
113
+ * Whether mail from `sender` came from the mailbox `memberAddress` names, by
114
+ * the same rules as {@link siteCareSenderCandidates}: the address itself,
115
+ * the sender's `+tag` dropped onto the member's untagged address, and, for
116
+ * Gmail alone, dots and the domain's two spellings ignored. A member's own
117
+ * tagged address is matched only as written: `avery+site@` signing in does
118
+ * not make every `avery+…@` theirs.
119
+ */
120
+ export declare function siteCareAddressMatches(sender: unknown, memberAddress: unknown): boolean;
121
+ /**
122
+ * The one member of a roster a sender is, or null: a member who signs in
123
+ * with the sender's mailbox first, then the one member who confirmed it as
124
+ * an alias in that workspace (AGL-2975). Two members who both match are a
125
+ * guess, and a guess files nothing — the message stays ordinary support mail.
126
+ */
127
+ export declare function siteCareRosterMember(roster: readonly RosterMember[], sender: unknown, options?: {
128
+ exactOnly?: boolean;
129
+ }): RosterMember | null;
130
+ /**
131
+ * How many Site Care workspaces the roster pass reads at most. It runs only
132
+ * for mail the account lookups could not place, and each workspace costs two
133
+ * reads, so the bound is what keeps a busy support inbox from costing more
134
+ * than a lookup should.
135
+ */
136
+ export declare const SITE_CARE_ROSTER_SCAN_MAX = 200;
137
+ /**
138
+ * EVERY Site Care workspace a sender belongs to, by workspace id (AGL-4031).
139
+ *
140
+ * First the account the sender's address signs in with, in any pool or as a
141
+ * confirmed account address, trying the address's tiers in order
142
+ * ({@link siteCareSenderCandidates}); then the workspaces that account is a
143
+ * member of with Site Care in force. When that places the sender nowhere,
144
+ * the rosters of the workspaces that bought Site Care are read for the
145
+ * sender's mailbox ({@link siteCareRosterMatches}).
146
+ *
147
+ * All of them, not the first: which one a message is filed on, when there
148
+ * are several, is the caller's choice.
149
+ */
150
+ export declare function findSiteCareWorkspacesForSender(firestore: FirebaseFirestore.Firestore, findAccount: SiteCareAccountLookup, sender: string): Promise<SiteCareSenderMatch[]>;
151
+ /**
152
+ * The Site Care workspace a sender's new request is filed on: the first of
153
+ * {@link findSiteCareWorkspacesForSender}'s, by workspace id, so the choice
154
+ * is stable. A sender in several Site Care workspaces files on the lowest
155
+ * id, with every candidate recorded for staff, who move the request when it
156
+ * belongs to another (AGL-4031, `moveSiteCareRequest`).
86
157
  */
87
158
  export declare function findSiteCareWorkspaceForSender(firestore: FirebaseFirestore.Firestore, findAccount: SiteCareAccountLookup, sender: string): Promise<SiteCareSenderMatch | null>;
88
159
  /** The words of a message, above any quoted history. */