Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
1673 lines (1557 loc) · 61.2 KB
/
Copy pathbackground.js
File metadata and controls
1673 lines (1557 loc) · 61.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Grab browser extension (MV3) — service worker.
//
// Three jobs:
// 1. Automatic interception: browser downloads are cancelled and POSTed to
// the Grab desktop app's local HTTP endpoint.
// 2. Explicit sends: context menu and keyboard shortcut send the current
// tab or a link/media URL to Grab through the grab: URI scheme
// (registered by the app's .desktop entry as x-scheme-handler/grab).
// The toolbar button opens the options page instead.
// 3. Video detection: <video> elements reported by the content script plus
// stream manifests sniffed via webRequest are offered in the right-click
// menu as "Download video with Grab", FDM-style.
//
// All listeners are registered synchronously at the top level: the worker is
// ephemeral and Chrome only wakes it for events it registered for on startup.
// shared.js loads via importScripts in the Chrome MV3 service worker.
// Firefox lists it as a background script before this file, so the
// globals already exist there (importScripts only exists in workers).
if (
typeof SHARED_DEFAULTS === "undefined" &&
typeof importScripts === "function"
) {
importScripts("shared.js");
}
const GRAB_SCHEME = "grab://";
// Browser startup time (Varia pattern): chrome.downloads.onCreated can re-fire
// on startup for downloads from a previous session. Anything with a startTime
// older than this is ignored so a cancelled download doesn't re-prompt on
// every browser launch. Kept in session storage, not a variable: the worker
// restarts whenever it idles, and a per-worker timestamp would postdate the
// startTime of the very download that woke it.
chrome.runtime.onStartup.addListener(() => {
chrome.storage.session.set({ browserStartTime: Date.now() });
});
// Shared defaults live in shared.js (importScripts'd above).
/// Wrap an http(s) URL for the Grab desktop app. Anything else (blob:, data:,
/// file:, …) cannot be handed off and returns null. The original scheme is
/// carried as the first path segment (grab://https/host/...) so Grab can
/// restore http vs https; needs Grab 4.7.1+.
function toGrabUrl(url) {
if (typeof url !== "string") return null;
const m = /^(https?):\/\/(.+)$/i.exec(url);
if (!m) return null;
// user:pass@host: Grab refuses credentials in links, and the grab: URL
// passes through argv (xdg-open), which other local users can read.
// The WHATWG parser handles the edge cases (tab/newline stripping, etc.).
let u;
try {
u = new URL(url);
} catch {
return null;
}
if (u.username || u.password) return null;
return `${GRAB_SCHEME}${m[1].toLowerCase()}/${m[2]}`;
}
/// Explicit user action (keyboard shortcut, context menu):
/// navigate the active tab to the grab: URL. The user acted on this tab, and
/// external-protocol navigations are handed to the OS without replacing the
/// page (the mailto: mechanism), so the tab is left alone. Never use this for
/// automatic interception: the download can come from any tab, or none.
function sendToGrab(url, tabId) {
const grabUrl = toGrabUrl(url);
if (!grabUrl) return;
// Name the tab the user acted on; without an id the browser picks the
// "current window", which is the wrong one when several are open.
updateTab(tabId, grabUrl);
}
/// Navigate `tabId` to `url`, falling back to the current window's active tab
/// when there is no real tab (TAB_ID_NONE is -1: devtools and similar). A tab
/// that closed in the meantime rejects the promise; nothing to recover.
function updateTab(tabId, url) {
const r =
tabId != null && tabId >= 0
? chrome.tabs.update(tabId, { url })
: chrome.tabs.update({ url });
if (r && typeof r.catch === "function") r.catch(() => {});
}
/// Grab's local HTTP server. The extension POSTs URLs here instead of using
/// native messaging — no host manifest, no extension IDs, works from Flatpak.
const GRAB_BASE_URL = "http://127.0.0.1:9412";
const GRAB_HTTP_URL = `${GRAB_BASE_URL}/add`;
/// Delays before retrying when Grab answers 429 (its handoff queue is full).
const HANDOFF_RETRY_DELAYS_MS = [300, 900];
/// Grab holds a `?confirm=1` request until the user answers its dialog (it
/// gives up after 120 s); wait a little longer than that.
const CONFIRM_TIMEOUT_MS = 130_000;
/// A pairing handshake is a loopback round trip.
const HELLO_TIMEOUT_MS = 3_000;
/// Grab rejects handoffs with more than 100 cookies or a JSON body over
/// 32 KiB. Stay under both so a cookie-heavy site still hands off: dropping
/// cookies beats losing the URL. 30 KiB leaves ~2 KiB under the cap; the
/// measured body already includes the URL and UA.
const MAX_HANDOFF_COOKIES = 100;
const MAX_HANDOFF_BODY_BYTES = 30 * 1024;
let sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// Test hook: swap the sleep implementation to observe retry delays.
function _setSleep(fn) {
sleep = fn;
}
// --- Pairing ---------------------------------------------------------------
//
// Any local process can listen on 127.0.0.1:9412 before Grab does. Once the
// user has pasted Grab's pairing code into the options page, the extension
// 1. makes Grab prove it knows the code (GET /hello) before anything else,
// 2. only then sends the page's cookies, and
// 3. signs the request body, so Grab can tell this extension from any other.
// Without a code it still hands URLs off, but never sends cookies.
const SERVER_CONTEXT = "grab-server\u0000";
const CLIENT_CONTEXT = "grab-client\u0000";
// Shared pattern lives in shared.js.
const STATUS_UNVERIFIED = -1;
/// The POST was sent but the answer never arrived (timeout or connection
/// drop): Grab may have accepted it. Never fall back to grab:// here —
/// that would duplicate the download.
const STATUS_MAYBE_SENT = -2;
/// The pairing code lives in local storage, not sync: it is a secret for this
/// machine's Grab and must not follow the profile to other devices.
async function getPairingCode() {
try {
const { pairingCode } = await chrome.storage.local.get({ pairingCode: "" });
const code = normalizePairingCode(pairingCode);
return SHARED_PAIRING_CODE_RE.test(code) ? code : "";
} catch {
return "";
}
}
function hexToBytes(hex) {
const out = new Uint8Array(hex.length / 2);
for (let i = 0; i < out.length; i++) {
out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
}
return out;
}
function bytesToHex(bytes) {
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
}
/// HMAC-SHA256(secret, context || message) as lowercase hex.
async function hmacHex(secretHex, context, message) {
const key = await crypto.subtle.importKey(
"raw",
hexToBytes(secretHex),
{ name: "HMAC", hash: "SHA-256" },
false,
["sign"],
);
const data = new TextEncoder().encode(context + message);
return bytesToHex(new Uint8Array(await crypto.subtle.sign("HMAC", key, data)));
}
function constantTimeEqual(a, b) {
if (typeof a !== "string" || typeof b !== "string" || a.length !== b.length) {
return false;
}
let diff = 0;
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
return diff === 0;
}
/// fetch() with a deadline.
async function fetchWithTimeout(url, opts, ms) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), ms);
try {
return await fetch(url, { ...opts, signal: controller.signal });
} finally {
clearTimeout(timer);
}
}
/// True when the listener on Grab's port knows the pairing code. A squatter
/// without it cannot answer, and a Grab that regenerated its code fails too.
async function verifyGrab(secret) {
const nonce = bytesToHex(crypto.getRandomValues(new Uint8Array(16)));
const resp = await fetchWithTimeout(
`${GRAB_BASE_URL}/hello?n=${nonce}`,
{ method: "GET" },
HELLO_TIMEOUT_MS,
);
if (!resp.ok) return false;
const body = await resp.json();
const expected = await hmacHex(secret, SERVER_CONTEXT, nonce);
return constantTimeEqual(body && body.proof, expected);
}
/// Prefer cookies most likely to carry authentication when the 100-cookie
/// server cap forces a choice. The original order breaks ties deterministically.
function cookieRetentionPriority(cookie) {
const name = typeof cookie?.name === "string" ? cookie.name : "";
if (name.toLowerCase() === "cf_clearance") return 0;
if (name.startsWith("__Host-")) return 1;
if (name.startsWith("__Secure-")) return 2;
if (/(session|auth|token|sid|csrf|xsrf|login|jwt|clearance)/i.test(name)) return 3;
return 4;
}
function limitHandoffCookies(cookies) {
return cookies
.map((cookie, index) => ({ cookie, index }))
.sort((a, b) =>
cookieRetentionPriority(a.cookie) - cookieRetentionPriority(b.cookie) ||
a.index - b.index
)
.slice(0, MAX_HANDOFF_COOKIES)
.sort((a, b) => a.index - b.index)
.map(({ cookie }) => cookie);
}
function serializeHandoffBody(url, cookies, userAgent) {
return JSON.stringify({ url, cookies, user_agent: userAgent });
}
/// Keep a valid URL handoff even if a site exposes a very large cookie jar.
/// Drop lower-priority cookies first; among equal priorities, remove the
/// largest serialized cookies first. Critical auth cookies are retained unless
/// they alone prevent the body from fitting.
function fitHandoffBody(url, cookies, userAgent) {
let body = serializeHandoffBody(url, cookies, userAgent);
const byteLength = (value) => new TextEncoder().encode(value).length;
if (byteLength(body) <= MAX_HANDOFF_BODY_BYTES) return body;
const dropOrder = cookies
.map((cookie, index) => ({
index,
priority: cookieRetentionPriority(cookie),
size: byteLength(JSON.stringify(cookie)),
}))
.sort((a, b) =>
b.priority - a.priority || b.size - a.size || b.index - a.index
);
const retained = new Set(cookies.map((_, index) => index));
for (const candidate of dropOrder) {
retained.delete(candidate.index);
body = serializeHandoffBody(
url,
cookies.filter((_, index) => retained.has(index)),
userAgent
);
if (byteLength(body) <= MAX_HANDOFF_BODY_BYTES) break;
}
return body;
}
/// The site's cookies in the shape Grab expects. Needs the optional `cookies`
/// permission; without it (or on any failure) the handoff is URL-only.
/// `storeId` scopes the read to the tab's cookie store (incognito, Firefox
/// containers); without it the default store's cookies would leak in.
async function readCookies(url, storeId) {
try {
const filter = storeId ? { url, storeId } : { url };
const all = await chrome.cookies.getAll(filter);
const cookies = all.map((c) => ({
name: c.name,
value: c.value,
domain: c.domain,
host_only: c.hostOnly,
path: c.path,
secure: c.secure,
expiration_date: c.expirationDate,
}));
return limitHandoffCookies(cookies);
} catch {
return [];
}
}
/// Resolve the cookie store for a handoff context. Returns a store ID string,
/// undefined for the default store, or null to fail closed (send no cookies).
/// Firefox exposes tab.cookieStoreId directly; Chrome needs a lookup through
/// getAllCookieStores() matching tabIds. Chrome's store list has no incognito
/// flag, so an incognito context with no resolvable store fails closed rather
/// than guessing.
async function resolveStoreId(ctx) {
const tabId = ctx && ctx.tabId;
const ctxIncognito = ctx && ctx.incognito === true;
if (Number.isInteger(tabId) && tabId >= 0) {
let tab;
try {
tab = await chrome.tabs.get(tabId);
} catch {
tab = undefined;
}
if (tab && tab.cookieStoreId) {
return tab.cookieStoreId; // Firefox (containers, incognito).
}
// Chrome: match the tab against the stores' tabIds.
try {
const stores = await chrome.cookies.getAllCookieStores();
if (Array.isArray(stores)) {
const match = stores.find(
(s) => Array.isArray(s.tabIds) && s.tabIds.includes(tabId)
);
if (match) return match.id;
}
} catch {}
if (ctxIncognito || (tab && tab.incognito === true)) {
return null; // Fail closed: never send default-store cookies for incognito.
}
} else if (ctxIncognito) {
return null; // Incognito interception with no tab: fail closed.
}
return undefined; // Default store.
}
/// POST one URL to Grab and wait for its answer to the confirm dialog.
/// Resolves to the HTTP status, 0 when Grab can't be reached (not running),
/// STATUS_UNVERIFIED when the listener could not prove it is Grab, or
/// STATUS_MAYBE_SENT when the POST may have reached Grab but the answer
/// was lost (timeout). The caller must not fall back to grab:// on
/// STATUS_MAYBE_SENT — that would risk a duplicate download.
async function postToGrab(url, ctx) {
let secret;
try {
secret = await getPairingCode();
} catch {
return 0; // Storage unreachable; treat as Grab not running.
}
let cookies = [];
if (secret) {
let verified;
try {
verified = await verifyGrab(secret);
} catch {
return 0; // Grab not reachable.
}
if (!verified) return STATUS_UNVERIFIED;
// Cookies let Grab's yt-dlp pass bot challenges (Cloudflare etc.).
// They go only to a Grab that has proven it holds the pairing code.
// Scope to the tab's cookie store: incognito/container tabs must not
// send the default store's cookies.
try {
const storeId = await resolveStoreId(ctx);
cookies = storeId === null ? [] : await readCookies(url, storeId);
} catch {
cookies = []; // Cookie read failure: URL-only handoff.
}
}
let body, headers;
try {
// userAgent travels with the cookies: cf_clearance is UA-bound, so Grab
// applies it to its HTTP client and yt-dlp alongside the jar.
const userAgent =
typeof navigator !== "undefined" && navigator.userAgent
? navigator.userAgent
: undefined;
// Preserve the URL and retain the highest-value auth cookies within the
// payload budget; don't drop the whole jar as the first fallback.
body = fitHandoffBody(url, cookies, userAgent);
headers = { "Content-Type": "application/json" };
if (secret) headers["X-Grab-Token"] = await hmacHex(secret, CLIENT_CONTEXT, body);
} catch {
return 0; // Crypto failed; POST never sent, safe to fall back.
}
const start = Date.now();
try {
// confirm=1: Grab answers only once the user has approved or declined, so
// the browser's own download is cancelled only when Grab really took over.
const resp = await fetchWithTimeout(
`${GRAB_HTTP_URL}?confirm=1`,
{ method: "POST", headers, body },
CONFIRM_TIMEOUT_MS,
);
return resp.status;
} catch {
// Fast failure (connection refused): Grab isn't running, the POST never
// left. Slow failure (timeout): Grab may have accepted it.
return Date.now() - start < 10000 ? 0 : STATUS_MAYBE_SENT;
}
}
/// POST to Grab, retrying briefly on 429 (queue full). Resolves to the final
/// HTTP status, or 0 when Grab isn't reachable.
async function postToGrabWithRetry(url, ctx, retryDelays = HANDOFF_RETRY_DELAYS_MS) {
let status = await postToGrab(url, ctx);
for (const delay of retryDelays) {
if (status !== 429) break;
await sleep(delay);
status = await postToGrab(url, ctx);
}
return status;
}
/// Send the URL to Grab via HTTP. Resolves to true only when Grab accepted it.
/// A 429 means Grab's queue is momentarily full, so retry briefly first. Any
/// other outcome (Grab not running or not verified, declined by the user (409),
/// no answer in time (408), 403, 414, …) is a failure: the caller must leave
/// the browser's own download alone. The caller validates the URL with
/// toGrabUrl first; the raw URL is posted as-is.
async function handOff(url, ctx, retryDelays = HANDOFF_RETRY_DELAYS_MS) {
const status = await postToGrabWithRetry(url, ctx, retryDelays);
return status >= 200 && status < 300;
}
/// Explicit user action (context menu, video menu, Alt+G): try the HTTP
/// handoff first, but only fall back to the grab:// navigation when Grab
/// isn't reachable at all (connection failure). If Grab responded — even
/// with 409 (card opened or declined) or 408 — it handled the URL; falling
/// back would duplicate the handoff.
async function explicitSend(url, tabId, incognito) {
if (!toGrabUrl(url)) return;
const status = await postToGrabWithRetry(url, { tabId, incognito });
const tabArg =
Number.isInteger(tabId) && tabId >= 0 ? { tabId } : {};
if (status === 0) {
// Grab not running: the OS launches it with the grab:// URL.
sendToGrab(url, tabId);
} else if (status === STATUS_UNVERIFIED) {
// Something else answers on Grab's port. Don't hand the URL to a
// stranger; flag it on the toolbar instead.
try {
await chrome.action.setBadgeText({ ...tabArg, text: "!" });
await chrome.action.setBadgeBackgroundColor({ ...tabArg, color: "#cc0000" });
await chrome.action.setTitle({ ...tabArg, title: "Grab not recognised. Pair again in Options." });
if (Number.isInteger(tabId) && tabId >= 0) warnedTabs.add(tabId);
} catch {}
} else if (status >= 200 && status < 300) {
// Success: clear any earlier warning.
try {
await chrome.action.setBadgeText({ ...tabArg, text: "" });
await chrome.action.setTitle({ ...tabArg, title: "" });
if (Number.isInteger(tabId) && tabId >= 0) warnedTabs.delete(tabId);
} catch {}
} else if (status !== STATUS_MAYBE_SENT) {
// Concrete HTTP rejections (especially exhausted 429 retries, 408, or
// 409) need visible feedback. Never fall back to grab:// after a response.
const title = status === 408
? "Grab did not respond in time (HTTP 408). Check Grab before retrying."
: status === 409
? "Grab did not queue this URL (HTTP 409). Check the Grab dialog."
: status === 429
? "Grab's queue is full after retries (HTTP 429). Try again after a download finishes."
: `Grab could not accept this URL (HTTP ${status}).`;
try {
await chrome.action.setBadgeText({ ...tabArg, text: "!" });
await chrome.action.setBadgeBackgroundColor({ ...tabArg, color: "#cc0000" });
await chrome.action.setTitle({ ...tabArg, title });
} catch {}
}
// STATUS_MAYBE_SENT may have been accepted; never fall back because that
// risks a duplicate download.
}
/// True when the URL's file extension is on the user's skip list.
function isSkipped(url, skipTypes) {
if (!skipTypes) return false;
let ext = "";
try {
const path = new URL(url).pathname;
const dot = path.lastIndexOf(".");
if (dot >= 0) ext = path.slice(dot + 1).toLowerCase();
} catch {
return false;
}
return skipTypes
.split(",")
.map((s) => s.trim().toLowerCase().replace(/^\./, ""))
.some((s) => s !== "" && s === ext);
}
async function getSettings() {
return chrome.storage.sync.get(SHARED_DEFAULTS);
}
/// Per-download claim keys in session storage: one key per download id, so two
/// downloads claimed at the same moment can't clobber each other's record the
/// way a shared read-modify-write set would. Session storage survives service
/// worker restarts and clears when the browser closes.
const claimKey = (id) => `claimedDownload:${id}`;
async function claimDownload(id) {
await chrome.storage.session.set({ [claimKey(id)]: true });
}
async function unclaimDownload(id) {
await chrome.storage.session.remove(claimKey(id));
}
async function isClaimed(id) {
const key = claimKey(id);
const result = await chrome.storage.session.get(key);
return result[key] === true;
}
// --- Automatic interception ----------------------------------------------
/// Remove the browser's own copy of a download Grab has taken over.
async function removeBrowserCopy(id) {
try {
await chrome.downloads.removeFile(id);
} catch {
// Already gone.
}
try {
await chrome.downloads.erase({ id });
} catch {
// Already gone.
}
}
async function interceptDownload(item) {
// Non-http(s) URLs (blob:, data:) and URLs with credentials can't be
// handed over.
if (!toGrabUrl(item.url)) return;
// Hand off over Grab's local HTTP endpoint. If Grab isn't running or
// refuses the request, the download is left to the browser.
// Only cancel the browser download on HTTP 200 (queued). HTTP 202 means
// Grab opened the New Download card (nothing queued yet) — the user may
// not complete it, so the browser copy must stay.
const status = await postToGrabWithRetry(item.url, { incognito: item.incognito === true });
if (status !== 200) return;
await claimDownload(item.id);
// A tiny download can finish while the handoff is in flight, before the
// claim exists, so onChanged skipped it: clean up here instead.
const [current] = await chrome.downloads.search({ id: item.id });
if (current && current.state === "complete") {
await removeBrowserCopy(item.id);
await unclaimDownload(item.id);
return;
}
try {
await chrome.downloads.cancel(item.id);
} catch {
// Already gone; the onChanged guard below still cleans up.
}
try {
await chrome.downloads.removeFile(item.id);
} catch {
// Nothing written yet or already removed.
}
}
// Downloads parked while waiting for their size to become known, when the
// user set a minimum intercept size. MV3 service workers are ephemeral: an
// in-memory Map + setTimeout can die mid-wait and lose the interception, so
// the pending set lives in session storage (survives worker restarts, clears
// with the browser) and the deadline is a chrome.alarms one-shot (alarms
// wake the worker). After a restart, the next onChanged or alarm re-reads
// the pending set and decides.
const pendingKey = (id) => `pendingSize:${id}`;
const alarmName = (id) => `size-wait:${id}`;
// Best-effort guard against deciding the same download twice when an alarm
// and a size event interleave within one worker lifetime. Cross-restart
// dedup comes from dropPending's session-storage removal.
const deciding = new Set();
async function isPending(id) {
const key = pendingKey(id);
const result = await chrome.storage.session.get(key);
return result[key] !== undefined;
}
async function parkForSize(item, deadline = Date.now() + SIZE_WAIT_MS) {
// The alarm is only the worker-wakeup: the stored deadline is the real
// timer. Packaged Chrome fires alarms no earlier than ~30s out, so the
// effective wait in packaged builds is >= 30s even though the deadline is
// sooner; the deadline still decides, so unpacked builds keep the short
// wait for development.
await chrome.storage.session.set({ [pendingKey(item.id)]: deadline });
await chrome.alarms.create(alarmName(item.id), { when: deadline });
}
async function dropPending(id) {
await chrome.alarms.clear(alarmName(id)).catch(() => {});
await chrome.storage.session.remove(pendingKey(id));
}
// How long to wait for a server to report the size before treating an
// unknown size as big enough to intercept (streams rarely send one, and they
// belong in Grab).
const SIZE_WAIT_MS = 10_000;
const minSizeBytes = (settings) =>
Math.max(0, settings.minSizeMB | 0) * 1024 * 1024;
async function decidePending(id) {
// Acquire the guard before the first await: two interleaved calls (an alarm
// and a size event arriving together) would otherwise both pass the check
// above before either reaches the add below, and both would intercept.
if (deciding.has(id)) return;
deciding.add(id);
try {
const stored = await chrome.storage.session.get(pendingKey(id));
const deadline = stored[pendingKey(id)];
if (deadline === undefined) return;
const settings = await getSettings();
const items = await chrome.downloads.search({ id });
const item = items[0];
if (!item) {
await dropPending(id);
return;
}
// The download finished or failed while parked (or in the async gap
// between deciding to park and persisting the pending state): too late
// to hand over — leave the browser copy alone.
if (item.state === "complete" || item.state === "interrupted") {
await dropPending(id);
return;
}
// The user may have changed their mind while we waited.
if (!settings.interceptDownloads || isSkipped(item.url, settings.skipTypes) || !toGrabUrl(item.url)) {
await dropPending(id);
return;
}
if (item.fileSize >= 0) {
// Size is known: small enough stays in the browser, big enough is
// intercepted now.
if (item.fileSize < minSizeBytes(settings)) {
await dropPending(id);
return;
}
} else if (Date.now() < deadline) {
// Size still unknown but the deadline hasn't passed: this call came
// too early (the alarm is only the wakeup). Re-park and wait for the
// real deadline instead of intercepting early. Don't drop: parkForSize
// refreshes the pending entry.
await parkForSize(item, deadline);
return;
}
// Unknown size past the deadline: streams rarely report one, and they
// belong in Grab (see SIZE_WAIT_MS).
// Drop the pending entry AFTER the handoff starts, so a worker death
// in between doesn't lose the download silently.
await interceptDownload(item);
await dropPending(id);
} finally {
deciding.delete(id);
}
}
// Size-wait deadline: decide the parked download even if the worker was
// restarted while it was parked (the pending set survived in session storage).
chrome.alarms.onAlarm.addListener((alarm) => {
const m = /^size-wait:(\d+)$/.exec(alarm.name);
if (m) decidePending(Number(m[1]));
});
chrome.downloads.onCreated.addListener(async (item) => {
const settings = await getSettings();
if (!settings.interceptDownloads) return;
// Ignore downloads from a previous browser session (Varia pattern):
// onCreated can re-fire on startup for old downloads. Missing startTime
// or a missing browserStartTime (no startup seen) is treated as new.
if (item.startTime) {
const { browserStartTime } = await chrome.storage.session.get(
"browserStartTime",
);
if (
browserStartTime !== undefined &&
new Date(item.startTime).getTime() < browserStartTime
) {
return;
}
}
// Extension installs/updates must never be intercepted.
if (item.mime === "application/x-chrome-extension") return;
if (isSkipped(item.url, settings.skipTypes)) return;
// Non-http(s) downloads (blob:, data:) have no server URL to hand over.
if (!toGrabUrl(item.url)) return;
const cap = minSizeBytes(settings);
if (cap > 0) {
if (item.fileSize >= 0 && item.fileSize < cap) return; // Too small: browser keeps it.
if (item.fileSize < 0) {
// Size not known yet (headers haven't arrived): wait for it instead of
// guessing. The browser download proceeds normally meanwhile.
await parkForSize(item);
// The download may have finished while the pending state was being
// written (async gap between deciding to park and persisting it):
// re-check, and drop the parked entry if it's already too late to
// hand over. Anything finishing after this is caught by the onChanged
// guard or by decidePending's own state check.
const fresh = await chrome.downloads.search({ id: item.id });
const current = fresh[0];
if (
!current ||
current.state === "complete" ||
current.state === "interrupted"
) {
await dropPending(item.id);
}
return;
}
}
await interceptDownload(item);
});
chrome.downloads.onChanged.addListener(async (delta) => {
if (await isPending(delta.id)) {
const state = delta.state && delta.state.current;
if (state === "complete" || state === "interrupted") {
// Finished or failed before the size arrived: too late to hand over.
await dropPending(delta.id);
return;
}
if (delta.fileSize && delta.fileSize.current >= 0) {
await decidePending(delta.id);
return;
}
}
if (!(await isClaimed(delta.id))) return;
const state = delta.state && delta.state.current;
if (state === "complete") {
// Lost the race: the browser finished before our cancel landed. Remove
// the duplicate so only Grab's copy remains.
await removeBrowserCopy(delta.id);
}
if (state === "complete" || state === "interrupted") {
await unclaimDownload(delta.id);
}
});
// --- Explicit sends -------------------------------------------------------
function createContextMenu() {
chrome.contextMenus.create({
id: "sendToGrab",
title: "Download with Grab",
contexts: ["link", "video", "audio", "image", "page"],
});
}
chrome.runtime.onInstalled.addListener(async () => {
const settings = await getSettings();
// removeAll first: onInstalled also fires on extension updates, when the
// menu may already exist (create would throw on a duplicate id).
await removeAllContextMenus();
if (settings.showContextMenu) createContextMenu();
});
chrome.storage.onChanged.addListener(async (changes, area) => {
if (area !== "sync") return;
if (changes.showContextMenu) {
// removeAll first: rapid toggles would otherwise stack a duplicate-id
// create on top of an in-flight one.
await removeAllContextMenus();
if (changes.showContextMenu.newValue) {
createContextMenu();
// removeAll also dropped the video submenu; rebuild it.
if (Number.isInteger(activeTabId) && activeTabId >= 0) {
refreshVideoMenu(activeTabId);
}
}
}
if (changes.detectVideos) {
detectVideosOn = changes.detectVideos.newValue !== false;
if (!detectVideosOn) clearAllVideoUi();
}
});
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
const id = info.menuItemId;
if (typeof id === "string" && id.startsWith(VIDEO_ITEM_PREFIX)) {
// A detected video: same explicit-send channel as the main item (the
// user picked this tab), not the background-tab interception channel.
// Resolve against the list the menu was built from: it was filtered
// (master playlists) and may belong to another window's tab.
// menuUrls is in-memory; after a worker restart, read the persisted copy.
let urls = menuUrls;
if (urls.length === 0) {
try {
const stored = await chrome.storage.session.get("menuUrls");
if (Array.isArray(stored.menuUrls)) urls = stored.menuUrls;
} catch {
// Fall through with the empty list.
}
}
const url = urls[Number(id.slice(VIDEO_ITEM_PREFIX.length))];
// Try the paired HTTP handoff first (sends cookies, waits for Grab's
// real answer); fall back to the grab:// navigation only when Grab isn't
// reachable at all.
if (url) await explicitSend(url, tab && tab.id, tab && tab.incognito === true);
return;
}
if (id !== "sendToGrab") return;
const candidates = [info.linkUrl, info.srcUrl, info.pageUrl];
// Magnet links already open in Grab through the OS handler; pass them
// through unwrapped.
const magnet = candidates.find(
(u) => typeof u === "string" && u.toLowerCase().startsWith("magnet:"),
);
if (magnet) {
updateTab(tab && tab.id, magnet);
return;
}
// Right-clicked on a video element whose srcUrl is unusable (blob:/data:):
// try to find the detected video matching the clicked element's src.
// If the tab has exactly one detected video, that's the one the user
// meant — don't fall back to the generic page URL.
let target = candidates.find((u) => toGrabUrl(u));
if (
info.mediaType === "video" &&
tab &&
Number.isInteger(tab.id) &&
target === info.pageUrl
) {
const detected = mergedVideoUrls(tab.id);
// Try to match the clicked video's srcUrl against detected videos.
// info.srcUrl is the video element's src (may be blob:).
let matched = null;
if (info.srcUrl) {
const videos = domVideosFor(tab.id);
for (const v of videos) {
if (v && v.src === info.srcUrl) {
matched = v;
break;
}
}
}
if (matched && toGrabUrl(matched.src) && matched.src !== info.pageUrl) {
// Direct URL: use it.
target = matched.src;
} else if (detected.length === 1 && toGrabUrl(detected[0])) {
// Single detected video: use it.
target = detected[0];
} else if (matched && matched.blob && detected.length > 0) {
// Blob video matched but no direct URL: use first detected (likely paired manifest).
const first = detected.find((u) => toGrabUrl(u));
if (first) target = first;
}
}
// Prefer the media/link target, but a blob:/data: media URL can't leave
// the browser — fall back to the page URL so yt-dlp can extract it there.
// Try the paired HTTP handoff first (sends cookies); fall back to grab://
// only when Grab isn't reachable at all.
if (target) await explicitSend(target, tab && tab.id, tab && tab.incognito === true);
});
// The toolbar button now opens popup.html (default_popup in the manifest),
// which hosts the settings UI directly.
chrome.commands.onCommand.addListener((command) => {
if (command !== "send-tab-to-grab") return;
chrome.tabs.query({ active: true, currentWindow: true }, async (tabs) => {
const url = tabs[0] && tabs[0].url;
// Paired HTTP handoff first (sends cookies); grab:// fallback only when
// Grab isn't reachable at all.
if (url) await explicitSend(url, tabs[0].id, tabs[0].incognito === true);
});
});
// --- Video detection ------------------------------------------------------
//
// FDM-style video menu: the content script reports <video> elements the user
// started playing (play-event latch; muted autoplay is noise), and webRequest
// sniffs the HLS/DASH stream manifests (.m3u8/.mpd) that blob:-based MSE
// players actually fetch. Sniffed manifests surface only alongside a played
// video. Detections are kept per tab and offered as right-click menu children;
// a toolbar badge shows the count. Picking an entry hands the URL to the Grab
// desktop app. Segment traffic (.ts/.m4s/...) is ignored so the menu isn't
// flooded with fragments.
const VIDEO_PARENT_ID = "grabVideos";
const VIDEO_ITEM_PREFIX = "grabVideo:";
/// Callback-compatible context-menu removal: manifest declares
/// minimum_chrome_version 102, but promise-returning chrome.contextMenus
/// methods need Chrome 123+. These work on both.
function removeAllContextMenus() {
return new Promise((resolve) => {
try {
chrome.contextMenus.removeAll(() => {
void chrome.runtime.lastError;
resolve();
});
} catch {
resolve();
}
});
}
function removeContextMenu(id) {
return new Promise((resolve) => {
try {
chrome.contextMenus.remove(id, () => {
void chrome.runtime.lastError;
resolve();
});
} catch {
resolve();
}
});
}
// Host exclusion domains and their predicate are defined once in shared.js.
/// True when the tab lives on an excluded host. Host permissions are granted,
/// so tabs.get exposes the URL; anything odd (no tab, weird URL) is treated
/// as not excluded.
async function isExcludedTab(tabId) {
try {
const tab = await chrome.tabs.get(tabId);
const url = tab && tab.url;
return !!url && sharedHostExcluded(new URL(url).hostname);
} catch {
return false;
}
}
/// Classify a sniffed response URL: "manifest" for HLS/DASH playlists,
/// "media" for direct video files, null for everything else (segments,
/// audio, images, pages). Manifests win on content type alone because some
/// are served extensionless; extensionless media is NOT guessed because
/// DASH segments look exactly like that.
function classifyStream(url, contentType) {
const u = String(url || "").toLowerCase();
if (!/^https?:\/\//i.test(u)) return null;
const ct = String(contentType || "").toLowerCase().split(";")[0].trim();
// Match the extension on the path only: "?file=a.mp4" is not a media file.
let path;
try {
path = new URL(u).pathname;
} catch {
return null;
}
if (/\.(m3u8|m3u|mpd)$/.test(path)) return "manifest";
if (
ct === "application/vnd.apple.mpegurl" ||
ct === "application/x-mpegurl" ||
ct === "audio/x-mpegurl" ||
ct === "application/dash+xml"
) {
return "manifest";
}
// Explicitly audio-typed responses are not video candidates.
if (/^audio\//.test(ct)) return null;
if (/\.(mp4|m4v|webm|ogv|mov|mkv)$/.test(path)) return "media";
return null;
}
const NAME_MAX = 16;
const TITLE_MAX = 16;
const shorten = (text) =>
text.length > NAME_MAX ? text.slice(0, NAME_MAX) + "…" : text;
const shortenTitle = (text) =>
text.length > TITLE_MAX ? text.slice(0, TITLE_MAX) + "…" : text;
/// Last path segment of a URL, decoded ("my%20clip.mp4" -> "my clip.mp4").
/// Empty when there is none.
function fileNameOf(url) {
let last;
try {
last = new URL(url).pathname.split("/").filter(Boolean).pop() || "";
} catch {
return "";
}
try {
return decodeURIComponent(last);
} catch {
return last; // malformed escape: show it raw
}
}
/// Name shown for a detected video. A direct file is named by its file name
/// ("clip.mp4"): that is what the person is about to download, and a page
/// title would name the page, not the file. A stream (HLS/DASH, whose URL is
/// usually "master.m3u8") is named by the page's video title when the content
/// script found one, else by its file name. "Video N" is the last resort.
function videoName(url, index, pageTitle, kind) {
const file = fileNameOf(url);
if (kind) {
const title = String(pageTitle || "").replace(/\s+/g, " ").trim();
if (title) return shortenTitle(title);
}
return file ? shorten(file) : `Video ${index + 1}`;
}
/// One row for an HLS master or DASH manifest: hand it to Grab, whose
/// yt-dlp picks the quality.
function manifestMenuRows(url) {
return [{ quality: "", url }];
}
/// Row for a direct file: the height the player reported, when known.
function directMenuRow(url, height) {
return { quality: height > 0 ? `${height}p` : "", url };
}
/// Text of one menu row. "%" is doubled: menu titles treat "%s" as the
/// selected text.