Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
405 lines (350 loc) · 14.9 KB
/
Copy pathscript.js
File metadata and controls
405 lines (350 loc) · 14.9 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
let isInvalid = false;
// Dynamic Tab Title
const originalTitle = "Extension Source Code Downloader";
const isPWA = window.matchMedia('(display-mode: standalone)').matches;
window.addEventListener("focus", () => document.title = originalTitle);
window.addEventListener("blur", () => {
// Keep full title for PWA window, only shrink for browser tabs
if (!isPWA) document.title = "ExtSrc";
});
const inputField = document.getElementById('extensionInput');
const downloadButton = document.getElementById('downloadButton');
function getThemeColor(variableName, fallback) {
const value = getComputedStyle(document.documentElement).getPropertyValue(variableName).trim();
return value || fallback;
}
// --- Toast Notification System ---
function showToast(message, type = 'error', duration = 4000) {
const container = document.getElementById('toastContainer');
const toast = document.createElement('div');
toast.className = `toast toast-${type}`;
toast.textContent = message;
container.appendChild(toast);
setTimeout(() => {
toast.classList.add('toast-out');
toast.addEventListener('animationend', () => toast.remove());
}, duration);
}
// --- Button Loading State ---
function setButtonLoading(button, loading) {
const spinner = button.querySelector('.btn-spinner');
if (loading) {
button.classList.add('loading');
if (spinner) spinner.hidden = false;
} else {
button.classList.remove('loading');
if (spinner) spinner.hidden = true;
}
}
// Handle form submission to download the extension
document.getElementById('extensionForm').addEventListener('submit', function (event) {
event.preventDefault();
downloadExtension();
});
// Update download options and focus on the input when browser selection changes
document.querySelectorAll('.browser-input').forEach(input => {
input.addEventListener('change', function () {
updateDownloadOptions();
inputField.focus();
});
});
// Keyboard shortcut '/' to focus on the input
document.addEventListener('keydown', function (event) {
if (event.key === '/' && event.target.tagName !== 'INPUT') {
event.preventDefault();
inputField.focus();
}
});
// Update download options based on the selected browser
function updateDownloadOptions() {
const browser = document.querySelector('input[name="browser"]:checked').value;
const downloadType = document.getElementById('downloadType');
const options = {
chrome: ['zip', 'crx'],
edge: ['zip', 'crx'],
firefox: ['zip', 'xpi'],
opera: ['zip', 'crx']
};
downloadType.innerHTML = "";
options[browser].forEach(format => {
const option = document.createElement("option");
option.value = format;
option.textContent = `Download as .${format}`;
downloadType.appendChild(option);
});
}
updateDownloadOptions();
// Detect browser from input URL and reset invalid state
// (Moved into the new input event listener above)
function detectBrowserFromUrl(input) {
const urlPatterns = {
chrome: [
/chrome\.google\.com\/webstore\/detail\//,
/chromewebstore\.google\.com\/detail\//
],
edge: [/microsoftedge\.microsoft\.com\/addons\/detail\//],
firefox: [
/addons\.mozilla\.org\/.*addon\//,
/addons\.allizom\.org\/.*addon\//,
/addons-dev\.allizom\.org\/.*addon\//,
/addons\.thunderbird\.net\/.*addon\//
],
opera: [/addons\.opera\.com\/.*extensions\/details\//]
};
for (const [browser, patterns] of Object.entries(urlPatterns)) {
if (patterns.some(pattern => pattern.test(input))) {
document.getElementById(browser).checked = true;
updateDownloadOptions();
break;
}
}
}
// Handle button click with preload fallback logic
downloadButton.addEventListener('click', function (event) {
event.preventDefault(); // Stop native navigation
const browser = document.querySelector('input[name="browser"]:checked').value;
const downloadType = document.getElementById('downloadType').value;
const input = inputField.value.trim();
const extensionId = extractExtensionId(input, browser);
const downloadUrl = getDownloadUrl(browser, extensionId);
if (!input || !extensionId) {
inputField.style.borderColor = getThemeColor('--input-error-color', '#b44dff');
showToast("Please enter a valid Extension URL.");
isInvalid = true;
return;
}
if (downloadType === "zip" && browser === "firefox") {
convertXpiToZip(downloadUrl, extensionId);
return;
}
// Attempt to preload the file into memory to enforce lowercase filename and avoid browser warnings
const expectedFilename = `${extensionId.toLowerCase()}.${downloadType.toLowerCase()}`;
setButtonLoading(downloadButton, true);
// Route through the local Vercel proxy to bypass CORS for Chromium browsers
let fetchUrl = downloadUrl;
if (browser === "chrome" || browser === "edge" || browser === "opera") {
fetchUrl = `/api/download?id=${extensionId}&browser=${browser}&format=${downloadType}`;
}
fetch(fetchUrl)
.then(response => {
if (response.status === 404 && fetchUrl.includes('/api/download')) {
throw new Error("MISSING_API");
}
if (response.status >= 500) {
throw new Error("SERVER_LIMIT");
}
if (!response.ok) throw new Error("Fetch failed");
return response.blob();
})
.then(blob => {
downloadBlob(blob, expectedFilename);
if (downloadType === "crx") {
showToast("If Chrome says 'Blocked • Unknown source', open downloads and select 'Download suspicious file' to keep it.", "success", 8000);
} else {
showToast("Download complete!", "success", 3000);
}
setButtonLoading(downloadButton, false);
})
.catch(err => {
if (err.message === "MISSING_API") {
console.warn("Vercel Serverless API missing. Falling back to direct store download.");
showToast("Serverless Proxy missing. Deploy to Vercel for perfect downloads. Falling back to direct download - you may need to 'Keep' the file manually.", "error", 8000);
} else if (err.message === "SERVER_LIMIT" && downloadType === "zip") {
console.warn("Extension exceeds Vercel payload limits. Falling back to raw CRX.");
showToast("Extension too large for auto-zip! Downloading raw format instead—please drag and drop it into the converter.", "error", 10000);
} else {
console.warn("Preload failed (likely CORS or limits), falling back to iframe:", err);
}
// Fallback: iframe download utilizing original direct store URL
const iframe = document.createElement("iframe");
iframe.style.display = "none";
iframe.src = downloadUrl; // Original URL, not the Vercel fetch URL
document.body.appendChild(iframe);
setTimeout(() => {
if (document.body.contains(iframe)) {
document.body.removeChild(iframe);
}
}, 10000);
if (err.message !== "MISSING_API" && err.message !== "SERVER_LIMIT") {
if (downloadType === "crx") {
showToast("If Chrome says 'Blocked • Unknown source', open downloads and select 'Download suspicious file' to keep it.", "success", 8000);
} else {
showToast("Downloading... Note: Server enforced the original filename.", "success", 6000);
}
}
setButtonLoading(downloadButton, false);
});
});
// Detection and cleanup
inputField.addEventListener("input", function () {
const value = this.value.trim();
detectBrowserFromUrl(value);
if (isInvalid) {
inputField.style.borderColor = '';
isInvalid = false;
}
});
document.querySelectorAll('.browser-input').forEach(input => {
input.addEventListener('change', updateDownloadOptions);
});
// Extract extension ID from the URL based on the browser type
function extractExtensionId(input, browser) {
const patterns = {
chrome: /([a-z]{32})/,
edge: /([a-z]{32})/,
firefox: /addons(?:-dev)?\.(?:mozilla\.org|allizom\.org|thunderbird\.net)\/[^\/]+\/(?:firefox|thunderbird)\/addon\/([^\/?]+)/,
opera: /(?:addons.opera.com\/.*?\/extensions\/details\/)([a-zA-Z0-9_-]+)(?=\/|$)/
};
const match = patterns[browser]?.exec(input);
return match ? match[1].toLowerCase() : null;
}
// Get the base download URL for each browser
function getDownloadUrl(browser, extensionId) {
const baseUrls = {
chrome: `https://clients2.google.com/service/update2/crx?response=redirect&os=win&arch=x86-64&os_arch=x86-64&nacl_arch=x86-64&prod=chromiumcrx&prodchannel=unknown&prodversion=2147483647&acceptformat=crx2,crx3&x=id%3D${extensionId}%26uc`,
edge: `https://edge.microsoft.com/extensionwebstorebase/v1/crx?response=redirect&x=id%3D${extensionId}%26installsource%3Dondemand%26uc`,
opera: `https://addons.opera.com/extensions/download/${extensionId}`
};
const inputUrl = inputField.value.trim();
if (browser === "firefox") {
if (inputUrl.includes("addons.allizom.org")) {
return `https://addons.allizom.org/firefox/downloads/latest/${extensionId}/platform:5/${extensionId}.xpi`;
}
if (inputUrl.includes("addons-dev.allizom.org")) {
return `https://addons-dev.allizom.org/firefox/downloads/latest/${extensionId}/platform:5/${extensionId}.xpi`;
}
if (inputUrl.includes("addons.thunderbird.net")) {
return `https://addons.thunderbird.net/firefox/downloads/latest/${extensionId}/platform:5/${extensionId}.xpi`;
}
else {
return `https://addons.mozilla.org/firefox/downloads/latest/${extensionId}/platform:5/${extensionId}.xpi`;
}
}
return baseUrls[browser];
}
// XPI to ZIP
function convertXpiToZip(url, extensionId) {
if (url.includes("addons.thunderbird.net")) {
showToast("Please download the XPI file first, then upload it here to convert it into a ZIP.", "error", 5000);
return;
}
const downloadBtn = document.getElementById('downloadButton');
setButtonLoading(downloadBtn, true);
fetch(url)
.then(response => response.arrayBuffer())
.then(arrayBuffer => {
const blob = new Blob([arrayBuffer], { type: "application/zip" });
downloadBlob(blob, extensionId.toLowerCase() + ".zip");
showToast("ZIP file ready!", "success", 3000);
})
.catch((error) => {
console.error("Error converting XPI to ZIP:", error);
showToast("Download failed. Please ensure the Extension ID/URL and browser are correct.");
})
.finally(() => {
setButtonLoading(downloadBtn, false);
});
}
// Handle file uploads for CRX/XPI conversion
const dropZone = document.getElementById("dropZone");
const fileInput = document.getElementById("fileInput");
const dropText = document.getElementById("dropText");
const convertButton = document.getElementById("convertButton");
// Initially disable the convert button
convertButton.disabled = true;
// Click to open file selection
dropZone.addEventListener("click", () => fileInput.click());
// Keyboard support for drop zone
dropZone.addEventListener("keydown", (event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
fileInput.click();
}
});
// Handle file selection
fileInput.addEventListener("change", handleFileSelect);
dropZone.addEventListener("dragover", (event) => {
event.preventDefault();
dropZone.style.background = "rgba(255, 255, 255, 0.2)";
});
dropZone.addEventListener("dragleave", () => {
dropZone.style.background = "transparent";
});
dropZone.addEventListener("drop", (event) => {
event.preventDefault();
fileInput.files = event.dataTransfer.files;
handleFileSelect();
});
function handleFileSelect() {
if (fileInput.files.length > 0) {
const file = fileInput.files[0];
dropText.textContent = `Selected: ${file.name}`;
convertButton.disabled = false;
} else {
dropText.textContent = "Drop your .crx or .xpi file here or click to browse";
convertButton.disabled = true;
}
}
// Handle Convert Button Click
convertButton.addEventListener("click", function () {
if (fileInput.files.length === 0) return;
const file = fileInput.files[0];
setButtonLoading(convertButton, true);
convertFileToZip(file);
});
// Convert CRX/XPI to ZIP
function convertFileToZip(file) {
const reader = new FileReader();
reader.onload = function (event) {
const arrayBuffer = event.target.result;
let zipBlob;
if (file.name.endsWith(".crx")) {
zipBlob = arrayBufferToBlob(arrayBuffer);
} else {
zipBlob = new Blob([arrayBuffer], { type: "application/zip" });
}
const fileNameBase = file.name.replace(/\.[^.]+$/, "");
downloadBlob(zipBlob, fileNameBase.toLowerCase() + ".zip");
showToast("Converted successfully!", "success", 3000);
setButtonLoading(convertButton, false);
};
reader.onerror = function () {
showToast("Failed to read the file. Please try again.");
setButtonLoading(convertButton, false);
};
reader.readAsArrayBuffer(file);
}
// Convert CRX to ZIP (Strips CRX Header)
function arrayBufferToBlob(arraybuffer) {
const buf = new Uint8Array(arraybuffer);
let zipStartOffset;
if (buf[4] === 2) { // CRX v2 format
const publicKeyLength = (buf[8] + (buf[9] << 8) + (buf[10] << 16) + (buf[11] << 24)) >>> 0;
const signatureLength = (buf[12] + (buf[13] << 8) + (buf[14] << 16) + (buf[15] << 24)) >>> 0;
zipStartOffset = 16 + publicKeyLength + signatureLength;
} else { // CRX v3 format
const publicKeyLength = (buf[8] + (buf[9] << 8) + (buf[10] << 16) + (buf[11] << 24)) >>> 0;
zipStartOffset = 12 + publicKeyLength;
}
return new Blob([new Uint8Array(arraybuffer, zipStartOffset)], { type: "application/zip" });
}
// Download a Blob as a file (with proper cleanup)
function downloadBlob(blob, fileName) {
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = fileName;
link.click();
// Prevent memory leak
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
// Ensure the dropdown starts correctly
updateDownloadOptions();
// PWA Service Worker Registration
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('sw.js').catch(error => {
console.log('ServiceWorker registration failed: ', error);
});
});
}