Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
/**
* InAppLoginService — Playwright-based web login for cookie providers
*
* Opens a Playwright browser context, navigates to the provider's login page,
* and polls for target cookies/tokens after the user completes login.
*
* The primary login surface for cookie providers (dashboard and web clients).
*
* Events:
* "status" — { providerId: string, status: string, message: string }
* status values: starting, navigating, waiting, polling, complete, error, cancelled
*/
import { EventEmitter } from "events";
import {
TOKEN_EXTRACTION_CONFIGS,
TokenExtractionConfig,
type TokenSource,
} from "./tokenExtractionConfig";
import { matchesCookieDomain } from "../utils/cookieDomain";
// ─── Types ──────────────────────────────────────────────────────────────────
export interface LoginResult {
success: boolean;
credentials?: Record<string, string>;
error?: string;
}
interface ActiveLogin {
providerId: string;
aborted: boolean;
}
export function captureConfiguredHeaders(
tokenSources: readonly TokenSource[],
requestHeaders: Record<string, string>,
credentials: Record<string, string>
): void {
for (const source of tokenSources) {
if (source.type !== "header" || credentials[source.name]) continue;
const value = requestHeaders[source.name.toLowerCase()];
if (typeof value === "string" && value.trim()) {
credentials[source.name] = value.trim();
}
}
}
// ─── Service ────────────────────────────────────────────────────────────────
export class InAppLoginService extends EventEmitter {
private activeLogin: ActiveLogin | null = null;
/**
* Start a login flow for a web-cookie provider using Playwright.
* @param providerId - e.g. "claude-web", "perplexity-web"
* @param options.timeout - Total timeout in ms (default: config value or 300s)
*/
async startLogin(providerId: string, options?: { timeout?: number }): Promise<LoginResult> {
const config = TOKEN_EXTRACTION_CONFIGS.get(providerId);
if (!config) {
this.emit("status", { providerId, status: "error", message: "No extraction config found" });
return { success: false, error: `No extraction config for provider: ${providerId}` };
}
if (this.activeLogin) {
this.emit("status", {
providerId,
status: "error",
message: "A login is already in progress",
});
return { success: false, error: "A login process is already in progress" };
}
this.activeLogin = { providerId, aborted: false };
this.emit("status", {
providerId,
status: "starting",
message: `Opening ${config.displayName} login...`,
});
try {
const result = await this.runBrowserLogin(config, options?.timeout);
this.emit("status", {
providerId,
status: result.success ? "complete" : "error",
message: result.success
? "Credentials extracted successfully"
: result.error || "Login failed",
});
return result;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
this.emit("status", { providerId, status: "error", message });
return { success: false, error: `Login failed: ${message}` };
} finally {
this.activeLogin = null;
}
}
/**
* Run the actual Playwright browser login flow
*/
private async runBrowserLogin(
config: TokenExtractionConfig,
timeout?: number
): Promise<LoginResult> {
const pollInterval = config.pollingConfig.pollInterval || 1000;
const maxTimeout = timeout || config.pollingConfig.timeout || 300_000;
const minLoginTime = config.pollingConfig.minLoginTime || 5000;
const providerId = config.providerId;
// Dynamically import Playwright (it's a heavy dep, only load when needed)
let playwright: any;
try {
playwright = await import("playwright");
} catch {
return {
success: false,
error: "Playwright is not installed. Use Electron for native login.",
};
}
if (this.activeLogin?.aborted) {
return { success: false, error: "Login cancelled" };
}
// Launch browser
this.emit("status", { providerId, status: "starting", message: "Launching browser..." });
const browser = await playwright.chromium.launch({
headless: false, // User must interact with the login page
});
try {
const context = await browser.newContext({
viewport: { width: 1280, height: 800 },
locale: "en-US",
});
const page = await context.newPage();
const credentials: Record<string, string> = {};
// Playwright normalizes request header names to lowercase. Capture only
// explicitly configured credentials and never replace the first token
// observed after login.
page.on("request", (request: { allHeaders(): Promise<Record<string, string>> }) => {
void request
.allHeaders()
.then((headers) => captureConfiguredHeaders(config.tokenSources, headers, credentials))
.catch(() => {
// Some browser-internal requests do not expose their full headers.
});
});
// Navigate to login URL
this.emit("status", {
providerId,
status: "navigating",
message: `Loading ${config.loginUrl}`,
});
await page.goto(config.loginUrl, { waitUntil: "domcontentloaded", timeout: 30000 });
// Poll for success URL + token extraction
const maxPolls = Math.floor(maxTimeout / pollInterval);
const startTime = Date.now();
for (let i = 0; i < maxPolls; i++) {
if (this.activeLogin?.aborted) {
this.emit("status", {
providerId,
status: "cancelled",
message: "Login cancelled by user",
});
return { success: false, error: "Login cancelled" };
}
// Emit progress every 30 seconds
if (i > 0 && i % 30 === 0) {
this.emit("status", {
providerId,
status: "waiting",
message: `Waiting for login... (${Math.round(i / 60)}m)`,
});
}
// Wait before polling (respect minLoginTime on first iteration)
if (Date.now() - startTime < minLoginTime) {
await sleep(pollInterval);
continue;
}
// Gather cookies from browser context
const cookies = await context.cookies();
const tokenSources = config.tokenSources;
// Check cookie-based sources
for (const source of tokenSources) {
if (source.type === "cookie") {
const domain = source.domain || undefined;
// Exact host or dot-boundary suffix, never `includes()`: a cookie
// from `<domain>.attacker.tld` would otherwise be captured and
// persisted as the operator's credential. Same class CodeQL flagged
// in volcengineConsoleAutoLogin (#860/#861); this callsite was not
// flagged because the expected domain is config-supplied.
const matched = cookies.find(
(c: any) =>
c.name === source.name && (!domain || matchesCookieDomain(c.domain, domain))
);
if (matched && !credentials[source.name]) {
credentials[source.name] = matched.value;
}
}
}
// Check localStorage-based tokens
for (const source of tokenSources) {
if (source.type === "localStorage" && !credentials[source.key]) {
try {
const value = await page.evaluate(
(key: string) => localStorage.getItem(key),
source.key
);
if (value && typeof value === "string") {
credentials[source.key] = value;
}
} catch {
// localStorage access may fail on some domains
}
}
if (source.type === "sessionStorage" && !credentials[source.key]) {
try {
const value = await page.evaluate(
(key: string) => sessionStorage.getItem(key),
source.key
);
if (value && typeof value === "string") {
credentials[source.key] = value;
}
} catch {
// sessionStorage access may fail on some domains
}
}
}
// Check if all required tokens are found
const requiredKeys = tokenSources.map((s) =>
s.type === "cookie"
? s.name
: s.type === "localStorage" || s.type === "sessionStorage"
? s.key
: s.name
);
const allFound = requiredKeys.every((k) => credentials[k] !== undefined);
if (allFound && Object.keys(credentials).length > 0) {
return { success: true, credentials };
}
// Check for success URL pattern
if (config.successUrlPattern) {
try {
const currentUrl = page.url();
if (config.successUrlPattern.test(currentUrl) && Object.keys(credentials).length > 0) {
return { success: true, credentials };
}
} catch {
// URL access may fail on some pages
}
}
await sleep(pollInterval);
}
return { success: false, error: "Login timed out" };
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
this.emit("status", { providerId, status: "error", message });
return { success: false, error: `Login failed: ${message}` };
} finally {
await browser.close().catch(() => {});
}
}
/**
* Cancel the current login flow
*/
cancel(): void {
if (this.activeLogin) {
this.emit("status", {
providerId: this.activeLogin.providerId,
status: "cancelled",
message: "Login cancelled by user",
});
this.activeLogin.aborted = true;
this.activeLogin = null;
}
}
/**
* Get the active provider ID, if any
*/
getActiveProvider(): string | null {
return this.activeLogin?.providerId || null;
}
/**
* Check if a login flow is in progress
*/
isActive(): boolean {
return this.activeLogin !== null && !this.activeLogin.aborted;
}
}
// ─── Sleep helper ───────────────────────────────────────────────────────────
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
// ─── Singleton ──────────────────────────────────────────────────────────────
export const inAppLoginService = new InAppLoginService();