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
+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);
});