-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
348 lines (305 loc) · 10.3 KB
/
Copy pathscript.js
File metadata and controls
348 lines (305 loc) · 10.3 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
(() => {
const THEME_KEY = "input-sanitizer-theme";
let domPurifyHookInstalled = false;
const byId = (id) => {
const element = document.getElementById(id);
if (!element) throw new Error(`Missing element: #${id}`);
return element;
};
const elements = {
input: byId("input"),
output: byId("output"),
preview: byId("preview"),
mode: byId("mode"),
allowStyles: byId("allowStyles"),
autoSanitize: byId("autoSanitize"),
sanitizeButton: byId("sanitizeButton"),
clearButton: byId("clearButton"),
copyButton: byId("copyButton"),
downloadButton: byId("downloadButton"),
inputCharCount: byId("inputCharCount"),
outputCharCount: byId("outputCharCount"),
suggestionsList: byId("suggestionsList"),
status: byId("status"),
themeToggle: byId("themeToggle"),
};
function setStatus(message, kind = "info") {
elements.status.textContent = message;
elements.status.classList.toggle("error", kind === "error");
}
function escapeHtml(text) {
return String(text)
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
}
function installDomPurifyHooksOnce() {
if (domPurifyHookInstalled) return;
if (!window.DOMPurify) return;
window.DOMPurify.addHook("afterSanitizeAttributes", (node) => {
if (
node &&
node.tagName === "A" &&
node.getAttribute("target") === "_blank"
) {
const existingRel = (node.getAttribute("rel") || "").trim();
const relParts = new Set(existingRel.split(/\s+/).filter(Boolean));
relParts.add("noopener");
relParts.add("noreferrer");
node.setAttribute("rel", Array.from(relParts).join(" "));
}
});
window.DOMPurify.addHook("uponSanitizeAttribute", (_node, data) => {
if (data.attrName === "style") {
const value = String(data.attrValue || "");
if (/javascript\s*:/i.test(value) || /expression\s*\(/i.test(value)) {
data.keepAttr = false;
}
}
});
domPurifyHookInstalled = true;
}
function sanitizeHtml(input, { allowStyles }) {
if (!window.DOMPurify) {
setStatus(
"DOMPurify failed to load. Falling back to basic escaping (safe but changes meaning).",
"error",
);
return escapeHtml(input);
}
installDomPurifyHooksOnce();
const forbidTags = [
"script",
"iframe",
"object",
"embed",
"link",
"meta",
"base",
];
const forbidAttrs = [];
if (!allowStyles) {
forbidTags.push("style");
forbidAttrs.push("style");
}
const config = {
USE_PROFILES: { html: true },
FORBID_TAGS: forbidTags,
FORBID_ATTR: forbidAttrs,
ALLOWED_URI_REGEXP:
/^(?:(?:https?|mailto|tel):|data:image\/(?:png|jpeg|gif|webp);base64,)/i,
};
return window.DOMPurify.sanitize(input, config);
}
function buildPreviewSrcDoc(mode, sanitized) {
const bodyContent =
mode === "html"
? sanitized
: `<pre style="white-space: pre-wrap; word-wrap: break-word;">${sanitized}</pre>`;
const csp =
"default-src 'none'; base-uri 'none'; script-src 'none'; connect-src 'none'; img-src https: data:; style-src 'unsafe-inline'; font-src https: data:;";
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Security-Policy" content="${csp}">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Preview</title>
<style>
:root { color-scheme: light dark; }
body { font-family: system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif; padding: 12px; }
</style>
</head>
<body>${bodyContent}</body>
</html>`;
}
function generateSuggestions(rawInput, mode) {
const suggestions = [];
const input = String(rawInput);
if (mode === "text") {
if (/<\w+[^>]*>/i.test(input)) {
suggestions.push(
"You selected plain text mode; HTML is being escaped, not “cleaned”.",
);
}
suggestions.push(
"If you are inserting untrusted content into the DOM, prefer textContent/innerText instead of innerHTML.",
);
return suggestions;
}
if (/<script\b/i.test(input))
suggestions.push("Avoid <script> in untrusted input (XSS).");
if (/\son\w+\s*=\s*(['"]).*?\1/i.test(input))
suggestions.push("Avoid inline event handlers (onclick/onerror/etc.).");
if (/javascript\s*:/i.test(input))
suggestions.push(
"Avoid javascript: URLs; browsers may execute them when clicked.",
);
if (/<iframe\b|<object\b|<embed\b/i.test(input))
suggestions.push(
"Avoid embedding active content (iframe/object/embed) from untrusted sources.",
);
if (/<style\b/i.test(input) || /\sstyle\s*=\s*/i.test(input)) {
suggestions.push(
"Untrusted CSS can be risky (tracking/visual spoofing). Keep CSS disabled unless you really need it.",
);
}
if (/(src|href)\s*=\s*(['"])https?:\/\//i.test(input)) {
suggestions.push(
"External URLs may load remote resources in the preview; treat them as untrusted.",
);
}
if (/data\s*:/i.test(input))
suggestions.push(
"Be cautious with data: URLs; they can hide unexpected content.",
);
if (suggestions.length === 0)
suggestions.push("No obvious issues detected for this mode.");
return suggestions;
}
function renderSuggestions(items) {
elements.suggestionsList.innerHTML = "";
for (const item of items) {
const li = document.createElement("li");
li.textContent = item;
elements.suggestionsList.appendChild(li);
}
}
function updateCounts(inputValue, outputValue) {
elements.inputCharCount.textContent = String(inputValue.length);
elements.outputCharCount.textContent = String(outputValue.length);
}
function sanitizeAndRender() {
const input = elements.input.value;
const mode = elements.mode.value;
const allowStyles = elements.allowStyles.checked;
let output = "";
if (mode === "html") {
output = sanitizeHtml(input, { allowStyles });
setStatus(
window.DOMPurify
? "Sanitized with DOMPurify."
: "Sanitized with fallback escaping (DOMPurify missing).",
window.DOMPurify ? "info" : "error",
);
} else {
output = escapeHtml(input);
setStatus("Escaped as plain text (safe for HTML insertion).");
}
elements.output.value = output;
updateCounts(input, output);
elements.preview.srcdoc = buildPreviewSrcDoc(mode, output);
renderSuggestions(generateSuggestions(input, mode));
}
function debounce(fn, delayMs) {
let timeoutId;
return (...args) => {
window.clearTimeout(timeoutId);
timeoutId = window.setTimeout(() => fn(...args), delayMs);
};
}
async function copyOutput() {
const text = elements.output.value;
if (!text) return;
try {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(text);
setStatus("Copied to clipboard.");
return;
}
} catch {
// Fall back below
}
elements.output.focus();
elements.output.select();
try {
document.execCommand("copy");
setStatus("Copied to clipboard (fallback).", "info");
} catch {
setStatus(
"Copy failed. Tip: the Clipboard API needs HTTPS. Please copy manually.",
"error",
);
}
window.getSelection()?.removeAllRanges?.();
}
function downloadOutput() {
const output = elements.output.value;
const blob = new Blob([output], { type: "text/plain" });
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = "sanitized_output.txt";
a.click();
URL.revokeObjectURL(a.href);
}
function clearAll() {
elements.input.value = "";
elements.output.value = "";
elements.preview.srcdoc = buildPreviewSrcDoc(elements.mode.value, "");
elements.suggestionsList.innerHTML = "";
updateCounts("", "");
setStatus("Cleared.");
}
function setTheme(isDark) {
document.body.classList.toggle("dark-mode", isDark);
elements.themeToggle.setAttribute("aria-pressed", String(isDark));
elements.themeToggle.textContent = isDark ? "Light mode" : "Dark mode";
localStorage.setItem(THEME_KEY, isDark ? "dark" : "light");
}
function initTheme() {
const saved = localStorage.getItem(THEME_KEY);
if (saved === "dark") {
setTheme(true);
} else if (saved === "light") {
setTheme(false);
} else {
const prefersDark = window.matchMedia?.(
"(prefers-color-scheme: dark)",
)?.matches;
setTheme(Boolean(prefersDark));
}
}
function syncModeUi() {
const isHtml = elements.mode.value === "html";
elements.allowStyles.disabled = !isHtml;
if (!isHtml) elements.allowStyles.checked = false;
sanitizeAndRender();
}
const debouncedAutoSanitize = debounce(() => {
if (elements.autoSanitize.checked) sanitizeAndRender();
else updateCounts(elements.input.value, elements.output.value);
}, 180);
function init() {
initTheme();
elements.themeToggle.addEventListener("click", () => {
const isDark = document.body.classList.contains("dark-mode");
setTheme(!isDark);
});
elements.sanitizeButton.addEventListener("click", sanitizeAndRender);
elements.clearButton.addEventListener("click", clearAll);
elements.copyButton.addEventListener("click", copyOutput);
elements.downloadButton.addEventListener("click", downloadOutput);
elements.input.addEventListener("input", debouncedAutoSanitize);
elements.mode.addEventListener("change", syncModeUi);
elements.allowStyles.addEventListener("change", () => sanitizeAndRender());
elements.autoSanitize.addEventListener("change", () => {
if (elements.autoSanitize.checked) sanitizeAndRender();
});
elements.input.addEventListener("keydown", (e) => {
if ((e.ctrlKey || e.metaKey) && e.key === "Enter") sanitizeAndRender();
});
syncModeUi();
setStatus(
window.DOMPurify
? "Ready."
: "Ready (DOMPurify still loading or blocked).",
);
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", init);
} else {
init();
}
})();