From f5810c5b557c46b7c5eff53d3c05d2cbf0383b56 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 21 Oct 2026 17:46:14 +0000 Subject: [PATCH 1/8] fix(router): harden redirects, store errors, manifest items and config ids A batch of small router and manifest hardening items: - A version's external redirect destination may no longer sit under the router's own base paths, which the router serves again and so loops on. - serveArchive refuses root objects whose name starts with an underscore (the publisher's and build's bookkeeping files), also with no base path. - A client error from the store for a malformed path is a plain 404 instead of a 503 and a logged error; credential, timeout and rate limit refusals stay failures. - A tag's releaseUrl is pinned to github.com and the banner bases to coder.com. - The release schedule is validated before it is served or cached. - The Global Config id must look like ecfg_ plus alphanumerics before it is placed in an API path. - The reader skips and logs one malformed manifest item instead of failing every request; writers and publishers stay strict. - The router turns off the Next image optimizer, and sharp and source-map-js move to their patched releases in the lockfile. Assisted-by: AI --- apps/router/lib/archive.ts | 16 ++ apps/router/lib/manifest.ts | 3 + apps/router/lib/releases-handler.ts | 4 +- apps/router/lib/router-hardening.test.ts | 132 +++++++++ apps/router/next.config.ts | 2 + packages/docs-manifest/src/items.ts | 83 ++++-- packages/docs-manifest/src/reader.ts | 7 +- .../src/router-hardening.test.ts | 127 +++++++++ .../docs-manifest/src/version-redirects.ts | 6 + packages/docs-manifest/src/write.ts | 32 +-- pnpm-lock.yaml | 252 +++++++++--------- 11 files changed, 491 insertions(+), 173 deletions(-) create mode 100644 apps/router/lib/router-hardening.test.ts create mode 100644 packages/docs-manifest/src/router-hardening.test.ts diff --git a/apps/router/lib/archive.ts b/apps/router/lib/archive.ts index 6befd891..27d58fc0 100644 --- a/apps/router/lib/archive.ts +++ b/apps/router/lib/archive.ts @@ -30,6 +30,16 @@ export const STORE_HEADERS_TIMEOUT_MS = 10_000; type GetOptions = Parameters[1]; export type ArchiveDeps = { get: Getter; headersTimeoutMs?: number }; +// Refusals about the router (credentials, quota, timeouts) stay failures; any other 4xx is about the path asked for. +const ROUTER_SIDE_STATUSES = new Set([401, 403, 408, 429]); + +/** Whether the store refused the key itself (a malformed path such as one carrying `%00`), so the object is simply not there. */ +function isStoreClientError(error: unknown): boolean { + const match = + error instanceof Error ? /Failed to fetch blob: (4\d\d)\b/.exec(error.message) : null; + return match !== null && !ROUTER_SIDE_STATUSES.has(Number(match[1])); +} + /** * `get`, cancelled when the client disconnects (for the whole read, body * included) or when the store has not answered within the headers timeout. @@ -60,6 +70,9 @@ async function readObject( }), timedOut, ]); + } catch (error) { + if (isStoreClientError(error)) return null; + throw error; } finally { clearTimeout(timer); } @@ -274,6 +287,9 @@ export async function serveArchive( // so the invariant does not come to depend solely on that call site never // changing. if (prefix !== "" && !mapped.key.startsWith(`${prefix}/`)) return null; + // The publisher's and build's own bookkeeping objects sit at the prefix root. + const relativeKey = prefix === "" ? mapped.key : mapped.key.slice(prefix.length + 1); + if (relativeKey.startsWith("_") && !relativeKey.includes("/")) return null; const ifNoneMatch = request.headers.get("if-none-match") ?? undefined; // The read goes through the Blob store's own CDN cache (the SDK's default; diff --git a/apps/router/lib/manifest.ts b/apps/router/lib/manifest.ts index cac8588b..41e0eff6 100644 --- a/apps/router/lib/manifest.ts +++ b/apps/router/lib/manifest.ts @@ -17,6 +17,9 @@ export function getManifestReader(): ManifestReader { reader = createManifestReader({ getAll: () => client.getAll>(), ttlMs: 60_000, + onInvalidItem: (key, error) => { + console.error(`docs-router: skipping malformed manifest item ${key}`, error); + }, onError: (error) => { console.error("docs-router: manifest refresh failed, serving the last good copy", error); }, diff --git a/apps/router/lib/releases-handler.ts b/apps/router/lib/releases-handler.ts index cd9f4778..aa9ea8d8 100644 --- a/apps/router/lib/releases-handler.ts +++ b/apps/router/lib/releases-handler.ts @@ -1,4 +1,4 @@ -import type { ReleaseSchedule } from "@coder/docs-config"; +import { type ReleaseSchedule, parseReleaseSchedule } from "@coder/docs-config"; const CACHEABLE = "public, max-age=300, s-maxage=3600, stale-while-revalidate=86400"; @@ -38,7 +38,7 @@ export function createReleasesHandler(deps: ReleasesHandlerDeps): () => Promise< pending ??= deps .load() .then((schedule) => { - good = { schedule, fetchedAt: now() }; + good = { schedule: parseReleaseSchedule(schedule), fetchedAt: now() }; }) .catch((error: unknown) => { failedAt = now(); diff --git a/apps/router/lib/router-hardening.test.ts b/apps/router/lib/router-hardening.test.ts new file mode 100644 index 00000000..91614cc1 --- /dev/null +++ b/apps/router/lib/router-hardening.test.ts @@ -0,0 +1,132 @@ +import assert from "node:assert/strict"; +import { mock, test } from "node:test"; +import type { ReleaseSchedule } from "@coder/docs-config"; +import { type ManifestReader, lineKey, parseManifestItems } from "@coder/docs-manifest"; +import { createArchiveHandler } from "./archive-handler.js"; +import { serveArchive } from "./archive.js"; +import { createReleasesHandler } from "./releases-handler.js"; +import config from "../next.config.js"; + +const PREFIX = `versions/2.37/${"a".repeat(40)}`; +const DEPLOYMENT = `https://abc123.private.blob.vercel-storage.com/${PREFIX}`; +const manifest = parseManifestItems({ + [lineKey("2.37")]: { + id: "2.37", + label: "v2.37", + ref: "release/2.37", + sha: "a".repeat(40), + deployment: DEPLOYMENT, + publishedAt: "2026-09-04T10:15:00Z", + }, + mainline: "2.37", +}); +const reader: ManifestReader = { read: async () => ({ manifest, fetchedAt: Date.now() }) }; + +type Getter = (key: string) => Promise; +const object = (body: string, contentType = "text/html; charset=utf-8") => ({ + statusCode: 200, + stream: new Blob([body]).stream(), + blob: { contentType, etag: '"e"', size: body.length }, +}); + +function archiveOf(objects: Record, calls: string[] = []): Getter { + return async (key) => { + calls.push(key); + const body = objects[key]; + return body === undefined ? null : object(body); + }; +} + +test("the publisher's and build's root objects are never served, even with no base path", async () => { + const calls: string[] = []; + const get = archiveOf( + { + [`${PREFIX}/_publish.json`]: "{}", + [`${PREFIX}/_objects.json`]: "{}", + [`${PREFIX}/_redirects.json`]: "[]", + [`${PREFIX}/_next/static/a.js`]: "export {};", + }, + calls, + ); + for (const name of ["_publish.json", "_objects.json", "_redirects.json"]) { + const response = await serveArchive( + { deployment: DEPLOYMENT, path: `/${name}`, versionId: "2.37" }, + new Request(`https://docs.example/${name}`), + { get: get as never }, + ); + assert.equal(response, null, name); + } + assert.deepEqual(calls, []); + const asset = await serveArchive( + { deployment: DEPLOYMENT, path: "/_next/static/a.js", versionId: "2.37" }, + new Request("https://docs.example/_next/static/a.js"), + { get: get as never }, + ); + assert.equal(asset?.status, 200); +}); + +function handlerWith(get: Getter) { + return createArchiveHandler({ getReader: () => reader, get: () => get as never }); +} + +test("a path the store refuses with a client error is a 404, not a 503 with a logged error", async () => { + const error = mock.method(console, "error", () => {}); + try { + const get: Getter = async (key) => { + if (key.includes("bad")) + throw new Error("Vercel Blob: Failed to fetch blob: 400 Bad Request"); + return null; + }; + const response = await handlerWith(get)(new Request("https://docs.example/bad")); + assert.equal(response.status, 404); + assert.equal(error.mock.callCount(), 0); + } finally { + error.mock.restore(); + } +}); + +test("a store refusal that is about the router, not the path, stays a 503", async () => { + const error = mock.method(console, "error", () => {}); + try { + for (const status of ["401 Unauthorized", "403 Forbidden", "429 Too Many Requests"]) { + const get: Getter = async () => { + throw new Error(`Vercel Blob: Failed to fetch blob: ${status}`); + }; + const response = await handlerWith(get)(new Request("https://docs.example/admin")); + assert.equal(response.status, 503, status); + } + } finally { + error.mock.restore(); + } +}); + +const schedule = (releasedAt: string): ReleaseSchedule => ({ + schemaVersion: 1, + generatedAt: "2026-09-30T12:00:00.000Z", + rows: [ + { + minor: "2.36", + status: "stable", + esr: false, + releasedAt, + firstTag: "v2.36.0", + latestTag: "v2.36.6", + }, + ], +}); + +test("a release schedule that fails validation is never served", async () => { + const error = mock.method(console, "error", () => {}); + try { + const handler = createReleasesHandler({ load: async () => schedule("not a date") }); + const response = await handler(); + assert.equal(response.status, 503); + assert.equal(response.headers.get("cache-control"), "no-store"); + } finally { + error.mock.restore(); + } +}); + +test("the image optimizer is off on a router that serves no images of its own", () => { + assert.equal(config.images?.unoptimized, true); +}); diff --git a/apps/router/next.config.ts b/apps/router/next.config.ts index ca2a6daa..f2c7fee5 100644 --- a/apps/router/next.config.ts +++ b/apps/router/next.config.ts @@ -14,6 +14,8 @@ const config: NextConfig = { // adding one back would loop; the archive handler serves both forms. skipTrailingSlashRedirect: true, poweredByHeader: false, + // A route-handler-only app: nothing here needs `/_next/image`. + images: { unoptimized: true }, redirects: async () => docsRedirects(rules, normalizeRouterBasePath(process.env.ROUTER_BASE_PATH)), }; diff --git a/packages/docs-manifest/src/items.ts b/packages/docs-manifest/src/items.ts index e9ae9245..92fb9bf6 100644 --- a/packages/docs-manifest/src/items.ts +++ b/packages/docs-manifest/src/items.ts @@ -53,6 +53,12 @@ const deploymentUrl = z.url({ protocol: /^https$/ }).refine((value) => { ); }, "deployment must be an https origin, optionally with a path prefix, and no trailing slash"); +/** Whether a URL's authority is exactly `host`: no userinfo, no port, no look-alike suffix. */ +function isPlainHost(value: string, host: string): boolean { + const url = new URL(value); + return url.host === host && url.username === "" && url.password === ""; +} + const engineSha = z.string().regex(SHA).optional(); const layout = z.literal(CANONICAL_LAYOUT).optional(); @@ -78,7 +84,10 @@ export const tagItemSchema = z.looseObject({ deployment: deploymentUrl, publishedAt: z.iso.datetime(), releasedAt: z.iso.datetime().optional(), - releaseUrl: z.url({ protocol: /^https$/ }).optional(), + releaseUrl: z + .url({ protocol: /^https$/ }) + .refine((value) => isPlainHost(value, "github.com"), "releaseUrl must be on github.com") + .optional(), engine: engineSha, layout, }); @@ -123,13 +132,13 @@ const bannerBase = z.string().refine((value) => { } return ( url.protocol === "https:" && - url.hostname.length > 0 && + isPlainHost(value, "coder.com") && url.search === "" && url.hash === "" && !value.endsWith("/") && url.pathname.length > 1 ); -}, "base must be an https URL with a path, and no surrounding whitespace, trailing slash, empty segment, query, or fragment"); +}, "base must be an https://coder.com URL with a path, and no surrounding whitespace, trailing slash, empty segment, query, or fragment"); /** * The beta banner switch. Runtime-fed on purpose: frozen tag builds cannot be @@ -193,6 +202,14 @@ function parseOrThrow(schema: z.ZodType, value: unknown, key: string): T { return result.data; } +export interface ParseManifestItemsOptions { + /** + * Readers pass this to skip a malformed item and keep the rest; without it + * the first malformed item throws, which is what writers and publishers want. + */ + onInvalidItem?: (key: string, error: unknown) => void; +} + /** * Turn the raw item map a Global Config store returns into a typed manifest. * Unknown keys are ignored so the store can grow; a known key whose value does @@ -201,34 +218,44 @@ function parseOrThrow(schema: z.ZodType, value: unknown, key: string): T { * `banner`: it is cosmetic and can drop nothing, so a malformed value leaves * `manifest.banner` undefined instead of failing the parse. */ -export function parseManifestItems(items: Record): Manifest { +export function parseManifestItems( + items: Record, + options: ParseManifestItemsOptions = {}, +): Manifest { const manifest = emptyManifest(); for (const [key, value] of Object.entries(items)) { - if (key.startsWith(LINE_KEY_PREFIX)) { - const item = parseOrThrow(lineItemSchema, value, key); - if (lineKey(item.id) !== key) - throw new ManifestParseError(`item ${key} carries id ${item.id}`); - manifest.lines.set(item.id, item); - } else if (key.startsWith(TAG_KEY_PREFIX)) { - const item = parseOrThrow(tagItemSchema, value, key); - if (tagKey(item.id) !== key) - throw new ManifestParseError(`item ${key} carries id ${item.id}`); - manifest.tags.set(item.id, item); - } else if (key === DEV_KEY) { - manifest.dev = parseOrThrow(devItemSchema, value, key); - } else if (key === MAINLINE_KEY) { - manifest.mainline = parseOrThrow(mainlineSchema, value, key); - } else if (key === SUPPORT_KEY) { - manifest.support = parseOrThrow(supportMatrixSchema, value, key); - } else if (key === BANNER_KEY) { - // Tolerated, not thrown: a reader with no prior snapshot rethrows a parse - // failure and the router turns that into a 503 for every documentation - // path, so a mistyped cosmetic switch must not be able to take the site - // down. Hidden is the banner's only failure mode. Writers stay strict - // through `parseBannerItem`, so the typo is caught where it is made. - const banner = bannerItemSchema.safeParse(value); - manifest.banner = banner.success ? banner.data : undefined; + try { + applyItem(manifest, key, value); + } catch (error) { + if (!options.onInvalidItem) throw error; + options.onInvalidItem(key, error); } } return manifest; } + +function applyItem(manifest: Manifest, key: string, value: unknown): void { + if (key.startsWith(LINE_KEY_PREFIX)) { + const item = parseOrThrow(lineItemSchema, value, key); + if (lineKey(item.id) !== key) throw new ManifestParseError(`item ${key} carries id ${item.id}`); + manifest.lines.set(item.id, item); + } else if (key.startsWith(TAG_KEY_PREFIX)) { + const item = parseOrThrow(tagItemSchema, value, key); + if (tagKey(item.id) !== key) throw new ManifestParseError(`item ${key} carries id ${item.id}`); + manifest.tags.set(item.id, item); + } else if (key === DEV_KEY) { + manifest.dev = parseOrThrow(devItemSchema, value, key); + } else if (key === MAINLINE_KEY) { + manifest.mainline = parseOrThrow(mainlineSchema, value, key); + } else if (key === SUPPORT_KEY) { + manifest.support = parseOrThrow(supportMatrixSchema, value, key); + } else if (key === BANNER_KEY) { + // Tolerated, not thrown: a reader with no prior snapshot rethrows a parse + // failure and the router turns that into a 503 for every documentation + // path, so a mistyped cosmetic switch must not be able to take the site + // down. Hidden is the banner's only failure mode. Writers stay strict + // through `parseBannerItem`, so the typo is caught where it is made. + const banner = bannerItemSchema.safeParse(value); + manifest.banner = banner.success ? banner.data : undefined; + } +} diff --git a/packages/docs-manifest/src/reader.ts b/packages/docs-manifest/src/reader.ts index 04516052..cd325e91 100644 --- a/packages/docs-manifest/src/reader.ts +++ b/packages/docs-manifest/src/reader.ts @@ -22,6 +22,8 @@ export interface ManifestReaderOptions { now?: () => number; /** Called when a refresh fails while a previous snapshot is still served. */ onError?: (error: unknown) => void; + /** Called for each malformed item, which is skipped so the others still route. */ + onInvalidItem?: (key: string, error: unknown) => void; } export interface ManifestReader { @@ -49,7 +51,10 @@ export function createManifestReader(options: ManifestReaderOptions): ManifestRe async function refresh(): Promise { try { const items = await options.getAll(); - const fresh = { manifest: parseManifestItems(items), fetchedAt: now() }; + const fresh = { + manifest: parseManifestItems(items, { onInvalidItem: options.onInvalidItem }), + fetchedAt: now(), + }; snapshot = fresh; lastFailure = undefined; return fresh; diff --git a/packages/docs-manifest/src/router-hardening.test.ts b/packages/docs-manifest/src/router-hardening.test.ts new file mode 100644 index 00000000..d27565b4 --- /dev/null +++ b/packages/docs-manifest/src/router-hardening.test.ts @@ -0,0 +1,127 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { bannerItemSchema, lineKey, parseManifestItems, tagItemSchema, tagKey } from "./items.js"; +import { createManifestReader } from "./reader.js"; +import { fixtureItems } from "./test-fixtures.js"; +import { isAllowedExternalRedirect, parseVersionRedirectsFile } from "./version-redirects.js"; +import { readManifestItems, writeManifestItems } from "./write.js"; + +test("an external destination under the router's own base paths is refused", () => { + for (const url of [ + "https://coder.com/docs", + "https://coder.com/docs/admin", + "https://coder.com/beta-docs", + "https://coder.com/beta-docs/v2.38/admin", + "https://coder.com/Docs/admin", + ]) { + assert.equal(isAllowedExternalRedirect(url), false, url); + assert.throws( + () => parseVersionRedirectsFile(JSON.stringify([{ source: "a", destination: url }])), + /redirects:/, + url, + ); + } +}); + +test("other coder.com and github.com destinations, including look-alike prefixes, stay allowed", () => { + for (const url of [ + "https://coder.com/pricing", + "https://coder.com/docs-archive/a", + "https://coder.com/documentation", + "https://github.com/coder/coder/blob/main/CONTRIBUTING.md", + ]) { + assert.equal(isAllowedExternalRedirect(url), true, url); + } +}); + +const tag = fixtureItems[tagKey("2.36.4")]; +const banner = { + enabled: true, + legacyBase: "https://coder.com/docs", + betaBase: "https://coder.com/beta-docs", +}; + +test("a tag's releaseUrl must be on github.com", () => { + assert.equal(tagItemSchema.safeParse(tag).success, true); + for (const releaseUrl of [ + "https://evil.example/coder/coder/releases/tag/v2.36.4", + "https://github.com.evil.example/coder/coder/releases/tag/v2.36.4", + "https://user@github.com/coder/coder/releases/tag/v2.36.4", + "https://github.com:8443/coder/coder/releases/tag/v2.36.4", + ]) { + assert.equal(tagItemSchema.safeParse({ ...(tag as object), releaseUrl }).success, false); + } +}); + +test("the banner's bases must be on coder.com", () => { + assert.equal(bannerItemSchema.safeParse(banner).success, true); + for (const bases of [ + { legacyBase: "https://evil.example/docs" }, + { betaBase: "https://evil.example/beta-docs" }, + { legacyBase: "https://coder.com.evil.example/docs" }, + { legacyBase: "https://user@coder.com/docs" }, + { betaBase: "https://coder.com:8443/beta-docs" }, + ]) { + assert.equal(bannerItemSchema.safeParse({ ...banner, ...bases }).success, false); + } +}); + +const badLine = { ...(fixtureItems[lineKey("2.36")] as object), sha: "not-a-sha" }; + +test("reading skips one malformed item, reports it, and keeps the rest", () => { + const skipped: string[] = []; + const manifest = parseManifestItems( + { ...fixtureItems, [lineKey("2.36")]: badLine }, + { onInvalidItem: (key) => skipped.push(key) }, + ); + assert.deepEqual(skipped, [lineKey("2.36")]); + assert.equal(manifest.lines.has("2.36"), false); + assert.equal(manifest.lines.has("2.37"), true); + assert.equal(manifest.mainline, "2.37"); +}); + +test("an item stored under another item's key is skipped when reading", () => { + const skipped: string[] = []; + const manifest = parseManifestItems( + { ...fixtureItems, [lineKey("2.36")]: fixtureItems[lineKey("2.37")] }, + { onInvalidItem: (key) => skipped.push(key) }, + ); + assert.deepEqual(skipped, [lineKey("2.36")]); + assert.equal(manifest.lines.has("2.36"), false); +}); + +test("writers and publishers still fail on a malformed item", () => { + assert.throws( + () => parseManifestItems({ ...fixtureItems, [lineKey("2.36")]: badLine }), + /line_2-36/, + ); +}); + +test("the reader serves the other versions when one item is malformed", async () => { + const skipped: string[] = []; + const reader = createManifestReader({ + getAll: async () => ({ ...fixtureItems, [lineKey("2.36")]: badLine }), + onInvalidItem: (key) => skipped.push(key), + }); + const { manifest } = await reader.read(); + assert.deepEqual([...manifest.lines.keys()], ["2.37"]); + assert.deepEqual(skipped, [lineKey("2.36")]); +}); + +test("a Global Config id that is not ecfg_ plus alphanumerics never reaches the API path", async () => { + const calls: string[] = []; + const fetchImpl: typeof fetch = async (input) => { + calls.push(String(input)); + return new Response("{}", { status: 200 }); + }; + for (const configId of ["ecfg_1/../../x", "ecfg_1?x=1", "ecfg_", "abc", "ecfg_1#", ""]) { + const target = { configId, teamId: "team_abc", token: "t", fetch: fetchImpl }; + await assert.rejects(readManifestItems(target), /configId/, configId); + await assert.rejects( + writeManifestItems(target, [{ key: "mainline", value: "2.37" }]), + /configId/, + configId, + ); + } + assert.deepEqual(calls, []); +}); diff --git a/packages/docs-manifest/src/version-redirects.ts b/packages/docs-manifest/src/version-redirects.ts index e33e67dc..defdc9ed 100644 --- a/packages/docs-manifest/src/version-redirects.ts +++ b/packages/docs-manifest/src/version-redirects.ts @@ -36,6 +36,8 @@ export type VersionRedirectTarget = ( const SEGMENT = /^[A-Za-z0-9._-]+$/; const RULE_FIELDS = new Set(["source", "destination", "permanent"]); const EXTERNAL_PREFIXES = ["https://github.com/coder/", "https://coder.com/"]; +// The router's own base paths: a destination under one is served by this router again, so it would redirect to itself. +const ROUTER_PATHS = ["/docs", "/beta-docs"]; const EXTERNAL_BODY = /^[A-Za-z0-9._/-]+$/; // Legacy trailing parameters that stand for `/*`: `:name*`, `:name(.*)`, and the // allowlisted `:name([A-Za-z0-9._-]+)*` the engine's own file uses. @@ -65,6 +67,10 @@ function externalProblem(url: string): string | null { if (!EXTERNAL_PREFIXES.some((prefix) => url.startsWith(prefix))) { return `external destination must start with ${EXTERNAL_PREFIXES.join(" or ")}`; } + const path = url.slice(url.indexOf("/", "https://".length)).toLowerCase(); + if (ROUTER_PATHS.some((base) => path === base || path.startsWith(`${base}/`))) { + return `external destination may not be under ${ROUTER_PATHS.join(" or ")}, which this router serves`; + } const body = url.slice("https://".length); if ( !EXTERNAL_BODY.test(body) || diff --git a/packages/docs-manifest/src/write.ts b/packages/docs-manifest/src/write.ts index 105a4f56..4b42f006 100644 --- a/packages/docs-manifest/src/write.ts +++ b/packages/docs-manifest/src/write.ts @@ -1,6 +1,7 @@ import { BANNER_KEY, MANIFEST_KEY_PATTERN, parseBannerItem, parseManifestItems } from "./items.js"; const API_ROOT = "https://api.vercel.com/v1/global-config"; +const CONFIG_ID_PATTERN = /^ecfg_[A-Za-z0-9]+$/; const SLUG_PATTERN = /^[A-Za-z0-9_-]{1,32}$/; export interface ManifestWrite { @@ -32,6 +33,13 @@ export class GlobalConfigError extends Error { } } +function itemsUrl(target: { configId: string; teamId: string }): string { + if (!CONFIG_ID_PATTERN.test(target.configId)) { + throw new Error(`configId must match ${CONFIG_ID_PATTERN}`); + } + return `${API_ROOT}/${target.configId}/items?teamId=${encodeURIComponent(target.teamId)}`; +} + /** * One publish is one PATCH: every item it touches goes in a single `items` * array, applied atomically by the API. Keys are validated here so an illegal @@ -99,15 +107,11 @@ export async function writeManifestItems( if (write.key === BANNER_KEY) parseBannerItem(write.value); } const body = JSON.stringify(buildItemsPatch(writes)); - await request( - target, - `${API_ROOT}/${target.configId}/items?teamId=${encodeURIComponent(target.teamId)}`, - { - method: "PATCH", - headers: { "content-type": "application/json" }, - body, - }, - ); + await request(target, itemsUrl(target), { + method: "PATCH", + headers: { "content-type": "application/json" }, + body, + }); } /** @@ -140,13 +144,9 @@ export function itemsToRecord(items: unknown): Record { export async function readManifestItems( target: GlobalConfigTarget, ): Promise> { - const items = await request( - target, - `${API_ROOT}/${target.configId}/items?teamId=${encodeURIComponent(target.teamId)}`, - { - method: "GET", - }, - ); + const items = await request(target, itemsUrl(target), { + method: "GET", + }); return itemsToRecord(items); } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 81d9bef9..aa38dba9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -862,160 +862,160 @@ packages: resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==} engines: {node: '>=18'} - '@img/sharp-darwin-arm64@0.35.4': - resolution: {integrity: sha512-Uhfl4V4lhP2nbUVF9+hyH1+luj86f1gUFeo8ALYxFoULoU+G87D43BfeMP8XHsk9boxAnCY/bf2EHwhA7MuGsA==} + '@img/sharp-darwin-arm64@0.35.5': + resolution: {integrity: sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [darwin] - '@img/sharp-darwin-x64@0.35.4': - resolution: {integrity: sha512-hWniXY3bG5qKpkKrAwPe4y+VTPmf086YQAnkxWh7uA1YrlRouWGa0M0Mxj3ZjnXFkv7/TD1bTy9lGUK26vRvWw==} + '@img/sharp-darwin-x64@0.35.5': + resolution: {integrity: sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==} engines: {node: '>=20.9.0'} cpu: [x64] os: [darwin] - '@img/sharp-freebsd-wasm32@0.35.4': - resolution: {integrity: sha512-lIsKw/BU+kjB4eZjxrYrZmwOJYi3Ajrv66iAlBmUPyKc3HpnloevB1g3wxGD9P/5BbQ1brBGl65VRRrCvQDEqA==} + '@img/sharp-freebsd-wasm32@0.35.5': + resolution: {integrity: sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==} engines: {node: '>=20.9.0'} os: [freebsd] - '@img/sharp-libvips-darwin-arm64@1.3.3': - resolution: {integrity: sha512-suTBPTDGrI9WodccaDdwZItTSaBYASlBk1NSfElSHrUfzu3szG6lvIF58+WiFvnfzuK8ZBFS5zE00PxqxnRiPg==} + '@img/sharp-libvips-darwin-arm64@1.3.4': + resolution: {integrity: sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==} cpu: [arm64] os: [darwin] - '@img/sharp-libvips-darwin-x64@1.3.3': - resolution: {integrity: sha512-FVJZ5mITMobmXIz/hPDTw0EintTW5H3WfrxwLqEqjiIihlu+hVRyGrFQ60xl0Lxn7Bt3zdpevPaQi0HEzqz9fw==} + '@img/sharp-libvips-darwin-x64@1.3.4': + resolution: {integrity: sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==} cpu: [x64] os: [darwin] - '@img/sharp-libvips-linux-arm64@1.3.3': - resolution: {integrity: sha512-0DaL0A6Xu6sQSQFwe4iVCrKWU2cCTItnRsYsCdxAMm9NF6twAA9BKnoqy4hqz4+azQ0JHuA26qiUKsf1XJ/v5A==} + '@img/sharp-libvips-linux-arm64@1.3.4': + resolution: {integrity: sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==} cpu: [arm64] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-arm@1.3.3': - resolution: {integrity: sha512-3rbU4vqXXc3hY/OiXdl52xZvT0F1yEngWfvqudtPJg/KkyiaQw2DRsFrNzpmLvfavbwOq3qXn36GP8obHRULQA==} + '@img/sharp-libvips-linux-arm@1.3.4': + resolution: {integrity: sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==} cpu: [arm] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-ppc64@1.3.3': - resolution: {integrity: sha512-cdn1OvUBwsXhbC0zSzJnNzf5MZ/mTrobawDvNXBTxe8VtqKAm0sRuEY2Evzovb/w9JMk4TvRxqt1mekSuJz64w==} + '@img/sharp-libvips-linux-ppc64@1.3.4': + resolution: {integrity: sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==} cpu: [ppc64] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-riscv64@1.3.3': - resolution: {integrity: sha512-HjPVx7yKz+0lqdhDlTw1tt90wamBoxhiXpvl1XZpJLiHH4RCJ5yDTqH+VlYPv2fwFs89JFw4c1IexYOcQUi4IQ==} + '@img/sharp-libvips-linux-riscv64@1.3.4': + resolution: {integrity: sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==} cpu: [riscv64] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-s390x@1.3.3': - resolution: {integrity: sha512-neWLh+3yCNThxnfy3c4BbVBeGgt9aftno+XbT56iK28RgeDs3UOFWviLWlUu0bArYVYJaFDK+RRohbicUNCm8Q==} + '@img/sharp-libvips-linux-s390x@1.3.4': + resolution: {integrity: sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==} cpu: [s390x] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-x64@1.3.3': - resolution: {integrity: sha512-4vKmvAst9nrowcqquKFAyZJUDolUaIp8uRiN0mWFguJ1IplC9/pitXtlnnlU4aa/eJw3J7i67V+pwUL+wZGdsA==} + '@img/sharp-libvips-linux-x64@1.3.4': + resolution: {integrity: sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==} cpu: [x64] os: [linux] libc: [glibc] - '@img/sharp-libvips-linuxmusl-arm64@1.3.3': - resolution: {integrity: sha512-Y9kQaLMuNoB0bPYOOdcZMaseNrFpPodIWWMrx+CZyydf2xn68j9WYc6sWWRrDwNkzCQjKYfc68L7jKjGlHMibw==} + '@img/sharp-libvips-linuxmusl-arm64@1.3.4': + resolution: {integrity: sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==} cpu: [arm64] os: [linux] libc: [musl] - '@img/sharp-libvips-linuxmusl-x64@1.3.3': - resolution: {integrity: sha512-fj8Mv0HHfD1Rr+4I68+3agJynxDWtBFgicTbSOb9Bke6pIwzGcJ+RX/yHjmiEGFMCavY/dxvem7MyNaJF+wDiw==} + '@img/sharp-libvips-linuxmusl-x64@1.3.4': + resolution: {integrity: sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==} cpu: [x64] os: [linux] libc: [musl] - '@img/sharp-linux-arm64@0.35.4': - resolution: {integrity: sha512-De4jpEnAU8Hd5oT0j1G3uL4ZvTuipVMn7YC6vPaJhy6/7EwEae0SVAoBrUMYQbkLGDm85taVWwuPc1a44LTzCQ==} + '@img/sharp-linux-arm64@0.35.5': + resolution: {integrity: sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [linux] libc: [glibc] - '@img/sharp-linux-arm@0.35.4': - resolution: {integrity: sha512-7OAS8gI0EReKGVN2HssHlM6umJgxF5VI3xN0p9FA91p/YO+ou5hiNghLdZ5BEHztwaaK5+bLKRf8x/o2L2nk9A==} + '@img/sharp-linux-arm@0.35.5': + resolution: {integrity: sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==} engines: {node: '>=20.9.0'} cpu: [arm] os: [linux] libc: [glibc] - '@img/sharp-linux-ppc64@0.35.4': - resolution: {integrity: sha512-2oYZJeIl4kCcMGk4ouZVjnkCtFrpQFlNEtJ6GbxzhHQchwH0NH/qEb9ykmOl29dqwMq+JhFdZn+1ak2FKhI9fQ==} + '@img/sharp-linux-ppc64@0.35.5': + resolution: {integrity: sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==} engines: {node: '>=20.9.0'} cpu: [ppc64] os: [linux] libc: [glibc] - '@img/sharp-linux-riscv64@0.35.4': - resolution: {integrity: sha512-cPbNChoRURAWdebDIHSenxRpgEdy7JkPydSnUxRm9VvKD7m0/xVaR/8Fzlu81pk5nHEvHH87UZUA7cTtwnbJSA==} + '@img/sharp-linux-riscv64@0.35.5': + resolution: {integrity: sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==} engines: {node: '>=20.9.0'} cpu: [riscv64] os: [linux] libc: [glibc] - '@img/sharp-linux-s390x@0.35.4': - resolution: {integrity: sha512-RY0JFY8Fd6RonCBtHz+DvadaPkXDSI1AUn6yWL9TipqkZ1vY8w8evqdgyDFnkm4/K1ve1TvZiaePP5oSd4+WVQ==} + '@img/sharp-linux-s390x@0.35.5': + resolution: {integrity: sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==} engines: {node: '>=20.9.0'} cpu: [s390x] os: [linux] libc: [glibc] - '@img/sharp-linux-x64@0.35.4': - resolution: {integrity: sha512-9qvvEAuk8k89TfWUoX2htWjbAMX8p+NxCppjpcg5k6xMsjhBQPTsoIh36h9Qde4WRuGpJeYnOjdosDn/cnv+OA==} + '@img/sharp-linux-x64@0.35.5': + resolution: {integrity: sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==} engines: {node: '>=20.9.0'} cpu: [x64] os: [linux] libc: [glibc] - '@img/sharp-linuxmusl-arm64@0.35.4': - resolution: {integrity: sha512-KB5jxpfWQTr0nc3xdHtWChdbifHrBGsd2SM62Eyxrl8afikm+f5qGBU75SJIZBT/S1MC8XyacdlXBMSWq6OURA==} + '@img/sharp-linuxmusl-arm64@0.35.5': + resolution: {integrity: sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [linux] libc: [musl] - '@img/sharp-linuxmusl-x64@0.35.4': - resolution: {integrity: sha512-f+eZJZIQNEEd26RPSW+76chwOf1XtA2Y/O+5ocVyLliHkeih3e+jhLVBdNTd2rS3IbNXK8+ug93Vf5ZXtF5Lxg==} + '@img/sharp-linuxmusl-x64@0.35.5': + resolution: {integrity: sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==} engines: {node: '>=20.9.0'} cpu: [x64] os: [linux] libc: [musl] - '@img/sharp-wasm32@0.35.4': - resolution: {integrity: sha512-zQnl4Kwp7Q6NHsENtU2T/00Zi+w3AQNwz3+UaTyVBy2FpXrzXzGjndpK61onhZjRtRpQXxCTeqw19bVyXOh7jA==} + '@img/sharp-wasm32@0.35.5': + resolution: {integrity: sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==} engines: {node: '>=20.9.0'} - '@img/sharp-webcontainers-wasm32@0.35.4': - resolution: {integrity: sha512-ESfNkywmCfPNyaZjxooddJQiQ+l/nTpGEOGthxiLnIHXC/CmcBixnfwUleX9mCz9ovrUUvKMap/pm8RYbzfwaA==} + '@img/sharp-webcontainers-wasm32@0.35.5': + resolution: {integrity: sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==} engines: {node: '>=20.9.0'} cpu: [wasm32] - '@img/sharp-win32-arm64@0.35.4': - resolution: {integrity: sha512-iNdlBX9gLVvqe2I3uIJSIKTq6wckP/DYxZtcqxm09x5Gi24DnFBmPAWZmr60ZyYMG0xlzo6goG3670ar+RXvRw==} + '@img/sharp-win32-arm64@0.35.5': + resolution: {integrity: sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [win32] - '@img/sharp-win32-ia32@0.35.4': - resolution: {integrity: sha512-kqRsbaa5CS6KHlpxnN7WhE6vAAugXyZButpRdvDWetlv6Qv4N9WTcrWzF7tXfB9T7MsoadqdI8hmwLq6UlLvtw==} + '@img/sharp-win32-ia32@0.35.5': + resolution: {integrity: sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==} engines: {node: ^20.9.0} cpu: [ia32] os: [win32] - '@img/sharp-win32-x64@0.35.4': - resolution: {integrity: sha512-XtmnYhBcrORsJ4XJngyzr/EWP0hRZLAZRFaApdKuviyqF78+ylxh2y06ZmtULAMOnObJ3ucpN0AcwSWnMowTRg==} + '@img/sharp-win32-x64@0.35.5': + resolution: {integrity: sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==} engines: {node: '>=20.9.0'} cpu: [x64] os: [win32] @@ -3372,8 +3372,8 @@ packages: engines: {node: '>=10'} hasBin: true - sharp@0.35.4: - resolution: {integrity: sha512-n++8XWcj+jCOr2IOl7h8LbKnGBDY4aPbmprMONBNFdn0ImXqpGVv5zliDs0V9HbmbCQLpbuo2ej9rAoOQTvMDA==} + sharp@0.35.5: + resolution: {integrity: sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==} engines: {node: '>=20.9.0'} peerDependencies: '@types/node': '*' @@ -3408,8 +3408,8 @@ packages: resolution: {integrity: sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ==} engines: {node: '>=10'} - source-map-js@1.2.1: - resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} + source-map-js@1.2.2: + resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} engines: {node: '>=0.10.0'} source-map@0.7.6: @@ -3913,108 +3913,108 @@ snapshots: '@img/colour@1.1.0': optional: true - '@img/sharp-darwin-arm64@0.35.4': + '@img/sharp-darwin-arm64@0.35.5': optionalDependencies: - '@img/sharp-libvips-darwin-arm64': 1.3.3 + '@img/sharp-libvips-darwin-arm64': 1.3.4 optional: true - '@img/sharp-darwin-x64@0.35.4': + '@img/sharp-darwin-x64@0.35.5': optionalDependencies: - '@img/sharp-libvips-darwin-x64': 1.3.3 + '@img/sharp-libvips-darwin-x64': 1.3.4 optional: true - '@img/sharp-freebsd-wasm32@0.35.4': + '@img/sharp-freebsd-wasm32@0.35.5': dependencies: - '@img/sharp-wasm32': 0.35.4 + '@img/sharp-wasm32': 0.35.5 optional: true - '@img/sharp-libvips-darwin-arm64@1.3.3': + '@img/sharp-libvips-darwin-arm64@1.3.4': optional: true - '@img/sharp-libvips-darwin-x64@1.3.3': + '@img/sharp-libvips-darwin-x64@1.3.4': optional: true - '@img/sharp-libvips-linux-arm64@1.3.3': + '@img/sharp-libvips-linux-arm64@1.3.4': optional: true - '@img/sharp-libvips-linux-arm@1.3.3': + '@img/sharp-libvips-linux-arm@1.3.4': optional: true - '@img/sharp-libvips-linux-ppc64@1.3.3': + '@img/sharp-libvips-linux-ppc64@1.3.4': optional: true - '@img/sharp-libvips-linux-riscv64@1.3.3': + '@img/sharp-libvips-linux-riscv64@1.3.4': optional: true - '@img/sharp-libvips-linux-s390x@1.3.3': + '@img/sharp-libvips-linux-s390x@1.3.4': optional: true - '@img/sharp-libvips-linux-x64@1.3.3': + '@img/sharp-libvips-linux-x64@1.3.4': optional: true - '@img/sharp-libvips-linuxmusl-arm64@1.3.3': + '@img/sharp-libvips-linuxmusl-arm64@1.3.4': optional: true - '@img/sharp-libvips-linuxmusl-x64@1.3.3': + '@img/sharp-libvips-linuxmusl-x64@1.3.4': optional: true - '@img/sharp-linux-arm64@0.35.4': + '@img/sharp-linux-arm64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-arm64': 1.3.3 + '@img/sharp-libvips-linux-arm64': 1.3.4 optional: true - '@img/sharp-linux-arm@0.35.4': + '@img/sharp-linux-arm@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-arm': 1.3.3 + '@img/sharp-libvips-linux-arm': 1.3.4 optional: true - '@img/sharp-linux-ppc64@0.35.4': + '@img/sharp-linux-ppc64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-ppc64': 1.3.3 + '@img/sharp-libvips-linux-ppc64': 1.3.4 optional: true - '@img/sharp-linux-riscv64@0.35.4': + '@img/sharp-linux-riscv64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-riscv64': 1.3.3 + '@img/sharp-libvips-linux-riscv64': 1.3.4 optional: true - '@img/sharp-linux-s390x@0.35.4': + '@img/sharp-linux-s390x@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-s390x': 1.3.3 + '@img/sharp-libvips-linux-s390x': 1.3.4 optional: true - '@img/sharp-linux-x64@0.35.4': + '@img/sharp-linux-x64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-x64': 1.3.3 + '@img/sharp-libvips-linux-x64': 1.3.4 optional: true - '@img/sharp-linuxmusl-arm64@0.35.4': + '@img/sharp-linuxmusl-arm64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linuxmusl-arm64': 1.3.3 + '@img/sharp-libvips-linuxmusl-arm64': 1.3.4 optional: true - '@img/sharp-linuxmusl-x64@0.35.4': + '@img/sharp-linuxmusl-x64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linuxmusl-x64': 1.3.3 + '@img/sharp-libvips-linuxmusl-x64': 1.3.4 optional: true - '@img/sharp-wasm32@0.35.4': + '@img/sharp-wasm32@0.35.5': dependencies: '@emnapi/runtime': 1.11.3 optional: true - '@img/sharp-webcontainers-wasm32@0.35.4': + '@img/sharp-webcontainers-wasm32@0.35.5': dependencies: - '@img/sharp-wasm32': 0.35.4 + '@img/sharp-wasm32': 0.35.5 optional: true - '@img/sharp-win32-arm64@0.35.4': + '@img/sharp-win32-arm64@0.35.5': optional: true - '@img/sharp-win32-ia32@0.35.4': + '@img/sharp-win32-ia32@0.35.5': optional: true - '@img/sharp-win32-x64@0.35.4': + '@img/sharp-win32-x64@0.35.5': optional: true '@jridgewell/gen-mapping@0.3.13': @@ -4637,7 +4637,7 @@ snapshots: jiti: 2.7.0 lightningcss: 1.32.0 magic-string: 0.30.21 - source-map-js: 1.2.1 + source-map-js: 1.2.2 tailwindcss: 4.3.3 '@tailwindcss/oxide-android-arm64@4.3.3': @@ -4955,7 +4955,7 @@ snapshots: css-tree@3.2.1: dependencies: mdn-data: 2.27.1 - source-map-js: 1.2.1 + source-map-js: 1.2.2 cssesc@3.0.0: {} @@ -6348,7 +6348,7 @@ snapshots: '@next/swc-linux-x64-musl': 16.3.8 '@next/swc-win32-arm64-msvc': 16.3.8 '@next/swc-win32-x64-msvc': 16.3.8 - sharp: 0.35.4(@types/node@22.20.1) + sharp: 0.35.5(@types/node@22.20.1) transitivePeerDependencies: - '@babel/core' - '@types/node' @@ -6478,13 +6478,13 @@ snapshots: dependencies: nanoid: 3.3.18 picocolors: 1.1.1 - source-map-js: 1.2.1 + source-map-js: 1.2.2 postcss@8.5.28: dependencies: nanoid: 3.3.18 picocolors: 1.1.1 - source-map-js: 1.2.1 + source-map-js: 1.2.2 property-information@7.2.0: {} @@ -6674,37 +6674,37 @@ snapshots: semver@7.8.5: optional: true - sharp@0.35.4(@types/node@22.20.1): + sharp@0.35.5(@types/node@22.20.1): dependencies: '@img/colour': 1.1.0 detect-libc: 2.1.2 semver: 7.8.5 optionalDependencies: - '@img/sharp-darwin-arm64': 0.35.4 - '@img/sharp-darwin-x64': 0.35.4 - '@img/sharp-freebsd-wasm32': 0.35.4 - '@img/sharp-libvips-darwin-arm64': 1.3.3 - '@img/sharp-libvips-darwin-x64': 1.3.3 - '@img/sharp-libvips-linux-arm': 1.3.3 - '@img/sharp-libvips-linux-arm64': 1.3.3 - '@img/sharp-libvips-linux-ppc64': 1.3.3 - '@img/sharp-libvips-linux-riscv64': 1.3.3 - '@img/sharp-libvips-linux-s390x': 1.3.3 - '@img/sharp-libvips-linux-x64': 1.3.3 - '@img/sharp-libvips-linuxmusl-arm64': 1.3.3 - '@img/sharp-libvips-linuxmusl-x64': 1.3.3 - '@img/sharp-linux-arm': 0.35.4 - '@img/sharp-linux-arm64': 0.35.4 - '@img/sharp-linux-ppc64': 0.35.4 - '@img/sharp-linux-riscv64': 0.35.4 - '@img/sharp-linux-s390x': 0.35.4 - '@img/sharp-linux-x64': 0.35.4 - '@img/sharp-linuxmusl-arm64': 0.35.4 - '@img/sharp-linuxmusl-x64': 0.35.4 - '@img/sharp-webcontainers-wasm32': 0.35.4 - '@img/sharp-win32-arm64': 0.35.4 - '@img/sharp-win32-ia32': 0.35.4 - '@img/sharp-win32-x64': 0.35.4 + '@img/sharp-darwin-arm64': 0.35.5 + '@img/sharp-darwin-x64': 0.35.5 + '@img/sharp-freebsd-wasm32': 0.35.5 + '@img/sharp-libvips-darwin-arm64': 1.3.4 + '@img/sharp-libvips-darwin-x64': 1.3.4 + '@img/sharp-libvips-linux-arm': 1.3.4 + '@img/sharp-libvips-linux-arm64': 1.3.4 + '@img/sharp-libvips-linux-ppc64': 1.3.4 + '@img/sharp-libvips-linux-riscv64': 1.3.4 + '@img/sharp-libvips-linux-s390x': 1.3.4 + '@img/sharp-libvips-linux-x64': 1.3.4 + '@img/sharp-libvips-linuxmusl-arm64': 1.3.4 + '@img/sharp-libvips-linuxmusl-x64': 1.3.4 + '@img/sharp-linux-arm': 0.35.5 + '@img/sharp-linux-arm64': 0.35.5 + '@img/sharp-linux-ppc64': 0.35.5 + '@img/sharp-linux-riscv64': 0.35.5 + '@img/sharp-linux-s390x': 0.35.5 + '@img/sharp-linux-x64': 0.35.5 + '@img/sharp-linuxmusl-arm64': 0.35.5 + '@img/sharp-linuxmusl-x64': 0.35.5 + '@img/sharp-webcontainers-wasm32': 0.35.5 + '@img/sharp-win32-arm64': 0.35.5 + '@img/sharp-win32-ia32': 0.35.5 + '@img/sharp-win32-x64': 0.35.5 '@types/node': 22.20.1 optional: true @@ -6737,7 +6737,7 @@ snapshots: astral-regex: 2.0.0 is-fullwidth-code-point: 3.0.0 - source-map-js@1.2.1: {} + source-map-js@1.2.2: {} source-map@0.7.6: {} From 6ccc8311e34d48ba451454bea372261ae34e8766 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 21 Oct 2026 13:58:19 -0700 Subject: [PATCH 2/8] fix(docs-manifest): keep a malformed item's last good value instead of dropping it Skipping a malformed item made the refresh succeed with that item missing, so every warm isolate dropped it within a minute instead of serving the last good snapshot. When the item was the mainline or its line, the whole root site became a cached 404. The reader now passes its last good manifest to the parser, and a malformed item keeps its value from there; it is dropped only on a cold start. If that leaves the mainline or its line unservable, the parse throws, so a warm reader keeps its whole snapshot and a cold one answers the uncached 503. The host pin moves to a dependency-free safe-urls module. It compares the raw string against https:///, so a port, userinfo or case change is refused, and it returns false rather than throwing on a value that is not a URL, so safeParse reports a failure naming the key. The banner component now uses the same check as the schema instead of a looser copy. The tests move into the files for the modules they cover. Assisted-by: AI --- apps/router/lib/manifest.ts | 5 +- packages/docs-manifest/package.json | 4 + packages/docs-manifest/src/index.ts | 1 + packages/docs-manifest/src/items.test.ts | 81 +++++++++++ packages/docs-manifest/src/items.ts | 98 ++++++++------ packages/docs-manifest/src/reader.test.ts | 81 +++++++++++ packages/docs-manifest/src/reader.ts | 8 +- .../src/router-hardening.test.ts | 127 ------------------ packages/docs-manifest/src/safe-urls.ts | 22 +++ .../src/version-redirects.test.ts | 29 ++++ packages/docs-manifest/src/write.test.ts | 14 ++ packages/docs-ui/src/beta-banner.test.tsx | 5 +- packages/docs-ui/src/beta-banner.tsx | 38 +----- 13 files changed, 303 insertions(+), 210 deletions(-) delete mode 100644 packages/docs-manifest/src/router-hardening.test.ts create mode 100644 packages/docs-manifest/src/safe-urls.ts diff --git a/apps/router/lib/manifest.ts b/apps/router/lib/manifest.ts index 41e0eff6..b019904b 100644 --- a/apps/router/lib/manifest.ts +++ b/apps/router/lib/manifest.ts @@ -18,7 +18,10 @@ export function getManifestReader(): ManifestReader { getAll: () => client.getAll>(), ttlMs: 60_000, onInvalidItem: (key, error) => { - console.error(`docs-router: skipping malformed manifest item ${key}`, error); + console.error( + `docs-router: malformed manifest item ${key}; serving its last good value, if any`, + error, + ); }, onError: (error) => { console.error("docs-router: manifest refresh failed, serving the last good copy", error); diff --git a/packages/docs-manifest/package.json b/packages/docs-manifest/package.json index 59308ffe..25d8a546 100644 --- a/packages/docs-manifest/package.json +++ b/packages/docs-manifest/package.json @@ -13,6 +13,10 @@ "types": "./dist/path-safety.d.ts", "default": "./dist/path-safety.js" }, + "./safe-urls": { + "types": "./dist/safe-urls.d.ts", + "default": "./dist/safe-urls.js" + }, "./version-segment": { "types": "./dist/version-segment.d.ts", "default": "./dist/version-segment.js" diff --git a/packages/docs-manifest/src/index.ts b/packages/docs-manifest/src/index.ts index eabf0f04..ae3e559b 100644 --- a/packages/docs-manifest/src/index.ts +++ b/packages/docs-manifest/src/index.ts @@ -2,6 +2,7 @@ export * from "./items.js"; export * from "./path-safety.js"; export * from "./reader.js"; export * from "./route.js"; +export * from "./safe-urls.js"; export * from "./versions-document.js"; export * from "./write.js"; export * from "./version-segment.js"; diff --git a/packages/docs-manifest/src/items.test.ts b/packages/docs-manifest/src/items.test.ts index 4e628c23..64b65038 100644 --- a/packages/docs-manifest/src/items.test.ts +++ b/packages/docs-manifest/src/items.test.ts @@ -11,6 +11,7 @@ import { lineKey, parseBannerItem, parseManifestItems, + tagItemSchema, tagKey, } from "./items.js"; import { fixtureItems, withLayout } from "./test-fixtures.js"; @@ -162,6 +163,13 @@ test("bannerItemSchema rejects unsafe or malformed bases and an oversized messag { ...banner, legacyBase: "https://coder.com/docs#" }, { ...banner, legacyBase: "https://coder.com//docs" }, { ...banner, betaBase: "https://coder.com/beta-docs " }, + { ...banner, legacyBase: "https://evil.example/docs" }, + { ...banner, betaBase: "https://evil.example/beta-docs" }, + { ...banner, legacyBase: "https://coder.com.evil.example/docs" }, + { ...banner, legacyBase: "https://user@coder.com/docs" }, + { ...banner, betaBase: "https://coder.com:8443/beta-docs" }, + { ...banner, betaBase: "https://coder.com:443/beta-docs" }, + { ...banner, legacyBase: "https://Coder.com/docs" }, ]) { assert.equal(bannerItemSchema.safeParse(bad).success, false, JSON.stringify(bad)); } @@ -208,3 +216,76 @@ test("a version entry may record the canonical storage layout, and a missing one test("an unknown storage layout fails the parse rather than being routed as legacy", () => { assert.throws(() => parseManifestItems(withLayout("sideways")), ManifestParseError); }); + +const tag = fixtureItems[tagKey("2.36.4")] as Record; + +test("a tag's releaseUrl must be on github.com, spelled exactly", () => { + assert.equal(tagItemSchema.safeParse(tag).success, true); + for (const releaseUrl of [ + "https://evil.example/coder/coder/releases/tag/v2.36.4", + "https://github.com.evil.example/coder/coder/releases/tag/v2.36.4", + "https://user@github.com/coder/coder/releases/tag/v2.36.4", + "https://github.com:8443/coder/coder/releases/tag/v2.36.4", + "https://github.com:443/coder/coder/releases/tag/v2.36.4", + "https://GitHub.com/coder/coder/releases/tag/v2.36.4", + ]) { + assert.equal(tagItemSchema.safeParse({ ...tag, releaseUrl }).success, false, releaseUrl); + } +}); + +test("a value that is not a URL at all is a parse failure naming the key, never a TypeError", () => { + for (const field of ["releaseUrl", "deployment"]) { + assert.equal(tagItemSchema.safeParse({ ...tag, [field]: "not a url" }).success, false, field); + assert.throws( + () => + parseManifestItems({ + ...fixtureItems, + [tagKey("2.36.4")]: { ...tag, [field]: "not a url" }, + }), + (error) => error instanceof ManifestParseError && /tag_2-36-4/.test(error.message), + field, + ); + } +}); + +const badLine = { ...(fixtureItems[lineKey("2.36")] as Record), sha: "not-a-sha" }; + +test("with onInvalidItem, one malformed item is reported and skipped and the rest still parse", () => { + const skipped: string[] = []; + const manifest = parseManifestItems( + { ...fixtureItems, [lineKey("2.36")]: badLine }, + { onInvalidItem: (key) => skipped.push(key) }, + ); + assert.deepEqual(skipped, [lineKey("2.36")]); + assert.equal(manifest.lines.has("2.36"), false); + assert.equal(manifest.lines.has("2.37"), true); + assert.equal(manifest.mainline, "2.37"); +}); + +test("with onInvalidItem, an item stored under another item's key is skipped", () => { + const skipped: string[] = []; + const manifest = parseManifestItems( + { ...fixtureItems, [lineKey("2.36")]: fixtureItems[lineKey("2.37")] }, + { onInvalidItem: (key) => skipped.push(key) }, + ); + assert.deepEqual(skipped, [lineKey("2.36")]); + assert.equal(manifest.lines.has("2.36"), false); +}); + +test("with a previous manifest, a malformed item keeps its last good value", () => { + const previous = parseManifestItems(fixtureItems); + const manifest = parseManifestItems( + { ...fixtureItems, [lineKey("2.36")]: badLine, [MAINLINE_KEY]: 7, [SUPPORT_KEY]: [] }, + { onInvalidItem: () => {}, previous }, + ); + assert.deepEqual(manifest.lines.get("2.36"), previous.lines.get("2.36")); + assert.equal(manifest.mainline, "2.37"); + assert.deepEqual(manifest.support, previous.support); +}); + +test("without onInvalidItem, as writers and publishers parse, a malformed item still throws", () => { + assert.throws( + () => parseManifestItems({ ...fixtureItems, [lineKey("2.36")]: badLine }), + /line_2-36/, + ); +}); diff --git a/packages/docs-manifest/src/items.ts b/packages/docs-manifest/src/items.ts index 92fb9bf6..f4eda3d6 100644 --- a/packages/docs-manifest/src/items.ts +++ b/packages/docs-manifest/src/items.ts @@ -1,4 +1,5 @@ import { z } from "zod"; +import { isPlainHost, isSafeBannerBase } from "./safe-urls.js"; import { CANONICAL_LAYOUT, LINE_ID_PATTERN as LINE_ID, @@ -47,18 +48,13 @@ export function tagKey(id: string): string { * append the request path directly. */ const deploymentUrl = z.url({ protocol: /^https$/ }).refine((value) => { + if (!URL.canParse(value)) return false; const url = new URL(value); return ( url.search === "" && url.hash === "" && !value.endsWith("/") && !url.pathname.includes("//") ); }, "deployment must be an https origin, optionally with a path prefix, and no trailing slash"); -/** Whether a URL's authority is exactly `host`: no userinfo, no port, no look-alike suffix. */ -function isPlainHost(value: string, host: string): boolean { - const url = new URL(value); - return url.host === host && url.username === "" && url.password === ""; -} - const engineSha = z.string().regex(SHA).optional(); const layout = z.literal(CANONICAL_LAYOUT).optional(); @@ -107,38 +103,14 @@ export type SupportLevel = (typeof supportLevels)[number]; export const supportMatrixSchema = z.record(z.string().regex(LINE_ID), z.enum(supportLevels)); export const mainlineSchema = z.string().regex(LINE_ID); -// A base is an https URL with a path and nothing after it, so a page path can -// be appended directly: `${legacyBase}/v2.36/install`. -// -// The first three checks read the raw string rather than the parsed URL, because -// `new URL` hides exactly the shapes that break that concatenation: it trims -// surrounding whitespace (which the client-side guard then rejects, so the -// banner would never render), and it reports an empty `search`/`hash` for a -// bare trailing `?` or `#` (which would swallow the appended page path). An -// empty segment (`//`) anywhere after the scheme is rejected for the same -// reason the deployment URLs reject it: the appended path must resolve. -// Deliberately not `z.url()`: that normalises its output (trimming whitespace -// away), and the value served to the client must be the value written, so this -// schema and `isSafeLegacyBase` in @coder/docs-ui judge the same string. -const bannerBase = z.string().refine((value) => { - if (value !== value.trim()) return false; - if (value.includes("?") || value.includes("#")) return false; - if (value.includes("//", value.indexOf("://") + 3)) return false; - let url: URL; - try { - url = new URL(value); - } catch { - return false; - } - return ( - url.protocol === "https:" && - isPlainHost(value, "coder.com") && - url.search === "" && - url.hash === "" && - !value.endsWith("/") && - url.pathname.length > 1 +// Deliberately not `z.url()`: that normalises its output, and the value served +// to the client must be the value written. +const bannerBase = z + .string() + .refine( + isSafeBannerBase, + "base must be an https://coder.com URL with a path, and no surrounding whitespace, trailing slash, empty segment, query, or fragment", ); -}, "base must be an https://coder.com URL with a path, and no surrounding whitespace, trailing slash, empty segment, query, or fragment"); /** * The beta banner switch. Runtime-fed on purpose: frozen tag builds cannot be @@ -204,36 +176,74 @@ function parseOrThrow(schema: z.ZodType, value: unknown, key: string): T { export interface ParseManifestItemsOptions { /** - * Readers pass this to skip a malformed item and keep the rest; without it - * the first malformed item throws, which is what writers and publishers want. + * Readers pass this to report a malformed item and carry on; without it the + * first malformed item throws, which is what writers and publishers want. */ onInvalidItem?: (key: string, error: unknown) => void; + /** The last good manifest: a malformed item keeps its value from here, and is dropped only when this has none. */ + previous?: Manifest; } /** * Turn the raw item map a Global Config store returns into a typed manifest. - * Unknown keys are ignored so the store can grow; a known key whose value does - * not match its schema, or whose embedded id disagrees with the key, fails - * loudly rather than silently dropping a version. The one exception is - * `banner`: it is cosmetic and can drop nothing, so a malformed value leaves - * `manifest.banner` undefined instead of failing the parse. + * Unknown keys are ignored so the store can grow. By default a known key whose + * value does not match its schema, or whose embedded id disagrees with the key, + * fails loudly. With `onInvalidItem` (readers) it is reported instead and keeps + * its value from `previous`, or is dropped when there is none; the parse still + * throws if that leaves the mainline, or the line it names, unservable, so the + * root is never routed to a line that is not there. `banner` is always + * tolerated: it is cosmetic, so a malformed value leaves it undefined. */ export function parseManifestItems( items: Record, options: ParseManifestItemsOptions = {}, ): Manifest { const manifest = emptyManifest(); + const dropped = new Set(); for (const [key, value] of Object.entries(items)) { try { applyItem(manifest, key, value); } catch (error) { if (!options.onInvalidItem) throw error; options.onInvalidItem(key, error); + if (!options.previous || !keepPrevious(manifest, options.previous, key)) dropped.add(key); } } + if (dropped.has(MAINLINE_KEY) || (manifest.mainline && dropped.has(lineKey(manifest.mainline)))) { + throw new ManifestParseError( + "the mainline or its line is malformed and there is no last good value to serve", + ); + } return manifest; } +/** Copy `key`'s value from `previous` into `manifest`; false when `previous` has none. */ +function keepPrevious(manifest: Manifest, previous: Manifest, key: string): boolean { + if (key.startsWith(LINE_KEY_PREFIX)) { + const item = [...previous.lines.values()].find((line) => lineKey(line.id) === key); + if (item) manifest.lines.set(item.id, item); + return item !== undefined; + } + if (key.startsWith(TAG_KEY_PREFIX)) { + const item = [...previous.tags.values()].find((tag) => tagKey(tag.id) === key); + if (item) manifest.tags.set(item.id, item); + return item !== undefined; + } + if (key === DEV_KEY) { + manifest.dev = previous.dev; + return previous.dev !== undefined; + } + if (key === MAINLINE_KEY) { + manifest.mainline = previous.mainline; + return previous.mainline !== undefined; + } + if (key === SUPPORT_KEY) { + manifest.support = previous.support; + return true; + } + return false; +} + function applyItem(manifest: Manifest, key: string, value: unknown): void { if (key.startsWith(LINE_KEY_PREFIX)) { const item = parseOrThrow(lineItemSchema, value, key); diff --git a/packages/docs-manifest/src/reader.test.ts b/packages/docs-manifest/src/reader.test.ts index e7c5ae3b..92e64568 100644 --- a/packages/docs-manifest/src/reader.test.ts +++ b/packages/docs-manifest/src/reader.test.ts @@ -1,5 +1,6 @@ import assert from "node:assert/strict"; import { test } from "node:test"; +import { MAINLINE_KEY, lineKey } from "./items.js"; import { fixtureItems } from "./test-fixtures.js"; import { createManifestReader } from "./reader.js"; @@ -141,3 +142,83 @@ test("before any snapshot exists, rejects reads inside the retry window without await assert.rejects(reader.read(), /boom/); assert.equal(calls, 2, "a new fetch is attempted once retryAfterMs has passed"); }); + +const badLine = (id: string) => ({ + ...(fixtureItems[lineKey(id)] as Record), + sha: "not-a-sha", +}); + +/** A reader whose store answers `items[0]` first and `items[1]` on every refresh after the ttl. */ +function warmReader(next: Record) { + const time = clock(); + let calls = 0; + const skipped: string[] = []; + const reader = createManifestReader({ + getAll: async () => (calls++ === 0 ? fixtureItems : next), + ttlMs: 60_000, + now: time.now, + onInvalidItem: (key) => skipped.push(key), + }); + return { reader, time, skipped }; +} + +test("a warm reader keeps the last good mainline line when its item turns malformed", async () => { + const { reader, time, skipped } = warmReader({ + ...fixtureItems, + [lineKey("2.37")]: badLine("2.37"), + }); + const before = await reader.read(); + time.advance(60_000); + const { manifest } = await reader.read(); + assert.deepEqual(skipped, [lineKey("2.37")]); + assert.equal(manifest.mainline, "2.37"); + assert.deepEqual(manifest.lines.get("2.37"), before.manifest.lines.get("2.37")); + assert.deepEqual([...manifest.lines.keys()], ["2.37", "2.36"]); +}); + +test("a warm reader keeps the last good mainline when the mainline item turns malformed", async () => { + const { reader, time, skipped } = warmReader({ ...fixtureItems, [MAINLINE_KEY]: "latest" }); + await reader.read(); + time.advance(60_000); + const { manifest } = await reader.read(); + assert.deepEqual(skipped, [MAINLINE_KEY]); + assert.equal(manifest.mainline, "2.37"); +}); + +test("a warm reader still takes the store's good changes alongside a malformed item", async () => { + const { reader, time } = warmReader({ + ...fixtureItems, + [lineKey("2.36")]: badLine("2.36"), + [MAINLINE_KEY]: "2.36", + }); + await reader.read(); + time.advance(60_000); + const { manifest } = await reader.read(); + assert.equal(manifest.mainline, "2.36"); + assert.equal( + manifest.lines.get("2.36")?.sha, + (fixtureItems[lineKey("2.36")] as { sha: string }).sha, + ); +}); + +test("a cold reader skips a malformed item that is not the mainline's and serves the rest", async () => { + const skipped: string[] = []; + const reader = createManifestReader({ + getAll: async () => ({ ...fixtureItems, [lineKey("2.36")]: badLine("2.36") }), + onInvalidItem: (key) => skipped.push(key), + }); + const { manifest } = await reader.read(); + assert.deepEqual([...manifest.lines.keys()], ["2.37"]); + assert.equal(manifest.mainline, "2.37"); + assert.deepEqual(skipped, [lineKey("2.36")]); +}); + +test("a cold reader refuses a manifest whose mainline it cannot serve, rather than 404 the root", async () => { + for (const items of [ + { ...fixtureItems, [lineKey("2.37")]: badLine("2.37") }, + { ...fixtureItems, [MAINLINE_KEY]: "latest" }, + ]) { + const reader = createManifestReader({ getAll: async () => items, onInvalidItem: () => {} }); + await assert.rejects(reader.read(), /mainline/); + } +}); diff --git a/packages/docs-manifest/src/reader.ts b/packages/docs-manifest/src/reader.ts index cd325e91..39cde864 100644 --- a/packages/docs-manifest/src/reader.ts +++ b/packages/docs-manifest/src/reader.ts @@ -22,7 +22,7 @@ export interface ManifestReaderOptions { now?: () => number; /** Called when a refresh fails while a previous snapshot is still served. */ onError?: (error: unknown) => void; - /** Called for each malformed item, which is skipped so the others still route. */ + /** Called for each malformed item, which keeps its last good value, or is skipped on a cold start. */ onInvalidItem?: (key: string, error: unknown) => void; } @@ -36,6 +36,7 @@ export interface ManifestReader { * it, shared by every concurrent caller. A failed refresh keeps serving the * last good snapshot so a store outage degrades to stale routing, never to a * site-wide 404; only a failure before any snapshot exists propagates. + * Likewise one malformed item keeps its value from the last good snapshot. * After a failed refresh, no new refresh is attempted until `retryAfterMs` * has passed, so a store outage costs one failing fetch per `retryAfterMs` * rather than one per request. @@ -52,7 +53,10 @@ export function createManifestReader(options: ManifestReaderOptions): ManifestRe try { const items = await options.getAll(); const fresh = { - manifest: parseManifestItems(items, { onInvalidItem: options.onInvalidItem }), + manifest: parseManifestItems(items, { + onInvalidItem: options.onInvalidItem, + previous: snapshot?.manifest, + }), fetchedAt: now(), }; snapshot = fresh; diff --git a/packages/docs-manifest/src/router-hardening.test.ts b/packages/docs-manifest/src/router-hardening.test.ts deleted file mode 100644 index d27565b4..00000000 --- a/packages/docs-manifest/src/router-hardening.test.ts +++ /dev/null @@ -1,127 +0,0 @@ -import assert from "node:assert/strict"; -import { test } from "node:test"; -import { bannerItemSchema, lineKey, parseManifestItems, tagItemSchema, tagKey } from "./items.js"; -import { createManifestReader } from "./reader.js"; -import { fixtureItems } from "./test-fixtures.js"; -import { isAllowedExternalRedirect, parseVersionRedirectsFile } from "./version-redirects.js"; -import { readManifestItems, writeManifestItems } from "./write.js"; - -test("an external destination under the router's own base paths is refused", () => { - for (const url of [ - "https://coder.com/docs", - "https://coder.com/docs/admin", - "https://coder.com/beta-docs", - "https://coder.com/beta-docs/v2.38/admin", - "https://coder.com/Docs/admin", - ]) { - assert.equal(isAllowedExternalRedirect(url), false, url); - assert.throws( - () => parseVersionRedirectsFile(JSON.stringify([{ source: "a", destination: url }])), - /redirects:/, - url, - ); - } -}); - -test("other coder.com and github.com destinations, including look-alike prefixes, stay allowed", () => { - for (const url of [ - "https://coder.com/pricing", - "https://coder.com/docs-archive/a", - "https://coder.com/documentation", - "https://github.com/coder/coder/blob/main/CONTRIBUTING.md", - ]) { - assert.equal(isAllowedExternalRedirect(url), true, url); - } -}); - -const tag = fixtureItems[tagKey("2.36.4")]; -const banner = { - enabled: true, - legacyBase: "https://coder.com/docs", - betaBase: "https://coder.com/beta-docs", -}; - -test("a tag's releaseUrl must be on github.com", () => { - assert.equal(tagItemSchema.safeParse(tag).success, true); - for (const releaseUrl of [ - "https://evil.example/coder/coder/releases/tag/v2.36.4", - "https://github.com.evil.example/coder/coder/releases/tag/v2.36.4", - "https://user@github.com/coder/coder/releases/tag/v2.36.4", - "https://github.com:8443/coder/coder/releases/tag/v2.36.4", - ]) { - assert.equal(tagItemSchema.safeParse({ ...(tag as object), releaseUrl }).success, false); - } -}); - -test("the banner's bases must be on coder.com", () => { - assert.equal(bannerItemSchema.safeParse(banner).success, true); - for (const bases of [ - { legacyBase: "https://evil.example/docs" }, - { betaBase: "https://evil.example/beta-docs" }, - { legacyBase: "https://coder.com.evil.example/docs" }, - { legacyBase: "https://user@coder.com/docs" }, - { betaBase: "https://coder.com:8443/beta-docs" }, - ]) { - assert.equal(bannerItemSchema.safeParse({ ...banner, ...bases }).success, false); - } -}); - -const badLine = { ...(fixtureItems[lineKey("2.36")] as object), sha: "not-a-sha" }; - -test("reading skips one malformed item, reports it, and keeps the rest", () => { - const skipped: string[] = []; - const manifest = parseManifestItems( - { ...fixtureItems, [lineKey("2.36")]: badLine }, - { onInvalidItem: (key) => skipped.push(key) }, - ); - assert.deepEqual(skipped, [lineKey("2.36")]); - assert.equal(manifest.lines.has("2.36"), false); - assert.equal(manifest.lines.has("2.37"), true); - assert.equal(manifest.mainline, "2.37"); -}); - -test("an item stored under another item's key is skipped when reading", () => { - const skipped: string[] = []; - const manifest = parseManifestItems( - { ...fixtureItems, [lineKey("2.36")]: fixtureItems[lineKey("2.37")] }, - { onInvalidItem: (key) => skipped.push(key) }, - ); - assert.deepEqual(skipped, [lineKey("2.36")]); - assert.equal(manifest.lines.has("2.36"), false); -}); - -test("writers and publishers still fail on a malformed item", () => { - assert.throws( - () => parseManifestItems({ ...fixtureItems, [lineKey("2.36")]: badLine }), - /line_2-36/, - ); -}); - -test("the reader serves the other versions when one item is malformed", async () => { - const skipped: string[] = []; - const reader = createManifestReader({ - getAll: async () => ({ ...fixtureItems, [lineKey("2.36")]: badLine }), - onInvalidItem: (key) => skipped.push(key), - }); - const { manifest } = await reader.read(); - assert.deepEqual([...manifest.lines.keys()], ["2.37"]); - assert.deepEqual(skipped, [lineKey("2.36")]); -}); - -test("a Global Config id that is not ecfg_ plus alphanumerics never reaches the API path", async () => { - const calls: string[] = []; - const fetchImpl: typeof fetch = async (input) => { - calls.push(String(input)); - return new Response("{}", { status: 200 }); - }; - for (const configId of ["ecfg_1/../../x", "ecfg_1?x=1", "ecfg_", "abc", "ecfg_1#", ""]) { - const target = { configId, teamId: "team_abc", token: "t", fetch: fetchImpl }; - await assert.rejects(readManifestItems(target), /configId/, configId); - await assert.rejects( - writeManifestItems(target, [{ key: "mainline", value: "2.37" }]), - /configId/, - configId, - ); - } - assert.deepEqual(calls, []); -}); diff --git a/packages/docs-manifest/src/safe-urls.ts b/packages/docs-manifest/src/safe-urls.ts new file mode 100644 index 00000000..769dcc26 --- /dev/null +++ b/packages/docs-manifest/src/safe-urls.ts @@ -0,0 +1,22 @@ +// Imports nothing, so client code (the beta banner) can use this subpath without zod. + +/** Whether `value` is a URL whose authority is spelled exactly `https:///`: no userinfo, port or case change. */ +export function isPlainHost(value: string, host: string): boolean { + return URL.canParse(value) && value.startsWith(`https://${host}/`); +} + +export const BANNER_HOST = "coder.com"; + +/** + * A banner base a page path can be appended to (`${legacyBase}/v2.36/install`): + * `https://coder.com/` with no surrounding whitespace, trailing slash, + * empty segment, query or fragment. Read from the raw string, because `new URL` + * trims whitespace and hides a bare `?` or `#`. The manifest schema and the + * banner component both judge the served string with this one check. + */ +export function isSafeBannerBase(value: string): boolean { + if (value !== value.trim() || value.endsWith("/")) return false; + if (value.includes("?") || value.includes("#")) return false; + if (value.includes("//", value.indexOf("://") + 3)) return false; + return isPlainHost(value, BANNER_HOST); +} diff --git a/packages/docs-manifest/src/version-redirects.test.ts b/packages/docs-manifest/src/version-redirects.test.ts index cbae9858..0e1157ff 100644 --- a/packages/docs-manifest/src/version-redirects.test.ts +++ b/packages/docs-manifest/src/version-redirects.test.ts @@ -7,6 +7,7 @@ import { parseVersionRedirectsArtifact, parseVersionRedirectsFile, resolveVersionRedirect, + isAllowedExternalRedirect, serializeVersionRedirects, } from "./version-redirects.js"; @@ -318,3 +319,31 @@ test("a fragment is refused on a wildcard, the root, an empty or odd fragment, a [rule("a", "b#c")], ); }); + +test("an external destination under the router's own base paths is refused", () => { + for (const url of [ + "https://coder.com/docs", + "https://coder.com/docs/admin", + "https://coder.com/beta-docs", + "https://coder.com/beta-docs/v2.38/admin", + "https://coder.com/Docs/admin", + ]) { + assert.equal(isAllowedExternalRedirect(url), false, url); + assert.throws( + () => parseVersionRedirectsFile(JSON.stringify([{ source: "a", destination: url }])), + /redirects:/, + url, + ); + } +}); + +test("other coder.com and github.com destinations, including look-alike prefixes, stay allowed", () => { + for (const url of [ + "https://coder.com/pricing", + "https://coder.com/docs-archive/a", + "https://coder.com/documentation", + "https://github.com/coder/coder/blob/main/CONTRIBUTING.md", + ]) { + assert.equal(isAllowedExternalRedirect(url), true, url); + } +}); diff --git a/packages/docs-manifest/src/write.test.ts b/packages/docs-manifest/src/write.test.ts index 25a4f955..33f4e779 100644 --- a/packages/docs-manifest/src/write.test.ts +++ b/packages/docs-manifest/src/write.test.ts @@ -193,3 +193,17 @@ test("writeManifestItems rejects a malformed banner and never calls fetch", asyn assert.equal(calls.length, 0); } }); + +test("a Global Config id that is not ecfg_ plus alphanumerics never reaches the API path", async () => { + const { fetchImpl, calls } = fakeFetch({ status: 200, body: {} }); + for (const configId of ["ecfg_1/../../x", "ecfg_1?x=1", "ecfg_", "abc", "ecfg_1#", ""]) { + const bad = { ...target, configId, fetch: fetchImpl }; + await assert.rejects(readManifestItems(bad), /configId/, configId); + await assert.rejects( + writeManifestItems(bad, [{ key: "mainline", value: "2.37" }]), + /configId/, + configId, + ); + } + assert.deepEqual(calls, []); +}); diff --git a/packages/docs-ui/src/beta-banner.test.tsx b/packages/docs-ui/src/beta-banner.test.tsx index faf5bb1f..4384d2a9 100644 --- a/packages/docs-ui/src/beta-banner.test.tsx +++ b/packages/docs-ui/src/beta-banner.test.tsx @@ -112,7 +112,7 @@ test("betaBannerLinkLabel puts the lead in the link's accessible name", () => { assert.equal(betaBannerLinkLabel(" ", version, null), "Coder 2.36 docs"); }); -test("isSafeLegacyBase accepts only an absolute https URL with no query, fragment, trailing slash, or masked whitespace", () => { +test("isSafeLegacyBase accepts only an https://coder.com URL with no query, fragment, trailing slash, or masked whitespace", () => { assert.equal(isSafeLegacyBase("javascript:alert(1)"), false); assert.equal(isSafeLegacyBase("data:text/html,x"), false); assert.equal(isSafeLegacyBase("//evil.example/docs"), false); @@ -122,6 +122,9 @@ test("isSafeLegacyBase accepts only an absolute https URL with no query, fragmen assert.equal(isSafeLegacyBase("https://coder.com/docs?"), false); assert.equal(isSafeLegacyBase("https://coder.com/docs#"), false); assert.equal(isSafeLegacyBase("https://coder.com//docs"), false); + assert.equal(isSafeLegacyBase("https://evil.example/docs"), false); + assert.equal(isSafeLegacyBase("https://coder.com.evil.example/docs"), false); + assert.equal(isSafeLegacyBase("https://user@coder.com/docs"), false); assert.equal(isSafeLegacyBase("https://coder.com/docs"), true); }); diff --git a/packages/docs-ui/src/beta-banner.tsx b/packages/docs-ui/src/beta-banner.tsx index ab8e84e4..782cf4d5 100644 --- a/packages/docs-ui/src/beta-banner.tsx +++ b/packages/docs-ui/src/beta-banner.tsx @@ -1,5 +1,6 @@ "use client"; +import { isSafeBannerBase } from "@coder/docs-manifest/safe-urls"; import { X } from "@phosphor-icons/react/ssr"; import { useCallback, useEffect, useMemo, useState } from "react"; import { type VersionsDocumentBanner, useVersionsDocument } from "./versions-document-client.js"; @@ -105,41 +106,8 @@ export function betaBannerLinkLabel( return lead ? `${lead} ${text}` : text; } -/** - * A `legacyBase` this component may safely turn into a link. It guarantees - * exactly this and no more: the string parses as an absolute URL, its scheme - * is `https:`, its host is non-empty, it carries no query and no fragment - * (checked on the raw string too, since `new URL` reports an empty `search` - * for a bare trailing `?`), no trailing slash, no empty path segment (`//`) - * after the scheme, and no surrounding whitespace (which `new URL` would trim - * away silently, masking what the raw value said). Those last three are the - * shapes `betaBannerHref` would otherwise concatenate a page path onto. - * - * It is not a lexical sanitizer: it does not reject control characters or any - * other character a URL parser accepts, and it pins the scheme and the shape, - * never the host — a hostile manifest can at most point the link at another - * https origin, which is the bound the whole guard rests on. - * - * The manifest schema enforces the same shape at write time - * (`packages/docs-manifest/src/items.ts`), but that is a property of one - * producer, not of the value this component receives over the wire — mirrors - * `mdx.tsx`'s stance that every href docs-ui renders is checked where it is - * used, not trusted from its source. - */ -export function isSafeLegacyBase(base: string): boolean { - if (base !== base.trim() || base.endsWith("/")) return false; - if (base.includes("?") || base.includes("#")) return false; - if (base.includes("//", base.indexOf("://") + 3)) return false; - let url: URL; - try { - url = new URL(base); - } catch { - return false; - } - return ( - url.protocol === "https:" && url.hostname.length > 0 && url.search === "" && url.hash === "" - ); -} +/** A `legacyBase` this component may turn into a link: the manifest schema's own check, applied again where the value is used. */ +export const isSafeLegacyBase = isSafeBannerBase; /** A release line `X.Y` or a tag `X.Y.Z`; the only ids the legacy site has pages for. */ const RELEASE_ID = /^\d+\.\d+(\.\d+)?$/; From b545378d9569156b48cdb10b9691df6dea805c5f Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 21 Oct 2026 13:58:19 -0700 Subject: [PATCH 3/8] fix(router): treat only key-shaped store refusals as misses, and never cache them Any 4xx outside a short denylist became a silent miss, so a 400 from a bad token, a 402 or a 410 turned every page into a 404 the edge cached for a minute, with nothing logged. A 4xx on a version's redirects object also read as "no redirects" without marking the response uncacheable. Now only 400 and 414, the statuses the store gives for a key it cannot take, count as a miss, and that response is sent with no-store and logged at most once a minute. Every other status is a failure again, and the redirects read no longer swallows any of them. The bookkeeping-object guard checks the percent-decoded key, so %5F and %5f spellings are refused too, and a key that does not decode is refused outright. The tests move into the files for the modules they cover, and the test that only asserted a config value is dropped. Assisted-by: AI --- apps/router/lib/archive-handler.test.ts | 83 +++++++++++++- apps/router/lib/archive-handler.ts | 20 +++- apps/router/lib/archive.test.ts | 36 +++++++ apps/router/lib/archive.ts | 30 ++++-- apps/router/lib/releases-handler.test.ts | 14 +++ apps/router/lib/router-hardening.test.ts | 132 ----------------------- 6 files changed, 168 insertions(+), 147 deletions(-) delete mode 100644 apps/router/lib/router-hardening.test.ts diff --git a/apps/router/lib/archive-handler.test.ts b/apps/router/lib/archive-handler.test.ts index c0c58a20..6c0d3864 100644 --- a/apps/router/lib/archive-handler.test.ts +++ b/apps/router/lib/archive-handler.test.ts @@ -3,6 +3,7 @@ import { mock, test } from "node:test"; import { DOCS_CONTENT_SECURITY_POLICY, docsContentSecurityPolicy } from "@coder/docs-config"; import { type ManifestReader, lineKey, parseManifestItems } from "@coder/docs-manifest"; import { createArchiveHandler } from "./archive-handler.js"; +import type { Getter } from "./archive.js"; const DEPLOYMENT = "https://coder-docs-versions-abc123-codercom.vercel.app"; const PREFIX = "versions/2.36/5627dae63cb058e4c0b4f3eb2019437ad3c268ce"; @@ -100,14 +101,20 @@ const storeWithoutNotFound = Object.fromEntries( ); function handlerWith( - getter = fakeGet(store), - overrides: { reader?: ManifestReader; basePath?: string; headersTimeoutMs?: number } = {}, + getter: { get: Getter; calls: string[] } = fakeGet(store), + overrides: { + reader?: ManifestReader; + basePath?: string; + headersTimeoutMs?: number; + now?: () => number; + } = {}, ) { const handler = createArchiveHandler({ getReader: () => overrides.reader ?? reader, get: () => getter.get, basePath: overrides.basePath, headersTimeoutMs: overrides.headersTimeoutMs, + now: overrides.now, }); return { handler, calls: getter.calls }; } @@ -496,6 +503,78 @@ test("a store failure degrades to a 503 that is never cached", async () => { assert.equal(await response.text(), "Documentation is temporarily unavailable."); }); +/** A store that refuses `refused` keys with `status` and holds nothing else. */ +function refusingGet(status: string, refused: (key: string) => boolean) { + const calls: string[] = []; + const get: Getter = async (pathname) => { + calls.push(pathname); + if (refused(pathname)) throw new Error(`Vercel Blob: Failed to fetch blob: ${status}`); + return null; + }; + return { get, calls }; +} + +test("a store refusal of the key itself (400, 414) is a miss that is never cached, logged at most once a minute", async () => { + for (const status of ["400 Bad Request", "414 URI Too Long"]) { + const error = mock.method(console, "error", () => {}); + try { + let now = 0; + const { handler } = handlerWith( + refusingGet(status, (key) => key.includes("%00")), + { now: () => now }, + ); + const request = () => new Request("https://docs.example/admin%00x/"); + const first = await handler(request()); + assert.equal(first.status, 404, status); + assert.equal(first.headers.get("cache-control"), "no-store", status); + await handler(request()); + assert.equal(error.mock.callCount(), 1, status); + now += 60_000; + await handler(request()); + assert.equal(error.mock.callCount(), 2, status); + } finally { + error.mock.restore(); + } + } +}); + +test("any other 4xx from the store is a 503 that is never cached, not a miss", async () => { + const error = mock.method(console, "error", () => {}); + try { + for (const status of [ + "401 Unauthorized", + "402 Payment Required", + "403 Forbidden", + "408 Request Timeout", + "410 Gone", + "429 Too Many Requests", + "451 Unavailable For Legal Reasons", + ]) { + const { handler } = handlerWith(refusingGet(status, () => true)); + const response = await handler(new Request("https://docs.example/@2.36/admin/")); + assert.equal(response.status, 503, status); + assert.equal(response.headers.get("cache-control"), "no-store", status); + } + } finally { + error.mock.restore(); + } +}); + +test("a store refusal of a version's redirects object is logged and the miss is never cached", async () => { + const error = mock.method(console, "error", () => {}); + try { + const { handler } = handlerWith( + refusingGet("400 Bad Request", (key) => key.endsWith("/_redirects.json")), + ); + const response = await handler(new Request("https://docs.example/@2.36/gone/")); + assert.equal(response.status, 404); + assert.equal(response.headers.get("cache-control"), "no-store"); + assert.ok(error.mock.callCount() >= 1); + } finally { + error.mock.restore(); + } +}); + test("a manifest failure degrades to the same 503", async () => { const { handler } = handlerWith(fakeGet(store), { reader: { diff --git a/apps/router/lib/archive-handler.ts b/apps/router/lib/archive-handler.ts index 6f54a79a..91558414 100644 --- a/apps/router/lib/archive-handler.ts +++ b/apps/router/lib/archive-handler.ts @@ -11,6 +11,7 @@ import { import { type Getter, isArchiveDeployment, + isStoreKeyRefusal, serveArchive, serveNotFoundPage, setCacheRule, @@ -76,6 +77,8 @@ export function createArchiveHandler( archive: () => ({ get: deps.get(), headersTimeoutMs: deps.headersTimeoutMs }), now: deps.now, }); + const now = deps.now ?? Date.now; + let keyRefusalLoggedAt = Number.NEGATIVE_INFINITY; return async (request) => { // The archive only ever answers reads; refuse anything else before the // manifest or the store is consulted. @@ -219,12 +222,25 @@ export function createArchiveHandler( }; try { - const served = await serveArchive(target, request, archiveDeps); + let served: Response | null; + let keyRefused = false; + try { + served = await serveArchive(target, request, archiveDeps); + } catch (error) { + if (!isStoreKeyRefusal(error)) throw error; + // A broken token can answer 400 too, so the miss is never cached, and is logged once a minute. + keyRefused = true; + served = null; + if (now() - keyRefusalLoggedAt >= 60_000) { + keyRefusalLoggedAt = now(); + console.error("docs-router: the store refused a key (logged once a minute)", error); + } + } // A miss, or a path with an unsafe segment, is answered with the // not-found page of the version the path named. const response = served ?? (await movedPage()) ?? (await notFound(target.deployment)); // A store blip must not pin a not-found page at the edge for a page that redirects. - if (probeFailed) setCacheRule(response.headers, "no-store"); + if (probeFailed || keyRefused) setCacheRule(response.headers, "no-store"); return response; } catch (error) { // A store outage or an expired OIDC token must not 500 every archived diff --git a/apps/router/lib/archive.test.ts b/apps/router/lib/archive.test.ts index d9d184e8..7591c9e1 100644 --- a/apps/router/lib/archive.test.ts +++ b/apps/router/lib/archive.test.ts @@ -347,3 +347,39 @@ test("the llms index files resolve as objects under their version's own prefix", assert.equal(headers.get("content-type"), "text/plain; charset=utf-8"); assert.equal(headers.get("x-content-type-options"), "nosniff"); }); + +test("the publisher's and build's root objects are never served, however the name is spelled", async () => { + const prefix = "versions/2.36/5627dae63cb058e4c0b4f3eb2019437ad3c268ce"; + const object = { body: "{}", contentType: "application/json", etag: '"b1"' }; + const { get, calls } = fakeGet({ + [`${prefix}/_publish.json`]: object, + [`${prefix}/_objects.json`]: object, + [`${prefix}/_redirects.json`]: object, + [`${prefix}/%5Fobjects.json`]: object, + [`${prefix}/%5fobjects.json`]: object, + [`${prefix}/%E0%A4%A.json`]: object, + [`${prefix}/_next/static/a.js`]: { ...object, contentType: "text/javascript" }, + }); + for (const path of [ + "/_publish.json", + "/_objects.json", + "/_redirects.json", + "/%5Fobjects.json", + "/%5fobjects.json", + "/%E0%A4%A.json", + ]) { + const target = { deployment, path, versionId: "2.36" }; + assert.equal( + await serveArchive(target, new Request("https://docs.example/x"), { get }), + null, + path, + ); + } + assert.deepEqual(calls, []); + const asset = await serveArchive( + { deployment, path: "/_next/static/a.js", versionId: "2.36" }, + new Request("https://docs.example/x"), + { get }, + ); + assert.equal(asset?.status, 200); +}); diff --git a/apps/router/lib/archive.ts b/apps/router/lib/archive.ts index 27d58fc0..a995e49a 100644 --- a/apps/router/lib/archive.ts +++ b/apps/router/lib/archive.ts @@ -30,14 +30,14 @@ export const STORE_HEADERS_TIMEOUT_MS = 10_000; type GetOptions = Parameters[1]; export type ArchiveDeps = { get: Getter; headersTimeoutMs?: number }; -// Refusals about the router (credentials, quota, timeouts) stay failures; any other 4xx is about the path asked for. -const ROUTER_SIDE_STATUSES = new Set([401, 403, 408, 429]); +// The statuses the store answers for a key it cannot take (an encoded NUL, an overlong path); every other status stays a failure. +const KEY_REFUSAL_STATUSES = new Set([400, 414]); -/** Whether the store refused the key itself (a malformed path such as one carrying `%00`), so the object is simply not there. */ -function isStoreClientError(error: unknown): boolean { +/** Whether the store refused the requested key itself; the SDK carries the status only in the message. */ +export function isStoreKeyRefusal(error: unknown): boolean { const match = - error instanceof Error ? /Failed to fetch blob: (4\d\d)\b/.exec(error.message) : null; - return match !== null && !ROUTER_SIDE_STATUSES.has(Number(match[1])); + error instanceof Error ? /Failed to fetch blob: (\d{3})\b/.exec(error.message) : null; + return match !== null && KEY_REFUSAL_STATUSES.has(Number(match[1])); } /** @@ -70,9 +70,6 @@ async function readObject( }), timedOut, ]); - } catch (error) { - if (isStoreClientError(error)) return null; - throw error; } finally { clearTimeout(timer); } @@ -263,6 +260,15 @@ export async function readVersionRedirectsText( return new Response(result.stream).text(); } +/** The key as a store that percent-decodes it would read it; null when it does not decode. */ +function decodedKey(key: string): string | null { + try { + return decodeURIComponent(key); + } catch { + return null; + } +} + /** * Serve a request from the private archive. Returns null on a miss, or on a * request whose path this router will not resolve against the store at all, @@ -288,8 +294,10 @@ export async function serveArchive( // changing. if (prefix !== "" && !mapped.key.startsWith(`${prefix}/`)) return null; // The publisher's and build's own bookkeeping objects sit at the prefix root. - const relativeKey = prefix === "" ? mapped.key : mapped.key.slice(prefix.length + 1); - if (relativeKey.startsWith("_") && !relativeKey.includes("/")) return null; + const relativeKey = decodedKey(prefix === "" ? mapped.key : mapped.key.slice(prefix.length + 1)); + if (relativeKey === null || (relativeKey.startsWith("_") && !relativeKey.includes("/"))) { + return null; + } const ifNoneMatch = request.headers.get("if-none-match") ?? undefined; // The read goes through the Blob store's own CDN cache (the SDK's default; diff --git a/apps/router/lib/releases-handler.test.ts b/apps/router/lib/releases-handler.test.ts index 223c9803..6cf385d1 100644 --- a/apps/router/lib/releases-handler.test.ts +++ b/apps/router/lib/releases-handler.test.ts @@ -112,3 +112,17 @@ test("with no schedule at all the answer is a 503 no cache keeps", async () => { assert.equal((await handler()).status, 200); mock.restoreAll(); }); + +test("a schedule that fails validation is never cached or served", async () => { + const error = mock.method(console, "error", () => {}); + try { + const valid = schedule("v2.36.6"); + const rows = valid.rows.map((row) => ({ ...row, releasedAt: "not a date" })); + const handler = createReleasesHandler({ load: async () => ({ ...valid, rows }) }); + const response = await handler(); + assert.equal(response.status, 503); + assert.equal(response.headers.get("cache-control"), "no-store"); + } finally { + error.mock.restore(); + } +}); diff --git a/apps/router/lib/router-hardening.test.ts b/apps/router/lib/router-hardening.test.ts deleted file mode 100644 index 91614cc1..00000000 --- a/apps/router/lib/router-hardening.test.ts +++ /dev/null @@ -1,132 +0,0 @@ -import assert from "node:assert/strict"; -import { mock, test } from "node:test"; -import type { ReleaseSchedule } from "@coder/docs-config"; -import { type ManifestReader, lineKey, parseManifestItems } from "@coder/docs-manifest"; -import { createArchiveHandler } from "./archive-handler.js"; -import { serveArchive } from "./archive.js"; -import { createReleasesHandler } from "./releases-handler.js"; -import config from "../next.config.js"; - -const PREFIX = `versions/2.37/${"a".repeat(40)}`; -const DEPLOYMENT = `https://abc123.private.blob.vercel-storage.com/${PREFIX}`; -const manifest = parseManifestItems({ - [lineKey("2.37")]: { - id: "2.37", - label: "v2.37", - ref: "release/2.37", - sha: "a".repeat(40), - deployment: DEPLOYMENT, - publishedAt: "2026-09-04T10:15:00Z", - }, - mainline: "2.37", -}); -const reader: ManifestReader = { read: async () => ({ manifest, fetchedAt: Date.now() }) }; - -type Getter = (key: string) => Promise; -const object = (body: string, contentType = "text/html; charset=utf-8") => ({ - statusCode: 200, - stream: new Blob([body]).stream(), - blob: { contentType, etag: '"e"', size: body.length }, -}); - -function archiveOf(objects: Record, calls: string[] = []): Getter { - return async (key) => { - calls.push(key); - const body = objects[key]; - return body === undefined ? null : object(body); - }; -} - -test("the publisher's and build's root objects are never served, even with no base path", async () => { - const calls: string[] = []; - const get = archiveOf( - { - [`${PREFIX}/_publish.json`]: "{}", - [`${PREFIX}/_objects.json`]: "{}", - [`${PREFIX}/_redirects.json`]: "[]", - [`${PREFIX}/_next/static/a.js`]: "export {};", - }, - calls, - ); - for (const name of ["_publish.json", "_objects.json", "_redirects.json"]) { - const response = await serveArchive( - { deployment: DEPLOYMENT, path: `/${name}`, versionId: "2.37" }, - new Request(`https://docs.example/${name}`), - { get: get as never }, - ); - assert.equal(response, null, name); - } - assert.deepEqual(calls, []); - const asset = await serveArchive( - { deployment: DEPLOYMENT, path: "/_next/static/a.js", versionId: "2.37" }, - new Request("https://docs.example/_next/static/a.js"), - { get: get as never }, - ); - assert.equal(asset?.status, 200); -}); - -function handlerWith(get: Getter) { - return createArchiveHandler({ getReader: () => reader, get: () => get as never }); -} - -test("a path the store refuses with a client error is a 404, not a 503 with a logged error", async () => { - const error = mock.method(console, "error", () => {}); - try { - const get: Getter = async (key) => { - if (key.includes("bad")) - throw new Error("Vercel Blob: Failed to fetch blob: 400 Bad Request"); - return null; - }; - const response = await handlerWith(get)(new Request("https://docs.example/bad")); - assert.equal(response.status, 404); - assert.equal(error.mock.callCount(), 0); - } finally { - error.mock.restore(); - } -}); - -test("a store refusal that is about the router, not the path, stays a 503", async () => { - const error = mock.method(console, "error", () => {}); - try { - for (const status of ["401 Unauthorized", "403 Forbidden", "429 Too Many Requests"]) { - const get: Getter = async () => { - throw new Error(`Vercel Blob: Failed to fetch blob: ${status}`); - }; - const response = await handlerWith(get)(new Request("https://docs.example/admin")); - assert.equal(response.status, 503, status); - } - } finally { - error.mock.restore(); - } -}); - -const schedule = (releasedAt: string): ReleaseSchedule => ({ - schemaVersion: 1, - generatedAt: "2026-09-30T12:00:00.000Z", - rows: [ - { - minor: "2.36", - status: "stable", - esr: false, - releasedAt, - firstTag: "v2.36.0", - latestTag: "v2.36.6", - }, - ], -}); - -test("a release schedule that fails validation is never served", async () => { - const error = mock.method(console, "error", () => {}); - try { - const handler = createReleasesHandler({ load: async () => schedule("not a date") }); - const response = await handler(); - assert.equal(response.status, 503); - assert.equal(response.headers.get("cache-control"), "no-store"); - } finally { - error.mock.restore(); - } -}); - -test("the image optimizer is off on a router that serves no images of its own", () => { - assert.equal(config.images?.unoptimized, true); -}); From 7f700dcfc725bae4cf9894db11a3dbd95a78b290 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 21 Oct 2026 13:58:19 -0700 Subject: [PATCH 4/8] chore(deps): drop the unrelated source-map-js lockfile bump The sharp bump is the security fix; source-map-js 1.2.2 came along with the lockfile refresh and has no advisory or need behind it, so it is put back to 1.2.1. Assisted-by: AI --- pnpm-lock.yaml | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index aa38dba9..81d6e7ee 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -3408,8 +3408,8 @@ packages: resolution: {integrity: sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ==} engines: {node: '>=10'} - source-map-js@1.2.2: - resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} + source-map-js@1.2.1: + resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} engines: {node: '>=0.10.0'} source-map@0.7.6: @@ -4637,7 +4637,7 @@ snapshots: jiti: 2.7.0 lightningcss: 1.32.0 magic-string: 0.30.21 - source-map-js: 1.2.2 + source-map-js: 1.2.1 tailwindcss: 4.3.3 '@tailwindcss/oxide-android-arm64@4.3.3': @@ -4955,7 +4955,7 @@ snapshots: css-tree@3.2.1: dependencies: mdn-data: 2.27.1 - source-map-js: 1.2.2 + source-map-js: 1.2.1 cssesc@3.0.0: {} @@ -6478,13 +6478,13 @@ snapshots: dependencies: nanoid: 3.3.18 picocolors: 1.1.1 - source-map-js: 1.2.2 + source-map-js: 1.2.1 postcss@8.5.28: dependencies: nanoid: 3.3.18 picocolors: 1.1.1 - source-map-js: 1.2.2 + source-map-js: 1.2.1 property-information@7.2.0: {} @@ -6737,7 +6737,7 @@ snapshots: astral-regex: 2.0.0 is-fullwidth-code-point: 3.0.0 - source-map-js@1.2.2: {} + source-map-js@1.2.1: {} source-map@0.7.6: {} From 5fb989369eaeb1aeedbcf560b8ab0a5f1518b6fb Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 21 Oct 2026 13:58:19 -0700 Subject: [PATCH 5/8] docs(agents): record the review rules on test file names, store errors and tolerant readers Assisted-by: AI --- AGENTS.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index fcfcb896..4a811c9a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -103,10 +103,13 @@ The number after each rule is the PR where it was raised. - Base corpus-shaped tests on real markup from the docs, not simplified examples. (#13, #28) - Back every documented invariant with a test that pins it. (#48, #53, #54) - Run any change that widens strict validation against the real corpus in strict mode before merging. (#50) +- Name a test file after the module it covers (`archive.test.ts`), never after the PR or the batch it came from. (#232) ### Security and content handling - Fail closed: reject ambiguous or unsafe input, and throw when a size or shape can't be determined, instead of assuming it's safe. (#28, #51) +- Map an upstream error to a miss only for the specific statuses known to mean one (an allowlist, never a denylist), and never let such a miss be cached. (#232) +- When a reader tolerates one bad item, it keeps that item's last good value instead of dropping it, and refuses the refresh when nothing good is left for an item the site depends on. (#232) - CSS alone never gates or hides content. If gating is incomplete, say so. (#28, #49) - Surface authoring defects at sync or build time rather than swallowing errors at runtime. (#28, #44) - When scanning HTML, treat raw-text elements (`script`, `style`, `textarea`, `title`) as text, and keep that list the same in every scanner. (#52, #53) From e92d6abb209ee622a8c11355ca486d19b4d289fe Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 21 Oct 2026 15:04:07 -0700 Subject: [PATCH 6/8] feat(docs-manifest): report the keys a reader dropped as malformed A cold isolate drops a malformed item it has no last good value for, while warm isolates keep serving that version from their snapshot. The router could not tell such a miss from a version that never existed, so the edge cached a 404 for a version that is still live elsewhere. The parse now records those keys in manifest.degraded, and namesDegradedVersion says whether a path is under one of them, so the router can keep that miss out of the cache. Assisted-by: AI --- packages/docs-manifest/src/items.test.ts | 10 ++++++ packages/docs-manifest/src/items.ts | 5 ++- packages/docs-manifest/src/route.test.ts | 27 +++++++++++++++- packages/docs-manifest/src/route.ts | 31 ++++++++++++++++++- packages/docs-manifest/src/version-segment.ts | 5 +++ 5 files changed, 75 insertions(+), 3 deletions(-) diff --git a/packages/docs-manifest/src/items.test.ts b/packages/docs-manifest/src/items.test.ts index 64b65038..c1068248 100644 --- a/packages/docs-manifest/src/items.test.ts +++ b/packages/docs-manifest/src/items.test.ts @@ -289,3 +289,13 @@ test("without onInvalidItem, as writers and publishers parse, a malformed item s /line_2-36/, ); }); + +test("with onInvalidItem, the keys dropped for want of a last good value are reported on the manifest", () => { + const previous = parseManifestItems(fixtureItems); + const items = { ...fixtureItems, [lineKey("2.36")]: badLine, [tagKey("2.36.4")]: { id: 1 } }; + const cold = parseManifestItems(items, { onInvalidItem: () => {} }); + assert.deepEqual([...cold.degraded], [lineKey("2.36"), tagKey("2.36.4")]); + const warm = parseManifestItems(items, { onInvalidItem: () => {}, previous }); + assert.deepEqual([...warm.degraded], []); + assert.deepEqual([...parseManifestItems(fixtureItems).degraded], []); +}); diff --git a/packages/docs-manifest/src/items.ts b/packages/docs-manifest/src/items.ts index f4eda3d6..bb24b852 100644 --- a/packages/docs-manifest/src/items.ts +++ b/packages/docs-manifest/src/items.ts @@ -153,6 +153,8 @@ export interface Manifest { support: SupportMatrix; /** The beta banner switch; undefined until written. */ banner: BannerItem | undefined; + /** Keys a reader dropped as malformed with no last good value to keep; empty from a strict parse. */ + degraded: Set; } export function emptyManifest(): Manifest { @@ -163,6 +165,7 @@ export function emptyManifest(): Manifest { mainline: undefined, support: {}, banner: undefined, + degraded: new Set(), }; } @@ -199,7 +202,7 @@ export function parseManifestItems( options: ParseManifestItemsOptions = {}, ): Manifest { const manifest = emptyManifest(); - const dropped = new Set(); + const dropped = manifest.degraded; for (const [key, value] of Object.entries(items)) { try { applyItem(manifest, key, value); diff --git a/packages/docs-manifest/src/route.test.ts b/packages/docs-manifest/src/route.test.ts index 01641130..ace847f5 100644 --- a/packages/docs-manifest/src/route.test.ts +++ b/packages/docs-manifest/src/route.test.ts @@ -2,11 +2,12 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import { fixtureItems, withLayout } from "./test-fixtures.js"; import { CANONICAL_LAYOUT } from "./version-segment.js"; -import { MAINLINE_KEY, lineKey, parseManifestItems } from "./items.js"; +import { MAINLINE_KEY, lineKey, parseManifestItems, tagKey } from "./items.js"; import { classicVersionRedirect, normalizeRouterBasePath, objectPath, + namesDegradedVersion, resolveRoute, } from "./route.js"; @@ -476,3 +477,27 @@ test("a canonical, old beta, unknown, or unsafe form names no classic redirect", assert.equal(classicVersionRedirect(path, manifest, options), null, path); } }); + +test("namesDegradedVersion is true only for a path under a version whose item was dropped", () => { + const items = { + ...fixtureItems, + [lineKey("2.36")]: { ...(fixtureItems[lineKey("2.36")] as object), sha: "x" }, + [tagKey("2.36.4")]: { id: 1 }, + dev_main: { id: "main" }, + }; + const degraded = parseManifestItems(items, { onInvalidItem: () => {} }); + for (const path of [ + "/v2.36/admin/", + "/@2.36/admin/", + "/@2.36", + "/@v2.36.4/x", + "/@main/", + "/beta-docs/@2.36/", + ]) { + const basePath = path.startsWith("/beta-docs") ? "/beta-docs" : ""; + assert.equal(namesDegradedVersion(path, degraded, { basePath }), true, path); + } + for (const path of ["/@2.37/admin/", "/admin/", "/@2.30/", "/"]) { + assert.equal(namesDegradedVersion(path, degraded), false, path); + } +}); diff --git a/packages/docs-manifest/src/route.ts b/packages/docs-manifest/src/route.ts index c237b886..aefcf24a 100644 --- a/packages/docs-manifest/src/route.ts +++ b/packages/docs-manifest/src/route.ts @@ -1,10 +1,12 @@ -import type { Manifest } from "./items.js"; +import { DEV_KEY, LINE_KEY_PREFIX, type Manifest, TAG_KEY_PREFIX } from "./items.js"; import { isUnsafePathSegment, normalizeConfiguredBasePath } from "./path-safety.js"; import { + DEV_ID, isVersionShapedSegment, oldFormsServed, parseClassicVersionPrefix, parseVersionSegment, + segmentNamesVersion, storedVersionSegment, versionSegment, } from "./version-segment.js"; @@ -165,3 +167,30 @@ export function objectPath(pathname: string): ObjectPath { if (isPage) return { kind: "object", key: `${pathname.slice(1)}/index.html` }; return { kind: "object", key: pathname.slice(1) }; } + +/** The version id a line, tag or dev item key stands for; null for any other key. */ +function versionIdOfKey(key: string): string | null { + if (key === DEV_KEY) return DEV_ID; + const prefix = [LINE_KEY_PREFIX, TAG_KEY_PREFIX].find((candidate) => key.startsWith(candidate)); + return prefix ? key.slice(prefix.length).replaceAll("-", ".") : null; +} + +/** + * Whether `pathname` is under a version whose item a reader dropped as + * malformed (`manifest.degraded`). Other isolates may still serve that version + * from their last good copy, so a miss there must not be cached. + */ +export function namesDegradedVersion( + pathname: string, + manifest: Manifest, + options: { basePath?: string } = {}, +): boolean { + if (manifest.degraded.size === 0) return false; + const relative = stripBasePath(pathname, normalizeRouterBasePath(options.basePath)); + if (relative === null) return false; + const first = decodeSegment(relative.split("/")[1] ?? ""); + return [...manifest.degraded].some((key) => { + const id = versionIdOfKey(key); + return id !== null && segmentNamesVersion(first, id); + }); +} diff --git a/packages/docs-manifest/src/version-segment.ts b/packages/docs-manifest/src/version-segment.ts index c7836937..473fb699 100644 --- a/packages/docs-manifest/src/version-segment.ts +++ b/packages/docs-manifest/src/version-segment.ts @@ -112,6 +112,11 @@ export function parseVersionSegment( return parsed && known(manifest, parsed.version) ? parsed : null; } +/** Whether a decoded first segment names version `id`, in its canonical or beta's old `@` form. */ +export function segmentNamesVersion(segment: string, id: string): boolean { + return segment === versionSegment(id) || segment === `${VERSION_SIGIL}${id}`; +} + const CLASSIC_LINE_SEGMENT = /^@v(\d+\.\d+)$/; const CLASSIC_RELEASE_SEGMENT = /^@release%2[Ff](\d+\.\d+)$/; const CLASSIC_RELEASE_BRANCH = "@release"; From 4dc10d957033a6d86d7d240a94df60b1cc9ef489 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 21 Oct 2026 15:04:07 -0700 Subject: [PATCH 7/8] fix(router): refuse keys the store rejects up front, and keep its 400 and 414 failures Treating a store 400 or 414 as a miss meant a broken token, which also gets a 400, would turn every page into a 404, and crawlers read that as the whole site being gone. Keys the store is known to reject are now refused before any call: a decoded key with a control character, or one over the store's 950-character pathname limit. A 400 or 414 from the store is a 503 again. It is logged once a minute with the key's shape (length, segments, percent-escapes) rather than the key, so the log can tell one hostile key from every key failing. A miss for a version this isolate dropped as malformed is now sent with no-store, since other isolates may still serve that version. Assisted-by: AI --- apps/router/lib/archive-handler.test.ts | 48 +++++++++++++++++++++---- apps/router/lib/archive-handler.ts | 45 ++++++++++++++--------- apps/router/lib/archive.test.ts | 16 +++++++++ apps/router/lib/archive.ts | 16 +++++++-- 4 files changed, 100 insertions(+), 25 deletions(-) diff --git a/apps/router/lib/archive-handler.test.ts b/apps/router/lib/archive-handler.test.ts index 6c0d3864..d2877ac7 100644 --- a/apps/router/lib/archive-handler.test.ts +++ b/apps/router/lib/archive-handler.test.ts @@ -1,7 +1,12 @@ import assert from "node:assert/strict"; import { mock, test } from "node:test"; import { DOCS_CONTENT_SECURITY_POLICY, docsContentSecurityPolicy } from "@coder/docs-config"; -import { type ManifestReader, lineKey, parseManifestItems } from "@coder/docs-manifest"; +import { + type ManifestReader, + createManifestReader, + lineKey, + parseManifestItems, +} from "@coder/docs-manifest"; import { createArchiveHandler } from "./archive-handler.js"; import type { Getter } from "./archive.js"; @@ -12,7 +17,7 @@ const MAINLINE_PREFIX = `versions/2.37/${"a".repeat(40)}`; const MAINLINE_DEPLOYMENT = `https://abc123.private.blob.vercel-storage.com/${MAINLINE_PREFIX}`; const SHORT_LIVED = "public, max-age=0, s-maxage=60, stale-while-revalidate=300"; -const manifest = parseManifestItems({ +const items: Record = { [lineKey("2.37")]: { id: "2.37", label: "v2.37", @@ -38,7 +43,8 @@ const manifest = parseManifestItems({ publishedAt: "2026-09-04T10:17:00Z", }, mainline: "2.37", -}); +}; +const manifest = parseManifestItems(items); const reader: ManifestReader = { read: async () => ({ manifest, fetchedAt: Date.now() }) }; type Stored = { body: string; contentType: string; etag: string }; @@ -514,21 +520,24 @@ function refusingGet(status: string, refused: (key: string) => boolean) { return { get, calls }; } -test("a store refusal of the key itself (400, 414) is a miss that is never cached, logged at most once a minute", async () => { +test("a store 400 or 414 on an ordinary key is a 503 that is never cached, logged once a minute with the key's shape", async () => { for (const status of ["400 Bad Request", "414 URI Too Long"]) { const error = mock.method(console, "error", () => {}); try { let now = 0; const { handler } = handlerWith( - refusingGet(status, (key) => key.includes("%00")), + refusingGet(status, () => true), { now: () => now }, ); - const request = () => new Request("https://docs.example/admin%00x/"); + const request = () => new Request("https://docs.example/@2.36/admin/"); const first = await handler(request()); - assert.equal(first.status, 404, status); + assert.equal(first.status, 503, status); assert.equal(first.headers.get("cache-control"), "no-store", status); await handler(request()); assert.equal(error.mock.callCount(), 1, status); + const logged = error.mock.calls[0]?.arguments.map(String).join(" ") ?? ""; + assert.match(logged, /length \d+/, status); + assert.doesNotMatch(logged, /admin/, status); now += 60_000; await handler(request()); assert.equal(error.mock.callCount(), 2, status); @@ -701,3 +710,28 @@ test("the sitemap is served from the mainline at the base path, as XML, and from "the request went to 2.36's own archive, not the mainline's", ); }); + +test("a version a cold reader dropped as malformed gets a not-found page that is never cached", async () => { + const error = mock.method(console, "error", () => {}); + try { + const cold = createManifestReader({ + getAll: async () => ({ + ...items, + [lineKey("2.36")]: { ...(items[lineKey("2.36")] as object), sha: "not-a-sha" }, + }), + onInvalidItem: () => {}, + }); + const { handler } = handlerWith(fakeGet(store), { reader: cold }); + const dropped = await handler(new Request("https://docs.example/@2.36/admin/")); + assert.equal(dropped.status, 404); + assert.equal(dropped.headers.get("cache-control"), "no-store"); + const unknown = await handler(new Request("https://docs.example/@2.30/admin/")); + assert.equal(unknown.status, 404); + assert.equal(unknown.headers.get("cache-control"), SHORT_LIVED); + const mainline = await handler(new Request("https://docs.example/")); + assert.equal(mainline.status, 200); + assert.equal(mainline.headers.get("cache-control"), SHORT_LIVED); + } finally { + error.mock.restore(); + } +}); diff --git a/apps/router/lib/archive-handler.ts b/apps/router/lib/archive-handler.ts index 91558414..81e98138 100644 --- a/apps/router/lib/archive-handler.ts +++ b/apps/router/lib/archive-handler.ts @@ -6,6 +6,7 @@ import { versionSegment, normalizeRouterBasePath, isVersionShapedSegment, + namesDegradedVersion, resolveRoute, } from "@coder/docs-manifest"; import { @@ -45,6 +46,12 @@ export interface ArchiveHandlerDeps { now?: () => number; } +/** A path's shape for a log line, without the path itself. */ +function keyShape(path: string): string { + const encoded = (path.match(/%[0-9A-Fa-f]{2}/g) ?? []).length; + return `length ${path.length}, ${path.split("/").length - 1} segments, ${encoded} percent-escapes`; +} + /** A target `redirectResponse` refuses is answered as a miss, never as a 500. */ export async function redirectOrNotFound( location: string, @@ -140,7 +147,15 @@ export function createArchiveHandler( // The literal root with nothing to serve there (no mainline published, or // a base path that puts the site elsewhere) keeps its placeholder; any // other unresolved path is an unknown version. - if (!target) return pathname === "/" ? placeholderResponse() : notFound(); + if (!target) { + if (pathname === "/") return placeholderResponse(); + const response = await notFound(); + // Other isolates may still serve a version this one dropped as malformed. + if (namesDegradedVersion(pathname, manifest, { basePath })) { + setCacheRule(response.headers, "no-store"); + } + return response; + } // An item written before every version moved to the archive may still name // a Vercel deployment; the router fetches from no such origin, so it is // treated as unpublished. @@ -222,27 +237,25 @@ export function createArchiveHandler( }; try { - let served: Response | null; - let keyRefused = false; - try { - served = await serveArchive(target, request, archiveDeps); - } catch (error) { - if (!isStoreKeyRefusal(error)) throw error; - // A broken token can answer 400 too, so the miss is never cached, and is logged once a minute. - keyRefused = true; - served = null; - if (now() - keyRefusalLoggedAt >= 60_000) { - keyRefusalLoggedAt = now(); - console.error("docs-router: the store refused a key (logged once a minute)", error); - } - } + const served = await serveArchive(target, request, archiveDeps); // A miss, or a path with an unsafe segment, is answered with the // not-found page of the version the path named. const response = served ?? (await movedPage()) ?? (await notFound(target.deployment)); // A store blip must not pin a not-found page at the edge for a page that redirects. - if (probeFailed || keyRefused) setCacheRule(response.headers, "no-store"); + if (probeFailed) setCacheRule(response.headers, "no-store"); return response; } catch (error) { + if (isStoreKeyRefusal(error)) { + // One hostile key and a broken token look alike, so the line carries the key's shape, rate-limited. + if (now() - keyRefusalLoggedAt >= 60_000) { + keyRefusalLoggedAt = now(); + console.error( + `docs-router: the store refused a key (${keyShape(target.path)}; logged once a minute)`, + error, + ); + } + return unavailableResponse(); + } // A store outage or an expired OIDC token must not 500 every archived // path; degrade to the same unavailable response a manifest outage // gets, but log it distinctly so an operator is not sent chasing the diff --git a/apps/router/lib/archive.test.ts b/apps/router/lib/archive.test.ts index 1d732591..ff0195f4 100644 --- a/apps/router/lib/archive.test.ts +++ b/apps/router/lib/archive.test.ts @@ -383,3 +383,19 @@ test("the publisher's and build's root objects are never served, however the nam ); assert.equal(asset?.status, 200); }); + +test("a key the store would refuse (a control character, or over its 950-character limit) is refused before any store call", async () => { + const { get, calls } = fakeGet({}); + const longest = (length: number) => { + const base = archiveKey({ deployment, path: "/.js", versionId: "2.36" }).key.length; + return `/${"a".repeat(length - base)}.js`; + }; + for (const path of ["/a%00b/", "/a%0Ab/", "/a%1Fb.js", "/a%7Fb.js", longest(951)]) { + const target = { deployment, path, versionId: "2.36" }; + assert.equal(await serveArchive(target, new Request("https://docs.example/x"), { get }), null); + } + assert.deepEqual(calls, []); + const target = { deployment, path: longest(950), versionId: "2.36" }; + assert.equal(await serveArchive(target, new Request("https://docs.example/x"), { get }), null); + assert.equal(calls.length, 1); +}); diff --git a/apps/router/lib/archive.ts b/apps/router/lib/archive.ts index 8ecc5771..ff67f9ac 100644 --- a/apps/router/lib/archive.ts +++ b/apps/router/lib/archive.ts @@ -32,8 +32,10 @@ export const STORE_HEADERS_TIMEOUT_MS = 10_000; type GetOptions = Parameters[1]; export type ArchiveDeps = { get: Getter; headersTimeoutMs?: number }; -// The statuses the store answers for a key it cannot take (an encoded NUL, an overlong path); every other status stays a failure. +// The statuses the store answers for a key it cannot take; still failures, since a broken token gets a 400 too. const KEY_REFUSAL_STATUSES = new Set([400, 414]); +// `@vercel/blob`'s MAXIMUM_PATHNAME_LENGTH, which it does not export: no stored key is longer. +const MAX_KEY_LENGTH = 950; /** Whether the store refused the requested key itself; the SDK carries the status only in the message. */ export function isStoreKeyRefusal(error: unknown): boolean { @@ -275,6 +277,10 @@ export async function readVersionRedirectsText( return text === null ? { kind: "too-large", reportedSize: blob.size } : { kind: "text", text }; } +function hasControlCharacter(value: string): boolean { + return [...value].some((char) => char.charCodeAt(0) < 0x20 || char === "\u007f"); +} + /** The key as a store that percent-decodes it would read it; null when it does not decode. */ function decodedKey(key: string): string | null { try { @@ -309,8 +315,14 @@ export async function serveArchive( // changing. if (prefix !== "" && !mapped.key.startsWith(`${prefix}/`)) return null; // The publisher's and build's own bookkeeping objects sit at the prefix root. + // Refused here rather than sent: the store would answer 400 or 414, which the handler treats as a failure. const relativeKey = decodedKey(prefix === "" ? mapped.key : mapped.key.slice(prefix.length + 1)); - if (relativeKey === null || (relativeKey.startsWith("_") && !relativeKey.includes("/"))) { + if ( + relativeKey === null || + (relativeKey.startsWith("_") && !relativeKey.includes("/")) || + hasControlCharacter(relativeKey) || + (prefix === "" ? 0 : prefix.length + 1) + relativeKey.length > MAX_KEY_LENGTH + ) { return null; } From adb6db47cfe20e877b484d67ac7d56dc0098b052 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 21 Oct 2026 15:04:07 -0700 Subject: [PATCH 8/8] docs(agents): prefer refusing known-bad input over mapping upstream errors to misses Assisted-by: AI --- AGENTS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index a11ce356..8b26fee6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -108,7 +108,7 @@ The number after each rule is the PR where it was raised. ### Security and content handling - Fail closed: reject ambiguous or unsafe input, and throw when a size or shape can't be determined, instead of assuming it's safe. (#28, #51) -- Map an upstream error to a miss only for the specific statuses known to mean one (an allowlist, never a denylist), and never let such a miss be cached. (#232) +- Refuse up front the input an upstream is known to reject, and treat its error statuses as failures (503) rather than misses (404): a crawler reads a 404 as gone and a 503 as try again. Never let a response produced from an error be cached. (#232) - When a reader tolerates one bad item, it keeps that item's last good value instead of dropping it, and refuses the refresh when nothing good is left for an item the site depends on. (#232) - CSS alone never gates or hides content. If gating is incomplete, say so. (#28, #49) - Surface authoring defects at sync or build time rather than swallowing errors at runtime. (#28, #44)