-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathverify-rendered-links.js
More file actions
212 lines (198 loc) · 7.16 KB
/
Copy pathverify-rendered-links.js
File metadata and controls
212 lines (198 loc) · 7.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
const fs = require('node:fs');
const path = require('node:path');
const {parse} = require('parse5');
const HOST = 'learn.netdata.cloud';
function allowedRenderedRedirectSources(policy) {
const configured = policy.allowed_rendered_redirect_sources ?? [];
if (!Array.isArray(configured)) {
throw new Error('allowed_rendered_redirect_sources must be an array');
}
const allowed = new Set();
for (const source of configured) {
if (
typeof source !== 'string' ||
!source.startsWith('/') ||
/[*:?#]/.test(source) ||
normalizePathname(source) !== source ||
allowed.has(source)
) {
throw new Error(`Invalid allowed rendered redirect source: ${JSON.stringify(source)}`);
}
allowed.add(source);
}
return allowed;
}
function decodeHtml(value) {
return value
.replace(/&#(\d+);/g, (_, code) => String.fromCodePoint(Number(code)))
.replace(/&#x([0-9a-f]+);/gi, (_, code) => String.fromCodePoint(Number.parseInt(code, 16)))
.replaceAll('&', '&')
.replaceAll('"', '"')
.replaceAll(''', "'");
}
function normalizePathname(value) {
let pathname;
try {
pathname = decodeURIComponent(value);
} catch {
pathname = value;
}
return pathname || '/';
}
function redirectSourceRules(netlifyToml, host = HOST) {
const exact = new Set();
const terminalWildcards = new Set();
for (const match of netlifyToml.matchAll(/(?:^|\n)\s*\[\[redirects\]\]([\s\S]*?)(?=(?:\n\s*\[\[)|$)/g)) {
const from = match[1].match(/(?:^|\n)\s*from\s*=\s*"([^"]+)"/);
if (!from) continue;
let source = decodeHtml(from[1]);
if (source.startsWith('http://') || source.startsWith('https://')) {
const url = new URL(source);
if (url.hostname !== host) continue;
source = url.pathname;
}
if (!source.startsWith('/')) continue;
if (source.endsWith('*') && !/[*:]/.test(source.slice(0, -1))) {
terminalWildcards.add(normalizePathname(source.slice(0, -1)));
} else if (!/[*:]/.test(source)) {
exact.add(normalizePathname(source));
}
}
return {exact, terminalWildcards};
}
function exactRedirectSources(netlifyToml, host = HOST) {
return redirectSourceRules(netlifyToml, host).exact;
}
function redirectSourceForPath(pathname, rules) {
if (rules.exact.has(pathname)) return pathname;
for (const prefix of rules.terminalWildcards) {
if (pathname.startsWith(prefix)) return `${prefix}*`;
}
return null;
}
function routeForFile(publishDir, filename) {
const relative = path.relative(publishDir, filename).split(path.sep).join('/');
if (relative === 'index.html') return '/';
if (relative.endsWith('/index.html')) return `/${relative.slice(0, -'/index.html'.length)}`;
return `/${relative.replace(/\.html$/i, '')}`;
}
function renderedInternalLinks(html, sourceRoute, host = HOST) {
const source = new URL(sourceRoute, `https://${host}/`);
const links = [];
const stack = [parse(html)];
while (stack.length) {
const node = stack.pop();
if (node.nodeName === 'a') {
const hrefAttribute = node.attrs?.find((attribute) => attribute.name === 'href');
const href = hrefAttribute?.value.trim();
if (href && !href.startsWith('#')) {
try {
const target = new URL(href, source);
if (['http:', 'https:'].includes(target.protocol) && target.hostname === host) {
links.push({href, pathname: normalizePathname(target.pathname)});
}
} catch {
// Invalid hrefs belong to the broader link checker, not this exact redirect gate.
}
}
}
for (let index = (node.childNodes?.length ?? 0) - 1; index >= 0; index -= 1) {
stack.push(node.childNodes[index]);
}
}
return links;
}
function verifyRenderedLinks(
publishDir,
netlifyPath,
host = HOST,
allowedRedirectSources = new Set(),
) {
const redirectRules = redirectSourceRules(fs.readFileSync(netlifyPath, 'utf8'), host);
for (const source of allowedRedirectSources) {
if (!redirectRules.exact.has(source)) {
throw new Error(`Allowed rendered redirect source is not an exact redirect: ${source}`);
}
}
const htmlFiles = [];
const stack = [publishDir];
while (stack.length) {
const directory = stack.pop();
for (const entry of fs.readdirSync(directory, {withFileTypes: true})) {
const filename = path.join(directory, entry.name);
if (entry.isDirectory()) stack.push(filename);
else if (entry.isFile() && entry.name.endsWith('.html')) htmlFiles.push(filename);
}
}
if (htmlFiles.length === 0) {
throw new Error(`Rendered link verification found no HTML files in ${publishDir}`);
}
const violations = [];
let internalLinks = 0;
let allowedRedirectLinks = 0;
for (const filename of htmlFiles.sort()) {
const sourceRoute = routeForFile(publishDir, filename);
for (const link of renderedInternalLinks(fs.readFileSync(filename, 'utf8'), sourceRoute, host)) {
internalLinks += 1;
const redirectSource = redirectSourceForPath(link.pathname, redirectRules);
if (redirectSource) {
if (allowedRedirectSources.has(redirectSource)) {
allowedRedirectLinks += 1;
continue;
}
violations.push({sourceRoute, href: link.href, redirectSource});
}
}
}
if (internalLinks === 0) {
throw new Error(
`Rendered link verification found zero internal links across ${htmlFiles.length} HTML files`,
);
}
if (violations.length) {
const detail = violations
.map(({sourceRoute, href, redirectSource}) => ` ${sourceRoute}: ${href} -> ${redirectSource}`)
.join('\n');
throw new Error(`Rendered links target redirect sources:\n${detail}`);
}
return {
htmlFiles: htmlFiles.length,
internalLinks,
redirectSources: redirectRules.exact.size + redirectRules.terminalWildcards.size,
exactRedirectSources: redirectRules.exact.size,
wildcardRedirectSources: redirectRules.terminalWildcards.size,
allowedRedirectLinks,
allowedRedirectSources: allowedRedirectSources.size,
};
}
if (require.main === module) {
try {
const publishDir = path.resolve(process.argv[2] || 'build');
const netlifyPath = path.resolve(process.argv[3] || 'netlify.toml');
const policyPath = path.resolve(process.argv[4] || 'config/redirect-policy.json');
const policy = JSON.parse(fs.readFileSync(policyPath, 'utf8'));
const allowedRedirectSources = allowedRenderedRedirectSources(policy);
const result = verifyRenderedLinks(
publishDir,
netlifyPath,
HOST,
allowedRedirectSources,
);
console.log(
`Verified ${result.internalLinks} rendered internal links across ${result.htmlFiles} HTML files avoid ${result.exactRedirectSources} exact and ${result.wildcardRedirectSources} terminal-wildcard redirect sources, except ${result.allowedRedirectLinks} links to ${result.allowedRedirectSources} policy-owned entrypoint.`,
);
} catch (error) {
console.error(`Rendered link verification failed: ${error.message}`);
process.exitCode = 1;
}
}
module.exports = {
allowedRenderedRedirectSources,
exactRedirectSources,
normalizePathname,
redirectSourceForPath,
redirectSourceRules,
renderedInternalLinks,
routeForFile,
verifyRenderedLinks,
};