Files
ofsaver/ext/background.js
collector 53d31572a1 init
2026-12-06 12:41:22 +01:00

418 lines
16 KiB
JavaScript

// 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);