-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbackground.js
More file actions
577 lines (525 loc) · 20.8 KB
/
Copy pathbackground.js
File metadata and controls
577 lines (525 loc) · 20.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
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
// MCP Auth Bridge - Background Service Worker
// Generic credential capture router driven by sites.json config
const NATIVE_HOST = "com.mcp.credentials";
// Sites config is loaded at startup and cached
let SITES = {};
// Load sites.json from the extension bundle
async function loadSitesConfig() {
try {
const url = chrome.runtime.getURL("sites.json");
const resp = await fetch(url);
const data = await resp.json();
SITES = data.sites || {};
console.log("[MCP Auth Bridge] Loaded config for sites:", Object.keys(SITES).join(", "));
} catch (e) {
console.error("[MCP Auth Bridge] Failed to load sites.json:", e);
}
}
// Initialize on startup
loadSitesConfig();
// ─── Domain Matching ────────────────────────────────────────────────────────
function findSiteByDomain(hostname) {
// Strip leading dot and www
const bare = hostname.replace(/^\./, "").replace(/^www\./, "");
for (const [key, site] of Object.entries(SITES)) {
for (const d of site.domains) {
const bareDomain = d.replace(/^www\./, "");
if (bare === bareDomain || bare.endsWith("." + bareDomain)) {
return { key, site };
}
}
}
return null;
}
// ─── Cookie Capture ─────────────────────────────────────────────────────────
async function captureCookies(siteKey, site, requestedDomain) {
// Collect cookies from all configured domains for this site
let allCookies = [];
const seen = new Set();
for (const domain of site.domains) {
// Try with dot prefix and without
for (const d of [domain, "." + domain, "www." + domain]) {
try {
const cookies = await chrome.cookies.getAll({ domain: d });
for (const c of cookies) {
const key = `${c.name}|${c.domain}`;
if (seen.has(key)) continue;
seen.add(key);
allCookies.push(c);
}
} catch (e) {}
}
}
if (allCookies.length === 0) {
return { success: false, error: `No cookies found for ${site.label}. Are you logged in?` };
}
// If site specifies required cookies, check for them
if (site.required_cookies && site.required_cookies.length > 0) {
const hasRequired = site.required_cookies.every(pattern => {
if (pattern.includes("*")) {
const prefix = pattern.replace("*", "");
return allCookies.some(c => c.name.startsWith(prefix));
}
return allCookies.some(c => c.name === pattern);
});
if (!hasRequired) {
return {
success: false,
error: `Auth cookies missing for ${site.label}. Log in first.`,
cookieCount: allCookies.length
};
}
}
// Filter to specific cookies if configured
let cookiesToSend = allCookies;
if (site.cookies && site.cookies.length > 0) {
cookiesToSend = allCookies.filter(c => site.cookies.includes(c.name));
if (cookiesToSend.length === 0) {
return {
success: false,
error: `Required cookies (${site.cookies.join(", ")}) not found for ${site.label}. Are you logged in?`,
cookieCount: allCookies.length
};
}
}
// Format based on output_format
let payload;
if (site.output_format === "cookie_editor") {
// Full cookie objects (Cookie-Editor compatible)
payload = {
site: siteKey,
output_format: site.output_format,
output_path: site.output_path,
cookies: cookiesToSend.map(c => ({
domain: c.domain,
expirationDate: c.expirationDate || null,
hostOnly: c.hostOnly || false,
httpOnly: c.httpOnly || false,
name: c.name,
path: c.path || "/",
sameSite: c.sameSite === "unspecified" ? null : c.sameSite,
secure: c.secure || false,
session: c.session || false,
storeId: c.storeId || null,
value: c.value
}))
};
} else {
// cookie_jar: simple name->value map
const cookieMap = {};
for (const c of cookiesToSend) {
cookieMap[c.name] = c.value;
}
payload = {
site: siteKey,
output_format: site.output_format || "cookie_jar",
output_path: site.output_path,
cookies: cookieMap,
domain: site.domains[0]
};
}
return new Promise(resolve => {
sendToNativeHost(payload, response => {
resolve({
success: true,
cookieCount: cookiesToSend.length,
domain: site.domains[0],
nativeResponse: response
});
});
});
}
// ─── Front Session Capture ──────────────────────────────────────────────────
//
// Front needs httpOnly session cookies (front.id / front.id.sig / front.csrf)
// AND page-context fields (cell, company, workspace_subdomain) that aren't in
// cookies. The cell + company are derivable from the active tab URL (Front's
// web app routes through https://app.frontapp.com/{cell}/...); the workspace
// subdomain is fetched via a same-origin call to /api/1/me.
//
// Multi-account: each save is keyed by a user-typed label (passed from popup
// via message.label). The native host upserts into a single front-sessions.json
// keyed by that label, so jumbo/xe coexist without overwriting each other.
async function captureFrontSession(siteKey, site, label, tabId) {
if (!label || typeof label !== "string" || !label.trim()) {
return { success: false, error: "Front session save requires a label (e.g. 'jumbo' or 'xe')." };
}
label = label.trim();
// 1. Collect httpOnly cookies via chrome.cookies (regular JS can't read these)
const wanted = site.session_cookies || ["front.id", "front.id.sig", "front.csrf"];
const cookieMap = {};
for (const domain of site.domains) {
for (const d of [domain, "." + domain]) {
try {
const cookies = await chrome.cookies.getAll({ domain: d });
for (const c of cookies) {
if (wanted.includes(c.name) && !(c.name in cookieMap)) {
cookieMap[c.name] = c.value;
}
}
} catch (e) {}
}
}
const missing = wanted.filter(n => !(n in cookieMap));
// front.id.sig is sometimes named differently across deployments; tolerate
// its absence but require front.id + front.csrf at minimum.
const required = site.required_cookies || ["front.id", "front.csrf"];
const reqMissing = required.filter(n => !(n in cookieMap));
if (reqMissing.length > 0) {
return {
success: false,
error: `Front session cookies missing (${reqMissing.join(", ")}). Open app.frontapp.com and sign in first.`
};
}
// 2. Run a page-context script to derive cell, company, workspace_subdomain,
// and the source URL. Same-origin fetch to /me lets us pick up the
// workspace metadata that isn't in the URL.
let pageContext = {};
try {
const results = await chrome.scripting.executeScript({
target: { tabId },
world: "MAIN",
func: async () => {
const url = window.location.href;
const debug = { discovery_methods_tried: [], discovery_method_used: null };
// ─── Cell discovery — try multiple methods ────────────────────────
// The user-facing URL usually doesn't include cell-NNNNN (those paths
// live under /inboxes/, /teammates/, etc.). Cell only appears in
// Front's internal API call URLs.
let cell = null;
// 1. URL path (cheap, covers the rare cell-prefixed user URL)
debug.discovery_methods_tried.push("location.href");
const urlMatch = url.match(/app\.frontapp\.com\/(cell-[a-zA-Z0-9_-]+)/);
if (urlMatch) {
cell = urlMatch[1];
debug.discovery_method_used = "location.href";
}
// 2. Performance entries — Front's web app HAS made API calls to
// cell-prefixed URLs by the time the user clicks Save. Walking the
// resource buffer finds them reliably.
if (!cell) {
debug.discovery_methods_tried.push("performance.getEntriesByType");
try {
const entries = performance.getEntriesByType("resource") || [];
for (const e of entries) {
const m = e.name && e.name.match(/app\.frontapp\.com\/(cell-[a-zA-Z0-9_-]+)/);
if (m) {
cell = m[1];
debug.discovery_method_used = "performance.getEntriesByType";
debug.discovery_match_url_sample = e.name.slice(0, 120);
break;
}
}
} catch (e) {}
}
// 3. Probe /api/1/me without cell prefix — Front may redirect to the
// cell-prefixed path. Read the Location header.
if (!cell) {
debug.discovery_methods_tried.push("redirect_probe");
try {
const probe = await fetch("/api/1/me", {
credentials: "include",
redirect: "manual",
headers: { "accept": "application/json" }
});
// Manual redirect surfaces 0-status with type='opaqueredirect' OR keeps the 3xx
const loc = probe.headers && probe.headers.get && probe.headers.get("location");
if (loc) {
const m = loc.match(/\/(cell-[a-zA-Z0-9_-]+)\//);
if (m) {
cell = m[1];
debug.discovery_method_used = "redirect_probe";
}
}
} catch (e) {}
}
// 4. Look in HTML meta tags or script src URLs (last resort)
if (!cell) {
debug.discovery_methods_tried.push("script_src_scan");
try {
for (const s of document.querySelectorAll("script[src], link[href]")) {
const u = s.src || s.href || "";
const m = u.match(/\/(cell-[a-zA-Z0-9_-]+)\//);
if (m) {
cell = m[1];
debug.discovery_method_used = "script_src_scan";
break;
}
}
} catch (e) {}
}
// ─── Company discovery ────────────────────────────────────────────
// Try URL first (only present inside conversations), then /me probe.
let company = null;
const compInUrl = url.match(/\/companies\/([a-f0-9]{16,64})/i);
if (compInUrl) company = compInUrl[1];
let workspace_subdomain = null;
let me_raw = null;
if (cell) {
try {
const meResp = await fetch(`/${cell}/api/1/me`, {
credentials: "include",
headers: { "accept": "application/json" }
});
if (meResp.ok) {
const meData = await meResp.json();
me_raw = meData;
if (!company) {
company =
meData.company_id ||
meData.companyId ||
meData.company ||
(meData.user && (meData.user.company_id || meData.user.companyId)) ||
(meData.workspace && (meData.workspace.company_id || meData.workspace.id)) ||
null;
}
workspace_subdomain =
meData.workspace_subdomain ||
meData.subdomain ||
(meData.workspace && meData.workspace.subdomain) ||
(meData.company && meData.company.subdomain) ||
null;
}
} catch (e) {}
}
// Fallback: scan performance entries for /companies/<hex>/ paths
if (!company) {
try {
const entries = performance.getEntriesByType("resource") || [];
for (const e of entries) {
const m = e.name && e.name.match(/\/companies\/([a-f0-9]{16,64})\//i);
if (m) {
company = m[1];
break;
}
}
} catch (e) {}
}
return {
cell,
company,
workspace_subdomain,
saved_from_url: url,
me_preview: me_raw ? JSON.stringify(me_raw).slice(0, 600) : null,
debug
};
}
});
if (results && results[0] && results[0].result) {
pageContext = results[0].result;
}
} catch (e) {
// executeScript can fail if the active tab isn't on app.frontapp.com
return {
success: false,
error: `Couldn't read Front page context: ${e.message || e}. Open app.frontapp.com in the active tab and try again.`
};
}
if (!pageContext.cell) {
const tried = (pageContext.debug && pageContext.debug.discovery_methods_tried) || [];
return {
success: false,
error:
"Couldn't auto-detect Front cell. Tried: " + tried.join(", ") + ". " +
"If you're on a fresh tab that hasn't loaded any API calls yet, try " +
"clicking into a conversation (any thread) and saving again. The cell " +
"is only in Front's internal XHR URLs.",
debug: pageContext.debug
};
}
// 3. Build payload. xsrf equals the front.csrf cookie value — captured
// explicitly so the contract is stable even if Front changes derivation.
const payload = {
site: siteKey,
output_format: site.output_format,
output_path: site.output_path,
label: label,
session: {
cookies: cookieMap,
xsrf: cookieMap["front.csrf"] || null,
cell: pageContext.cell,
company: pageContext.company,
workspace_subdomain: pageContext.workspace_subdomain,
saved_from_url: pageContext.saved_from_url
}
};
return new Promise(resolve => {
sendToNativeHost(payload, response => {
resolve({
success: true,
label: label,
cookieCount: Object.keys(cookieMap).length,
cell: pageContext.cell,
company: pageContext.company,
workspace_subdomain: pageContext.workspace_subdomain,
missing_optional_cookies: missing.filter(n => !required.includes(n)),
debug: pageContext.debug,
nativeResponse: response
});
});
});
}
// ─── Bearer Token Handling ──────────────────────────────────────────────────
function handleBearerToken(siteKey, site, data) {
return new Promise(resolve => {
if (!data.at || !data.at.startsWith("eyJ")) {
resolve({ success: false, error: "No valid bearer token received" });
return;
}
const payload = {
site: siteKey,
output_format: site.output_format,
output_path: site.output_path,
access_token: data.at,
refresh_token: data.rt || null,
extra_fields: {},
credential_type: site.credential_type || siteKey
};
// Include any extra fields (like cartId)
if (site.extra_fields) {
for (const [field, _config] of Object.entries(site.extra_fields)) {
if (data[field] !== undefined) {
payload.extra_fields[field] = data[field];
}
}
}
// Pass dotenv config if present
if (site.dotenv_mapping) payload.dotenv_mapping = site.dotenv_mapping;
if (site.dotenv_defaults) payload.dotenv_defaults = site.dotenv_defaults;
if (site.credential_file) payload.credential_file = site.credential_file;
sendToNativeHost(payload, response => {
resolve({
success: true,
tokenLength: data.at.length,
hasExtra: Object.keys(payload.extra_fields).length > 0,
nativeResponse: response
});
});
});
}
// ─── Native Messaging ───────────────────────────────────────────────────────
function sendToNativeHost(message, callback) {
try {
chrome.runtime.sendNativeMessage(NATIVE_HOST, message, response => {
if (chrome.runtime.lastError) {
console.error("[MCP Auth Bridge] Native host error:", chrome.runtime.lastError.message);
callback({ success: false, error: chrome.runtime.lastError.message });
} else {
callback(response || { success: true });
}
});
} catch (e) {
console.error("[MCP Auth Bridge] Native messaging exception:", e);
callback({ success: false, error: e.message });
}
}
// ─── Message Listener ───────────────────────────────────────────────────────
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
// Generic save request from popup
if (message.type === "SAVE_SITE") {
const siteKey = message.siteKey;
const site = SITES[siteKey];
if (!site) {
sendResponse({ success: false, error: `Unknown site: ${siteKey}` });
return true;
}
if (site.capture_method === "cookies") {
captureCookies(siteKey, site, message.domain).then(result => {
// Store last capture info
const storageData = {};
storageData[`${siteKey}_last_capture`] = Date.now();
storageData[`${siteKey}_cookie_count`] = result.cookieCount || 0;
storageData[`${siteKey}_save_result`] = result;
chrome.storage.local.set(storageData);
sendResponse(result);
});
return true;
}
if (site.capture_method === "front_session") {
// Need active tab id for page-context script execution
chrome.tabs.query({ active: true, currentWindow: true }, async tabs => {
const tab = tabs && tabs[0];
if (!tab || !tab.id) {
sendResponse({ success: false, error: "No active tab found." });
return;
}
// Verify the active tab is on Front before running anything
const tabUrl = tab.url || "";
const onFront = site.domains.some(d => tabUrl.includes(d));
if (!onFront) {
sendResponse({ success: false, error: `Active tab isn't on ${site.label}. Open app.frontapp.com and try again.` });
return;
}
const result = await captureFrontSession(siteKey, site, message.label, tab.id);
const storageData = {};
storageData[`${siteKey}_last_capture`] = Date.now();
storageData[`${siteKey}_cookie_count`] = result.cookieCount || 0;
storageData[`${siteKey}_last_label`] = message.label || null;
storageData[`${siteKey}_last_cell`] = result.cell || null;
storageData[`${siteKey}_save_result`] = result;
chrome.storage.local.set(storageData);
sendResponse(result);
});
return true;
}
if (site.capture_method === "bearer_intercept" || site.capture_method === "firebase_idtoken") {
// Both methods produce the same payload shape; route through handleBearerToken.
if (message.tokenData) {
handleBearerToken(siteKey, site, message.tokenData).then(result => {
const storageData = {};
storageData[`${siteKey}_last_capture`] = Date.now();
storageData[`${siteKey}_token_length`] = message.tokenData.at ? message.tokenData.at.length : 0;
storageData[`${siteKey}_save_result`] = result;
// Store extra fields info
if (site.extra_fields) {
for (const field of Object.keys(site.extra_fields)) {
storageData[`${siteKey}_has_${field}`] = !!message.tokenData[field];
}
}
chrome.storage.local.set(storageData);
sendResponse(result);
});
} else {
const hint = site.capture_method === "firebase_idtoken"
? `Open ${site.label} in a tab and make sure you're logged in.`
: `Browse ${site.label} first.`;
sendResponse({ success: false, error: `No token data. ${hint}` });
}
return true;
}
sendResponse({ success: false, error: `Unknown capture method: ${site.capture_method}` });
return true;
}
// Token relay from content script bridge
if (message.type === "BEARER_TOKEN") {
const siteKey = message.siteKey;
const site = SITES[siteKey];
if (!site) return;
handleBearerToken(siteKey, site, message.data).then(result => {
const storageData = {};
storageData[`${siteKey}_last_capture`] = Date.now();
storageData[`${siteKey}_token_length`] = message.data.at ? message.data.at.length : 0;
storageData[`${siteKey}_save_result`] = result;
if (site.extra_fields) {
for (const field of Object.keys(site.extra_fields)) {
storageData[`${siteKey}_has_${field}`] = !!message.data[field];
}
}
chrome.storage.local.set(storageData);
sendResponse(result);
});
return true;
}
// Get status for all sites
if (message.type === "GET_STATUS") {
chrome.storage.local.get(null, data => {
sendResponse({ stored: data, sites: SITES });
});
return true;
}
// Get sites config
if (message.type === "GET_SITES") {
sendResponse({ sites: SITES });
return true;
}
});