-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsanitizer.js
More file actions
402 lines (342 loc) · 13.9 KB
/
Copy pathsanitizer.js
File metadata and controls
402 lines (342 loc) · 13.9 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
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
// sanitizer.js
// Shared HTML helpers for extension pages. Native Sanitizer API is used when
// available; the existing strict allow-list sanitizer remains as a fallback.
const MARKDOWN_ALLOWED_TAGS = new Set([
'a', 'abbr', 'b', 'blockquote', 'br', 'caption', 'code', 'col', 'colgroup',
'dd', 'del', 'details', 'div', 'dl', 'dt', 'em', 'h1', 'h2', 'h3', 'h4',
'h5', 'h6', 'hr', 'i', 'img', 'input', 'kbd', 'li', 'mark', 'ol', 'p',
'pre', 's', 'small', 'span', 'strong', 'sub', 'summary', 'sup', 'table',
'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'ul'
]);
const RICH_ALLOWED_TAGS = new Set([
...MARKDOWN_ALLOWED_TAGS,
'article', 'aside', 'footer', 'header', 'main', 'nav', 'section'
]);
const DROP_WITH_CONTENT_TAGS = new Set([
'script', 'style', 'iframe', 'object', 'embed', 'link', 'meta', 'base',
'form', 'svg', 'math', 'template', 'video', 'audio', 'source', 'track',
'canvas'
]);
const MARKDOWN_GLOBAL_ATTRS = new Set(['title', 'aria-label', 'aria-hidden', 'role']);
const RICH_GLOBAL_ATTRS = new Set([...MARKDOWN_GLOBAL_ATTRS, 'class']);
const COMMON_TAG_ATTRS = {
a: new Set(['href', 'title', 'target', 'rel']),
img: new Set(['src', 'alt', 'title', 'width', 'height', 'loading']),
input: new Set(['type', 'checked', 'disabled']),
th: new Set(['align', 'colspan', 'rowspan']),
td: new Set(['align', 'colspan', 'rowspan']),
col: new Set(['span']),
colgroup: new Set(['span']),
code: new Set(['class'])
};
const PROFILES = {
markdown: {
allowedTags: MARKDOWN_ALLOWED_TAGS,
globalAttrs: MARKDOWN_GLOBAL_ATTRS,
tagAttrs: COMMON_TAG_ATTRS,
classPolicy: 'code-language-only'
},
rich: {
allowedTags: RICH_ALLOWED_TAGS,
globalAttrs: RICH_GLOBAL_ATTRS,
tagAttrs: COMMON_TAG_ATTRS,
classPolicy: 'safe-css-tokens'
}
};
const URL_ATTRS = new Set(['href', 'src']);
const SAFE_TARGETS = new Set(['_blank', '_self', '_parent', '_top']);
const SAFE_URL_PROTOCOLS = new Set(['http:', 'https:', 'mailto:', 'tel:']);
const SAFE_ALIGN_VALUES = new Set(['left', 'right', 'center', 'justify']);
const MAX_ATTR_LENGTH = 1024;
const MAX_CLASS_ATTR_LENGTH = 512;
const nativeSanitizerCache = new Map();
function getProfile(profileName = 'markdown') {
return PROFILES[profileName] || PROFILES.markdown;
}
function escapeHtml(value) {
return String(value ?? '')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
const isSafeUrl = (value, attrName) => {
const raw = String(value ?? '').trim();
if (!raw) return false;
if (raw.startsWith('#')) return true;
try {
const currentLocation = (typeof window !== 'undefined' && window.location) ? window.location : null;
const base = currentLocation ? currentLocation.href : 'https://invalid.local/';
const parsed = new URL(raw, base);
const isSameOrigin = !!currentLocation && (
parsed.origin === currentLocation.origin
|| (parsed.protocol === currentLocation.protocol && parsed.host === currentLocation.host)
);
// Markdown image loads can make silent requests as soon as a note is previewed.
// Keep links flexible, but restrict rendered media sources to same-origin URLs
// so a pasted/imported note cannot beacon to arbitrary remote hosts.
if (attrName === 'src') return isSameOrigin;
if (SAFE_URL_PROTOCOLS.has(parsed.protocol)) return true;
if (isSameOrigin) return true;
return false;
} catch {
return false;
}
};
function sanitizeClassValue(value, tagName, profile) {
if (!value || value.length > MAX_CLASS_ATTR_LENGTH) return '';
if (profile.classPolicy === 'code-language-only') {
if (tagName !== 'code') return '';
return value
.split(/\s+/)
.filter(token => /^language-[a-z0-9_+-]+$/i.test(token))
.join(' ');
}
return value
.split(/\s+/)
.filter(token => /^[a-z0-9_-]{1,80}$/i.test(token))
.slice(0, 32)
.join(' ');
}
function sanitizeNumericAttribute(element, attrName, value) {
if (attrName === 'colspan' || attrName === 'rowspan' || attrName === 'span') {
if (!/^\d{1,3}$/.test(value) || Number(value) < 1) element.removeAttribute(attrName);
return;
}
if (attrName === 'width' || attrName === 'height') {
if (!/^\d{1,4}$/.test(value) || Number(value) < 1) element.removeAttribute(attrName);
}
}
const sanitizeAttributes = (element, profileName = 'markdown') => {
const profile = getProfile(profileName);
const tagName = element.tagName.toLowerCase();
const tagAttrs = profile.tagAttrs[tagName] || new Set();
for (const attr of Array.from(element.attributes)) {
const originalName = attr.name;
const name = originalName.toLowerCase();
const value = attr.value ?? '';
const isAllowed = profile.globalAttrs.has(name) || tagAttrs.has(name);
if (!isAllowed || name.startsWith('on') || name === 'style' || name === 'srcdoc' || value.length > MAX_ATTR_LENGTH) {
element.removeAttribute(originalName);
continue;
}
if (URL_ATTRS.has(name) && !isSafeUrl(value, name)) {
element.removeAttribute(originalName);
continue;
}
if (name === 'target' && !SAFE_TARGETS.has(value)) {
element.removeAttribute(originalName);
continue;
}
if (name === 'rel' && tagName !== 'a') {
element.removeAttribute(originalName);
continue;
}
if (name === 'class') {
const safeClasses = sanitizeClassValue(value, tagName, profile);
if (safeClasses) element.setAttribute('class', safeClasses);
else element.removeAttribute(originalName);
continue;
}
if (name === 'align' && !SAFE_ALIGN_VALUES.has(String(value).toLowerCase())) {
element.removeAttribute(originalName);
continue;
}
sanitizeNumericAttribute(element, name, value);
}
if (tagName === 'a' && element.hasAttribute('href')) {
element.setAttribute('rel', 'noopener noreferrer');
if (!element.hasAttribute('target')) element.setAttribute('target', '_blank');
}
if (tagName === 'input') {
if ((element.getAttribute('type') || '').toLowerCase() !== 'checkbox') {
element.remove();
return;
}
element.setAttribute('type', 'checkbox');
element.setAttribute('disabled', '');
}
if (tagName === 'img') {
if (!element.hasAttribute('src')) {
element.remove();
return;
}
element.setAttribute('loading', 'lazy');
}
};
const unwrapElement = (element) => {
const parent = element.parentNode;
if (!parent) return;
while (element.firstChild) parent.insertBefore(element.firstChild, element);
element.remove();
};
const sanitizeNode = (node, profileName = 'markdown') => {
if (typeof Node !== 'undefined'
&& (node.nodeType === Node.COMMENT_NODE || node.nodeType === Node.PROCESSING_INSTRUCTION_NODE)) {
node.remove();
return;
}
if (typeof Node === 'undefined' || node.nodeType !== Node.ELEMENT_NODE) return;
const tagName = node.tagName.toLowerCase();
if (DROP_WITH_CONTENT_TAGS.has(tagName)) {
node.remove();
return;
}
for (const child of Array.from(node.childNodes)) {
sanitizeNode(child, profileName);
}
if (!getProfile(profileName).allowedTags.has(tagName)) {
unwrapElement(node);
return;
}
sanitizeAttributes(node, profileName);
};
function hardenSanitizedTree(root, options = {}) {
if (!root || typeof Node === 'undefined') return;
const profileName = options.profile || 'markdown';
const nodes = options.includeRoot
? [root]
: (root.nodeType === Node.DOCUMENT_NODE && root.body
? Array.from(root.body.childNodes)
: Array.from(root.childNodes || []));
for (const child of nodes) sanitizeNode(child, profileName);
}
function parseAndHardenHtml(dirtyHtml, profileName) {
if (dirtyHtml === null || dirtyHtml === undefined) return null;
const html = String(dirtyHtml);
if (typeof document === 'undefined' || typeof document.createElement !== 'function') return null;
// DOMParser's detached HTML document can still fetch <img>/<iframe> URLs
// before their nodes reach our sanitizer. Template content stays inert until
// the already-sanitized nodes are moved into the live document.
const template = document.createElement('template');
template.innerHTML = html;
hardenSanitizedTree(template.content, { profile: profileName });
return template;
}
function sanitizeHtmlWithProfile(dirtyHtml, profileName) {
if (dirtyHtml === null || dirtyHtml === undefined) return '';
const template = parseAndHardenHtml(dirtyHtml, profileName);
if (!template) return escapeHtml(dirtyHtml);
return template.innerHTML;
}
function buildNativeSanitizerConfig(profileName) {
const profile = getProfile(profileName);
const attributes = new Set(profile.globalAttrs);
for (const tagAttrs of Object.values(profile.tagAttrs)) {
for (const attr of tagAttrs) attributes.add(attr);
}
return {
// Keep the native config deliberately simple and spec-valid:
// per-element attributes combined with repeated global attributes can be
// rejected by some Chromium Sanitizer implementations after
// canonicalization. MothNote applies its stricter per-tag URL/class/media
// policy in parseAndHardenHtml() before live DOM insertion, and again in
// hardenSanitizedTree() after native setHTML().
elements: Array.from(profile.allowedTags).sort(),
attributes: Array.from(attributes).sort(),
comments: false,
dataAttributes: false
};
}
function supportsNativeSanitizer() {
return typeof window !== 'undefined'
&& typeof window.Sanitizer === 'function'
&& typeof Element !== 'undefined'
&& typeof Element.prototype.setHTML === 'function';
}
function getNativeSanitizer(profileName) {
if (!supportsNativeSanitizer()) return null;
if (nativeSanitizerCache.has(profileName)) return nativeSanitizerCache.get(profileName);
try {
const sanitizer = new window.Sanitizer(buildNativeSanitizerConfig(profileName));
nativeSanitizerCache.set(profileName, sanitizer);
return sanitizer;
} catch {
// Native Sanitizer API is still evolving across browser versions. A
// config rejected by one implementation must be a quiet capability miss,
// not a user-visible console warning; the local allow-list sanitizer is
// the supported fallback path.
nativeSanitizerCache.set(profileName, null);
return null;
}
}
function replaceChildrenSafely(target, nodes) {
const ownerDocument = target.ownerDocument;
if (ownerDocument && typeof ownerDocument.createDocumentFragment === 'function') {
// replaceChildren(...nodes)는 큰 노트가 많은 최상위 노드를 만들 때
// JavaScript 엔진의 함수 인수 한도를 넘어 RangeError를 발생시킵니다.
// 노드를 문서 조각에 순차적으로 모은 뒤 단일 인수로 교체합니다.
const fragment = ownerDocument.createDocumentFragment();
for (const node of nodes) fragment.appendChild(node);
if (typeof target.replaceChildren === 'function') {
target.replaceChildren(fragment);
} else {
while (target.firstChild) target.removeChild(target.firstChild);
target.appendChild(fragment);
}
return;
}
while (target.firstChild) target.removeChild(target.firstChild);
for (const node of nodes) target.appendChild(node);
}
function setSanitizedHtml(target, dirtyHtml, options = {}) {
if (!target) return;
const profileName = options.profile || 'markdown';
const html = String(dirtyHtml ?? '');
if (!html) {
replaceChildrenSafely(target, []);
return;
}
// First apply MothNote's local policy in an inert document. This prevents
// remote image beacons and other app-policy violations before any live DOM
// insertion can trigger resource loads.
const template = parseAndHardenHtml(html, profileName);
if (!template) {
target.textContent = html;
return;
}
const safeHtml = template.innerHTML;
const nativeSanitizer = getNativeSanitizer(profileName);
if (nativeSanitizer && typeof target.setHTML === 'function') {
try {
target.setHTML(safeHtml, { sanitizer: nativeSanitizer });
// Re-apply the app policy after native sanitization because the
// native config is intentionally broad for cross-version validity.
hardenSanitizedTree(target, { profile: profileName });
return;
} catch {
// Treat native setHTML failures as a silent fallback. The already
// hardened inert document below remains the source of truth.
}
}
replaceChildrenSafely(target, Array.from(template.content.childNodes));
}
function sanitizeHtml(dirtyHtml) {
return sanitizeHtmlWithProfile(dirtyHtml, 'markdown');
}
function sanitizeRichHtml(dirtyHtml) {
return sanitizeHtmlWithProfile(dirtyHtml, 'rich');
}
function setSanitizedRichHtml(target, dirtyHtml) {
setSanitizedHtml(target, dirtyHtml, { profile: 'rich' });
}
const api = Object.freeze({
escapeHtml,
hardenSanitizedTree,
sanitizeHtml,
sanitizeRichHtml,
setSanitizedHtml,
setSanitizedRichHtml
});
if (typeof window !== 'undefined') {
window.MothNoteSanitizer = api;
}
export {
escapeHtml,
hardenSanitizedTree,
sanitizeHtml,
sanitizeRichHtml,
setSanitizedHtml,
setSanitizedRichHtml
};