@aglyn/plugins-redirects 1.29.3 → 1.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/plugins-redirects",
3
- "version": "1.29.3",
3
+ "version": "1.30.0",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,16 +25,16 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.29.3",
29
- "@aglyn/shared-data-mdi": "1.29.3",
30
- "@aglyn/shared-ui-jsx": "1.29.3",
31
- "@aglyn/shared-ui-snackstack": "1.29.3",
32
- "@aglyn/shared-util-email": "1.29.3",
33
- "@aglyn/shared-util-http": "1.29.3",
34
- "@aglyn/shared-util-timestamp": "1.29.3",
35
- "@aglyn/shared-util-tools": "1.29.3",
36
- "@aglyn/tenant-data-admin": "1.29.3",
37
- "@aglyn/tenant-feature-instance": "1.29.3",
28
+ "@aglyn/aglyn": "1.30.0",
29
+ "@aglyn/shared-data-mdi": "1.30.0",
30
+ "@aglyn/shared-ui-jsx": "1.30.0",
31
+ "@aglyn/shared-ui-snackstack": "1.30.0",
32
+ "@aglyn/shared-util-email": "1.30.0",
33
+ "@aglyn/shared-util-http": "1.30.0",
34
+ "@aglyn/shared-util-timestamp": "1.30.0",
35
+ "@aglyn/shared-util-tools": "1.30.0",
36
+ "@aglyn/tenant-data-admin": "1.30.0",
37
+ "@aglyn/tenant-feature-instance": "1.30.0",
38
38
  "@swc/helpers": "0.5.24"
39
39
  },
40
40
  "peerDependencies": {
@@ -0,0 +1,52 @@
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
+ * How many rules one page of the walk reads (AGL-4247). Not a ceiling: the
19
+ * walk keeps reading pages until one comes back short.
20
+ */
21
+ export declare const REDIRECT_RULES_PAGE_SIZE = 500;
22
+ /** The slice of a Firestore admin query the walk uses, so a spec can stand in for it. */
23
+ export interface RedirectRulesQuery<Doc> {
24
+ where(field: string, op: '==', value: unknown): RedirectRulesQuery<Doc>;
25
+ orderBy(field: unknown): RedirectRulesQuery<Doc>;
26
+ startAfter(doc: Doc): RedirectRulesQuery<Doc>;
27
+ limit(count: number): RedirectRulesQuery<Doc>;
28
+ get(): Promise<{
29
+ docs: Doc[];
30
+ }>;
31
+ }
32
+ /**
33
+ * EVERY rule of a site's `hosts/{id}/redirects`, read in pages (AGL-4247).
34
+ *
35
+ * The live resolver read `where('enabled', '==', true).limit(100)` with no
36
+ * order, so a site past 100 rules lost the rest silently: Firestore answers
37
+ * an unordered limit in document-id order, and the ids are generated, so it
38
+ * was a pseudo-random hundred that fired and the others sent visitors to
39
+ * "page not found". Pro and Custom are sold with no redirect limit, and a
40
+ * Shopify or Wix move routinely brings hundreds of old addresses, so the
41
+ * window was the bug: there is no count at which dropping a stored rule is
42
+ * correct.
43
+ *
44
+ * Ordered by document id, which every document has (`source` is not
45
+ * validated for presence, so ordering on it would drop a rule saved without
46
+ * one, see AGL-2501), and paged with `startAfter` so no single read is
47
+ * unbounded. The resolver caches the result per host, so the walk runs once
48
+ * per cache entry, not per request.
49
+ */
50
+ export declare function readAllRedirectRules<Doc>(rules: RedirectRulesQuery<Doc>, options?: {
51
+ enabledOnly?: boolean;
52
+ }): Promise<Doc[]>;
@@ -0,0 +1,51 @@
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
+ */ import { FieldPath } from "firebase-admin/firestore";
17
+ /**
18
+ * How many rules one page of the walk reads (AGL-4247). Not a ceiling: the
19
+ * walk keeps reading pages until one comes back short.
20
+ */ export const REDIRECT_RULES_PAGE_SIZE = 500;
21
+ /**
22
+ * EVERY rule of a site's `hosts/{id}/redirects`, read in pages (AGL-4247).
23
+ *
24
+ * The live resolver read `where('enabled', '==', true).limit(100)` with no
25
+ * order, so a site past 100 rules lost the rest silently: Firestore answers
26
+ * an unordered limit in document-id order, and the ids are generated, so it
27
+ * was a pseudo-random hundred that fired and the others sent visitors to
28
+ * "page not found". Pro and Custom are sold with no redirect limit, and a
29
+ * Shopify or Wix move routinely brings hundreds of old addresses, so the
30
+ * window was the bug: there is no count at which dropping a stored rule is
31
+ * correct.
32
+ *
33
+ * Ordered by document id, which every document has (`source` is not
34
+ * validated for presence, so ordering on it would drop a rule saved without
35
+ * one, see AGL-2501), and paged with `startAfter` so no single read is
36
+ * unbounded. The resolver caches the result per host, so the walk runs once
37
+ * per cache entry, not per request.
38
+ */ export async function readAllRedirectRules(rules, options = {}) {
39
+ const base = options.enabledOnly ? rules.where('enabled', '==', true) : rules;
40
+ const ordered = base.orderBy(FieldPath.documentId());
41
+ const docs = [];
42
+ let last;
43
+ for(;;){
44
+ const page = await (last === undefined ? ordered : ordered.startAfter(last)).limit(REDIRECT_RULES_PAGE_SIZE).get();
45
+ docs.push(...page.docs);
46
+ if (page.docs.length < REDIRECT_RULES_PAGE_SIZE) return docs;
47
+ last = page.docs[page.docs.length - 1];
48
+ }
49
+ }
50
+
51
+ //# sourceMappingURL=read-redirect-rules.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/redirects/src/lib/server/read-redirect-rules.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 { FieldPath } from 'firebase-admin/firestore'\n\n/**\n * How many rules one page of the walk reads (AGL-4247). Not a ceiling: the\n * walk keeps reading pages until one comes back short.\n */\nexport const REDIRECT_RULES_PAGE_SIZE = 500\n\n/** The slice of a Firestore admin query the walk uses, so a spec can stand in for it. */\nexport interface RedirectRulesQuery<Doc> {\n where(field: string, op: '==', value: unknown): RedirectRulesQuery<Doc>\n orderBy(field: unknown): RedirectRulesQuery<Doc>\n startAfter(doc: Doc): RedirectRulesQuery<Doc>\n limit(count: number): RedirectRulesQuery<Doc>\n get(): Promise<{ docs: Doc[] }>\n}\n\n/**\n * EVERY rule of a site's `hosts/{id}/redirects`, read in pages (AGL-4247).\n *\n * The live resolver read `where('enabled', '==', true).limit(100)` with no\n * order, so a site past 100 rules lost the rest silently: Firestore answers\n * an unordered limit in document-id order, and the ids are generated, so it\n * was a pseudo-random hundred that fired and the others sent visitors to\n * \"page not found\". Pro and Custom are sold with no redirect limit, and a\n * Shopify or Wix move routinely brings hundreds of old addresses, so the\n * window was the bug: there is no count at which dropping a stored rule is\n * correct.\n *\n * Ordered by document id, which every document has (`source` is not\n * validated for presence, so ordering on it would drop a rule saved without\n * one, see AGL-2501), and paged with `startAfter` so no single read is\n * unbounded. The resolver caches the result per host, so the walk runs once\n * per cache entry, not per request.\n */\nexport async function readAllRedirectRules<Doc>(\n rules: RedirectRulesQuery<Doc>,\n options: { enabledOnly?: boolean } = {},\n): Promise<Doc[]> {\n const base = options.enabledOnly ? rules.where('enabled', '==', true) : rules\n const ordered = base.orderBy(FieldPath.documentId())\n const docs: Doc[] = []\n let last: Doc | undefined\n for (;;) {\n const page = await (last === undefined ? ordered : ordered.startAfter(last))\n .limit(REDIRECT_RULES_PAGE_SIZE)\n .get()\n docs.push(...page.docs)\n if (page.docs.length < REDIRECT_RULES_PAGE_SIZE) return docs\n last = page.docs[page.docs.length - 1]\n }\n}\n"],"names":["FieldPath","REDIRECT_RULES_PAGE_SIZE","readAllRedirectRules","rules","options","base","enabledOnly","where","ordered","orderBy","documentId","docs","last","page","undefined","startAfter","limit","get","push","length"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,SAAS,QAAQ,2BAA0B;AAEpD;;;CAGC,GACD,OAAO,MAAMC,2BAA2B,IAAG;AAW3C;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,eAAeC,qBACpBC,KAA8B,EAC9BC,UAAqC,CAAC,CAAC;IAEvC,MAAMC,OAAOD,QAAQE,WAAW,GAAGH,MAAMI,KAAK,CAAC,WAAW,MAAM,QAAQJ;IACxE,MAAMK,UAAUH,KAAKI,OAAO,CAACT,UAAUU,UAAU;IACjD,MAAMC,OAAc,EAAE;IACtB,IAAIC;IACJ,OAAS;QACP,MAAMC,OAAO,MAAM,AAACD,CAAAA,SAASE,YAAYN,UAAUA,QAAQO,UAAU,CAACH,KAAI,EACvEI,KAAK,CAACf,0BACNgB,GAAG;QACNN,KAAKO,IAAI,IAAIL,KAAKF,IAAI;QACtB,IAAIE,KAAKF,IAAI,CAACQ,MAAM,GAAGlB,0BAA0B,OAAOU;QACxDC,OAAOC,KAAKF,IAAI,CAACE,KAAKF,IAAI,CAACQ,MAAM,GAAG,EAAE;IACxC;AACF"}
@@ -16,6 +16,7 @@
16
16
  */ import { _ as _extends } from "@swc/helpers/_/_extends";
17
17
  import { holdsSiteKey, siteKeyRefusal } from "@aglyn/aglyn/app-utils/host-permissions";
18
18
  import { firebaseAdmin } from "@aglyn/tenant-data-admin";
19
+ import { readAllRedirectRules } from "./read-redirect-rules.js";
19
20
  import { TENANT_APEX } from "@aglyn/aglyn/app-utils/tenant-apex";
20
21
  import { findDuplicateRedirect, isSelfRedirect, normalizeRedirectDestination, normalizeRedirectSource, redirectSourceIsLivePage, REDIRECT_STATUS_CODES, validateRedirectRule, walkRedirectChain } from "../model/redirects.js";
21
22
  /**
@@ -85,7 +86,6 @@ import { findDuplicateRedirect, isSelfRedirect, normalizeRedirectDestination, no
85
86
  notice
86
87
  };
87
88
  }
88
- /** Rules a check reads, past the page's 200-rule window, so a duplicate or loop beyond it is still caught. */ const RULES_WINDOW = 500;
89
89
  /**
90
90
  * `POST /api/redirects/check`: runs {@link checkRedirectSave} for a member
91
91
  * who may publish on the site (the role the Firestore rules gate redirect
@@ -127,8 +127,9 @@ import { findDuplicateRedirect, isSelfRedirect, normalizeRedirectDestination, no
127
127
  error: siteKeyRefusal('site.publish')
128
128
  });
129
129
  }
130
- const snapshot = await hostRef.collection('redirects').limit(RULES_WINDOW).get();
131
- const rules = snapshot.docs.map((doc)=>_extends({
130
+ // Every rule, past the page's 200-rule window, so a duplicate or loop anywhere is caught (AGL-4247).
131
+ const docs = await readAllRedirectRules(hostRef.collection('redirects'));
132
+ const rules = docs.map((doc)=>_extends({
132
133
  $id: doc.id
133
134
  }, doc.data()));
134
135
  return res.status(200).json(checkRedirectSave(draft, (_host_data = host.data()) != null ? _host_data : {}, rules));
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/redirects/src/lib/server/redirect-check.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { holdsSiteKey, siteKeyRefusal } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { TENANT_APEX } from '@aglyn/aglyn/app-utils/tenant-apex'\nimport {\n findDuplicateRedirect,\n isSelfRedirect,\n normalizeRedirectDestination,\n normalizeRedirectSource,\n redirectSourceIsLivePage,\n REDIRECT_STATUS_CODES,\n validateRedirectRule,\n walkRedirectChain,\n} from '../model/redirects'\n\n/** What a save is asked to write. */\nexport interface RedirectSaveDraft {\n /** The rule being edited; absent for a new rule. */\n id?: string\n kind?: string\n source: string\n destination: string\n statusCode?: number\n}\n\n/** The answer: the page's refusal in its own words, or the rule as the page would store it. */\nexport type RedirectSaveCheck =\n | { ok: false; problem: string }\n | { ok: true; source: string; destination: string; statusCode: number; kind: string; notice: string | null }\n\ntype Rule = { $id: string; source?: string; destination?: string; kind?: string; deletedAt?: unknown }\n\n/**\n * The Redirects page's save checks, in its order and its words\n * (`redirects-console-page.tsx` `handleSave`): the shared rule validation\n * (match mode, from-path or pattern, destination, another company's address),\n * a path redirected to itself, a duplicate rule, a chain that loops back, and\n * the published-page notice that warns without refusing. One source of truth\n * for every client that saves a rule: the native apps ask it here rather than\n * carry their own copy of the phishing screen and the pattern engine.\n */\nexport function checkRedirectSave(\n draft: RedirectSaveDraft,\n host: { cname?: unknown; subdomain?: unknown; screens?: unknown },\n rules: readonly Rule[],\n): RedirectSaveCheck {\n const kind = draft.kind || 'exact'\n const problem = validateRedirectRule(\n { kind, source: draft.source, destination: draft.destination },\n {\n ownDomains: [\n typeof host.cname === 'string' ? host.cname : null,\n typeof host.subdomain === 'string' && host.subdomain ? `${host.subdomain}.${TENANT_APEX}` : null,\n ],\n },\n )\n if (problem) return { ok: false, problem }\n const source = kind === 'regex' ? draft.source.trim() : (normalizeRedirectSource(draft.source) as string)\n const destination = normalizeRedirectDestination(draft.destination) as string\n if (kind !== 'regex' && isSelfRedirect({ source, destination })) {\n return { ok: false, problem: 'That would redirect the path to itself' }\n }\n const live = rules.filter((rule) => !rule.deletedAt)\n if (findDuplicateRedirect(live as never, { $id: draft.id, source, kind })) {\n return { ok: false, problem: `A rule for ${source} already exists` }\n }\n if (walkRedirectChain(live as never, { $id: draft.id, source, destination }).loop) {\n return { ok: false, problem: 'That destination chains back to this rule — a redirect loop' }\n }\n const statusCode = (REDIRECT_STATUS_CODES as readonly number[]).includes(Number(draft.statusCode))\n ? Number(draft.statusCode)\n : 302\n const notice = redirectSourceIsLivePage(host.screens as never, source)\n ? `${source} is a published page — the redirect takes precedence`\n : null\n return { ok: true, source, destination, statusCode, kind, notice }\n}\n\n/** Rules a check reads, past the page's 200-rule window, so a duplicate or loop beyond it is still caught. */\nconst RULES_WINDOW = 500\n\n/**\n * `POST /api/redirects/check`: runs {@link checkRedirectSave} for a member\n * who may publish on the site (the role the Firestore rules gate redirect\n * writes on). It reads and answers; it writes nothing, so the save itself\n * stays the same write the page makes, under the same rules.\n */\nexport const redirectCheckHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : ''\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n const body = typeof req.body === 'string' ? JSON.parse(req.body || '{}') : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n if (!hostId || /^__.*__$/.test(hostId) || hostId.includes('/')) return res.status(400).json({ error: 'Missing hostId' })\n const draft: RedirectSaveDraft = {\n id: typeof body.id === 'string' && body.id ? body.id : undefined,\n kind: typeof body.kind === 'string' ? body.kind : undefined,\n source: String(body.source ?? '').slice(0, 2000),\n destination: String(body.destination ?? '').slice(0, 2000),\n statusCode: Number(body.statusCode),\n }\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const hostRef = firebaseAdmin.app().firestore().collection('hosts').doc(hostId)\n const host = await hostRef.get()\n if (!host.exists) return res.status(404).json({ error: 'Unknown site' })\n // \"Publish site content\" (`site.publish`, AGL-4047), as the rules ask it of a redirect.\n if (!holdsSiteKey(host, decoded.uid, 'site.publish')) {\n return res.status(403).json({ error: siteKeyRefusal('site.publish') })\n }\n const snapshot = await hostRef.collection('redirects').limit(RULES_WINDOW).get()\n const rules = snapshot.docs.map((doc: { id: string; data: () => Record<string, unknown> }) => ({ $id: doc.id, ...doc.data() }))\n return res.status(200).json(checkRedirectSave(draft, host.data() ?? {}, rules))\n } catch (error) {\n console.error('[redirects/check]', error)\n return res.status(500).json({ error: 'The redirect could not be checked' })\n }\n}\n"],"names":["holdsSiteKey","siteKeyRefusal","firebaseAdmin","TENANT_APEX","findDuplicateRedirect","isSelfRedirect","normalizeRedirectDestination","normalizeRedirectSource","redirectSourceIsLivePage","REDIRECT_STATUS_CODES","validateRedirectRule","walkRedirectChain","checkRedirectSave","draft","host","rules","kind","problem","source","destination","ownDomains","cname","subdomain","ok","trim","live","filter","rule","deletedAt","$id","id","loop","statusCode","includes","Number","notice","screens","RULES_WINDOW","redirectCheckHandler","req","res","body","method","status","json","error","authorization","String","headers","idToken","startsWith","slice","length","JSON","parse","hostId","test","undefined","decoded","app","auth","verifyIdToken","hostRef","firestore","collection","doc","get","exists","uid","snapshot","limit","docs","map","data","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,YAAY,EAAEC,cAAc,QAAQ,0CAAyC;AACtF,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,WAAW,QAAQ,qCAAoC;AAChE,SACEC,qBAAqB,EACrBC,cAAc,EACdC,4BAA4B,EAC5BC,uBAAuB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C"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/redirects/src/lib/server/redirect-check.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { holdsSiteKey, siteKeyRefusal } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { readAllRedirectRules } from './read-redirect-rules'\nimport { TENANT_APEX } from '@aglyn/aglyn/app-utils/tenant-apex'\nimport {\n findDuplicateRedirect,\n isSelfRedirect,\n normalizeRedirectDestination,\n normalizeRedirectSource,\n redirectSourceIsLivePage,\n REDIRECT_STATUS_CODES,\n validateRedirectRule,\n walkRedirectChain,\n} from '../model/redirects'\n\n/** What a save is asked to write. */\nexport interface RedirectSaveDraft {\n /** The rule being edited; absent for a new rule. */\n id?: string\n kind?: string\n source: string\n destination: string\n statusCode?: number\n}\n\n/** The answer: the page's refusal in its own words, or the rule as the page would store it. */\nexport type RedirectSaveCheck =\n | { ok: false; problem: string }\n | { ok: true; source: string; destination: string; statusCode: number; kind: string; notice: string | null }\n\ntype Rule = { $id: string; source?: string; destination?: string; kind?: string; deletedAt?: unknown }\n\n/**\n * The Redirects page's save checks, in its order and its words\n * (`redirects-console-page.tsx` `handleSave`): the shared rule validation\n * (match mode, from-path or pattern, destination, another company's address),\n * a path redirected to itself, a duplicate rule, a chain that loops back, and\n * the published-page notice that warns without refusing. One source of truth\n * for every client that saves a rule: the native apps ask it here rather than\n * carry their own copy of the phishing screen and the pattern engine.\n */\nexport function checkRedirectSave(\n draft: RedirectSaveDraft,\n host: { cname?: unknown; subdomain?: unknown; screens?: unknown },\n rules: readonly Rule[],\n): RedirectSaveCheck {\n const kind = draft.kind || 'exact'\n const problem = validateRedirectRule(\n { kind, source: draft.source, destination: draft.destination },\n {\n ownDomains: [\n typeof host.cname === 'string' ? host.cname : null,\n typeof host.subdomain === 'string' && host.subdomain ? `${host.subdomain}.${TENANT_APEX}` : null,\n ],\n },\n )\n if (problem) return { ok: false, problem }\n const source = kind === 'regex' ? draft.source.trim() : (normalizeRedirectSource(draft.source) as string)\n const destination = normalizeRedirectDestination(draft.destination) as string\n if (kind !== 'regex' && isSelfRedirect({ source, destination })) {\n return { ok: false, problem: 'That would redirect the path to itself' }\n }\n const live = rules.filter((rule) => !rule.deletedAt)\n if (findDuplicateRedirect(live as never, { $id: draft.id, source, kind })) {\n return { ok: false, problem: `A rule for ${source} already exists` }\n }\n if (walkRedirectChain(live as never, { $id: draft.id, source, destination }).loop) {\n return { ok: false, problem: 'That destination chains back to this rule — a redirect loop' }\n }\n const statusCode = (REDIRECT_STATUS_CODES as readonly number[]).includes(Number(draft.statusCode))\n ? Number(draft.statusCode)\n : 302\n const notice = redirectSourceIsLivePage(host.screens as never, source)\n ? `${source} is a published page — the redirect takes precedence`\n : null\n return { ok: true, source, destination, statusCode, kind, notice }\n}\n\n/**\n * `POST /api/redirects/check`: runs {@link checkRedirectSave} for a member\n * who may publish on the site (the role the Firestore rules gate redirect\n * writes on). It reads and answers; it writes nothing, so the save itself\n * stays the same write the page makes, under the same rules.\n */\nexport const redirectCheckHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : ''\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n const body = typeof req.body === 'string' ? JSON.parse(req.body || '{}') : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n if (!hostId || /^__.*__$/.test(hostId) || hostId.includes('/')) return res.status(400).json({ error: 'Missing hostId' })\n const draft: RedirectSaveDraft = {\n id: typeof body.id === 'string' && body.id ? body.id : undefined,\n kind: typeof body.kind === 'string' ? body.kind : undefined,\n source: String(body.source ?? '').slice(0, 2000),\n destination: String(body.destination ?? '').slice(0, 2000),\n statusCode: Number(body.statusCode),\n }\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const hostRef = firebaseAdmin.app().firestore().collection('hosts').doc(hostId)\n const host = await hostRef.get()\n if (!host.exists) return res.status(404).json({ error: 'Unknown site' })\n // \"Publish site content\" (`site.publish`, AGL-4047), as the rules ask it of a redirect.\n if (!holdsSiteKey(host, decoded.uid, 'site.publish')) {\n return res.status(403).json({ error: siteKeyRefusal('site.publish') })\n }\n // Every rule, past the page's 200-rule window, so a duplicate or loop anywhere is caught (AGL-4247).\n const docs = await readAllRedirectRules(hostRef.collection('redirects'))\n const rules = docs.map((doc: { id: string; data: () => Record<string, unknown> }) => ({ $id: doc.id, ...doc.data() }))\n return res.status(200).json(checkRedirectSave(draft, host.data() ?? {}, rules))\n } catch (error) {\n console.error('[redirects/check]', error)\n return res.status(500).json({ error: 'The redirect could not be checked' })\n }\n}\n"],"names":["holdsSiteKey","siteKeyRefusal","firebaseAdmin","readAllRedirectRules","TENANT_APEX","findDuplicateRedirect","isSelfRedirect","normalizeRedirectDestination","normalizeRedirectSource","redirectSourceIsLivePage","REDIRECT_STATUS_CODES","validateRedirectRule","walkRedirectChain","checkRedirectSave","draft","host","rules","kind","problem","source","destination","ownDomains","cname","subdomain","ok","trim","live","filter","rule","deletedAt","$id","id","loop","statusCode","includes","Number","notice","screens","redirectCheckHandler","req","res","body","method","status","json","error","authorization","String","headers","idToken","startsWith","slice","length","JSON","parse","hostId","test","undefined","decoded","app","auth","verifyIdToken","hostRef","firestore","collection","doc","get","exists","uid","docs","map","data","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;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GAAGC;IAC1E,EAAE,OAAO6B,OAAO;QACd2B,QAAQ3B,KAAK,CAAC,qBAAqBA;QACnC,OAAOL,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAoC;IAC3E;AACF,EAAC"}
@@ -20,6 +20,7 @@ import { analyticsDayExpiresAt, firebaseAdmin, getOrgForHost, reviewSiteRedirect
20
20
  import { PUBLISHED_SITE_DATA_TTL_SECONDS, tenantDataTag, withRenderCache } from "@aglyn/tenant-data-admin/render-cache";
21
21
  import { boundedAwait } from "@aglyn/shared-util-http/bounded-await";
22
22
  import { FieldValue } from "firebase-admin/firestore";
23
+ import { readAllRedirectRules } from "./read-redirect-rules.js";
23
24
  /**
24
25
  * How long a render waits on the phishing review of an off-site rule before
25
26
  * treating the rule as held for this request (AGL-3565).
@@ -38,9 +39,14 @@ import { FieldValue } from "firebase-admin/firestore";
38
39
  * drops that path's cached HTML — that call is what keeps the manager's
39
40
  * "live within ~30 seconds" true, not this TTL.
40
41
  */ const REDIRECT_RULES_TTL_SECONDS = PUBLISHED_SITE_DATA_TTL_SECONDS;
41
- async function readEnabledRules(hostId) {
42
- const rules = await firebaseAdmin.app().firestore().collection('hosts').doc(hostId).collection('redirects').where('enabled', '==', true).limit(100).get();
43
- return rules.docs.map((doc)=>_extends({}, doc.data(), {
42
+ /**
43
+ * Every enabled rule, never a window of them (AGL-4247): a `limit(100)` here
44
+ * left a site's 101st rule and on silently unenforced.
45
+ */ async function readEnabledRules(hostId) {
46
+ const docs = await readAllRedirectRules(firebaseAdmin.app().firestore().collection('hosts').doc(hostId).collection('redirects'), {
47
+ enabledOnly: true
48
+ });
49
+ return docs.map((doc)=>_extends({}, doc.data(), {
44
50
  $id: doc.id
45
51
  }));
46
52
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/redirects/src/lib/server/resolve-redirect.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { checkEntitlement } from '@aglyn/aglyn/server'\nimport {\n type HostRedirect,\n isExternalRedirectDestination,\n matchRedirect,\n normalizeRedirectSource,\n redirectHitKey,\n} from '../model/redirects'\nimport {\n analyticsDayExpiresAt,\n firebaseAdmin,\n getOrgForHost,\n reviewSiteRedirect,\n} from '@aglyn/tenant-data-admin'\nimport {\n PUBLISHED_SITE_DATA_TTL_SECONDS,\n tenantDataTag,\n withRenderCache,\n} from '@aglyn/tenant-data-admin/render-cache'\nimport { boundedAwait } from '@aglyn/shared-util-http/bounded-await'\nimport { FieldValue } from 'firebase-admin/firestore'\n\n/**\n * How long a render waits on the phishing review of an off-site rule before\n * treating the rule as held for this request (AGL-3565).\n */\nconst REDIRECT_REVIEW_DEADLINE_MS = 5_000\n\n/**\n * One of three per-render reads AGL-1302 left uncached (AGL-1440).\n *\n * This query runs before route resolution on every render of every path, and\n * Firestore bills a minimum of one read for a query returning nothing — so a\n * site that has never written a rule still paid for asking, forever. The rules\n * are pure host-scoped published config: `revalidateTag(tenant-data:{hostId})`\n * busts them, and the shared hour-long TTL is only the backstop for a write\n * that never announces itself. Rule edits DO announce themselves: the\n * console's redirect manager posts `/api/screens/revalidate` with the rule's\n * source path after every save, toggle and delete, which busts the tag and\n * drops that path's cached HTML — that call is what keeps the manager's\n * \"live within ~30 seconds\" true, not this TTL.\n */\nconst REDIRECT_RULES_TTL_SECONDS = PUBLISHED_SITE_DATA_TTL_SECONDS\n\n/** One enabled rule, flattened to the plain data the matcher reads. */\ntype StoredRedirect = HostRedirect & { $id: string }\n\nasync function readEnabledRules(hostId: string): Promise<StoredRedirect[]> {\n const rules = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('redirects')\n .where('enabled', '==', true)\n .limit(100)\n .get()\n return rules.docs.map((doc) => ({\n ...(doc.data() as HostRedirect),\n $id: doc.id,\n }))\n}\n\nexport interface ResolvedRedirect {\n destination: string\n statusCode: 301 | 302 | 307 | 308\n}\n\n\n/**\n * Redirect enforcement (AGL-155), Option A per the issue: rules apply in\n * `getStaticProps` before route resolution, with a low revalidate on the\n * redirect response. Trade-offs, documented: rule edits take effect on\n * the next revalidation (≤30s), and hit counts are SAMPLED — cached\n * redirect responses never re-execute code, so each count represents \"at\n * least one hit in a revalidation window\", not per-request accuracy.\n * Middleware-accurate counting stays open as a later upgrade.\n *\n * Paid gating: when the host has enabled rules but the owning org's\n * plan lacks the `redirects` flag (downgrade with leftover rules), the\n * rules stop firing — the org read only happens when rules exist.\n * Loop guard: self-redirects never execute even if stored (console\n * validation and this floor can disagree; both refuse).\n * Phishing screen: a rule that leaves the site fires only once\n * `reviewSiteRedirect` answers `serve` — a destination that wears a brand is\n * held for every workspace, a lure path sent off the site for a workspace in\n * its first fortnight (AGL-3447).\n */\nexport async function resolveRedirect(\n host: { $id: string } & Record<string, unknown>,\n requestPath: string,\n): Promise<ResolvedRedirect | null> {\n try {\n const source = normalizeRedirectSource(\n requestPath === '/' || requestPath === '' ? '/' : `/${requestPath}`,\n )\n if (!source) return null\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(host.$id)\n // Cached per host, never per path (AGL-1440): the rule set is the same for\n // every URL on the site, so a path in the key would mint one entry per\n // route and cache nothing.\n const ruleList = await withRenderCache({\n key: ['redirect-rules', host.$id],\n revalidate: REDIRECT_RULES_TTL_SECONDS,\n tags: [tenantDataTag(host.$id)],\n read: () => readEnabledRules(host.$id),\n })\n if (!ruleList.length) return null\n\n // v2 matcher (AGL-375): exact/prefix/regex in priority order, capture\n // substitution, self-redirect floor. Run per request — it depends on the\n // path, which the cache key deliberately does not carry.\n const matched = matchRedirect(ruleList, source)\n if (!matched) return null\n const matchId = ruleList[matched.index]?.$id\n if (!matchId) return null\n\n // Paid gate — only paid orgs' rules fire (dark-launch orgs pass).\n //\n // Deliberately OUTSIDE the cache above. A cached entitlement would keep a\n // downgraded org's leftover rules redirecting for the life of the entry,\n // which on this code path means taking pages off the internet on the\n // strength of a plan the org no longer has.\n const owner = await getOrgForHost(host.$id)\n if (!checkEntitlement(owner?.org as any, 'redirects')) {\n return null\n }\n\n // The phishing screen (AGL-3447), for a rule that sends visitors OFF the\n // site: a page whose one call to action fires on arrival. A held rule does\n // not fire and is not counted; the request resolves as if it had no rule.\n // Outside the cache, like the paid gate: a staff decision takes effect on\n // the next request, not at the end of an hour.\n //\n // The review asks Google Web Risk and, for a rule it holds, files the hold\n // and tells staff — all inside this page render. It answers within a\n // deadline or the rule is treated as held, as the review itself fails\n // closed; the review carries on behind the page, so the next request\n // reads its decision (AGL-3565).\n if (isExternalRedirectDestination(matched.destination)) {\n const review = await boundedAwait(\n reviewSiteRedirect({\n hostId: host.$id,\n ruleId: matchId,\n source: ruleList[matched.index].source,\n destination: matched.destination,\n // The resolved host doc, when the hook handed one over; read otherwise.\n host: typeof host['subdomain'] === 'string' ? host : undefined,\n org: (owner?.org as Record<string, unknown> | undefined) ?? null,\n orgId: owner?.orgId ?? null,\n }),\n REDIRECT_REVIEW_DEADLINE_MS,\n null,\n 'redirects.site-redirect-review',\n )\n if (review?.outcome !== 'serve') return null\n }\n\n // Sampled hit recording (fire-and-forget): day-doc counter + recency\n // stamp for the manager (AGL-157). Also outside the cache — a cached\n // function would stop counting altogether rather than counting less often.\n // The rule's ref is rebuilt from its id, because a `DocumentReference`\n // cannot survive the cache's JSON round trip.\n const day = new Date().toISOString().slice(0, 10)\n void hostRef\n .collection('analytics')\n .doc(day)\n .set(\n {\n redirects: { [redirectHitKey(matchId)]: FieldValue.increment(1) },\n // Retention (AGL-1844): every writer of a day doc stamps the\n // day-anchored expiry the TTL policy sweeps on.\n expiresAt: analyticsDayExpiresAt(day),\n },\n { merge: true },\n )\n .catch(() => undefined)\n void hostRef\n .collection('redirects')\n .doc(matchId)\n .set({ lastHitAt: FieldValue.serverTimestamp() }, { merge: true })\n .catch(() => undefined)\n\n return { destination: matched.destination, statusCode: matched.statusCode }\n } catch (error) {\n console.error('resolveRedirect failed', host.$id, requestPath, error)\n return null\n }\n}\n\nexport default resolveRedirect\n"],"names":["checkEntitlement","isExternalRedirectDestination","matchRedirect","normalizeRedirectSource","redirectHitKey","analyticsDayExpiresAt","firebaseAdmin","getOrgForHost","reviewSiteRedirect","PUBLISHED_SITE_DATA_TTL_SECONDS","tenantDataTag","withRenderCache","boundedAwait","FieldValue","REDIRECT_REVIEW_DEADLINE_MS","REDIRECT_RULES_TTL_SECONDS","readEnabledRules","hostId","rules","app","firestore","collection","doc","where","limit","get","docs","map","data","$id","id","resolveRedirect","host","requestPath","ruleList","source","hostRef","key","revalidate","tags","read","length","matched","matchId","index","owner","org","destination","review","ruleId","undefined","orgId","outcome","day","Date","toISOString","slice","set","redirects","increment","expiresAt","merge","catch","lastHitAt","serverTimestamp","statusCode","error","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,QAAQ,sBAAqB;AACtD,SAEEC,6BAA6B,EAC7BC,aAAa,EACbC,uBAAuB,EACvBC,cAAc,QACT,wBAAoB;AAC3B,SACEC,qBAAqB,EACrBC,aAAa,EACbC,aAAa,EACbC,kBAAkB,QACb,2BAA0B;AACjC,SACEC,+BAA+B,EAC/BC,aAAa,EACbC,eAAe,QACV,wCAAuC;AAC9C,SAASC,YAAY,QAAQ,wCAAuC;AACpE,SAASC,UAAU,QAAQ,2BAA0B;AAErD;;;CAGC,GACD,MAAMC,8BAA8B;AAEpC;;;;;;;;;;;;;CAaC,GACD,MAAMC,6BAA6BN;AAKnC,eAAeO,iBAAiBC,MAAc;IAC5C,MAAMC,QAAQ,MAAMZ,cACjBa,GA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YAAEM,WAAWlD,WAAWmD,eAAe;QAAG,GAAG;YAAEH,OAAO;QAAK,GAC/DC,KAAK,CAAC,IAAMZ;QAEf,OAAO;YAAEH,aAAaL,QAAQK,WAAW;YAAEkB,YAAYvB,QAAQuB,UAAU;QAAC;IAC5E,EAAE,OAAOC,OAAO;QACdC,QAAQD,KAAK,CAAC,0BAA0BlC,KAAKH,GAAG,EAAEI,aAAaiC;QAC/D,OAAO;IACT;AACF;AAEA,eAAenC,gBAAe"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/redirects/src/lib/server/resolve-redirect.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { checkEntitlement } from '@aglyn/aglyn/server'\nimport {\n type HostRedirect,\n isExternalRedirectDestination,\n matchRedirect,\n normalizeRedirectSource,\n redirectHitKey,\n} from '../model/redirects'\nimport {\n analyticsDayExpiresAt,\n firebaseAdmin,\n getOrgForHost,\n reviewSiteRedirect,\n} from '@aglyn/tenant-data-admin'\nimport {\n PUBLISHED_SITE_DATA_TTL_SECONDS,\n tenantDataTag,\n withRenderCache,\n} from '@aglyn/tenant-data-admin/render-cache'\nimport { boundedAwait } from '@aglyn/shared-util-http/bounded-await'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { readAllRedirectRules } from './read-redirect-rules'\n\n/**\n * How long a render waits on the phishing review of an off-site rule before\n * treating the rule as held for this request (AGL-3565).\n */\nconst REDIRECT_REVIEW_DEADLINE_MS = 5_000\n\n/**\n * One of three per-render reads AGL-1302 left uncached (AGL-1440).\n *\n * This query runs before route resolution on every render of every path, and\n * Firestore bills a minimum of one read for a query returning nothing — so a\n * site that has never written a rule still paid for asking, forever. The rules\n * are pure host-scoped published config: `revalidateTag(tenant-data:{hostId})`\n * busts them, and the shared hour-long TTL is only the backstop for a write\n * that never announces itself. Rule edits DO announce themselves: the\n * console's redirect manager posts `/api/screens/revalidate` with the rule's\n * source path after every save, toggle and delete, which busts the tag and\n * drops that path's cached HTML — that call is what keeps the manager's\n * \"live within ~30 seconds\" true, not this TTL.\n */\nconst REDIRECT_RULES_TTL_SECONDS = PUBLISHED_SITE_DATA_TTL_SECONDS\n\n/** One enabled rule, flattened to the plain data the matcher reads. */\ntype StoredRedirect = HostRedirect & { $id: string }\n\n/**\n * Every enabled rule, never a window of them (AGL-4247): a `limit(100)` here\n * left a site's 101st rule and on silently unenforced.\n */\nasync function readEnabledRules(hostId: string): Promise<StoredRedirect[]> {\n const docs = await readAllRedirectRules(\n firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('redirects'),\n { enabledOnly: true },\n )\n return docs.map((doc) => ({\n ...(doc.data() as HostRedirect),\n $id: doc.id,\n }))\n}\n\nexport interface ResolvedRedirect {\n destination: string\n statusCode: 301 | 302 | 307 | 308\n}\n\n\n/**\n * Redirect enforcement (AGL-155), Option A per the issue: rules apply in\n * `getStaticProps` before route resolution, with a low revalidate on the\n * redirect response. Trade-offs, documented: rule edits take effect on\n * the next revalidation (≤30s), and hit counts are SAMPLED — cached\n * redirect responses never re-execute code, so each count represents \"at\n * least one hit in a revalidation window\", not per-request accuracy.\n * Middleware-accurate counting stays open as a later upgrade.\n *\n * Paid gating: when the host has enabled rules but the owning org's\n * plan lacks the `redirects` flag (downgrade with leftover rules), the\n * rules stop firing — the org read only happens when rules exist.\n * Loop guard: self-redirects never execute even if stored (console\n * validation and this floor can disagree; both refuse).\n * Phishing screen: a rule that leaves the site fires only once\n * `reviewSiteRedirect` answers `serve` — a destination that wears a brand is\n * held for every workspace, a lure path sent off the site for a workspace in\n * its first fortnight (AGL-3447).\n */\nexport async function resolveRedirect(\n host: { $id: string } & Record<string, unknown>,\n requestPath: string,\n): Promise<ResolvedRedirect | null> {\n try {\n const source = normalizeRedirectSource(\n requestPath === '/' || requestPath === '' ? '/' : `/${requestPath}`,\n )\n if (!source) return null\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(host.$id)\n // Cached per host, never per path (AGL-1440): the rule set is the same for\n // every URL on the site, so a path in the key would mint one entry per\n // route and cache nothing.\n const ruleList = await withRenderCache({\n key: ['redirect-rules', host.$id],\n revalidate: REDIRECT_RULES_TTL_SECONDS,\n tags: [tenantDataTag(host.$id)],\n read: () => readEnabledRules(host.$id),\n })\n if (!ruleList.length) return null\n\n // v2 matcher (AGL-375): exact/prefix/regex in priority order, capture\n // substitution, self-redirect floor. Run per request — it depends on the\n // path, which the cache key deliberately does not carry.\n const matched = matchRedirect(ruleList, source)\n if (!matched) return null\n const matchId = ruleList[matched.index]?.$id\n if (!matchId) return null\n\n // Paid gate — only paid orgs' rules fire (dark-launch orgs pass).\n //\n // Deliberately OUTSIDE the cache above. A cached entitlement would keep a\n // downgraded org's leftover rules redirecting for the life of the entry,\n // which on this code path means taking pages off the internet on the\n // strength of a plan the org no longer has.\n const owner = await getOrgForHost(host.$id)\n if (!checkEntitlement(owner?.org as any, 'redirects')) {\n return null\n }\n\n // The phishing screen (AGL-3447), for a rule that sends visitors OFF the\n // site: a page whose one call to action fires on arrival. A held rule does\n // not fire and is not counted; the request resolves as if it had no rule.\n // Outside the cache, like the paid gate: a staff decision takes effect on\n // the next request, not at the end of an hour.\n //\n // The review asks Google Web Risk and, for a rule it holds, files the hold\n // and tells staff — all inside this page render. It answers within a\n // deadline or the rule is treated as held, as the review itself fails\n // closed; the review carries on behind the page, so the next request\n // reads its decision (AGL-3565).\n if (isExternalRedirectDestination(matched.destination)) {\n const review = await boundedAwait(\n reviewSiteRedirect({\n hostId: host.$id,\n ruleId: matchId,\n source: ruleList[matched.index].source,\n destination: matched.destination,\n // The resolved host doc, when the hook handed one over; read otherwise.\n host: typeof host['subdomain'] === 'string' ? host : undefined,\n org: (owner?.org as Record<string, unknown> | undefined) ?? null,\n orgId: owner?.orgId ?? null,\n }),\n REDIRECT_REVIEW_DEADLINE_MS,\n null,\n 'redirects.site-redirect-review',\n )\n if (review?.outcome !== 'serve') return null\n }\n\n // Sampled hit recording (fire-and-forget): day-doc counter + recency\n // stamp for the manager (AGL-157). Also outside the cache — a cached\n // function would stop counting altogether rather than counting less often.\n // The rule's ref is rebuilt from its id, because a `DocumentReference`\n // cannot survive the cache's JSON round trip.\n const day = new Date().toISOString().slice(0, 10)\n void hostRef\n .collection('analytics')\n .doc(day)\n .set(\n {\n redirects: { [redirectHitKey(matchId)]: FieldValue.increment(1) },\n // Retention (AGL-1844): every writer of a day doc stamps the\n // day-anchored expiry the TTL policy sweeps on.\n expiresAt: analyticsDayExpiresAt(day),\n },\n { merge: true },\n )\n .catch(() => undefined)\n void hostRef\n .collection('redirects')\n .doc(matchId)\n .set({ lastHitAt: FieldValue.serverTimestamp() }, { merge: true })\n .catch(() => undefined)\n\n return { destination: matched.destination, statusCode: matched.statusCode }\n } catch (error) {\n console.error('resolveRedirect failed', host.$id, requestPath, error)\n return null\n }\n}\n\nexport default resolveRedirect\n"],"names":["checkEntitlement","isExternalRedirectDestination","matchRedirect","normalizeRedirectSource","redirectHitKey","analyticsDayExpiresAt","firebaseAdmin","getOrgForHost","reviewSiteRedirect","PUBLISHED_SITE_DATA_TTL_SECONDS","tenantDataTag","withRenderCache","boundedAwait","FieldValue","readAllRedirectRules","REDIRECT_REVIEW_DEADLINE_MS","REDIRECT_RULES_TTL_SECONDS","readEnabledRules","hostId","docs","app","firestore","collection","doc","enabledOnly","map","data","$id","id","resolveRedirect","host","requestPath","ruleList","source","hostRef","key","revalidate","tags","read","length","matched","matchId","index","owner","org","destination","review","ruleId","undefined","orgId","outcome","day","Date","toISOString","slice","set","redirects","increment","expiresAt","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