@aglyn/tenant-data-admin 1.0.0-beta.216 → 1.0.0-beta.218

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.
@@ -17,7 +17,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
17
17
  */ import { isPluginNetworkAllowed, PLUGIN_FETCH_MAX_BODY_BYTES } from "@aglyn/aglyn/server";
18
18
  import { lookup } from "node:dns/promises";
19
19
  import { isIPv4, isIPv6 } from "net";
20
- import { Agent } from "undici";
20
+ import { Agent, Dispatcher1Wrapper } from "undici";
21
21
  import { firebaseAdmin } from "./firebase-admin.js";
22
22
  const FETCH_TIMEOUT_MS = 8000;
23
23
  /**
@@ -99,14 +99,25 @@ const FETCH_TIMEOUT_MS = 8000;
99
99
  * is a **declared direct dependency** for exactly this reason: it used to
100
100
  * arrive only as a transitive of the dev-only `jsdom`, which meant a
101
101
  * `--omit=dev` install had no `undici` at all and a jsdom bump silently
102
- * re-versioned the HTTP client behind a production security control. undici 8
103
- * rejects this `lookup` shape with `UND_ERR_INVALID_ARG` on every request —
104
- * fail-closed, but the plugin-fetch route stops working outright. The spec
105
- * drives a real request through this dispatcher so that break is a red test,
106
- * not a production discovery.
102
+ * re-versioned the HTTP client behind a production security control. The spec
103
+ * drives a real request through this dispatcher so that a transport break is a
104
+ * red test, not a production discovery.
105
+ *
106
+ * ## Why the agent is wrapped
107
+ *
108
+ * The request goes through Node's BUILT-IN `fetch`, which is undici 7 inside
109
+ * Node 24 and speaks the v1 handler protocol. An undici 8 `Agent` speaks v2, so
110
+ * handing it to the built-in `fetch` bare fails every request with
111
+ * `InvalidArgumentError: invalid onRequestStart method` — fail-closed, but the
112
+ * plugin-fetch route stops working outright. `Dispatcher1Wrapper` is undici's
113
+ * own bridge for exactly that pairing, and it forwards `close()` to the agent.
114
+ *
115
+ * `allowH2: false` keeps the transport HTTP/1.1, which is what this pin was
116
+ * written and measured against; undici 8 turned HTTP/2 on by default.
107
117
  */ export function createPinnedDispatcher(pinnedIp) {
108
118
  const family = isIPv6(pinnedIp) ? 6 : 4;
109
- return new Agent({
119
+ return new Dispatcher1Wrapper(new Agent({
120
+ allowH2: false,
110
121
  connect: {
111
122
  lookup: (_host, options, cb)=>options && options.all ? cb(null, [
112
123
  {
@@ -115,7 +126,7 @@ const FETCH_TIMEOUT_MS = 8000;
115
126
  }
116
127
  ]) : cb(null, pinnedIp, family)
117
128
  }
118
- });
129
+ }));
119
130
  }
120
131
  /**
121
132
  * Host-mediated plugin fetch (AGL-191). The sandboxed plugin can't reach
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/serve-plugin-fetch.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 {\n isPluginNetworkAllowed,\n PLUGIN_FETCH_MAX_BODY_BYTES,\n} from '@aglyn/aglyn/server'\nimport { lookup } from 'dns/promises'\nimport { isIPv4, isIPv6 } from 'net'\nimport type { NextApiRequest, NextApiResponse } from 'next'\nimport { Agent } from 'undici'\nimport { firebaseAdmin } from './firebase-admin'\n\nconst FETCH_TIMEOUT_MS = 8000\n/**\n * Redirect hops the proxy will follow, each one re-validated (AGL-1881).\n * Small on purpose: a legitimate API redirects once (http->https is refused\n * outright by the allowlist, so in practice this is a path or host alias).\n */\nconst MAX_REDIRECT_HOPS = 3\n/** The statuses `redirect: 'manual'` hands back instead of following. */\nconst REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308])\n\n/** True for loopback / private / link-local / CGNAT / ULA addresses. */\nfunction isPrivateIp(ip: string): boolean {\n if (isIPv4(ip)) {\n const [a, b] = ip.split('.').map(Number)\n if (a === 0 || a === 10 || a === 127) return true\n if (a === 169 && b === 254) return true // link-local + cloud metadata\n if (a === 172 && b >= 16 && b <= 31) return true\n if (a === 192 && b === 168) return true\n if (a === 100 && b >= 64 && b <= 127) return true // CGNAT\n // The ranges AGL-1881 found missing. None is routable on the public\n // internet, so refusing them costs a plugin nothing:\n if (a === 192 && b === 0) return true // 192.0.0.0/24 IETF protocol\n if (a === 198 && (b === 18 || b === 19)) return true // 198.18/15 benchmark\n if (a >= 224) return true // 224/4 multicast, 240/4 reserved, broadcast\n return false\n }\n if (isIPv6(ip)) {\n const low = ip.toLowerCase()\n if (low === '::1' || low === '::') return true\n if (low.startsWith('fc') || low.startsWith('fd')) return true // ULA\n // Link-local is fe80::/10 — fe80 through febf, not the fe80 prefix\n // alone (AGL-1881). `fec0::/10` site-local is deprecated but inside the\n // same span, so one test covers both.\n if (/^fe[89ab]/.test(low)) return true // link-local fe80::/10\n if (low.startsWith('::ffff:')) return isPrivateIp(low.slice(7)) // v4-mapped\n return false\n }\n return true // unparseable → refuse\n}\n\n/**\n * SSRF hardening (AGL-515): even an https, allowlisted origin can resolve to\n * an internal address (a plugin author pointing DNS at 127.0.0.1 / the cloud\n * metadata endpoint). Resolve the host and return a single validated PUBLIC\n * address to pin the connection to (null if any resolved address is private).\n * Pinning the exact IP the fetch connects to closes the DNS-rebinding TOCTOU —\n * the name can't re-resolve to an internal target between check and connect.\n */\nexport async function resolvePublicIp(hostname: string): Promise<string | null> {\n try {\n const addresses = await lookup(hostname, { all: true })\n if (!addresses.length) return null\n if (addresses.some((a) => isPrivateIp(a.address))) return null\n return addresses[0].address\n } catch {\n return null\n }\n}\n\n/**\n * Build the dispatcher that pins the socket to `pinnedIp` (AGL-515). A custom\n * `connect.lookup` forces the connection to the address `resolvePublicIp`\n * already validated, so the name can't be rebound to an internal target\n * between the check and the connect. TLS SNI / certificate validation still\n * use the original hostname, because only the address resolution is replaced.\n *\n * Exported so the transport itself is covered by a spec (AGL-2480). `undici`\n * is a **declared direct dependency** for exactly this reason: it used to\n * arrive only as a transitive of the dev-only `jsdom`, which meant a\n * `--omit=dev` install had no `undici` at all and a jsdom bump silently\n * re-versioned the HTTP client behind a production security control. undici 8\n * rejects this `lookup` shape with `UND_ERR_INVALID_ARG` on every request —\n * fail-closed, but the plugin-fetch route stops working outright. The spec\n * drives a real request through this dispatcher so that break is a red test,\n * not a production discovery.\n */\nexport function createPinnedDispatcher(pinnedIp: string): Agent {\n const family = isIPv6(pinnedIp) ? 6 : 4\n return new Agent({\n connect: {\n lookup: (_host, options, cb) =>\n options && options.all\n ? cb(null, [{ address: pinnedIp, family }])\n : cb(null, pinnedIp, family),\n },\n })\n}\n\n/**\n * Host-mediated plugin fetch (AGL-191). The sandboxed plugin can't reach\n * the network directly under a strict plugin-origin CSP, so `PluginFrame`\n * forwards a `fetch-request` here and the host proxies it. Mounted in BOTH\n * apps (console for the editor/preview, tenant for the published site) so\n * plugin fetches work wherever the plugin renders — hence public, no\n * admin auth: the security boundary is the ALLOWLIST, re-derived from the\n * host's server-side install record and never trusting the client's claim.\n * https-only, exact-origin, method/body/time capped, and no host\n * credentials are ever forwarded — a plugin can only reach origins it\n * declared at install (surfaced on the install screen).\n *\n * Abuse note: this uses platform egress to origins the plugin already\n * declared; a per-listing rate limit is a sensible follow-up.\n */\nexport async function servePluginFetch(\n req: NextApiRequest,\n res: NextApiResponse,\n): Promise<void> {\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST')\n res.status(405).json({ ok: false, status: 0, error: 'Method not allowed' })\n return\n }\n const body =\n typeof req.body === 'string' ? safeJson(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n const listingId = String(body.listingId ?? '')\n const url = String(body.url ?? '')\n const method = body.method === 'POST' ? 'POST' : 'GET'\n const requestBody =\n typeof body.body === 'string' ? (body.body as string) : undefined\n if (!hostId || !listingId || !url) {\n res.status(400).json({ ok: false, status: 0, error: 'Bad request' })\n return\n }\n if (requestBody && Buffer.byteLength(requestBody) > PLUGIN_FETCH_MAX_BODY_BYTES) {\n res.status(413).json({ ok: false, status: 0, error: 'Body too large' })\n return\n }\n\n try {\n const install = (\n await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('installs')\n .doc(listingId)\n .get()\n ).data() as { manifest?: { capabilities?: unknown } } | undefined\n if (!install?.manifest) {\n res.status(404).json({ ok: false, status: 0, error: 'Not installed' })\n return\n }\n if (\n !isPluginNetworkAllowed(\n url,\n (install.manifest as { capabilities?: any }).capabilities,\n )\n ) {\n res\n .status(403)\n .json({ ok: false, status: 0, error: 'URL not in allowlist' })\n return\n }\n // Follow redirects OURSELVES, re-validating every hop (AGL-1881).\n //\n // `fetch` defaults to `redirect: 'follow'`, and every control above runs\n // on the FIRST url only: the allowlist, the https-only check and the\n // pinned dispatcher. A declared, allowlisted, genuinely public origin\n // answering `302 Location: http://169.254.169.254/...` therefore reached\n // the cloud metadata service and returned its body to the caller — on an\n // unauthenticated route. The IP pin did not stop it: Node skips a custom\n // `connect.lookup` when the target is an IP literal, so the redirect\n // connected directly and the pinned lookup was consulted exactly once,\n // for the original hostname.\n //\n // `redirect: 'manual'` hands us each hop instead. Every one re-enters the\n // same two gates the first url passed — the manifest allowlist (which is\n // also what enforces https and the exact origin) and a fresh\n // `resolvePublicIp` with its own pinned dispatcher — so a redirect can\n // only ever reach somewhere the plugin could have named directly.\n let currentUrl = url\n let upstream: Response\n for (let hop = 0; ; hop++) {\n if (hop > MAX_REDIRECT_HOPS) {\n res\n .status(403)\n .json({ ok: false, status: 0, error: 'Too many redirects' })\n return\n }\n const pinnedIp = await resolvePublicIp(new URL(currentUrl).hostname)\n if (!pinnedIp) {\n res.status(403).json({\n ok: false,\n status: 0,\n error: 'URL resolves to a non-public address',\n })\n return\n }\n\n // Pin the socket to the address we just validated (AGL-515).\n const dispatcher = createPinnedDispatcher(pinnedIp)\n const controller = new AbortController()\n const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS)\n // `dispatcher` is an undici extension not in the DOM RequestInit type;\n // assigning to a variable first avoids the object-literal excess-property\n // check while still passing it through to the (undici) global fetch.\n const requestInit = {\n method,\n signal: controller.signal,\n dispatcher,\n redirect: 'manual' as const,\n headers: { Accept: 'application/json, text/*;q=0.9, */*;q=0.1' },\n ...(method === 'POST' && requestBody ? { body: requestBody } : {}),\n }\n try {\n upstream = await fetch(currentUrl, requestInit)\n } finally {\n clearTimeout(timeout)\n await dispatcher.close().catch(() => undefined)\n }\n\n if (!REDIRECT_STATUSES.has(upstream.status)) break\n\n const location = upstream.headers.get('location')\n if (!location) break // a redirect status with no target is just a body\n let nextUrl: string\n try {\n nextUrl = new URL(location, currentUrl).toString()\n } catch {\n res\n .status(403)\n .json({ ok: false, status: 0, error: 'Redirect target is not a URL' })\n return\n }\n if (\n !isPluginNetworkAllowed(\n nextUrl,\n (install.manifest as { capabilities?: any }).capabilities,\n )\n ) {\n res.status(403).json({\n ok: false,\n status: 0,\n error: 'Redirect target not in allowlist',\n })\n return\n }\n currentUrl = nextUrl\n }\n\n const text = await upstream.text()\n const clipped =\n Buffer.byteLength(text) > PLUGIN_FETCH_MAX_BODY_BYTES\n ? text.slice(0, PLUGIN_FETCH_MAX_BODY_BYTES)\n : text\n res.status(200).json({\n ok: upstream.ok,\n status: upstream.status,\n body: clipped,\n })\n } catch (error) {\n console.error('servePluginFetch failed', hostId, listingId, error)\n res.status(502).json({ ok: false, status: 0, error: 'Fetch failed' })\n }\n}\n\nfunction safeJson(value: string): Record<string, unknown> {\n try {\n return JSON.parse(value)\n } catch {\n return {}\n }\n}\n"],"names":["isPluginNetworkAllowed","PLUGIN_FETCH_MAX_BODY_BYTES","lookup","isIPv4","isIPv6","Agent","firebaseAdmin","FETCH_TIMEOUT_MS","MAX_REDIRECT_HOPS","REDIRECT_STATUSES","Set","isPrivateIp","ip","a","b","split","map","Number","low","toLowerCase","startsWith","test","slice","resolvePublicIp","hostname","addresses","all","length","some","address","createPinnedDispatcher","pinnedIp","family","connect","_host","options","cb","servePluginFetch","req","res","body","method","setHeader","status","json","ok","error","safeJson","hostId","String","listingId","url","requestBody","undefined","Buffer","byteLength","install","app","firestore","collection","doc","get","data","manifest","capabilities","currentUrl","upstream","hop","URL","dispatcher","controller","AbortController","timeout","setTimeout","abort","requestInit","signal","redirect","headers","Accept","fetch","clearTimeout","close","catch","has","location","nextUrl","toString","text","clipped","console","value","JSON","parse"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,sBAAsB,EACtBC,2BAA2B,QACtB,sBAAqB;AAC5B,SAASC,MAAM,QAAQ,oBAAc;AACrC,SAASC,MAAM,EAAEC,MAAM,QAAQ,MAAK;AAEpC,SAASC,KAAK,QAAQ,SAAQ;AAC9B,SAASC,aAAa,QAAQ,sBAAkB;AAEhD,MAAMC,mBAAmB;AACzB;;;;CAIC,GACD,MAAMC,oBAAoB;AAC1B,uEAAuE,GACvE,MAAMC,oBAAoB,IAAIC,IAAI;IAAC;IAAK;IAAK;IAAK;IAAK;CAAI;AAE3D,sEAAsE,GACtE,SAASC,YAAYC,EAAU;IAC7B,IAAIT,OAAOS,KAAK;QACd,MAAM,CAACC,GAAGC,EAAE,GAAGF,GAAGG,KAAK,CAAC,KAAKC,GAAG,CAACC;QACjC,IAAIJ,MAAM,KAAKA,MAAM,MAAMA,MAAM,KAAK,OAAO;QAC7C,IAAIA,MAAM,OAAOC,MAAM,KAAK,OAAO,KAAK,8BAA8B;;QACtE,IAAID,MAAM,OAAOC,KAAK,MAAMA,KAAK,IAAI,OAAO;QAC5C,IAAID,MAAM,OAAOC,MAAM,KAAK,OAAO;QACnC,IAAID,MAAM,OAAOC,KAAK,MAAMA,KAAK,KAAK,OAAO,KAAK,QAAQ;;QAC1D,oEAAoE;QACpE,qDAAqD;QACrD,IAAID,MAAM,OAAOC,MAAM,GAAG,OAAO,KAAK,6BAA6B;;QACnE,IA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C7B,IAAI;QACF,OAAOC,KAAKC,KAAK,CAACF;IACpB,EAAE,eAAM;QACN,OAAO,CAAC;IACV;AACF"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/serve-plugin-fetch.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 {\n isPluginNetworkAllowed,\n PLUGIN_FETCH_MAX_BODY_BYTES,\n} from '@aglyn/aglyn/server'\nimport { lookup } from 'dns/promises'\nimport { isIPv4, isIPv6 } from 'net'\nimport type { NextApiRequest, NextApiResponse } from 'next'\nimport { Agent, type Dispatcher, Dispatcher1Wrapper } from 'undici'\nimport { firebaseAdmin } from './firebase-admin'\n\nconst FETCH_TIMEOUT_MS = 8000\n/**\n * Redirect hops the proxy will follow, each one re-validated (AGL-1881).\n * Small on purpose: a legitimate API redirects once (http->https is refused\n * outright by the allowlist, so in practice this is a path or host alias).\n */\nconst MAX_REDIRECT_HOPS = 3\n/** The statuses `redirect: 'manual'` hands back instead of following. */\nconst REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308])\n\n/** True for loopback / private / link-local / CGNAT / ULA addresses. */\nfunction isPrivateIp(ip: string): boolean {\n if (isIPv4(ip)) {\n const [a, b] = ip.split('.').map(Number)\n if (a === 0 || a === 10 || a === 127) return true\n if (a === 169 && b === 254) return true // link-local + cloud metadata\n if (a === 172 && b >= 16 && b <= 31) return true\n if (a === 192 && b === 168) return true\n if (a === 100 && b >= 64 && b <= 127) return true // CGNAT\n // The ranges AGL-1881 found missing. None is routable on the public\n // internet, so refusing them costs a plugin nothing:\n if (a === 192 && b === 0) return true // 192.0.0.0/24 IETF protocol\n if (a === 198 && (b === 18 || b === 19)) return true // 198.18/15 benchmark\n if (a >= 224) return true // 224/4 multicast, 240/4 reserved, broadcast\n return false\n }\n if (isIPv6(ip)) {\n const low = ip.toLowerCase()\n if (low === '::1' || low === '::') return true\n if (low.startsWith('fc') || low.startsWith('fd')) return true // ULA\n // Link-local is fe80::/10 — fe80 through febf, not the fe80 prefix\n // alone (AGL-1881). `fec0::/10` site-local is deprecated but inside the\n // same span, so one test covers both.\n if (/^fe[89ab]/.test(low)) return true // link-local fe80::/10\n if (low.startsWith('::ffff:')) return isPrivateIp(low.slice(7)) // v4-mapped\n return false\n }\n return true // unparseable → refuse\n}\n\n/**\n * SSRF hardening (AGL-515): even an https, allowlisted origin can resolve to\n * an internal address (a plugin author pointing DNS at 127.0.0.1 / the cloud\n * metadata endpoint). Resolve the host and return a single validated PUBLIC\n * address to pin the connection to (null if any resolved address is private).\n * Pinning the exact IP the fetch connects to closes the DNS-rebinding TOCTOU —\n * the name can't re-resolve to an internal target between check and connect.\n */\nexport async function resolvePublicIp(hostname: string): Promise<string | null> {\n try {\n const addresses = await lookup(hostname, { all: true })\n if (!addresses.length) return null\n if (addresses.some((a) => isPrivateIp(a.address))) return null\n return addresses[0].address\n } catch {\n return null\n }\n}\n\n/**\n * Build the dispatcher that pins the socket to `pinnedIp` (AGL-515). A custom\n * `connect.lookup` forces the connection to the address `resolvePublicIp`\n * already validated, so the name can't be rebound to an internal target\n * between the check and the connect. TLS SNI / certificate validation still\n * use the original hostname, because only the address resolution is replaced.\n *\n * Exported so the transport itself is covered by a spec (AGL-2480). `undici`\n * is a **declared direct dependency** for exactly this reason: it used to\n * arrive only as a transitive of the dev-only `jsdom`, which meant a\n * `--omit=dev` install had no `undici` at all and a jsdom bump silently\n * re-versioned the HTTP client behind a production security control. The spec\n * drives a real request through this dispatcher so that a transport break is a\n * red test, not a production discovery.\n *\n * ## Why the agent is wrapped\n *\n * The request goes through Node's BUILT-IN `fetch`, which is undici 7 inside\n * Node 24 and speaks the v1 handler protocol. An undici 8 `Agent` speaks v2, so\n * handing it to the built-in `fetch` bare fails every request with\n * `InvalidArgumentError: invalid onRequestStart method` — fail-closed, but the\n * plugin-fetch route stops working outright. `Dispatcher1Wrapper` is undici's\n * own bridge for exactly that pairing, and it forwards `close()` to the agent.\n *\n * `allowH2: false` keeps the transport HTTP/1.1, which is what this pin was\n * written and measured against; undici 8 turned HTTP/2 on by default.\n */\nexport function createPinnedDispatcher(pinnedIp: string): Dispatcher {\n const family = isIPv6(pinnedIp) ? 6 : 4\n return new Dispatcher1Wrapper(\n new Agent({\n allowH2: false,\n connect: {\n lookup: (_host, options, cb) =>\n options && options.all\n ? cb(null, [{ address: pinnedIp, family }])\n : cb(null, pinnedIp, family),\n },\n }),\n )\n}\n\n/**\n * Host-mediated plugin fetch (AGL-191). The sandboxed plugin can't reach\n * the network directly under a strict plugin-origin CSP, so `PluginFrame`\n * forwards a `fetch-request` here and the host proxies it. Mounted in BOTH\n * apps (console for the editor/preview, tenant for the published site) so\n * plugin fetches work wherever the plugin renders — hence public, no\n * admin auth: the security boundary is the ALLOWLIST, re-derived from the\n * host's server-side install record and never trusting the client's claim.\n * https-only, exact-origin, method/body/time capped, and no host\n * credentials are ever forwarded — a plugin can only reach origins it\n * declared at install (surfaced on the install screen).\n *\n * Abuse note: this uses platform egress to origins the plugin already\n * declared; a per-listing rate limit is a sensible follow-up.\n */\nexport async function servePluginFetch(\n req: NextApiRequest,\n res: NextApiResponse,\n): Promise<void> {\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST')\n res.status(405).json({ ok: false, status: 0, error: 'Method not allowed' })\n return\n }\n const body =\n typeof req.body === 'string' ? safeJson(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n const listingId = String(body.listingId ?? '')\n const url = String(body.url ?? '')\n const method = body.method === 'POST' ? 'POST' : 'GET'\n const requestBody =\n typeof body.body === 'string' ? (body.body as string) : undefined\n if (!hostId || !listingId || !url) {\n res.status(400).json({ ok: false, status: 0, error: 'Bad request' })\n return\n }\n if (requestBody && Buffer.byteLength(requestBody) > PLUGIN_FETCH_MAX_BODY_BYTES) {\n res.status(413).json({ ok: false, status: 0, error: 'Body too large' })\n return\n }\n\n try {\n const install = (\n await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('installs')\n .doc(listingId)\n .get()\n ).data() as { manifest?: { capabilities?: unknown } } | undefined\n if (!install?.manifest) {\n res.status(404).json({ ok: false, status: 0, error: 'Not installed' })\n return\n }\n if (\n !isPluginNetworkAllowed(\n url,\n (install.manifest as { capabilities?: any }).capabilities,\n )\n ) {\n res\n .status(403)\n .json({ ok: false, status: 0, error: 'URL not in allowlist' })\n return\n }\n // Follow redirects OURSELVES, re-validating every hop (AGL-1881).\n //\n // `fetch` defaults to `redirect: 'follow'`, and every control above runs\n // on the FIRST url only: the allowlist, the https-only check and the\n // pinned dispatcher. A declared, allowlisted, genuinely public origin\n // answering `302 Location: http://169.254.169.254/...` therefore reached\n // the cloud metadata service and returned its body to the caller — on an\n // unauthenticated route. The IP pin did not stop it: Node skips a custom\n // `connect.lookup` when the target is an IP literal, so the redirect\n // connected directly and the pinned lookup was consulted exactly once,\n // for the original hostname.\n //\n // `redirect: 'manual'` hands us each hop instead. Every one re-enters the\n // same two gates the first url passed — the manifest allowlist (which is\n // also what enforces https and the exact origin) and a fresh\n // `resolvePublicIp` with its own pinned dispatcher — so a redirect can\n // only ever reach somewhere the plugin could have named directly.\n let currentUrl = url\n let upstream: Response\n for (let hop = 0; ; hop++) {\n if (hop > MAX_REDIRECT_HOPS) {\n res\n .status(403)\n .json({ ok: false, status: 0, error: 'Too many redirects' })\n return\n }\n const pinnedIp = await resolvePublicIp(new URL(currentUrl).hostname)\n if (!pinnedIp) {\n res.status(403).json({\n ok: false,\n status: 0,\n error: 'URL resolves to a non-public address',\n })\n return\n }\n\n // Pin the socket to the address we just validated (AGL-515).\n const dispatcher = createPinnedDispatcher(pinnedIp)\n const controller = new AbortController()\n const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS)\n // `dispatcher` is an undici extension not in the DOM RequestInit type;\n // assigning to a variable first avoids the object-literal excess-property\n // check while still passing it through to the (undici) global fetch.\n const requestInit = {\n method,\n signal: controller.signal,\n dispatcher,\n redirect: 'manual' as const,\n headers: { Accept: 'application/json, text/*;q=0.9, */*;q=0.1' },\n ...(method === 'POST' && requestBody ? { body: requestBody } : {}),\n }\n try {\n upstream = await fetch(currentUrl, requestInit)\n } finally {\n clearTimeout(timeout)\n await dispatcher.close().catch(() => undefined)\n }\n\n if (!REDIRECT_STATUSES.has(upstream.status)) break\n\n const location = upstream.headers.get('location')\n if (!location) break // a redirect status with no target is just a body\n let nextUrl: string\n try {\n nextUrl = new URL(location, currentUrl).toString()\n } catch {\n res\n .status(403)\n .json({ ok: false, status: 0, error: 'Redirect target is not a URL' })\n return\n }\n if (\n !isPluginNetworkAllowed(\n nextUrl,\n (install.manifest as { capabilities?: any }).capabilities,\n )\n ) {\n res.status(403).json({\n ok: false,\n status: 0,\n error: 'Redirect target not in allowlist',\n })\n return\n }\n currentUrl = nextUrl\n }\n\n const text = await upstream.text()\n const clipped =\n Buffer.byteLength(text) > PLUGIN_FETCH_MAX_BODY_BYTES\n ? text.slice(0, PLUGIN_FETCH_MAX_BODY_BYTES)\n : text\n res.status(200).json({\n ok: upstream.ok,\n status: upstream.status,\n body: clipped,\n })\n } catch (error) {\n console.error('servePluginFetch failed', hostId, listingId, error)\n res.status(502).json({ ok: false, status: 0, error: 'Fetch failed' })\n }\n}\n\nfunction safeJson(value: string): Record<string, unknown> {\n try {\n return JSON.parse(value)\n } catch {\n return {}\n }\n}\n"],"names":["isPluginNetworkAllowed","PLUGIN_FETCH_MAX_BODY_BYTES","lookup","isIPv4","isIPv6","Agent","Dispatcher1Wrapper","firebaseAdmin","FETCH_TIMEOUT_MS","MAX_REDIRECT_HOPS","REDIRECT_STATUSES","Set","isPrivateIp","ip","a","b","split","map","Number","low","toLowerCase","startsWith","test","slice","resolvePublicIp","hostname","addresses","all","length","some","address","createPinnedDispatcher","pinnedIp","family","allowH2","connect","_host","options","cb","servePluginFetch","req","res","body","method","setHeader","status","json","ok","error","safeJson","hostId","String","listingId","url","requestBody","undefined","Buffer","byteLength","install","app","firestore","collection","doc","get","data","manifest","capabilities","currentUrl","upstream","hop","URL","dispatcher","controller","AbortController","timeout","setTimeout","abort","requestInit","signal","redirect","headers","Accept","fetch","clearTimeout","close","catch","has","location","nextUrl","toString","text","clipped","console","value","JSON","parse"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,sBAAsB,EACtBC,2BAA2B,QACtB,sBAAqB;AAC5B,SAASC,MAAM,QAAQ,oBAAc;AACrC,SAASC,MAAM,EAAEC,MAAM,QAAQ,MAAK;AAEpC,SAASC,KAAK,EAAmBC,kBAAkB,QAAQ,SAAQ;AACnE,SAASC,aAAa,QAAQ,sBAAkB;AAEhD,MAAMC,mBAAmB;AACzB;;;;CAIC,GACD,MAAMC,oBAAoB;AAC1B,uEAAuE,GACvE,MAAMC,oBAAoB,IAAIC,IAAI;IAAC;IAAK;IAAK;IAAK;IAAK;CAAI;AAE3D,sEAAsE,GACtE,SAASC,YAAYC,EAAU;IAC7B,IAAIV,OAAOU,KAAK;QACd,MAAM,CAACC,GAAGC,EAAE,GAAGF,GAAGG,KAAK,CAAC,KAAKC,GAAG,CAACC;QACjC,IAAIJ,MAAM,KAAKA,MAAM,MAAMA,MAAM,KAAK,OAAO;QAC7C,IAAIA,MAAM,OAAOC,MAAM,KAAK,OAAO,KAAK,8BAA8B;;QACtE,IAAID,MAAM,OAAOC,KAAK,MAAMA,KAAK,IAAI,OAAO;QAC5C,IAAID,MAAM,OAAOC,MAAM,KAAK,OAAO;QACnC,IAAID,MAAM,OAAOC,KAAK,MAAMA,KAAK,KAAK,OAAO,KAAK,QAAQ;;QAC1D,oEAAo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