@aglyn/plugins-redirects 1.0.0-beta.143

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/redirects/src/lib/components/redirects-console-page.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { checkQuota, pluginDocsHelp } from '@aglyn/aglyn'\nimport { type ConsolePluginPageProps } from '@aglyn/aglyn'\nimport { isExternalRedirectDestination, isSelfRedirect, matchRedirect, normalizeRedirectDestination, normalizeRedirectSource, REDIRECT_DEFAULT_PRIORITY, validateRedirectRule, REDIRECT_STATUS_CODES } from '../model'\nimport { CardDisplay, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport QuotaReadoutComponent from '@aglyn/shared-ui-jsx/components/quota-readout.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Timestamp } from '@aglyn/shared-util-timestamp'\nimport {\n Alert,\n Button,\n Chip,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n MenuItem,\n Stack,\n Switch,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n deleteField,\n doc,\n getCountFromServer,\n getDoc,\n setDoc,\n updateDoc,\n} from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { TABLE_PAGE_SIZE_DEFAULT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport {\n ceilingedWindow,\n collectionCeiling,\n useFirestore,\n useFirestoreCollection,\n useFirestoreDoc,\n useHostResourceApi,\n useUser,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\n\n/**\n * How many redirect documents this page reads.\n *\n * A CEILING, not a page size. Everything the page decides is computed over\n * the WHOLE rule set: the duplicate-source check, the chain-loop walk that\n * follows internal destinations through the rules, and the inline tester that\n * runs the enforcement matcher. A server page would give each of them a\n * tenth of the rules to reason about, and the duplicate check would then\n * create exactly the collision it exists to prevent.\n */\nconst REDIRECT_CEILING = 200\n\ninterface RedirectDraft {\n id: string | null\n source: string\n destination: string\n statusCode: number\n /** Match mode (AGL-375): exact | prefix | regex. */\n kind: string\n /** Lower fires first. */\n priority: number\n /**\n * The rule's on/off state, carried through the editor rather than reset by\n * it (AGL-1372). The save used to hardcode `true`, so changing a **disabled**\n * rule's target turned it back on and rerouted the site without the author\n * asking. A new rule seeds this `true`; an edit seeds it from the stored\n * rule, which is also where the row's switch reads from.\n */\n enabled: boolean\n}\n\n/**\n * Redirect manager (AGL-156): CRUD over `hosts/{hostId}/redirects` with\n * the shared AGL-154 validation (normalized sources, https-or-internal\n * destinations, self-redirect refusal, duplicate-source check). Paid\n * (`redirects` flag + `redirectsPerHost` quota); rules take effect on the\n * site within ~30 seconds (AGL-155 ISR window).\n *\n * The plan gate is the SHELL's, and it runs before this component exists\n * (AGL-2484): the console resolves `redirects` from the org billing doc and\n * renders its own refusal notice in place of the surface, so this card is\n * only ever mounted for an entitled org and states no plan terms of its own.\n * Redirects registers no `upgradeNotice` override because it is a genuine\n * upgrade — free denies it, Starter and above grant it — which makes the\n * shell's plan-derived sentence the accurate one already.\n *\n * `entitled` is still read below, where it is not redundant: it holds back\n * the thirty analytics day-doc reads behind the hit counts, and refuses the\n * add path ahead of the server that enforces it.\n */\nexport function RedirectsConsolePage(props: ConsolePluginPageProps) {\n const { hostId, entitled, org } = props\n const firestore = useFirestore()\n const createHostResource = useHostResourceApi()\n const { data: currentUser } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n\n const {\n data: redirectDocs,\n status: redirectsStatus,\n /**\n * The rows this editor is seeded from are unconfirmed by the server\n * (AGL-1358). Editing copies every field the form owns out of the stored\n * rule and writes all of them back, so `merge: true` protects only the\n * fields written elsewhere (`lastHitAt`, `deletedAt`). This is the site\n * where a rollback is hardest to undo: a reverted `destination` on a\n * **301** is cached by every browser that has already followed it, so the\n * stale target outlives the fix in the console. `kind` reverting from\n * exact to prefix silently widens a rule over a whole subtree, and\n * `priority` reorders which rule fires when several match.\n */\n fromCache: redirectsFromCache,\n } = useFirestoreCollection<any>(\n /*\n * ORDERED AND CEILINGED, with a probe (AGL-2501).\n *\n * `limit(200)` alone is answered in DOCUMENT-ID order and the ids are\n * generated, so the window was a pseudo-random two hundred of the site's\n * rules — sorted by `source` in the browser afterwards, which is what\n * made it invisible: the rules on screen run alphabetically and are\n * simply the wrong rules, and the ones missing leave no gap to notice.\n *\n * `orderBy('source')` is the tempting fix and the dangerous one. It\n * matches only documents that HAVE the field, and nothing validates\n * `source` for presence — `/api/hosts/resources` stores an allow-list of\n * fields and checks none of them — so a rule saved without one would\n * vanish from this page while still redirecting live traffic. The\n * document NAME cannot be absent, so the walk is total: every rule is\n * reachable, and the alphabetical order stays where it belongs, in the\n * sort below over a window the page holds whole.\n */\n () =>\n collectionCeiling(\n collection(firestore, 'hosts', hostId, 'redirects'),\n REDIRECT_CEILING,\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n const { rows: readRedirects, truncated: redirectsTruncated } =\n ceilingedWindow<any>(redirectDocs, REDIRECT_CEILING)\n const redirects = [...readRedirects]\n .filter((redirect: any) => !redirect.deletedAt)\n .sort((a: any, b: any) =>\n String(a.source ?? '').localeCompare(String(b.source ?? '')),\n )\n\n /*\n * The page is a SLICE of the ceiling, which is what the three whole-set\n * consumers above require. The count is the rules this page HOLDS, after\n * soft-deleted ones are dropped — not the quota, which is a server count of\n * every document including the soft-deleted, and is read separately below.\n */\n const [page, setPage] = useState(0)\n const [pageSize, setPageSize] = useState(TABLE_PAGE_SIZE_DEFAULT)\n const visibleRedirects = useMemo(\n () => redirects.slice(page * pageSize, page * pageSize + pageSize),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [redirectDocs, page, pageSize],\n )\n\n /**\n * What the ENFORCING route counts, which is not what this page was counting.\n *\n * `hosts/{id}/redirects` is read here as an unordered `limit(200)` window\n * and then filtered to drop soft-deleted rows, and that filtered length was\n * feeding both `checkQuota('redirectsPerHost')` and the readout beside it.\n * The route in `app/api/hosts/resources` counts the collection plainly —\n * `collectionRef.count()`, every document, soft-deleted ones included — so\n * the two disagreed on both counts at once: a rule deleted in this console\n * still occupies a slot on the server, and a site past 200 rules has rows\n * the window never saw.\n *\n * The visible effect is the worst kind: the page shows room, the author\n * fills in the form, and the save is refused by a server counting something\n * else. Same shape as AGL-1716.\n *\n * An aggregation query, so it costs one read unit per thousand documents\n * rather than reading them. Re-run when the document set changes, which\n * covers an add; a soft delete leaves the document in place and so does not\n * move this number — correctly, because it does not move the server's\n * either.\n *\n * Only the COUNT is corrected here. Whether a soft-deleted rule should go on\n * occupying a slot is the quota RULE, and that lives with the enforcing\n * route.\n */\n const [enforcedCount, setEnforcedCount] = useState<number | null>(null)\n const redirectDocCount = redirectDocs?.length ?? 0\n\n /**\n * `null` when the count cannot be taken, never a number.\n *\n * `try`, not `.catch()`: `getCountFromServer` validates its reference and\n * THROWS synchronously on a bad one, so a rejection handler alone leaves the\n * error to escape the effect and take the page down with it. Unreadable is\n * also not zero — answering zero would tell an author at their cap that the\n * whole allowance is free.\n */\n const countRedirects = useCallback(async (): Promise<number | null> => {\n try {\n const snapshot = await getCountFromServer(\n collection(firestore, 'hosts', hostId, 'redirects'),\n )\n return snapshot.data().count\n } catch {\n return null\n }\n }, [firestore, hostId])\n\n useEffect(() => {\n let active = true\n void countRedirects().then((count) => {\n if (active && count != null) setEnforcedCount(count)\n })\n return () => {\n active = false\n }\n }, [countRedirects, redirectDocCount])\n\n const [draft, setDraft] = useState<RedirectDraft | null>(null)\n const [testPath, setTestPath] = useState('')\n\n // Host routing map for the screen-collision warning (AGL-156 spec).\n const { data: host } = useFirestoreDoc<any>(\n () => doc(firestore, 'hosts', hostId),\n [firestore, hostId],\n { idField: '$id' },\n )\n\n // Sampled hit counts (AGL-157): summed from the last 30 analytics day\n // docs' `redirects` maps written by enforcement. Counts are sampled —\n // one per ISR revalidation window with traffic, not per request.\n const [hits, setHits] = useState<Record<string, number> | null>(null)\n useEffect(() => {\n if (!entitled) return\n let active = true\n const ids = Array.from({ length: 30 }, (_, index) => {\n const date = new Date()\n date.setDate(date.getDate() - index)\n return date.toISOString().slice(0, 10)\n })\n void Promise.all(\n ids.map((id) =>\n getDoc(doc(firestore, 'hosts', hostId, 'analytics', id))\n .then((snapshot) => (snapshot.get('redirects') ?? {}) as Record<string, number>)\n .catch(() => ({}) as Record<string, number>),\n ),\n ).then((days) => {\n if (!active) return\n const totals: Record<string, number> = {}\n for (const dayMap of days) {\n for (const [redirectId, count] of Object.entries(dayMap)) {\n totals[redirectId] = (totals[redirectId] ?? 0) + Number(count)\n }\n }\n setHits(totals)\n })\n return () => {\n active = false\n }\n }, [entitled, firestore, hostId])\n const idKey = (value: string) => value.replace(/[.$#[\\]/]/g, '_')\n const totalHits = Object.values(hits ?? {}).reduce(\n (sum, count) => sum + count,\n 0,\n )\n\n const handleAdd = useCallback(() => {\n if (!entitled) {\n return void enqueueSnackbar(\n 'URL redirects require a Starter plan — see Billing to upgrade',\n { variant: 'warning', persist: false },\n )\n }\n /*\n * The SERVER's count, not the rows on screen — the whole point of this\n * fix. Read from the polled value rather than re-counted on the click:\n * this gate is a courtesy that spares the author a form they are about to\n * be refused, the route is the actual enforcer, and making the button\n * await an aggregation would delay the dialog on every press to sharpen a\n * number the server re-checks anyway.\n *\n * `null` means the count could not be read, and that lets the add through:\n * refusing on a number we do not have would block an author who may well\n * be inside their cap.\n */\n const quota = checkQuota(org, 'redirectsPerHost', enforcedCount ?? 0)\n if (!quota.allowed) {\n return void enqueueSnackbar(\n `Redirect limit reached (${quota.limit}) — upgrade in Billing`,\n { variant: 'warning', persist: false },\n )\n }\n setDraft({\n id: null,\n source: '',\n destination: '',\n statusCode: 302,\n kind: 'exact',\n priority: REDIRECT_DEFAULT_PRIORITY,\n // A NEW rule is on: the author is adding it to make it fire, and\n // enforcement queries `where('enabled', '==', true)`, so a rule created\n // without the field would never resolve (AGL-1372).\n enabled: true,\n })\n }, [entitled, org, enforcedCount, enqueueSnackbar])\n\n /**\n * Tell the tenant a rule changed (best effort, never awaited into the save\n * outcome). Rule writes are client Firestore writes with no publish step,\n * and the tenant's rules list sits behind the hour-long\n * `tenant-data:{hostId}` backstop — without this call a new rule waits out\n * that TTL while the snackbar above promises ~30 seconds. The route busts\n * the host tag and drops the source path's cached HTML; a regex pattern has\n * no single literal path, so it announces `/` for the tag bust alone and\n * the matching pages catch up on their own ISR window.\n */\n const announceRuleChange = useCallback(\n (source: string | undefined) => {\n const redirectPath =\n typeof source === 'string' && source.startsWith('/') ? source : '/'\n void authorizedFetch(currentUser, '/api/screens/revalidate', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId, redirectPath }),\n }).catch(() => undefined)\n },\n [currentUser, hostId],\n )\n\n const handleSave = useCallback(async () => {\n if (!draft) return\n const kind = draft.kind || 'exact'\n // Shared v2 validation (AGL-375): regex patterns must compile; path\n // kinds keep the v1 normalization.\n const problem = validateRedirectRule({\n kind,\n source: draft.source,\n destination: draft.destination,\n })\n if (problem) {\n return void enqueueSnackbar(problem, {\n variant: 'warning',\n persist: false,\n })\n }\n const source =\n kind === 'regex'\n ? draft.source.trim()\n : (normalizeRedirectSource(draft.source) as string)\n const destination = normalizeRedirectDestination(\n draft.destination,\n ) as string\n if (kind !== 'regex' && isSelfRedirect({ source, destination })) {\n return void enqueueSnackbar('That would redirect the path to itself', {\n variant: 'warning',\n persist: false,\n })\n }\n const duplicate = redirects.find(\n (redirect: any) =>\n redirect.source === source &&\n (redirect.kind ?? 'exact') === kind &&\n redirect.$id !== draft.id,\n )\n if (duplicate) {\n return void enqueueSnackbar(`A rule for ${source} already exists`, {\n variant: 'warning',\n persist: false,\n })\n }\n // Chain-loop detection (AGL-156): follow internal destinations through\n // the rule set; a walk that returns to this source can never execute.\n if (destination.startsWith('/')) {\n const bySource = new Map<string, string>(\n redirects\n .filter((redirect: any) => redirect.$id !== draft.id)\n .map((redirect: any) => [redirect.source, redirect.destination]),\n )\n let cursor: string | undefined = destination.toLowerCase()\n for (let hop = 0; hop < 10 && cursor; hop += 1) {\n if (cursor === source) {\n return void enqueueSnackbar(\n 'That destination chains back to this rule — a redirect loop',\n { variant: 'warning', persist: false },\n )\n }\n const next: string | undefined = bySource.get(cursor)\n cursor = next && next.startsWith('/') ? next.toLowerCase() : undefined\n }\n }\n // Screen-route collision: shadowing a live page may be intentional\n // (moved pages) — warn, don't block (decision per the issue).\n const routedPaths = Object.values(\n (host?.screens ?? {}) as Record<string, string>,\n ).map((path) => (path === '/' ? '/' : `/${path}`))\n if (routedPaths.includes(source)) {\n enqueueSnackbar(\n `${source} is a published page — the redirect takes precedence`,\n { variant: 'info', persist: false },\n )\n }\n const fields = {\n source,\n destination,\n statusCode: (REDIRECT_STATUS_CODES as readonly number[]).includes(\n draft.statusCode,\n )\n ? draft.statusCode\n : 302,\n kind,\n priority: Number.isFinite(Number(draft.priority))\n ? Number(draft.priority)\n : REDIRECT_DEFAULT_PRIORITY,\n /**\n * Whatever the rule already was (AGL-1372). This was `true`, so editing\n * a **disabled** rule's target silently re-enabled it — a deliberate\n * \"off\" (a retired campaign, a rule that broke something) undone by a\n * routine save, changing site routing without the author asking.\n *\n * `!== false` rather than the raw value, because the switch below reads\n * the stored field the same way: absent means on. Enforcement's query is\n * `where('enabled', '==', true)`, so a rule missing the field is not\n * served, and normalising it here makes the console's claim true.\n *\n * The create default lives in `handleAdd` — a new rule seeds the draft\n * `true`, so both defaults hold without either one reading the other.\n */\n enabled: draft.enabled !== false,\n }\n /**\n * The publisher's stamp on an external destination (AGL-1881).\n *\n * `matchRedirect` will not send traffic off the platform without it, and\n * `cloud/firebase-firestore.rules` admits no write to this collection from\n * anyone but `canPublishHostContent` — so reaching this line at all is the\n * approval, and saving is how a rule written before that fix starts firing\n * again.\n *\n * Written on EDIT only. A create rides /api/hosts/resources, which stamps\n * the same field from the id token's verified uid; sending it from here\n * would be the client supplying its own provenance, and that route drops\n * it for exactly that reason.\n *\n * Cleared with `deleteField()` when the destination is internal, rather\n * than left standing. `merge: true` never removes a key, so an edit from\n * `https://elsewhere.example` back to `/pricing` would otherwise leave a\n * stamp behind that a LATER edit back to an external target would inherit\n * — approval carried across a destination nobody approved.\n */\n const approval = isExternalRedirectDestination(destination)\n ? { externalDestinationApprovedBy: currentUser?.uid ?? null }\n : { externalDestinationApprovedBy: deleteField() }\n try {\n if (draft.id) {\n /**\n * Edit stays client-direct (no quota consumed) — and is refused when\n * its seed was never confirmed by the server (AGL-1358); the eight\n * validation refusals above have all already returned by here.\n *\n * `merge: true` is load-bearing, contrary to what this said before\n * (AGL-1372): `fields` is every key the FORM owns, not every key the\n * document holds. `lastHitAt` is written by enforcement\n * (`resolve-redirect`), and `deletedAt` by the delete below — a\n * replacing write would erase both.\n *\n * The guard WRAPS the write. An early return is a shape you can keep\n * while losing the protection; here the write is only reachable\n * through the verdict.\n */\n const verdict = await writeGuardedBySeed(\n {\n subject: 'redirect',\n unreadable: redirectsStatus === 'error',\n fromCache: redirectsFromCache,\n },\n async () => {\n await setDoc(\n doc(firestore, 'hosts', hostId, 'redirects', draft.id),\n { ...fields, ...approval, updatedAt: Timestamp.now() },\n { merge: true },\n )\n },\n )\n // Before `setDraft(null)`, so a refusal keeps the dialog open with\n // what was typed, in the same warning vocabulary as the validation\n // refusals above it.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n } else {\n // New redirect rides the quota-enforcing resources API (AGL-473) —\n // it also re-checks the `redirects` entitlement server-side.\n await createHostResource({ hostId, resource: 'redirect', data: fields })\n }\n // The changed rule, and — when an edit moved the source — the path\n // that just STOPPED redirecting, so its page refreshes too.\n announceRuleChange(source)\n if (draft.id) {\n const previous = (redirects ?? []).find(\n (rule: any) => rule.$id === draft.id,\n )?.source\n if (previous && previous !== source) announceRuleChange(previous)\n }\n setDraft(null)\n enqueueSnackbar('Redirect saved — live within ~30 seconds', {\n variant: 'success',\n persist: false,\n })\n } catch (error: any) {\n console.error(error)\n enqueueSnackbar(error?.message ?? 'An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n }, [\n draft,\n redirects,\n host,\n firestore,\n hostId,\n createHostResource,\n currentUser,\n enqueueSnackbar,\n redirectsStatus,\n redirectsFromCache,\n announceRuleChange,\n ])\n\n /**\n * A refusal has to be visible (AGL-1881).\n *\n * These two writes were bare `await`s. The rules now gate this collection on\n * a publishing role, so an `author` reaching either gets a\n * permission-denied — and an unhandled rejection renders as a control that\n * flips back with no error, which is the worst way to say no. `handleSave`\n * has always ended in a snackbar; these now match it.\n *\n * The card is not role-gated on purpose: it is entitlement-gated, and the\n * rules leave READ to the catch-all so an author can still see the rules\n * that affect the pages they write.\n */\n const reportWriteFailure = useCallback(\n (error: any) => {\n enqueueSnackbar(\n error?.code === 'permission-denied'\n ? 'Changing a redirect needs a publishing role — ask an editor or admin'\n : (error?.message ?? 'An error has occurred'),\n { variant: 'warning', persist: false },\n )\n },\n [enqueueSnackbar],\n )\n\n const handleToggle = useCallback(\n (redirect: any) => async (event: { target: { checked: boolean } }) => {\n try {\n await updateDoc(\n doc(firestore, 'hosts', hostId, 'redirects', redirect.$id),\n { enabled: event.target.checked, updatedAt: Timestamp.now() },\n )\n announceRuleChange(redirect.source)\n } catch (error: any) {\n reportWriteFailure(error)\n }\n },\n [firestore, hostId, reportWriteFailure, announceRuleChange],\n )\n\n const handleDelete = useCallback(\n (redirect: any) => async () => {\n const confirmed = await confirm({\n title: 'Delete this redirect?',\n description: `${redirect.source} stops redirecting.`,\n confirmationText: 'Delete',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n try {\n await updateDoc(\n doc(firestore, 'hosts', hostId, 'redirects', redirect.$id),\n { deletedAt: Timestamp.now(), enabled: false },\n )\n announceRuleChange(redirect.source)\n } catch (error: any) {\n reportWriteFailure(error)\n }\n },\n [confirm, firestore, hostId, reportWriteFailure, announceRuleChange],\n )\n\n return (\n <CardDisplay\n header={'URL redirects'}\n help={pluginDocsHelp('redirects', { anchor: '#manage-redirects' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Exact-path rules; 302 while testing, promote to 301 when ' +\n 'sure (browsers cache 301 aggressively). Changes go live ' +\n 'within ~30 seconds.'}\n </Typography>\n {hits && totalHits > 0 ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`${totalHits} redirect hit${totalHits === 1 ? '' : 's'} in ` +\n 'the last 30 days (sampled — one per cache window with ' +\n 'traffic).'}\n </Typography>\n ) : null}\n {visibleRedirects.map((redirect: any) => (\n <Stack\n key={redirect.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Switch\n size=\"small\"\n checked={redirect.enabled !== false}\n onChange={handleToggle(redirect)}\n />\n <Chip size=\"small\" label={redirect.statusCode ?? 302} />\n {(redirect.kind ?? 'exact') !== 'exact' ? (\n <Chip\n size=\"small\"\n variant=\"outlined\"\n label={redirect.kind}\n />\n ) : null}\n {/* An external rule with no publisher stamp is not being served\n (AGL-1881) — `matchRedirect` skips it. Say so on the row\n rather than letting it read as live: a rule that silently\n stops firing is the failure mode a fail-closed gate owes an\n explanation for, and pressing Edit → Save is the whole fix.\n Shown for external destinations only, since that is the only\n case the gate applies to. */}\n {isExternalRedirectDestination(redirect.destination) &&\n !redirect.externalDestinationApprovedBy ? (\n <Chip\n size=\"small\"\n color=\"warning\"\n variant=\"outlined\"\n label=\"not serving\"\n title={\n 'This rule sends visitors to another site. Open it and ' +\n 'save to confirm the destination — until then it is ' +\n 'skipped.'\n }\n />\n ) : null}\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {`${redirect.source} → ${redirect.destination}`}\n </Typography>\n {hits || redirect.lastHitAt ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {[\n hits\n ? `${hits[idKey(redirect.$id)] ?? 0} hits (30d, sampled)`\n : null,\n redirect.lastHitAt\n ? `last ${redirect.lastHitAt\n .toDate()\n .toLocaleString()}`\n : null,\n ]\n .filter(Boolean)\n .join(' · ')}\n </Typography>\n ) : null}\n </Stack>\n <Button\n size=\"small\"\n onClick={() =>\n setDraft({\n id: redirect.$id,\n source: redirect.source ?? '',\n destination: redirect.destination ?? '',\n statusCode: redirect.statusCode ?? 302,\n kind: redirect.kind ?? 'exact',\n priority: redirect.priority ?? REDIRECT_DEFAULT_PRIORITY,\n // Read exactly as the switch beside it does (AGL-1372):\n // an edit must not be a way to turn a rule back on.\n enabled: redirect.enabled !== false,\n })\n }\n >\n {'Edit'}\n </Button>\n <Button\n size=\"small\"\n color=\"error\"\n onClick={handleDelete(redirect)}\n >\n {'Delete'}\n </Button>\n </Stack>\n ))}\n {redirects.length === 0 ? null : (\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={visibleRedirects.length}\n // The rules this page HOLDS, after the soft-deleted ones are\n // dropped. Not the quota figure below it: that is a server\n // count over every document, soft-deleted rows included,\n // because a deleted rule still occupies a slot.\n count={redirects.length}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n />\n )}\n {redirectsTruncated ? (\n <Alert severity=\"info\">\n {`Showing ${REDIRECT_CEILING} rules, ordered by id. This site ` +\n 'has more — the duplicate check and the tester below only ' +\n 'cover the ones listed here.'}\n </Alert>\n ) : null}\n <Button\n size=\"small\"\n color=\"primary\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={handleAdd}\n >\n {'Add redirect'}\n </Button>\n {/* The cap, standing rather than only on refusal (AGL-2113).\n `enforcedCount` is what the enforcing route counts and what\n `handleAdd` checks against, so the readout, the gate and the\n server cannot disagree. It is deliberately NOT the number of rows\n on screen: a soft-deleted rule still occupies a slot, so showing\n the visible count here would promise room the server refuses. */}\n <QuotaReadoutComponent\n ready={org != null && enforcedCount != null}\n used={enforcedCount ?? 0}\n limit={\n checkQuota(org, 'redirectsPerHost', enforcedCount ?? 0).limit\n }\n noun=\"redirect\"\n />\n {/* Inline tester (AGL-375): same matcher as enforcement. */}\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <TextField\n size=\"small\"\n label=\"Test a path\"\n placeholder=\"/old-page\"\n value={testPath}\n onChange={(event) => setTestPath(event.target.value)}\n sx={{ maxWidth: 260 }}\n />\n {testPath.trim() ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {(() => {\n const normalized =\n normalizeRedirectSource(testPath) ?? testPath.trim()\n const result = matchRedirect(redirects as any, normalized)\n return result\n ? `→ ${result.destination} (${result.statusCode})`\n : 'No rule matches'\n })()}\n </Typography>\n ) : null}\n </Stack>\n </Stack>\n\n <Dialog\n open={Boolean(draft)}\n onClose={() => setDraft(null)}\n maxWidth=\"xs\"\n fullWidth\n >\n <DialogTitle>{draft?.id ? 'Edit redirect' : 'Add redirect'}</DialogTitle>\n <DialogContent\n sx={{ display: 'flex', flexDirection: 'column', gap: 1.5, pt: 1 }}\n >\n <TextField\n select\n label=\"Match mode\"\n value={draft?.kind ?? 'exact'}\n onChange={(event) =>\n setDraft((prev) =>\n prev ? { ...prev, kind: event.target.value } : prev,\n )\n }\n size=\"small\"\n sx={{ mt: 1 }}\n >\n <MenuItem value=\"exact\">{'Exact path'}</MenuItem>\n <MenuItem value=\"prefix\">{'Path prefix'}</MenuItem>\n <MenuItem value=\"regex\">{'Regular expression'}</MenuItem>\n </TextField>\n <TextField\n label={draft?.kind === 'regex' ? 'Pattern' : 'From path'}\n placeholder={\n draft?.kind === 'regex' ? '/product/(\\\\d+)' : '/old-page'\n }\n helperText={\n draft?.kind === 'regex'\n ? 'Anchored to the whole path; use $1, $2 in the destination'\n : draft?.kind === 'prefix'\n ? 'Matches the path and everything under it'\n : undefined\n }\n value={draft?.source ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev ? { ...prev, source: event.target.value } : prev,\n )\n }\n size=\"small\"\n autoFocus\n />\n <TextField\n label=\"To\"\n placeholder=\"/new-page or https://example.com\"\n value={draft?.destination ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev ? { ...prev, destination: event.target.value } : prev,\n )\n }\n size=\"small\"\n />\n <TextField\n select\n label=\"Status code\"\n value={draft?.statusCode ?? 302}\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? { ...prev, statusCode: Number(event.target.value) }\n : prev,\n )\n }\n size=\"small\"\n >\n <MenuItem value={302}>{'302 — temporary (default)'}</MenuItem>\n <MenuItem value={301}>{'301 — permanent'}</MenuItem>\n <MenuItem value={307}>{'307 — temporary, keep method'}</MenuItem>\n <MenuItem value={308}>{'308 — permanent, keep method'}</MenuItem>\n </TextField>\n <TextField\n label=\"Priority\"\n type=\"number\"\n helperText=\"Lower fires first when several rules match\"\n value={draft?.priority ?? REDIRECT_DEFAULT_PRIORITY}\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? { ...prev, priority: Number(event.target.value) }\n : prev,\n )\n }\n size=\"small\"\n />\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setDraft(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={!draft?.source.trim() || !draft?.destination.trim()}\n onClick={handleSave}\n >\n {'Save redirect'}\n </Button>\n </DialogActions>\n </Dialog>\n </CardDisplay>\n )\n}\nRedirectsConsolePage.displayName = 'RedirectsConsolePage'\n\nexport default RedirectsConsolePage\n"],"names":["checkQuota","pluginDocsHelp","isExternalRedirectDestination","isSelfRedirect","matchRedirect","normalizeRedirectDestination","normalizeRedirectSource","REDIRECT_DEFAULT_PRIORITY","validateRedirectRule","REDIRECT_STATUS_CODES","CardDisplay","useConfirmationContext","authorizedFetch","QuotaReadoutComponent","useSnackbar","Timestamp","Alert","Button","Chip","Dialog","DialogActions","DialogContent","DialogTitle","MenuItem","Stack","Switch","TextField","Typography","collection","deleteField","doc","getCountFromServer","getDoc","setDoc","updateDoc","useCallback","useEffect","useMemo","useState","ListPagination","TABLE_PAGE_SIZE_DEFAULT","ceilingedWindow","collectionCeiling","useFirestore","useFirestoreCollection","useFirestoreDoc","useHostResourceApi","useUser","writeGuardedBySeed","REDIRECT_CEILING","RedirectsConsolePage","props","hostId","entitled","org","firestore","createHostResource","data","currentUser","enqueueSnackbar","confirm","redirectDocs","status","redirectsStatus","fromCache","redirectsFromCache","idField","rows","readRedirects","truncated","redirectsTruncated","redirects","filter","redirect","deletedAt","sort","a","b","String","source","localeCompare","page","setPage","pageSize","setPageSize","visibleRedirects","slice","enforcedCount","setEnforcedCount","redirectDocCount","length","countRedirects","snapshot","count","active","then","draft","setDraft","testPath","setTestPath","host","hits","setHits","ids","Array","from","_","index","date","Date","setDate","getDate","toISOString","Promise","all","map","id","get","catch","days","totals","dayMap","redirectId","Object","entries","Number","idKey","value","replace","totalHits","values","reduce","sum","handleAdd","variant","persist","quota","allowed","limit","destination","statusCode","kind","priority","enabled","announceRuleChange","redirectPath","startsWith","method","headers","body","JSON","stringify","undefined","handleSave","problem","trim","duplicate","find","$id","bySource","Map","cursor","toLowerCase","hop","next","routedPaths","screens","path","includes","fields","isFinite","approval","externalDestinationApprovedBy","uid","verdict","subject","unreadable","updatedAt","now","merge","ok","message","resource","previous","rule","error","console","allowDuplicate","reportWriteFailure","code","handleToggle","event","target","checked","handleDelete","confirmed","title","description","confirmationText","confirmationButtonProps","color","header","help","anchor","contentGutterX","contentGutterY","spacing","direction","sx","alignItems","size","onChange","label","flex","minWidth","noWrap","lastHitAt","toDate","toLocaleString","Boolean","join","onClick","rowCount","onPageChange","onPageSizeChange","severity","alignSelf","ready","used","noun","placeholder","maxWidth","normalized","result","open","onClose","fullWidth","display","flexDirection","gap","pt","select","prev","mt","helperText","autoFocus","type","disabled","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAASA,UAAU,EAAEC,cAAc,QAAQ,eAAc;AAEzD,SAASC,6BAA6B,EAAEC,cAAc,EAAEC,aAAa,EAAEC,4BAA4B,EAAEC,uBAAuB,EAAEC,yBAAyB,EAAEC,oBAAoB,EAAEC,qBAAqB,QAAQ,oBAAU;AACtN,SAASC,WAAW,EAAEC,sBAAsB,QAAQ,uBAAsB;AAC1E,SAASC,eAAe,QAAQ,2CAA0C;AAC1E,OAAOC,2BAA2B,0DAAyD;AAC3F,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,SAAS,QAAQ,+BAA8B;AACxD,SACEC,KAAK,EACLC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,QAAQ,EACRC,KAAK,EACLC,MAAM,EACNC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SACEC,UAAU,EACVC,WAAW,EACXC,GAAG,EACHC,kBAAkB,EAClBC,MAAM,EACNC,MAAM,EACNC,SAAS,QACJ,qBAAoB;AAC3B,SAASC,WAAW,EAAEC,SAAS,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACjE,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SAASC,uBAAuB,QAAQ,8CAA6C;AACrF,SACEC,eAAe,EACfC,iBAAiB,EACjBC,YAAY,EACZC,sBAAsB,EACtBC,eAAe,EACfC,kBAAkB,EAClBC,OAAO,EACPC,kBAAkB,QACb,iCAAgC;AAEvC;;;;;;;;;CASC,GACD,MAAMC,mBAAmB;AAqBzB;;;;;;;;;;;;;;;;;;CAkBC,GAC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AAM,CAACjE,KAAK;6CAAKmH;gCAG1DhC,MAAK;;0CAEP,MAACxL;gCACCuN,MAAM;gCACN7B,OAAM;gCACNrF,KAAK,WAAE/B,yBAAAA,MAAO4C,UAAU,oBAAI;gCAC5BuE,UAAU,CAACpB,QACT9F,SAAS,CAACiJ,OACRA,OACI,aAAKA;4CAAMtG,YAAYf,OAAOkE,MAAMC,MAAM,CAACjE,KAAK;6CAChDmH;gCAGRhC,MAAK;;kDAEL,KAAC3L;wCAASwG,OAAO;kDAAM;;kDACvB,KAACxG;wCAASwG,OAAO;kDAAM;;kDACvB,KAACxG;wCAASwG,OAAO;kDAAM;;kDACvB,KAACxG;wCAASwG,OAAO;kDAAM;;;;0CAEzB,KAACrG;gCACC0L,OAAM;gCACNkC,MAAK;gCACLF,YAAW;gCACXrH,KAAK,WAAE/B,yBAAAA,MAAO8C,QAAQ,oBAAIvI;gCAC1B4M,UAAU,CAACpB,QACT9F,SAAS,CAACiJ,OACRA,OACI,aAAKA;4CAAMpG,UAAUjB,OAAOkE,MAAMC,MAAM,CAACjE,KAAK;6CAC9CmH;gCAGRhC,MAAK;;;;kCAGT,MAAC9L;;0CACC,KAACH;gCAAO4M,SAAS,IAAM5H,SAAS;0CAAQ;;0CACxC,KAAChF;gCACCqH,SAAQ;gCACRkE,OAAM;gCACN+C,UAAU,EAACvJ,yBAAAA,MAAOjB,MAAM,CAAC4E,IAAI,OAAM,EAAC3D,yBAAAA,MAAO2C,WAAW,CAACgB,IAAI;gCAC3DkE,SAASpE;0CAER;;;;;;;;AAMb;AACAvG,qBAAqBsM,WAAW,GAAG;AAEnC,eAAetM,qBAAoB"}
@@ -0,0 +1,8 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ */
8
+ export declare const BUNDLE_ID = "redirects";
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ */ export const BUNDLE_ID = 'redirects';
8
+
9
+ //# sourceMappingURL=bundle-common.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/redirects/src/lib/constants/bundle-common.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 */\n\nexport const BUNDLE_ID = 'redirects'\n"],"names":["BUNDLE_ID"],"mappings":"AAAA;;;;;;CAMC,GAED,OAAO,MAAMA,YAAY,YAAW"}
@@ -0,0 +1,22 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /**
18
+ * Redirects domain model (AGL-412): rule matching/validation relocated from core app-utils.
19
+ * Context-free — importable by client components, /server handlers, and
20
+ * other plugins/apps via `@aglyn/plugins-redirects/model`.
21
+ */
22
+ export * from './redirects';
@@ -0,0 +1,22 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ /**
17
+ * Redirects domain model (AGL-412): rule matching/validation relocated from core app-utils.
18
+ * Context-free — importable by client components, /server handlers, and
19
+ * other plugins/apps via `@aglyn/plugins-redirects/model`.
20
+ */ export * from "./redirects.js";
21
+
22
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/redirects/src/lib/model/index.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Redirects domain model (AGL-412): rule matching/validation relocated from core app-utils.\n * Context-free — importable by client components, /server handlers, and\n * other plugins/apps via `@aglyn/plugins-redirects/model`.\n */\nexport * from './redirects'\n"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;CAIC,GACD,cAAc,iBAAa"}
@@ -0,0 +1,143 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /**
18
+ * URL redirects (AGL-154): paid per-host rules at
19
+ * `hosts/{hostId}/redirects/{id}`. Exact source match in v1 (the `kind`
20
+ * field leaves room for patterns later); destinations are internal paths
21
+ * or absolute https URLs. Console validation and tenant enforcement share
22
+ * these helpers so they can't disagree.
23
+ */
24
+ import { type LinearPattern } from '@aglyn/shared-util-tools/linear-regex';
25
+ export interface HostRedirect {
26
+ /**
27
+ * Match input: a normalized path for exact/prefix rules, a regular
28
+ * expression for regex rules (v2, AGL-375).
29
+ */
30
+ source: string;
31
+ /**
32
+ * Internal path (`/pricing`) or absolute https URL. Regex rules may
33
+ * reference capture groups as `$1`, `$2`, ….
34
+ */
35
+ destination: string;
36
+ /** 302 by default while testing; owners promote to 301 when sure. */
37
+ statusCode: 301 | 302 | 307 | 308;
38
+ enabled?: boolean;
39
+ /** Match mode (AGL-375); missing = exact (v1 rules). */
40
+ kind?: 'exact' | 'prefix' | 'regex';
41
+ /** Evaluation order — lower fires first; missing = 100 (v1 rules). */
42
+ priority?: number;
43
+ /**
44
+ * The uid of the publishing-role member who last saved this rule with an
45
+ * EXTERNAL destination (AGL-1881). Absent on every internal rule, and on
46
+ * every rule written before that issue.
47
+ *
48
+ * This is provenance, not preference. `cloud/firebase-firestore.rules` lets
49
+ * only `canPublishHostContent` — admin or editor, never `author` — write
50
+ * anything in `hosts/{hostId}/redirects`, so the presence of this field is
51
+ * the serve path's evidence that a publisher chose to send traffic off the
52
+ * platform. `matchRedirect` will not serve an absolute destination without
53
+ * it, which is what makes a rule written BEFORE the rules were fixed refuse
54
+ * to fire rather than having to be trusted.
55
+ *
56
+ * Deliberately a uid rather than a boolean: `true` says nothing a log can be
57
+ * read against, and the recovery for a rule that stops firing is for a
58
+ * publisher to open it and save, which stamps their own uid.
59
+ */
60
+ externalDestinationApprovedBy?: string;
61
+ }
62
+ export declare const REDIRECT_STATUS_CODES: readonly [301, 302, 307, 308];
63
+ export declare const REDIRECT_KINDS: readonly ["exact", "prefix", "regex"];
64
+ export declare const REDIRECT_DEFAULT_PRIORITY = 100;
65
+ /**
66
+ * Compiles a regex rule's source for LINEAR-TIME matching (SEC-M8).
67
+ *
68
+ * Redirect sources are attacker-controlled: any host member with the
69
+ * `author` role can write `source` and `kind` straight to Firestore with the
70
+ * client SDK, so the console's validation is a convenience, not a control —
71
+ * this function, on the request path, is the only thing standing between a
72
+ * customer-authored string and the tenant event loop.
73
+ *
74
+ * It therefore does not use `RegExp`. `compileLinearPattern` runs the
75
+ * pattern on a Thompson NFA simulation whose cost is bounded by
76
+ * `path length × program length` for every possible input, replacing the
77
+ * AGL-505 star-height heuristic that `(a|a|aa)+` walked straight through
78
+ * (9 characters, 59 s measured on a 27-character path).
79
+ *
80
+ * Returns null for malformed patterns and for syntax outside the supported
81
+ * subset — callers reject at save and skip at match, so a bad pattern can
82
+ * never take a site down.
83
+ */
84
+ export declare function compileRedirectRegex(source: string): LinearPattern | null;
85
+ /** Validation for a v2 rule; returns a problem string or null when ok. */
86
+ export declare function validateRedirectRule(rule: {
87
+ kind?: string;
88
+ source: string;
89
+ destination: string;
90
+ }): string | null;
91
+ /**
92
+ * Does this destination leave the platform? (AGL-1881.)
93
+ *
94
+ * Written as "not internal" rather than as "starts with https://", so that
95
+ * anything the normalizer has not already vouched for — an empty string, a
96
+ * protocol-relative `//host`, a scheme we never expected — answers TRUE and
97
+ * meets the approval gate rather than slipping past it. `strictNullChecks` is
98
+ * off repo-wide: an absent destination arrives here as `undefined`, folds to
99
+ * `''`, and must not read as "internal, therefore safe".
100
+ */
101
+ export declare function isExternalRedirectDestination(destination: string): boolean;
102
+ export interface RedirectMatch {
103
+ /** Destination with any capture groups substituted. */
104
+ destination: string;
105
+ statusCode: 301 | 302 | 307 | 308;
106
+ /** The rule that fired (for hit recording). */
107
+ index: number;
108
+ }
109
+ /**
110
+ * Evaluates rules against a request path (AGL-375): priority order
111
+ * (lower first, stable by list order), exact → equality, prefix →
112
+ * segment-boundary prefix, regex → anchored pattern with `$n` capture
113
+ * substitution in the destination. Disabled, self-targeting, and
114
+ * invalid rules never fire.
115
+ *
116
+ * The DESTINATION is validated here too (AGL-1881), after substitution: it
117
+ * must still normalize, and an external one must carry a publisher's stamp.
118
+ * See the two notes inside the loop.
119
+ */
120
+ export declare function matchRedirect(rules: Array<HostRedirect & {
121
+ deletedAt?: unknown;
122
+ }>, path: string): RedirectMatch | null;
123
+ /**
124
+ * Source normalization: leading slash, lowercase, query/hash stripped,
125
+ * trailing slash stripped (root stays `/`). Returns null for unusable
126
+ * input so callers reject rather than store junk.
127
+ */
128
+ export declare function normalizeRedirectSource(input: string): string | null;
129
+ /**
130
+ * Destination validation: an internal path (normalized like sources but
131
+ * case-preserved) or an absolute https URL. Returns the cleaned value or
132
+ * null when invalid.
133
+ */
134
+ export declare function normalizeRedirectDestination(input: string): string | null;
135
+ /**
136
+ * True when the rule would redirect a path onto itself — the loop case
137
+ * both the console and the tenant enforcement must refuse (they validate
138
+ * independently and may disagree; this is the shared floor).
139
+ */
140
+ export declare function isSelfRedirect(redirect: {
141
+ source: string;
142
+ destination: string;
143
+ }): boolean;
@@ -0,0 +1,255 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ /**
17
+ * URL redirects (AGL-154): paid per-host rules at
18
+ * `hosts/{hostId}/redirects/{id}`. Exact source match in v1 (the `kind`
19
+ * field leaves room for patterns later); destinations are internal paths
20
+ * or absolute https URLs. Console validation and tenant enforcement share
21
+ * these helpers so they can't disagree.
22
+ */ import { compileLinearPattern, explainLinearPattern } from "@aglyn/shared-util-tools/linear-regex";
23
+ export const REDIRECT_STATUS_CODES = [
24
+ 301,
25
+ 302,
26
+ 307,
27
+ 308
28
+ ];
29
+ export const REDIRECT_KINDS = [
30
+ 'exact',
31
+ 'prefix',
32
+ 'regex'
33
+ ];
34
+ export const REDIRECT_DEFAULT_PRIORITY = 100;
35
+ /** Max regex source length — a rule source has no business being longer. */ const REGEX_SOURCE_MAX = 200;
36
+ /**
37
+ * Anchors a rule source to the whole path unless the author anchored it
38
+ * themselves. Kept in one place so validation and matching cannot disagree
39
+ * about what is actually compiled.
40
+ */ function anchorSource(pattern) {
41
+ return (pattern.startsWith('^') ? '' : '^') + pattern + (pattern.endsWith('$') ? '' : '$');
42
+ }
43
+ /**
44
+ * Compiles a regex rule's source for LINEAR-TIME matching (SEC-M8).
45
+ *
46
+ * Redirect sources are attacker-controlled: any host member with the
47
+ * `author` role can write `source` and `kind` straight to Firestore with the
48
+ * client SDK, so the console's validation is a convenience, not a control —
49
+ * this function, on the request path, is the only thing standing between a
50
+ * customer-authored string and the tenant event loop.
51
+ *
52
+ * It therefore does not use `RegExp`. `compileLinearPattern` runs the
53
+ * pattern on a Thompson NFA simulation whose cost is bounded by
54
+ * `path length × program length` for every possible input, replacing the
55
+ * AGL-505 star-height heuristic that `(a|a|aa)+` walked straight through
56
+ * (9 characters, 59 s measured on a 27-character path).
57
+ *
58
+ * Returns null for malformed patterns and for syntax outside the supported
59
+ * subset — callers reject at save and skip at match, so a bad pattern can
60
+ * never take a site down.
61
+ */ export function compileRedirectRegex(source) {
62
+ const pattern = String(source != null ? source : '').trim();
63
+ if (!pattern || pattern.length > REGEX_SOURCE_MAX) return null;
64
+ return compileLinearPattern(anchorSource(pattern));
65
+ }
66
+ /** Validation for a v2 rule; returns a problem string or null when ok. */ export function validateRedirectRule(rule) {
67
+ var _rule_kind;
68
+ const kind = (_rule_kind = rule.kind) != null ? _rule_kind : 'exact';
69
+ if (!REDIRECT_KINDS.includes(kind)) {
70
+ return 'Unknown match mode';
71
+ }
72
+ if (kind === 'regex') {
73
+ if (compileRedirectRegex(rule.source) === null) {
74
+ var _rule_source;
75
+ // Say *why* — the supported subset excludes lookaround and
76
+ // backreferences, and "not a valid regular expression" would send an
77
+ // author hunting for a typo that isn't there.
78
+ const pattern = String((_rule_source = rule.source) != null ? _rule_source : '').trim();
79
+ if (!pattern) return 'Enter a pattern';
80
+ if (pattern.length > REGEX_SOURCE_MAX) {
81
+ return `Patterns are limited to ${REGEX_SOURCE_MAX} characters`;
82
+ }
83
+ const reason = explainLinearPattern(anchorSource(pattern));
84
+ return reason ? `That pattern can't be used: ${reason}` : 'The pattern is not a valid regular expression';
85
+ }
86
+ } else if (!normalizeRedirectSource(rule.source)) {
87
+ return 'Enter a site path like /old-page';
88
+ }
89
+ if (!normalizeRedirectDestination(rule.destination)) {
90
+ return 'Destinations are internal paths or https:// URLs';
91
+ }
92
+ return null;
93
+ }
94
+ /**
95
+ * Does this destination leave the platform? (AGL-1881.)
96
+ *
97
+ * Written as "not internal" rather than as "starts with https://", so that
98
+ * anything the normalizer has not already vouched for — an empty string, a
99
+ * protocol-relative `//host`, a scheme we never expected — answers TRUE and
100
+ * meets the approval gate rather than slipping past it. `strictNullChecks` is
101
+ * off repo-wide: an absent destination arrives here as `undefined`, folds to
102
+ * `''`, and must not read as "internal, therefore safe".
103
+ */ export function isExternalRedirectDestination(destination) {
104
+ const value = String(destination != null ? destination : '').trim();
105
+ return !(value.startsWith('/') && !value.startsWith('//'));
106
+ }
107
+ /**
108
+ * Has a publisher vouched for this rule's external destination? (AGL-1881.)
109
+ *
110
+ * The `typeof` test is the point. With `strictNullChecks` off, a missing field
111
+ * is `undefined` and a stored `null` is `null`; both must answer FALSE, and so
112
+ * must a stamp that is present but blank. Only a non-empty string counts.
113
+ */ function externalDestinationApproved(rule) {
114
+ const approver = rule.externalDestinationApprovedBy;
115
+ return typeof approver === 'string' && approver.trim().length > 0;
116
+ }
117
+ /**
118
+ * Evaluates rules against a request path (AGL-375): priority order
119
+ * (lower first, stable by list order), exact → equality, prefix →
120
+ * segment-boundary prefix, regex → anchored pattern with `$n` capture
121
+ * substitution in the destination. Disabled, self-targeting, and
122
+ * invalid rules never fire.
123
+ *
124
+ * The DESTINATION is validated here too (AGL-1881), after substitution: it
125
+ * must still normalize, and an external one must carry a publisher's stamp.
126
+ * See the two notes inside the loop.
127
+ */ export function matchRedirect(rules, path) {
128
+ const ordered = rules.map((rule, index)=>({
129
+ rule,
130
+ index
131
+ })).filter(({ rule })=>rule.enabled !== false && !rule.deletedAt).sort((a, b)=>{
132
+ var _a_rule_priority, _b_rule_priority;
133
+ return ((_a_rule_priority = a.rule.priority) != null ? _a_rule_priority : REDIRECT_DEFAULT_PRIORITY) - ((_b_rule_priority = b.rule.priority) != null ? _b_rule_priority : REDIRECT_DEFAULT_PRIORITY) || a.index - b.index;
134
+ });
135
+ for (const { rule, index } of ordered){
136
+ var _rule_kind;
137
+ const kind = (_rule_kind = rule.kind) != null ? _rule_kind : 'exact';
138
+ let destination = null;
139
+ if (kind === 'exact') {
140
+ if (rule.source === path) destination = rule.destination;
141
+ } else if (kind === 'prefix') {
142
+ if (path === rule.source || path.startsWith(rule.source) && (rule.source === '/' || path[rule.source.length] === '/')) {
143
+ destination = rule.destination;
144
+ }
145
+ } else if (kind === 'regex') {
146
+ const pattern = compileRedirectRegex(rule.source);
147
+ const matched = pattern == null ? void 0 : pattern.exec(path);
148
+ if (matched) {
149
+ destination = rule.destination.replace(/\$(\d)/g, (token, groupIndex)=>{
150
+ var _matched_Number;
151
+ return (_matched_Number = matched[Number(groupIndex)]) != null ? _matched_Number : '';
152
+ });
153
+ }
154
+ }
155
+ if (!destination) continue;
156
+ /**
157
+ * Validate the destination HERE, on the serve path, after any `$n`
158
+ * substitution (AGL-1881).
159
+ *
160
+ * This function used to hand `rule.destination` straight back. Console
161
+ * validation was the only thing standing between a stored string and a
162
+ * `Location:` header — the same "the console is a convenience, not a
163
+ * control" note `compileRedirectRegex` already carries about `source`,
164
+ * one field over and never applied.
165
+ *
166
+ * Two distinct holes close on this line:
167
+ *
168
+ * 1. A destination that never met `normalizeRedirectDestination` at all,
169
+ * because it was written straight to Firestore rather than through the
170
+ * console — `http://` (a downgrade), `//host` (protocol-relative), a
171
+ * `javascript:`/`data:` scheme, a value carrying whitespace or CRLF.
172
+ * 2. A destination that DID meet it and stops meeting it once captures
173
+ * are substituted. `/$1` is an internal path at save time and becomes
174
+ * `//attacker.example` when the pattern's group swallows a hostname —
175
+ * an open redirect out of a rule that reads as entirely internal.
176
+ * Post-substitution is the only place either can be seen.
177
+ *
178
+ * A rule that fails is SKIPPED, not fatal: evaluation continues to the
179
+ * next rule exactly as it does for an uncompilable pattern, so a bad
180
+ * destination can never take a site down.
181
+ */ const validated = normalizeRedirectDestination(destination);
182
+ if (!validated) continue;
183
+ destination = validated;
184
+ /**
185
+ * An external destination fires only with a publisher's stamp on it.
186
+ *
187
+ * This is the defence-in-depth half of AGL-1881, and it is what makes the
188
+ * rules fix retroactive. Rules stop an `author` from WRITING one from now
189
+ * on; a rule already written — before this file, from a role that has
190
+ * since been refused, or by any path we have not thought of — still sits
191
+ * in Firestore, and without this it would still be served on every request
192
+ * to the site. Absent stamp, absent field, blank stamp: all refuse.
193
+ *
194
+ * Internal destinations are untouched, which is deliberate. The cost of
195
+ * failing closed here is paid ONLY by rules that send traffic off the
196
+ * platform, and recovering one is a publisher opening it and pressing
197
+ * Save.
198
+ */ if (isExternalRedirectDestination(destination) && !externalDestinationApproved(rule)) {
199
+ continue;
200
+ }
201
+ if (isSelfRedirect({
202
+ source: path,
203
+ destination
204
+ })) continue;
205
+ const statusCode = REDIRECT_STATUS_CODES.includes(rule.statusCode) ? rule.statusCode : 302;
206
+ return {
207
+ destination,
208
+ statusCode,
209
+ index
210
+ };
211
+ }
212
+ return null;
213
+ }
214
+ /**
215
+ * Source normalization: leading slash, lowercase, query/hash stripped,
216
+ * trailing slash stripped (root stays `/`). Returns null for unusable
217
+ * input so callers reject rather than store junk.
218
+ */ export function normalizeRedirectSource(input) {
219
+ let path = String(input != null ? input : '').trim();
220
+ if (!path) return null;
221
+ // Absolute URLs and protocol-ish sources are not paths.
222
+ if (/^[a-z][a-z0-9+.-]*:/i.test(path) || path.startsWith('//')) return null;
223
+ if (!path.startsWith('/')) path = `/${path}`;
224
+ path = path.split(/[?#]/)[0].toLowerCase();
225
+ if (path.length > 1) path = path.replace(/\/+$/, '');
226
+ if (path.length > 500 || /\s/.test(path)) return null;
227
+ return path || '/';
228
+ }
229
+ /**
230
+ * Destination validation: an internal path (normalized like sources but
231
+ * case-preserved) or an absolute https URL. Returns the cleaned value or
232
+ * null when invalid.
233
+ */ export function normalizeRedirectDestination(input) {
234
+ const value = String(input != null ? input : '').trim();
235
+ if (!value || value.length > 1000 || /\s/.test(value)) return null;
236
+ if (/^https:\/\/[^/]+/i.test(value)) return value;
237
+ if (value.startsWith('/') && !value.startsWith('//')) {
238
+ return value.length > 1 ? value.replace(/\/+$/, '') : '/';
239
+ }
240
+ return null;
241
+ }
242
+ /**
243
+ * True when the rule would redirect a path onto itself — the loop case
244
+ * both the console and the tenant enforcement must refuse (they validate
245
+ * independently and may disagree; this is the shared floor).
246
+ */ export function isSelfRedirect(redirect) {
247
+ const destination = redirect.destination.toLowerCase();
248
+ if (destination.startsWith('/')) {
249
+ const normalized = destination.length > 1 ? destination.replace(/\/+$/, '') : '/';
250
+ return normalized === redirect.source;
251
+ }
252
+ return false;
253
+ }
254
+
255
+ //# sourceMappingURL=redirects.js.map