-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
469 lines (444 loc) · 14.3 KB
/
Copy pathbackground.js
File metadata and controls
469 lines (444 loc) · 14.3 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
const ACTIVE_REQUESTS = new Map();
let siteProfilesCache = {};
let activeAccountMap = {};
let autoUpdateEnabled = false;
let updateAvailableVersion = null;
const AUTO_SYNC_QUEUE = new Map();
const AUTO_SYNC_SUSPEND = new Set();
const MIN_VALUE_MATCHES = 2;
const MIN_VALUE_MATCH_RATIO = 0.1;
const AUTO_UPDATE_ALARM = 'auto-update-check';
const AUTO_UPDATE_INTERVAL_MIN = 60;
const REMOTE_MANIFEST_URL = 'https://github.com/abidkhanpk/cookie_switch/raw/refs/heads/master/manifest.json';
bootstrapCaches();
chrome.storage.onChanged.addListener(handleStorageChange);
chrome.cookies.onChanged.addListener(handleCookieChange);
chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === AUTO_UPDATE_ALARM) {
performAutoUpdateCheck();
}
});
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message?.type === 'switch-account') {
const key = `${message.payload?.origin}-${message.payload?.accountId}`;
const task = handleSwitchRequest(message.payload)
.then((result) => {
ACTIVE_REQUESTS.delete(key);
sendResponse(result);
})
.catch((error) => {
ACTIVE_REQUESTS.delete(key);
sendResponse({ error: error.message || 'Failed to switch account.' });
});
ACTIVE_REQUESTS.set(key, task);
return true; // Keep the message channel open for async work
}
if (message?.type === 'set-active-account') {
const { origin, accountId } = message.payload || {};
setActiveAccount(origin, accountId)
.then(() => sendResponse({ success: true }))
.catch((error) => sendResponse({ error: error.message || 'Unable to mark account active.' }));
return true;
}
if (message?.type === 'fetch-cookies') {
handleFetchCookiesRequest(message.payload)
.then((cookies) => sendResponse({ cookies }))
.catch((error) => sendResponse({ error: error.message || 'Unable to fetch cookies.' }));
return true;
}
if (message?.type === 'refresh-auto-update-alarm') {
autoUpdateEnabled = Boolean(message.payload?.enabled);
configureAutoUpdateAlarm();
if (autoUpdateEnabled) {
performAutoUpdateCheck();
}
sendResponse({ success: true });
return true;
}
return false;
});
async function handleSwitchRequest(payload = {}) {
const { origin, cookies } = payload;
if (!origin) {
throw new Error('Site origin missing. Save the site before switching.');
}
if (!Array.isArray(cookies) || !cookies.length) {
throw new Error('Account has no cookies to apply.');
}
const url = new URL(origin);
const domain = url.hostname;
AUTO_SYNC_SUSPEND.add(origin);
try {
await clearExistingCookies(domain);
await applyCookies(origin, cookies);
await reloadMatchingTabs(origin);
await setActiveAccount(origin, payload.accountId);
} finally {
AUTO_SYNC_SUSPEND.delete(origin);
}
return { success: true };
}
async function clearExistingCookies(domain) {
const existing = await chrome.cookies.getAll({ domain });
const tasks = existing.map((cookie) =>
chrome.cookies.remove(
(() => {
const details = {
name: cookie.name,
url: buildCookieUrl({
domain: cookie.domain || domain,
secure: cookie.secure,
path: cookie.path
})
};
if (cookie.storeId) {
details.storeId = cookie.storeId;
}
return details;
})()
)
);
await Promise.all(tasks);
}
async function applyCookies(origin, cookies) {
const originUrl = new URL(origin);
const tasks = cookies.map((cookie) => {
const cookieName = cookie.name || '';
const isHostCookie = Boolean(cookie.hostOnly) || cookieName.startsWith('__Host-');
const requiresSecure = cookieName.startsWith('__Host-') || cookieName.startsWith('__Secure-');
const secure = requiresSecure ? true : Boolean(cookie.secure ?? originUrl.protocol === 'https:');
const fallbackHost = originUrl.hostname;
const storedDomain = (cookie.domain || '').trim();
const normalizedHost = (isHostCookie ? storedDomain : storedDomain.replace(/^\./, '')) || fallbackHost;
const rawPath = cookie.path || '/';
const normalizedPath = isHostCookie ? '/' : rawPath.startsWith('/') ? rawPath : `/${rawPath}`;
const cookieUrl = buildCookieUrl({
domain: normalizedHost,
secure,
path: normalizedPath
});
const details = {
url: cookieUrl,
name: cookieName,
value: cookie.value,
path: normalizedPath,
secure,
httpOnly: Boolean(cookie.httpOnly)
};
if (!isHostCookie) {
details.domain = storedDomain || `.${fallbackHost}`;
}
if (cookie.storeId) {
details.storeId = cookie.storeId;
}
if (cookie.partitionKey) {
details.partitionKey = cookie.partitionKey;
}
if (cookie.sameSite) {
details.sameSite = cookie.sameSite;
}
if (cookie.priority) {
details.priority = cookie.priority;
}
if (cookie.expirationDate) {
details.expirationDate = cookie.expirationDate;
}
return chrome.cookies.set(details);
});
await Promise.all(tasks);
}
async function reloadMatchingTabs(origin) {
const url = new URL(origin);
const tabs = await chrome.tabs.query({});
const matches = tabs.filter((tab) => {
if (!tab.url) return false;
try {
const tabUrl = new URL(tab.url);
return tabUrl.hostname === url.hostname;
} catch (err) {
return false;
}
});
if (!matches.length) {
await chrome.tabs.create({ url: origin });
return;
}
await Promise.all(
matches
.filter((tab) => typeof tab.id === 'number')
.map((tab) => chrome.tabs.reload(tab.id))
);
}
function buildCookieUrl({ domain, secure, path }) {
const protocol = secure ? 'https:' : 'http:';
const cleanDomain = (domain || '').replace(/^\./, '');
const safePath = path && path.startsWith('/') ? path : '/';
return `${protocol}//${cleanDomain || 'localhost'}${safePath}`;
}
function bootstrapCaches() {
chrome.storage.local.get(
{ siteProfiles: {}, activeAccountMap: {}, autoUpdateEnabled: false, updateAvailableVersion: null },
(data) => {
siteProfilesCache = data.siteProfiles || {};
activeAccountMap = data.activeAccountMap || {};
autoUpdateEnabled = Boolean(data.autoUpdateEnabled);
updateAvailableVersion = data.updateAvailableVersion || null;
configureAutoUpdateAlarm();
refreshBadge();
}
);
}
function handleStorageChange(changes, area) {
if (area !== 'local') return;
if (changes.siteProfiles) {
siteProfilesCache = changes.siteProfiles.newValue || {};
}
if (changes.activeAccountMap) {
activeAccountMap = changes.activeAccountMap.newValue || {};
}
if (changes.autoUpdateEnabled) {
autoUpdateEnabled = Boolean(changes.autoUpdateEnabled.newValue);
configureAutoUpdateAlarm();
}
if (changes.updateAvailableVersion) {
updateAvailableVersion = changes.updateAvailableVersion.newValue || null;
refreshBadge();
}
}
async function handleFetchCookiesRequest(payload = {}) {
const origin = payload.origin;
if (!origin) {
throw new Error('Select or save a site first.');
}
const domain = new URL(origin).hostname;
const query = { domain };
if (payload.tabId) {
const storeId = await resolveStoreIdFromTab(payload.tabId);
if (storeId) {
query.storeId = storeId;
}
}
const cookies = await chrome.cookies.getAll(query);
return cookies.map((cookie) => serializeCookie(cookie));
}
async function resolveStoreIdFromTab(tabId) {
if (typeof tabId !== 'number') {
return null;
}
const stores = await chrome.cookies.getAllCookieStores();
const targetStore = stores.find((store) => Array.isArray(store.tabIds) && store.tabIds.includes(tabId));
return targetStore ? targetStore.id : null;
}
async function setActiveAccount(origin, accountId) {
if (!origin) {
return;
}
if (!accountId) {
const { [origin]: _removed, ...rest } = activeAccountMap;
activeAccountMap = rest;
} else {
activeAccountMap = { ...activeAccountMap, [origin]: { accountId } };
}
await chrome.storage.local.set({ activeAccountMap });
}
function handleCookieChange(changeInfo) {
const cookie = changeInfo.cookie;
if (!cookie || changeInfo.removed) return;
const affectedOrigins = Object.keys(siteProfilesCache).filter((origin) => {
try {
const siteHost = new URL(origin).hostname;
return matchesDomain(siteHost, cookie.domain);
} catch (err) {
return false;
}
});
affectedOrigins.forEach((origin) => {
if (AUTO_SYNC_SUSPEND.has(origin)) {
return;
}
const active = activeAccountMap[origin];
if (!active) return;
const site = siteProfilesCache[origin];
const account = site?.accounts?.find((acc) => acc.id === active.accountId);
if (!account || !account.autoSync) return;
scheduleAutoSync(origin, cookie.storeId);
});
}
function matchesDomain(hostname, cookieDomain = '') {
const domain = cookieDomain.replace(/^\./, '').toLowerCase();
const host = hostname.toLowerCase();
if (!domain) return false;
return host === domain || host.endsWith(`.${domain}`);
}
function scheduleAutoSync(origin, storeId) {
const key = `${origin}::${storeId || 'default'}`;
if (AUTO_SYNC_QUEUE.has(key)) {
return;
}
const job = autoSyncAccount(origin, storeId)
.catch(() => {})
.finally(() => {
AUTO_SYNC_QUEUE.delete(key);
});
AUTO_SYNC_QUEUE.set(key, job);
}
async function autoSyncAccount(origin, storeId) {
const site = siteProfilesCache[origin];
if (!site) return;
const host = new URL(origin).hostname;
const query = { domain: host };
if (storeId) {
query.storeId = storeId;
}
const cookies = await chrome.cookies.getAll(query);
const targetAccountId = selectAccountForUpdate(origin, site, cookies);
if (!targetAccountId) {
return;
}
const accountIndex = site.accounts?.findIndex((acc) => acc.id === targetAccountId);
if (accountIndex === undefined || accountIndex < 0) return;
const normalized = cookies.map((cookie) => serializeCookie(cookie));
site.accounts[accountIndex] = {
...site.accounts[accountIndex],
cookies: normalized,
updatedAt: Date.now()
};
siteProfilesCache[origin] = site;
await chrome.storage.local.set({ siteProfiles: siteProfilesCache });
}
function serializeCookie(cookie) {
const normalized = {
name: cookie.name,
value: cookie.value,
domain: cookie.domain,
path: cookie.path || '/',
secure: cookie.secure,
httpOnly: cookie.httpOnly,
hostOnly: cookie.hostOnly,
expirationDate: cookie.expirationDate,
sameSite: cookie.sameSite,
priority: cookie.priority,
storeId: cookie.storeId,
partitionKey: cookie.partitionKey,
session: cookie.session
};
Object.keys(normalized).forEach((key) => {
if (normalized[key] === undefined) {
delete normalized[key];
}
});
return normalized;
}
function configureAutoUpdateAlarm() {
chrome.alarms.clear(AUTO_UPDATE_ALARM, () => {
if (autoUpdateEnabled) {
chrome.alarms.create(AUTO_UPDATE_ALARM, {
delayInMinutes: 1,
periodInMinutes: AUTO_UPDATE_INTERVAL_MIN
});
}
});
}
async function performAutoUpdateCheck() {
if (!autoUpdateEnabled) {
return;
}
try {
const response = await fetch(REMOTE_MANIFEST_URL);
if (!response.ok) {
return;
}
const data = await response.json();
const remoteVersion = data.version;
if (!remoteVersion) {
return;
}
const comparison = compareVersions(remoteVersion, chrome.runtime.getManifest().version);
if (comparison > 0) {
await setUpdateAvailableVersion(remoteVersion);
} else {
await setUpdateAvailableVersion(null);
}
} catch (error) {
// ignore network errors during auto update checks
}
}
async function setUpdateAvailableVersion(version) {
const normalized = version || null;
if (normalized === updateAvailableVersion) {
return;
}
updateAvailableVersion = normalized;
await chrome.storage.local.set({ updateAvailableVersion: normalized });
refreshBadge();
}
function refreshBadge() {
if (updateAvailableVersion) {
chrome.action.setBadgeText({ text: 'UPD' });
chrome.action.setBadgeBackgroundColor({ color: '#dc2626' });
} else {
chrome.action.setBadgeText({ text: '' });
}
}
function compareVersions(a = '', b = '') {
const aParts = a.split('.').map((n) => parseInt(n, 10) || 0);
const bParts = b.split('.').map((n) => parseInt(n, 10) || 0);
const length = Math.max(aParts.length, bParts.length);
for (let i = 0; i < length; i += 1) {
const diff = (aParts[i] || 0) - (bParts[i] || 0);
if (diff !== 0) {
return diff > 0 ? 1 : -1;
}
}
return 0;
}
function selectAccountForUpdate(origin, site, currentCookies = []) {
const accounts = (site?.accounts || []).filter((acc) => acc.autoSync && Array.isArray(acc.cookies) && acc.cookies.length);
if (!accounts.length || !currentCookies.length) {
return null;
}
const active = activeAccountMap[origin];
const currentMap = new Map(
currentCookies.map((cookie) => [buildCookieKey(cookie), cookie.value])
);
let best = null;
accounts.forEach((account) => {
const { overlap, valueMatches, ratio, total } = scoreAccountCookies(account.cookies, currentMap);
const requiredMatches = Math.min(MIN_VALUE_MATCHES, total || 1);
const passesThreshold =
valueMatches >= requiredMatches || (valueMatches > 0 && ratio >= MIN_VALUE_MATCH_RATIO);
if (!passesThreshold && overlap < requiredMatches) {
return;
}
const score =
valueMatches * 3 +
overlap +
(active?.accountId === account.id ? 1 : 0);
if (!best || score > best.score) {
best = { accountId: account.id, score };
}
});
return best ? best.accountId : null;
}
function scoreAccountCookies(accountCookies = [], currentMap) {
let overlap = 0;
let valueMatches = 0;
accountCookies.forEach((cookie) => {
const key = buildCookieKey(cookie);
if (!currentMap.has(key)) {
return;
}
overlap += 1;
if (currentMap.get(key) === cookie.value) {
valueMatches += 1;
}
});
const total = accountCookies.length || 0;
const ratio = total ? valueMatches / total : 0;
return { overlap, valueMatches, ratio, total };
}
function buildCookieKey(cookie = {}) {
const domain = (cookie.domain || '').replace(/^\./, '').toLowerCase();
const path = (cookie.path || '/').trim() || '/';
return `${domain}|${path}|${cookie.name || ''}`;
}