From dc1dc5cc1310484a772c7f2e5db3b5b824dcfab9 Mon Sep 17 00:00:00 2001 From: Christian Mejlak Date: Fri, 4 Dec 2026 14:04:56 +0100 Subject: [PATCH 01/20] check-redirects: test that a removed docs URL needs a redirect A PR that removes a docs page must add a redirect, or readers get a 404. Pages under the CLI reference are exempt, because the site redirects a dead reference URL to its nearest parent page, but the reference root is not. An unreadable manifest is reported on its own: invalid JSON, or JSON in a shape the site can't read. --- .../scripts/check-redirects/rules.test.mjs | 191 ++++++++++++++++++ 1 file changed, 191 insertions(+) create mode 100644 .github/scripts/check-redirects/rules.test.mjs diff --git a/.github/scripts/check-redirects/rules.test.mjs b/.github/scripts/check-redirects/rules.test.mjs new file mode 100644 index 00000000..a629ebdb --- /dev/null +++ b/.github/scripts/check-redirects/rules.test.mjs @@ -0,0 +1,191 @@ +import assert from 'node:assert/strict' +import { describe, it } from 'node:test' + +import { checkRedirects, pageUrl, readManifest } from './rules.mjs' + +const revision = (manifest) => ({ + manifestText: + typeof manifest === 'string' ? manifest : JSON.stringify(manifest, null, 2), + paths: new Set(), + mdx: new Map() +}) + +const page = (path) => ({ title: path, path }) + +describe('readManifest', () => { + it('accepts a heading route without a path', () => { + const { manifest, problem } = readManifest( + JSON.stringify({ + routes: [{ title: 'Platform', routes: [page('/platform/README.mdx')] }] + }) + ) + + assert.equal(problem, undefined) + assert.equal(manifest.routes.length, 1) + }) + + const unreadable = [ + ['a missing manifest', null, /missing/], + ['invalid JSON', '{ "routes": [ }', /isn't valid JSON/], + ['a top level that is not an object', '[]', /top level/], + ['a missing routes array', '{}', /routes/], + ['routes that are an object', '{ "routes": {} }', /routes/], + [ + 'a route that is not an object', + '{ "routes": ["/foo.mdx"] }', + /routes\[0\]/ + ], + [ + 'a path that is not a string', + '{ "routes": [{ "path": 1 }] }', + /routes\[0\]\.path/ + ], + [ + 'a path without a leading slash', + '{ "routes": [{ "path": "foo.mdx" }] }', + /routes\[0\]\.path/ + ], + [ + 'a path without .mdx', + '{ "routes": [{ "path": "/foo.md" }] }', + /routes\[0\]\.path/ + ], + [ + 'nested routes that are not an array', + '{ "routes": [{ "title": "Platform", "routes": {} }] }', + /routes\[0\]\.routes/ + ], + [ + 'a bad path in a nested route', + '{ "routes": [{ "title": "Platform", "routes": [{ "path": 2 }] }] }', + /routes\[0\]\.routes\[0\]\.path/ + ] + ] + + for (const [name, text, location] of unreadable) { + it(`rejects ${name}`, () => { + const { manifest, problem } = readManifest(text) + + assert.equal(manifest, undefined) + assert.match(problem, location) + }) + } +}) + +describe('pageUrl', () => { + const urls = [ + ['/README.mdx', '/docs'], + ['/foo.mdx', '/docs/foo'], + ['/foo/README.mdx', '/docs/foo'], + ['/step-cli/reference/ca/README.mdx', '/docs/step-cli/reference/ca'] + ] + + for (const [path, url] of urls) { + it(`maps ${path} to ${url}`, () => { + assert.equal(pageUrl(path), url) + }) + } +}) + +describe('checkRedirects', () => { + describe('R1', () => { + it('fails a removed page and offers a redirect to paste', () => { + const base = revision({ routes: [page('/foo.mdx'), page('/bar.mdx')] }) + const head = revision({ routes: [page('/bar.mdx')] }) + + const [violation, ...others] = checkRedirects({ base, head }) + + assert.deepEqual(others, []) + assert.equal(violation.rule, 'R1') + assert.equal(violation.severity, 'error') + assert.equal(violation.file, 'manifest.json') + assert.match(violation.message, /\/docs\/foo/) + assert.match( + violation.message, + /\{ "source": "\/docs\/foo", "destination": "\/docs\/…" \}/ + ) + }) + + it('passes when every page still works', () => { + const base = revision({ routes: [page('/foo.mdx')] }) + const head = revision({ routes: [page('/foo.mdx'), page('/bar.mdx')] }) + + assert.deepEqual(checkRedirects({ base, head }), []) + }) + + it('passes when a page moves to a README at the same URL', () => { + const base = revision({ routes: [page('/foo.mdx')] }) + const head = revision({ routes: [page('/foo/README.mdx')] }) + + assert.deepEqual(checkRedirects({ base, head }), []) + }) + + it('exempts a removed page under the CLI reference', () => { + const reference = { + title: 'Reference', + path: '/step-cli/reference/README.mdx', + isStepReference: true + } + const base = revision({ + routes: [ + { ...reference, routes: [page('/step-cli/reference/ca/README.mdx')] } + ] + }) + const head = revision({ routes: [{ ...reference, routes: [] }] }) + + assert.deepEqual(checkRedirects({ base, head }), []) + }) + + it('keeps the reference root covered', () => { + const base = revision({ + routes: [ + page('/step-cli/README.mdx'), + page('/step-cli/reference/README.mdx') + ] + }) + const head = revision({ routes: [page('/step-cli/README.mdx')] }) + + const violations = checkRedirects({ base, head }) + + assert.equal(violations.length, 1) + assert.equal(violations[0].rule, 'R1') + assert.match(violations[0].message, /\/docs\/step-cli\/reference /) + }) + }) + + describe('an unreadable manifest', () => { + it('reports only the unreadable head manifest', () => { + const base = revision({ routes: [page('/foo.mdx')] }) + const head = revision('{ "routes": [ }') + + const violations = checkRedirects({ base, head }) + + assert.equal(violations.length, 1) + assert.equal(violations[0].severity, 'error') + assert.equal(violations[0].file, 'manifest.json') + assert.match(violations[0].message, /isn't valid JSON/) + }) + + it('points at the line of a JSON syntax error', () => { + const base = revision({ routes: [page('/foo.mdx')] }) + const head = revision('{\n "routes": [],\n}\n') + + const [violation] = checkRedirects({ base, head }) + + assert.equal(violation.line, 3) + }) + + it('skips R1 and warns when the base manifest is unreadable', () => { + const base = revision('{ "routes": [ }') + const head = revision({ routes: [] }) + + const violations = checkRedirects({ base, head }) + + assert.deepEqual( + violations.map(({ severity }) => severity), + ['warning'] + ) + assert.match(violations[0].message, /skipped/) + }) + }) +}) From 70da41db29cb08ac2f333cb3c4003f2fd0fb0449 Mon Sep 17 00:00:00 2001 From: Christian Mejlak Date: Fri, 4 Dec 2026 14:05:40 +0100 Subject: [PATCH 02/20] check-redirects: fail a removed docs URL without a redirect checkRedirects compares a PR's head with its base. A page URL that works on the base and not on the head is an error with a redirect entry to paste, unless it is under the CLI reference. readManifest rejects JSON smallstep.com can't walk, and the error names the bad route. --- .github/scripts/check-redirects/rules.mjs | 169 ++++++++++++++++++++++ 1 file changed, 169 insertions(+) create mode 100644 .github/scripts/check-redirects/rules.mjs diff --git a/.github/scripts/check-redirects/rules.mjs b/.github/scripts/check-redirects/rules.mjs new file mode 100644 index 00000000..f8f43dd5 --- /dev/null +++ b/.github/scripts/check-redirects/rules.mjs @@ -0,0 +1,169 @@ +/** + * @typedef {object} Revision + * @property {string | null} manifestText - manifest.json, or null when it is missing + * @property {Set} paths - every file at the revision, relative to the repo root + * @property {Map} mdx - the text of every .mdx file, by path + * + * @typedef {object} Violation + * @property {string} rule - R1 to R9b, or manifest + * @property {string} key - the rule and what it is about, compared between head and base + * @property {'error' | 'warning'} severity + * @property {boolean} introduced - false when the problem is already on the base + * @property {string} file - where to annotate it + * @property {number} [line] + * @property {string} message - what is wrong and how to fix it + */ + +const REFERENCE_PREFIX = '/docs/step-cli/reference/' + +/** + * Compares a PR's head with its base. + * + * @param {{ base: Revision, head: Revision }} revisions + * @returns {Violation[]} + */ +export function checkRedirects({ base, head }) { + const headRead = readManifest(head.manifestText) + if (headRead.problem) { + return [ + { + rule: 'manifest', + key: 'manifest', + severity: 'error', + introduced: true, + file: 'manifest.json', + line: headRead.line, + message: `${headRead.problem}. No other rule runs until manifest.json can be read.` + } + ] + } + + const baseRead = readManifest(base.manifestText) + if (baseRead.problem) { + return [ + { + rule: 'manifest', + key: 'base manifest', + severity: 'warning', + introduced: false, + file: 'manifest.json', + message: `The base manifest.json is unreadable (${baseRead.problem}), so R1 and R9 were skipped and every other finding is a warning.` + } + ] + } + + return removedUrls(baseRead.manifest, headRead.manifest) +} + +/** + * Parses manifest.json and checks the shape smallstep.com reads. + * + * @param {string | null} text - manifest.json, or null when it is missing + * @returns {{ manifest: object, problem?: undefined } | { problem: string, line?: number }} + */ +export function readManifest(text) { + if (text === null) return { problem: 'manifest.json is missing' } + + let manifest + try { + manifest = JSON.parse(text) + } catch (err) { + return { + problem: `manifest.json isn't valid JSON: ${err.message}`, + line: syntaxErrorLine(err, text) + } + } + + const problem = shapeProblem(manifest) + return problem ? { problem } : { manifest } +} + +/** + * The URL smallstep.com serves a manifest path at, as its convertPathToSlug + * maps it. + * + * @param {string} path - A manifest path such as /step-ca/README.mdx + * @returns {string} A URL without a trailing slash + * + * @example + * pageUrl('/step-ca/README.mdx') // => '/docs/step-ca' + */ +export function pageUrl(path) { + const segments = path + .replace(/\.mdx$/, '') + .replace(/^\//, '') + .split('/') + .filter((segment) => segment !== 'README') + return ['/docs', ...segments].join('/') +} + +function removedUrls(baseManifest, headManifest) { + const working = workingUrls(headManifest) + return [...workingUrls(baseManifest)] + .filter((url) => !working.has(url) && !url.startsWith(REFERENCE_PREFIX)) + .map((url) => ({ + rule: 'R1', + key: `R1 ${url}`, + severity: 'error', + introduced: true, + file: 'manifest.json', + message: `${url} works before this change but not after it. Add a redirect to "redirects" in manifest.json: { "source": "${url}", "destination": "/docs/…" }` + })) +} + +function workingUrls(manifest) { + return new Set(pageUrls(manifest.routes).keys()) +} + +function pageUrls(routes, urls = new Map()) { + for (const route of routes) { + if (route.path) { + const url = pageUrl(route.path) + urls.set(url, [...(urls.get(url) ?? []), route.path]) + } + if (route.routes) pageUrls(route.routes, urls) + } + return urls +} + +// smallstep.com walks routes without checking them, so a manifest in any other +// shape takes down every docs page. +function shapeProblem(manifest) { + if (!isObject(manifest)) { + return 'the top level of manifest.json must be an object' + } + if (!Array.isArray(manifest.routes)) return '`routes` must be an array' + return routesProblem(manifest.routes, 'routes') +} + +function routesProblem(routes, location) { + for (const [index, route] of routes.entries()) { + const at = `${location}[${index}]` + if (!isObject(route)) return `${at} must be an object` + if ('path' in route && !isPagePath(route.path)) { + return `${at}.path must be a string that starts with / and ends in .mdx` + } + if ('routes' in route) { + if (!Array.isArray(route.routes)) return `${at}.routes must be an array` + const problem = routesProblem(route.routes, `${at}.routes`) + if (problem) return problem + } + } + return null +} + +const isObject = (value) => + typeof value === 'object' && value !== null && !Array.isArray(value) + +// The site finds a page by comparing /.mdx with each path. +const isPagePath = (path) => + typeof path === 'string' && path.startsWith('/') && path.endsWith('.mdx') + +// V8 names the line in newer releases and only the offset in older ones. +function syntaxErrorLine(err, text) { + const line = err.message.match(/\(line (\d+) column \d+\)/) + if (line) return Number(line[1]) + const position = err.message.match(/at position (\d+)/) + if (position) return text.slice(0, Number(position[1])).split('\n').length + return undefined +} From b78736ff1880d3ab37777ab83a2a39fc616e44f4 Mon Sep 17 00:00:00 2001 From: Christian Mejlak Date: Fri, 4 Dec 2026 14:06:56 +0100 Subject: [PATCH 03/20] check-redirects: test the command line against git revisions The check compares a head, the working tree by default, with the merge base of --base and that head, so a branch that is behind main isn't blamed for main's changes. In GitHub Actions it prints annotations and writes the run summary: errors first, then new warnings, then warnings already on the base. Elsewhere it prints a plain list. It exits 1 on any error and 2 when it can't read a revision. --- .github/scripts/check-redirects/cli.test.mjs | 195 ++++++++++++++++++ .../scripts/check-redirects/report.test.mjs | 99 +++++++++ 2 files changed, 294 insertions(+) create mode 100644 .github/scripts/check-redirects/cli.test.mjs create mode 100644 .github/scripts/check-redirects/report.test.mjs diff --git a/.github/scripts/check-redirects/cli.test.mjs b/.github/scripts/check-redirects/cli.test.mjs new file mode 100644 index 00000000..5f9bca8e --- /dev/null +++ b/.github/scripts/check-redirects/cli.test.mjs @@ -0,0 +1,195 @@ +import assert from 'node:assert/strict' +import { execFileSync, spawnSync } from 'node:child_process' +import { + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync +} from 'node:fs' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { after, describe, it } from 'node:test' +import { fileURLToPath } from 'node:url' + +import { readCommit, readWorkingTree } from '../check-redirects.mjs' + +const CLI = fileURLToPath(new URL('../check-redirects.mjs', import.meta.url)) + +const page = (path) => ({ title: path, path }) +const manifest = (...paths) => + JSON.stringify({ routes: paths.map(page) }, null, 2) + '\n' + +const directories = [] +after(() => { + for (const dir of directories) rmSync(dir, { recursive: true, force: true }) +}) + +const git = (dir, ...args) => + execFileSync('git', args, { cwd: dir, encoding: 'utf8' }) + +// Writes files (null deletes one) without committing them. +const write = (dir, files) => { + for (const [path, text] of Object.entries(files)) { + const file = join(dir, path) + if (text === null) { + rmSync(file) + } else { + mkdirSync(dirname(file), { recursive: true }) + writeFileSync(file, text) + } + } +} + +const commit = (dir, files) => { + write(dir, files) + git(dir, 'add', '--all') + git(dir, 'commit', '--quiet', '--message', 'change') +} + +const repo = (files) => { + const dir = mkdtempSync(join(tmpdir(), 'check-redirects-')) + directories.push(dir) + git(dir, 'init', '--quiet', '--initial-branch', 'main') + git(dir, 'config', 'user.name', 'Test') + git(dir, 'config', 'user.email', 'test@example.com') + git(dir, 'config', 'commit.gpgsign', 'false') + commit(dir, files) + return dir +} + +const twoPages = { + 'manifest.json': manifest('/foo.mdx', '/bar.mdx'), + 'foo.mdx': '# Foo\n', + 'bar.mdx': '# Bar\n' +} + +const run = (dir, args, env = {}) => + spawnSync(process.execPath, [CLI, ...args], { + cwd: dir, + encoding: 'utf8', + env: { ...process.env, GITHUB_ACTIONS: '', GITHUB_STEP_SUMMARY: '', ...env } + }) + +describe('check-redirects.mjs', () => { + it('fails a branch that removes a page, with an annotation and a summary', () => { + const dir = repo(twoPages) + git(dir, 'switch', '--quiet', '--create', 'feature') + commit(dir, { 'manifest.json': manifest('/bar.mdx'), 'foo.mdx': null }) + const summaryDir = mkdtempSync(join(tmpdir(), 'check-redirects-summary-')) + directories.push(summaryDir) + const summaryFile = join(summaryDir, 'summary.md') + + const result = run(dir, ['--base', 'main', '--head', 'feature'], { + GITHUB_ACTIONS: 'true', + GITHUB_STEP_SUMMARY: summaryFile + }) + + assert.equal(result.status, 1) + assert.match( + result.stdout, + /^::error file=manifest\.json,title=R1::\/docs\/foo works before/m + ) + assert.match( + readFileSync(summaryFile, 'utf8'), + /\{ "source": "\/docs\/foo", "destination": "\/docs\/…" \}/ + ) + }) + + it('passes a branch that keeps every page', () => { + const dir = repo(twoPages) + git(dir, 'switch', '--quiet', '--create', 'feature') + commit(dir, { + 'manifest.json': manifest('/foo.mdx', '/bar.mdx', '/baz.mdx'), + 'baz.mdx': '# Baz\n' + }) + + const result = run(dir, ['--base', 'main', '--head', 'feature']) + + assert.equal(result.status, 0) + assert.match(result.stdout, /0 errors/) + }) + + it('checks the working tree when no head is given', () => { + const dir = repo(twoPages) + write(dir, { 'manifest.json': manifest('/bar.mdx') }) + + const result = run(dir, ['--base', 'main']) + + assert.equal(result.status, 1) + assert.match(result.stdout, /\/docs\/foo/) + }) + + it('compares a branch that is behind main with their merge base', () => { + const dir = repo(twoPages) + git(dir, 'switch', '--quiet', '--create', 'feature') + commit(dir, { + 'manifest.json': manifest('/foo.mdx', '/bar.mdx', '/baz.mdx'), + 'baz.mdx': '# Baz\n' + }) + git(dir, 'switch', '--quiet', 'main') + commit(dir, { + 'manifest.json': manifest('/foo.mdx', '/bar.mdx', '/qux.mdx'), + 'qux.mdx': '# Qux\n' + }) + + const result = run(dir, ['--base', 'main', '--head', 'feature']) + + assert.equal(result.status, 0) + }) + + it('prints a plain list outside GitHub Actions', () => { + const dir = repo(twoPages) + write(dir, { 'manifest.json': manifest('/bar.mdx') }) + + const result = run(dir, ['--base', 'main']) + + assert.doesNotMatch(result.stdout, /^::/m) + assert.match(result.stdout, /^error R1 manifest\.json: \/docs\/foo/m) + }) + + it('exits 2 when a revision does not exist', () => { + const dir = repo(twoPages) + + const result = run(dir, ['--base', 'no-such-branch']) + + assert.equal(result.status, 2) + assert.match(result.stderr, /no-such-branch/) + }) +}) + +describe('readCommit', () => { + it('reads the manifest, the file list and every .mdx file of a commit', () => { + const dir = repo({ ...twoPages, 'graphics/logo.svg': '' }) + + const revision = readCommit(dir, 'main') + + assert.equal(revision.manifestText, twoPages['manifest.json']) + assert.deepEqual([...revision.paths].sort(), [ + 'bar.mdx', + 'foo.mdx', + 'graphics/logo.svg', + 'manifest.json' + ]) + assert.deepEqual([...revision.mdx].sort(), [ + ['bar.mdx', '# Bar\n'], + ['foo.mdx', '# Foo\n'] + ]) + }) +}) + +describe('readWorkingTree', () => { + it('includes untracked files and leaves out deleted ones', () => { + const dir = repo(twoPages) + write(dir, { 'new.mdx': '# New\n', 'foo.mdx': null }) + + const revision = readWorkingTree(dir) + + assert.deepEqual([...revision.paths].sort(), [ + 'bar.mdx', + 'manifest.json', + 'new.mdx' + ]) + assert.equal(revision.mdx.get('new.mdx'), '# New\n') + }) +}) diff --git a/.github/scripts/check-redirects/report.test.mjs b/.github/scripts/check-redirects/report.test.mjs new file mode 100644 index 00000000..465bffb4 --- /dev/null +++ b/.github/scripts/check-redirects/report.test.mjs @@ -0,0 +1,99 @@ +import assert from 'node:assert/strict' +import { describe, it } from 'node:test' + +import { annotations, plainText, summary } from './report.mjs' + +const violation = (overrides) => ({ + rule: 'R1', + key: 'R1 /docs/foo', + severity: 'error', + introduced: true, + file: 'manifest.json', + message: '/docs/foo works before this change but not after it.', + ...overrides +}) + +const removedPage = violation() +const newWarning = violation({ + rule: 'R9b', + key: 'R9b a.mdx /docs/gone', + severity: 'warning', + file: 'a.mdx', + line: 3, + message: 'a.mdx links to /docs/gone, which is not a page.' +}) +const oldWarning = violation({ + rule: 'R9b', + key: 'R9b b.mdx /docs/old', + severity: 'warning', + introduced: false, + file: 'b.mdx', + line: 7, + message: 'b.mdx links to /docs/old, which is not a page.' +}) + +describe('annotations', () => { + it('writes a workflow command per violation', () => { + assert.deepEqual(annotations([removedPage, newWarning]), [ + '::error file=manifest.json,title=R1::/docs/foo works before this change but not after it.', + '::warning file=a.mdx,line=3,title=R9b::a.mdx links to /docs/gone, which is not a page.' + ]) + }) + + it('lists errors, then new warnings, then warnings already on the base', () => { + const lines = annotations([oldWarning, newWarning, removedPage]) + + assert.deepEqual( + lines.map((line) => line.match(/title=(\w+)/)[1]), + ['R1', 'R9b', 'R9b'] + ) + assert.match(lines[1], /file=a\.mdx/) + }) + + it('escapes the message and the properties', () => { + const [line] = annotations([ + violation({ file: 'a:b,c.mdx', message: '100% broken\nsecond line\r' }) + ]) + + assert.equal( + line, + '::error file=a%3Ab%2Cc.mdx,title=R1::100%25 broken%0Asecond line%0D' + ) + }) +}) + +describe('summary', () => { + it('groups errors, new warnings and warnings already on the base', () => { + const markdown = summary([oldWarning, newWarning, removedPage]) + + assert.match(markdown, /1 error, 1 new warning, 1 existing warning/) + const headings = markdown.match(/^### .+$/gm) + assert.deepEqual(headings, [ + '### Errors', + '### New warnings', + '### Warnings already on the base branch' + ]) + assert.match( + markdown, + /- \*\*R9b\*\* `a\.mdx:3`: a\.mdx links to \/docs\/gone/ + ) + assert.match(markdown, /- \*\*R1\*\* `manifest\.json`: \/docs\/foo/) + }) + + it('says when there is nothing to report', () => { + assert.match(summary([]), /No problems found\./) + }) +}) + +describe('plainText', () => { + it('prints the counts and one line per violation', () => { + assert.equal( + plainText([newWarning, removedPage]), + [ + 'Redirect check: 1 error, 1 new warning, 0 existing warnings', + 'error R1 manifest.json: /docs/foo works before this change but not after it.', + 'warning R9b a.mdx:3: a.mdx links to /docs/gone, which is not a page.' + ].join('\n') + ) + }) +}) From 8fe073121fcd6779c0953cfa412d28ac18dfe5cb Mon Sep 17 00:00:00 2001 From: Christian Mejlak Date: Fri, 4 Dec 2026 14:07:46 +0100 Subject: [PATCH 04/20] check-redirects: run the check from the command line check-redirects.mjs reads each revision with one git cat-file process: the commit's file list, manifest.json and every .mdx file. The working tree is read in place, untracked files included. report.mjs writes annotations, the run summary and a plain list. A full run over the docs repo takes about a quarter of a second. --- .github/scripts/check-redirects.mjs | 175 +++++++++++++++++++++ .github/scripts/check-redirects/report.mjs | 100 ++++++++++++ 2 files changed, 275 insertions(+) create mode 100644 .github/scripts/check-redirects.mjs create mode 100644 .github/scripts/check-redirects/report.mjs diff --git a/.github/scripts/check-redirects.mjs b/.github/scripts/check-redirects.mjs new file mode 100644 index 00000000..faa6bad1 --- /dev/null +++ b/.github/scripts/check-redirects.mjs @@ -0,0 +1,175 @@ +#!/usr/bin/env node +// Fails a docs change that makes a docs URL stop working without a redirect. +// Usage: node .github/scripts/check-redirects.mjs [--base ] [--head ] +// --base defaults to origin/main and --head to the working tree. The check +// compares the head with the merge base of the two. + +import { execFileSync } from 'node:child_process' +import { appendFileSync, existsSync, readFileSync } from 'node:fs' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +import { parseArgs } from 'node:util' + +import { annotations, plainText, summary } from './check-redirects/report.mjs' +import { checkRedirects } from './check-redirects/rules.mjs' + +const USAGE = + 'Usage: node .github/scripts/check-redirects.mjs [--base ] [--head ]' + +// manifest.json and every .mdx file of a revision in one read. +const MAX_BUFFER = 512 * 1024 * 1024 + +/** + * Runs the check and reports it. Exits 1 on any error and 2 when it can't run. + * + * @param {string[]} argv - Arguments after the script name + * @param {NodeJS.ProcessEnv} [env] + * @returns {number} The exit code + */ +export function main(argv, env = process.env) { + let options + try { + options = parseArgs({ + args: argv, + options: { + base: { type: 'string', default: 'origin/main' }, + head: { type: 'string' } + } + }).values + } catch (err) { + console.error(`${err.message}\n${USAGE}`) + return 2 + } + + let violations + try { + violations = runCheck({ cwd: process.cwd(), ...options }) + } catch (err) { + const detail = err.stderr?.toString().trim() || err.message + console.error(`check-redirects couldn't read the revisions: ${detail}`) + return 2 + } + + if (env.GITHUB_ACTIONS === 'true') { + for (const line of annotations(violations)) console.log(line) + if (env.GITHUB_STEP_SUMMARY) { + appendFileSync(env.GITHUB_STEP_SUMMARY, summary(violations)) + } + } + console.log(plainText(violations)) + return violations.some(({ severity }) => severity === 'error') ? 1 : 0 +} + +/** + * Reads the base and head from git and checks them. + * + * @param {{ cwd: string, base: string, head?: string }} options - Git + * revisions. Without a head, the working tree is the head. + * @returns {import('./check-redirects/rules.mjs').Violation[]} + */ +export function runCheck({ cwd, base, head }) { + const root = git(cwd, 'rev-parse', '--show-toplevel').trim() + const mergeBase = git(root, 'merge-base', base, head ?? 'HEAD').trim() + return checkRedirects({ + base: readCommit(root, mergeBase), + head: head ? readCommit(root, head) : readWorkingTree(root) + }) +} + +/** + * Reads a commit's file list, its manifest and its .mdx files. + * + * @param {string} root - The repository's top level + * @param {string} rev - Any git revision + * @returns {import('./check-redirects/rules.mjs').Revision} + */ +export function readCommit(root, rev) { + const commit = git(root, 'rev-parse', '--verify', `${rev}^{commit}`).trim() + const paths = git(root, 'ls-tree', '-r', '-z', '--name-only', commit) + .split('\0') + .filter(Boolean) + const wanted = paths.filter(isRead) + const texts = catFile( + root, + wanted.map((path) => `${commit}:${path}`) + ) + const byPath = new Map(wanted.map((path, index) => [path, texts[index]])) + return revision(paths, (path) => byPath.get(path)) +} + +/** + * Reads the working tree, including untracked files that aren't ignored. + * + * @param {string} root - The repository's top level + * @returns {import('./check-redirects/rules.mjs').Revision} + */ +export function readWorkingTree(root) { + const paths = git( + root, + 'ls-files', + '-z', + '--cached', + '--others', + '--exclude-standard' + ) + .split('\0') + .filter((path) => path && existsSync(join(root, path))) + return revision(paths, (path) => readFileSync(join(root, path), 'utf8')) +} + +function revision(paths, read) { + const files = new Set(paths) + return { + manifestText: files.has('manifest.json') ? read('manifest.json') : null, + paths: files, + mdx: new Map( + [...files] + .filter((path) => path.endsWith('.mdx')) + .map((path) => [path, read(path)]) + ) + } +} + +const isRead = (path) => path === 'manifest.json' || path.endsWith('.mdx') + +// One git process per revision instead of one per file. +function catFile(root, specs) { + if (specs.length === 0) return [] + const output = execFileSync('git', ['cat-file', '--batch'], { + cwd: root, + input: specs.join('\n') + '\n', + maxBuffer: MAX_BUFFER, + stdio: ['pipe', 'pipe', 'pipe'] + }) + + const texts = [] + let offset = 0 + for (const spec of specs) { + const headerEnd = output.indexOf(0x0a, offset) + const header = output.toString('utf8', offset, headerEnd) + offset = headerEnd + 1 + if (header.endsWith(' missing')) { + throw new Error(`git cat-file found no ${spec}`) + } + const size = Number(header.slice(header.lastIndexOf(' ') + 1)) + texts.push(output.toString('utf8', offset, offset + size)) + offset += size + 1 + } + return texts +} + +function git(cwd, ...args) { + return execFileSync('git', args, { + cwd, + encoding: 'utf8', + maxBuffer: MAX_BUFFER, + stdio: ['ignore', 'pipe', 'pipe'] + }) +} + +if ( + process.argv[1] && + import.meta.url === pathToFileURL(process.argv[1]).href +) { + process.exitCode = main(process.argv.slice(2)) +} diff --git a/.github/scripts/check-redirects/report.mjs b/.github/scripts/check-redirects/report.mjs new file mode 100644 index 00000000..3a2a870c --- /dev/null +++ b/.github/scripts/check-redirects/report.mjs @@ -0,0 +1,100 @@ +/** + * Workflow commands that annotate each violation, errors first. GitHub shows + * at most 10 of each kind per step, so the order decides which ones appear. + * + * @param {import('./rules.mjs').Violation[]} violations + * @returns {string[]} + */ +export function annotations(violations) { + return ordered(violations).map(({ severity, file, line, rule, message }) => { + const properties = [`file=${escapeProperty(file)}`] + if (line) properties.push(`line=${line}`) + properties.push(`title=${escapeProperty(rule)}`) + return `::${severity} ${properties.join(',')}::${escapeData(message)}` + }) +} + +/** + * Markdown for $GITHUB_STEP_SUMMARY. Unlike the annotations, it lists every + * violation. + * + * @param {import('./rules.mjs').Violation[]} violations + * @returns {string} + */ +export function summary(violations) { + const lines = ['## Redirect check', ''] + if (violations.length === 0) { + lines.push('No problems found.') + } else { + const groups = grouped(violations) + lines.push(`${counts(groups)}.`) + for (const [heading, group] of [ + ['Errors', groups.errors], + ['New warnings', groups.newWarnings], + ['Warnings already on the base branch', groups.oldWarnings] + ]) { + if (group.length === 0) continue + lines.push('', `### ${heading}`, '') + for (const violation of group) { + lines.push( + `- **${violation.rule}** \`${location(violation)}\`: ${violation.message}` + ) + } + } + } + return lines.join('\n') + '\n' +} + +/** + * The counts and one line per violation, for a terminal or the job log. + * + * @param {import('./rules.mjs').Violation[]} violations + * @returns {string} + */ +export function plainText(violations) { + return [ + `Redirect check: ${counts(grouped(violations))}`, + ...ordered(violations).map( + (violation) => + `${violation.severity} ${violation.rule} ${location(violation)}: ${violation.message}` + ) + ].join('\n') +} + +function grouped(violations) { + return { + errors: violations.filter(({ severity }) => severity === 'error'), + newWarnings: violations.filter( + ({ severity, introduced }) => severity === 'warning' && introduced + ), + oldWarnings: violations.filter( + ({ severity, introduced }) => severity === 'warning' && !introduced + ) + } +} + +function ordered(violations) { + const { errors, newWarnings, oldWarnings } = grouped(violations) + return [...errors, ...newWarnings, ...oldWarnings] +} + +const counts = ({ errors, newWarnings, oldWarnings }) => + [ + plural(errors.length, 'error'), + plural(newWarnings.length, 'new warning'), + plural(oldWarnings.length, 'existing warning') + ].join(', ') + +const plural = (count, noun) => `${count} ${noun}${count === 1 ? '' : 's'}` + +const location = ({ file, line }) => (line ? `${file}:${line}` : file) + +// The escaping @actions/core applies to workflow command data and properties. +const escapeData = (value) => + String(value) + .replaceAll('%', '%25') + .replaceAll('\r', '%0D') + .replaceAll('\n', '%0A') + +const escapeProperty = (value) => + escapeData(value).replaceAll(':', '%3A').replaceAll(',', '%2C') From 0c1d28e8f1decdd2687fd7b93fb03119d28761af Mon Sep 17 00:00:00 2001 From: Christian Mejlak Date: Fri, 4 Dec 2026 14:08:19 +0100 Subject: [PATCH 05/20] check-redirects: replay docs PRs #529 and #493 Both removed pages without a redirect. #529 removed four Wi-Fi and MDM guides that returned 404 for about 4.5 months, and #493 removed a tutorial that returned 404 for about 10. Each replay must report exactly those URLs. In a shallow clone the replays skip. --- .../scripts/check-redirects/replay.test.mjs | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 .github/scripts/check-redirects/replay.test.mjs diff --git a/.github/scripts/check-redirects/replay.test.mjs b/.github/scripts/check-redirects/replay.test.mjs new file mode 100644 index 00000000..f1de5106 --- /dev/null +++ b/.github/scripts/check-redirects/replay.test.mjs @@ -0,0 +1,60 @@ +import assert from 'node:assert/strict' +import { execFileSync } from 'node:child_process' +import { dirname } from 'node:path' +import { describe, it } from 'node:test' +import { fileURLToPath } from 'node:url' + +import { runCheck } from '../check-redirects.mjs' + +// Real changes from this repo's history, so the expectations are facts. +const HERE = dirname(fileURLToPath(import.meta.url)) + +const inClone = (rev) => { + try { + execFileSync('git', ['cat-file', '-e', `${rev}^{commit}`], { + cwd: HERE, + stdio: 'ignore' + }) + return true + } catch { + return false + } +} + +// A shallow clone lacks the old commits, so the replay skips there. +const replay = (t, base, head) => { + if (!inClone(base) || !inClone(head)) { + t.skip(`${base} or ${head} isn't in this clone; fetch full history`) + return null + } + return runCheck({ cwd: HERE, base, head }) +} + +const errorKeys = (violations) => + violations + .filter(({ severity }) => severity === 'error') + .map(({ key }) => key) + .sort() + +describe('replays of docs history', () => { + it('fails PR #529 for exactly the four guides it removed', (t) => { + const violations = replay(t, '16d0af17^1', '16d0af17') + if (!violations) return + + assert.deepEqual(errorKeys(violations), [ + 'R1 /docs/tutorials/apple-mdm-jamf-setup-guide', + 'R1 /docs/tutorials/intune-mdm-setup-guide', + 'R1 /docs/tutorials/wifi-authentication-webhooks', + 'R1 /docs/tutorials/wifi-setup-guide' + ]) + }) + + it('fails PR #493 for exactly the tutorial it removed', (t) => { + const violations = replay(t, '63979d5f^1', '63979d5f') + if (!violations) return + + assert.deepEqual(errorKeys(violations), [ + 'R1 /docs/tutorials/mutual-tls-aws' + ]) + }) +}) From db8a672e65c0d25aedb2466f4bcffbff3d91c75f Mon Sep 17 00:00:00 2001 From: Christian Mejlak Date: Fri, 4 Dec 2026 14:52:17 +0100 Subject: [PATCH 06/20] check-redirects: test R1 on nested routes and the exit code for warnings Every page in the docs manifest sits under a heading route, so R1 checks nothing if the walk stops recursing. Until now only the replays caught that, and they skip in a shallow clone. The spec also says warnings never fail the check, which no test covered. Each new test fails when its behavior is broken. --- .github/scripts/check-redirects/cli.test.mjs | 11 +++++++++++ .github/scripts/check-redirects/rules.test.mjs | 16 ++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/.github/scripts/check-redirects/cli.test.mjs b/.github/scripts/check-redirects/cli.test.mjs index 5f9bca8e..56e3ef3a 100644 --- a/.github/scripts/check-redirects/cli.test.mjs +++ b/.github/scripts/check-redirects/cli.test.mjs @@ -110,6 +110,17 @@ describe('check-redirects.mjs', () => { assert.match(result.stdout, /0 errors/) }) + it('exits 0 when it finds only warnings', () => { + const dir = repo({ ...twoPages, 'manifest.json': '{ "routes": [ }' }) + git(dir, 'switch', '--quiet', '--create', 'feature') + commit(dir, { 'manifest.json': manifest('/foo.mdx', '/bar.mdx') }) + + const result = run(dir, ['--base', 'main', '--head', 'feature']) + + assert.equal(result.status, 0) + assert.match(result.stdout, /0 errors, 0 new warnings, 1 existing warning/) + }) + it('checks the working tree when no head is given', () => { const dir = repo(twoPages) write(dir, { 'manifest.json': manifest('/bar.mdx') }) diff --git a/.github/scripts/check-redirects/rules.test.mjs b/.github/scripts/check-redirects/rules.test.mjs index a629ebdb..accb1b35 100644 --- a/.github/scripts/check-redirects/rules.test.mjs +++ b/.github/scripts/check-redirects/rules.test.mjs @@ -106,6 +106,22 @@ describe('checkRedirects', () => { ) }) + it('fails a removed page nested under a heading route', () => { + const heading = (...routes) => ({ + title: 'Smallstep Documentation', + routes + }) + const base = revision({ + routes: [heading(page('/foo.mdx'), page('/bar.mdx'))] + }) + const head = revision({ routes: [heading(page('/bar.mdx'))] }) + + assert.deepEqual( + checkRedirects({ base, head }).map(({ key }) => key), + ['R1 /docs/foo'] + ) + }) + it('passes when every page still works', () => { const base = revision({ routes: [page('/foo.mdx')] }) const head = revision({ routes: [page('/foo.mdx'), page('/bar.mdx')] }) From 68df24b41699e9141b6580d76129c0c0807e1ffb Mon Sep 17 00:00:00 2001 From: Christian Mejlak Date: Fri, 4 Dec 2026 14:52:38 +0100 Subject: [PATCH 07/20] check-redirects: test file names that contain a newline Git allows a newline in a file name. readCommit sends one : line per file to git cat-file --batch, so such a name becomes two requests, and every later file gets the text of the one before it. A branch that removes a page can then pass: a decoy file sits where manifest.json is read. These tests fail until contents are read by object id. --- .github/scripts/check-redirects/cli.test.mjs | 38 ++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/.github/scripts/check-redirects/cli.test.mjs b/.github/scripts/check-redirects/cli.test.mjs index 56e3ef3a..9094b235 100644 --- a/.github/scripts/check-redirects/cli.test.mjs +++ b/.github/scripts/check-redirects/cli.test.mjs @@ -159,6 +159,28 @@ describe('check-redirects.mjs', () => { assert.match(result.stdout, /^error R1 manifest\.json: \/docs\/foo/m) }) + // A name with a newline used to split into two cat-file requests and shift + // every later file's contents by one, here onto manifest.json. + it( + 'fails a branch that hides a removed page behind a file name with a newline', + { skip: process.platform === 'win32' }, + () => { + const dir = repo(twoPages) + git(dir, 'switch', '--quiet', '--create', 'feature') + commit(dir, { + 'manifest.json': manifest('/bar.mdx'), + 'foo.mdx': null, + 'manifest.jsoa.mdx': twoPages['manifest.json'], + 'manifest.jsoa.mdx\nHEAD:manifest.jsoa.mdx': 'x' + }) + + const result = run(dir, ['--base', 'main', '--head', 'feature']) + + assert.equal(result.status, 1) + assert.match(result.stdout, /^error R1 manifest\.json: \/docs\/foo/m) + } + ) + it('exits 2 when a revision does not exist', () => { const dir = repo(twoPages) @@ -189,6 +211,22 @@ describe('readCommit', () => { }) }) +describe('readCommit with unusual file names', () => { + it( + 'reads a file whose name contains a newline', + { skip: process.platform === 'win32' }, + () => { + const dir = repo({ ...twoPages, 'odd\nname.mdx': '# Odd\n' }) + + const revision = readCommit(dir, 'main') + + assert.equal(revision.manifestText, twoPages['manifest.json']) + assert.equal(revision.mdx.get('odd\nname.mdx'), '# Odd\n') + assert.equal(revision.mdx.get('foo.mdx'), '# Foo\n') + } + ) +}) + describe('readWorkingTree', () => { it('includes untracked files and leaves out deleted ones', () => { const dir = repo(twoPages) From 9921217325447fe52c96cef0269506e5a9a5f439 Mon Sep 17 00:00:00 2001 From: Christian Mejlak Date: Fri, 4 Dec 2026 14:53:03 +0100 Subject: [PATCH 08/20] check-redirects: read commit files by object id readCommit lists the tree with object ids and asks git cat-file --batch for blobs by id, so a file name can no longer reach the batch protocol. Each answer must carry the requested id, be a blob and have a numeric size, and no output may be left over; anything else fails the check with exit 2. Error messages carry object ids, not file names. --- .github/scripts/check-redirects.mjs | 53 ++++++++++++++++++++--------- 1 file changed, 36 insertions(+), 17 deletions(-) diff --git a/.github/scripts/check-redirects.mjs b/.github/scripts/check-redirects.mjs index faa6bad1..88899b91 100644 --- a/.github/scripts/check-redirects.mjs +++ b/.github/scripts/check-redirects.mjs @@ -85,16 +85,22 @@ export function runCheck({ cwd, base, head }) { */ export function readCommit(root, rev) { const commit = git(root, 'rev-parse', '--verify', `${rev}^{commit}`).trim() - const paths = git(root, 'ls-tree', '-r', '-z', '--name-only', commit) + const entries = git(root, 'ls-tree', '-r', '-z', '--full-tree', commit) .split('\0') .filter(Boolean) - const wanted = paths.filter(isRead) + .map(treeEntry) + const wanted = entries.filter( + ({ type, path }) => type === 'blob' && isRead(path) + ) const texts = catFile( root, - wanted.map((path) => `${commit}:${path}`) + wanted.map(({ oid }) => oid) + ) + const byPath = new Map(wanted.map(({ path }, index) => [path, texts[index]])) + return revision( + entries.map(({ path }) => path), + (path) => byPath.get(path) ) - const byPath = new Map(wanted.map((path, index) => [path, texts[index]])) - return revision(paths, (path) => byPath.get(path)) } /** @@ -132,28 +138,41 @@ function revision(paths, read) { const isRead = (path) => path === 'manifest.json' || path.endsWith('.mdx') -// One git process per revision instead of one per file. -function catFile(root, specs) { - if (specs.length === 0) return [] +// " \t". The path is stored as is and may contain a +// newline, so contents are requested by object id, never by path. +function treeEntry(entry) { + const tab = entry.indexOf('\t') + const [, type, oid] = entry.slice(0, tab).split(' ') + return { type, oid, path: entry.slice(tab + 1) } +} + +// One git process per revision instead of one per file. Each answer must match +// its request, so no file can be handed another file's contents. +function catFile(root, oids) { + if (oids.length === 0) return [] const output = execFileSync('git', ['cat-file', '--batch'], { cwd: root, - input: specs.join('\n') + '\n', + input: oids.join('\n') + '\n', maxBuffer: MAX_BUFFER, stdio: ['pipe', 'pipe', 'pipe'] }) const texts = [] let offset = 0 - for (const spec of specs) { + for (const oid of oids) { const headerEnd = output.indexOf(0x0a, offset) - const header = output.toString('utf8', offset, headerEnd) - offset = headerEnd + 1 - if (header.endsWith(' missing')) { - throw new Error(`git cat-file found no ${spec}`) + const [answer, type, size] = output + .toString('utf8', offset, headerEnd) + .split(' ') + if (answer !== oid || type !== 'blob' || !/^\d+$/.test(size)) { + throw new Error(`git cat-file didn't return blob ${oid}`) } - const size = Number(header.slice(header.lastIndexOf(' ') + 1)) - texts.push(output.toString('utf8', offset, offset + size)) - offset += size + 1 + offset = headerEnd + 1 + texts.push(output.toString('utf8', offset, offset + Number(size))) + offset += Number(size) + 1 + } + if (offset !== output.length) { + throw new Error('git cat-file returned more than was requested') } return texts } From fb8599ddd9a4a4bea44e4d7e7e083d5c9815d286 Mon Sep 17 00:00:00 2001 From: Christian Mejlak Date: Fri, 4 Dec 2026 14:54:29 +0100 Subject: [PATCH 09/20] check-redirects: test that the change's text never acts as a command Messages quote text from the change: URLs built from manifest paths now, and link targets and file names later. V8's JSON errors also quote the manifest around the bad token, newlines included. On a GitHub runner, a printed line that starts with :: or holds ##[ is a workflow command, so a manifest path can forge annotations in the plain list or in git's error text. The summary is Markdown, where the same text can add links, images or headings. The tests expect: - one line per violation in the plain list; - in Actions, the plain list and stderr wrapped in a stop-commands block; - the change's text in the summary rendered as plain text; - JSON errors that give a position instead of quoting the manifest. --- .github/scripts/check-redirects/cli.test.mjs | 60 ++++++++++++++++++- .../scripts/check-redirects/report.test.mjs | 52 ++++++++++++++-- .../scripts/check-redirects/rules.test.mjs | 11 ++++ 3 files changed, 115 insertions(+), 8 deletions(-) diff --git a/.github/scripts/check-redirects/cli.test.mjs b/.github/scripts/check-redirects/cli.test.mjs index 9094b235..3ccc77ce 100644 --- a/.github/scripts/check-redirects/cli.test.mjs +++ b/.github/scripts/check-redirects/cli.test.mjs @@ -64,6 +64,26 @@ const twoPages = { 'bar.mdx': '# Bar\n' } +// The lines the Actions runner would run as workflow commands: those that +// start with :: or hold the legacy ##[ form, outside a stop-commands block. +const commandLines = (output) => { + const commands = [] + let resume = null + for (const line of output.split('\n').map((text) => text.trim())) { + if (resume) { + if (line === resume) resume = null + continue + } + const stop = line.match(/^::stop-commands::(.+)$/) + if (stop) { + resume = `::${stop[1]}::` + continue + } + if (line.startsWith('::') || line.includes('##[')) commands.push(line) + } + return commands +} + const run = (dir, args, env = {}) => spawnSync(process.execPath, [CLI, ...args], { cwd: dir, @@ -90,12 +110,46 @@ describe('check-redirects.mjs', () => { result.stdout, /^::error file=manifest\.json,title=R1::\/docs\/foo works before/m ) - assert.match( - readFileSync(summaryFile, 'utf8'), - /\{ "source": "\/docs\/foo", "destination": "\/docs\/…" \}/ + assert.ok( + readFileSync(summaryFile, 'utf8').includes( + String.raw`\{ \"source\"\: \"\/docs\/foo\"\, \"destination\"\: \"\/docs\/…\" \}` + ) ) }) + it("runs none of the change's text as a workflow command in GitHub Actions", () => { + const dir = repo({ + 'manifest.json': manifest( + '/foo ##[error]legacy\n::error::forged.mdx', + '/bar.mdx' + ), + 'bar.mdx': '# Bar\n' + }) + git(dir, 'switch', '--quiet', '--create', 'feature') + commit(dir, { 'manifest.json': manifest('/bar.mdx') }) + + const result = run(dir, ['--base', 'main', '--head', 'feature'], { + GITHUB_ACTIONS: 'true' + }) + + assert.equal(result.status, 1) + const commands = commandLines(result.stdout) + assert.equal(commands.length, 1) + assert.match(commands[0], /^::error file=manifest\.json,title=R1::/) + }) + + it("keeps git's error text inert in GitHub Actions", () => { + const dir = repo(twoPages) + + const result = run(dir, ['--base', '##[error]forged'], { + GITHUB_ACTIONS: 'true' + }) + + assert.equal(result.status, 2) + assert.match(result.stderr, /forged/) + assert.deepEqual(commandLines(result.stderr), []) + }) + it('passes a branch that keeps every page', () => { const dir = repo(twoPages) git(dir, 'switch', '--quiet', '--create', 'feature') diff --git a/.github/scripts/check-redirects/report.test.mjs b/.github/scripts/check-redirects/report.test.mjs index 465bffb4..7a07b92a 100644 --- a/.github/scripts/check-redirects/report.test.mjs +++ b/.github/scripts/check-redirects/report.test.mjs @@ -1,7 +1,7 @@ import assert from 'node:assert/strict' import { describe, it } from 'node:test' -import { annotations, plainText, summary } from './report.mjs' +import { annotations, inert, plainText, summary } from './report.mjs' const violation = (overrides) => ({ rule: 'R1', @@ -62,6 +62,15 @@ describe('annotations', () => { }) }) +describe('inert', () => { + it('wraps text so the runner reads no workflow command in it', () => { + assert.equal( + inert('a\n::error::x\n##[error]y', 'token'), + '::stop-commands::token\na\n::error::x\n##[error]y\n::token::' + ) + }) +}) + describe('summary', () => { it('groups errors, new warnings and warnings already on the base', () => { const markdown = summary([oldWarning, newWarning, removedPage]) @@ -73,11 +82,34 @@ describe('summary', () => { '### New warnings', '### Warnings already on the base branch' ]) - assert.match( - markdown, - /- \*\*R9b\*\* `a\.mdx:3`: a\.mdx links to \/docs\/gone/ + const lines = markdown.split('\n') + assert.ok( + lines.includes( + String.raw`- **R9b** a\.mdx\:3 — a\.mdx links to \/docs\/gone\, which is not a page\.` + ) + ) + assert.ok( + lines.includes( + String.raw`- **R1** manifest\.json — \/docs\/foo works before this change but not after it\.` + ) + ) + }) + + it('renders text from the change as plain text', () => { + const markdown = summary([ + violation({ + file: 'odd`name.mdx', + message: 'see [here](https://evil.example)\n# Fake ' + }) + ]) + + assert.ok( + markdown + .split('\n') + .includes( + String.raw`- **R1** odd\`name\.mdx — see \[here\]\(https\:\/\/evil\.example\) ⏎ \# Fake \` + ) ) - assert.match(markdown, /- \*\*R1\*\* `manifest\.json`: \/docs\/foo/) }) it('says when there is nothing to report', () => { @@ -86,6 +118,16 @@ describe('summary', () => { }) describe('plainText', () => { + it('keeps each violation on one line', () => { + assert.equal( + plainText([violation({ message: 'a\n::error::x\r\nb\u001b[31mc' })]), + [ + 'Redirect check: 1 error, 0 new warnings, 0 existing warnings', + 'error R1 manifest.json: a ⏎ ::error::x ⏎ b\ufffd[31mc' + ].join('\n') + ) + }) + it('prints the counts and one line per violation', () => { assert.equal( plainText([newWarning, removedPage]), diff --git a/.github/scripts/check-redirects/rules.test.mjs b/.github/scripts/check-redirects/rules.test.mjs index accb1b35..614483e6 100644 --- a/.github/scripts/check-redirects/rules.test.mjs +++ b/.github/scripts/check-redirects/rules.test.mjs @@ -189,6 +189,17 @@ describe('checkRedirects', () => { const [violation] = checkRedirects({ base, head }) assert.equal(violation.line, 3) + assert.match(violation.message, /at line 3, column 1/) + }) + + it('does not quote the manifest in a JSON error', () => { + const base = revision({ routes: [page('/foo.mdx')] }) + const head = revision('{"routes":\n::error::forged}') + + const [violation] = checkRedirects({ base, head }) + + assert.match(violation.message, /isn't valid JSON/) + assert.doesNotMatch(violation.message, /forged|\n/) }) it('skips R1 and warns when the base manifest is unreadable', () => { From 95a2dab2a9162e35ec79e307b9141e76ca9d32d6 Mon Sep 17 00:00:00 2001 From: Christian Mejlak Date: Fri, 4 Dec 2026 14:55:25 +0100 Subject: [PATCH 10/20] check-redirects: keep the change's text from acting as a command MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - In GitHub Actions, everything printed besides the annotations sits in a stop-commands block with a random token: the plain list, and the usage and git errors on stderr. The runner then reads none of it as a workflow command. - The plain list and the summary make line breaks visible as ⏎ and replace other control characters, so each violation stays on one line. - The summary escapes all ASCII punctuation in locations and messages, so text from the change renders as written. - A JSON syntax error now gives only its line and column instead of V8's message, which quotes the manifest around the error. --- .github/scripts/check-redirects.mjs | 21 +++++++++++++---- .github/scripts/check-redirects/report.mjs | 27 ++++++++++++++++++++-- .github/scripts/check-redirects/rules.mjs | 21 ++++++++--------- 3 files changed, 52 insertions(+), 17 deletions(-) diff --git a/.github/scripts/check-redirects.mjs b/.github/scripts/check-redirects.mjs index 88899b91..7b898320 100644 --- a/.github/scripts/check-redirects.mjs +++ b/.github/scripts/check-redirects.mjs @@ -5,12 +5,18 @@ // compares the head with the merge base of the two. import { execFileSync } from 'node:child_process' +import { randomUUID } from 'node:crypto' import { appendFileSync, existsSync, readFileSync } from 'node:fs' import { join } from 'node:path' import { pathToFileURL } from 'node:url' import { parseArgs } from 'node:util' -import { annotations, plainText, summary } from './check-redirects/report.mjs' +import { + annotations, + inert, + plainText, + summary +} from './check-redirects/report.mjs' import { checkRedirects } from './check-redirects/rules.mjs' const USAGE = @@ -27,6 +33,11 @@ const MAX_BUFFER = 512 * 1024 * 1024 * @returns {number} The exit code */ export function main(argv, env = process.env) { + // Output quotes text from the change. On a runner, only the annotations may + // be read as workflow commands. + const shown = (text) => + env.GITHUB_ACTIONS === 'true' ? inert(text, randomUUID()) : text + let options try { options = parseArgs({ @@ -37,7 +48,7 @@ export function main(argv, env = process.env) { } }).values } catch (err) { - console.error(`${err.message}\n${USAGE}`) + console.error(shown(`${err.message}\n${USAGE}`)) return 2 } @@ -46,7 +57,9 @@ export function main(argv, env = process.env) { violations = runCheck({ cwd: process.cwd(), ...options }) } catch (err) { const detail = err.stderr?.toString().trim() || err.message - console.error(`check-redirects couldn't read the revisions: ${detail}`) + console.error( + shown(`check-redirects couldn't read the revisions: ${detail}`) + ) return 2 } @@ -56,7 +69,7 @@ export function main(argv, env = process.env) { appendFileSync(env.GITHUB_STEP_SUMMARY, summary(violations)) } } - console.log(plainText(violations)) + console.log(shown(plainText(violations))) return violations.some(({ severity }) => severity === 'error') ? 1 : 0 } diff --git a/.github/scripts/check-redirects/report.mjs b/.github/scripts/check-redirects/report.mjs index 3a2a870c..42ef60f2 100644 --- a/.github/scripts/check-redirects/report.mjs +++ b/.github/scripts/check-redirects/report.mjs @@ -37,7 +37,7 @@ export function summary(violations) { lines.push('', `### ${heading}`, '') for (const violation of group) { lines.push( - `- **${violation.rule}** \`${location(violation)}\`: ${violation.message}` + `- **${violation.rule}** ${markdownText(location(violation))} — ${markdownText(violation.message)}` ) } } @@ -56,11 +56,23 @@ export function plainText(violations) { `Redirect check: ${counts(grouped(violations))}`, ...ordered(violations).map( (violation) => - `${violation.severity} ${violation.rule} ${location(violation)}: ${violation.message}` + `${violation.severity} ${violation.rule} ${oneLine(location(violation))}: ${oneLine(violation.message)}` ) ].join('\n') } +/** + * Wraps text in a stop-commands block, so the Actions runner reads none of its + * lines as a workflow command, not even one that starts with :: or holds ##[. + * + * @param {string} text + * @param {string} token - Unguessable, so the text can't end the block itself + * @returns {string} + */ +export function inert(text, token) { + return `::stop-commands::${token}\n${text}\n::${token}::` +} + function grouped(violations) { return { errors: violations.filter(({ severity }) => severity === 'error'), @@ -89,6 +101,17 @@ const plural = (count, noun) => `${count} ${noun}${count === 1 ? '' : 's'}` const location = ({ file, line }) => (line ? `${file}:${line}` : file) +// Messages quote text from the change, which can hold line breaks and other +// control characters. A visible mark keeps each violation on one line. +const oneLine = (text) => + String(text) + .replace(/\r\n|\r|\n/g, ' ⏎ ') + .replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, '\ufffd') + +// CommonMark lets any ASCII punctuation be escaped, which renders the text +// as written: no links, images, HTML, headings or code spans. +const markdownText = (text) => oneLine(text).replace(/[!-/:-@[-`{-~]/g, '\\$&') + // The escaping @actions/core applies to workflow command data and properties. const escapeData = (value) => String(value) diff --git a/.github/scripts/check-redirects/rules.mjs b/.github/scripts/check-redirects/rules.mjs index f8f43dd5..98a9cd7a 100644 --- a/.github/scripts/check-redirects/rules.mjs +++ b/.github/scripts/check-redirects/rules.mjs @@ -68,9 +68,17 @@ export function readManifest(text) { try { manifest = JSON.parse(text) } catch (err) { + // V8's message quotes the manifest around the error, so keep only where it is. + const at = err.message.match(/\(line (\d+) column (\d+)\)/) + if (!at) { + return { + problem: + "manifest.json isn't valid JSON, and the parser gave no position; check the lines this change edits" + } + } return { - problem: `manifest.json isn't valid JSON: ${err.message}`, - line: syntaxErrorLine(err, text) + problem: `manifest.json isn't valid JSON at line ${at[1]}, column ${at[2]}`, + line: Number(at[1]) } } @@ -158,12 +166,3 @@ const isObject = (value) => // The site finds a page by comparing /.mdx with each path. const isPagePath = (path) => typeof path === 'string' && path.startsWith('/') && path.endsWith('.mdx') - -// V8 names the line in newer releases and only the offset in older ones. -function syntaxErrorLine(err, text) { - const line = err.message.match(/\(line (\d+) column \d+\)/) - if (line) return Number(line[1]) - const position = err.message.match(/at position (\d+)/) - if (position) return text.slice(0, Number(position[1])).split('\n').length - return undefined -} From 44f75a10c01910adde7985cb737314dfd4a1495c Mon Sep 17 00:00:00 2001 From: Christian Mejlak Date: Fri, 4 Dec 2026 16:56:36 +0100 Subject: [PATCH 11/20] check-redirects: test the redirect entry rules MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `redirects` in manifest.json must be an array of objects with exactly a string source and a string destination (R2). A source is /docs plus at least one segment, written as smallstep.com matches it (R3). A destination is a docs page in the change, optionally with a fragment (R4). No URL may be both a page and a source (R5), and no source may appear twice (R6). An entry that passes R2–R4 keeps its source working for R1, so removing it, or pointing it at a missing page, fails like removing a page. A problem already on the base is a warning, and so is every finding when the base manifest can't be read. --- .../scripts/check-redirects/rules.test.mjs | 190 ++++++++++++++++++ 1 file changed, 190 insertions(+) diff --git a/.github/scripts/check-redirects/rules.test.mjs b/.github/scripts/check-redirects/rules.test.mjs index 614483e6..24ace183 100644 --- a/.github/scripts/check-redirects/rules.test.mjs +++ b/.github/scripts/check-redirects/rules.test.mjs @@ -216,3 +216,193 @@ describe('checkRedirects', () => { }) }) }) + +describe('checkRedirects: redirect entries', () => { + const pages = [page('/README.mdx'), page('/new.mdx')] + const site = (redirects) => + revision( + redirects === undefined ? { routes: pages } : { routes: pages, redirects } + ) + const check = (redirects, baseRedirects) => + checkRedirects({ base: site(baseRedirects), head: site(redirects) }) + const outcome = (violations) => + violations.map( + ({ rule, severity, introduced }) => + `${rule} ${severity}${introduced ? '' : ' (base)'}` + ) + + it('accepts redirects to a page, with or without a fragment', () => { + const redirects = [ + { source: '/docs/old', destination: '/docs/new' }, + { source: '/docs/older', destination: '/docs/new#install' }, + { source: '/docs/oldest', destination: '/docs' } + ] + + assert.deepEqual(check(redirects), []) + }) + + describe('R2', () => { + const malformed = [ + ['redirects that are not an array', {}], + ['an entry that is not an object', ['/docs/old']], + ['a null entry', [null]], + ['a missing destination', [{ source: '/docs/old' }]], + [ + 'a source that is not a string', + [{ source: 1, destination: '/docs/new' }] + ], + [ + 'a key other than source and destination', + [{ source: '/docs/old', destination: '/docs/new', permanent: true }] + ] + ] + + for (const [name, redirects] of malformed) { + it(`fails ${name}`, () => { + assert.deepEqual(outcome(check(redirects)), ['R2 error']) + }) + } + }) + + describe('R3', () => { + const sources = [ + ['/docs', 'no segment after /docs'], + ['/docs/old/', 'a trailing slash'], + ['/docs//old', 'an empty segment'], + ['/docs/old.mdx', '.mdx'], + ['/docs/old?tab=linux', 'a query string'], + ['/docs/old#install', 'a fragment'], + ['/docs/cli/:slug*', 'pattern syntax'], + ['/docs/old(1)', 'a parenthesis'], + ['docs/old', 'no leading slash'], + ['/blog/old', 'a path outside /docs'] + ] + + for (const [source, problem] of sources) { + it(`fails a source with ${problem}: ${source}`, () => { + assert.deepEqual( + outcome(check([{ source, destination: '/docs/new' }])), + ['R3 error'] + ) + }) + } + + it("points at the line of the entry's source", () => { + const head = site([{ source: '/docs/old/', destination: '/docs/new' }]) + const expected = + head.manifestText + .split('\n') + .findIndex((line) => line.includes('"/docs/old/"')) + 1 + + const [violation] = checkRedirects({ base: site(), head }) + + assert.equal(violation.file, 'manifest.json') + assert.equal(violation.line, expected) + }) + }) + + describe('R4', () => { + const destinations = [ + ['/docs/new/', 'a trailing slash'], + ['/docs/new?tab=linux', 'a query string'], + ['/docs/new.mdx', '.mdx'], + ['/docs/new:install', 'pattern syntax'], + ['https://smallstep.com/docs/new', 'a full URL'], + ['/blog/new', 'a path outside /docs'], + ['/docs/missing', 'a URL that is not a page'], + ['/docs/missing#install', 'a URL that is not a page, with a fragment'] + ] + + for (const [destination, problem] of destinations) { + it(`fails a destination with ${problem}: ${destination}`, () => { + assert.deepEqual( + outcome(check([{ source: '/docs/old', destination }])), + ['R4 error'] + ) + }) + } + }) + + it('R5: fails a source that is also a page', () => { + const violations = check([{ source: '/docs/new', destination: '/docs' }]) + + assert.deepEqual(outcome(violations), ['R5 error']) + assert.match(violations[0].message, /\/docs\/new/) + }) + + it('R6: fails two redirects with the same source, once', () => { + const violations = check([ + { source: '/docs/old', destination: '/docs/new' }, + { source: '/docs/old', destination: '/docs' } + ]) + + assert.deepEqual(outcome(violations), ['R6 error']) + assert.match(violations[0].message, /\/docs\/old/) + }) + + it('warns about a problem that is already on the base', () => { + const redirects = [{ source: '/docs/old/', destination: '/docs/new' }] + + assert.deepEqual(outcome(check(redirects, redirects)), [ + 'R3 warning (base)' + ]) + }) + + it("turns the head's findings into warnings when the base manifest is unreadable", () => { + const violations = checkRedirects({ + base: revision('{ "routes": [ }'), + head: site([{ source: '/docs/old/', destination: '/docs/new' }]) + }) + + assert.deepEqual(outcome(violations), [ + 'manifest warning (base)', + 'R3 warning (base)' + ]) + }) +}) + +describe('checkRedirects: R1 with redirects', () => { + const routes = (...paths) => paths.map(page) + + it('passes when a removed page gets a redirect', () => { + const base = revision({ + routes: routes('/README.mdx', '/old.mdx', '/new.mdx') + }) + const head = revision({ + routes: routes('/README.mdx', '/new.mdx'), + redirects: [{ source: '/docs/old', destination: '/docs/new' }] + }) + + assert.deepEqual(checkRedirects({ base, head }), []) + }) + + it('fails when a redirect goes away and no page takes its URL', () => { + const base = revision({ + routes: routes('/README.mdx', '/new.mdx'), + redirects: [{ source: '/docs/old', destination: '/docs/new' }] + }) + const head = revision({ routes: routes('/README.mdx', '/new.mdx') }) + + assert.deepEqual( + checkRedirects({ base, head }).map(({ key }) => key), + ['R1 /docs/old'] + ) + }) + + it('does not count a redirect to a missing page as working', () => { + const base = revision({ + routes: routes('/README.mdx', '/old.mdx', '/new.mdx') + }) + const head = revision({ + routes: routes('/README.mdx', '/new.mdx'), + redirects: [{ source: '/docs/old', destination: '/docs/missing' }] + }) + + assert.deepEqual( + checkRedirects({ base, head }) + .map(({ rule }) => rule) + .sort(), + ['R1', 'R4'] + ) + }) +}) From 5866a6bd7514e40d6937a8b6e10a7567fdb29370 Mon Sep 17 00:00:00 2001 From: Christian Mejlak Date: Fri, 4 Dec 2026 16:58:07 +0100 Subject: [PATCH 12/20] check-redirects: validate redirect entries MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit readSite collects what one revision serves: its pages, plus the sources of redirects that pass R2–R4. That is what R1 compares. It also collects the revision's own problems (R2–R6), each keyed by rule and entry. A problem in the head becomes an error when the base doesn't have its key, and a warning otherwise. Annotations point at the line of the entry's source. An entry with a malformed source gets only R3 and R4, since R5 and R6 can't apply to a URL smallstep.com would never match. --- .github/scripts/check-redirects/rules.mjs | 193 ++++++++++++++++++++-- 1 file changed, 183 insertions(+), 10 deletions(-) diff --git a/.github/scripts/check-redirects/rules.mjs b/.github/scripts/check-redirects/rules.mjs index 98a9cd7a..39d968ad 100644 --- a/.github/scripts/check-redirects/rules.mjs +++ b/.github/scripts/check-redirects/rules.mjs @@ -16,6 +16,13 @@ const REFERENCE_PREFIX = '/docs/step-cli/reference/' +// smallstep.com matches a source exactly against /docs/, so a source is +// /docs plus at least one segment with no query, fragment, empty segment, +// trailing slash or pattern syntax. A destination may be /docs itself and may +// end in a fragment. +const SOURCE = /^\/docs(?:\/[^/?#:*(]+)+$/ +const DESTINATION = /^\/docs(?:\/[^/?#:*(]+)*(?:#.*)?$/ + /** * Compares a PR's head with its base. * @@ -37,6 +44,7 @@ export function checkRedirects({ base, head }) { } ] } + const headSite = readSite(headRead.manifest, head) const baseRead = readManifest(base.manifestText) if (baseRead.problem) { @@ -48,11 +56,28 @@ export function checkRedirects({ base, head }) { introduced: false, file: 'manifest.json', message: `The base manifest.json is unreadable (${baseRead.problem}), so R1 and R9 were skipped and every other finding is a warning.` - } + }, + ...headSite.findings.map((finding) => ({ + ...finding, + severity: 'warning', + introduced: false + })) ] } + const baseSite = readSite(baseRead.manifest, base) + const onBase = new Set(baseSite.findings.map(({ key }) => key)) - return removedUrls(baseRead.manifest, headRead.manifest) + return [ + ...removedUrlViolations(baseSite, headSite), + ...headSite.findings.map((finding) => { + const introduced = !onBase.has(finding.key) + return { + ...finding, + severity: introduced ? 'error' : 'warning', + introduced + } + }) + ] } /** @@ -105,10 +130,162 @@ export function pageUrl(path) { return ['/docs', ...segments].join('/') } -function removedUrls(baseManifest, headManifest) { - const working = workingUrls(headManifest) - return [...workingUrls(baseManifest)] - .filter((url) => !working.has(url) && !url.startsWith(REFERENCE_PREFIX)) +// What one revision serves, and the problems it has on its own. Findings get +// their severity once the head is compared with the base. +function readSite(manifest, revision) { + const pages = pageUrls(manifest.routes) + const lines = lineFinder(revision.manifestText) + const redirects = readRedirects(manifest, pages, lines) + return { + pages, + working: new Set([...pages.keys(), ...redirects.sources]), + findings: redirects.findings + } +} + +// R2–R6. A source works only when its entry passes R2–R4. +function readRedirects(manifest, pages, lines) { + const findings = [] + const sources = new Set() + if (!('redirects' in manifest)) return { sources, findings } + + if (!Array.isArray(manifest.redirects)) { + findings.push( + manifestFinding( + 'R2', + 'R2 redirects', + lines.redirectsKey(), + '`redirects` in manifest.json must be an array.' + ) + ) + return { sources, findings } + } + + const seen = new Set() + const duplicated = new Set() + for (const entry of manifest.redirects) { + if (!isEntry(entry)) { + const written = JSON.stringify(entry) + findings.push( + manifestFinding( + 'R2', + `R2 ${written}`, + undefined, + `Each redirect must be an object with exactly "source" and "destination", both strings: ${written}` + ) + ) + continue + } + + const { source, destination } = entry + const line = lines.source(source) + const goodSource = isSource(source) + let works = goodSource + + if (!goodSource) { + findings.push( + manifestFinding( + 'R3', + `R3 ${source}`, + line, + `The redirect source ${source} must be /docs/ plus at least one segment, with no trailing slash, query, fragment, .mdx, ":", "*" or "(".` + ) + ) + } + + if (!isDestination(destination)) { + works = false + findings.push( + manifestFinding( + 'R4', + `R4 ${source} ${destination}`, + line, + `The redirect from ${source} goes to ${destination}, which must be /docs or a /docs/ path, optionally with a #fragment, and with no trailing slash, query, .mdx, ":", "*" or "(".` + ) + ) + } else if (!pages.has(destination.replace(/#.*$/, ''))) { + works = false + findings.push( + manifestFinding( + 'R4', + `R4 ${source} ${destination}`, + line, + `The redirect from ${source} goes to ${destination}, which isn't a docs page after this change.` + ) + ) + } + + if (!goodSource) continue + if (pages.has(source)) { + findings.push( + manifestFinding( + 'R5', + `R5 ${source}`, + line, + `${source} is both a page and a redirect source, so the redirect hides the page. Remove the redirect or the page.` + ) + ) + } + if (seen.has(source)) { + if (!duplicated.has(source)) { + duplicated.add(source) + findings.push( + manifestFinding( + 'R6', + `R6 ${source}`, + line, + `More than one redirect has the source ${source}. Keep one.` + ) + ) + } + continue + } + seen.add(source) + if (works) sources.add(source) + } + return { sources, findings } +} + +function manifestFinding(rule, key, line, message) { + return { rule, key, file: 'manifest.json', line, message } +} + +const isEntry = (entry) => + isObject(entry) && + Object.keys(entry).length === 2 && + typeof entry.source === 'string' && + typeof entry.destination === 'string' + +const isSource = (source) => SOURCE.test(source) && !source.endsWith('.mdx') + +const isDestination = (destination) => + DESTINATION.test(destination) && !/\.mdx(?:#|$)/.test(destination) + +// Annotations point at the first line that holds a value. JSON.stringify +// writes the value the way the manifest does. +function lineFinder(text) { + const lines = text.split('\n') + const find = (matches, from = 0) => { + const index = lines.findIndex((line, i) => i >= from && matches(line)) + return index === -1 ? undefined : index + 1 + } + const redirectsKey = () => find((line) => /"redirects"\s*:/.test(line)) + return { + redirectsKey, + source: (source) => + find( + (line) => + /"source"\s*:/.test(line) && line.includes(JSON.stringify(source)), + (redirectsKey() ?? 1) - 1 + ) + } +} + +function removedUrlViolations(baseSite, headSite) { + return [...baseSite.working] + .filter( + (url) => !headSite.working.has(url) && !url.startsWith(REFERENCE_PREFIX) + ) .map((url) => ({ rule: 'R1', key: `R1 ${url}`, @@ -119,10 +296,6 @@ function removedUrls(baseManifest, headManifest) { })) } -function workingUrls(manifest) { - return new Set(pageUrls(manifest.routes).keys()) -} - function pageUrls(routes, urls = new Map()) { for (const route of routes) { if (route.path) { From 5407317424a910d946dc1351da5d82f37f4c071a Mon Sep 17 00:00:00 2001 From: Christian Mejlak Date: Fri, 4 Dec 2026 16:58:41 +0100 Subject: [PATCH 13/20] check-redirects: test manifest integrity A manifest path whose file doesn't exist is a page smallstep.com can't render (R7). Two manifest paths that map to the same URL, such as /foo.mdx and /foo/README.mdx, make one of them unreachable (R8). Both are errors when the change introduces them and warnings when the base already has them. The test revision now gives every manifest path a file unless a test lists the files itself. --- .../scripts/check-redirects/rules.test.mjs | 66 ++++++++++++++++++- 1 file changed, 63 insertions(+), 3 deletions(-) diff --git a/.github/scripts/check-redirects/rules.test.mjs b/.github/scripts/check-redirects/rules.test.mjs index 24ace183..5bd4857b 100644 --- a/.github/scripts/check-redirects/rules.test.mjs +++ b/.github/scripts/check-redirects/rules.test.mjs @@ -3,13 +3,26 @@ import { describe, it } from 'node:test' import { checkRedirects, pageUrl, readManifest } from './rules.mjs' -const revision = (manifest) => ({ +// Every manifest path has a file unless `files` says otherwise. +const revision = (manifest, { files, mdx = {} } = {}) => ({ manifestText: typeof manifest === 'string' ? manifest : JSON.stringify(manifest, null, 2), - paths: new Set(), - mdx: new Map() + paths: new Set(files ?? [...routeFiles(manifest), ...Object.keys(mdx)]), + mdx: new Map(Object.entries(mdx)) }) +const routeFiles = (manifest) => { + const walk = (routes = []) => + routes.flatMap((route) => [ + ...(route.path ? [route.path.slice(1)] : []), + ...walk(route.routes) + ]) + return typeof manifest === 'string' ? [] : walk(manifest.routes) +} + +const lineOf = (revision, text) => + revision.manifestText.split('\n').findIndex((line) => line.includes(text)) + 1 + const page = (path) => ({ title: path, path }) describe('readManifest', () => { @@ -406,3 +419,50 @@ describe('checkRedirects: R1 with redirects', () => { ) }) }) + +describe('checkRedirects: manifest integrity', () => { + const outcome = (violations) => + violations.map( + ({ rule, severity, introduced }) => + `${rule} ${severity}${introduced ? '' : ' (base)'}` + ) + + it('R7: fails a manifest path with no file, at its line', () => { + const base = revision({ routes: [page('/foo.mdx')] }) + const head = revision( + { routes: [page('/foo.mdx'), page('/new.mdx')] }, + { files: ['foo.mdx'] } + ) + + const violations = checkRedirects({ base, head }) + + assert.deepEqual(outcome(violations), ['R7 error']) + assert.match(violations[0].message, /\/new\.mdx/) + assert.equal(violations[0].line, lineOf(head, '"/new.mdx"')) + }) + + it('R7: warns about a file that is already missing on the base', () => { + const manifest = { routes: [page('/foo.mdx'), page('/gone.mdx')] } + + const violations = checkRedirects({ + base: revision(manifest, { files: ['foo.mdx'] }), + head: revision(manifest, { files: ['foo.mdx'] }) + }) + + assert.deepEqual(outcome(violations), ['R7 warning (base)']) + }) + + it('R8: fails two manifest paths with the same URL, at the second one', () => { + const base = revision({ routes: [page('/foo.mdx')] }) + const head = revision({ + routes: [page('/foo.mdx'), page('/foo/README.mdx')] + }) + + const violations = checkRedirects({ base, head }) + + assert.deepEqual(outcome(violations), ['R8 error']) + assert.match(violations[0].message, /\/foo\.mdx.*\/foo\/README\.mdx/) + assert.match(violations[0].message, /\/docs\/foo\b/) + assert.equal(violations[0].line, lineOf(head, '"/foo/README.mdx"')) + }) +}) From d92490949d444a3b5db9888a260595b3dc739221 Mon Sep 17 00:00:00 2001 From: Christian Mejlak Date: Fri, 4 Dec 2026 16:59:11 +0100 Subject: [PATCH 14/20] check-redirects: check that manifest paths exist and map to unique URLs pageFindings reports a manifest path with no file (R7) and a URL that more than one path maps to (R8), each at the line of its "path". The R7 and R8 tests expected the title's line, because the test routes use the path as their title. They now look for the "path" line. --- .github/scripts/check-redirects/rules.mjs | 39 ++++++++++++++++++- .../scripts/check-redirects/rules.test.mjs | 4 +- 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/.github/scripts/check-redirects/rules.mjs b/.github/scripts/check-redirects/rules.mjs index 39d968ad..a3ec71ba 100644 --- a/.github/scripts/check-redirects/rules.mjs +++ b/.github/scripts/check-redirects/rules.mjs @@ -139,10 +139,43 @@ function readSite(manifest, revision) { return { pages, working: new Set([...pages.keys(), ...redirects.sources]), - findings: redirects.findings + findings: [ + ...redirects.findings, + ...pageFindings(pages, revision.paths, lines) + ] } } +// R7–R8. +function pageFindings(pages, files, lines) { + const findings = [] + for (const [url, paths] of pages) { + for (const path of new Set(paths)) { + if (!files.has(path.slice(1))) { + findings.push( + manifestFinding( + 'R7', + `R7 ${path}`, + lines.path(path), + `manifest.json lists ${path}, but the file doesn't exist.` + ) + ) + } + } + if (paths.length > 1) { + findings.push( + manifestFinding( + 'R8', + `R8 ${url}`, + lines.path(paths[1]), + `Several manifest paths map to ${url}: ${paths.join(', ')}. Keep one.` + ) + ) + } + } + return findings +} + // R2–R6. A source works only when its entry passes R2–R4. function readRedirects(manifest, pages, lines) { const findings = [] @@ -272,6 +305,10 @@ function lineFinder(text) { const redirectsKey = () => find((line) => /"redirects"\s*:/.test(line)) return { redirectsKey, + path: (path) => + find( + (line) => /"path"\s*:/.test(line) && line.includes(JSON.stringify(path)) + ), source: (source) => find( (line) => diff --git a/.github/scripts/check-redirects/rules.test.mjs b/.github/scripts/check-redirects/rules.test.mjs index 5bd4857b..d5ced3cc 100644 --- a/.github/scripts/check-redirects/rules.test.mjs +++ b/.github/scripts/check-redirects/rules.test.mjs @@ -438,7 +438,7 @@ describe('checkRedirects: manifest integrity', () => { assert.deepEqual(outcome(violations), ['R7 error']) assert.match(violations[0].message, /\/new\.mdx/) - assert.equal(violations[0].line, lineOf(head, '"/new.mdx"')) + assert.equal(violations[0].line, lineOf(head, '"path": "/new.mdx"')) }) it('R7: warns about a file that is already missing on the base', () => { @@ -463,6 +463,6 @@ describe('checkRedirects: manifest integrity', () => { assert.deepEqual(outcome(violations), ['R8 error']) assert.match(violations[0].message, /\/foo\.mdx.*\/foo\/README\.mdx/) assert.match(violations[0].message, /\/docs\/foo\b/) - assert.equal(violations[0].line, lineOf(head, '"/foo/README.mdx"')) + assert.equal(violations[0].line, lineOf(head, '"path": "/foo/README.mdx"')) }) }) From 30cde9a0de95dc0881b81ce570ebf869f80f966a Mon Sep 17 00:00:00 2001 From: Christian Mejlak Date: Fri, 4 Dec 2026 17:01:44 +0100 Subject: [PATCH 15/20] check-redirects: test links to removed pages and non-pages docsLinks reads the docs URLs an .mdx file links to, and the line of each: - inline links, reference definitions, JSX href, and autolinks or bare https://smallstep.com/docs URLs; - skipped: images, footnotes, fenced and inline code, other schemes and hosts, anchors and assets. Each link resolves the way smallstep.com renders it: - Markdown links as remark-relative-links.js rewrites them, against the file's directory; - JSX hrefs as the browser resolves them, since the site leaves them alone; - then the fragment, query string, trailing slash, and trailing /index.html or /README are dropped. It must stay fast on hostile input. A link to a page the change removes fails (R9), even when the change adds a redirect. It only warns when the file is generated under step-cli/reference/. A link to any other non-page is a warning (R9b). --- .../scripts/check-redirects/links.test.mjs | 146 ++++++++++++++++++ .../scripts/check-redirects/rules.test.mjs | 77 +++++++++ 2 files changed, 223 insertions(+) create mode 100644 .github/scripts/check-redirects/links.test.mjs diff --git a/.github/scripts/check-redirects/links.test.mjs b/.github/scripts/check-redirects/links.test.mjs new file mode 100644 index 00000000..db83bc73 --- /dev/null +++ b/.github/scripts/check-redirects/links.test.mjs @@ -0,0 +1,146 @@ +import assert from 'node:assert/strict' +import { describe, it } from 'node:test' +import { performance } from 'node:perf_hooks' + +import { docsLinks } from './links.mjs' + +const links = (file, text) => + docsLinks(file, text).map(({ line, url }) => `${line} ${url}`) + +describe('docsLinks', () => { + it('reads an inline link to a docs URL', () => { + assert.deepEqual( + links( + 'ssh/README.mdx', + 'See [step-ca](https://smallstep.com/docs/step-ca/).' + ), + ['1 /docs/step-ca'] + ) + }) + + it('reads a /docs path and drops its fragment and query', () => { + assert.deepEqual( + links('ssh/README.mdx', 'See [hosts](/docs/ssh/hosts?os=linux#keys).'), + ['1 /docs/ssh/hosts'] + ) + }) + + it("resolves a relative link against the file's directory, as the site does", () => { + const text = [ + '[templates](templates.mdx#syntax)', + '[guide](../tutorials/acme.mdx)', + '[CLI](../step-cli/README.mdx)', + '[this section](README.mdx)' + ].join('\n') + + assert.deepEqual(links('step-ca/provisioners.mdx', text), [ + '1 /docs/step-ca/templates', + '2 /docs/tutorials/acme', + '3 /docs/step-cli', + '4 /docs/step-ca' + ]) + }) + + it('resolves a relative link from a README against its own directory', () => { + assert.deepEqual( + links('step-cli/reference/ca/README.mdx', 'See [email](email/).'), + ['1 /docs/step-cli/reference/ca/email'] + ) + }) + + it('resolves a JSX href as a browser does, from the page URL', () => { + const wired = links( + 'tutorials/protect-wired-networks.mdx', + 'Set up wireless.' + ) + const ssh = links( + 'ssh/README.mdx', + `step-ca and mTLS` + ) + + assert.deepEqual(wired, [ + '1 /docs/tutorials/protect-wired-networks/protect-wireless-networks.mdx' + ]) + assert.deepEqual(ssh, ['1 /docs/step-ca', '1 /docs/mtls']) + }) + + it('reads reference definitions but not footnotes', () => { + const text = [ + '[ca]: https://smallstep.com/docs/step-ca', + '[^1]: https://smallstep.com/docs/gone' + ].join('\n') + + assert.deepEqual(links('ssh/README.mdx', text), ['1 /docs/step-ca']) + }) + + it('reads autolinks and bare URLs without trailing punctuation', () => { + const text = [ + 'See .', + 'Templates: https://smallstep.com/docs/step-ca/templates/index.html#syntax.' + ].join('\n') + + assert.deepEqual(links('ssh/README.mdx', text), [ + '1 /docs/ssh', + '2 /docs/step-ca/templates' + ]) + }) + + it('skips images, code, other schemes and hosts, anchors and assets', () => { + const text = [ + '![diagram](https://smallstep.com/docs/step-ca)', + '```bash', + 'curl https://smallstep.com/docs/inside-a-fence', + '```', + 'Run `open https://smallstep.com/docs/inline-code` now.', + 'Run ``a ` tick https://smallstep.com/docs/double-ticks`` too.', + '[mail](mailto:support@smallstep.com)', + '[other](https://example.com/docs/step-ca)', + '[plain http](http://smallstep.com/docs/old)', + '[anchor](#install)', + 'settings', + '[sheet](https://smallstep.com/docs/sheet.pdf)', + '[logo](../graphics/logo.png)' + ].join('\n') + + assert.deepEqual(links('step-ca/README.mdx', text), []) + }) + + it('skips a fence indented inside a list item', () => { + const text = [ + '1. Fetch it:', + ' ```', + ' curl https://smallstep.com/docs/inside-a-fence', + ' ```', + '2. Read [the guide](https://smallstep.com/docs/step-ca).' + ].join('\n') + + assert.deepEqual(links('ssh/README.mdx', text), ['5 /docs/step-ca']) + }) + + it('reads each link once when the text repeats the URL', () => { + assert.deepEqual( + links( + 'ssh/README.mdx', + '[https://smallstep.com/docs/ssh](https://smallstep.com/docs/ssh)' + ), + ['1 /docs/ssh'] + ) + }) + + it('stays fast on hostile input', () => { + const hostile = [ + '['.repeat(100_000), + '[a]('.repeat(25_000), + '](x'.repeat(30_000), + '` a'.repeat(30_000), + 'https://smallstep.com/docs/' + 'a'.repeat(100_000), + ' { + const reference = page('/step-cli/reference/README.mdx') + const before = { + routes: [page('/README.mdx'), page('/old.mdx'), page('/new.mdx'), reference] + } + const after = { + routes: [page('/README.mdx'), page('/new.mdx'), reference], + redirects: [{ source: '/docs/old', destination: '/docs/new' }] + } + const outcome = (violations) => + violations.map( + ({ rule, severity, introduced, file, line }) => + `${rule} ${severity}${introduced ? '' : ' (base)'} ${file}:${line}` + ) + + it('R9: fails a link to a page the change removes, even with a redirect', () => { + const mdx = { 'new.mdx': '# New\n\nIt replaces [the old page](old.mdx).\n' } + + const violations = checkRedirects({ + base: revision(before, { mdx }), + head: revision(after, { mdx }) + }) + + assert.deepEqual(outcome(violations), ['R9 error new.mdx:3']) + assert.match(violations[0].message, /\/docs\/old/) + }) + + it('R9: only warns when a generated reference page has the link', () => { + const mdx = { 'step-cli/reference/README.mdx': 'See [old](/docs/old).\n' } + + const violations = checkRedirects({ + base: revision(before, { mdx }), + head: revision(after, { mdx }) + }) + + assert.deepEqual(outcome(violations), [ + 'R9 warning step-cli/reference/README.mdx:1' + ]) + }) + + it('R9b: warns about a new link to a URL that is not a page', () => { + const violations = checkRedirects({ + base: revision(before, { mdx: { 'new.mdx': '# New\n' } }), + head: revision(before, { + mdx: { 'new.mdx': '# New\n[gone](/docs/gone)\n' } + }) + }) + + assert.deepEqual(outcome(violations), ['R9b warning new.mdx:2']) + }) + + it('R9b: reports a link that is already broken on the base as existing', () => { + const mdx = { 'new.mdx': '[gone](/docs/gone)\n' } + + const violations = checkRedirects({ + base: revision(before, { mdx }), + head: revision(before, { mdx }) + }) + + assert.deepEqual(outcome(violations), ['R9b warning (base) new.mdx:1']) + }) + + it('passes links to pages', () => { + const mdx = { + 'new.mdx': '[home](/docs) and [new](https://smallstep.com/docs/new/)\n' + } + + assert.deepEqual( + checkRedirects({ + base: revision(before, { mdx }), + head: revision(before, { mdx }) + }), + [] + ) + }) +}) From bbcea001569463ead457b92ccb57ee7a007bacf4 Mon Sep 17 00:00:00 2001 From: Christian Mejlak Date: Fri, 4 Dec 2026 17:03:48 +0100 Subject: [PATCH 16/20] check-redirects: check links to removed pages and non-pages links.mjs reads the links of each .mdx file one line at a time, outside fenced and inline code. Every pattern has bounded repeats: a 100k-character line of "[" takes about 120 ms. How a link resolves: - A Markdown link or definition resolves as remark-relative-links.js rewrites it. - A JSX href resolves from the page URL as a browser would. The site renders JSX untouched, so on /docs/a/b/ leads to /docs/a/b/x.mdx. pageUrl moves to links.mjs, so rules.mjs depends on links.mjs and not the other way round. R9 is an error for a link to a page the change removes, and a warning when a generated reference page has it. R9b warns about any other link to a non-page. On main (247185f) the check reports three existing R9b warnings, not the two the spec expects. The third is tutorials/protect-wired-networks.mdx:30, whose relative JSX href leads to /docs/tutorials/protect-wired-networks/protect-wireless-networks.mdx. smallstep.com answers that URL only through a redirects.js entry. --- .github/scripts/check-redirects/links.mjs | 186 ++++++++++++++++++++++ .github/scripts/check-redirects/rules.mjs | 92 +++++++---- 2 files changed, 250 insertions(+), 28 deletions(-) create mode 100644 .github/scripts/check-redirects/links.mjs diff --git a/.github/scripts/check-redirects/links.mjs b/.github/scripts/check-redirects/links.mjs new file mode 100644 index 00000000..4da781f1 --- /dev/null +++ b/.github/scripts/check-redirects/links.mjs @@ -0,0 +1,186 @@ +import { posix } from 'node:path' + +const SITE = 'https://smallstep.com' + +// Every repeat is bounded, and lines are matched one at a time, so no pattern +// backtracks across a whole hostile file. +const FENCE = /^[ \t]*(`{3,}|~{3,})(.*)$/ +const DEFINITION = /^ {0,3}\[([^\]]{1,500})\]:[ \t]*]{1,2000})/ +const INLINE = + /(!?)\[[^\]]{0,500}\]\([ \t]{0,10}]{1,2000})>?(?:[ \t]{1,10}(?:"[^"]{0,500}"|'[^']{0,500}'))?[ \t]{0,10}\)/g +const HREF = /\bhref[ \t]{0,5}=[ \t]{0,5}(?:"([^"]{1,2000})"|'([^']{1,2000})')/g +const BARE = /https:\/\/smallstep\.com\/docs(?![\w-])[^\s<>"'`()[\]{}]{0,2000}/g + +/** + * The URL smallstep.com serves a manifest path at, as its convertPathToSlug + * maps it. + * + * @param {string} path - A manifest path such as /step-ca/README.mdx + * @returns {string} A URL without a trailing slash + * + * @example + * pageUrl('/step-ca/README.mdx') // => '/docs/step-ca' + */ +export function pageUrl(path) { + const segments = path + .replace(/\.mdx$/, '') + .replace(/^\//, '') + .split('/') + .filter((segment) => segment !== 'README') + return ['/docs', ...segments].join('/') +} + +/** + * The docs URLs an .mdx file links to, each with its line, resolved the way + * smallstep.com renders the link. + * + * @param {string} file - Path from the repo root, such as step-ca/README.mdx + * @param {string} text - The file's contents + * @returns {{ url: string, line: number }[]} URLs without a trailing slash + * + * @example + * docsLinks('step-ca/provisioners.mdx', 'See [templates](templates.mdx).') + * // => [{ url: '/docs/step-ca/templates', line: 1 }] + */ +export function docsLinks(file, text) { + const links = [] + let fence = null + for (const [index, line] of text.split('\n').entries()) { + const marker = line.match(FENCE) + if (fence) { + if (isClosingFence(marker, fence)) fence = null + continue + } + // A backtick fence's info string can't hold a backtick; ```a``` is code. + if (marker && !(marker[1][0] === '`' && marker[2].includes('`'))) { + fence = marker[1] + continue + } + for (const { target, kind } of targets(withoutCodeSpans(line))) { + const url = docsUrl(file, target, kind) + if (url) links.push({ url, line: index + 1 }) + } + } + return links +} + +const isClosingFence = (marker, fence) => + marker !== null && + marker[1][0] === fence[0] && + marker[1].length >= fence.length && + marker[2].trim() === '' + +// Inline code shows text, not links. A run of backticks opens a span that the +// next run of the same length closes; a run with no partner is literal. +function withoutCodeSpans(line) { + const runs = [...line.matchAll(/`+/g)].map((match) => ({ + start: match.index, + end: match.index + match[0].length + })) + const partner = [] + const nextOfLength = new Map() + for (let i = runs.length - 1; i >= 0; i--) { + const length = runs[i].end - runs[i].start + partner[i] = nextOfLength.get(length) + nextOfLength.set(length, i) + } + + let result = '' + let copied = 0 + for (let i = 0; i < runs.length; i++) { + const close = partner[i] + if (close === undefined) continue + result += + line.slice(copied, runs[i].start) + + ' '.repeat(runs[close].end - runs[i].start) + copied = runs[close].end + i = close + } + return result + line.slice(copied) +} + +// Link targets in one line of prose. Each match is blanked out, so a URL that +// is also a link's text or target is read once. +function targets(line) { + const definition = line.match(DEFINITION) + if (definition) { + return definition[1].startsWith('^') + ? [] + : [{ target: definition[2], kind: 'markdown' }] + } + + const found = [] + const rest = line + .replace(INLINE, (match, image, target) => { + if (!image) found.push({ target, kind: 'markdown' }) + return ' '.repeat(match.length) + }) + .replace(HREF, (match, double, single) => { + found.push({ target: double ?? single, kind: 'jsx' }) + return ' '.repeat(match.length) + }) + for (const [url] of rest.matchAll(BARE)) { + found.push({ target: url.replace(/[.,;:!?]+$/, ''), kind: 'absolute' }) + } + return found +} + +// The docs URL a link leads to on smallstep.com, or null when it leads +// elsewhere or to an asset. +function docsUrl(file, target, kind) { + if (target.startsWith('#') || target.startsWith('//')) return null + if (/^[a-z][a-z\d+.-]*:/i.test(target)) { + if (target !== SITE && !target.startsWith(`${SITE}/`)) return null + target = target.slice(SITE.length) || '/' + kind = 'absolute' + } + if (isAsset(target)) return null + + let path = target + if (kind === 'markdown') path = renderedMarkdownUrl(file, target) + else if (kind === 'jsx' && !target.startsWith('/')) { + // The site leaves JSX alone, so the browser resolves it from the page URL. + path = new URL(target, `${SITE}${pageUrl(`/${file}`)}/`).pathname + } + + // The router also serves a README page at /README, and + // smallstep.com redirects /:path*/index.html to /:path*/. + const url = path + .replace(/[?#].*$/, '') + .replace(/\/+$/, '') + .replace(/\/(?:index\.html|README)$/, '') + return url === '/docs' || url.startsWith('/docs/') ? url : null +} + +function isAsset(target) { + const path = target.replace(/[?#].*$/, '') + const name = path.slice(path.lastIndexOf('/') + 1) + const dot = name.lastIndexOf('.') + return ( + dot > 0 && + !['mdx', 'md', 'html'].includes(name.slice(dot + 1).toLowerCase()) + ) +} + +// How smallstep.com's remark-relative-links.js rewrites a Markdown link, quirks +// included, so the check sees the URL the site renders. +function renderedMarkdownUrl(file, target) { + let rootPath = `/${file}` + let url = target + if (!url.startsWith('#')) + rootPath = rootPath.split('/').slice(0, -1).join('/') + for (const extension of ['.mdx', '.md']) { + rootPath = rootPath.replace(extension, '') + url = url.replace(extension, '') + } + if (!rootPath.startsWith('/docs')) rootPath = `/docs${rootPath}` + rootPath = rootPath.replace('/README', '') + url = url.replace('/README', '') + + const depth = (target.match(/\.\.\//g) ?? []).length + const skipPrefix = depth > 0 && rootPath.split('/').slice(1).length === depth + const resolved = posix.resolve(rootPath, url) + return !skipPrefix && !resolved.startsWith('/docs') && !target.startsWith('/') + ? `/docs${resolved}` + : resolved +} diff --git a/.github/scripts/check-redirects/rules.mjs b/.github/scripts/check-redirects/rules.mjs index a3ec71ba..0231f66c 100644 --- a/.github/scripts/check-redirects/rules.mjs +++ b/.github/scripts/check-redirects/rules.mjs @@ -1,3 +1,7 @@ +import { docsLinks, pageUrl } from './links.mjs' + +export { pageUrl } + /** * @typedef {object} Revision * @property {string | null} manifestText - manifest.json, or null when it is missing @@ -16,6 +20,9 @@ const REFERENCE_PREFIX = '/docs/step-cli/reference/' +// Rules that only warn, even about a problem the change introduces. +const WARNING_RULES = new Set(['R9b']) + // smallstep.com matches a source exactly against /docs/, so a source is // /docs plus at least one segment with no query, fragment, empty segment, // trailing slash or pattern syntax. A destination may be /docs itself and may @@ -57,7 +64,7 @@ export function checkRedirects({ base, head }) { file: 'manifest.json', message: `The base manifest.json is unreadable (${baseRead.problem}), so R1 and R9 were skipped and every other finding is a warning.` }, - ...headSite.findings.map((finding) => ({ + ...[...headSite.findings, ...linkFindings(headSite)].map((finding) => ({ ...finding, severity: 'warning', introduced: false @@ -65,18 +72,29 @@ export function checkRedirects({ base, head }) { ] } const baseSite = readSite(baseRead.manifest, base) - const onBase = new Set(baseSite.findings.map(({ key }) => key)) + const onBase = new Set( + [...baseSite.findings, ...linkFindings(baseSite)].map(({ key }) => key) + ) + const removedPages = new Set( + [...baseSite.pages.keys()].filter((url) => !headSite.pages.has(url)) + ) return [ ...removedUrlViolations(baseSite, headSite), - ...headSite.findings.map((finding) => { - const introduced = !onBase.has(finding.key) - return { - ...finding, - severity: introduced ? 'error' : 'warning', - introduced + ...removedPageLinks(headSite, removedPages), + ...[...headSite.findings, ...linkFindings(headSite, removedPages)].map( + (finding) => { + const introduced = !onBase.has(finding.key) + return { + ...finding, + severity: + introduced && !WARNING_RULES.has(finding.rule) + ? 'error' + : 'warning', + introduced + } } - }) + ) ] } @@ -111,25 +129,6 @@ export function readManifest(text) { return problem ? { problem } : { manifest } } -/** - * The URL smallstep.com serves a manifest path at, as its convertPathToSlug - * maps it. - * - * @param {string} path - A manifest path such as /step-ca/README.mdx - * @returns {string} A URL without a trailing slash - * - * @example - * pageUrl('/step-ca/README.mdx') // => '/docs/step-ca' - */ -export function pageUrl(path) { - const segments = path - .replace(/\.mdx$/, '') - .replace(/^\//, '') - .split('/') - .filter((segment) => segment !== 'README') - return ['/docs', ...segments].join('/') -} - // What one revision serves, and the problems it has on its own. Findings get // their severity once the head is compared with the base. function readSite(manifest, revision) { @@ -139,6 +138,9 @@ function readSite(manifest, revision) { return { pages, working: new Set([...pages.keys(), ...redirects.sources]), + links: [...revision.mdx].flatMap(([file, text]) => + docsLinks(file, text).map((link) => ({ file, ...link })) + ), findings: [ ...redirects.findings, ...pageFindings(pages, revision.paths, lines) @@ -318,6 +320,40 @@ function lineFinder(text) { } } +// R9. Generated reference pages can only change in smallstep/cli, so a link +// there is a warning. +function removedPageLinks(headSite, removedPages) { + return headSite.links + .filter(({ url }) => removedPages.has(url)) + .map(({ file, line, url }) => { + const generated = file.startsWith('step-cli/reference/') + return { + rule: 'R9', + key: `R9 ${file} ${url}`, + severity: generated ? 'warning' : 'error', + introduced: true, + file, + line, + message: generated + ? `${file} links to ${url}, which this change removes. The file is generated by smallstep/cli, so the link has to change there.` + : `${file} links to ${url}, which this change removes. Point the link at the page that replaces it.` + } + }) +} + +// R9b. Links to removed pages are R9's, so they are left out here. +function linkFindings(site, removedPages = new Set()) { + return site.links + .filter(({ url }) => !site.pages.has(url) && !removedPages.has(url)) + .map(({ file, line, url }) => ({ + rule: 'R9b', + key: `R9b ${file} ${url}`, + file, + line, + message: `${file} links to ${url}, which isn't a docs page.` + })) +} + function removedUrlViolations(baseSite, headSite) { return [...baseSite.working] .filter( From 8ab09776ef8fb907db50434f35af2086f041feb5 Mon Sep 17 00:00:00 2001 From: Christian Mejlak Date: Fri, 4 Dec 2026 17:04:28 +0100 Subject: [PATCH 17/20] check-redirects: replay a step-ci push and main The step-ci push 5184bd81 removed ten beta/ca reference pages without a redirect, which the reference exemption allows. It fails only for the hand-written link to one of them, at certificate-manager/kubernetes-tls/kubernetes-step-issuer.mdx:31. Main at 247185f has no errors and exactly three existing R9b warnings. A full run over main takes about 0.27 s. --- .../scripts/check-redirects/replay.test.mjs | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/.github/scripts/check-redirects/replay.test.mjs b/.github/scripts/check-redirects/replay.test.mjs index f1de5106..fd5e1ac2 100644 --- a/.github/scripts/check-redirects/replay.test.mjs +++ b/.github/scripts/check-redirects/replay.test.mjs @@ -49,6 +49,41 @@ describe('replays of docs history', () => { ]) }) + // step-travis-ci pushed this straight to main and removed ten beta/ca + // reference pages. Removed reference pages need no redirect, but a + // hand-written page that links to one has to change. + it('fails a step-ci push only for a hand-written link to a page it removed', (t) => { + const violations = replay(t, '5184bd81^1', '5184bd81') + if (!violations) return + + assert.deepEqual(errorKeys(violations), [ + 'R9 certificate-manager/kubernetes-tls/kubernetes-step-issuer.mdx /docs/step-cli/reference/beta/ca/provisioner/add' + ]) + assert.equal( + violations.find(({ severity }) => severity === 'error').line, + 31 + ) + }) + + it('finds no errors on main, and exactly the three known broken links', (t) => { + const violations = replay(t, '247185f', '247185f') + if (!violations) return + + assert.deepEqual( + violations + .map( + ({ rule, severity, file, line }) => + `${rule} ${severity} ${file}:${line}` + ) + .sort(), + [ + 'R9b warning certificate-manager/kubernetes-tls/kubernetes-step-issuer.mdx:32', + 'R9b warning step-ca/certificate-authority-server-production.mdx:837', + 'R9b warning tutorials/protect-wired-networks.mdx:30' + ] + ) + }) + it('fails PR #493 for exactly the tutorial it removed', (t) => { const violations = replay(t, '63979d5f^1', '63979d5f') if (!violations) return From 83beee0c0b437ed0cfe01a16d8f12a07067b6eb5 Mon Sep 17 00:00:00 2001 From: Christian Mejlak Date: Fri, 4 Dec 2026 17:08:55 +0100 Subject: [PATCH 18/20] check-redirects: run the check and its tests in CI check-redirects.yml is meant to become a required check: - It runs on every pull request, with no paths filter, and on `edited` too, so changing the base branch runs it again. - It checks out the merge commit with fetch-depth 2 and fails if HEAD has no second parent, because only then is HEAD^1 the base branch. - It has a read-only token, no persisted credentials, no secrets and no job-level `if`. A skipped required check counts as passing. check-redirects-tests.yml runs the script's tests when the script or these workflows change. It fetches full history for the replays. Both pin actions/checkout v7.0.1 and actions/setup-node v7.2.0 to commit SHAs and use Node 24. actionlint reports nothing. --- .github/workflows/check-redirects-tests.yml | 31 ++++++++++++++++ .github/workflows/check-redirects.yml | 39 +++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 .github/workflows/check-redirects-tests.yml create mode 100644 .github/workflows/check-redirects.yml diff --git a/.github/workflows/check-redirects-tests.yml b/.github/workflows/check-redirects-tests.yml new file mode 100644 index 00000000..407d21d5 --- /dev/null +++ b/.github/workflows/check-redirects-tests.yml @@ -0,0 +1,31 @@ +name: Test the redirect check + +on: + pull_request: + paths: + - '.github/scripts/**' + - '.github/workflows/check-redirects*.yml' + push: + branches: [main] + paths: + - '.github/scripts/**' + - '.github/workflows/check-redirects*.yml' + +permissions: + contents: read + +jobs: + check-redirects-tests: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + # The replays read old commits from this repository's history. + fetch-depth: 0 + persist-credentials: false + - uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0 + with: + node-version: 24 + - name: Run the tests + run: node --test '.github/scripts/**/*.test.mjs' diff --git a/.github/workflows/check-redirects.yml b/.github/workflows/check-redirects.yml new file mode 100644 index 00000000..848d8ff2 --- /dev/null +++ b/.github/workflows/check-redirects.yml @@ -0,0 +1,39 @@ +name: Check redirects + +# A required check: a removed docs URL needs a redirect in manifest.json, and +# redirects must be well formed. There is no paths filter, because a required +# check skipped by one never reports. `edited` runs it again when the base +# branch changes. +on: + pull_request: + types: [opened, synchronize, reopened, edited] + +permissions: + contents: read + +concurrency: + group: check-redirects-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + check-redirects: + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 2 + persist-credentials: false + - uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0 + with: + node-version: 24 + # The check compares HEAD with HEAD^1, which is the base branch only when + # HEAD is the merge commit actions/checkout makes for a pull request. + - name: Require the merge commit + run: | + if ! git rev-parse --verify --quiet 'HEAD^2' > /dev/null; then + echo "::error::HEAD isn't the pull request's merge commit, so HEAD^1 isn't the base branch." + exit 1 + fi + - name: Check redirects + run: node .github/scripts/check-redirects.mjs --base 'HEAD^1' --head HEAD From caa704e9fcf1b6159c1d93fbf44ec7ac8c6071e6 Mon Sep 17 00:00:00 2001 From: Christian Mejlak Date: Fri, 4 Dec 2026 17:09:22 +0100 Subject: [PATCH 19/20] Add an empty redirects list to the manifest smallstep.com serves each entry of a top-level "redirects" array in manifest.json as a 308 (smallstep/smallstep.com#1303). The list starts empty, and each later change that removes a docs URL adds its redirect here. The reference update in smallstep/cli's release workflow replaces only the routes of the node marked isStepReference, so it keeps this key. --- manifest.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/manifest.json b/manifest.json index df2916b4..3a40c6df 100644 --- a/manifest.json +++ b/manifest.json @@ -1708,5 +1708,6 @@ } ] } - ] + ], + "redirects": [] } From 30f2c958e96b9f9affbc4e00edde7d2ecc024c7c Mon Sep 17 00:00:00 2001 From: Christian Mejlak Date: Fri, 4 Dec 2026 17:09:41 +0100 Subject: [PATCH 20/20] Document how to remove, rename, or move a page CONTRIBUTING.md gets a section on the redirect a change needs when it takes a docs URL away: - the entry format; - that the destination must be a page; - updating links to the old URL in the same pull request; - why reference pages need none; - how to run the check locally, including when origin is a fork. AGENTS.md gets the same rule and the local command. --- AGENTS.md | 2 ++ CONTRIBUTING.md | 31 +++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 32f3b28e..1254e5d6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -5,6 +5,8 @@ vale --no-wrap --glob='!step-cli/reference/**' DO NOT modify any auto-generated files inside step-cli/reference Use markdown-link-check to check links +When removing, renaming, or moving a page, add a redirect to `redirects` in manifest.json and update links to the old URL (see CONTRIBUTING.md) +Check redirects with `node .github/scripts/check-redirects.mjs` To preview the docs in a web browser, run `pnpm dev` inside the `smallstep.com` repo, which you may find in the parent directory. A server will open on https://localhost:5050 Use pnpm If new dependencies are needed, update CONTRIBUTING.md to reflect requirements diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fc12afc9..ffa556ad 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -33,6 +33,37 @@ Issues and pull requests are welcome! Everything under `src/pages/docs/step-cli/reference` is auto-generated whenever we release a new version of `step`. To make a change to the CLI reference, you'll have to make the edit in [smallstep/cli](https://github.com/smallstep/cli) and make a PR over there. The reference docs are embedded in the source files under the `command` folder in that repo. +## Removing, renaming, or moving a page + +Other sites, search engines, and the Smallstep product link to docs URLs. +When a pull request takes a URL away, it must also add a redirect for that URL to `redirects` in [`manifest.json`](manifest.json): + +```json +"redirects": [ + { + "source": "/docs/tutorials/old-page", + "destination": "/docs/tutorials/new-page" + } +] +``` + +- `source` is the old URL: `/docs/` and the old path, with no trailing slash. +- `destination` is a docs page that still exists. It can end in a `#fragment`. +- Update links to the old URL in the same pull request. +- Pages under `step-cli/reference` don't need a redirect. + smallstep.com sends a removed reference URL to its nearest parent page. +- Keep a redirect until the docs serve a page at its `source` again. + +The `check-redirects` pull request check enforces these rules. +To run it locally, you need Node.js 22 or later: + +```bash +node .github/scripts/check-redirects.mjs +``` + +It compares your working tree with `origin/main`. +If `origin` is your fork, add `--base upstream/main`. + ## Practical zero trust The Practical Zero Trust articles are a bit different.