diff --git a/.github/scripts/check-redirects.mjs b/.github/scripts/check-redirects.mjs new file mode 100644 index 00000000..7b898320 --- /dev/null +++ b/.github/scripts/check-redirects.mjs @@ -0,0 +1,207 @@ +#!/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 { 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, + inert, + 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) { + // 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({ + args: argv, + options: { + base: { type: 'string', default: 'origin/main' }, + head: { type: 'string' } + } + }).values + } catch (err) { + console.error(shown(`${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( + shown(`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(shown(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 entries = git(root, 'ls-tree', '-r', '-z', '--full-tree', commit) + .split('\0') + .filter(Boolean) + .map(treeEntry) + const wanted = entries.filter( + ({ type, path }) => type === 'blob' && isRead(path) + ) + const texts = catFile( + root, + 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) + ) +} + +/** + * 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') + +// " \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: oids.join('\n') + '\n', + maxBuffer: MAX_BUFFER, + stdio: ['pipe', 'pipe', 'pipe'] + }) + + const texts = [] + let offset = 0 + for (const oid of oids) { + const headerEnd = output.indexOf(0x0a, offset) + 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}`) + } + 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 +} + +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/cli.test.mjs b/.github/scripts/check-redirects/cli.test.mjs new file mode 100644 index 00000000..3ccc77ce --- /dev/null +++ b/.github/scripts/check-redirects/cli.test.mjs @@ -0,0 +1,298 @@ +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' +} + +// 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, + 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.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') + 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('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') }) + + 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) + }) + + // 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) + + 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('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) + 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/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/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), + ' + docsLinks(file, text).map((link) => ({ file, ...link })) + ), + 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 = [] + 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, + path: (path) => + find( + (line) => /"path"\s*:/.test(line) && line.includes(JSON.stringify(path)) + ), + source: (source) => + find( + (line) => + /"source"\s*:/.test(line) && line.includes(JSON.stringify(source)), + (redirectsKey() ?? 1) - 1 + ) + } +} + +// 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( + (url) => !headSite.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 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') diff --git a/.github/scripts/check-redirects/rules.test.mjs b/.github/scripts/check-redirects/rules.test.mjs new file mode 100644 index 00000000..8a8bc776 --- /dev/null +++ b/.github/scripts/check-redirects/rules.test.mjs @@ -0,0 +1,545 @@ +import assert from 'node:assert/strict' +import { describe, it } from 'node:test' + +import { checkRedirects, pageUrl, readManifest } from './rules.mjs' + +// 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(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', () => { + 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('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')] }) + + 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) + 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', () => { + 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/) + }) + }) +}) + +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'] + ) + }) +}) + +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, '"path": "/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, '"path": "/foo/README.mdx"')) + }) +}) + +describe('checkRedirects: links', () => { + 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 }) + }), + [] + ) + }) +}) 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 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. diff --git a/manifest.json b/manifest.json index df2916b4..3a40c6df 100644 --- a/manifest.json +++ b/manifest.json @@ -1708,5 +1708,6 @@ } ] } - ] + ], + "redirects": [] }