자동 복호화 프로그램 업데이트
// UserScript
// @name kone base64 자동복호화
// @namespace http://tampermonkey.net/
// @version 1.6.0
// @description base64코드 자동복호화
// @author SYJ
// @match https://arca.live/*
// @match https://kone.gg/*
// @icon https://www.google.com/s2/favicons?sz=64&domain=kone.gg
// @grant GM_registerMenuCommand
// @grant GM_unregisterMenuCommand
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_addValueChangeListener
// @license MIT
// @downloadURL https://update.greasyfork.org/scripts/441706/kone%20base64%20%EC%9E%90%EB%8F%99%EB%B3%B5%ED%98%B8%ED%99%94.user.js
// @updateURL https://update.greasyfork.org/scripts/441706/kone%20base64%20%EC%9E%90%EB%8F%99%EB%B3%B5%ED%98%B8%ED%99%94.meta.js
// /UserScript
/* eslint-disable no-console */
(function () {
'use strict';
// ─────────────────────────────────────────────────────────────
// 설정
// ─────────────────────────────────────────────────────────────
const DEBUG = false; // 문제 생기면 true 로 바꿔서 콘솔 확인
const MAX_DECODE_COUNT = 10 + 1; // 다중 인코딩 최대 해제 횟수
// 스캔 대상 루트. 위에서부터 있는 것만 사용하고, 없으면 그냥 건너뜀.
// 셀렉터가 또 바뀌더라도 FALLBACK_ROOT 덕분에 완전히 죽지는 않음.
const ROOT_SELECTORS = [
'#post-article', // kone.gg - 글 제목 + 본문 (2024 리뉴얼 이후)
'#post-list', // kone.gg - 글 목록
'#post-comment', // kone.gg - 댓글
'main #post_content', // kone.gg - 구버전(shadow DOM) 호환
'.article-content', // arca.live - 본문
'.article-head', // arca.live - 제목
'.article-list', // arca.live - 글 목록
'.comment-wrapper', // arca.live - 댓글
];
const FALLBACK_ROOT = 'main'; // 위 셀렉터가 하나도 안 잡힐 때
const SKIP_TAGS = new Set(['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SVG', 'CODE', 'PRE']);
// ─────────────────────────────────────────────────────────────
// 부트스트랩
// ※ 예전 코드는 window 'load' 만 기다렸는데, @run-at document-idle 로
// load 이후에 주입되면 이벤트가 영영 안 와서 스크립트가 통째로 죽었음.
// ─────────────────────────────────────────────────────────────
let started = false;
if (document.readyState === 'complete') {
boot();
} else {
window.addEventListener('load', boot, { once: true });
// load 가 안 오는 경우 대비 백업
setTimeout(boot, 3000);
}
function boot() {
if (started) return;
started = true;
setTimeout(main, 500);
}
let autoMode = true;
async function main() {
autoMode = await GM_getValue('toggleVal', true);
renderUI(); // 메뉴는 딱 한 번만 등록 (예전엔 URL 바뀔 때마다 중복 등록됨)
registerManualKeys();
observeDom(applyAuto);
schedule();
// 다른 탭/메뉴에서 토글하면 새로고침 없이 바로 반영
if (typeof GM_addValueChangeListener === 'function') {
GM_addValueChangeListener('toggleVal', (name, oldVal, newVal) => {
autoMode = newVal;
if (autoMode) schedule();
});
}
}
// ─────────────────────────────────────────────────────────────
// 자동 변환
// ─────────────────────────────────────────────────────────────
const processed = new WeakSet(); // 이미 처리한 텍스트노드 (무한루프/중복작업 방지)
let mutatingByUs = false; // 우리가 만든 DOM 변경은 다시 트리거하지 않음
function collectRoots() {
const roots = new Set();
for (const sel of ROOT_SELECTORS) {
for (const el of document.querySelectorAll(sel)) {
roots.add(el.shadowRoot || el); // shadow DOM 쓰던 시절도 그대로 지원
}
}
if (roots.size === 0) {
const fb = document.querySelector(FALLBACK_ROOT);
if (fb) roots.add(fb);
}
// 루트 안쪽에 또 shadow root 가 있으면 같이 수집
for (const root of Array.from(roots)) {
for (const el of root.querySelectorAll('*')) {
if (el.shadowRoot) roots.add(el.shadowRoot);
}
}
return roots;
}
function applyAuto() {
if (!autoMode) return;
mutatingByUs = true;
try {
for (const root of collectRoots()) {
for (const node of collectTextNodes(root)) {
processed.add(node);
const original = node.nodeValue;
const decoded = doDecode(original);
if (decoded === original) continue;
dbg(original, '->', decoded);
replaceTextNode(node, decoded);
}
}
} finally {
setTimeout(() => { mutatingByUs = false; }, 0);
}
}
function collectTextNodes(root) {
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
acceptNode(node) {
const text = node.nodeValue;
if (!text || text.length < 6) return NodeFilter.FILTER_REJECT;
if (processed.has(node)) return NodeFilter.FILTER_REJECT;
const parent = node.parentElement;
if (!parent) return NodeFilter.FILTER_REJECT;
if (SKIP_TAGS.has(parent.tagName)) return NodeFilter.FILTER_REJECT;
// 글 작성/수정 중인 에디터는 절대 건드리지 않음
if (parent.closest('[contenteditable=""], [contenteditable="true"]')) return NodeFilter.FILTER_REJECT;
return NodeFilter.FILTER_ACCEPT;
}
});
const nodes = [];
let n;
while ((n = walker.nextNode())) nodes.push(n);
return nodes;
}
// ─────────────────────────────────────────────────────────────
// 텍스트노드 교체 + URL 링크화
// "앞 텍스트 + <a>URL</a> + 뒷 텍스트" 로 쪼개서 한 번에 갈아끼움
// ─────────────────────────────────────────────────────────────
const URL_REGEX = /https?:\/\/[^\s<>"'()]+/g;
function replaceTextNode(node, text) {
const parent = node.parentNode;
if (!parent) return;
// 이미 <a> 안이면 중첩 링크가 되니 텍스트만 교체
if (node.parentElement && node.parentElement.closest('a')) {
node.nodeValue = text;
processed.add(node);
return;
}
URL_REGEX.lastIndex = 0;
if (!URL_REGEX.test(text)) {
node.nodeValue = text;
processed.add(node);
return;
}
URL_REGEX.lastIndex = 0;
const frag = document.createDocumentFragment();
let last = 0;
let m;
while ((m = URL_REGEX.exec(text))) {
let url = m[0].replace(/[.,;:!?)\]}]+$/, ''); // 끝에 붙은 문장부호 제외
const end = m.index + url.length;
if (m.index > last) frag.appendChild(mark(document.createTextNode(text.slice(last, m.index))));
frag.appendChild(makeATag(url));
last = end;
URL_REGEX.lastIndex = end;
}
if (last < text.length) frag.appendChild(mark(document.createTextNode(text.slice(last))));
parent.replaceChild(frag, node);
}
function mark(node) { processed.add(node); return node; }
function makeATag(link) {
const a = document.createElement('a');
a.href = link;
a.textContent = link;
a.target = '_blank';
a.rel = 'noreferrer noopener';
a.style.textDecoration = 'underline';
return a;
}
// ─────────────────────────────────────────────────────────────
// 디코드
// ─────────────────────────────────────────────────────────────
const B64_CHUNK = /[0-9A-Za-z+/]{6,}={0,2}/g;
// 원문으로 인정할 문자 범위 (한영숫자 + 자주쓰는 특문 + 한자/가나)
const WORD_TEST = /^[ㄱ-ㅎㅏ-ㅣ가-힣A-Za-z0-9!@#$%^&*()_+\-=\[\]{}\\|;:'",.<>/?`~\s-ゟ゠-ヿ㐀-䶿一-鿿豈- -〿!-⦆]+$/;
const nonBase64Collection = new Set();
// 텍스트 한 덩어리 안의 모든 base64 구문을 제자리에서 복원
function doDecode(text) {
B64_CHUNK.lastIndex = 0;
return text.replace(B64_CHUNK, (match, offset, whole) => {
// URL 한복판(경로/쿼리)에 있는 토큰은 건드리지 않음
const before = whole.slice(0, offset);
if (/https?:\/\/\S*$/.test(before)) return match;
return decodeNtime(match);
});
}
function decodeNtime(str) {
let decoded = str;
for (let i = 0; i < MAX_DECODE_COUNT; i++) {
const old = decoded;
decoded = decodeOneTime(decoded);
if (decoded === old) break;
}
return decoded;
}
function decodeOneTime(str) {
// 유효한 base64 는 길이가 4의 배수여야 함 (예전엔 이 체크가 없어서 오탐 다수)
if (str.length % 4 !== 0) return str;
if (!/^[0-9A-Za-z+/]+={0,2}$/.test(str)) return str;
try {
const decoded = base64DecodeUnicode(str);
if (!decoded || !WORD_TEST.test(decoded)) {
nonBase64Collection.add(str);
return str;
}
return decoded;
} catch (e) {
return str;
}
}
function base64DecodeUnicode(str) {
const binary = atob(str);
const bytes = Uint8Array.from(binary, ch => ch.charCodeAt(0));
// fatal:true → 깨진 UTF-8 이면 조용히 (U+FFFD) 넘어가지 않고 예외
return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
}
// ─────────────────────────────────────────────────────────────
// 수동 변환 (더블클릭 / Ctrl+Shift+Alt+F)
// ─────────────────────────────────────────────────────────────
function registerManualKeys() {
document.addEventListener('keydown', e => {
if (e.ctrlKey && e.shiftKey && e.altKey && (e.key === 'f' || e.key === 'F')) {
decodeSelectedRange();
}
}, true);
document.addEventListener('dblclick', () => {
decodeSelectedRange();
}, true);
}
function getSelectionAcrossShadow() {
for (const sel of ROOT_SELECTORS) {
for (const el of document.querySelectorAll(sel)) {
const s = el.shadowRoot && el.shadowRoot.getSelection && el.shadowRoot.getSelection();
if (s && s.rangeCount > 0 && s.toString().trim()) return s;
}
}
return window.getSelection();
}
function decodeSelectedRange() {
const sel = getSelectionAcrossShadow();
if (!sel || sel.rangeCount === 0) { dbg('선택 영역 없음'); return false; }
const selectedText = sel.toString();
if (!selectedText.trim()) { dbg('선택 텍스트 비어있음'); return false; }
const decoded = doDecode(selectedText);
if (decoded === selectedText) { dbg('변환할 내용 없음'); return false; }
const range = sel.getRangeAt(0);
try {
const holder = document.createTextNode(decoded);
range.deleteContents();
range.insertNode(holder);
replaceTextNode(holder, decoded); // URL 있으면 링크로
sel.removeAllRanges();
return true;
} catch (err) {
dbg('교체 실패', err);
return false;
}
}
// ─────────────────────────────────────────────────────────────
// DOM 감시 (SPA 라우팅/무한스크롤 대응)
// ─────────────────────────────────────────────────────────────
let timer = null;
function schedule(delay = 150) {
if (timer) clearTimeout(timer);
timer = setTimeout(() => { timer = null; applyAuto(); }, delay);
}
function observeDom(fn) {
const observer = new MutationObserver(() => {
if (mutatingByUs) return; // 우리가 바꾼 것 때문에 다시 도는 것 방지
schedule();
});
observer.observe(document.body, { childList: true, subtree: true, characterData: true });
// SPA 라우팅 감지 (pushState / popstate)
const fire = () => { schedule(300); schedule(1200); };
const origPush = history.pushState;
history.pushState = function (...args) { const r = origPush.apply(this, args); fire(); return r; };
const origReplace = history.replaceState;
history.replaceState = function (...args) { const r = origReplace.apply(this, args); fire(); return r; };
window.addEventListener('popstate', fire);
}
// ─────────────────────────────────────────────────────────────
// 메뉴 UI
// ─────────────────────────────────────────────────────────────
async function renderUI() {
let val = await GM_getValue('toggleVal', true);
let menuId = null;
render();
function render() {
if (menuId != null) GM_unregisterMenuCommand(menuId);
menuId = GM_registerMenuCommand(자동모드 토글 (현재: ${val ? 'ON' : 'OFF'}), toggleValue);
}
async function toggleValue() {
val = !val;
await GM_setValue('toggleVal', val);
autoMode = val;
render();
if (val) schedule(0);
}
}
// ─────────────────────────────────────────────────────────────
function dbg(...args) {
if (DEBUG) console.log('[b64-decode]', ...args);
}
})();
윗 내용 싹 긁어서 Tempermonkey 스크립트 누르고 수정, 붙여넣기, 저장 누르면 됨
Deleted comment.