-
-
Notifications
You must be signed in to change notification settings - Fork 5k
/
htmlUtils.ts
438 lines (345 loc) · 12.1 KB
/
htmlUtils.ts
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
const Entities = require('html-entities').AllHtmlEntities;
const htmlentities = new Entities().encode;
import { fileUriToPath } from '@joplin/utils/url';
const htmlparser2 = require('@joplin/fork-htmlparser2');
// [\s\S] instead of . for multiline matching
// https://stackoverflow.com/a/16119722/561309
const imageRegex = /<img([\s\S]*?)src=["']([\s\S]*?)["']([\s\S]*?)>/gi;
const anchorRegex = /<a([\s\S]*?)href=["']([\s\S]*?)["']([\s\S]*?)>/gi;
const selfClosingElements = [
'area',
'base',
'basefont',
'br',
'col',
'command',
'embed',
'frame',
'hr',
'img',
'input',
'isindex',
'keygen',
'link',
'meta',
'param',
'source',
'track',
'wbr',
];
interface SanitizeHtmlOptions {
addNoMdConvClass?: boolean;
allowedFilePrefixes?: string[];
}
export const attributesHtml = (attr: Record<string, string>) => {
const output = [];
for (const n in attr) {
if (!attr.hasOwnProperty(n)) continue;
if (!attr[n]) {
output.push(n);
} else {
output.push(`${n}="${htmlentities(attr[n])}"`);
}
}
return output.join(' ');
};
export const isSelfClosingTag = (tagName: string) => {
return selfClosingElements.includes(tagName.toLowerCase());
};
class HtmlUtils {
// eslint-disable-next-line @typescript-eslint/ban-types -- Old code before rule was applied
public processImageTags(html: string, callback: Function) {
if (!html) return '';
return html.replace(imageRegex, (_v, before, src, after) => {
const action = callback({ src: src });
if (!action) return `<img${before}src="${src}"${after}>`;
if (action.type === 'replaceElement') {
return action.html;
}
if (action.type === 'replaceSource') {
return `<img${before}src="${action.src}"${after}>`;
}
if (action.type === 'setAttributes') {
const attrHtml = attributesHtml(action.attrs);
return `<img${before}${attrHtml}${after}>`;
}
throw new Error(`Invalid action: ${action.type}`);
});
}
// eslint-disable-next-line @typescript-eslint/ban-types -- Old code before rule was applied
public processAnchorTags(html: string, callback: Function) {
if (!html) return '';
interface Action {
type: 'replaceElement' | 'replaceSource' | 'setAttributes';
href: string;
html: string;
attrs: Record<string, string>;
}
return html.replace(anchorRegex, (_v, before, href, after) => {
const action: Action = callback({ href: href });
if (!action) return `<a${before}href="${href}"${after}>`;
if (action.type === 'replaceElement') {
return action.html;
}
if (action.type === 'replaceSource') {
return `<img${before}href="${action.href}"${after}>`;
}
if (action.type === 'setAttributes') {
const attrHtml = attributesHtml(action.attrs);
return `<img${before}${attrHtml}${after}>`;
}
throw new Error(`Invalid action: ${action.type}`);
});
}
public stripHtml(html: string) {
const output: string[] = [];
const tagStack: string[] = [];
const currentTag = () => {
if (!tagStack.length) return '';
return tagStack[tagStack.length - 1];
};
const disallowedTags = ['script', 'style', 'head', 'iframe', 'frameset', 'frame', 'object', 'base'];
const parser = new htmlparser2.Parser({
onopentag: (name: string) => {
tagStack.push(name.toLowerCase());
},
ontext: (decodedText: string) => {
if (disallowedTags.includes(currentTag())) return;
output.push(decodedText);
},
onclosetag: (name: string) => {
if (currentTag() === name.toLowerCase()) tagStack.pop();
},
}, { decodeEntities: true });
parser.write(html);
parser.end();
// In general, we want to get back plain text from this function, so all
// HTML entities are decoded. Howver, to prevent XSS attacks, we
// re-encode all the "<" characters, which should break any attempt to
// inject HTML tags.
return output.join('')
.replace(/\s+/g, ' ')
.replace(/</g, '<');
}
// This is tested in sanitize_links.md
private isAcceptedUrl(url: string, allowedFilePrefixes: string[]): boolean {
url = url.toLowerCase();
if (url.startsWith('https://') ||
url.startsWith('http://') ||
url.startsWith('mailto:') ||
url.startsWith('joplin://') ||
!!url.match(/:\/[0-9a-zA-Z]{32}/) ||
// We also allow anchors but only with a specific set of a characters.
// Fixes https://github.com/laurent22/joplin/issues/8286
!!url.match(/^#[a-zA-Z0-9-]+$/)) return true;
if (url.startsWith('file://')) {
// We need to do a case insensitive comparison because the URL we
// get appears to be converted to lowercase somewhere. To be
// completely sure, we make it lowercase explicitely.
const filePath = fileUriToPath(url).toLowerCase();
for (const filePrefix of allowedFilePrefixes) {
if (filePath.startsWith(filePrefix.toLowerCase())) return true;
}
}
return false;
}
public sanitizeHtml(html: string, options: SanitizeHtmlOptions = null) {
options = {
// If true, adds a "jop-noMdConv" class to all the tags.
// It can be used afterwards to restore HTML tags in Markdown.
addNoMdConvClass: false,
...options,
};
// If options.allowedFilePrefixes is `undefined`, default to [].
options.allowedFilePrefixes ??= [];
const output: string[] = [];
const tagStack: string[] = [];
const currentTag = () => {
if (!tagStack.length) return '';
return tagStack[tagStack.length - 1];
};
// When we encounter a disallowed tag, all the other tags within it are
// going to be skipped too. This is necessary to prevent certain XSS
// attacks. See sanitize_11.md
let disallowedTagDepth = 0;
// The BASE tag allows changing the base URL from which files are
// loaded, and that can break several plugins, such as Katex (which
// needs to load CSS files using a relative URL). For that reason it is
// disabled. More info: https://github.com/laurent22/joplin/issues/3021
//
// "link" can be used to escape the parser and inject JavaScript. Adding
// "meta" too for the same reason as it shouldn't be used in notes
// anyway.
//
// There are too many issues with SVG tags and to handle them properly
// we should parse them separately. Currently we are not so it is better
// to disable them. SVG graphics are still supported via the IMG tag.
const disallowedTags = [
'script', 'iframe', 'frameset', 'frame', 'object', 'base',
'embed', 'link', 'meta', 'noscript', 'button', 'form',
'input', 'select', 'textarea', 'option', 'optgroup',
'svg',
// Disallow map and area tags: <area ...> links are currently not
// sanitized as well as <a ...> links, allowing potential sandbox
// escape.
'map', 'area',
];
const parser = new htmlparser2.Parser({
onopentag: (name: string, attrs: Record<string, string>) => {
// Note: "name" and attribute names are always lowercase even
// when the input is not. So there is no need to call
// "toLowerCase" on them.
tagStack.push(name);
if (disallowedTags.includes(currentTag())) {
disallowedTagDepth++;
return;
}
if (disallowedTagDepth) return;
attrs = { ...attrs };
// Remove all the attributes that start with "on", which
// normally should be JavaScript events. A better solution
// would be to blacklist known events only but it seems the
// list is not well defined [0] and we don't want any to slip
// throught the cracks. A side effect of this change is a
// regular harmless attribute that starts with "on" will also
// be removed.
// 0: https://developer.mozilla.org/en-US/docs/Web/Events
for (const attrName in attrs) {
if (!attrs.hasOwnProperty(attrName)) continue;
if (attrName.length <= 2) continue;
if (attrName.substr(0, 2) !== 'on') continue;
delete attrs[attrName];
}
// Make sure that only non-acceptable URLs are filtered out. In
// particular we want to exclude `javascript:` URLs. This
// applies to A tags, and also AREA ones but to be safe we don't
// filter on the tag name and process all HREF attributes.
if ('href' in attrs && !this.isAcceptedUrl(attrs['href'], options.allowedFilePrefixes)) {
attrs['href'] = '#';
}
// We need to clear any such attribute, otherwise it will
// make any arbitrary link open within the application.
if ('data-from-md' in attrs) {
delete attrs['data-from-md'];
}
if (options.addNoMdConvClass) {
let classAttr = attrs['class'] || '';
if (!classAttr.includes('jop-noMdConv')) {
classAttr += ' jop-noMdConv';
attrs['class'] = classAttr.trim();
}
}
// For some reason, entire parts of HTML notes don't show up in
// the viewer when there's an anchor tag without an "href"
// attribute. It doesn't always happen and it seems to depend on
// what else is in the note but in any case adding the "href"
// fixes it. https://github.com/laurent22/joplin/issues/5687
if (name === 'a' && !attrs['href']) {
attrs['href'] = '#';
}
let attrHtml = attributesHtml(attrs);
if (attrHtml) attrHtml = ` ${attrHtml}`;
const closingSign = isSelfClosingTag(name) ? '/>' : '>';
output.push(`<${name}${attrHtml}${closingSign}`);
},
ontext: (decodedText: string) => {
if (disallowedTagDepth) return;
if (currentTag() === 'style') {
// For CSS, we have to put the style as-is inside the tag
// because if we html-entities encode it, it's not going to
// work. But it's ok because JavaScript won't run within the
// style tag. Ideally CSS should be loaded from an external
// file.
// We however have to encode at least the `<` characters to
// prevent certain XSS injections that would rely on the
// content not being encoded (see sanitize_13.md)
output.push(decodedText.replace(/</g, '<'));
} else {
output.push(htmlentities(decodedText));
}
},
onclosetag: (name: string) => {
const current = currentTag();
if (current === name.toLowerCase()) tagStack.pop();
// The Markdown sanitization code can result in calls like this:
// sanitizeHtml('<invlaid>')
// sanitizeHtml('</invalid>')
// Thus, we need to be able to remove '</invalid>', even if there is no
// corresponding opening tag.
if (disallowedTags.includes(current) || disallowedTags.includes(name)) {
if (disallowedTagDepth > 0) {
disallowedTagDepth--;
}
return;
}
if (disallowedTagDepth) return;
if (isSelfClosingTag(name)) return;
output.push(`</${name}>`);
},
}, { decodeEntities: true });
parser.write(html);
parser.end();
return output.join('');
}
}
const makeHtmlTag = (name: string, attrs: Record<string, string>) => {
let attrHtml = attributesHtml(attrs);
if (attrHtml) attrHtml = ` ${attrHtml}`;
const closingSign = isSelfClosingTag(name) ? '/>' : '>';
return `<${name}${attrHtml}${closingSign}`;
};
// Will return either the content of the <BODY> tag if it exists, or the whole
// HTML (which would be a fragment of HTML)
export const extractHtmlBody = (html: string) => {
let inBody = false;
let bodyFound = false;
const output: string[] = [];
const parser = new htmlparser2.Parser({
onopentag: (name: string, attrs: Record<string, string>) => {
if (name === 'body') {
inBody = true;
bodyFound = true;
return;
}
if (inBody) {
output.push(makeHtmlTag(name, attrs));
}
},
ontext: (encodedText: string) => {
if (inBody) output.push(encodedText);
},
onclosetag: (name: string) => {
if (inBody && name === 'body') inBody = false;
if (inBody) {
if (isSelfClosingTag(name)) return;
output.push(`</${name}>`);
}
},
}, { decodeEntities: false });
parser.write(html);
parser.end();
return bodyFound ? output.join('') : html;
};
export const htmlDocIsImageOnly = (html: string) => {
let imageCount = 0;
let nonImageFound = false;
let textFound = false;
const parser = new htmlparser2.Parser({
onopentag: (name: string) => {
if (name === 'img') {
imageCount++;
} else if (['meta'].includes(name)) {
// We allow these tags since they don't print anything
} else {
nonImageFound = true;
}
},
ontext: (text: string) => {
if (text.trim()) textFound = true;
},
});
parser.write(html);
parser.end();
return imageCount === 1 && !nonImageFound && !textFound;
};
export default new HtmlUtils();