From 00a71b06185cdd7b600cfdf626bdb7a30bafcac6 Mon Sep 17 00:00:00 2001 From: Peter White <1788320+peterwhite@users.noreply.github.com> Date: Tue, 1 Dec 2026 10:43:15 +0100 Subject: [PATCH] Add permanent redirect lint warning and public-repo caching rules (#4867) --- .oxlintrc.json | 9 ++ AGENTS.md | 10 ++ scripts/oxlint-caching-plugin.mjs | 195 +++++++++++++++++++++++++ scripts/oxlint-caching-plugin.test.mjs | 75 ++++++++++ 4 files changed, 289 insertions(+) create mode 100644 scripts/oxlint-caching-plugin.mjs create mode 100644 scripts/oxlint-caching-plugin.test.mjs diff --git a/.oxlintrc.json b/.oxlintrc.json index f77105a94..58f6e8f99 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -66,6 +66,15 @@ "use-isnan": "error", "valid-typeof": "error" }, + "overrides": [ + { + "files": ["packages/gitbook/src/**"], + "jsPlugins": ["./scripts/oxlint-caching-plugin.mjs"], + "rules": { + "gitbook-cache/no-unbounded-permanent-redirect": "warn" + } + } + ], "ignorePatterns": [ "**/node_modules/**", "**/dist/**", diff --git a/AGENTS.md b/AGENTS.md index 5f14baea7..203d5d505 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,5 +1,9 @@ # AGENTS Instructions +## Public repository + +This repository is public. Never disclose information from outside this repository in code, comments, documentation, tests, commit messages, or pull request descriptions. That includes internal services, private endpoints or routes, infrastructure details from private repositories, and customer names or URLs. + ## Commands ```bash @@ -79,6 +83,12 @@ When it counts: 1. Warn the engineer before the PR is opened: "This changes customers' live sites. Have the support and sales leads agreed the rollout and announcement?" 2. Suggest a flag or staged rollout if there isn't one, so it can ship dark and be turned on after the notice goes out. +## Caching and redirects + +- **Always use the provided API endpoint from env.** Route API calls through the configured API endpoint rather than hardcoding or bypassing it. +- **Keep `middleware.ts` light.** Do not add published-content or redirect API lookups to every request in middleware when a cheap URL normalization or downstream route can handle it. +- **Bound `Cache-Control` on GitBook-generated permanent redirects (`301`/`308`).** For our own redirects (such as trailing-slash normalization), set an explicit bounded `Cache-Control` (for example `private, max-age=86400`, or `private, no-store` when query parameters are present) so browsers and CDNs do not cache redirect loops indefinitely. Do not add a `Cache-Control` cap to user-defined permanent redirects, since that lifetime is the user's choice. Warned for `Response`/`NextResponse` constructors by Oxlint (`gitbook-cache/no-unbounded-permanent-redirect`). + ## Bumping Next.js or OpenNext Type checks and unit tests miss runtime regressions: OpenNext 4.1.15 changed the composable cache key format, and every `'use cache'` call silently missed for days. Before committing a bump of `next`, `@opennextjs/aws` or `@opennextjs/cloudflare`, run both runtimes locally from `packages/gitbook`: diff --git a/scripts/oxlint-caching-plugin.mjs b/scripts/oxlint-caching-plugin.mjs new file mode 100644 index 000000000..32de57110 --- /dev/null +++ b/scripts/oxlint-caching-plugin.mjs @@ -0,0 +1,195 @@ +const PERMANENT_REDIRECT_STATUSES = new Set([301, 308]); +const BOUNDED_CACHE_CONTROL_PATTERN = /\b(max-age\s*=\s*\d+|s-maxage\s*=\s*\d+|no-store)\b/i; +const MESSAGE = + "GitBook-generated permanent redirects (301/308) should set a bounded Cache-Control header (e.g. 'private, max-age=86400' or 'private, no-store') so browsers and CDNs do not cache redirect loops indefinitely. User-defined permanent redirects may omit it."; + +function getPropertyName(node) { + if (!node) { + return null; + } + if (node.type === 'Identifier') { + return node.name; + } + if (node.type === 'Literal' && typeof node.value === 'string') { + return node.value; + } + return null; +} + +function unwrapExpression(node) { + let current = node; + while (current) { + if ( + current.type === 'ChainExpression' || + current.type === 'ParenthesizedExpression' || + current.type === 'TSAsExpression' || + current.type === 'TSTypeAssertion' || + current.type === 'TSNonNullExpression' || + current.type === 'TSSatisfiesExpression' + ) { + current = current.expression; + continue; + } + return current; + } + return current; +} + +function expressionContainsPermanentStatus(node) { + const current = unwrapExpression(node); + if (!current) { + return false; + } + if (current.type === 'Literal' && typeof current.value === 'number') { + return PERMANENT_REDIRECT_STATUSES.has(current.value); + } + if (current.type === 'ConditionalExpression') { + return ( + expressionContainsPermanentStatus(current.consequent) || + expressionContainsPermanentStatus(current.alternate) + ); + } + return false; +} + +function getObjectProperty(objectNode, targetName) { + if (!objectNode || objectNode.type !== 'ObjectExpression') { + return null; + } + const lowerTarget = targetName.toLowerCase(); + for (const prop of objectNode.properties) { + if (prop.type !== 'Property') { + continue; + } + const name = getPropertyName(prop.key); + if (name && name.toLowerCase() === lowerTarget) { + return prop; + } + } + return null; +} + +function isBoundedCacheControlValue(valueNode) { + const current = unwrapExpression(valueNode); + if (!current) { + return false; + } + if (current.type === 'Literal') { + return ( + typeof current.value === 'string' && BOUNDED_CACHE_CONTROL_PATTERN.test(current.value) + ); + } + if (current.type === 'TemplateLiteral') { + const raw = current.quasis.map((q) => q.value.raw).join('0'); + return BOUNDED_CACHE_CONTROL_PATTERN.test(raw); + } + // Dynamic variables or helpers are allowed when an explicit Cache-Control entry is present. + return true; +} + +function objectExpressionHasBoundedCacheControl(objectNode) { + for (const prop of objectNode.properties) { + if (prop.type === 'SpreadElement') { + return true; + } + if (prop.type !== 'Property') { + continue; + } + const name = getPropertyName(prop.key); + if (name && name.toLowerCase() === 'cache-control') { + return isBoundedCacheControlValue(prop.value); + } + } + return false; +} + +function headersObjectHasCacheControl(headersNode) { + const current = unwrapExpression(headersNode); + if (!current) { + return false; + } + if (current.type === 'Identifier' && current.name === 'undefined') { + return false; + } + if (current.type === 'Literal' && current.value === null) { + return false; + } + if (current.type === 'ObjectExpression') { + return objectExpressionHasBoundedCacheControl(current); + } + if ( + current.type === 'NewExpression' && + current.callee.type === 'Identifier' && + current.callee.name === 'Headers' + ) { + if (current.arguments.length === 0) { + return false; + } + return headersObjectHasCacheControl(current.arguments[0]); + } + // Non-literal Headers instances or variables may set Cache-Control dynamically. + return true; +} + +function checkResponseInit(context, reportNode, initNode) { + if (!initNode || initNode.type !== 'ObjectExpression') { + return; + } + const statusProp = getObjectProperty(initNode, 'status'); + if (!statusProp || !expressionContainsPermanentStatus(statusProp.value)) { + return; + } + const headersProp = getObjectProperty(initNode, 'headers'); + if (!headersProp || !headersObjectHasCacheControl(headersProp.value)) { + context.report({ node: reportNode, message: MESSAGE }); + } +} + +export default { + meta: { + name: 'gitbook-cache', + }, + rules: { + 'no-unbounded-permanent-redirect': { + create(context) { + return { + NewExpression(node) { + if (node.callee.type !== 'Identifier') { + return; + } + if ( + node.callee.name !== 'Response' && + node.callee.name !== 'NextResponse' + ) { + return; + } + checkResponseInit(context, node, node.arguments[1]); + }, + CallExpression(node) { + if ( + node.callee.type !== 'MemberExpression' || + node.callee.computed || + node.callee.object.type !== 'Identifier' + ) { + return; + } + const objName = node.callee.object.name; + const propName = getPropertyName(node.callee.property); + if ( + propName !== 'redirect' || + (objName !== 'Response' && objName !== 'NextResponse') + ) { + return; + } + const secondArg = node.arguments[1]; + if (expressionContainsPermanentStatus(secondArg)) { + context.report({ node, message: MESSAGE }); + return; + } + checkResponseInit(context, node, secondArg); + }, + }; + }, + }, + }, +}; diff --git a/scripts/oxlint-caching-plugin.test.mjs b/scripts/oxlint-caching-plugin.test.mjs new file mode 100644 index 000000000..9f3b60df4 --- /dev/null +++ b/scripts/oxlint-caching-plugin.test.mjs @@ -0,0 +1,75 @@ +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import test from 'node:test'; + +const REPO_ROOT = path.resolve(import.meta.dirname, '..'); +const OXLINT_BIN = path.join(REPO_ROOT, 'node_modules/.bin/oxlint'); +const PLUGIN_PATH = path.join(import.meta.dirname, 'oxlint-caching-plugin.mjs'); + +function runLint(source) { + const dir = mkdtempSync(path.join(tmpdir(), 'oxlint-gbo-caching-test-')); + try { + const configPath = path.join(dir, 'oxlint.json'); + const filePath = path.join(dir, 'sample.ts'); + writeFileSync( + configPath, + JSON.stringify({ + jsPlugins: [PLUGIN_PATH], + rules: { + 'gitbook-cache/no-unbounded-permanent-redirect': 'error', + }, + }) + ); + writeFileSync(filePath, source); + const result = spawnSync(OXLINT_BIN, ['-c', configPath, filePath], { + encoding: 'utf8', + }); + return { + status: result.status, + output: `${result.stdout}\n${result.stderr}`, + }; + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + +test('no-unbounded-permanent-redirect flags 301/308 redirects missing a bounded Cache-Control', () => { + const bad = runLint(` + export function f(permanent: boolean) { + const a = Response.redirect('https://example.com', 308); + const b = new Response(null, { status: 301, headers: { Location: '/x' } }); + const c = new Response(null, { status: permanent ? 308 : 307, headers: { Location: '/x' } }); + const d = new Response(null, { status: 308, headers: { Location: '/x', 'Cache-Control': 'private' } }); + const e = new Response(null, { status: 308, headers: undefined }); + const g = new Response(null, { status: 308, headers: new Headers({ Location: '/x' }) }); + return [a, b, c, d, e, g]; + } + `); + assert.equal(bad.status, 1); + assert.equal( + (bad.output.match(/gitbook-cache\(no-unbounded-permanent-redirect\)/g) ?? []).length, + 6 + ); +}); + +test('no-unbounded-permanent-redirect allows bounded 308 redirects and temporary redirects', () => { + const ok = runLint(` + export function f() { + const a = Response.redirect('https://example.com', 302); + const b = new Response(null, { + status: 308, + headers: { Location: '/x', 'Cache-Control': 'private, max-age=86400' }, + }); + const c = new Response(null, { + status: 308, + headers: new Headers({ Location: '/x', 'Cache-Control': 'private, no-store' }), + }); + const d = new Response(null, { status: 307, headers: { Location: '/x' } }); + return [a, b, c, d]; + } + `); + assert.equal(ok.status, 0); +});