Add permanent redirect lint warning and public-repo caching rules (#4867)

This commit is contained in:
Peter White
2026-12-01 10:43:15 +01:00
committed by GitHub
parent f648e55ed6
commit 00a71b0618
4 changed files with 289 additions and 0 deletions
+9
View File
@@ -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/**",
+10
View File
@@ -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`:
+195
View File
@@ -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);
},
};
},
},
},
};
+75
View File
@@ -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);
});