This commit is contained in:
collector
2026-12-06 12:41:22 +01:00
commit 53d31572a1
49 changed files with 8546 additions and 0 deletions

417
ext/background.js Normal file
View File

@@ -0,0 +1,417 @@
// Service worker: relay content-script requests to the offscreen worker,
// create the offscreen document on demand, trigger downloads.
import { buildPath } from "./lib/paths.js";
const OFFSCREEN_URL = "offscreen.html";
function toUnixSeconds(d) {
if (d == null) return null;
if (typeof d === "number") return d > 1e12 ? Math.floor(d / 1000) : Math.floor(d);
const parsed = Date.parse(d);
return Number.isNaN(parsed) ? null : Math.floor(parsed / 1000);
}
// Folder/file names want the creator's handle. No API calls — the page's
// own traffic already names every user it shows (chat batches, author
// objects, the hook's users map). Capture-only, fanripper-style: cache →
// ask the sending tab → numeric id as last resort.
const USERNAME_TTL = 7 * 24 * 3600 * 1000;
async function resolveCreator(media, tabId = null) {
if (media.username) return media.username;
const id = String(media.creatorId ?? "");
if (!id) return "unknown";
try {
const { usernames } = await chrome.storage.local.get("usernames");
const hit = usernames?.[id];
if (hit?.u && Date.now() - (hit.t ?? 0) < USERNAME_TTL) return hit.u;
if (tabId) {
const w = await chrome.tabs.sendMessage(tabId, { op: "whoIs", mediaId: media.id, creatorId: media.creatorId }).catch(() => null);
const u = w?.ok ? (w.username ?? null) : null;
if (u) {
await chrome.storage.local.set({ usernames: { ...(usernames ?? {}), [id]: { u, t: Date.now() } } });
return u;
}
}
} catch {}
return id;
}
async function fileNamingOpts(media, { bulk = false, ext = "mp4", quality = null, section = null, tabId = null } = {}) {
const stored = await chrome.storage.local.get(["singleScheme", "bulkScheme", "nameTemplate"]);
const createdAt = media.createdAt ?? null;
return {
scheme: bulk ? (stored.bulkScheme ?? "creator-section-type") : (stored.singleScheme ?? "creator-type"),
singleScheme: stored.singleScheme,
bulk,
creator: await resolveCreator(media, tabId),
type: media.type ?? "video",
section,
date: createdAt,
timestamp: toUnixSeconds(createdAt),
mediaId: media.id,
postId: media.postId,
quality,
ext,
template: stored.nameTemplate,
};
}
async function hasOffscreen() {
const contexts = await chrome.runtime.getContexts({
contextTypes: ["OFFSCREEN_DOCUMENT"],
});
return contexts.length > 0;
}
async function ensureOffscreen() {
if (await hasOffscreen()) return;
await chrome.offscreen.createDocument({
url: OFFSCREEN_URL,
reasons: ["DOM_SCRAPING"],
justification: "hosts the OnlyFans request signer (module-eval) and the DRM pipeline",
});
}
async function callOffscreen(msg) {
await ensureOffscreen();
return chrome.runtime.sendMessage(msg);
}
// Free the offscreen's OPFS files + blob URLs once the download actually
// finishes (or fails) — not on a fixed timer, since multi-GB downloads can
// run for many minutes.
function cleanupAfterDownload(downloadId, { urls = [], ids = [] } = {}) {
if (!downloadId) return;
let done = false;
const finish = () => {
if (done) return;
done = true;
chrome.downloads.onChanged.removeListener(listener);
if (urls.length) callOffscreen({ op: "revokeUrls", urls }).catch(() => {});
if (ids.length) callOffscreen({ op: "dropHeld", ids }).catch(() => {});
};
const listener = (delta) => {
if (delta.id !== downloadId) return;
const st = delta.state?.current;
if (st === "complete" || st === "interrupted") finish();
};
chrome.downloads.onChanged.addListener(listener);
// safety net in case the state event never arrives
setTimeout(finish, 30 * 60 * 1000);
}
const safe = (s) => String(s ?? "").replace(/[^\w.-]/g, "_");
// ---- saved-media registry (so the UI can mark what we already have) ----
async function getSavedSet() {
const { savedMedia } = await chrome.storage.local.get("savedMedia");
return savedMedia ?? {};
}
async function markSaved(mediaIds) {
if (!mediaIds?.length) return;
const set = await getSavedSet();
for (const id of mediaIds) if (id != null) set[id] = Date.now();
await chrome.storage.local.set({ savedMedia: set });
// let open tabs update their buttons
for (const tab of await chrome.tabs.query({ url: "https://onlyfans.com/*" })) {
chrome.tabs.sendMessage(tab.id, { op: "savedUpdated", ids: mediaIds }).catch(() => {});
}
}
async function saveViaPage(tabId, url, filename) {
if (!tabId) return { ok: false, error: "no page tab" };
return chrome.tabs.sendMessage(tabId, { op: "saveUrl", url, filename });
}
/** Ensure the content scripts exist in a tab (reloads orphan open tabs). */
async function ensureContentScripts(tabId) {
try {
await chrome.tabs.sendMessage(tabId, { op: "ping" });
return true;
} catch {
try {
await chrome.scripting.executeScript({
target: { tabId },
world: "MAIN",
files: ["lib/main-hook.js"],
});
await chrome.scripting.executeScript({
target: { tabId },
files: ["content.js"],
});
return true;
} catch (e) {
return false;
}
}
}
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.op === "lastLog") {
// content-side probe after a hung item: surface the offscreen's last log
callOffscreen({ op: "lastLog" })
.then((r) => sendResponse(r ?? { ok: false }))
.catch(() => sendResponse({ ok: false }));
return true;
}
if (msg.op === "dlProgress") {
if (msg.tabId) chrome.tabs.sendMessage(msg.tabId, { op: "dlProgress", id: msg.id, pct: msg.pct }).catch(() => {});
return;
}
if (msg.op === "downloadUrl") {
(async () => {
try {
const naming = await fileNamingOpts(msg.media ?? {}, {
ext: msg.ext ?? "jpg",
quality: msg.quality ?? null,
tabId: sender?.tab?.id,
});
const filename = buildPath(naming);
// same proven path as DRM: fetch in offscreen → blob → chrome.downloads
const hold = await callOffscreen({ op: "fetchAndHold", files: [{ url: msg.url, filename }], tabId: sender?.tab?.id, dlId: msg.media?.id });
const h = hold?.held?.[0];
if (!h?.ok) {
sendResponse({ ok: false, error: h?.error ?? hold?.error ?? "fetch failed" });
return;
}
const dl = await chrome.downloads.download({
url: h.blobUrl,
filename, // buildPath already sanitizes each segment — don't flatten the path
conflictAction: "uniquify",
saveAs: false,
});
cleanupAfterDownload(dl, { urls: [h.blobUrl], ids: [h.id] });
await markSaved([msg.media?.id]);
sendResponse({ ok: true, size: h.size });
} catch (e) {
sendResponse({ ok: false, error: e.message });
}
})();
return true;
}
if (msg.op === "download") {
(async () => {
try {
let userId = null, xBc = null;
// Prefer the SENDING TAB's own session identity (captured by the
// main-world hook from the page's signed API requests). In incognito
// the cookies API only sees the regular jar, so cookie-based auth
// signs the license with the wrong user-id and OF kills the session.
try {
const tabId = sender?.tab?.id;
if (tabId) {
const auth = await chrome.tabs.sendMessage(tabId, { op: "getAuth" }).catch(() => null);
if (auth?.ok && auth.auth?.uid) {
userId = auth.auth.uid;
xBc = auth.auth.bc ?? null;
}
}
} catch {}
if (userId == null) {
// fallback: regular-jar cookies (normal windows)
try {
const [c1, c2] = await Promise.all([
chrome.cookies.get({ url: "https://onlyfans.com", name: "auth_id" }),
chrome.cookies.get({ url: "https://onlyfans.com", name: "fp" }),
]);
userId = c1?.value ?? null;
xBc = c2?.value ?? null;
} catch {}
}
let media = { ...msg.media };
const tabId = sender?.tab?.id;
// DRM manifest signatures expire — refresh the media's drm object
// from the post detail endpoint so the MPD URL is freshly signed
if (tabId && media.responseType !== "message" && media.postId) {
try {
const rf = await callOffscreen({ op: "refreshDrm", postId: media.postId, mediaId: media.id, userId });
if (rf?.ok && rf.media) {
media = { ...media, drm: rf.media.files?.drm ?? media.drm };
// keep the page-world store fresh for the next downloads too
await chrome.tabs.sendMessage(tabId, {
op: "ingest",
data: { list: [{ id: media.postId, responseType: media.responseType ?? "post", postedAt: 0, media: [rf.media] }] },
}).catch(() => {});
}
} catch {}
}
const res = await callOffscreen({ op: "prepareLicense", media: { ...media, xBc }, userId });
if (!res?.ok) {
sendResponse({ ok: false, error: `${res?.error ?? "offscreen failed"} [${(res?.log ?? []).slice(-1)[0] ?? "no log"}]`, log: res?.log });
return;
}
// relay the license POST through the page (same-origin fetch — OF
// rejects extension origins with a CORS error)
if (tabId) await ensureContentScripts(tabId);
let licenseRes = null;
if (tabId) {
licenseRes = await chrome.tabs.sendMessage(tabId, {
op: "licensePost",
url: `https://onlyfans.com${res.licensePath}`,
headers: res.headers,
bodyB64: res.challengeB64,
}).catch((e) => ({ ok: false, error: "relay failed: " + e.message }));
} else {
licenseRes = { ok: false, error: "no page tab to relay through" };
}
if (!licenseRes?.ok) {
sendResponse({ ok: false, error: licenseRes?.error ?? `license relay failed (HTTP ${licenseRes?.status ?? "?"}) :: ${(res.log ?? []).slice(-1)[0] ?? "no log"}`, log: res.log });
return;
}
const fin = await callOffscreen({
op: "finishLicense",
licenseB64: licenseRes.bodyB64,
licenseRequestB64: res.licenseRequestB64,
mpd: res.mpd,
mpdUrl: res.mpdUrl ?? null,
});
if (!fin?.ok) {
sendResponse({ ok: false, error: fin?.error ?? "license processing failed", log: fin?.log });
return;
}
const s = fin.summary;
const saved = [];
// fetch both tracks, decrypt with the content key, mux into one mp4
const hold = await callOffscreen({
op: "fetchAndHold",
tabId,
dlId: msg.media.id,
files: (s.reps ?? []).map((rep) => ({
url: rep.url,
filename: `${rep.kind}.mp4.part`,
})),
});
if (!hold?.ok) {
sendResponse({ ok: false, error: hold?.error ?? "fetch failed", log: hold?.log });
return;
}
const videoFile = (hold.held ?? []).find((h) => h.filename?.startsWith("video"));
const audioFile = (hold.held ?? []).find((h) => h.filename?.startsWith("audio"));
if (!videoFile?.ok) {
sendResponse({ ok: false, error: videoFile?.error ?? "video fetch failed" });
return;
}
const keyB64 = btoa(String.fromCharCode(...(s.key ?? "").match(/../g).map((h) => parseInt(h, 16))));
const mux = await callOffscreen({
op: "decryptAndMux",
tabId,
dlId: msg.media.id,
videoId: videoFile.id,
audioId: audioFile?.ok ? audioFile.id : null,
keyB64,
});
if (!mux?.ok) {
sendResponse({ ok: false, error: mux?.error ?? "decrypt failed", log: mux?.log });
return;
}
try {
const naming = await fileNamingOpts(msg.media, {
quality: "source", // DRM mux = the original-quality stream
ext: "mp4",
tabId,
});
const dl = await chrome.downloads.download({
url: mux.blobUrl,
filename: buildPath(naming),
conflictAction: "uniquify",
saveAs: false,
});
saved.push(`${mux.size}B`);
cleanupAfterDownload(dl, { urls: [mux.blobUrl], ids: mux.files ?? [] });
try {
// ground-truth capture is a build-time diagnostic — opt-in only,
// users shouldn't get a surprise ofsaver-drm-sample.json
const { drmDebug } = await chrome.storage.local.get("drmDebug");
if (drmDebug) {
const cap = await callOffscreen({ op: "getCapture" });
if (cap?.ok && cap.jsonB64) {
await chrome.downloads.download({ url: "data:application/json;base64," + cap.jsonB64, filename: "ofsaver-drm-sample.json", conflictAction: "overwrite", saveAs: false });
}
}
} catch {}
} catch (e) {
saved.push(`ERR ${e.message}`);
// the blob URL and mux file would leak — free them anyway
callOffscreen({ op: "revokeUrls", urls: [mux.blobUrl] }).catch(() => {});
if (mux.files?.length) callOffscreen({ op: "dropHeld", ids: mux.files }).catch(() => {});
}
const okCount = saved.filter((x) => !x.startsWith("ERR")).length;
if (okCount > 0) await markSaved([msg.media.id]);
sendResponse({
ok: okCount > 0 && saved.every((x) => !x.startsWith("ERR")),
detail: "saved",
key: s.key,
kid: s.kid,
log: [...(res.log ?? []), `downloads: ${saved.join(" ")}`],
});
} catch (err) {
sendResponse({ ok: false, error: String(err.message ?? err) });
}
})();
return true;
}
if (msg.op === "getSaved") {
getSavedSet().then((set) => sendResponse({ ok: true, set }));
return true;
}
if (msg.op === "bundle") {
(async () => {
try {
let userId = null;
try {
const c = await chrome.cookies.get({ url: "https://onlyfans.com", name: "auth_id" });
userId = c?.value ?? null;
} catch {}
const stored = await chrome.storage.local.get(["singleScheme", "bulkScheme", "nameTemplate"]);
const res = await callOffscreen({ op: "bundle", who: msg.who, max: msg.max ?? 200, userId, naming: stored });
if (!res?.ok) {
sendResponse({ ok: false, error: res?.error ?? "bundle failed", log: res?.log });
return;
}
const s = res.summary;
let started = 0;
for (const d of s.downloads ?? []) {
try {
await chrome.downloads.download({
url: d.url,
filename: safe(d.filename),
conflictAction: "uniquify",
saveAs: false,
});
started++;
} catch {}
}
if (s.savedIds?.length) await markSaved(s.savedIds);
sendResponse({
ok: true,
count: started,
keys: s.keys,
log: [...(res.log ?? []), `downloads started: ${started}`],
});
} catch (err) {
sendResponse({ ok: false, error: String(err.message ?? err) });
}
})();
return true;
}
});
chrome.action.onClicked.addListener(() => {
chrome.runtime.openOptionsPage();
});
// re-inject content scripts into every open OF tab after (re)install —
// otherwise their pills are orphaned and clicks die silently
async function injectEverywhere() {
for (const tab of await chrome.tabs.query({ url: "https://onlyfans.com/*" })) {
try {
await chrome.scripting.executeScript({ target: { tabId: tab.id }, world: "MAIN", files: ["lib/main-hook.js"] });
await chrome.scripting.executeScript({ target: { tabId: tab.id }, files: ["content.js"] });
} catch {}
}
}
chrome.runtime.onInstalled.addListener(injectEverywhere);
chrome.runtime.onStartup.addListener(injectEverywhere);

790
ext/content.js Normal file
View File

@@ -0,0 +1,790 @@
// Isolated world: per-media Download pills in post/message
// toolbars + a BUNDLE pill for multi-media groups. Menus offer quality
// variants; DRM media run the full license flow; saved media are marked.
(() => {
if (window.__ofsaverContentLoaded) return;
window.__ofsaverContentLoaded = true;
// drop pills left by a previous (orphaned) instance
document.querySelectorAll("[data-ofsaver-media]").forEach((el) => el.remove());
if (!document.getElementById("ofsaver-style")) {
const st = document.createElement("style");
st.id = "ofsaver-style";
st.textContent = "@keyframes ofsaverspin{to{transform:rotate(360deg)}}";
document.documentElement.appendChild(st);
}
const media = new Map(); // id -> entry
const buttons = new Map(); // key -> pill element
const savedSet = new Map(); // mediaId -> ts
let openMenu = null;
let activeBundle = null; // { btn, done, items } while a bundle runs
function refreshSaved() {
chrome.runtime.sendMessage({ op: "getSaved" }, (res) => {
if (res?.ok && res.set) {
for (const [id, ts] of Object.entries(res.set)) savedSet.set(id, ts);
render();
}
});
}
refreshSaved();
function postMedia(postId) {
return [...media.values()].filter((m) => String(m.postId) === String(postId));
}
const POST_ANCHORS = [
(id) => document.getElementById(`postId_${id}`),
(id) => document.querySelector(`[data-post-id="${id}"]`),
];
const TOOLBARS = [".b-post__tools", ".b-post__actions", ".feed-item-stats"];
const MESSAGE_ANCHORS = [
(id) => document.querySelector(`[data-message-id="${id}"]`),
(id) => document.getElementById(`messageId_${id}`),
];
const MESSAGE_TOOLBARS = [".m-chat-message__actions"];
function findToolbar(postId) {
for (const anchor of POST_ANCHORS) {
const root = anchor(postId);
if (!root) continue;
for (const sel of TOOLBARS) {
const bar = root.querySelector(sel) ?? (root.matches(sel) ? root : null);
if (bar) return bar;
}
return root;
}
for (const anchor of MESSAGE_ANCHORS) {
const root = anchor(postId);
if (!root) continue;
for (const sel of MESSAGE_TOOLBARS) {
const bar = root.querySelector(sel) ?? (root.matches(sel) ? root : null);
if (bar) return bar;
}
return root;
}
return null;
}
function pageUsername() {
if (/\/my\/chats\//.test(location.pathname)) return null; // chat routes have no creator in the path
const segs = location.pathname.split("/").filter(Boolean);
for (let i = segs.length - 1; i >= 0; i--) {
if (!/^\d+$/.test(segs[i]) && segs[i].length > 1) return segs[i];
}
return null;
}
// ---- pills -------------------------------------------------------------
const BADGES = { photo: "PIC", video: "VID", gif: "GIF", audio: "AUD" };
function fmtDuration(sec) {
const s = Math.round(Number(sec) || 0);
if (!s) return "";
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
}
const SPINNER = `<span style="width:12px;height:12px;flex:none;border:2px solid #d8d8de;border-top-color:#e5484d;border-radius:50%;display:inline-block;animation:ofsaverspin .7s linear infinite"></span>`;
function pillEl(key) {
let btn = buttons.get(key);
if (btn && btn.isConnected) return btn;
btn = document.createElement("div");
btn.dataset.ofsaverMedia = key;
btn.__ofsaverMine = true;
btn.style.cssText =
"display:inline-flex;align-items:center;gap:4px;margin-left:8px;cursor:pointer;user-select:none;flex:none;vertical-align:middle;";
buttons.set(key, btn);
return btn;
}
function pillInner(entry, status, pct) {
const hasDrm = Boolean(entry.drm);
const saved = savedSet.has(String(entry.id));
const dur = fmtDuration(entry.duration);
const label = status === "loading" ? `Downloading ${pct ?? 0}%` : (status || (saved ? "Saved" : "Download"));
return (
`<span style="background:#fff;border-radius:8px;color:#111;font:600 13px/1 -apple-system,system-ui,sans-serif;padding:6px 10px;display:inline-flex;align-items:center;gap:6px;box-shadow:0 1px 2px rgba(0,0,0,.25);position:relative;overflow:hidden">` +
(status === "loading" && pct != null ? `<span data-bar style="position:absolute;left:0;bottom:0;height:2px;background:#e5484d;width:${pct}%;transition:width .2s"></span>` : "") +
(status === "loading" ? SPINNER : "") +
`<span data-label>${label}</span>` +
(dur && !status ? `<span style="color:#e5484d;font-size:11px">· ${dur}</span>` : "") +
`<span style="font-size:9px;opacity:.6">▼</span></span>` +
(hasDrm ? `<span style="background:#111;color:#fff;border-radius:6px;font:700 10px/1 -apple-system,system-ui,sans-serif;padding:4px 7px;display:inline-flex;align-items:center">DRM</span>` : "") +
(saved && !status ? `<span style="color:#23a55a;font:600 12px -apple-system,system-ui,sans-serif">✓</span>` : "")
);
}
function paintPill(btn, entry, status, pct) {
pct = pct ?? (Number(btn.dataset.pct) || 0);
if (status === "loading" && btn.dataset.status === "loading" && btn.querySelector("[data-bar]")) {
paintPillProgress(btn, pct); // smooth: update label + bar in place
return;
}
btn.innerHTML = pillInner(entry, status, pct);
}
function paintPillProgress(btn, pct) {
btn.dataset.pct = pct;
const lbl = btn.querySelector("[data-label]");
if (lbl) lbl.textContent = `Downloading ${pct}%`;
const bar = btn.querySelector("[data-bar]");
if (bar) bar.style.width = pct + "%";
}
function paintBundlePill(btn, count, status, pct) {
const saved = status === "saved";
btn.innerHTML =
`<span style="background:#fff;border-radius:8px;color:#111;font:600 13px/1 -apple-system,system-ui,sans-serif;padding:6px 10px;display:inline-flex;align-items:center;gap:6px;box-shadow:0 1px 2px rgba(0,0,0,.25);position:relative;overflow:hidden">` +
(status === "loading" && pct != null ? `<span data-bar style="position:absolute;left:0;bottom:0;height:2px;background:#e5484d;width:${pct}%;transition:width .2s"></span>` : "") +
(status === "loading" ? SPINNER : "") +
`<span data-blabel>${status === "loading" ? (pct != null ? `Downloading ${pct}%` : "Downloading…") : saved ? "Saved" : "Download all"}</span>` +
`<span style="color:#888;font-size:11px">${count}</span></span>`;
}
/** In-place bundle label/bar update (no innerHTML churn). */
function paintBundleProgress(btn, text, pct) {
btn.dataset.pct = pct ?? "";
const lbl = btn.querySelector("[data-blabel]");
if (lbl) lbl.textContent = text;
const bar = btn.querySelector("[data-bar]");
if (pct != null) {
if (bar) { bar.style.width = pct + "%"; return; }
// no bar yet (pill was painted without one) — add it
const shell = btn.firstElementChild;
if (shell) {
const el = document.createElement("span");
el.dataset.bar = "";
el.style.cssText = "position:absolute;left:0;bottom:0;height:2px;background:#e5484d;width:" + pct + "%;transition:width .2s";
shell.prepend(el);
}
}
}
// ---- menu --------------------------------------------------------------
function closeMenu() {
openMenu?.remove();
openMenu = null;
}
document.addEventListener("click", (e) => {
if (openMenu && !openMenu.contains(e.target) && !e.target.closest("[data-ofsaver-media]")) closeMenu();
}, true);
const fmtSize = (n) => {
if (!n || n <= 0) return "";
if (n < 1024 * 1024) return Math.max(1, Math.round(n / 1024)) + " KB";
return (n / (1024 * 1024)).toFixed(1) + " MB";
};
function qualityOptions(entry) {
const out = [];
const files = entry.raw?.files ?? {};
if (entry.type === "photo" || entry.type === "gif") {
if (files.full?.url) out.push({ label: "source", url: files.full.url, ext: entry.type === "gif" ? "gif" : "jpg", size: files.full?.size });
if (!files.full?.url && files.preview?.url) out.push({ label: "preview", url: files.preview.url, ext: "jpg" });
} else if (entry.drm) {
out.push({ label: "source", drm: true, size: files.source?.size });
} else {
const vs = entry.raw?.videoSources;
const variants = [];
if (Array.isArray(vs)) for (const v of vs) if (v?.url) variants.push(v);
else if (files.source?.sources) for (const v of files.source.sources) if (v?.url) variants.push(v);
const seen = new Set();
for (const v of variants) {
if (seen.has(v.url)) continue;
seen.add(v.url);
out.push({ label: v.height ? v.height + "p" : (v.type ?? "video"), url: v.url, ext: "mp4", size: v.size ?? files.source?.size });
}
if (files.source?.url) out.push({ label: "source", url: files.source.url, ext: "mp4", size: files.source?.size });
else if (files.full?.url) out.push({ label: "source", url: files.full.url, ext: "mp4", size: files.full?.size });
}
return out;
}
function thumbFor(entry) {
return (
entry.raw?.files?.preview?.url ??
entry.raw?.files?.full?.url ??
entry.raw?.files?.source?.url ??
""
);
}
/** Backfill: if the DOM shows more media than we indexed, fetch the post. */
async function backfillIfNeeded(postId, entries, root) {
if (!root) return;
const countEl = [...root.querySelectorAll("*")].find((el) =>
el.children.length === 0 && /^\s*\d+\s*\/\s*\d+\s*$/.test(el.textContent ?? "")
);
if (!countEl) return;
const expected = Number(countEl.textContent.split("/")[1]);
if (!expected || expected <= entries.length) return;
const any = entries[0];
const res = await new Promise((r) =>
chrome.runtime.sendMessage(
{ op: "fetchPostMedia", postId, creatorId: any?.creatorId, username: any?.username ?? pageUsername() },
r
)
);
if (res?.ok && res.data) {
window.dispatchEvent(new CustomEvent("ofsaver-ingest", { detail: res.data }));
}
}
function toggleMenu(btn, entry) {
const key = String(entry.id);
if (openMenu && openMenu.dataset.media === key) { closeMenu(); return; }
closeMenu();
const who = entry.username ? `@${entry.username}` : (entry.creatorId ? `#${entry.creatorId}` : "");
const menu = document.createElement("div");
menu.dataset.media = key;
menu.style.cssText = [
"position:absolute", "z-index:1000000", "background:#fff", "color:#111",
"border-radius:14px", "padding:14px 16px", "min-width:340px",
"max-height:65vh", "overflow:auto", "box-shadow:0 8px 32px rgba(0,0,0,.35)",
"font:13px/1.5 -apple-system,system-ui,sans-serif",
].join(";");
const opts = qualityOptions(entry);
const thumb = thumbFor(entry);
const rows = [];
opts.forEach((opt, i) => {
const isSaved = savedSet.has(String(entry.id));
rows.push(
`<div style="display:flex;align-items:center;gap:10px;padding:6px 0${isSaved ? ";opacity:.55" : ""}">` +
(thumb
? `<img src="${thumb}" style="width:44px;height:44px;border-radius:8px;object-fit:cover;flex:none" referrerpolicy="no-referrer">`
: `<div style="width:44px;height:44px;border-radius:8px;background:#eee;flex:none"></div>`) +
`<div style="flex:1;min-width:0"><div style="font-weight:600">${opt.label}${isSaved ? ` <span style="color:#23a55a;font-size:11px;font-weight:700">saved</span>` : ""}</div>` +
`<div style="font-size:11px;color:#777">${fmtSize(opt.size)}</div></div>` +
`<button data-idx="${i}" title="download" style="width:34px;height:34px;border-radius:50%;border:1px solid #f3c1c3;background:#fdf3f4;color:#e5484d;font-size:14px;cursor:pointer;flex:none">${isSaved ? "↻" : "⬇"}</button>` +
`</div>`
);
});
if (!opts.length) rows.push(`<div style="color:#888;padding:8px 0">no downloadable media</div>`);
menu.innerHTML =
`<div style="display:flex;align-items:baseline;gap:8px;margin-bottom:4px">` +
`<div style="font-weight:700;font-size:14px">${entry.type} by ${who}</div>` +
`<button data-close style="margin-left:auto;border:0;background:none;font-size:14px;cursor:pointer;color:#888">✕</button>` +
`</div>` +
rows.join("");
menu.querySelector("[data-close]")?.addEventListener("click", closeMenu);
menu.querySelectorAll("button[data-idx]").forEach((b) => {
b.addEventListener("click", () => {
const opt = opts[Number(b.dataset.idx)];
closeMenu();
runOne(entry, opt, btn);
});
});
document.body.appendChild(menu);
const r = btn.getBoundingClientRect();
menu.style.left = Math.max(8, Math.min(r.left - 120, window.innerWidth - 380)) + "px";
menu.style.top = r.bottom + window.scrollY + 8 + "px";
openMenu = menu;
}
// Watchdog: resolve a hard failure if the SW never answers — but dlProgress
// activity re-arms the timer, so a slow multi-GB item is never killed mid-
// flight. Registered per media id so the dlProgress handler can feed it.
const pendingTouches = new Map(); // mediaId -> arm()
function sendMessageP(msg, timeoutMs = 300000) {
return new Promise((resolve) => {
let done = false;
let timer = null;
const finish = (res) => {
if (done) return;
done = true;
pendingTouches.delete(String(msg.media?.id));
clearTimeout(timer);
resolve(res);
};
const arm = () => {
clearTimeout(timer);
timer = setTimeout(() => finish({ ok: false, error: `no response in ${Math.round(timeoutMs / 1000)}s` }), timeoutMs);
};
arm();
if (msg.media?.id != null) pendingTouches.set(String(msg.media.id), arm);
try {
chrome.runtime.sendMessage(msg, (res) => {
if (chrome.runtime.lastError) finish({ ok: false, error: chrome.runtime.lastError.message });
else finish(res ?? { ok: false, error: "no response" });
});
} catch (e) { finish({ ok: false, error: String(e.message ?? e) }) }
});
}
/** Ask the offscreen doc for its last log line — names the stage that's
* stuck when an item dies without a response. 3s budget: if the offscreen
* can't even answer this, its event loop is blocked (that's the answer). */
async function probeOffscreenLog() {
try {
const res = await Promise.race([
new Promise((r) => {
try { chrome.runtime.sendMessage({ op: "lastLog" }, (x) => r(chrome.runtime.lastError ? null : x)); } catch { r(null); }
}),
new Promise((r) => setTimeout(() => r(null), 3000)),
]);
return res?.ok ? String(res.line ?? "") : null;
} catch { return null; }
}
async function runOne(entry, opt, btn) {
if (btn) { btn.__entry = entry; btn.dataset.status = "loading"; paintPill(btn, entry, "loading", 0); }
const quality = /^\d+p$/.test(opt.label) ? opt.label : (opt.label === "source" ? "source" : null);
const enriched = { ...entry, username: entry.username ?? pageUsername() };
const msg = opt.drm
? { op: "download", media: { ...enriched, responseType: entry.responseType ?? "post" } }
: { op: "downloadUrl", url: opt.url, media: enriched, ext: opt.ext, quality };
const res = await sendMessageP(msg);
if (res?.ok) {
savedSet.set(String(entry.id), Date.now());
if (btn) { delete btn.dataset.status; paintPill(btn, entry); }
} else {
const err = String(res?.error ?? "failed").slice(0, 90);
console.log("[ofsaver] download failed:", err);
if (btn) {
btn.innerHTML =
`<span style="background:#fff;border-radius:8px;color:#c2333a;font:600 11px/1.2 -apple-system,system-ui,sans-serif;padding:6px 10px;display:inline-flex;align-items:center;max-width:340px;word-break:break-word">${err}</span>`;
setTimeout(() => { delete btn.dataset.status; paintPill(btn, entry); }, 8000);
}
}
}
async function runBundle(postId, entries, btn) {
if (btn) { btn.dataset.status = "loading"; btn.dataset.pct = 0; paintBundlePill(btn, entries.length, "loading", 0); }
activeBundle = { btn, done: 0, items: entries };
let i = 0, ok = 0, fail = 0, firstError = null;
const n = entries.length;
const step = async () => {
if (i >= n) {
activeBundle = null;
if (btn) {
delete btn.dataset.status;
if (fail === 0) for (const e of entries) savedSet.set(String(e.id), Date.now());
if (fail === 0) {
paintBundlePill(btn, n, "saved");
setTimeout(() => { delete btn.dataset.status; paintBundlePill(btn, n); }, 3000);
} else {
const err = String(firstError ?? `${fail} failed`).slice(0, 90);
console.log("[ofsaver] bundle finished with failures:", fail, firstError);
btn.innerHTML =
`<span style="background:#fff;border-radius:8px;color:#c2333a;font:600 11px/1.2 -apple-system,system-ui,sans-serif;padding:6px 10px;display:inline-flex;align-items:center;max-width:340px;word-break:break-word">${err}</span>`;
setTimeout(() => { delete btn.dataset.status; paintBundlePill(btn, n); }, 8000);
}
}
return;
}
const entry = entries[i++];
const k = i; // 1-based index of the item now starting
if (activeBundle) activeBundle.done = i - 1;
if (btn?.isConnected) paintBundleProgress(btn, `${k}/${n}`, Math.round(((k - 1) / n) * 100));
const opts = qualityOptions(entry);
if (!opts.length) { await step(); return; }
const quality = /^\d+p$/.test(opts[0].label) ? opts[0].label : (opts[0].label === "source" ? "source" : null);
const enriched = { ...entry, username: entry.username ?? pageUsername() };
const msg = opts[0].drm
? { op: "download", media: { ...enriched, responseType: entry.responseType ?? "post" } }
: { op: "downloadUrl", url: opts[0].url, media: enriched, ext: opts[0].ext, quality };
const res = await sendMessageP(msg);
if (res?.ok) {
ok++;
} else {
fail++;
const err = String(res?.error ?? "failed").slice(0, 60);
const line = await probeOffscreenLog();
const shown = line ? `${err} · ${line}` : err;
firstError = firstError ?? shown;
console.log(`[ofsaver] bundle item ${k}/${n} (${entry.type} ${entry.id}) failed:`, shown);
if (btn?.isConnected) paintBundleProgress(btn, `${k}/${n} · ${err.slice(0, 40)}`, null);
}
await step();
};
await step();
}
// ---- injection ---------------------------------------------------------
function expectedCount(root) {
if (!root) return 0;
const countEl = [...root.querySelectorAll("*")].find((el) =>
el.children.length === 0 && /^\s*\d+\s*\/\s*\d+\s*$/.test(el.textContent ?? "")
);
if (!countEl) return 0;
return Number(countEl.textContent.split("/")[1]) || 0;
}
function render() {
const postIds = new Set(
[...media.values()].filter((m) => m.postId != null).map((m) => String(m.postId))
);
for (const postId of postIds) {
const bar = findToolbar(postId);
if (!bar) continue;
const entries = postMedia(postId);
// backfill once when the DOM advertises more media than we indexed
const root = bar.closest('[id^="postId_"],[data-post-id],[data-message-id]');
if (entries.length && entries.length < expectedCount(root)) {
const marker = `bf_${postId}`;
if (!bar.dataset[marker]) {
bar.dataset[marker] = "1";
backfillIfNeeded(postId, entries, root);
}
}
const withOpts = entries.filter((e) => qualityOptions(e).length);
// BUNDLE pill first (toolbars clip on the right; it must stay visible)
if (withOpts.length > 1) {
const key = `b_${postId}`;
const btn = pillEl(key);
if (!btn.isConnected) {
btn.addEventListener("click", (ev) => {
ev.preventDefault();
ev.stopPropagation();
runBundle(postId, withOpts, btn);
});
bar.prepend(btn);
}
if (btn.dataset.status !== "loading") paintBundlePill(btn, withOpts.length, btn.dataset.status);
}
for (const entry of withOpts) {
const key = `m_${entry.id}`;
const btn = pillEl(key);
if (!btn.isConnected) {
btn.addEventListener("click", (ev) => {
ev.preventDefault();
ev.stopPropagation();
toggleMenu(btn, entry);
});
bar.appendChild(btn);
}
paintPill(btn, entry, btn.dataset.status);
}
}
renderChat();
}
// MAIN world pushes the full store whenever new media shows up
window.addEventListener("ofsaver-media-data", (e) => {
for (const it of e.detail ?? []) media.set(it.id, it);
render();
});
// id → handle pairs seen in any API response (naming fallback)
const userNames = new Map();
window.addEventListener("ofsaver-users", (e) => {
for (const [id, u] of e.detail ?? []) userNames.set(String(id), u);
});
chrome.runtime.onMessage.addListener((msg, _s, sendResponse) => {
if (msg.op === "ingest" && msg.data) {
// refreshed media data (fresh DRM signatures) from the background
window.dispatchEvent(new CustomEvent("ofsaver-ingest", { detail: msg.data }));
sendResponse({ ok: true });
return;
}
if (msg.op === "whoIs") {
// sender username for a media id, straight from what the page has
// already shown us — no API call needed (naming fallback)
let username = null;
outer: for (const st of chatState.values()) {
for (const m of st.chrono) {
if ((m.media ?? []).some((x) => String(x.id) === String(msg.mediaId))) {
username = m.username ?? null;
break outer;
}
}
}
if (!username && msg.creatorId != null) username = userNames.get(String(msg.creatorId)) ?? null;
sendResponse({ ok: true, username });
return;
}
if (msg.op === "getAuth") {
// session identity captured by the MAIN-world hook from the page's own
// signed API requests — correct even in incognito
try {
const raw = document.documentElement.getAttribute("data-ofsaver-auth");
sendResponse({ ok: true, auth: raw ? JSON.parse(raw) : null });
} catch { sendResponse({ ok: true, auth: null }); }
return;
}
if (msg.op === "dlProgress") {
const pct = Math.max(0, Math.min(100, Number(msg.pct) || 0));
pendingTouches.get(String(msg.id))?.(); // activity: re-arm the watchdog
const btn = buttons.get(`m_${msg.id}`);
if (btn && btn.dataset.status === "loading") paintPillProgress(btn, pct);
if (activeBundle && activeBundle.btn?.isConnected) {
const n = activeBundle.items.length;
const k = Math.min(n, activeBundle.done + 1); // item in flight
const overall = Math.min(100, Math.round(((activeBundle.done + pct / 100) / n) * 100));
paintBundleProgress(activeBundle.btn, `${k}/${n} · ${overall}%`, overall);
}
return;
}
if (msg.op === "savedUpdated") {
for (const id of msg.ids ?? []) savedSet.set(String(id), Date.now());
render();
sendResponse({});
return;
}
if (msg.op === "licensePost") {
// same-origin relay: the page's origin is what OF's CORS check accepts
(async () => {
try {
const body = Uint8Array.from(atob(msg.bodyB64), (c) => c.charCodeAt(0));
const res = await fetch(msg.url, { method: "POST", credentials: "include", headers: msg.headers, body });
const buf = new Uint8Array(await res.arrayBuffer());
let bin = "";
for (const b of buf) bin += String.fromCharCode(b);
if (!res.ok) console.log("[ofsaver] license relay status:", res.status);
sendResponse({ ok: res.ok, status: res.status, bodyB64: btoa(bin) });
} catch (e) {
sendResponse({ ok: false, error: String(e.message ?? e) });
}
})();
return true;
}
});
// orphaned instances (extension reloaded under us) must stop rendering —
// otherwise they keep re-adding duplicate pills forever. The LAST injected
// instance owns the token; older ones see a mismatch and self-terminate.
const myToken = Math.random().toString(36).slice(2);
document.documentElement.setAttribute("data-ofsaver-inst", myToken);
const renderTimer = setInterval(() => {
try {
if (document.documentElement.getAttribute("data-ofsaver-inst") !== myToken) {
throw new Error("superseded");
}
void chrome.runtime.id;
render();
} catch {
clearInterval(renderTimer);
document.querySelectorAll("[data-ofsaver-media]").forEach((el) => {
if (el.__ofsaverMine) el.remove();
});
}
}, 1500);
// ---- chat pills (new OF chat UI) ----------------------------------------
// Chat rows carry [at-attr="chat_message"] but expose NO message/media ids.
// Rows are mapped to API messages positionally (the messages list order
// mirrors the row order); locked media (no files in the API) get a
// duration pill instead of a download. Pills mount in their own
// flex-wrap block at the bottom of the row — never inside
// .b-chat__message__controls (a non-wrapping flex strip that shoves the
// media swiper off-view when filled).
document.documentElement.dataset.ofsaverV = "0.5.14";
const diagTick = () => { document.documentElement.dataset.ofsaverMediaCount = String(media.size); };
const CHAT_ROW_SEL = '.b-chat__messages-wrapper [at-attr="chat_message"]';
const chatState = new Map(); // chatId -> { chrono: [], seen: Set }
const TYPE_LABELS = { video: "Videos", photo: "Photos", gif: "GIFs", audio: "Audio" };
function paintGroupPill(btn, label, count, status, pct) {
const saved = status === "saved";
const loading = status === "loading";
const text = loading ? (pct != null ? `Downloading ${pct}%` : "Downloading…") : saved ? "Saved" : label;
btn.innerHTML =
`<span style="background:#fff;border-radius:8px;color:#111;font:600 13px/1 -apple-system,system-ui,sans-serif;padding:6px 10px;display:inline-flex;align-items:center;gap:6px;box-shadow:0 1px 2px rgba(0,0,0,.25);position:relative;overflow:hidden">` +
(loading && pct != null ? `<span data-bar style="position:absolute;left:0;bottom:0;height:2px;background:#e5484d;width:${pct}%;transition:width .2s"></span>` : "") +
(loading ? SPINNER : "") +
`<span data-blabel>${text}</span>` +
(!loading && !saved ? `<span style="color:#888;font-size:11px">${count}</span>` : "") +
(saved ? `<span style="color:#23a55a;font:600 12px -apple-system,system-ui,sans-serif">✓</span>` : "") +
`</span>`;
}
function attachPills(bar, entries, groupKey) {
// bundles: one pill per media type ("Videos 3", "Photos 22") instead of a
// pill per media — individual pills overflow post toolbars and flood
// chat rows. Single media keeps the quality menu.
if (entries.length > 1) {
const groups = new Map();
for (const e of entries) {
const t = TYPE_LABELS[e.type] ? e.type : "video";
if (!groups.has(t)) groups.set(t, []);
groups.get(t).push(e);
}
const single = groups.size === 1;
for (const [t, list] of groups) {
const key = `b_${groupKey}_${t}`;
const btn = pillEl(key);
const label = single ? `Download all` : (TYPE_LABELS[t] ?? t);
if (!btn.isConnected) {
btn.addEventListener("click", (ev) => {
ev.preventDefault();
ev.stopPropagation();
runBundle(null, list, btn);
});
}
bar.appendChild(btn);
// loading pills are owned by runBundle/dlProgress (live k/N + pct) —
// repainting here fights them and the label flickers every tick
if (btn.dataset.status !== "loading") paintGroupPill(btn, label, list.length, btn.dataset.status);
}
return;
}
const entry = entries[0];
const key = `m_${entry.id}`;
const btn = pillEl(key);
if (!btn.isConnected) {
btn.addEventListener("click", (ev) => {
ev.preventDefault();
ev.stopPropagation();
toggleMenu(btn, entry);
});
bar.appendChild(btn);
}
paintPill(btn, entry, btn.dataset.status);
}
window.addEventListener("ofsaver-chat-batch", (e) => {
try {
const { chatId, msgs } = e.detail ?? {};
if (!chatId || !Array.isArray(msgs) || !msgs.length) return;
let st = chatState.get(chatId);
if (!st) { st = { chrono: [], seen: new Set() }; chatState.set(chatId, st); }
const chrono = [...msgs].reverse(); // oldest → newest
const nums = chrono.map((m) => Number(m.id)).filter((x) => !Number.isNaN(x));
if (st.seen.size === 0) {
st.chrono = chrono;
} else {
const seenNums = [...st.seen].map(Number).filter((x) => !Number.isNaN(x));
const minSeen = seenNums.length ? Math.min(...seenNums) : Infinity;
const maxSeen = seenNums.length ? Math.max(...seenNums) : -Infinity;
const batchMin = nums.length ? Math.min(...nums) : Infinity;
const batchMax = nums.length ? Math.max(...nums) : -Infinity;
if (batchMax < minSeen) st.chrono = [...chrono, ...st.chrono]; // history scroll-up
else if (batchMin > maxSeen) st.chrono = [...st.chrono, ...chrono]; // live messages
}
for (const m of chrono) st.seen.add(String(m.id));
render();
} catch {}
});
function currentChatId() {
// both routes: classic /my/chats/chat/{id} and the newer /chat/{id} SPA
const m = location.pathname.match(/\/(?:my\/chats\/)?chat\/([^/]+)/);
return m ? m[1] : null;
}
/** Stable hex tokens for a media file url (file-id hash + shard dir). */
function fileTokens(url) {
const out = new Set();
if (!url) return out;
const segs = String(url).split("?")[0].split("/").filter(Boolean);
const last = decodeURIComponent(segs[segs.length - 1] ?? "");
const m = last.match(/^(?:\d+x\d+_)?([0-9a-f]{16,})(?:_frame_\d+)?\.(?:jpe?g|png|webp|gif|mp4|webm|mov|m4v)$/i);
if (m) out.add(m[1].toLowerCase());
const dir = segs[segs.length - 2];
if (dir && /^[0-9a-f]{16,}$/i.test(dir)) out.add(dir.toLowerCase());
return out;
}
function entryTokens(entry) {
const out = new Set();
const files = entry.raw?.files ?? {};
const urls = [
files.full?.url,
files.preview?.url,
files.source?.url,
...(files.source?.sources ?? []).map((s) => s?.url),
...(entry.raw?.videoSources ?? []).map((s) => s?.url),
].filter(Boolean);
for (const u of urls) for (const t of fileTokens(u)) out.add(t);
return out;
}
function rowTokens(row) {
const out = new Set();
for (const el of row.querySelectorAll("img, video, source")) {
const urls = [el.currentSrc || "", el.getAttribute("src") || "", el.tagName === "VIDEO" ? el.poster || "" : ""];
for (const u of urls.filter(Boolean)) for (const t of fileTokens(u)) out.add(t);
}
return out;
}
function renderChat() {
try {
diagTick();
const chatId = currentChatId();
const st = chatId ? chatState.get(chatId) : null;
const rows = [...document.querySelectorAll(CHAT_ROW_SEL)];
for (let ri = 0; ri < rows.length; ri++) {
const row = rows[ri];
let bar = row.querySelector(":scope > .ofsaver-chat-pills");
if (!bar) {
bar = document.createElement("div");
bar.className = "ofsaver-chat-pills";
bar.style.cssText = "display:flex;flex-wrap:wrap;gap:4px;align-items:center;margin:6px 0 2px;width:100%;";
row.appendChild(bar);
}
// positional mapping: rows are chronological, aligned from the bottom
const rowEntries = [];
if (st && st.chrono.length) {
const msg = st.chrono[Math.max(0, st.chrono.length - rows.length + ri)];
if (msg) {
for (const mm of msg.media) {
let entry = media.get(mm.id) ?? media.get(Number(mm.id));
// the sender's handle names the file — the store entry may lack
// it, but the batch always knows who sent the message
if (entry && !entry.username && msg.username) entry = { ...entry, username: msg.username };
rowEntries.push({ mm, entry });
}
}
}
// fallback: match by file-hash tokens between row thumbs and index
if (!rowEntries.length) {
const rowTok = rowTokens(row);
if (rowTok.size) {
for (const e of media.values()) {
const toks = entryTokens(e);
if (!toks.size) continue;
let hit = false;
for (const t of toks) if (rowTok.has(t)) { hit = true; break; }
if (hit && !rowEntries.some((x) => String(x.entry?.id) === String(e.id))) rowEntries.push({ mm: null, entry: e });
}
}
}
const downloadable = rowEntries.map((r) => r.entry).filter((e) => e && qualityOptions(e).length);
if (downloadable.length) attachPills(bar, downloadable, "c" + String(downloadable[0].id));
// locked media (no files in the API) — one pill per media, with the
// video duration like ofcheck shows
for (const r of rowEntries) {
if (r.entry && qualityOptions(r.entry).length) continue;
const key = `l_${r.mm?.id ?? "h" + String(r.entry?.id ?? "")}`;
const btn = pillEl(key);
if (!btn.isConnected) {
const dur = r.mm && fmtDuration(r.mm.duration);
btn.innerHTML =
`<span style="background:#ececee;border-radius:8px;color:#8b8b93;font:600 12px/1 -apple-system,system-ui,sans-serif;padding:6px 10px;display:inline-flex;align-items:center;gap:4px;margin-left:8px;vertical-align:middle">Locked${dur ? ` <span style="color:#e5484d;font-size:11px">${dur}</span>` : ""}</span>`;
bar.appendChild(btn);
}
}
// row has media we never saw in any batch — generic locked marker
const hasMedia = row.matches(".m-has-media") || row.querySelector(".b-chat__message__media-wrapper");
if (!rowEntries.length && hasMedia && !row.dataset.ofsaverLocked) {
row.dataset.ofsaverLocked = "1";
const lbtn = document.createElement("div");
lbtn.dataset.ofsaverMedia = "locked";
lbtn.innerHTML =
`<span style="background:#ececee;border-radius:8px;color:#8b8b93;font:600 12px/1 -apple-system,system-ui,sans-serif;padding:6px 10px;display:inline-flex;align-items:center;margin-left:8px;vertical-align:middle">Locked</span>`;
bar.appendChild(lbtn);
}
}
} catch (e) {
console.log("[ofsaver] renderChat error:", e.message);
}
}
})();

4
ext/lib/device.js Normal file
View File

@@ -0,0 +1,4 @@
// Classic Widevine L3 device (same files OF-Scraper's manual mode uses).
export const CLIENT_BLOB_B64 = "CAESmgsK3QMIAhIQT30ajtB91RUzwMQQ0Wc8MRj0n96PBiKOAjCCAQoCggEBALOpKShDvD0RTJlg//DxrSMYR506TuPd6/XcFl0ZDMFmFPjLF2kANsB3S7MoJZtR0eBngTBpnawgM/vv49S3IXV+ItkrSHYGhXNM5Mqj1tlDStO1TEXTqk9bPneSZvaE+PoURNB9f+sKJXWFOSqngXQwDgbK877pZbjQ4RfBaZTZ8LA9nHz9pTO6bgOtKnTUFOn4bitaWT7ryqrF5NRirrQ9bJ+TP3A0u+XJxurvglTYH8Ib4cSMbWVMnWbiVKqMS03EHn36h2e6zGvO8pNd+vcx2UCdklAjfMBGR/L8nnMIceY92sKIkdhN6k7nX+AwwtmyWCZVjq8s8b0O04BSWIMCAwEAASjwIkgBUqoBCAEQABqBAQRAgPPDpqjCqwmKLpGRDD/T1qazqZRCXGfOJ3L3sI4XanzS2wyipwtUAUw9aiKD3c4SykB4InynJLji3fFZjMjDfQGRKQNtI6KW0DWZDHFuD0VOylica+BaK8+r3/KDACSxVvm/gLIJCJX/IlzB+YE2rnOokXoeRisZrLWsoZeTTiIgu2bvvdxDvB4cc+3s0+ktKzUG56ExJGaoezNJeoqIf1ASgAIeOsyI1pwR2NPA7YgU+rODJV9lmGgf8zJ2Lo94oBxlM2Thz2puj+y/ZwbuJJRV2fBIPZRKrPMH3ZJHZqxmv9rhs53qLXuhvk+ESVdTES5YP0oXyJuP+ifUphinyxjyrBQj2lCpW5o4aY2035vPeSeeTLwyNKdjYAcQ7RZsjG5y5aQJ2tfcAl6Vz3HH6nFm74PP0oHv0p1KH1ohGgl2f3q1dIG6vtojsz80ZaCouCKola52Tg8QGQc41HIFQiJ8VhIgK0+Buxcp4N7yHFYk7MpzkNZ9fToo/D54FKirEz3JBL1T4JPIewG9p2Ocgwkjbhs12GxUI4ThF+cRvBtQwwmTGrQFCq4CCAESEGnj6Ji7LD+4o7MoHYT4jBQYjtW+kQUijgIwggEKAoIBAQDY9um1ifBRIOmkPtDZTqH+CZUBbb0eK0Cn3NHFf8MFUDzPEz+emK/OTub/hNxCJCao//pP5L8tRNUPFDrrvCBMo7Rn+iUb+mA/2yXiJ6ivqcN9Cu9i5qOU1ygon9SWZRsujFFB8nxVreY5Lzeq0283zn1Cg1stcX4tOHT7utPzFG/ReDFQt0O/GLlzVwB0d1sn3SKMO4XLjhZdncrtF9jljpg7xjMIlnWJUqxDo7TQkTytJmUl0kcM7bndBLerAdJFGaXc6oSY4eNy/IGDluLCQR3KZEQsy/mLeV1ggQ44MFr7XOM+rd+4/314q/deQbjHqjWFuVr8iIaKbq+R63ShAgMBAAEo8CISgAMii2Mw6z+Qs1bvvxGStie9tpcgoO2uAt5Zvv0CDXvrFlwnSbo+qR71Ru2IlZWVSbN5XYSIDwcwBzHjY8rNr3fgsXtSJty425djNQtF5+J2jrAhf3Q2m7EI5aohZGpD2E0cr+dVj9o8x0uJR2NWR8FVoVQSXZpad3M/4QzBLNto/tz+UKyZwa7Sc/eTQc2+ZcDS3ZEO3lGRsH864Kf/cEGvJRBBqcpJXKfG+ItqEW1AAPptjuggzmZEzRq5xTGf6or+bXrKjCpBS9G1SOyvCNF1k5z6lG8KsXhgQxL6ADHMoulxvUIihyPY5MpimdXfUdEQ5HA2EqNiNVNIO4qP007jW51yAeThOry4J22xs8RdkIClOGAauLIl0lLA4flMzW+VfQl5xYxP0E5tuhn0h+844DslU8ZF7U1dU2QprIApffXD9wgAACk26Rggy8e96z8i86/+YYyZQkc9hIdCAERrgEYCEbByzONrdRDs1MrS/ch1moV5pJv63BIKvQHGvLkaFgoMY29tcGFueV9uYW1lEgZHb29nbGUaIQoKbW9kZWxfbmFtZRITQU9TUCBvbiBJQSBFbXVsYXRvchoYChFhcmNoaXRlY3R1cmVfbmFtZRIDeDg2Gh4KC2RldmljZV9uYW1lEg9nZW5lcmljX3g4Nl9hcm0aIgoMcHJvZHVjdF9uYW1lEhJzZGtfZ3Bob25lX3g4Nl9hcm0aZAoKYnVpbGRfaW5mbxJWZ29vZ2xlL3Nka19ncGhvbmVfeDg2X2FybS9nZW5lcmljX3g4Nl9hcm06OS9QU1IxLjE4MDcyMC4xMjIvNjczNjc0Mjp1c2VyZGVidWcvZGV2LWtleXMaHgoUd2lkZXZpbmVfY2RtX3ZlcnNpb24SBjE0LjAuMBokCh9vZW1fY3J5cHRvX3NlY3VyaXR5X3BhdGNoX2xldmVsEgEwMg4QASAAKA0wAEAASABQAA==";
// device_private_key as PKCS#8 DER (base64) — WebCrypto importKey('pkcs8') ready
export const PRIVATE_KEY_DER_B64 = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCzqSkoQ7w9EUyZYP/w8a0jGEedOk7j3ev13BZdGQzBZhT4yxdpADbAd0uzKCWbUdHgZ4EwaZ2sIDP77+PUtyF1fiLZK0h2BoVzTOTKo9bZQ0rTtUxF06pPWz53kmb2hPj6FETQfX/rCiV1hTkqp4F0MA4GyvO+6WW40OEXwWmU2fCwPZx8/aUzum4DrSp01BTp+G4rWlk+68qqxeTUYq60PWyfkz9wNLvlycbq74JU2B/CG+HEjG1lTJ1m4lSqjEtNxB59+odnusxrzvKTXfr3MdlAnZJQI3zARkfy/J5zCHHmPdrCiJHYTepO51/gMMLZslgmVY6vLPG9DtOAUliDAgMBAAECggEBAID8ljv+RYtifCgyaA7ItJFZwTC0yCb5EYu2s6ercGj5rVziErCkIqsT+xlpXXahy5jdNvdXHIiTpj7fACecQz1jjgl09dUm4XDiZ/DEqF/b3EEbDOOlD8VhsPuP9LRQy6BgJPe64rgQ1MwHFf/1uw974NYnp9ANKacC8Fhp2C+xAoubeZCAWxBZXsCG9Uu+MbxpQMyraKUyGWKNYAsCsHl3eSi0Ti5kYk4jBPiiTWL5ZqYooo1HiM+6MkgJ8UEL1AgSEP92cpgMq6DHC1nAjrqWtfM5tdDvOirs1bDUSbudpgCHRS/1RyOMLriJV9ZwWaA7F9ttesSVF1VREf5MPmECgYEA89kIgWSG64Yc9qGbfKOcd4J90ITa2VLLLX9Q+r35yGMcwEKqVTpnulndeeIKPz34MJQDSE8e1o9Z8uAMwPR3ZoPDn6VDV91cS/PHiLIneM9w8sKOOFaDB1cl8oTK5/gfF07JGXggac2nfx7VS1vCNExI4kqxCM6q6D8qNz1st38CgYEAvJ09vUvmw692bZnh2vudWX0urXY0WChlevRb8B0kN8wci7ecVh507T/lqwKLbz1m8a9qqhjbp+bttwdB6C34DTm+jB0exGMMEJOcL5JotqGCssXLDZJxJoHrgtzkgUUNFIYw42A+YEXqMtbMPXoMwLwtVAvMGSMVDDL11CyfAP0CgYBSSddY8vek22lCwV6bPQs8OUkD6RGBbTMrc198fkegm/HD37tjb4Y5mMHos6MJnHv4yLoi2LBrb4zHLVygcN8qNST65uZG7GiNKQMY2iX/2uEeyxD7ahZlj786jB19EnpLf0bV1Xf6vG/dsiYAfEKZK3UdCF+dvUBnh4lTguMBOQKBgQCq5zOFLZxIndmKUA/1c15NMv+zj1K4usnREk+oD0+8+0a2VsXixrAeNXKudJzRS+rWfaMBw4ps5fNpj7rpXZXQrgz5On2hZzoMXyP7ewdEzK33vP9TKek7AifbKLooY+AJQ9pSfOeoJlGihT0FS2z4ysmryRDDiiVNK3PSMChXJQKBgQCgCwDgzmbxFLi7qxFyFsncBLMQ38WLS3JwZvLXXgfmJxb2/CAcuKd2viwrN0c7Mb0xLIOIukLWNsioCkqY9SWqTp8F9wsM7Owl6n0YYGPHqiUxYjFKLVKSPstzdaVOZWlndl1S88k4mKJdIGz3T6J2BVFMevK5VR1pusLcWqMxJA==";

Binary file not shown.

View File

@@ -0,0 +1,27 @@
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEAs6kpKEO8PRFMmWD/8PGtIxhHnTpO493r9dwWXRkMwWYU+MsX
aQA2wHdLsyglm1HR4GeBMGmdrCAz++/j1LchdX4i2StIdgaFc0zkyqPW2UNK07VM
RdOqT1s+d5Jm9oT4+hRE0H1/6woldYU5KqeBdDAOBsrzvulluNDhF8FplNnwsD2c
fP2lM7puA60qdNQU6fhuK1pZPuvKqsXk1GKutD1sn5M/cDS75cnG6u+CVNgfwhvh
xIxtZUydZuJUqoxLTcQeffqHZ7rMa87yk1369zHZQJ2SUCN8wEZH8vyecwhx5j3a
woiR2E3qTudf4DDC2bJYJlWOryzxvQ7TgFJYgwIDAQABAoIBAQCA/JY7/kWLYnwo
MmgOyLSRWcEwtMgm+RGLtrOnq3Bo+a1c4hKwpCKrE/sZaV12ocuY3Tb3VxyIk6Y+
3wAnnEM9Y44JdPXVJuFw4mfwxKhf29xBGwzjpQ/FYbD7j/S0UMugYCT3uuK4ENTM
BxX/9bsPe+DWJ6fQDSmnAvBYadgvsQKLm3mQgFsQWV7AhvVLvjG8aUDMq2ilMhli
jWALArB5d3kotE4uZGJOIwT4ok1i+WamKKKNR4jPujJICfFBC9QIEhD/dnKYDKug
xwtZwI66lrXzObXQ7zoq7NWw1Em7naYAh0Uv9UcjjC64iVfWcFmgOxfbbXrElRdV
URH+TD5hAoGBAPPZCIFkhuuGHPahm3yjnHeCfdCE2tlSyy1/UPq9+chjHMBCqlU6
Z7pZ3XniCj89+DCUA0hPHtaPWfLgDMD0d2aDw5+lQ1fdXEvzx4iyJ3jPcPLCjjhW
gwdXJfKEyuf4HxdOyRl4IGnNp38e1UtbwjRMSOJKsQjOqug/Kjc9bLd/AoGBALyd
Pb1L5sOvdm2Z4dr7nVl9Lq12NFgoZXr0W/AdJDfMHIu3nFYedO0/5asCi289ZvGv
aqoY26fm7bcHQegt+A05vowdHsRjDBCTnC+SaLahgrLFyw2ScSaB64Lc5IFFDRSG
MONgPmBF6jLWzD16DMC8LVQLzBkjFQwy9dQsnwD9AoGAUknXWPL3pNtpQsFemz0L
PDlJA+kRgW0zK3NffH5HoJvxw9+7Y2+GOZjB6LOjCZx7+Mi6Itiwa2+Mxy1coHDf
KjUk+ubmRuxojSkDGNol/9rhHssQ+2oWZY+/OowdfRJ6S39G1dV3+rxv3bImAHxC
mSt1HQhfnb1AZ4eJU4LjATkCgYEAquczhS2cSJ3ZilAP9XNeTTL/s49SuLrJ0RJP
qA9PvPtGtlbF4sawHjVyrnSc0Uvq1n2jAcOKbOXzaY+66V2V0K4M+Tp9oWc6DF8j
+3sHRMyt97z/UynpOwIn2yi6KGPgCUPaUnznqCZRooU9BUts+MrJq8kQw4olTStz
0jAoVyUCgYEAoAsA4M5m8RS4u6sRchbJ3ASzEN/Fi0tycGby114H5icW9vwgHLin
dr4sKzdHOzG9MSyDiLpC1jbIqApKmPUlqk6fBfcLDOzsJep9GGBjx6olMWIxSi1S
kj7Lc3WlTmVpZ3ZdUvPJOJiiXSBs90+idgVRTHryuVUdabrC3FqjMSQ=
-----END RSA PRIVATE KEY-----

229
ext/lib/holds.js Normal file
View File

@@ -0,0 +1,229 @@
// Disk-backed holds: media streams into the browser's private filesystem
// (OPFS) instead of living in RAM, so multi-GB files never bloat the
// offscreen document. Files are laid out exactly like the old in-memory
// arrays (header first, then each decrypted fragment in order) so the
// MuxPlanner offsets match the previous behavior byte for byte.
// ground-truth capture for building our own decrypt/mux: the first DRM
// download after load records real inputs and the wasm's exact outputs
export const drmCapture = { frags: [], moofs: [], headers: {}, mux: null, sent: false };
const b64 = (bytes) => {
let s = "";
for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));
return btoa(s);
};
export async function holdsDir() {
const root = await navigator.storage.getDirectory();
return root.getDirectoryHandle("holds", { create: true });
}
/** Stream a fetch Response body into OPFS. Returns {id, size}. */
export async function streamIntoHold(dir, res, onChunk) {
const id = "h_" + Math.random().toString(36).slice(2);
const fh = await dir.getFileHandle(id, { create: true });
const w = await fh.createWritable();
let size = 0;
for await (const chunk of res.body) {
await w.write(chunk);
size += chunk.byteLength;
if (onChunk) onChunk(chunk.byteLength);
}
await w.close();
return { id, size };
}
/** Blob URL for a held file — disk-backed, so chrome.downloads streams it. */
export async function holdFileUrl(dir, id, mime = "application/octet-stream") {
const fh = await dir.getFileHandle(id);
const file = await fh.getFile();
// slice with a contentType — OPFS files carry no MIME type, and an untyped
// blob makes Chrome append .txt to the download
return URL.createObjectURL(file.slice(0, file.size, mime || "application/octet-stream"));
}
export async function removeHolds(dir, names) {
for (const name of names ?? []) {
if (!name) continue;
try { await dir.removeEntry(name); } catch {}
}
}
/**
* Async-iterate the top-level boxes of an mp4 File with chunked reads.
* Yields {type, start, end, bytes} — `bytes` is a copy only for types in
* `withBytes`. Boxes bigger than a chunk are skipped without buffering
* unless their bytes were requested, so huge mdats never enter RAM here.
*/
export async function* mp4Boxes(file, { withBytes = [], chunkSize = 1 << 22 } = {}) {
const want = new Set(withBytes);
let buf = new Uint8Array(0); // pending bytes, starting at file offset `base`
let base = 0;
for (;;) {
let size = 0;
if (buf.length >= 8) {
const dv = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
size = dv.getUint32(0);
if (size === 1) {
size = buf.length >= 16 ? Number(dv.getBigUint64(8)) : -1; // need more
} else if (size === 0) {
size = file.size - base; // box extends to EOF
}
if (size >= 0 && size < 8) return; // malformed, like the old parser
if (size >= 8) {
const type = String.fromCharCode(buf[4], buf[5], buf[6], buf[7]);
if (buf.length >= size) {
yield { type, start: base, end: base + size, bytes: want.has(type) ? buf.slice(0, size) : undefined };
buf = buf.subarray(size);
base += size;
continue;
}
if (!want.has(type) && base + size <= file.size) {
// large box we don't need bytes for — skip past it without buffering
yield { type, start: base, end: base + size, bytes: undefined };
buf = new Uint8Array(0);
base += size;
continue;
}
}
}
if (base + buf.length >= file.size) return; // EOF (or partial box at EOF)
const from = base + buf.length;
const to = Math.min(from + chunkSize, file.size);
const chunk = new Uint8Array(await file.slice(from, to).arrayBuffer());
const merged = new Uint8Array(buf.length + chunk.length);
merged.set(buf);
merged.set(chunk, buf.length);
buf = merged;
}
}
/**
* Stream-decrypt one track. Reads the source hold, decrypts each
* moof..mdat fragment in place with the same wasm calls as the in-memory
* flow, and appends to a new OPFS file laid out like the old result array:
* header first, fragments in order. Returns {header} (the pre-strip source
* header, as the old code used it).
*/
export async function decryptTrackToOpfs(dir, srcId, decId, keyBytes, fns, label = "video", onProgress) {
const src = await (await dir.getFileHandle(srcId)).getFile();
const dec = await dir.getFileHandle(decId, { create: true });
const w = await dec.createWritable();
let header = null;
try {
let marker = 0, pattern = null, civ = null;
let moofStart = -1, done = 0;
for await (const box of mp4Boxes(src)) {
if (header === null) {
if (box.type !== "moof") continue;
header = new Uint8Array(await src.slice(0, box.start).arrayBuffer());
marker = fns.tencMarker(header);
if (marker < 0) throw new Error("no tenc — not CENC-protected");
fns.stripInit(header);
pattern = fns.tencCryptPattern(header);
civ = fns.tencConstantIv(header);
await w.write(header);
moofStart = box.start;
continue;
}
if (box.type === "moof") { moofStart = box.start; continue; }
if (box.type === "mdat" && moofStart >= 0) {
const bytes = new Uint8Array(await src.slice(moofStart, box.end).arrayBuffer());
if (!drmCapture.sent && drmCapture.frags.filter((f) => f.track === label).length < 1) {
drmCapture.headers[label] = b64(header);
drmCapture.key = b64(keyBytes);
drmCapture.marker = marker;
drmCapture.pattern = pattern ? [...pattern] : null;
drmCapture.civ = civ ? [...civ] : null;
var capIn = b64(bytes);
}
if (pattern) {
fns.decryptAndStripFragmentCbcs(bytes, keyBytes, marker, pattern[0] ?? 0, pattern[1] ?? 0, civ ?? new Uint8Array());
} else {
fns.decryptAndStripFragment(bytes, keyBytes, marker);
}
await w.write(bytes);
done += bytes.length;
if (onProgress) onProgress(done, src.size);
if (capIn) { drmCapture.frags.push({ track: label, in: capIn, out: b64(bytes) }); capIn = null; }
moofStart = -1;
}
}
if (header === null) {
// degenerate track with no fragments: the old flow treated the whole
// file as its own "header"
await w.write(new Uint8Array(await src.slice(0, src.size).arrayBuffer()));
}
} catch (e) {
try { await w.close(); } catch {}
try { await dir.removeEntry(decId); } catch {}
throw e;
}
await w.close();
return { header };
}
/**
* Re-parse a decrypted track file and feed every moof into the MuxPlanner
* exactly like the in-memory flow did: bytes from the moof's start through
* whatever follows it up to (not including) the next mdat, at the moof's
* offset. Returns the bytes before the first moof — the header the planner
* constructor wants.
*/
export async function pushTrackMoofs(dir, decId, planner, isVideo) {
const file = await (await dir.getFileHandle(decId)).getFile();
let header = null, moofStart = -1;
for await (const box of mp4Boxes(file)) {
if (box.type === "moof") {
if (header === null) header = new Uint8Array(await file.slice(0, box.start).arrayBuffer());
moofStart = box.start;
continue;
}
if (box.type === "mdat" && moofStart >= 0) {
const moof = new Uint8Array(await file.slice(moofStart, box.start).arrayBuffer());
const track = isVideo ? "video" : "audio";
if (!drmCapture.sent && drmCapture.moofs.filter((x) => x.track === track).length < 3) {
drmCapture.moofs.push({ track, offset: moofStart, moof: b64(moof) });
}
isVideo ? planner.pushVideoMoof(moof, moofStart) : planner.pushAudioMoof(moof, moofStart);
moofStart = -1;
}
}
return header ?? new Uint8Array(await file.slice(0, file.size).arrayBuffer());
}
/**
* Write the muxed output: muxed header, then each layout range copied from
* the decrypted track files in chunks. Returns {blobUrl, size}.
*/
export async function writeMuxedFile(dir, finalId, muxed, videoFile, audioFile) {
const fh = await dir.getFileHandle(finalId, { create: true });
const w = await fh.createWritable();
try {
await w.write(muxed.header());
const layout = muxed.layout();
for (let i = 0; i < layout.length; i += 3) {
const isVideo = layout[i], off = layout[i + 1], len = layout[i + 2];
const f = (isVideo || !audioFile) ? videoFile : audioFile;
let p = off;
const end = off + len;
while (p < end) {
const n = Math.min(1 << 22, end - p);
await w.write(await f.slice(p, p + n).arrayBuffer());
p += n;
}
}
} catch (e) {
try { await w.close(); } catch {}
try { await dir.removeEntry(finalId); } catch {}
throw e;
}
await w.close();
if (!drmCapture.sent) {
try { drmCapture.mux = { header: b64(muxed.header()), layout: [...muxed.layout()] }; } catch {}
}
const ofile = await fh.getFile();
// OPFS files have no MIME type — an untyped blob URL makes Chrome append
// .txt to the download, so hand out a typed view of the same file
return { blobUrl: URL.createObjectURL(ofile.slice(0, ofile.size, "video/mp4")), size: ofile.size };
}

234
ext/lib/main-hook.js Normal file
View File

@@ -0,0 +1,234 @@
// MAIN world: hook the page's network and index every media entry OF sends us.
// Posts/media land in window.__ofsaverMedia; the content script picks them up
// via a DOM CustomEvent, so both worlds see the same data.
(() => {
if (window.__ofsaverHooked) return;
window.__ofsaverHooked = true;
const store = new Map(); // mediaId -> entry (includes .raw = full media object)
const users = new Map(); // userId -> username (from any response that names a user)
const emit = () => {
try {
window.dispatchEvent(new CustomEvent("ofsaver-media-data", {
detail: [...store.values()],
}));
window.dispatchEvent(new CustomEvent("ofsaver-users", {
detail: [...users.entries()],
}));
} catch {}
};
const walk = (obj, found) => {
if (!obj || typeof obj !== "object") return;
if (Array.isArray(obj)) { for (const v of obj) walk(v, found); return; }
const type = obj.type;
const files = obj.files;
if ((type === "video" || type === "audio" || type === "photo" || type === "gif") && files && typeof files === "object" && obj.id != null) {
found.add(obj);
}
for (const k of Object.keys(obj)) walk(obj[k], found);
};
const ingest = (json, url) => {
let data;
try { data = JSON.parse(json); } catch { return; }
// chat messages: emit the ordered batch so the content script can map
// DOM rows positionally (the chat rows expose no message ids). Locked
// chat media ships WITHOUT a files key and is NOT added to the media
// store — its info rides in this batch instead, keeping the store
// exactly as the download flow expects it.
if (url) {
const cm = String(url).match(/\/api2\/v2\/chats\/([^/]+)\/messages/);
if (cm) {
const list = data?.list ?? (Array.isArray(data) ? data : null);
if (list && list.length) {
const fu = list.find((m) => m.fromUser)?.fromUser;
if (fu) console.log("[ofsaver] chat batch fromUser sample:", fu.id, fu.username);
try {
window.dispatchEvent(new CustomEvent("ofsaver-chat-batch", {
detail: {
chatId: cm[1],
msgs: list.map((m) => ({
id: String(m.id),
username: m.fromUser?.username ?? null,
media: (m.media ?? []).map((x) => ({
id: x.id,
type: x.type,
duration: x.duration ?? x.videoDuration ?? null,
canView: x.canView !== false,
})),
})),
},
}));
} catch {}
}
}
}
const found = new Set();
walk(data, found);
// find post context: any post objects mapping postId → their media list
const postMedia = new Map();
// containers: posts (postedAt/responseType) and chat messages (fromUser/createdAt)
const containers = [];
const walkContainers = (o) => {
if (!o || typeof o !== "object") return;
if (Array.isArray(o)) { for (const v of o) walkContainers(v); return; }
if (o.id != null && Array.isArray(o.media) && o.media.length) {
const isPost = o.postedAt !== undefined || o.responseType !== undefined;
const isMessage = Array.isArray(o.media) && (o.fromUser !== undefined || o.createdAt !== undefined) && !isPost;
if (isPost || isMessage) {
containers.push({
id: o.id,
responseType: isMessage ? "message" : (o.responseType ?? "post"),
username: o.author?.username ?? o.fromUser?.username,
creatorId: o.author?.id ?? o.fromUser?.id,
});
}
}
for (const k of Object.keys(o)) walkContainers(o[k]);
};
walkContainers(data);
// second pass: map media ids to their container
const containerMedia = new Map();
const walkMediaLinks = (o) => {
if (!o || typeof o !== "object") return;
if (Array.isArray(o)) { for (const v of o) walkMediaLinks(v); return; }
if (o.id != null && Array.isArray(o.media) && o.media.length) {
const isPost = o.postedAt !== undefined || o.responseType !== undefined;
const isMessage = o.fromUser !== undefined || (o.createdAt !== undefined && !isPost);
if (isPost || isMessage) {
for (const m of o.media) {
if (m?.id != null) containerMedia.set(m.id, {
postId: o.id,
responseType: isMessage ? "message" : (o.responseType ?? "post"),
username: o.author?.username ?? o.fromUser?.username,
creatorId: o.author?.id ?? o.fromUser?.id,
});
}
}
}
for (const k of Object.keys(o)) walkMediaLinks(o[k]);
};
walkMediaLinks(data);
// any response that names a user fixes the id → handle mapping for all
// future naming (some views ship fromUser.id without the username)
const usersBefore = users.size;
const walkUsers = (o) => {
if (!o || typeof o !== "object") return;
if (Array.isArray(o)) { for (const v of o) walkUsers(v); return; }
if (o.id != null && typeof o.username === "string" && o.username) users.set(String(o.id), o.username);
for (const k of Object.keys(o)) walkUsers(o[k]);
};
walkUsers(data);
for (const m of found) {
const drm = m.files?.drm;
const src = m.files?.source?.url ?? m.files?.full?.url ?? null;
const prev = store.get(m.id);
// keep the richest info we've seen (later API views may be less privileged)
const ctx = containerMedia.get(m.id) ?? {};
const entry = {
id: m.id,
postId: ctx.postId ?? prev?.postId ?? null,
responseType: ctx.responseType ?? prev?.responseType ?? null,
username: ctx.username ?? (ctx.creatorId != null ? users.get(String(ctx.creatorId)) : null) ?? prev?.username ?? null,
creatorId: ctx.creatorId ?? prev?.creatorId ?? null,
type: m.type,
canView: m.canView !== false, // latest API view wins
duration: m.duration ?? m.videoDuration ?? prev?.duration ?? null,
createdAt: m.createdAt ?? prev?.createdAt ?? null,
height: m.height ?? m.files?.source?.h ?? prev?.height ?? null,
drm: (drm?.manifest && drm) || prev?.drm || null,
source: (m.canView !== false && src) || prev?.source || null,
raw: m, // full media object for quality variants
};
if (m.canView === false) entry.canView = false;
store.set(m.id, entry);
}
if (found.size || users.size !== usersBefore) emit();
};
const of = window.fetch;
window.fetch = async function (...args) {
try {
const u = typeof args[0] === "string" ? args[0] : args[0]?.url ?? "";
if (/\/api2\//.test(u)) {
const h = args[1]?.headers;
const get = (k) => {
if (!h) return null;
if (typeof Headers !== "undefined" && h instanceof Headers) return h.get(k);
return h[k] ?? h[k.toLowerCase()] ?? null;
};
const uid = get("user-id");
const bc = get("x-bc");
if (uid != null || bc != null) {
const store = JSON.parse(document.documentElement.getAttribute("data-ofsaver-auth") || "{}");
if (uid != null) store.uid = String(uid);
if (bc != null) store.bc = String(bc);
store.t = Date.now();
document.documentElement.setAttribute("data-ofsaver-auth", JSON.stringify(store));
}
}
} catch {}
const res = await of.apply(this, args);
try {
const url = typeof args[0] === "string" ? args[0] : args[0]?.url ?? "";
if (/\/api2\/v2\//.test(url) && res.ok) {
const clone = res.clone();
clone.text().then((t) => ingest(t, url)).catch(() => {});
}
} catch {}
return res;
};
// capture the page's own license request headers for auth debugging
const osrh = XMLHttpRequest.prototype.setRequestHeader;
XMLHttpRequest.prototype.setRequestHeader = function (k, v) {
try {
const lk = String(k).toLowerCase();
const u = String(this.__ofsaverUrl ?? "");
// session auth capture: every signed /api2/ request carries user-id
// and x-bc — the tab's own session, which is the only correct one in
// incognito (chrome.cookies reads the regular jar there)
if (/\/api2\//.test(u) && (lk === "user-id" || lk === "x-bc")) {
const store = JSON.parse(document.documentElement.getAttribute("data-ofsaver-auth") || "{}");
if (lk === "user-id") store.uid = String(v);
else store.bc = String(v);
store.t = Date.now();
document.documentElement.setAttribute("data-ofsaver-auth", JSON.stringify(store));
}
if (/\/drm\/|\/licenses?\b|type=widevine/i.test(u) || /sign|time|x-bc|app-token|user-id|x-of-rev/i.test(lk)) {
const store = JSON.parse(document.documentElement.getAttribute("data-ofsaver-lic") || "{}");
(store.h = store.h || {})[lk] = v;
store.url = u.slice(0, 120);
store.t = Date.now();
document.documentElement.setAttribute("data-ofsaver-lic", JSON.stringify(store));
}
} catch {}
return osrh.call(this, k, v);
};
const oo = XMLHttpRequest.prototype.open;
const os = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.open = function (method, url, ...rest) {
this.__ofsaverUrl = url;
return oo.call(this, method, url, ...rest);
};
XMLHttpRequest.prototype.send = function (...args) {
this.addEventListener("load", () => {
try {
if (/\/api2\/v2\//.test(String(this.__ofsaverUrl ?? "")) && this.responseText) ingest(this.responseText, this.__ofsaverUrl);
} catch {}
});
return os.apply(this, args);
};
emit();
// content script can push fetched API data back in (backfills for posts
// whose responses happened before this hook installed)
window.addEventListener("ofsaver-ingest", (e) => {
try { ingest(e.detail); } catch {}
});
})();

556
ext/lib/owndrm.js Normal file
View File

@@ -0,0 +1,556 @@
// Own DRM module — drop-in replacement for fanripper's drm.wasm.
// Decrypt is AES-128-CTR (cenc) / CBC (cbcs) with per-sample IVs from senc,
// verified byte-identical against the wasm. The muxer builds a progressive
// MP4 (merged header + interleaved mdat), mirroring MuxPlanner.
// AES-128 decrypt — equivalent inverse cipher, T-table driven.
const S = new Uint8Array(256)
const SI = new Uint8Array(256)
const xt0 = (a, b) => { let r = 0; while (b) { if (b & 1) r ^= a; a = (a << 1) ^ ((a >> 7) * 0x11b); b >>>= 1 } return r & 255 }
const rotl8 = (v, n) => ((v << n) | (v >>> (8 - n))) & 255
for (let i = 0; i < 256; i++) {
let inv = 0
if (i !== 0) { let base = i, e = 254, r = 1; while (e) { if (e & 1) r = xt0(r, base); base = xt0(base, base); e >>= 1 } inv = r }
S[i] = inv ^ rotl8(inv, 1) ^ rotl8(inv, 2) ^ rotl8(inv, 3) ^ rotl8(inv, 4) ^ 0x63
SI[S[i]] = i
}
const xt = (a, b) => { let r = 0; while (b) { if (b & 1) r ^= a; a = (a << 1) ^ ((a >> 7) * 0x11b); b >>>= 1 } return r & 255 }
const U0 = new Uint32Array(256), U1 = new Uint32Array(256), U2 = new Uint32Array(256), U3 = new Uint32Array(256)
for (let i = 0; i < 256; i++) {
const s = SI[i]
const r0 = xt(s, 0xe), r1 = xt(s, 9), r2 = xt(s, 0xd), r3 = xt(s, 0xb)
U0[i] = (r0 << 24) | (r1 << 16) | (r2 << 8) | r3
U1[i] = (r3 << 24) | (r0 << 16) | (r1 << 8) | r2
U2[i] = (r2 << 24) | (r3 << 16) | (r0 << 8) | r1
U3[i] = (r1 << 24) | (r2 << 16) | (r3 << 8) | r0
}
export function makeKeys(key) {
const w = new Uint32Array(44)
for (let i = 0; i < 4; i++) w[i] = (key[4*i] << 24) | (key[4*i+1] << 16) | (key[4*i+2] << 8) | key[4*i+3]
let rc = 1
for (let i = 4; i < 44; i++) {
let t = w[i-1]
if (i % 4 === 0) {
t = ((t << 8) | (t >>> 24)) >>> 0
t = (S[t >>> 24] << 24) ^ (S[(t >>> 16) & 255] << 16) ^ (S[(t >>> 8) & 255] << 8) ^ S[t & 255] ^ (rc << 24)
rc = xt(rc, 2)
}
w[i] = w[i-4] ^ t
}
const dw = new Uint32Array(44)
for (let r = 1; r < 10; r++) {
for (let c = 0; c < 4; c++) {
const col = w[r*4+c]
const a0 = col >>> 24, a1 = (col >>> 16) & 255, a2 = (col >>> 8) & 255, a3 = col & 255
dw[r*4+c] = ((xt(a0, 14) ^ xt(a1, 11) ^ xt(a2, 13) ^ xt(a3, 9)) << 24) |
((xt(a0, 9) ^ xt(a1, 14) ^ xt(a2, 11) ^ xt(a3, 13)) << 16) |
((xt(a0, 13) ^ xt(a1, 9) ^ xt(a2, 14) ^ xt(a3, 11)) << 8) |
(xt(a0, 11) ^ xt(a1, 13) ^ xt(a2, 9) ^ xt(a3, 14))
}
}
return { w, dw }
}
/** In-place CBC decrypt of buf[off .. off+len] (len%16 tail copied as-is).
* iv: 16-byte initial chain. Returns nothing (mutates buf). */
export function cbcDecrypt(buf, off, len, iv, keys) {
const { w, dw } = keys
const st = new Uint8Array(16)
const xti = (a, b) => { let r = 0; while (b) { if (b & 1) r ^= a; a = (a << 1) ^ ((a >> 7) * 0x11b); b >>>= 1 } return r & 255 }
const full = Math.floor(len / 16) * 16
for (let p = off; p < off + full; p += 16) {
const prev = buf.subarray(p, p + 16)
const prevCopy = Uint8Array.from(prev)
for (let k = 0; k < 16; k++) st[k] = prev[k]
const rk = (getWord) => { for (let k = 0; k < 16; k++) st[k] ^= (getWord(k >> 2) >>> ((3 - (k & 3)) * 8)) & 255 }
rk((i) => w[40 + i])
for (let r = 9; r >= 1; r--) {
// InvShiftRows: row j rotates right by j
for (let j = 1; j < 4; j++) {
const row = [st[j], st[4 + j], st[8 + j], st[12 + j]]
const rot = [row[(4 - j) % 4], row[(5 - j) % 4], row[(6 - j) % 4], row[(7 - j) % 4]]
st[j] = rot[0]; st[4 + j] = rot[1]; st[8 + j] = rot[2]; st[12 + j] = rot[3]
}
for (let k = 0; k < 16; k++) st[k] = SI[st[k]]
rk((i) => w[r * 4 + i])
// InvMixColumns
for (let c = 0; c < 4; c++) {
const a0 = st[c * 4], a1 = st[c * 4 + 1], a2 = st[c * 4 + 2], a3 = st[c * 4 + 3]
st[c * 4] = xti(a0, 14) ^ xti(a1, 11) ^ xti(a2, 13) ^ xti(a3, 9)
st[c * 4 + 1] = xti(a0, 9) ^ xti(a1, 14) ^ xti(a2, 11) ^ xti(a3, 13)
st[c * 4 + 2] = xti(a0, 13) ^ xti(a1, 9) ^ xti(a2, 14) ^ xti(a3, 11)
st[c * 4 + 3] = xti(a0, 11) ^ xti(a1, 13) ^ xti(a2, 9) ^ xti(a3, 14)
}
}
for (let j = 1; j < 4; j++) {
const row = [st[j], st[4 + j], st[8 + j], st[12 + j]]
const rot = [row[(4 - j) % 4], row[(5 - j) % 4], row[(6 - j) % 4], row[(7 - j) % 4]]
st[j] = rot[0]; st[4 + j] = rot[1]; st[8 + j] = rot[2]; st[12 + j] = rot[3]
}
for (let k = 0; k < 16; k++) st[k] = SI[st[k]]
for (let k = 0; k < 16; k++) st[k] ^= (w[k >> 2] >>> ((3 - (k & 3)) * 8)) & 255
for (let k = 0; k < 16; k++) buf[p + k] = st[k] ^ iv[k]
iv = prevCopy
}
return iv
}
// forward AES block encrypt (for CTR keystream)
const T0 = new Uint32Array(256), T1 = new Uint32Array(256), T2 = new Uint32Array(256), T3 = new Uint32Array(256)
for (let i = 0; i < 256; i++) {
const s2 = xt(S[i], 2), s3 = xt(S[i], 3)
T0[i] = (s2 << 24) | (S[i] << 16) | (S[i] << 8) | s3
T1[i] = (s3 << 24) | (s2 << 16) | (S[i] << 8) | S[i]
T2[i] = (S[i] << 24) | (s3 << 16) | (s2 << 8) | S[i]
T3[i] = (S[i] << 24) | (S[i] << 16) | (s3 << 8) | s2
}
export function encryptBlock(out, o, inp, i2, keys) {
const { w } = keys
let s0 = ((inp[i2] << 24) | (inp[i2+1] << 16) | (inp[i2+2] << 8) | inp[i2+3]) ^ w[0]
let s1 = ((inp[i2+4] << 24) | (inp[i2+5] << 16) | (inp[i2+6] << 8) | inp[i2+7]) ^ w[1]
let s2 = ((inp[i2+8] << 24) | (inp[i2+9] << 16) | (inp[i2+10] << 8) | inp[i2+11]) ^ w[2]
let s3 = ((inp[i2+12] << 24) | (inp[i2+13] << 16) | (inp[i2+14] << 8) | inp[i2+15]) ^ w[3]
for (let r = 1; r <= 9; r++) {
const t0 = T0[s0 >>> 24] ^ T1[(s1 >>> 16) & 255] ^ T2[(s2 >>> 8) & 255] ^ T3[s3 & 255] ^ w[r*4]
const t1 = T0[s1 >>> 24] ^ T1[(s2 >>> 16) & 255] ^ T2[(s3 >>> 8) & 255] ^ T3[s0 & 255] ^ w[r*4+1]
const t2 = T0[s2 >>> 24] ^ T1[(s3 >>> 16) & 255] ^ T2[(s0 >>> 8) & 255] ^ T3[s1 & 255] ^ w[r*4+2]
const t3 = T0[s3 >>> 24] ^ T1[(s0 >>> 16) & 255] ^ T2[(s1 >>> 8) & 255] ^ T3[s2 & 255] ^ w[r*4+3]
s0 = t0; s1 = t1; s2 = t2; s3 = t3
}
const e0 = ((S[s0 >>> 24] << 24) | (S[(s1 >>> 16) & 255] << 16) | (S[(s2 >>> 8) & 255] << 8) | S[s3 & 255]) ^ w[40]
const e1 = ((S[s1 >>> 24] << 24) | (S[(s2 >>> 16) & 255] << 16) | (S[(s3 >>> 8) & 255] << 8) | S[s0 & 255]) ^ w[41]
const e2 = ((S[s2 >>> 24] << 24) | (S[(s3 >>> 16) & 255] << 16) | (S[(s0 >>> 8) & 255] << 8) | S[s1 & 255]) ^ w[42]
const e3 = ((S[s3 >>> 24] << 24) | (S[(s0 >>> 16) & 255] << 16) | (S[(s1 >>> 8) & 255] << 8) | S[s2 & 255]) ^ w[43]
const put = (v, k) => { out[o + 4*k] = v >>> 24; out[o + 4*k + 1] = (v >>> 16) & 255; out[o + 4*k + 2] = (v >>> 8) & 255; out[o + 4*k + 3] = v & 255 }
put(e0, 0); put(e1, 1); put(e2, 2); put(e3, 3)
}
// ---- box helpers -----------------------------------------------------------
function u32(v) { return [(v >>> 24) & 255, (v >>> 16) & 255, (v >>> 8) & 255, v & 255] }
function b64bytes(s) { return Uint8Array.from(atob(s), (c) => c.charCodeAt(0)) }
function parseBoxes(buf, start, end) {
const out = []; let i = start
while (i + 8 <= end) {
let size = ((buf[i] << 24) | (buf[i+1] << 16) | (buf[i+2] << 8) | buf[i+3]) >>> 0
const type = String.fromCharCode(buf[i+4], buf[i+5], buf[i+6], buf[i+7])
let hdr = 8
if (size === 1) { size = Number((BigInt(buf[i+8]) << 56n) | (BigInt(buf[i+9]) << 48n) | (BigInt(buf[i+10]) << 40n) | (BigInt(buf[i+11]) << 32n) | (BigInt(buf[i+12]) << 24n) | (BigInt(buf[i+13]) << 16n) | (BigInt(buf[i+14]) << 8n) | BigInt(buf[i+15])); hdr = 16 }
if (size < 8 || i + size > end) break
out.push({ type, start: i, end: i + size, hdr })
i += size
}
return out
}
function child(buf, start, end, type) { return parseBoxes(buf, start, end).find((b) => b.type === type) || null }
function sub(buf, b) { return buf.subarray(b.start, b.end) }
function box(type, ...parts) {
const len = 8 + parts.reduce((n, p) => n + p.length, 0)
const out = new Uint8Array(len)
out.set(u32(len), 0)
out.set([...type].map((c) => c.charCodeAt(0)), 4)
let o = 8
for (const p of parts) { out.set(p, o); o += p.length }
return out
}
function concat(parts) {
const n = parts.reduce((a, p) => a + p.length, 0)
const out = new Uint8Array(n)
let o = 0
for (const p of parts) { out.set(p, o); o += p.length }
return out
}
// ---- tenc parsing ----------------------------------------------------------
export function stripInit() {}
export function initDrmWasm() {}
function tencOf(header) {
const moov = child(header, 0, header.length, "moov")
if (!moov) return null
const trak = child(header, moov.start + moov.hdr, moov.end, "trak")
if (!trak) return null
const mdia = child(header, trak.start + trak.hdr, trak.end, "mdia")
const minf = mdia && child(header, mdia.start + mdia.hdr, mdia.end, "minf")
const stbl = minf && child(header, minf.start + minf.hdr, minf.end, "stbl")
const stsd = stbl && child(header, stbl.start + stbl.hdr, stbl.end, "stsd")
if (!stsd) return null
for (const entry of parseBoxes(header, stsd.start + stsd.hdr + 8, stsd.end)) {
// the entry payload starts with raw sample-entry fields; the encryption
// info sits in frma/schm/schi (sometimes wrapped in sinf) — scan for a
// valid tenc box by its type bytes instead of walking a box tree
for (let p = entry.start + entry.hdr; p + 8 <= entry.end; p++) {
if (!(header[p + 4] === 0x74 && header[p + 5] === 0x65 && header[p + 6] === 0x6e && header[p + 7] === 0x63)) continue // "tenc"
const start = p
const size = ((header[start] << 24) | (header[start + 1] << 16) | (header[start + 2] << 8) | header[start + 3]) >>> 0
if (size < 20 || start + size > entry.end) continue
return { tenc: { type: "tenc", start, end: start + size, hdr: 8 }, sinf: null }
}
}
return null
}
export function tencMarker(header) {
const t = tencOf(header)
if (!t) return -1
return header[t.tenc.start + t.tenc.hdr + 7]
}
export function tencCryptPattern(header) {
const t = tencOf(header)
if (!t) return undefined
const ver = header[t.tenc.start + t.tenc.hdr]
if (ver !== 1) return undefined
const p = header[t.tenc.start + t.tenc.hdr + 24]
const crypt = p >> 4, skip = p & 15
return crypt || skip ? [skip, crypt] : undefined
}
export function tencConstantIv(header) {
const t = tencOf(header)
if (!t) return undefined
const ver = header[t.tenc.start + t.tenc.hdr]
if (ver !== 1) return undefined
const p = header[t.tenc.start + t.tenc.hdr + 24]
const size = header[t.tenc.start + t.tenc.hdr + 25]
if (!(p >> 4) || !size) return undefined
return header.slice(t.tenc.start + t.tenc.hdr + 26, t.tenc.start + t.tenc.hdr + 26 + size)
}
// ---- fragment decryption ---------------------------------------------------
const RENAME = new Set(["pssh", "senc", "saio", "saiz", "sbgp", "sgpd"])
function parseFragment(frag) {
const moof = child(frag, 0, Math.min(frag.length, 1 << 20), "moof")
if (!moof) throw new Error("no moof")
const traf = child(frag, moof.start + moof.hdr, moof.end, "traf")
if (!traf) throw new Error("no traf")
let dataOff = null, sizes = [], senc = null
for (const b of parseBoxes(frag, traf.start + traf.hdr, traf.end)) {
if (b.type === "trun") {
const flags = ((frag[b.start + b.hdr + 1] << 16) | (frag[b.start + b.hdr + 2] << 8) | frag[b.start + b.hdr + 3])
const count = ((frag[b.start + b.hdr + 4] << 24) | (frag[b.start + b.hdr + 5] << 16) | (frag[b.start + b.hdr + 6] << 8) | frag[b.start + b.hdr + 7]) >>> 0
let p = b.start + b.hdr + 8
if (flags & 0x1) { dataOff = ((frag[p] << 24) | (frag[p+1] << 16) | (frag[p+2] << 8) | frag[p+3]); p += 4 }
if (flags & 0x4) p += 4
for (let k = 0; k < count; k++) {
if (flags & 0x100) p += 4
if (flags & 0x200) { sizes.push(((frag[p] << 24) | (frag[p+1] << 16) | (frag[p+2] << 8) | frag[p+3]) >>> 0); p += 4 } else sizes.push(0)
if (flags & 0x400) p += 4
if (flags & 0x800) p += 4
}
}
if (b.type === "senc") senc = b
}
if (!senc) throw new Error("no senc")
const payload = frag.subarray(senc.start + senc.hdr, senc.end)
const sflags = ((payload[1] << 16) | (payload[2] << 8) | payload[3])
const count = ((payload[4] << 24) | (payload[5] << 16) | (payload[6] << 8) | payload[7]) >>> 0
let q = 8
const samples = []
for (let k = 0; k < count; k++) {
const iv = payload.slice(q, q + 8); q += 8
if (sflags & 0x2) {
const nsub = (payload[q] << 8) | payload[q + 1]; q += 2
const runs = []
for (let s = 0; s < nsub; s++) {
runs.push([(payload[q] << 8) | payload[q + 1], ((payload[q+2] << 24) | (payload[q+3] << 16) | (payload[q+4] << 8) | payload[q+5]) >>> 0])
q += 6
}
samples.push({ iv, runs })
} else {
samples.push({ iv, runs: [[0, sizes[k] || 0]] })
}
}
// rename encryption boxes to free
for (const b of parseBoxes(frag, moof.start + moof.hdr, moof.end)) if (RENAME.has(b.type)) frag.set([102, 114, 101, 101], b.start + 4)
for (const b of parseBoxes(frag, traf.start + traf.hdr, traf.end)) if (RENAME.has(b.type)) frag.set([102, 114, 101, 101], b.start + 4)
return { samples, sizes, dataOff }
}
/** cenc (AES-CTR) — verified byte-identical */
export function decryptAndStripFragment(frag, key, marker) {
const { samples, sizes, dataOff } = parseFragment(frag)
const keys = makeKeys(key)
const ctr = new Uint8Array(16)
const ks = new Uint8Array(16)
let off = 0
for (let si = 0; si < samples.length; si++) {
const smp = samples[si]
let pos = 0
let counter = 0n
let kpos = 16
for (const [clear, prot] of smp.runs) {
pos += clear
for (let k = 0; k < prot; k++) {
if (kpos === 16) {
ctr.fill(0)
ctr.set(smp.iv, 0)
ctr.set([Number((counter >> 56n) & 255n), Number((counter >> 48n) & 255n), Number((counter >> 40n) & 255n), Number((counter >> 32n) & 255n), Number((counter >> 24n) & 255n), Number((counter >> 16n) & 255n), Number((counter >> 8n) & 255n), Number(counter & 255n)], 8)
encryptBlock(ks, 0, ctr, 0, keys)
counter++
kpos = 0
}
frag[dataOff + off + pos + k] ^= ks[kpos++]
}
pos += prot
}
off += sizes[si] || 0
}
return frag
}
/** cbcs (AES-CBC with pattern) */
export function decryptAndStripFragmentCbcs(frag, key, marker, skip, crypt, constantIv) {
const { samples, sizes, dataOff } = parseFragment(frag)
const keys = makeKeys(key)
let off = 0
for (let si = 0; si < samples.length; si++) {
const smp = samples[si]
let iv = new Uint8Array(16)
if (constantIv && constantIv.length) iv.set(constantIv)
else iv.set(smp.iv.subarray(0, 8), 0)
let pos = 0
for (const [clear, prot] of smp.runs) {
pos += clear
let rem = prot
while (rem > 0) {
const take = Math.min(16, rem)
const blk = frag.slice(dataOff + off + pos, dataOff + off + pos + 16)
const chain = blk.slice()
cbcDecrypt(blk, 0, 16, iv, keys)
frag.set(blk.subarray(0, take), dataOff + off + pos)
iv = chain
pos += take
rem -= take
}
}
off += sizes[si] || 0
}
return frag
}
// ---- progressive muxer (mirrors MuxPlanner) --------------------------------
const patchU32 = (b, at, v) => { b[at] = (v >>> 24) & 255; b[at+1] = (v >>> 16) & 255; b[at+2] = (v >>> 8) & 255; b[at+3] = v & 255 }
const readU32 = (b, o) => ((b[o] << 24) | (b[o+1] << 16) | (b[o+2] << 8) | b[o+3]) >>> 0
const u64 = (v) => [...u32(Math.floor(v / 2 ** 32)), ...u32(v >>> 0)]
const pad4 = (v) => v >>> 0
function fullbox(type, ver, ...parts) { return box(type, new Uint8Array([ver & 255, 0, 0, 0]), ...parts) }
function trackParts(header) {
const moov = child(header, 0, header.length, "moov")
const trak = child(header, moov.start + moov.hdr, moov.end, "trak")
const tkhd = child(header, trak.start + trak.hdr, trak.end, "tkhd")
const mdia = child(header, trak.start + trak.hdr, trak.end, "mdia")
const mdhd = child(header, mdia.start + mdia.hdr, mdia.end, "mdhd")
const hdlr = child(header, mdia.start + mdia.hdr, mdia.end, "hdlr")
const minf = child(header, mdia.start + mdia.hdr, mdia.end, "minf")
const stbl = child(header, minf.start + minf.hdr, minf.end, "stbl")
return {
moov,
tkhd: sub(header, tkhd),
mdhd: sub(header, mdhd),
hdlr: sub(header, hdlr),
vmhd: (() => { const b = child(header, minf.start + minf.hdr, minf.end, "vmhd"); return b && sub(header, b) })(),
smhd: (() => { const b = child(header, minf.start + minf.hdr, minf.end, "smhd"); return b && sub(header, b) })(),
dinf: sub(header, child(header, minf.start + minf.hdr, minf.end, "dinf")),
stsd: sub(header, child(header, stbl.start + stbl.hdr, stbl.end, "stsd")),
timescale: readU32(header, mdhd.start + mdhd.hdr + 12),
mvhd: null,
ftyp: null,
}
}
function moofSamples(moof) {
const traf = child(moof, 8, moof.length, "traf")
const trun = child(moof, traf.start + traf.hdr, traf.end, "trun")
const p = (trun.start + trun.hdr)
const flags = (moof[p+1] << 16) | (moof[p+2] << 8) | moof[p+3]
const count = readU32(moof, p + 4)
let q = p + 8
if (flags & 0x1) q += 4
let firstFlags = 0
if (flags & 0x4) { firstFlags = readU32(moof, q); q += 4 }
const samples = []
let sizeSum = 0
for (let k = 0; k < count; k++) {
const dur = flags & 0x100 ? readU32(moof, q) : 0
if (flags & 0x100) q += 4
const size = flags & 0x200 ? readU32(moof, q) : 0
if (flags & 0x200) q += 4
const sflags = flags & 0x400 ? readU32(moof, q) : (k === 0 ? firstFlags : 0)
if (flags & 0x400) q += 4
let comp = 0
if (flags & 0x800) { const raw = readU32(moof, q); comp = raw | 0; q += 4 }
samples.push({ dur, size, flags: sflags, comp, sync: k === 0 })
sizeSum += size
}
return { samples, sizeSum }
}
function rle(values) {
const out = []
let i = 0
while (i < values.length) {
let j = i
while (j + 1 < values.length && values[j + 1] === values[i]) j++
out.push([j - i + 1, values[i]])
i = j + 1
}
return out
}
const sttsOf = (samples) => { const r = rle(samples.map((s) => s.dur)); return fullbox("stts", 0, u32(r.length), ...r.flatMap(([c, d]) => [u32(c), u32(d)])) }
const cttsOf = (samples) => { const r = rle(samples.map((s) => s.comp)); return fullbox("ctts", 1, u32(r.length), ...r.flatMap(([c, d]) => [u32(c), u32(d)])) }
const stssOf = (samples) => {
const sync = []
samples.forEach((s, i) => { if (s.sync && !(s.flags & 0x10000)) sync.push(u32(i + 1)) })
return fullbox("stss", 0, u32(sync.length), ...sync)
}
const stscOf = (chunks) => {
const r = rle(chunks.map((c) => c[2]))
let chunkNo = 1
const parts = []
for (const [count, per] of r) { parts.push(u32(chunkNo), u32(per), u32(1)); chunkNo += count }
return fullbox("stsc", 0, u32(r.length), ...parts)
}
const stszOf = (samples) => fullbox("stsz", 0, u32(0), u32(samples.length), ...samples.map((s) => u32(s.size)))
const co64Of = (chunks) => fullbox("co64", 0, u32(chunks.length), ...chunks.map(() => new Uint8Array(8)))
export class MuxPlanner {
constructor(videoHeader, audioHeader) {
this.v = trackParts(videoHeader)
this.v.ftyp = sub(videoHeader, child(videoHeader, 0, videoHeader.length, "ftyp"))
this.v.mvhd = sub(videoHeader, child(videoHeader, this.v.moov.start + this.v.moov.hdr, this.v.moov.end, "mvhd"))
this.a = audioHeader ? trackParts(audioHeader) : null
this.vs = []
this.as = []
this.vchunks = []
this.achunks = []
}
pushVideoMoof(moof, offset) {
const s = moofSamples(moof)
this.vs.push(...s.samples)
this.vchunks.push([offset + moof.length + 8, s.sizeSum, s.samples.length])
}
pushAudioMoof(moof, offset) {
const s = moofSamples(moof)
this.as.push(...s.samples)
this.achunks.push([offset + moof.length + 8, s.sizeSum, s.samples.length])
}
finish() {
const vDur = this.vs.reduce((n, s) => n + s.dur, 0)
const aDur = this.as.reduce((n, s) => n + s.dur, 0)
const movieTs = this.v.timescale
const vFirstDur = this.vs.length ? this.vs[0].dur : 1
const vTrackDur = vDur + vFirstDur
const aTrackDur = this.a ? Math.round(aDur * movieTs / this.a.timescale) : 0
const movieDur = Math.max(vTrackDur, aTrackDur)
const trackCount = this.a ? 2 : 1
// --- layout: interleave chunks video/audio ---
const layout = []
const n = Math.max(this.vchunks.length, this.achunks.length)
for (let k = 0; k < n; k++) {
const vc = this.vchunks[k]
if (vc) layout.push(1, vc[0], vc[1])
const ac = this.achunks[k]
if (ac) layout.push(0, ac[0], ac[1])
}
// --- build header with placeholder co64 + mdat header (16B, 64-bit size) ---
const mdatPayload = layout.reduce((sum, val, i) => (i % 3 === 2 ? sum + val : sum), 0)
const vTkhd = this.v.tkhd.slice()
patchU32(vTkhd, 8 + 12, 1)
patchU32(vTkhd, 8 + 20, vTrackDur)
const mdhdV = this.v.mdhd.slice()
patchU32(mdhdV, 8 + 12, movieTs)
patchU32(mdhdV, 8 + 16, vDur)
const elstEntries = [u32(vFirstDur), u32(0xffffffff), u32(0x00010000), u32(vDur), u32(vFirstDur), u32(0x00010000)]
const edts = box("edts", fullbox("elst", 0, u32(2), ...elstEntries))
// sample entries must be plain avc1/mp4a — the source stsd may be the
// encrypted encv/enca variant, which players like AVFoundation refuse
const stsdV = this.v.stsd.slice()
if (stsdV[20] === 0x65 && stsdV[21] === 0x6e && stsdV[22] === 0x63 && stsdV[23] === 0x76) stsdV.set([97, 118, 99, 49], 20) // encv -> avc1
const co64V = co64Of(this.vchunks)
const stblV = box("stbl", stsdV, sttsOf(this.vs), cttsOf(this.vs), stssOf(this.vs), stscOf(this.vchunks), stszOf(this.vs), co64V)
const minfV = box("minf", this.v.vmhd, this.v.dinf, stblV)
const mdiaV = box("mdia", mdhdV, this.v.hdlr, minfV)
const trakV = box("trak", vTkhd, edts, mdiaV)
let trakA = null
let co64A = null
if (this.a) {
const aTkhd = this.a.tkhd.slice()
patchU32(aTkhd, 8 + 12, 2)
patchU32(aTkhd, 8 + 20, aTrackDur)
const stsdA = this.a.stsd.slice()
if (stsdA[20] === 0x65 && stsdA[21] === 0x6e && stsdA[22] === 0x63 && stsdA[23] === 0x61) stsdA.set([109, 112, 52, 97], 20) // enca -> mp4a
co64A = co64Of(this.achunks)
const stblA = box("stbl", stsdA, sttsOf(this.as), stscOf(this.achunks), stszOf(this.as), co64A)
const minfA = box("minf", this.a.smhd, this.a.dinf, stblA)
const mdiaA = box("mdia", this.a.mdhd, this.a.hdlr, minfA)
trakA = box("trak", aTkhd, mdiaA)
}
const mvhd = this.v.mvhd.slice()
patchU32(mvhd, 8 + 16, movieDur)
patchU32(mvhd, 8 + 96, trackCount + 1)
const moov = box("moov", mvhd, trakV, ...(trakA ? [trakA] : []))
const header = concat([this.v.ftyp, moov])
// patch real chunk offsets (header len + 16-byte ftyp?? no — mdat header 16)
const mdatStart = header.length + 16
// patch real chunk offsets into the finished header's co64 boxes
const mdatStart2 = header.length + 16
const co64s = []
const collect = (start2, end2) => {
for (const b of parseBoxes(header, start2, end2)) {
if (b.type === "co64") co64s.push(b)
if (["moov","trak","mdia","minf","stbl"].includes(b.type)) collect(b.start + b.hdr, b.end)
}
}
collect(0, header.length)
const vo2 = [0, 0]
let cum2 = 0
let ci = 0
for (let k = 0; k < n; k++) {
const vc = this.vchunks[k]
if (vc) {
const b = co64s[0]
const off = mdatStart2 + cum2
patchU32(header, b.start + 16 + vo2[0], 0)
patchU32(header, b.start + 16 + vo2[0] + 4, off)
vo2[0] += 8
cum2 += vc[1]
}
const ac = this.achunks[k]
if (ac) {
const b = co64s[1]
if (b) {
const off = mdatStart2 + cum2
patchU32(header, b.start + 16 + vo2[1], 0)
patchU32(header, b.start + 16 + vo2[1] + 4, off)
vo2[1] += 8
}
cum2 += ac[1]
}
}
ci = 0
// header byte sizes must be unchanged by patching — they are.
const mdatHeader = new Uint8Array(16)
mdatHeader.set(u32(1), 0)
mdatHeader.set([109, 100, 97, 116], 4) // mdat
const total = 16 + mdatPayload
mdatHeader.set(u64(total).slice(4), 8) // 64-bit size low half?? fixed below
mdatHeader.set([...u32(Math.floor(total / 2 ** 32)), ...u32(total >>> 0)], 8)
const full = concat([header, mdatHeader])
return new MuxResult(full, layout, mdatHeader)
}
}
class MuxResult {
constructor(header, layout, mdatHeader) {
this._h = header
this._l = layout
this._m = mdatHeader
}
header() { return this._h }
layout() { return this._l }
mdatHeader() { return this._m }
}

100
ext/lib/paths.js Normal file
View File

@@ -0,0 +1,100 @@
// Folder/filename scheme builder, shared by background + options preview.
// Folder and file naming schemes.
export const SINGLE_SCHEMES = {
one: { label: "One folder", desc: "Saves go straight into Downloads.", folders: [] },
creator: { label: "By creator", desc: "A folder for each creator.", folders: ["{creator}"] },
"creator-type": {
label: "By creator and type",
rec: true,
desc: "A folder per creator, with Videos, Photos and Audio inside.",
folders: ["{creator}", "{typeFolder}"],
},
"site-creator-type": {
label: "By site, creator and type",
desc: "Like By creator and type, with a folder for each site on top.",
folders: ["OnlyFans", "{creator}", "{typeFolder}"],
},
};
export const BULK_SCHEMES = {
"creator-section-type": {
label: "By creator, section and type",
rec: true,
desc: "A folder per creator, then Timeline, Messages, Paid… with Videos and Photos inside.",
folders: ["{creator}", "{section}", "{typeFolder}"],
},
same: { label: "Same as single downloads", desc: "Bulk downloads fill the folders your single downloads use.", same: true },
"creator-date-section": {
label: "By creator, date and section (classic)",
desc: "A folder for the day each run starts, split by section.",
folders: ["{creator}", "{date}", "{section}"],
},
one: { label: "One folder", desc: "Saves go straight into Downloads.", folders: [] },
};
const TYPE_FOLDERS = { video: "Videos", photo: "Photos", gif: "Photos", audio: "Audio" };
/** Build the full download path (relative to Downloads).
* opts: { scheme, bulk, creator, type, section, date(ts s|Date|str), timestamp, mediaId, postId, quality, ext, template } */
export function buildPath(opts) {
const scheme = opts.scheme ?? "creator-type";
const def = opts.bulk ? BULK_SCHEMES[scheme] ?? BULK_SCHEMES.same : SINGLE_SCHEMES[scheme] ?? SINGLE_SCHEMES["creator-type"];
const folders = def.same ? (SINGLE_SCHEMES[opts.singleScheme ?? "creator-type"] ?? SINGLE_SCHEMES["creator-type"]).folders : def.folders;
const type = opts.type ?? "video";
const typeFolder = TYPE_FOLDERS[type] ?? "Other";
const date = formatDate(opts.date);
const creator = sanitize(opts.creator ?? "unknown");
const parts = folders.map((f) =>
sanitize(
f
.replaceAll("{creator}", creator)
.replaceAll("{typeFolder}", typeFolder)
.replaceAll("{section}", sanitize(opts.section ?? "Timeline"))
.replaceAll("{date}", date)
)
);
const name = buildName(opts);
return [...parts, name].filter(Boolean).join("/");
}
export function buildName(opts) {
const type = opts.type ?? "video";
const template = opts.template ?? "{creator}_{type}_{date}_{timestamp}_{mediaId}_{quality}";
const out = template
.replaceAll("{creator}", sanitize(opts.creator ?? "unknown"))
.replaceAll("{type}", type)
.replaceAll("{date}", formatDate(opts.date))
.replaceAll("{timestamp}", String(opts.timestamp ?? Math.floor(Date.now() / 1000)))
.replaceAll("{mediaId}", String(opts.mediaId ?? ""))
.replaceAll("{postId}", String(opts.postId ?? ""))
.replaceAll("{quality}", opts.quality ?? "")
.replaceAll("{ext}", opts.ext ?? "mp4")
.replace(/_+(\.)/g, "$1")
.replace(/_{2,}/g, "_");
const out2 = sanitize(out);
// always end with a sensible extension
const ext = (opts.ext ?? "mp4").replace(/^\./, "");
return out2.toLowerCase().endsWith("." + ext.toLowerCase()) ? out2 : `${out2.replace(/_+$/, "")}.${ext}`;
}
function formatDate(d) {
if (!d) return "";
let date;
if (d instanceof Date) date = d;
else if (typeof d === "number") date = new Date(d * (d > 1e12 ? 1 : 1000));
else {
const parsed = Date.parse(d);
if (Number.isNaN(parsed)) return sanitize(String(d));
date = new Date(parsed);
}
const p = (n) => String(n).padStart(2, "0");
return `${date.getFullYear()}-${p(date.getMonth() + 1)}-${p(date.getDate())}`;
}
function sanitize(s) {
return String(s ?? "").replace(/[^\w.-]+/g, "_").replace(/^\.+/, "_");
}

104
ext/lib/pb.js Normal file
View File

@@ -0,0 +1,104 @@
/** Minimal protobuf wire-format writer/reader (widevine messages) — Uint8Array only (browser-safe). */
export function varint(n) {
const out = [];
let v = BigInt(n);
while (v > 0x7fn) {
out.push(Number((v & 0x7fn) | 0x80n));
v >>= 7n;
}
out.push(Number(v));
return new Uint8Array(out);
}
export function tag(field, wire) {
return varint((field << 3) | wire);
}
export function pbVarint(field, value) {
return concat(tag(field, 0), varint(value));
}
export function pbBytes(field, buf) {
return concat(tag(field, 2), varint(buf.length), buf);
}
export function pbString(field, str) {
return pbBytes(field, new TextEncoder().encode(str));
}
/** Concatenate pre-encoded fields. */
export function pbMsg(...parts) {
return concat(...parts);
}
export function concat(...arrays) {
const len = arrays.reduce((n, a) => n + a.length, 0);
const out = new Uint8Array(len);
let o = 0;
for (const a of arrays) { out.set(a, o); o += a.length; }
return out;
}
export function tryParse(buf) {
const out = [];
let i = 0;
while (i < buf.length) {
let key = 0, shift = 0;
while (true) {
if (i >= buf.length) return null;
const b = buf[i++];
key |= (b & 0x7f) << shift;
if (!(b & 0x80)) break;
shift += 7;
if (shift > 35) return null;
}
const field = key >> 3, wire = key & 7;
if (field === 0) return null;
if (wire === 0) {
let v = 0n, s = 0n;
while (true) {
if (i >= buf.length) return null;
const b = buf[i++];
v |= BigInt(b & 0x7f) << s;
if (!(b & 0x80)) break;
s += 7n;
}
out.push([field, 0, v]);
} else if (wire === 1) {
if (i + 8 > buf.length) return null;
out.push([field, 1, buf.slice(i, i + 8)]);
i += 8;
} else if (wire === 2) {
let len = 0, sh = 0;
while (true) {
if (i >= buf.length) return null;
const b = buf[i++];
len |= (b & 0x7f) << sh;
if (!(b & 0x80)) break;
sh += 7;
if (sh > 30) return null;
}
if (i + len > buf.length) return null;
out.push([field, 2, buf.slice(i, i + len)]);
i += len;
} else if (wire === 5) {
if (i + 4 > buf.length) return null;
out.push([field, 5, buf.slice(i, i + 4)]);
i += 4;
} else return null;
}
return out;
}
/** Get field values: getAll(buf, field) → array of values. */
export function getAll(buf, field) {
const fields = tryParse(buf);
if (!fields) return [];
return fields.filter(([f]) => f === field).map(([, , v]) => v);
}
export function get(buf, field) {
const all = getAll(buf, field);
return all.length ? all[0] : undefined;
}

4
ext/lib/signer-module.js Normal file

File diff suppressed because one or more lines are too long

222
ext/lib/signer.js Normal file
View File

@@ -0,0 +1,222 @@
// Live OF request signer — port of ofsaver's ofrules.js for the offscreen
// document (eval allowed via relaxed CSP). In-memory cache per revision.
const BUNDLE_ROOT = "https://static2.onlyfans.com/static/prod/f";
const REV_ENDPOINT = "https://onlyfans.com/api2/v2/ip";
const RC4_ALPHABET =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=";
export const APP_TOKEN = "33d57ade8c02dbc5a333db99ff9ae26a";
// --- sync SHA-1 (hex) — the signer's dep is called synchronously ----------
export function sha1hex(text) {
const msg = new TextEncoder().encode(text);
const ml = msg.length;
const padded = new Uint8Array((((ml + 8) >> 6) + 1) << 6);
padded.set(msg);
padded[ml] = 0x80;
const bitLen = ml * 8;
const dv = new DataView(padded.buffer);
dv.setUint32(padded.length - 4, bitLen >>> 0);
dv.setUint32(padded.length - 8, Math.floor(bitLen / 2 ** 32));
let h0 = 0x67452301, h1 = 0xefcdab89, h2 = 0x98badcfe, h3 = 0x10325476, h4 = 0xc3d2e1f0;
const w = new Uint32Array(80);
const rol = (x, n) => (x << n) | (x >>> (32 - n));
for (let i = 0; i < padded.length; i += 64) {
for (let j = 0; j < 16; j++) w[j] = dv.getUint32(i + j * 4);
for (let j = 16; j < 80; j++) w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
let a = h0, b = h1, c = h2, d = h3, e = h4;
for (let j = 0; j < 80; j++) {
let f, k;
if (j < 20) { f = (b & c) | (~b & d); k = 0x5a827999; }
else if (j < 40) { f = b ^ c ^ d; k = 0x6ed9eba1; }
else if (j < 60) { f = (b & c) | (b & d) | (c & d); k = 0x8f1bbcdc; }
else { f = b ^ c ^ d; k = 0xca62c1d6; }
const t = (rol(a, 5) + f + e + k + w[j]) >>> 0;
e = d; d = c; c = rol(b, 30); b = a; a = t;
}
h0 = (h0 + a) >>> 0; h1 = (h1 + b) >>> 0; h2 = (h2 + c) >>> 0; h3 = (h3 + d) >>> 0; h4 = (h4 + e) >>> 0;
}
return [h0, h1, h2, h3, h4].map((x) => x.toString(16).padStart(8, "0")).join("");
}
export function pathGet(obj, path, fallback) {
if (obj == null) return fallback;
let cur = obj;
for (const key of String(path).split(".")) {
if (cur == null) return fallback;
cur = cur[key];
}
return cur === undefined ? fallback : cur;
}
export async function fetchRevision() {
const res = await fetch(REV_ENDPOINT, { method: "HEAD", signal: AbortSignal.timeout(10_000) });
const rev = res.headers.get("x-of-rev");
if (!rev) throw new Error("no x-of-rev header on /api2/v2/ip response");
return rev;
}
export function extractChunkRenameMap(appJs) {
const marker = '}[e]||e)+".js"';
const idx = appJs.indexOf(marker);
if (idx === -1) throw new Error("chunk map not found in app.js");
const start = appJs.lastIndexOf("({", idx) + 1;
const literal = appJs.slice(start, idx);
const map = {};
for (const m of literal.matchAll(/(\d+):"([^"]+)"/g)) map[m[1]] = m[2];
return map;
}
export function extractInitialChunkIds(appJs) {
const m = appJs.match(/\.O\(void 0,\[([\d,]+)\]/);
if (!m) throw new Error("initial chunk list not found in app.js");
return m[1].split(",").filter(Boolean);
}
export function extractModuleSource(chunkText, moduleId) {
const key = `${moduleId}:function(`;
const start = chunkText.indexOf(key);
if (start === -1) return null;
const fnStart = start + moduleId.length + 1;
const bodyStart = chunkText.indexOf("{", fnStart);
let depth = 0, inStr = null, esc = false;
for (let i = bodyStart; i < chunkText.length; i++) {
const ch = chunkText[i];
if (esc) { esc = false; continue; }
if (inStr) {
if (ch === "\\") esc = true;
else if (ch === inStr) inStr = null;
continue;
}
if (ch === '"' || ch === "'" || ch === "`") { inStr = ch; continue; }
if (ch === "{") depth++;
else if (ch === "}") {
depth--;
if (depth === 0) return chunkText.slice(fnStart, i + 1);
}
}
return null;
}
function moduleIdBefore(chunkText, markerIndex) {
const re = /(\d+):function\(/g;
let last = null, m;
while ((m = re.exec(chunkText)) && m.index < markerIndex) last = m;
return last ? last[1] : null;
}
function makeRequire(table) {
const cache = {};
const req = (id) => {
if (cache[id]) return cache[id].exports;
const fn = table[id];
if (!fn) throw new Error("missing module " + id);
const mod = { exports: {} };
cache[id] = mod;
fn.call(mod.exports, mod, mod.exports, req);
return mod.exports;
};
req.d = (exports, definition) => {
for (const key in definition)
if (!Object.prototype.hasOwnProperty.call(exports, key) &&
Object.prototype.hasOwnProperty.call(definition, key))
Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
};
req.n = (module) => {
const getter = module && module.__esModule ? () => module.default : () => module;
req.d(getter, { a: getter });
return getter;
};
req.o = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop);
req.r = (exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
};
return req;
}
function makeUniversalDep(userIdHolder) {
const dep = function (a, b, c) {
if (b === undefined) return sha1hex(String(a));
return pathGet(a, b, c);
};
dep.A = {
get getters() { return { "auth/authUserId": userIdHolder.value }; },
};
return dep;
}
import signerFactoryDefault from "./signer-module.js";
async function registerSigner(table, signerModuleId, signerSource, userIdHolder) {
const t = { ...table };
const header = signerSource.slice(0, 800);
for (const m of header.matchAll(/([A-Za-z_$][\w$]*)=t\((\d+)\)/g)) {
const id = m[2];
t[id] = (module) => { module.exports = makeUniversalDep(userIdHolder); };
}
t[signerModuleId] = signerFactoryDefault;
return t;
}
const bundleCache = new Map(); // rev -> {appJs, chunks: Map}
async function cachedFetch(rev, name, url) {
let entry = bundleCache.get(rev);
if (!entry) { entry = { chunks: new Map() }; bundleCache.set(rev, entry); }
if (name === "app.js") {
if (!entry.appJs) entry.appJs = await (await fetch(url, { signal: AbortSignal.timeout(60_000) })).text();
return entry.appJs;
}
if (!entry.chunks.has(name)) {
entry.chunks.set(name, await (await fetch(url, { signal: AbortSignal.timeout(60_000) })).text());
}
return entry.chunks.get(name);
}
/** Build the live signer: { revision, appToken, sign(urlPath, userId) }. */
export async function loadLiveSigner(log = () => {}) {
if (typeof globalThis.window === "undefined") globalThis.window = globalThis;
const rev = await fetchRevision();
log(`bundle revision: ${rev}`);
const appJs = await cachedFetch(rev, "app.js", `${BUNDLE_ROOT}/${rev}/app.js`);
const renameMap = extractChunkRenameMap(appJs);
const initialIds = extractInitialChunkIds(appJs);
log(`initial chunks: ${initialIds.length}`);
const userIdHolder = { value: "0" };
for (const id of initialIds) {
const name = renameMap[id] ?? id;
let text;
try {
text = await cachedFetch(rev, `${name}.js`, `${BUNDLE_ROOT}/${rev}/${name}.js`);
} catch { continue; }
const markerIdx = text.indexOf(RC4_ALPHABET);
if (markerIdx === -1) continue;
const moduleId = moduleIdBefore(text, markerIdx);
if (!moduleId) continue;
const source = extractModuleSource(text, moduleId);
if (!source || !/\.A\s*=/.test(source)) continue;
try {
const table = await registerSigner({}, moduleId, source, userIdHolder);
const signer = makeRequire(table)(moduleId);
if (typeof signer.A !== "function") continue;
userIdHolder.value = "0";
const probe = signer.A({ url: "/api2/v2/users/me" });
if (!probe || typeof probe.sign !== "string" || probe.sign.split(":").length < 3 || !probe.time) continue;
log(`signer module ${moduleId} active from chunk ${name}.js`);
return {
mode: "bundle",
revision: rev,
appToken: APP_TOKEN,
sign(urlPath, userId) {
userIdHolder.value = String(userId ?? "0");
const out = signer.A({ url: urlPath });
return { sign: out.sign, time: String(out.time) };
},
};
} catch (err) {
log(`candidate chunk ${name}.js failed: ${err.message}`);
}
}
throw new Error("signer module not found in any initial chunk");
}

220
ext/lib/wv.js Normal file
View File

@@ -0,0 +1,220 @@
// Widevine L3 DRM core for the browser (WebCrypto port of ofsaver's src/drm).
// Same protocol as ofsaver: classic device blob, PSS-SHA1 challenge signature,
// CMAC key derivation, AES-CBC key unwrap, HMAC license verify.
import { CLIENT_BLOB_B64, PRIVATE_KEY_DER_B64 } from "./device.js";
import { pbMsg, pbBytes, pbVarint, pbString, tryParse, get, getAll } from "./pb.js";
// ---- crypto helpers ----------------------------------------------------
const b64ToBytes = (b64) => {
const bin = atob(b64);
const out = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
return out;
};
const bytesToB64 = (bytes) => {
let s = "";
for (const b of bytes) s += String.fromCharCode(b);
return btoa(s);
};
let signKeyPromise = null, decKeyPromise = null;
function rsaSignKey() {
if (!signKeyPromise) {
signKeyPromise = crypto.subtle.importKey(
"pkcs8", b64ToBytes(PRIVATE_KEY_DER_B64),
{ name: "RSA-PSS", hash: "SHA-1" }, false, ["sign"]
);
}
return signKeyPromise;
}
function rsaDecKey() {
if (!decKeyPromise) {
decKeyPromise = crypto.subtle.importKey(
"pkcs8", b64ToBytes(PRIVATE_KEY_DER_B64),
{ name: "RSA-OAEP", hash: "SHA-1" }, false, ["decrypt"]
);
}
return decKeyPromise;
}
/** Widevine device signature: RSA-PSS SHA-1, salt length = 20. */
export async function signDevice(data) {
const key = await rsaSignKey();
return new Uint8Array(await crypto.subtle.sign({ name: "RSA-PSS", saltLength: 20 }, key, data));
}
/** sessionKey = RSA-OAEP-SHA1 unwrap of SignedLicense.SessionKey (f4). */
async function unwrapSessionKey(wrapped) {
const key = await rsaDecKey();
const buf = await crypto.subtle.decrypt({ name: "RSA-OAEP" }, key, wrapped);
return new Uint8Array(buf);
}
/** AES single block encrypt via CBC with zero IV (== ECB for one block). */
async function aesEncBlock(keyBytes, block) {
const key = await crypto.subtle.importKey("raw", keyBytes, "AES-CBC", false, ["encrypt"]);
const buf = await crypto.subtle.encrypt(
{ name: "AES-CBC", iv: new Uint8Array(16) }, key, block
);
return new Uint8Array(buf.slice(0, 16));
}
/** AES-CMAC (NIST SP 800-38B) — faithful port of ofsaver's validated cmac.js. */
export async function aesCmac(keyBytes, data) {
const blockSize = 16;
const l = await aesEncBlock(keyBytes, new Uint8Array(16));
const RB = new Uint8Array(16);
RB[15] = 0x87; // Rb constant occupies the LAST byte of the block
let k1 = shiftLeft(l);
if (l[0] & 0x80) k1 = xor(k1, RB);
let k2 = shiftLeft(k1);
if (k1[0] & 0x80) k2 = xor(k2, RB);
const lastComplete = data.length > 0 && data.length % blockSize === 0;
// main loop processes only the complete blocks BEFORE the last block
const nonZeroLen = lastComplete ? data.length - blockSize : Math.floor(data.length / blockSize) * blockSize;
let x = new Uint8Array(16);
for (let i = 0; i < nonZeroLen; i += blockSize) {
// X_i = AES_K(X_{i-1} XOR M_i) — XOR happens before encryption
x = await aesEncBlock(keyBytes, xor(x, data.slice(i, i + blockSize)));
}
let last = data.slice(nonZeroLen);
if (last.length < blockSize || !lastComplete) {
const padded = new Uint8Array(16);
padded.set(last, 0);
padded[last.length] = 0x80;
last = xor(padded, k2);
} else {
last = xor(new Uint8Array(last), k1);
}
return aesEncBlock(keyBytes, xor(last, x));
}
function shiftLeft(b) {
const out = new Uint8Array(b.length);
let carry = 0;
for (let i = b.length - 1; i >= 0; i--) {
out[i] = ((b[i] << 1) | carry) & 0xff;
carry = b[i] >> 7;
}
return out;
}
function xor(a, b) {
const out = new Uint8Array(a.length);
for (let i = 0; i < a.length; i++) out[i] = a[i] ^ b[i];
return out;
}
/** key = AES-CBC-PKCS7(container.Key, Enc, container.Iv) */
async function aesCbcDecrypt(keyBytes, iv, data) {
const key = await crypto.subtle.importKey("raw", keyBytes, "AES-CBC", false, ["decrypt"]);
const buf = await crypto.subtle.decrypt({ name: "AES-CBC", iv }, key, data);
return new Uint8Array(buf);
}
async function hmacSha256(keyBytes, data) {
const key = await crypto.subtle.importKey("raw", keyBytes, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
return new Uint8Array(await crypto.subtle.sign("HMAC", key, data));
}
// ---- challenge ---------------------------------------------------------
const CLIENT_INFO_B64 = null; // blob carries its own client_info
/** The classic blob IS the ClientIdentification (cert chain pre-signed by
* Google's L3 intermediate) — used verbatim, same as ofsaver. */
export function clientIdentification() {
return b64ToBytes(CLIENT_BLOB_B64);
}
/** ContentIdentification embedding the media's own widevine pssh payload. */
export function buildContentIdentification(psshPayload, requestId) {
return pbMsg(pbBytes(1, pbMsg(pbBytes(1, psshPayload), pbVarint(2, 1), pbString(3, requestId))));
}
/** SignedRequest for LICENSE_REQUEST (same layout as the verified ofsaver one). */
export async function buildChallenge(psshPayload) {
const requestId = [...crypto.getRandomValues(new Uint8Array(16))]
.map((b) => b.toString(16).padStart(2, "0")).join("").toUpperCase();
const licenseRequest = pbMsg(
pbBytes(1, clientIdentification()),
pbBytes(2, buildContentIdentification(psshPayload, requestId)),
pbVarint(3, 1), // NEW
pbVarint(4, Math.floor(Date.now() / 1000)),
pbVarint(6, 21),
pbVarint(7, new Uint32Array(crypto.getRandomValues(new Uint8Array(4)).buffer)[0]) // key_control_nonce
);
const sig = await signDevice(licenseRequest);
return pbMsg(pbVarint(1, 1), pbBytes(2, licenseRequest), pbBytes(3, sig));
}
// ---- license processing ------------------------------------------------
/** Full license processing (identical to ofsaver's verified processLicense). */
export async function processLicense(licenseBuf, challengeLicenseRequestBytes) {
const msg = new Uint8Array(get(licenseBuf, 2));
const sessionKeyWrapped = new Uint8Array(get(licenseBuf, 4));
const signature = new Uint8Array(get(licenseBuf, 3));
const sessionKey = await unwrapSessionKey(sessionKeyWrapped);
if (sessionKey.length !== 16) throw new Error(`session key ${sessionKey.length}B, expected 16`);
const encKeyBase = Uint8Array.from([
...new TextEncoder().encode("ENCRYPTION"), 0,
...challengeLicenseRequestBytes, 0, 0, 0, 0x80,
]);
const authKeyBase = Uint8Array.from([
...new TextEncoder().encode("AUTHENTICATION"), 0,
...challengeLicenseRequestBytes, 0, 0, 2, 0,
]);
const encKey = await aesCmac(sessionKey, Uint8Array.from([1, ...encKeyBase]));
const auth1 = Uint8Array.from([
...(await aesCmac(sessionKey, Uint8Array.from([1, ...authKeyBase]))),
...(await aesCmac(sessionKey, Uint8Array.from([2, ...authKeyBase]))),
]);
const hmac = await hmacSha256(auth1, msg);
const signatureOk = hmac.every((b, i) => b === signature[i]);
const keys = [];
for (const container of getAll(msg, 3)) {
const id = get(container, 1);
const iv = get(container, 2);
const wrapped = get(container, 3);
const type = Number(get(container, 4) ?? 0);
if (type === 1 /* SIGNING */ || !wrapped || !iv) continue;
const key = await aesCbcDecrypt(encKey, iv, wrapped);
keys.push({
kidHex: id ? [...new Uint8Array(id)].map((b) => b.toString(16).padStart(2, "0")).join("") : null,
keyHex: [...key].map((b) => b.toString(16).padStart(2, "0")).join(""),
type,
});
}
return { keys, sessionKeyHex: [...sessionKey].map((b) => b.toString(16).padStart(2, "0")).join(""), signatureOk };
}
// ---- MPD helpers -------------------------------------------------------
/** Extract the widevine PSSH payload from an MPD (systemId edef8ba9-…). */
export function widevinePsshFromMpd(mpdText) {
const re = /<cenc:pssh[^>]*>([^<]+)<\/cenc:pssh>/g;
let m;
while ((m = re.exec(mpdText))) {
const box = b64ToBytes(m[1]);
const hex = [...box.slice(12, 28)].map((b) => b.toString(16).padStart(2, "0")).join("");
if (hex.startsWith("edef8ba9")) {
const dataSize = (box[28] << 24) | (box[29] << 16) | (box[30] << 8) | box[31];
return box.slice(32, 32 + dataSize);
}
}
return null;
}
/** KID from the MPD's cenc:default_KID. */
export function kidFromMpd(mpdText) {
const m = /cenc:default_KID="([0-9a-fA-F-]{36})"/.exec(mpdText);
return m ? m[1] : null;
}

50
ext/manifest.json Normal file
View File

@@ -0,0 +1,50 @@
{
"manifest_version": 3,
"name": "ofsaver",
"description": "Personal OnlyFans downloader \u2014 DRM (widevine) + plain media",
"version": "0.5.14",
"minimum_chrome_version": "116",
"permissions": [
"offscreen",
"downloads",
"storage",
"cookies",
"scripting"
],
"host_permissions": [
"https://onlyfans.com/*",
"https://*.onlyfans.com/*"
],
"background": {
"service_worker": "background.js",
"type": "module"
},
"action": {
"default_title": "ofsaver"
},
"content_scripts": [
{
"matches": [
"https://onlyfans.com/*"
],
"js": [
"lib/main-hook.js"
],
"run_at": "document_start",
"world": "MAIN"
},
{
"matches": [
"https://onlyfans.com/*"
],
"js": [
"content.js"
],
"run_at": "document_idle"
}
],
"content_security_policy": {
"extension_pages": "script-src 'self' 'wasm-unsafe-eval'; object-src 'self'"
},
"options_page": "options.html"
}

7
ext/offscreen.html Normal file
View File

@@ -0,0 +1,7 @@
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"></head>
<body>
<script type="module" src="offscreen.js"></script>
</body>
</html>

495
ext/offscreen.js Normal file
View File

@@ -0,0 +1,495 @@
// Offscreen document: hosts the live OF signer (needs eval) and runs the
// whole DRM pipeline. The SW relays messages here.
import { loadLiveSigner } from "./lib/signer.js";
import { buildPath } from "./lib/paths.js";
import {
holdsDir, streamIntoHold, holdFileUrl, removeHolds,
decryptTrackToOpfs, pushTrackMoofs, writeMuxedFile, drmCapture,
} from "./lib/holds.js";
function toUnixSeconds(d) {
if (d == null) return null;
if (typeof d === "number") return d > 1e12 ? Math.floor(d / 1000) : Math.floor(d);
const parsed = Date.parse(d);
return Number.isNaN(parsed) ? null : Math.floor(parsed / 1000);
}
import {
buildChallenge, processLicense, widevinePsshFromMpd, kidFromMpd,
} from "./lib/wv.js";
import { tryParse } from "./lib/pb.js";
const log = [];
const say = (m) => {
log.push(m);
if (log.length > 120) log.splice(0, log.length - 120); // cap: bundles log a lot
console.log("[ofsaver]", m);
};
const b64ToBytes = (b64) => Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
const bytesToB64 = (bytes) => {
let s = "";
for (const b of bytes) s += String.fromCharCode(b);
return btoa(s);
};
let signerPromise = null;
function getSigner() {
if (!signerPromise) {
signerPromise = loadLiveSigner(say).catch((err) => {
signerPromise = null;
throw err;
});
}
return signerPromise;
}
/** The logged-in account id from the browser cookie jar. */
async function authUserId() {
try {
const c = await chrome.cookies.get({ url: "https://onlyfans.com", name: "auth_id" });
return c?.value ?? "0";
} catch { return "0"; }
}
/** Signed headers for an OF API call (same shape as ofsaver's OfApi). */
let cachedUserId = null;
function setUserId(id) { if (id) cachedUserId = String(id); }
let activeSigner = null;
async function signedHeaders(pathWithQuery, method = "GET", hasBody = false) {
const signer = await getSigner();
activeSigner = signer;
const userId = cachedUserId ?? "0";
const { sign, time } = signer.sign(pathWithQuery, userId);
const headers = {
accept: "application/json, text/plain, */*",
"app-token": signer.appToken,
"user-id": userId,
referer: "https://onlyfans.com/",
"user-agent": navigator.userAgent,
sign,
time,
"x-of-rev": signer.revision,
};
if (hasBody) headers["content-type"] = "application/json";
return headers;
}
const CANON = {
"CloudFront-Policy": "Policy",
"CloudFront-Signature": "Signature",
"CloudFront-Key-Pair-Id": "Key-Pair-Id",
};
function signedCdnUrl(rawUrl, sig) {
const url = new URL(rawUrl);
for (const [k, v] of Object.entries(sig ?? {})) {
const name = CANON[k] ?? k;
url.searchParams.delete(k);
url.searchParams.set(name, v);
}
return url.toString();
}
/** Plain-media download URL from a crawled media object. */
function plainDownload(mediaItem) {
const files = mediaItem.files ?? {};
const type = mediaItem.type;
if (type === "video" || type === "audio") {
const url = files.source?.url ?? files.full?.url ?? null;
return url ? { url, ext: "mp4" } : null;
}
if (type === "photo" || type === "gif") {
const url = files.full?.url ?? files.preview?.url ?? null;
return url ? { url, ext: type === "gif" ? "gif" : "jpg" } : null;
}
return null;
}
/** Creator bundle: resolve, crawl timeline, license DRM videos, list downloads. */
async function runBundle(who, max = 200) {
const t0 = Date.now();
const uPath = `/api2/v2/users/${encodeURIComponent(String(who).replace(/^@/, ""))}`;
let headers;
try { headers = await signedHeaders(uPath); }
catch (e) { headers = { referer: "https://onlyfans.com/" }; }
const uRes = await fetch(`https://onlyfans.com${uPath}`, { credentials: "include", headers });
if (!uRes.ok) throw new Error(`user HTTP ${uRes.status}`);
const user = await uRes.json();
say(`bundle: ${user.username} (${user.id})`);
const mediaItems = []; // {media, postId, responseType}
let cursor = "";
for (let page = 0; page < 40 && mediaItems.length < max; page++) {
let path = `/api2/v2/users/${user.id}/posts/medias?limit=50&order=publish_date_desc&skip_users=all&format=infinite&counters=1`;
if (cursor) path += `&beforePublishTime=${encodeURIComponent(cursor)}`;
let h;
try { h = await signedHeaders(path); } catch { h = { referer: "https://onlyfans.com/" }; }
const res = await fetch(`https://onlyfans.com${path}`, { credentials: "include", headers: h });
if (!res.ok) throw new Error(`timeline HTTP ${res.status}`);
const data = await res.json();
const list = Array.isArray(data) ? data : data?.list ?? [];
if (!list.length) break;
for (const post of list) {
for (const m of post.media ?? []) {
mediaItems.push({ media: m, postId: post.id, responseType: post.responseType });
}
}
say(` page ${page + 1}: +${list.length} posts (total media ${mediaItems.length})`);
if (data?.hasMore !== true) break;
cursor = data?.tailMarker ?? list[list.length - 1]?.postedAtPrecise ?? "";
if (!cursor) break;
await new Promise((r) => setTimeout(r, 400 + Math.floor(Math.random() * 400)));
}
const downloads = [];
const keys = [];
let licensed = 0;
for (const item of mediaItems.slice(0, max)) {
const m = item.media;
if (m.files?.drm?.manifest) {
try {
const r = await runDrm({
id: m.id,
postId: item.postId,
responseType: item.responseType === "message" ? "message" : "post",
drm: m.files.drm,
});
keys.push({ mediaId: m.id, kid: r.summary.kid, key: r.summary.key });
savedIds.push(m.id);
licensed++;
for (const rep of r.summary.reps) {
downloads.push({
url: rep.url,
filename: buildPath({
scheme: msg.naming?.bulkScheme ?? "creator-section-type",
bulk: true,
creator: user.username,
type: m.type,
section: "Timeline",
date: m.createdAt ?? item.post?.postedAt ?? null,
timestamp: toUnixSeconds(m.createdAt ?? item.post?.postedAt),
mediaId: m.id,
postId: item.postId,
quality: "source", // bundle takes the best rep = original
ext: "mp4",
template: msg.naming?.nameTemplate,
}),
});
}
await new Promise((r2) => setTimeout(r2, 300));
} catch (e) {
say(` media ${m.id}: ${e.message}`);
}
} else {
const d = plainDownload(m);
if (d && m.canView !== false) {
savedIds.push(m.id);
downloads.push({
url: d.url,
filename: buildPath({
scheme: msg.naming?.bulkScheme ?? "creator-section-type",
bulk: true,
creator: user.username,
type: m.type,
section: "Timeline",
date: m.createdAt ?? item.post?.postedAt ?? null,
timestamp: toUnixSeconds(m.createdAt ?? item.post?.postedAt),
mediaId: m.id,
postId: item.postId,
ext: d.ext,
template: msg.naming?.nameTemplate,
}),
});
}
}
}
say(`bundle done: ${downloads.length} downloads, ${licensed} licensed (${Date.now() - t0}ms)`);
return { ok: true, summary: { count: downloads.length, downloads, keys, savedIds, user: user.username, ms: Date.now() - t0 } };
}
/** Phase 1: fetch MPD, build challenge + signed headers. */
async function prepareLicense(media) {
const { manifest, signature } = media.drm;
const mpdUrl = signedCdnUrl(manifest.dash, signature?.dash);
say(`MPD: ${mpdUrl.slice(0, 100)}`);
const mpdRes = await fetch(mpdUrl, {
credentials: "include",
headers: { referer: "https://onlyfans.com/", origin: "https://onlyfans.com" },
});
if (!mpdRes.ok) {
const body = (await mpdRes.text().catch(() => "")).replace(/\s+/g, " ").slice(0, 110);
throw new Error(`MPD HTTP ${mpdRes.status} ${mpdUrl.split("?")[0].slice(-40)} :: ${body}`);
}
const mpd = await mpdRes.text();
say(`MPD ${mpd.length}B`);
const psshPayload = widevinePsshFromMpd(mpd);
const kid = kidFromMpd(mpd);
if (!psshPayload) throw new Error("no widevine pssh in MPD");
say(`KID ${kid} · pssh ${psshPayload.length}B`);
const challenge = await buildChallenge(psshPayload);
const licenseRequest = new Uint8Array(tryParse(challenge).find(([f]) => f === 2)[2]);
const responseType = media.responseType === "message" ? "message" : "post";
const licensePath =
`/api2/v2/users/media/${media.id}/drm/${responseType}/${media.postId}?type=widevine`;
const headers = await signedHeaders(licensePath, "POST", true);
headers["content-type"] = "application/octet-stream";
// match the captured relay exactly: accept: application/json,
// x-bc header (fp cookie), no user-agent/referer (the page adds its own)
headers["accept"] = "application/json";
headers["x-bc"] = media.xBc ?? headers["x-bc"] ?? "";
delete headers["user-agent"];
say(`challenge ${challenge.length}B ready — relaying through page`);
return {
ok: true,
phase: "prepare",
diag: { uid: cachedUserId ?? "none", bcLen: String(media.xBc ?? "").length, rev: activeSigner?.revision ?? "?" },
mpd, kid, mpdUrl,
licensePath,
challengeB64: bytesToB64(challenge),
licenseRequestB64: bytesToB64(licenseRequest),
headers,
};
}
/** Phase 2: process the license the page fetched for us. */
async function finishLicense(msg) {
const licenseBuf = b64ToBytes(msg.licenseB64);
const licenseRequest = b64ToBytes(msg.licenseRequestB64);
const { keys, signatureOk, sessionKeyHex } = await processLicense(licenseBuf, licenseRequest);
say(`license HMAC ok: ${signatureOk}; keys: ${keys.length}`);
const contentKey = keys.find((k) => k.type === 2);
if (!contentKey) throw new Error("no content key in license");
const mpd = msg.mpd;
const mpdUrl = msg.mpdUrl;
const reps = [];
const sets = [...mpd.matchAll(/<AdaptationSet[\s\S]*?<\/AdaptationSet>/g)];
for (const set of sets) {
const kind = /video\/mp4/.test(set[0]) ? "video" : "audio";
let best = null;
for (const m of set[0].matchAll(/<Representation[^>]*bandwidth="(\d+)"[\s\S]*?<\/Representation>/g)) {
const bw = Number(m[1]);
if (!best || bw > best.bw) best = { bw, body: m[0] };
}
if (!best) continue;
const file = /<BaseURL>([^<]+)<\/BaseURL>/.exec(best.body)?.[1];
if (file) {
const dir = mpdUrl.slice(0, mpdUrl.lastIndexOf("/") + 1);
// the CloudFront signature lives in the MPD's query — carry it onto
// each representation file (they're under the same signed wildcard)
const query = mpdUrl.slice(mpdUrl.indexOf("?"));
const rHeight = /\sheight="(\d+)"/.exec(best.body)?.[1] ?? null;
const rWidth = /\swidth="(\d+)"/.exec(best.body)?.[1] ?? null;
reps.push({ kind, bandwidth: best.bw, height: rHeight ? Number(rHeight) : null, width: rWidth ? Number(rWidth) : null, url: dir + file + query });
}
}
say(`reps: ${reps.map((r) => r.kind).join("+")}`);
return {
ok: true,
summary: {
kid: contentKey.kidHex,
key: contentKey.keyHex,
sessionKeyHex,
signatureOk,
mpdUrl,
reps,
},
};
}
chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
if (msg.op === "lastLog") {
// synchronous probe: names the stage an item hung on (or proves the doc's
// event loop is blocked, when even this never answers)
sendResponse({ ok: true, line: log[log.length - 1] ?? "" });
return;
}
if (msg.op === "prepareLicense") {
setUserId(msg.userId);
prepareLicense(msg.media)
.then((r) => sendResponse({ ...r, log }))
.catch((err) => sendResponse({ ok: false, error: String(err.message ?? err), log }));
return true;
}
if (msg.op === "finishLicense") {
finishLicense(msg)
.then((r) => sendResponse({ ...r, log }))
.catch((err) => sendResponse({ ok: false, error: String(err.message ?? err), log }));
return true;
}
if (msg.op === "fetchAndHold") {
// fetch files in the offscreen (extension origin + host permissions work
// here), streaming each straight into OPFS so even multi-GB files never
// sit in RAM. Returns blob URLs (disk-backed) + hold ids.
(async () => {
try {
const dir = await holdsDir();
const held = [];
const mimeFor = (fn) => {
const ext2 = (fn.split(".").pop() ?? "").toLowerCase();
return { jpg: "image/jpeg", jpeg: "image/jpeg", png: "image/png", gif: "image/gif", mp4: "video/mp4", webm: "video/webm" }[ext2] ?? "application/octet-stream";
};
let total = 0, got = 0, last = 0;
const report = () => {
if (!msg.tabId || !total) return;
const now = Date.now();
if (now - last < 250 && got < total) return;
last = now;
chrome.runtime.sendMessage({ op: "dlProgress", tabId: msg.tabId, id: msg.dlId, pct: Math.min(80, Math.round((got / total) * 80)) }).catch(() => {});
};
for (const f of msg.files ?? []) {
const res = await fetch(f.url, { credentials: "include", headers: { referer: "https://onlyfans.com/" } });
if (!res.ok) { held.push({ filename: f.filename, ok: false, error: "HTTP " + res.status }); continue; }
total += Number(res.headers.get("content-length") || 0);
const { id, size } = await streamIntoHold(dir, res, (n) => { got += n; report(); });
held.push({ id, filename: f.filename, ok: true, size, blobUrl: await holdFileUrl(dir, id, mimeFor(f.filename)) });
}
sendResponse({ ok: true, held });
} catch (e) {
sendResponse({ ok: false, error: String(e.message ?? e) });
}
})();
return true;
}
if (msg.op === "refreshDrm") {
// DRM manifest signatures are short-lived — re-fetch the owning post
// with a signed request and return the media's fresh drm object
setUserId(msg.userId);
(async () => {
try {
const path = `/api2/v2/post/${msg.postId}?userId=${cachedUserId ?? "0"}`;
const headers = await signedHeaders(path);
const res = await fetch(`https://onlyfans.com${path}`, { credentials: "include", headers });
if (!res.ok) { sendResponse({ ok: false, error: "HTTP " + res.status }); return; }
const data = await res.json();
let fresh = null;
const walk = (x) => {
if (!x || typeof x !== "object" || fresh) return;
if (Array.isArray(x)) { for (const v of x) walk(v); return; }
if (String(x.id) === String(msg.mediaId) && x.files?.drm) { fresh = x; return; }
for (const k of Object.keys(x)) walk(x[k]);
};
walk(data);
sendResponse({ ok: true, media: fresh });
} catch (e) {
sendResponse({ ok: false, error: String(e.message ?? e) });
}
})();
return true;
}
if (msg.op === "getCapture") {
const jsonB64 = globalThis.__ofsaverCapB64 ?? null;
globalThis.__ofsaverCapB64 = null;
sendResponse({ ok: true, jsonB64 });
return;
}
if (msg.op === "revokeUrls") {
for (const u of msg.urls ?? []) { try { URL.revokeObjectURL(u); } catch {} }
sendResponse({ ok: true });
return;
}
if (msg.op === "dropHeld") {
// remove held/decrypted/muxed files from OPFS once a download finished
(async () => {
try {
await removeHolds(await holdsDir(), msg.ids ?? []);
sendResponse({ ok: true });
} catch { sendResponse({ ok: true }); } // best effort
})();
return true;
}
if (msg.op === "decryptAndMux") {
// Stream the DRM flow: tracks stream from OPFS holds, decrypt fragment
// by fragment into OPFS, and the muxed mp4 is assembled on disk — RAM
// stays flat no matter the file size.
(async () => {
let dir = null;
const decVideo = "d_" + String(msg.videoId ?? "").replace(/^h_/, "");
const decAudio = msg.audioId ? "d_" + String(msg.audioId).replace(/^h_/, "") : null;
const finalName = "m_" + Math.random().toString(36).slice(2);
try {
const { initDrmWasm, decryptAndStripFragment, decryptAndStripFragmentCbcs,
stripInit, tencMarker, tencConstantIv, tencCryptPattern, MuxPlanner } =
await import(chrome.runtime.getURL("lib/owndrm.js"));
await initDrmWasm();
const keyBytes = b64ToBytes(msg.keyB64);
dir = await holdsDir();
const fns = { stripInit, tencMarker, tencCryptPattern, tencConstantIv, decryptAndStripFragment, decryptAndStripFragmentCbcs };
let last = 0;
const report = (pct) => {
if (!msg.tabId) return;
const now = Date.now();
if (now - last < 250 && pct < 99) return;
last = now;
chrome.runtime.sendMessage({ op: "dlProgress", tabId: msg.tabId, id: msg.dlId, pct }).catch(() => {});
};
const { header: vHeader } = await decryptTrackToOpfs(dir, msg.videoId, decVideo, keyBytes, fns, "video", (done, tot) => report(80 + Math.round((done / tot) * 12)));
let aHeader = null;
if (msg.audioId) aHeader = (await decryptTrackToOpfs(dir, msg.audioId, decAudio, keyBytes, fns, "audio", (done, tot) => report(92 + Math.round((done / tot) * 6)))).header;
say(`decrypted tracks: video ok${msg.audioId ? ", audio ok" : ""}`);
const planner = new MuxPlanner(vHeader, aHeader ?? undefined);
await pushTrackMoofs(dir, decVideo, planner, true);
if (msg.audioId) await pushTrackMoofs(dir, decAudio, planner, false);
const muxed = planner.finish();
const vFile = await (await dir.getFileHandle(decVideo)).getFile();
const aFile = decAudio ? await (await dir.getFileHandle(decAudio)).getFile() : null;
report(99);
const out = await writeMuxedFile(dir, finalName, muxed, vFile, aFile);
report(100);
say(`muxed final: ${out.size}B`);
await removeHolds(dir, [decVideo, ...(decAudio ? [decAudio] : [])]);
let capB64 = null;
if (!drmCapture.sent && drmCapture.frags.length) {
drmCapture.headers.mux = drmCapture.mux ? drmCapture.mux.header : null;
drmCapture.layout = drmCapture.mux ? drmCapture.mux.layout : null;
capB64 = btoa(JSON.stringify(drmCapture));
drmCapture.sent = true;
}
if (capB64) globalThis.__ofsaverCapB64 = capB64;
sendResponse({ ok: true, blobUrl: out.blobUrl, size: out.size, files: [finalName], capB64 });
} catch (e) {
if (dir) await removeHolds(dir, [decVideo, decAudio, finalName].filter(Boolean));
sendResponse({ ok: false, error: String(e.message ?? e), log });
}
})();
return true;
}
if (msg.op === "fetchPostMedia") {
// signed GET of a post's full media list (bundle backfill)
(async () => {
try {
const { postId, creatorId, username } = msg;
let id = creatorId ?? null;
if (!id && username) {
const uPath = `/api2/v2/users/${encodeURIComponent(username)}`;
let h;
try { h = await signedHeaders(uPath); } catch { h = { referer: "https://onlyfans.com/" }; }
const uRes = await fetch(`https://onlyfans.com${uPath}`, { credentials: "include", headers: h });
if (uRes.ok) id = (await uRes.json())?.id ?? null;
}
if (!id) { sendResponse({ ok: false, error: "no creator id" }); return; }
const path = `/api2/v2/post/${postId}?userId=${id}`;
let h2;
try { h2 = await signedHeaders(path); } catch { h2 = { referer: "https://onlyfans.com/" }; }
const res = await fetch(`https://onlyfans.com${path}`, { credentials: "include", headers: h2 });
if (!res.ok) { sendResponse({ ok: false, error: "post HTTP " + res.status }); return; }
sendResponse({ ok: true, data: await res.json() });
} catch (e) {
sendResponse({ ok: false, error: String(e.message ?? e) });
}
})();
return true;
}
if (msg.op === "bundle") {
setUserId(msg.userId);
runBundle(msg.who, msg.max)
.then((r) => sendResponse({ ...r, log }))
.catch((err) => sendResponse({ ok: false, error: String(err.message ?? err), log }));
return true;
}
});

218
ext/options.html Normal file
View File

@@ -0,0 +1,218 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ofsaver settings</title>
<style>
:root {
color-scheme: light dark;
--bg: #fafafa;
--surface: #ffffff;
--sunken: #f4f4f5;
--text: #18181b;
--text-2: #52525b;
--text-3: #71717a;
--line: rgba(24, 24, 27, .09);
--line-strong: rgba(24, 24, 27, .16);
--accent: #d63a3f;
--accent-hover: #c2333a;
--accent-ink: #c2333a;
--ok: #2f7d52;
--ring: rgba(214, 58, 63, .35);
--mono: ui-monospace, "SF Mono", Menlo, monospace;
--ease: cubic-bezier(.2, 0, 0, 1);
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #141416;
--surface: #1c1c1f;
--sunken: #19191c;
--text: #ededef;
--text-2: #a1a1aa;
--text-3: #7c7c85;
--line: rgba(237, 237, 239, .08);
--line-strong: rgba(237, 237, 239, .16);
--accent-ink: #f0686c;
--ok: #5fb585;
}
}
* { box-sizing: border-box; }
body {
margin: 0;
padding: 48px 24px 96px;
background: var(--bg);
color: var(--text);
font: 14px/1.5 -apple-system, system-ui, sans-serif;
-webkit-font-smoothing: antialiased;
}
.wrap { max-width: 760px; margin: 0 auto; }
svg.i { width: 16px; height: 16px; flex: none; fill: none; stroke: currentColor; stroke-width: 1.5; stroke-linecap: round; stroke-linejoin: round; }
header { margin-bottom: 40px; }
.brand { font: 500 13px var(--mono); color: var(--text-3); margin-bottom: 8px; }
h1 { font-size: 24px; line-height: 32px; font-weight: 500; margin: 0 0 4px; letter-spacing: -.01em; }
.sub { color: var(--text-2); margin: 0; }
section { padding: 32px 0; border-top: 1px solid var(--line); }
h2 { font-size: 15px; font-weight: 500; margin: 0; }
.section-sub { color: var(--text-2); font-size: 13px; margin: 4px 0 16px; }
.cards { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
.card {
position: relative;
display: grid;
grid-template-columns: 16px 1fr;
column-gap: 12px;
padding: 16px;
background: var(--surface);
border: 1px solid var(--line);
border-radius: 12px;
cursor: pointer;
text-align: left;
font: inherit;
color: inherit;
transition: border-color .15s var(--ease), background-color .15s var(--ease);
}
.card:hover { border-color: var(--line-strong); }
.card:focus-visible { outline: 2px solid var(--ring); outline-offset: 2px; }
.card.selected { border-color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); }
.radio {
width: 16px; height: 16px; margin-top: 2px;
border-radius: 8px;
border: 1px solid var(--line-strong);
transition: border-color .15s var(--ease), border-width .15s var(--ease);
}
.card.selected .radio { border: 5px solid var(--accent); }
.card .t { font-size: 14px; font-weight: 500; display: flex; align-items: baseline; gap: 8px; }
.card .rec { font-size: 12px; font-weight: 400; color: var(--text-3); }
.card .d { grid-column: 2; font-size: 13px; color: var(--text-2); margin-top: 2px; }
.card .path {
grid-column: 2;
margin-top: 12px;
font: 12px/16px var(--mono);
color: var(--text-3);
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.card .path .sep { opacity: .5; padding: 0 2px; }
.preview {
margin-top: 12px;
padding: 12px 16px;
background: var(--sunken);
border: 1px solid var(--line);
border-radius: 12px;
}
.preview .label { font-size: 12px; color: var(--text-3); margin-bottom: 8px; }
.crumbs { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 2px; font: 12px/20px var(--mono); color: var(--text-2); }
.crumb { display: inline-flex; align-items: center; gap: 6px; min-width: 0; }
.crumb svg.i { width: 14px; height: 14px; color: var(--text-3); }
.crumb.file { color: var(--text); word-break: break-all; }
.crumbs .sep { color: var(--text-3); opacity: .6; padding: 0 4px; }
input[type="text"] {
width: 100%;
height: 40px;
padding: 0 12px;
background: var(--surface);
color: var(--text);
border: 1px solid var(--line-strong);
border-radius: 8px;
font: 13px var(--mono);
transition: border-color .15s var(--ease), box-shadow .15s var(--ease);
}
input[type="text"]:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px var(--ring); }
.tokens { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; margin-top: 12px; }
.tokens .label { font-size: 12px; color: var(--text-3); margin-right: 4px; }
.tokens button {
height: 24px;
padding: 0 8px;
border: 1px solid var(--line);
border-radius: 6px;
background: var(--surface);
color: var(--text-2);
font: 12px var(--mono);
cursor: pointer;
transition: border-color .15s var(--ease), color .15s var(--ease);
}
.tokens button:hover { border-color: var(--line-strong); color: var(--text); }
.tokens button:focus-visible { outline: 2px solid var(--ring); outline-offset: 1px; }
.actions { display: flex; align-items: center; gap: 12px; padding-top: 32px; border-top: 1px solid var(--line); }
button.save {
height: 36px;
padding: 0 16px;
background: var(--accent);
color: #fff;
border: 0;
border-radius: 8px;
font: 500 14px -apple-system, system-ui, sans-serif;
cursor: pointer;
transition: background-color .15s var(--ease), transform .1s var(--ease);
}
button.save:hover { background: var(--accent-hover); }
button.save:active { transform: scale(.98); }
button.save:focus-visible { outline: 2px solid var(--ring); outline-offset: 2px; }
.toast {
display: inline-flex; align-items: center; gap: 6px;
font-size: 13px; color: var(--ok);
opacity: 0;
transition: opacity .2s var(--ease);
}
@media (max-width: 600px) {
body { padding: 32px 16px 64px; }
.cards { grid-template-columns: 1fr; }
}
</style>
</head>
<body>
<div class="wrap">
<header>
<div class="brand">ofsaver</div>
<h1>Settings</h1>
<p class="sub">Choose the folders and names for what you save. Changes apply to the next download.</p>
</header>
<section>
<h2>Single downloads</h2>
<p class="section-sub">The Download button on posts and messages</p>
<div class="cards" id="singleCards" role="radiogroup" aria-label="Single download folders"></div>
<div class="preview" id="singlePreview"></div>
</section>
<section>
<h2>Bulk downloads</h2>
<p class="section-sub">Whole profile downloads</p>
<div class="cards" id="bulkCards" role="radiogroup" aria-label="Bulk download folders"></div>
<div class="preview" id="bulkPreview"></div>
</section>
<section>
<h2>File name</h2>
<p class="section-sub">Build the name from tokens. Click one to insert it.</p>
<input type="text" id="nameTemplate" spellcheck="false" aria-label="File name pattern">
<div class="tokens" id="tokens">
<span class="label">Tokens</span>
<button type="button" data-t="{creator}">creator</button>
<button type="button" data-t="{type}">type</button>
<button type="button" data-t="{date}">date</button>
<button type="button" data-t="{timestamp}">timestamp</button>
<button type="button" data-t="{mediaId}">mediaId</button>
<button type="button" data-t="{postId}">postId</button>
<button type="button" data-t="{quality}">quality</button>
<button type="button" data-t="{ext}">ext</button>
</div>
</section>
<div class="actions">
<button class="save" id="save">Save settings</button>
<span class="toast" id="toast" role="status">
<svg class="i" viewBox="0 0 24 24"><path d="M20 6 9 17l-5-5"/></svg>Saved
</span>
</div>
</div>
<script type="module" src="options.js"></script>
</body>
</html>

107
ext/options.js Normal file
View File

@@ -0,0 +1,107 @@
// Options page: folder scheme cards + filename template with live preview.
import { SINGLE_SCHEMES, BULK_SCHEMES, buildPath } from "./lib/paths.js";
const $ = (id) => document.getElementById(id);
const DEFAULTS = {
singleScheme: "creator-type",
bulkScheme: "creator-section-type",
nameTemplate: "{creator}_{type}_{date}_{timestamp}_{mediaId}_{quality}",
};
let settings = { ...DEFAULTS };
async function load() {
const stored = await chrome.storage.local.get(Object.keys(DEFAULTS));
settings = { ...DEFAULTS, ...stored };
$("nameTemplate").value = settings.nameTemplate;
renderCards();
renderPreviews();
}
async function save() {
settings.nameTemplate = $("nameTemplate").value.trim() || DEFAULTS.nameTemplate;
await chrome.storage.local.set(settings);
const t = $("toast");
t.style.opacity = 1;
clearTimeout(save.timer);
save.timer = setTimeout(() => (t.style.opacity = 0), 1600);
}
const esc = (v) => String(v).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
const ICON_FOLDER = `<svg class="i" viewBox="0 0 24 24"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"/></svg>`;
const ICON_FILE = `<svg class="i" viewBox="0 0 24 24"><path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/></svg>`;
function cardHtml(key, def, selected) {
const folders = def.folders
? def.folders.map((f) => f.replaceAll("{creator}", "alice").replaceAll("{typeFolder}", "Videos").replaceAll("{section}", "Timeline").replaceAll("{date}", "2026-12-05"))
: ["same folders as single downloads"];
const path = ["Downloads", ...folders].map(esc).join(`<span class="sep">/</span>`);
return `<button type="button" role="radio" aria-checked="${selected}" class="card ${selected ? "selected" : ""}" data-key="${key}">
<span class="radio"></span>
<span class="t">${esc(def.label)}${def.rec ? `<span class="rec">Recommended</span>` : ""}</span>
<span class="d">${esc(def.desc)}</span>
<span class="path">${path}</span>
</button>`;
}
function renderCards() {
$("singleCards").innerHTML = Object.entries(SINGLE_SCHEMES)
.map(([k, def]) => cardHtml(k, def, settings.singleScheme === k))
.join("");
$("bulkCards").innerHTML = Object.entries(BULK_SCHEMES)
.map(([k, def]) => cardHtml(k, def, settings.bulkScheme === k))
.join("");
for (const el of $("singleCards").querySelectorAll(".card")) {
el.addEventListener("click", () => {
settings.singleScheme = el.dataset.key;
renderCards();
renderPreviews();
});
}
for (const el of $("bulkCards").querySelectorAll(".card")) {
el.addEventListener("click", () => {
settings.bulkScheme = el.dataset.key;
renderCards();
renderPreviews();
});
}
}
const SAMPLE = {
creator: "alice", type: "video", date: 1736000000, timestamp: 1796427457,
mediaId: "4812154655", postId: "2937318423", quality: "1080p", ext: "mp4",
};
function crumbsHtml(path) {
const parts = ["Downloads", ...String(path).split("/").filter(Boolean)];
return parts
.map((p, i) => {
const last = i === parts.length - 1;
return `<span class="crumb${last ? " file" : ""}">${last ? ICON_FILE : ICON_FOLDER}${esc(p)}</span>`;
})
.join(`<span class="sep">/</span>`);
}
function renderPreviews() {
const one = buildPath({ ...SAMPLE, scheme: settings.singleScheme, bulk: false, template: $("nameTemplate").value });
const bulk = buildPath({ ...SAMPLE, scheme: settings.bulkScheme, bulk: true, singleScheme: settings.singleScheme, section: "Timeline", template: $("nameTemplate").value });
$("singlePreview").innerHTML = `<div class="label">Next download</div><div class="crumbs">${crumbsHtml(one)}</div>`;
$("bulkPreview").innerHTML = `<div class="label">Next bulk download</div><div class="crumbs">${crumbsHtml(bulk)}</div>`;
}
for (const b of $("tokens").querySelectorAll("button[data-t]")) {
b.addEventListener("click", () => {
const input = $("nameTemplate");
const start = input.selectionStart ?? input.value.length;
const end = input.selectionEnd ?? start;
input.setRangeText(b.dataset.t, start, end, "end");
input.focus();
renderPreviews();
});
}
$("nameTemplate").addEventListener("input", renderPreviews);
$("save").addEventListener("click", save);
load();