forked from uptechteam/default.wtf
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice-worker.js
More file actions
327 lines (283 loc) · 10.3 KB
/
Copy pathservice-worker.js
File metadata and controls
327 lines (283 loc) · 10.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
// Service Worker for Default Account+ for Google (Manifest V3)
import { buildRedirectRules } from './redirect-rules.js';
// ============================================================
// Storage Helper Class
// ============================================================
class SyncStorage {
static store(obj, callback) {
chrome.storage.sync.set(obj, callback);
}
static get(key, callback) {
chrome.storage.sync.get(key, callback);
}
static async getAsync(key) {
return new Promise((resolve) => {
chrome.storage.sync.get(key, resolve);
});
}
static async storeAsync(obj) {
return new Promise((resolve) => {
chrome.storage.sync.set(obj, resolve);
});
}
}
// ============================================================
// Google Service URL Detection
// ============================================================
// Full list of Google Services subdomains - https://gist.github.com/abuvanth/b9fcbaf7c77c2954f96c6e556138ffe8
function isGoogleServiceUrl(url) {
return (
/^https?:\/\/[^?&]*(?:mail|drive|calendar|meet|docs|admin|photos|translate|keep|hangouts|chat|workspace|maps|news|ads|ediscovery|jamboard|earth|podcasts|classroom|business|myaccount|adsense|cloud|adwords|analytics|firebase|play|voice|tagmanager|duo|datastudio|optimize|merchants|finance|colab\.research|contacts|script|messages|search|stadia|developers|one|chrome|books|sites|groups|gemini|notebooklm|aistudio)\.google\.co.*/i.test(
url
) ||
// test several services that switched from the pattern "https://maps.google.com" -> https://www.google.com/maps
/^https?:\/\/(www\.)?google\.co(?:m|\.[a-z]{2,3})\/(?:maps|finance|travel|flights)/i.test(
url
)
);
}
function isAnyGoogleUrl(url) {
return /^https?:\/\/([^?&]*\.)?google\.co.*/i.test(url);
}
// ============================================================
// URL Conversion
// ============================================================
// converts the "originalUrl" to the redirectUrl
// if defaultAccount is the same as in "?authuser={num}" or "/u/{num}" - returns null (meaning no need for redirect)
function convertToRedirectUrl(originalUrl, defaultAccount) {
try {
const url = new URL(originalUrl);
const params = new URLSearchParams(url.search);
// check if current user is not the same (?authuser={num} or /u/{num}/)
if (`${params.get('authuser')}` === `${defaultAccount}`) return null;
const uMatch = originalUrl.match(/\/u\/(\d+)\/?/i);
if (uMatch && uMatch[1] && `${uMatch[1]}` === `${defaultAccount}`)
return null;
// current user is different, change
params.delete('authuser');
params.set('authuser', defaultAccount);
url.search = params.toString();
return url.toString();
} catch {
return null;
}
}
function redirectCurrentTab(defaultAccount) {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
if (tabs && tabs[0] && isGoogleServiceUrl(tabs[0].url)) {
const url = convertToRedirectUrl(tabs[0].url, defaultAccount);
if (url) {
chrome.tabs.update(tabs[0].id, { url });
}
}
});
}
// ============================================================
// Offscreen Document Management for Parsing
// ============================================================
let creatingOffscreen = null;
async function ensureOffscreenDocument() {
const existingContexts = await chrome.runtime.getContexts({
contextTypes: ['OFFSCREEN_DOCUMENT'],
documentUrls: [chrome.runtime.getURL('offscreen.html')]
});
if (existingContexts.length > 0) {
return;
}
if (creatingOffscreen) {
await creatingOffscreen;
return;
}
creatingOffscreen = chrome.offscreen.createDocument({
url: 'offscreen.html',
reasons: ['DOM_PARSER'],
justification: 'Parse Google accounts response which requires DOMParser'
});
await creatingOffscreen;
creatingOffscreen = null;
}
async function parseAccountsWithOffscreen(rawText) {
await ensureOffscreenDocument();
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage({ type: 'parse_accounts', rawText }, (response) => {
if (chrome.runtime.lastError) {
reject(new Error(chrome.runtime.lastError.message));
return;
}
if (response.error) {
reject(new Error(response.error));
return;
}
resolve(response.result);
});
});
}
// ============================================================
// Declarative Net Request Rules Management
// ============================================================
// We use dynamic rules to redirect Google service URLs to include the correct authuser parameter
// This replaces the webRequest.onBeforeRequest blocking listener from MV2
const RULE_ID_BASE = 1000;
const MAX_RULES = 100;
let isUpdatingRules = false;
async function updateRedirectRules() {
if (isUpdatingRules) return;
isUpdatingRules = true;
try {
const data = await SyncStorage.getAsync(['defaultAccount', 'rules', 'accounts']);
const newRules = buildRedirectRules({
defaultAccount: data.defaultAccount ?? 0,
customRules: data.rules ?? [],
accounts: data.accounts ?? [],
ruleIdBase: RULE_ID_BASE
});
const existingRules = await chrome.declarativeNetRequest.getDynamicRules();
const existingRuleIds = existingRules.map(rule => rule.id);
await chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: existingRuleIds,
addRules: newRules.slice(0, MAX_RULES)
});
console.log(`Updated ${newRules.length} redirect rules`);
} finally {
isUpdatingRules = false;
}
}
// ============================================================
// Installation and Storage Change Handlers
// ============================================================
chrome.runtime.onInstalled.addListener(function (details) {
if (details.reason === 'install') {
SyncStorage.get('rules', (data) => {
if (data.rules === undefined) {
SyncStorage.store({ rules: [] });
}
});
SyncStorage.get('defaultAccount', (data) => {
if (data.defaultAccount === undefined) {
SyncStorage.store({ defaultAccount: 0 });
}
});
}
// Update rules on install/update
updateRedirectRules();
});
// Listen for storage changes and update rules accordingly
chrome.storage.onChanged.addListener(function (changes, namespace) {
if (namespace === 'sync') {
if ('defaultAccount' in changes || 'rules' in changes || 'accounts' in changes) {
updateRedirectRules();
}
}
});
// ============================================================
// Message Handling
// ============================================================
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message === 'fetch_google_accounts') {
const url =
'https://accounts.google.com/ListAccounts?gpsia=1&source=ogb&mo=1&origin=https://accounts.google.com';
fetch(url)
.then((response) => response.text())
.then(async (rawText) => {
try {
// Use offscreen document for parsing
const result = await parseAccountsWithOffscreen(rawText);
sendResponse(result);
} catch (error) {
console.error('Failed to parse accounts:', error);
// Fallback: try regex-based parsing
try {
const match = rawText.match(/<script>.*?'([^']+)'.*?<\/script>/s);
if (match && match[1]) {
const decoded = match[1]
.replace(/\\x([0-9a-fA-F]{2})/g, (m, p) =>
String.fromCharCode(parseInt(p, 16))
)
.replace(/\\\//g, '/')
.replace(/\\n/g, '');
sendResponse(JSON.parse(decoded));
} else {
sendResponse([]);
}
} catch {
sendResponse([]);
}
}
})
.catch((error) => {
console.error('Failed to fetch accounts:', error);
sendResponse([]);
});
return true; // Keep the message channel open for async response
}
});
// ============================================================
// Tab Navigation Handler
// ============================================================
// Handle new tabs opened to Google services
chrome.tabs.onCreated.addListener(async (tab) => {
const url = tab.pendingUrl || tab.url;
if (!url || !isGoogleServiceUrl(url)) return;
const data = await SyncStorage.getAsync(['defaultAccount', 'rules', 'accounts']);
const defaultAccount = data.defaultAccount ?? 0;
const customRules = data.rules ?? [];
const accounts = data.accounts ?? [];
// Check if URL already has authuser
if (url.toLowerCase().includes('authuser') || /\/u\/\d+/i.test(url)) {
return;
}
// Determine which account to use
let accountId = defaultAccount;
for (const rule of customRules) {
const reg = new RegExp(
`^https?://[^?&]*${rule.serviceName.toLowerCase()}\\.google\\.co.*`,
'is'
);
if (reg.test(url)) {
accountId = rule.accountId;
break;
}
}
// Skip if account 0 or not logged in
if (accountId === 0 || !accounts[accountId]?.isLoggedIn) {
return;
}
// Check if opened from another Google page
if (tab.openerTabId) {
try {
const openerTab = await chrome.tabs.get(tab.openerTabId);
if (openerTab && isAnyGoogleUrl(openerTab.url)) {
return; // Don't redirect if opened from Google
}
} catch {
// Opener tab may not exist
}
}
const redirectUrl = convertToRedirectUrl(url, accountId);
if (redirectUrl) {
chrome.tabs.update(tab.id, { url: redirectUrl });
}
});
// ============================================================
// Keyboard Shortcuts Handler
// ============================================================
chrome.commands.onCommand.addListener((command) => {
if (command?.indexOf('switch_to_ga_') >= 0) {
try {
const accNum = parseInt(command.charAt(command.length - 1)) - 1;
SyncStorage.get('accounts', (data) => {
// redirect only if accNum is not > than total number of accounts
if (data.accounts && data.accounts.length > accNum) {
redirectCurrentTab(accNum);
}
});
} catch {
// Ignore errors
}
}
});
// ============================================================
// Service Worker Startup
// ============================================================
// Initialize rules when service worker starts
updateRedirectRules();