mirror of
https://github.com/garrytan/gstack.git
synced 2026-10-05 02:47:17 +02:00
v1.90.0.0 feat: make browser cookie imports explicit and safe (#2964)
* fix(browse): prepare reliable cookie import wave for validation * ci: sequence quality and behavior for validation branch * fix(browse): isolate Windows qualification and preserve native diagnostics * test(browse): cover cookie workflow quality and isolate Windows user paths * test(browse): trace native member startup and initialize fresh folders * fix(browse): keep Windows member stdin alive through EOF * fix(browse): latch native timeouts and compare contained Edge startup * test(browse): verify native version metadata and actual Windows argv * test(browse): qualify Dia import on isolated macOS CI * fix(browse): require picker origin for session mutations * fix(browse): bound credential reads through stream completion * test(browse): inspect owned Windows process arguments natively * test(evals): preserve passing coverage during cookie repair reruns * test(browse): isolate Dia qualification in a fresh macOS account * test(browse): pass bounded integer timeouts to native Mac probes * test(browse): distinguish Windows profile initialization from containment * test(browse): await descendant pipe readiness before parent exit * test(browse): initialize and restore isolated macOS Keychain state * test(browse): initialize Windows fixture folders before qualification * test(ci): pin the same Node runtime across Windows checks * test(browse): distinguish native macOS browser preflight stages * test(browse): isolate Windows descendant console lifetime * test(browse): preserve native receipts and identify fixture lock holders * test(browse): prepare dependency resolution before native Mac worker startup * test(ci): include lock and close checks in native diagnostics * test(browse): preserve native owner probe stages and subprocess deadlines * fix(browse): classify Chromium profile-in-use exit precisely * test(browse): retain Mac qualification evidence through cleanup failures * test(browse): bound Mac fixture paths and retire its owned user domain * test(browse): accept vanished fixture entries without weakening cleanup * test(browse): identify probe-created macOS user domains safely * test(browse): observe Mac user domains without targeting them first * test(browse): use passive fresh-user ownership throughout Mac qualification * test(browse): distinguish profile and registered-home Keychain lookups * test(browse): qualify Dia under one registered account home * test(browse): identify Dia startup and owned process-group failures * test(browse): classify bounded Dia startup diagnostics without leaking output * fix(test): preserve native Mac sandboxing and reap owned browser children * fix(browse): preserve Chromium sandboxing for native profile imports * test(browse): inspect signed Mach-O architecture without launching Xcode tools * test(browse): sample pending Dia startup and reap on all cleanup paths * test(browse): compare protected Dia launches in fresh Bun and Node accounts * test(browse): inspect isolated Mac GUI readiness without browser access * v1.90.0.0 fix: bind cookie picker actions to their document * test: validate cookie guards and fit nested launch fixtures * ci: configure the bundled Chromium sandbox helper * fix(browse): classify Playwright authentication timeouts * test: retain bounded Windows lifecycle diagnostics * test(cso): reuse bounded NTFS precision candidates * test(review): handle explicit preservation choices safely * test(browse): remove owned fixture directories with explicit primitives * test(review): distinguish descriptive reuse from edit commitments * test: admit only the approved unscored cookie workflow refusal * test: keep the Office Hours judge mock export-complete * fix: keep dependency-free CI planners independent of the model SDK * test: observe the exact holder after a native fixture unlink failure * fix: start seeded PTY observations at owned readiness * test: acquire identity-bound Windows deletion admission before profile resets * test: preserve qualified Git index bits without authorizing mutations
This commit is contained in:
1 parent
730a1017d1
commit
a84b0b5b6d
111 files changed
+14996
-1057
No files matched your search
@@ -19,24 +19,34 @@
|
||||
|
||||
import * as crypto from 'crypto';
|
||||
import type { BrowserManager } from './browser-manager';
|
||||
import { findInstalledBrowsers, listProfiles, listDomains, importCookies, importCookiesViaCdp, hasV20Cookies, CookieImportError, type PlaywrightCookie } from './cookie-import-browser';
|
||||
import { findInstalledBrowsers, listDomains, withCookieReadRetry, CookieImportError } from './cookie-import-browser';
|
||||
import { getCookiePickerHTML } from './cookie-picker-ui';
|
||||
import { getCookieProfiles, runCookieImport, type CookieImportTarget } from './cookie-import-operation';
|
||||
import { validateCookieStorageSupport } from './cookie-auth-verification';
|
||||
|
||||
// ─── Auth State ─────────────────────────────────────────────────
|
||||
// One-time codes for the cookie picker UI (code → expiry timestamp).
|
||||
// Codes are generated by generatePickerCode() and consumed on first use.
|
||||
const pendingCodes = new Map<string, number>();
|
||||
const CODE_TTL_MS = 30_000; // 30 seconds
|
||||
interface PickerContext {
|
||||
target?: CookieImportTarget;
|
||||
browser?: string;
|
||||
profile?: string;
|
||||
clearStorage?: boolean;
|
||||
verifyAuth?: boolean;
|
||||
}
|
||||
|
||||
const pendingCodes = new Map<string, PickerContext & { expiry: number }>();
|
||||
const CODE_TTL_MS = 5 * 60_000;
|
||||
|
||||
// Session cookies for authenticated picker access (session → expiry timestamp).
|
||||
// Sessions are created after a valid code exchange and last 1 hour.
|
||||
const validSessions = new Map<string, number>();
|
||||
const validSessions = new Map<string, PickerContext & { expiry: number; pickerInstance: string }>();
|
||||
const SESSION_TTL_MS = 3_600_000; // 1 hour
|
||||
|
||||
/** Generate a one-time code for opening the cookie picker UI. */
|
||||
export function generatePickerCode(): string {
|
||||
export function generatePickerCode(context: PickerContext = {}): string {
|
||||
const code = crypto.randomUUID();
|
||||
pendingCodes.set(code, Date.now() + CODE_TTL_MS);
|
||||
pendingCodes.set(code, { ...context, expiry: Date.now() + CODE_TTL_MS });
|
||||
return code;
|
||||
}
|
||||
|
||||
@@ -44,13 +54,13 @@ export function generatePickerCode(): string {
|
||||
export function hasActivePicker(): boolean {
|
||||
const now = Date.now();
|
||||
|
||||
for (const [code, expiry] of pendingCodes) {
|
||||
if (expiry > now) return true;
|
||||
for (const [code, context] of pendingCodes) {
|
||||
if (context.expiry > now) return true;
|
||||
pendingCodes.delete(code);
|
||||
}
|
||||
|
||||
for (const [session, expiry] of validSessions) {
|
||||
if (expiry > now) return true;
|
||||
for (const [session, context] of validSessions) {
|
||||
if (context.expiry > now) return true;
|
||||
validSessions.delete(session);
|
||||
}
|
||||
|
||||
@@ -67,9 +77,9 @@ function getSessionFromCookie(req: Request): string | null {
|
||||
|
||||
/** Check if a session cookie value is valid and not expired. */
|
||||
function isValidSession(session: string): boolean {
|
||||
const expiry = validSessions.get(session);
|
||||
if (!expiry) return false;
|
||||
if (Date.now() > expiry) { validSessions.delete(session); return false; }
|
||||
const context = validSessions.get(session);
|
||||
if (!context) return false;
|
||||
if (Date.now() >= context.expiry) { validSessions.delete(session); return false; }
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -121,7 +131,7 @@ export async function handleCookiePickerRoute(
|
||||
headers: {
|
||||
'Access-Control-Allow-Origin': corsOrigin(port),
|
||||
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
|
||||
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
|
||||
'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-Gstack-Picker-Instance',
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -133,8 +143,8 @@ export async function handleCookiePickerRoute(
|
||||
|
||||
// Code exchange: validate one-time code, set session cookie, redirect
|
||||
if (code) {
|
||||
const expiry = pendingCodes.get(code);
|
||||
if (!expiry || Date.now() > expiry) {
|
||||
const context = pendingCodes.get(code);
|
||||
if (!context || Date.now() >= context.expiry) {
|
||||
pendingCodes.delete(code);
|
||||
return new Response('Invalid or expired code. Re-run cookie-import-browser.', {
|
||||
status: 403,
|
||||
@@ -143,7 +153,7 @@ export async function handleCookiePickerRoute(
|
||||
}
|
||||
pendingCodes.delete(code); // one-time use
|
||||
const session = crypto.randomUUID();
|
||||
validSessions.set(session, Date.now() + SESSION_TTL_MS);
|
||||
validSessions.set(session, { ...context, expiry: Date.now() + SESSION_TTL_MS, pickerInstance: crypto.randomUUID() });
|
||||
return new Response(null, {
|
||||
status: 302,
|
||||
headers: {
|
||||
@@ -157,7 +167,26 @@ export async function handleCookiePickerRoute(
|
||||
// Session cookie: serve HTML (no auth token inlined)
|
||||
const session = getSessionFromCookie(req);
|
||||
if (session && isValidSession(session)) {
|
||||
const html = getCookiePickerHTML(port);
|
||||
const context = validSessions.get(session)!;
|
||||
let targetOrigin: string | undefined;
|
||||
let storageResetAvailable = false;
|
||||
try {
|
||||
const url = new URL(context.target?.url ?? '');
|
||||
if (['http:', 'https:'].includes(url.protocol)) targetOrigin = url.origin;
|
||||
} catch {}
|
||||
if (context.target) {
|
||||
try { validateCookieStorageSupport(context.target.page); storageResetAvailable = true; } catch {}
|
||||
}
|
||||
const html = getCookiePickerHTML(port, {
|
||||
pickerInstance: context.pickerInstance,
|
||||
browser: context.browser,
|
||||
profile: context.profile,
|
||||
clearStorage: context.clearStorage,
|
||||
verifyAuth: context.verifyAuth,
|
||||
targetOrigin,
|
||||
storageResetAvailable,
|
||||
verificationAvailable: !!process.env.GSTACK_COOKIE_AUTH_SELECTOR?.trim() && !!process.env.GSTACK_COOKIE_AUTH_EXPECTED_IDENTITY?.trim(),
|
||||
});
|
||||
return new Response(html, {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'text/html; charset=utf-8' },
|
||||
@@ -182,6 +211,13 @@ export async function handleCookiePickerRoute(
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
if (req.method === 'POST' && !hasBearer && req.headers.get('origin') !== url.origin) {
|
||||
return errorResponse('Cookie picker mutations require a same-origin request.', 'invalid_origin', { port, status: 403 });
|
||||
}
|
||||
const pickerContext = !hasBearer && hasSession ? validSessions.get(sessionId!)! : undefined;
|
||||
if (pickerContext && req.headers.get('X-Gstack-Picker-Instance') !== pickerContext.pickerInstance) {
|
||||
return errorResponse('This picker no longer matches the active picker session. Reopen the picker from the intended page before continuing.', 'picker_changed', { port, status: 403 });
|
||||
}
|
||||
|
||||
// GET /cookie-picker/browsers — list installed browsers
|
||||
if (pathname === '/cookie-picker/browsers' && req.method === 'GET') {
|
||||
@@ -200,8 +236,9 @@ export async function handleCookiePickerRoute(
|
||||
if (!browserName) {
|
||||
return errorResponse("Missing 'browser' parameter", 'missing_param', { port });
|
||||
}
|
||||
const profiles = listProfiles(browserName);
|
||||
return jsonResponse({ profiles }, { port });
|
||||
let hostname: string | undefined;
|
||||
try { hostname = new URL(pickerContext?.target?.url ?? '').hostname || undefined; } catch {}
|
||||
return jsonResponse(await getCookieProfiles(browserName, [], hostname), { port });
|
||||
}
|
||||
|
||||
// GET /cookie-picker/domains?browser=<name>&profile=<profile> — list domains + counts
|
||||
@@ -211,7 +248,7 @@ export async function handleCookiePickerRoute(
|
||||
return errorResponse("Missing 'browser' parameter", 'missing_param', { port });
|
||||
}
|
||||
const profile = url.searchParams.get('profile') || 'Default';
|
||||
const result = listDomains(browserName, profile);
|
||||
const result = await withCookieReadRetry(() => listDomains(browserName, profile));
|
||||
return jsonResponse({
|
||||
browser: result.browser,
|
||||
domains: result.domains,
|
||||
@@ -227,61 +264,27 @@ export async function handleCookiePickerRoute(
|
||||
return errorResponse('Invalid JSON body', 'bad_request', { port });
|
||||
}
|
||||
|
||||
const { browser, domains, profile } = body;
|
||||
const { browser, domains, profile, clearStorage, verifyAuth } = body ?? {};
|
||||
if (!browser) return errorResponse("Missing 'browser' field", 'missing_param', { port });
|
||||
if (!domains || !Array.isArray(domains) || domains.length === 0) {
|
||||
return errorResponse("Missing or empty 'domains' array", 'missing_param', { port });
|
||||
}
|
||||
|
||||
// Decrypt cookies from the browser DB
|
||||
const selectedProfile = profile || 'Default';
|
||||
let result = await importCookies(browser, domains, selectedProfile);
|
||||
|
||||
// If all cookies failed and v20 encryption is detected, try CDP extraction
|
||||
if (result.cookies.length === 0 && result.failed > 0 && hasV20Cookies(browser, selectedProfile)) {
|
||||
console.log(`[cookie-picker] v20 App-Bound Encryption detected, trying CDP extraction...`);
|
||||
try {
|
||||
result = await importCookiesViaCdp(browser, domains, selectedProfile);
|
||||
} catch (cdpErr: any) {
|
||||
console.log(`[cookie-picker] CDP fallback failed: ${cdpErr.message}`);
|
||||
return jsonResponse({
|
||||
imported: 0,
|
||||
failed: result.failed,
|
||||
domainCounts: {},
|
||||
message: `Cookies use App-Bound Encryption (v20). Close ${browser}, retry, or use /connect-chrome to browse with your real browser directly.`,
|
||||
code: 'v20_encryption',
|
||||
}, { port });
|
||||
}
|
||||
}
|
||||
|
||||
if (result.cookies.length === 0) {
|
||||
return jsonResponse({
|
||||
imported: 0,
|
||||
failed: result.failed,
|
||||
domainCounts: {},
|
||||
message: result.failed > 0
|
||||
? `All ${result.failed} cookies failed to decrypt`
|
||||
: 'No cookies found for the specified domains',
|
||||
}, { port });
|
||||
}
|
||||
|
||||
// Add to Playwright context
|
||||
const page = bm.getActiveSession().getPage();
|
||||
await page.context().addCookies(result.cookies);
|
||||
|
||||
// Track what was imported
|
||||
const page = pickerContext?.target?.page ?? bm.getActiveSession().getPage();
|
||||
const target = pickerContext?.target ?? { page, url: page.url() };
|
||||
const result = await runCookieImport({
|
||||
browser, domains, profile,
|
||||
clearStorage: clearStorage ?? pickerContext?.clearStorage ?? false,
|
||||
verifyAuth: verifyAuth ?? pickerContext?.verifyAuth ?? false,
|
||||
}, target, domains => bm.trackCookieImportDomains(domains), {
|
||||
identitySelector: process.env.GSTACK_COOKIE_AUTH_SELECTOR,
|
||||
expectedIdentity: process.env.GSTACK_COOKIE_AUTH_EXPECTED_IDENTITY,
|
||||
});
|
||||
for (const domain of Object.keys(result.domainCounts)) {
|
||||
importedDomains.add(domain);
|
||||
importedCounts.set(domain, (importedCounts.get(domain) || 0) + result.domainCounts[domain]);
|
||||
importedCounts.set(domain, result.domainCounts[domain]);
|
||||
}
|
||||
|
||||
console.log(`[cookie-picker] Imported ${result.count} cookies for ${Object.keys(result.domainCounts).length} domains`);
|
||||
|
||||
return jsonResponse({
|
||||
imported: result.count,
|
||||
failed: result.failed,
|
||||
domainCounts: result.domainCounts,
|
||||
}, { port });
|
||||
return jsonResponse(result, { port });
|
||||
}
|
||||
|
||||
// POST /cookie-picker/remove — clear cookies for domains
|
||||
@@ -334,7 +337,7 @@ export async function handleCookiePickerRoute(
|
||||
if (err instanceof CookieImportError) {
|
||||
return errorResponse(err.message, err.code, { port, status: 400, action: err.action });
|
||||
}
|
||||
console.error(`[cookie-picker] Error: ${err.message}`);
|
||||
return errorResponse(err.message || 'Internal error', 'internal_error', { port, status: 500 });
|
||||
console.error('[cookie-picker] Operation failed');
|
||||
return errorResponse('Cookie picker operation failed. Retry or reopen the picker.', 'internal_error', { port, status: 500 });
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user