This repository was archived by the owner on Oct 3, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
487 lines (443 loc) · 14.1 KB
/
content.js
File metadata and controls
487 lines (443 loc) · 14.1 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
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
let settings = {};
let compiled = {
simple: [],
prefix: [],
selector: []
};
// 규칙 진단 정보 저장용
const ruleDiagnostics = {
simple: [],
prefix: []
};
/**
* 위험(RegEx ReDoS 가능성) 휴리스틱 판별
*/
function isRiskyRegex(pattern) {
if (pattern.length > 5000) return true;
// (.+)+, (.*)+ 등 중첩 반복
if (/\((?:[^()]*?[+*][^()]*?)\)[+*]/.test(pattern)) return true;
// .*.*.* 같은 과도한 와일드카드 반복
if (/(\.\*){2,}/.test(pattern)) return true;
// Lookaround 다량 사용
const lookAroundCount = (pattern.match(/\(\?=|\(\?!/g) || []).length;
if (lookAroundCount > 5) return true;
return false;
}
/**
* 규칙 파싱
* @param {string} rulesStr - "패턴 -> 치환" 라인들
* @param {object} options
* allowRegex: /.../flags 허용 여부
* isPrefix: prefix 규칙 여부
* ruleType: 'simple' | 'prefix' (진단 구분용)
*/
function parseRules(rulesStr, { allowRegex = false, isPrefix = false, ruleType = 'simple' } = {}) {
if (!rulesStr) return [];
const result = [];
rulesStr.split('\n').forEach((rawLine, idx) => {
const lineNumber = idx + 1;
const line = rawLine.trim();
if (!line) return;
const parts = line.split('->');
if (parts.length !== 2) {
// 구조 문제는 단순 스킵 (필요시 warn)
ruleDiagnostics[ruleType].push({
line: lineNumber,
raw: line,
status: 'invalid',
reason: '형식 오류 (-> 구분자 필요)'
});
console.warn(`[Privacy Filter][${ruleType}] ${lineNumber}행: 형식 오류 (-> 필요): "${line}"`);
return;
}
const fromRaw = parts[0].trim();
const to = parts[1].trim();
if (!fromRaw) {
ruleDiagnostics[ruleType].push({
line: lineNumber,
raw: line,
status: 'invalid',
reason: '좌측 패턴 없음'
});
console.warn(`[Privacy Filter][${ruleType}] ${lineNumber}행: 패턴이 비어있어 스킵`);
return;
}
let isRegex = false;
let regexObj = null;
let sourcePattern = fromRaw;
let flags = 'gi'; // 기본 플래그 (literal 일 때)
if (allowRegex && fromRaw.startsWith('/')) {
const m = fromRaw.match(/^\/(.+)\/([a-zA-Z]*)$/);
if (m) {
let pattern = m[1];
flags = m[2] || '';
// autoGlobal 설정: g 자동 추가
if (settings.autoGlobal !== 'off' && !flags.includes('g')) {
flags += 'g';
}
// prefix 규칙 + anchorPrefix 설정 시 ^ 자동 추가
if (isPrefix && settings.anchorPrefix !== 'off' && !pattern.startsWith('^')) {
pattern = '^' + pattern;
}
sourcePattern = pattern;
// 위험성 휴리스틱 검사
if (isRiskyRegex(sourcePattern)) {
ruleDiagnostics[ruleType].push({
line: lineNumber,
raw: fromRaw,
status: 'risky',
reason: '잠재적 성능 문제 (중첩/폭발 가능성)'
});
console.warn(
`[Privacy Filter][${ruleType}] ${lineNumber}행: 위험 가능성 있는 정규식 스킵 -> ${fromRaw}`
);
return;
}
try {
regexObj = new RegExp(sourcePattern, flags);
isRegex = true;
} catch (e) {
ruleDiagnostics[ruleType].push({
line: lineNumber,
raw: fromRaw,
status: 'invalid',
reason: '정규식 생성 실패: ' + e.message
});
console.warn(
`[Privacy Filter][${ruleType}] ${lineNumber}행: 정규식 생성 실패 -> ${fromRaw} (${e.message})`
);
return;
}
} else {
// /로 시작했지만 /패턴/플래그 구조가 아님
ruleDiagnostics[ruleType].push({
line: lineNumber,
raw: fromRaw,
status: 'invalid',
reason: '정규식 표기 형식 오류'
});
console.warn(
`[Privacy Filter][${ruleType}] ${lineNumber}행: 정규식 표기 형식 오류 -> ${fromRaw}`
);
return;
}
}
if (!isRegex) {
// Literal
const escaped = fromRaw.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
sourcePattern = escaped;
flags = 'gi';
try {
regexObj = new RegExp(sourcePattern, flags);
} catch (e) {
ruleDiagnostics[ruleType].push({
line: lineNumber,
raw: fromRaw,
status: 'invalid',
reason: 'Literal RegExp 생성 실패: ' + e.message
});
console.warn(
`[Privacy Filter][${ruleType}] ${lineNumber}행: Literal RegExp 생성 실패 -> ${fromRaw} (${e.message})`
);
return;
}
}
result.push({
original: fromRaw,
to,
isRegex,
regex: regexObj,
sourcePattern,
flags
});
ruleDiagnostics[ruleType].push({
line: lineNumber,
raw: fromRaw,
status: 'ok',
pattern: sourcePattern,
flags,
to
});
});
return result;
}
// 클래스/ID 규칙 (정규식 지원 안 함)
function parseSelectorRules(rulesStr) {
if (!rulesStr) return [];
return rulesStr
.split('\n')
.map(line => {
const parts = line.split('->');
if (parts.length === 2) {
return { from: parts[0].trim(), to: parts[1].trim() };
}
return null;
})
.filter(Boolean);
}
function compileAllRules() {
// 이전 진단 초기화
ruleDiagnostics.simple = [];
ruleDiagnostics.prefix = [];
compiled.simple = parseRules(settings.rules, {
allowRegex: true,
isPrefix: false,
ruleType: 'simple'
});
compiled.prefix = parseRules(settings.prefixRules, {
allowRegex: true,
isPrefix: true,
ruleType: 'prefix'
});
compiled.selector = parseSelectorRules(settings.classoridRules);
logRuleDiagnosticsSummary();
}
/**
* 규칙 진단 요약/상세 콘솔 출력
*/
function logRuleDiagnosticsSummary() {
const categories = ['simple', 'prefix'];
console.groupCollapsed('[Privacy Filter] 규칙 컴파일 결과 요약');
categories.forEach(cat => {
const list = ruleDiagnostics[cat];
const ok = list.filter(r => r.status === 'ok').length;
const invalid = list.filter(r => r.status === 'invalid').length;
const risky = list.filter(r => r.status === 'risky').length;
console.info(
` - ${cat} : OK=${ok}, INVALID=${invalid}, RISKY=${risky}, TOTAL=${list.length}`
);
});
console.groupEnd();
categories.forEach(cat => {
const list = ruleDiagnostics[cat];
if (!list.length) return;
console.groupCollapsed(`[Privacy Filter] ${cat} 규칙 상세`);
list.forEach(r => {
if (r.status === 'ok') {
console.debug(
`[OK][${cat}] line:${r.line} pattern:${r.pattern || r.raw} flags:${r.flags} -> "${r.to}"`
);
} else if (r.status === 'invalid') {
console.warn(
`[INVALID][${cat}] line:${r.line} "${r.raw}" 이유: ${r.reason}`
);
} else if (r.status === 'risky') {
console.warn(
`[RISKY][${cat}] line:${r.line} "${r.raw}" 이유: ${r.reason}`
);
}
});
console.groupEnd();
});
}
// title 변환
function transformTitle() {
if (settings.titleTransform !== 'on' || !document.title) return;
const originalTitle = document.title;
let newTitle = originalTitle;
for (const rule of compiled.prefix) {
if (rule.isRegex) {
rule.regex.lastIndex = 0;
if (rule.regex.test(newTitle.trim())) {
newTitle = rule.to;
break;
}
} else {
if (newTitle.trim().toLowerCase().startsWith(rule.original.toLowerCase())) {
newTitle = rule.to;
break;
}
}
}
if (newTitle === originalTitle) {
for (const rule of compiled.simple) {
newTitle = newTitle.replace(rule.regex, rule.to);
}
}
if (newTitle !== originalTitle) {
if (settings.masking === 'replaceText') {
document.title = newTitle.replaceAll(/./g, '*');
} else {
document.title = newTitle;
}
}
}
// 클래스/ID 기반 변환
function transformBySelector() {
for (const rule of compiled.selector) {
try {
const elements = document.querySelectorAll(rule.from);
elements.forEach(el => {
if (settings.masking === 'replaceTextAndBlur') {
el.style.filter = 'blur(5px)';
}
const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
const textNodes = [];
while (walker.nextNode()) textNodes.push(walker.currentNode);
for (const tn of textNodes) {
const parent = tn.parentElement;
if (!parent || parent.tagName === 'SCRIPT' || parent.tagName === 'STYLE') continue;
if (!tn.nodeValue.trim()) continue;
if (settings.masking === 'replaceTextAndBlur') {
tn.nodeValue = rule.to;
} else if (settings.masking === 'replaceText') {
tn.nodeValue = rule.to.replaceAll(/./g, '*');
} else {
tn.nodeValue = rule.to;
}
}
});
} catch (e) {
console.warn('[Privacy Filter] Invalid selector:', rule.from);
}
}
}
// 텍스트 노드 변환
function transformText(root) {
if (!root) return;
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
const textNodes = [];
while (walker.nextNode()) {
const parent = walker.currentNode.parentElement;
if (parent && (parent.tagName === 'SCRIPT' || parent.tagName === 'STYLE')) continue;
textNodes.push(walker.currentNode);
}
for (const tn of textNodes) {
if (!tn.nodeValue.trim()) continue;
let originalContent = tn.nodeValue;
let newContent = originalContent;
for (const rule of compiled.prefix) {
if (rule.isRegex) {
rule.regex.lastIndex = 0;
if (rule.regex.test(newContent.trim())) {
newContent = rule.to;
break;
}
} else {
if (newContent.trim().toLowerCase().startsWith(rule.original.toLowerCase())) {
newContent = rule.to;
break;
}
}
}
if (newContent === originalContent) {
for (const rule of compiled.simple) {
newContent = newContent.replace(rule.regex, rule.to);
}
}
if (newContent !== originalContent) {
const parent = tn.parentElement;
if (!parent) continue;
if (settings.masking === 'replaceTextAndBlur') {
const span = document.createElement('span');
span.style.filter = 'blur(5px)';
span.style.pointerEvents = 'none';
span.textContent = newContent;
if (parent.style.filter && parent.style.filter.includes('blur')) {
parent.textContent = newContent;
} else {
tn.replaceWith(span);
}
} else if (settings.masking === 'replaceText') {
tn.nodeValue = newContent.replaceAll(/./g, '*');
} else {
tn.nodeValue = newContent;
}
}
}
}
// MutationObserver
const observer = new MutationObserver(mutations => {
if (settings.enable === 'off') return;
const hasRelevant = mutations.some(m => {
if (m.type === 'childList' && (m.addedNodes.length || m.removedNodes.length)) return true;
if (m.type === 'characterData' && m.target.nodeValue.trim() !== m.oldValue?.trim()) return true;
return false;
});
if (!hasRelevant) return;
observer.disconnect();
transformBySelector();
transformText(document.body);
observer.observe(document.body, {
childList: true,
subtree: true,
characterData: true,
characterDataOldValue: true
});
});
// 메인
async function main() {
const data = await chrome.storage.sync.get([
'enable',
'loading',
'masking',
'rules',
'prefixRules',
'classoridRules',
'titleTransform',
'listMode',
'urlList',
'autoGlobal',
'anchorPrefix'
]);
settings = data;
settings.autoGlobal = settings.autoGlobal || 'on';
settings.anchorPrefix = settings.anchorPrefix || 'on';
const listMode = settings.listMode || 'none';
if (listMode !== 'none') {
const hostname = window.location.hostname;
const urlList = (settings.urlList || '')
.split('\n')
.map(u => u.trim())
.filter(Boolean);
if (urlList.length) {
const isOnList = urlList.some(u => hostname.includes(u));
if (listMode === 'whitelist' && !isOnList) return;
if (listMode === 'blacklist' && isOnList) return;
}
}
if (settings.enable === 'off') return;
compileAllRules();
const run = () => {
if (settings.titleTransform === 'on') transformTitle();
transformBySelector();
transformText(document.body);
observer.observe(document.body, {
childList: true,
subtree: true,
characterData: true,
characterDataOldValue: true
});
if (settings.titleTransform === 'on') {
const head = document.querySelector('head');
if (head) {
const headObserver = new MutationObserver(() => {
headObserver.disconnect();
transformTitle();
headObserver.observe(head, { childList: true, subtree: true });
});
headObserver.observe(head, { childList: true, subtree: true });
}
}
};
if (settings.loading === 'instant' && document.readyState === 'loading') {
const style = document.createElement('style');
style.id = 'privacy-filter-hide-style';
style.textContent = 'body { visibility: hidden !important; }';
document.documentElement.appendChild(style);
document.addEventListener('DOMContentLoaded', () => {
run();
requestAnimationFrame(() => {
const s = document.getElementById('privacy-filter-hide-style');
if (s) s.remove();
});
});
} else {
if (document.readyState === 'complete' || document.readyState === 'interactive') {
run();
} else {
document.addEventListener('DOMContentLoaded', run);
}
}
}
main();