-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.ts
More file actions
380 lines (352 loc) · 12.8 KB
/
background.ts
File metadata and controls
380 lines (352 loc) · 12.8 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
import { generateCliCommand } from "./commandUtils"
import type { DownloadTool, StoredCommand, StoredSettings } from "./types"
console.log("Arify Extension: Background script loaded.")
interface DownloadItemWithHeaders extends chrome.downloads.DownloadItem {
requestHeaders?: chrome.webRequest.HttpHeader[]
}
const getAllRequestHeaders = (
headers: chrome.webRequest.HttpHeader[] | undefined
): Record<string, string> => {
const result: Record<string, string> = {}
if (headers) {
for (const header of headers) {
if (header.name && header.value) {
if (header.name.toLowerCase() !== "cookie") {
result[header.name] = header.value
}
}
}
}
return result
}
const getCookies = async (url: string): Promise<string> => {
return new Promise((resolve) => {
if (!chrome.cookies) {
console.warn("Arify Extension: chrome.cookies API not available.")
resolve("")
return
}
const primaryUrl = url
chrome.cookies.getAll({ url: primaryUrl }, (cookiesFromUrl) => {
let primaryError = false
if (chrome.runtime.lastError) {
console.error(
`Arify Extension: Error getting cookies for URL ${primaryUrl}:`,
chrome.runtime.lastError.message
)
primaryError = true
}
let allFetchedCookies: chrome.cookies.Cookie[] = []
if (cookiesFromUrl && !primaryError) {
allFetchedCookies = allFetchedCookies.concat(cookiesFromUrl)
}
try {
const parsedUrl = new URL(primaryUrl)
const hostname = parsedUrl.hostname
chrome.cookies.getAll(
{ domain: hostname },
(cookiesFromExactDomain) => {
if (chrome.runtime.lastError) {
console.error(
`Arify Extension: Error getting cookies for exact domain ${hostname}:`,
chrome.runtime.lastError.message
)
} else if (
cookiesFromExactDomain &&
cookiesFromExactDomain.length > 0
) {
allFetchedCookies = allFetchedCookies.concat(
cookiesFromExactDomain
)
}
const domainParts = hostname.split(".")
if (domainParts.length > 1) {
const parentDomainAttempt =
"." +
(domainParts.length > 2
? domainParts.slice(1).join(".")
: hostname)
if (parentDomainAttempt !== "." + hostname) {
chrome.cookies.getAll(
{ domain: parentDomainAttempt },
(cookiesFromParentDomain) => {
if (chrome.runtime.lastError) {
console.error(
`Arify Extension: Error getting cookies for parent domain ${parentDomainAttempt}:`,
chrome.runtime.lastError.message
)
} else if (
cookiesFromParentDomain &&
cookiesFromParentDomain.length > 0
) {
allFetchedCookies = allFetchedCookies.concat(
cookiesFromParentDomain
)
}
finalizeAndResolveCookies()
}
)
} else {
finalizeAndResolveCookies()
}
} else {
finalizeAndResolveCookies()
}
}
)
const finalizeAndResolveCookies = () => {
const uniqueCookieKeys = new Set<string>()
const uniqueCookies = allFetchedCookies.filter((cookie) => {
const key = `${cookie.name}|${cookie.domain}|${cookie.path}`
if (uniqueCookieKeys.has(key)) {
return false
}
uniqueCookieKeys.add(key)
return true
})
if (uniqueCookies.length > 0) {
console.log(
`Arify Extension: Total ${uniqueCookies.length} unique cookie(s) processed for ${primaryUrl}.`
)
}
resolve(
uniqueCookies
.map((cookie) => `${cookie.name}=${cookie.value}`)
.join("; ")
)
}
} catch (e) {
console.error(
`Arify Extension: Error processing URL ${primaryUrl} for domain-based cookie query:`,
e
)
const uniqueCookies = Array.from(
new Map(
allFetchedCookies.map((cookie) => [
`${cookie.name}|${cookie.domain}|${cookie.path}`,
cookie
])
).values()
)
resolve(
uniqueCookies
.map((cookie) => `${cookie.name}=${cookie.value}`)
.join("; ")
)
}
})
})
}
chrome.downloads.onDeterminingFilename.addListener(
(
downloadItemSuggest: chrome.downloads.DownloadItem,
suggest: (suggestion?: chrome.downloads.DownloadFilenameSuggestion) => void
) => {
const downloadItem = downloadItemSuggest as DownloadItemWithHeaders
console.log(
"Arify Extension: onDeterminingFilename triggered for:",
downloadItem.url
)
chrome.storage.local.get(
["isInterceptorEnabled", "selectedTool"],
async (settings: StoredSettings) => {
if (chrome.runtime.lastError) {
console.error(
"Arify Extension: Error retrieving settings:",
chrome.runtime.lastError.message
)
suggest()
return
}
const { isInterceptorEnabled = true, selectedTool = "curl" } = settings
if (!isInterceptorEnabled) {
console.log(
"Arify Extension: Interceptor is disabled. Allowing download."
)
suggest()
return true
}
if (!downloadItem.url) {
console.warn(
"Arify Extension: Download item has no URL. Allowing download."
)
suggest()
return
}
console.log(
`Arify Extension: Intercepting download: ${downloadItem.url}`
)
const cookies = await getCookies(downloadItem.url)
const requestHeadersFromDownloadItem = getAllRequestHeaders(
downloadItem.requestHeaders
)
const userAgent = navigator.userAgent
const referer =
downloadItem.referrer ||
requestHeadersFromDownloadItem["Referer"] ||
requestHeadersFromDownloadItem["referer"]
const command = generateCliCommand({
originalUrl: downloadItem.url,
filename: downloadItem.filename,
requestHeaders: requestHeadersFromDownloadItem,
cookies: cookies,
userAgent: userAgent,
referer: referer,
tool: selectedTool
})
const newCommandEntry: StoredCommand = {
id: String(downloadItem.id),
command,
originalUrl: downloadItem.url,
referer: referer,
timestamp: downloadItem.startTime
? new Date(downloadItem.startTime).getTime()
: Date.now(),
tool: selectedTool,
isNew: true,
filename: downloadItem.filename,
requestHeaders: requestHeadersFromDownloadItem,
cookies: cookies,
userAgent: userAgent
}
chrome.storage.local.get(
{ savedCommands: [] },
(data: { savedCommands?: StoredCommand[] }) => {
if (chrome.runtime.lastError) {
console.error(
"Arify Extension: Error retrieving saved commands:",
chrome.runtime.lastError.message
)
suggest()
return
}
const currentCommands = data.savedCommands || []
const updatedCommands = [newCommandEntry, ...currentCommands]
chrome.storage.local.set({ savedCommands: updatedCommands }, () => {
if (chrome.runtime.lastError) {
console.error(
"Arify Extension: Error saving command:",
chrome.runtime.lastError.message
)
suggest()
return
}
console.log(
"Arify Extension: Command saved to storage:",
newCommandEntry.id
)
const finalSuggest = (
conflict: chrome.downloads.FilenameConflictAction = "uniquify"
) => {
suggest({
filename: downloadItem.filename,
conflictAction: conflict
})
console.log(
`Arify Extension: Called suggest() for ${downloadItem.filename} with action ${conflict}.`
)
}
let downloadIdToCancel: number | undefined = undefined
if (
typeof downloadItem.id === "number" &&
!isNaN(downloadItem.id)
) {
downloadIdToCancel = downloadItem.id
} else if (typeof downloadItem.id === "string") {
const parsedId = parseInt(downloadItem.id, 10)
if (!isNaN(parsedId)) {
downloadIdToCancel = parsedId
} else {
console.error(
`Arify Extension: Download ID string "${downloadItem.id}" could not be parsed to a valid number for cancellation.`
)
}
} else {
console.error(
`Arify Extension: Download ID "${downloadItem.id}" (type: ${typeof downloadItem.id}) is not a valid number or string for cancellation.`
)
}
if (downloadIdToCancel !== undefined) {
console.log(
`Arify Extension: Attempting to cancel download ID: ${downloadIdToCancel}`
)
chrome.downloads.cancel(downloadIdToCancel, () => {
if (chrome.runtime.lastError) {
console.warn(
`Arify Extension: Could not cancel download (ID: ${downloadItem.id}): ${chrome.runtime.lastError.message}. It might have already completed or been cancelled by other means.`
)
} else {
console.log(
"Arify Extension: Download successfully cancelled by extension:",
downloadItem.id
)
}
finalSuggest()
})
} else {
console.warn(
"Arify Extension: No valid Download ID to cancel. Calling suggest() to finalize download event."
)
finalSuggest("uniquify")
}
if (chrome.notifications) {
const notifId = `arify-dl-${Date.now()}-${downloadItem.id}`
chrome.notifications.create(
notifId,
{
type: "basic",
iconUrl: chrome.runtime.getURL("assets/icon.png"),
title: "Download Intercepted",
message: `CLI command generated for: ${downloadItem.filename || "file"}`,
priority: 0
},
(createdNotificationId) => {
if (chrome.runtime.lastError) {
console.error(
`Arify Extension: Notification error for ID ${notifId}:`,
chrome.runtime.lastError.message
)
} else {
if (createdNotificationId) {
console.log(
`Arify Extension: Notification ${createdNotificationId} shown for: ${downloadItem.filename || downloadItem.url}`
)
} else {
console.warn(
`Arify Extension: Notification was attempted for ${downloadItem.filename || downloadItem.url}, but create callback received no ID.`
)
}
}
}
)
}
})
}
)
}
)
return true
}
)
chrome.runtime.onInstalled.addListener((details) => {
if (details.reason === "install") {
chrome.storage.local.set(
{
isInterceptorEnabled: true,
selectedTool: "curl",
savedCommands: []
},
() => {
if (chrome.runtime.lastError) {
console.error(
"Arify Extension: Error setting default settings on install:",
chrome.runtime.lastError.message
)
} else {
console.log("Arify Extension: Default settings saved on install.")
}
}
)
}
})
console.log("Arify Extension: Background script event listeners attached.")