Files
OmniRoute/electron/loginManager.js
Diego Rodrigues de Sa e Souza a25d5f1ef6 Release v3.8.13 (#3327)
* chore(release): open v3.8.13 development cycle

Bump 3.8.12 → 3.8.13 across package.json, lockfile, electron/, open-sse/, and
docs/reference/openapi.yaml; add the [3.8.13] cycle placeholder to the root
CHANGELOG and the 41 i18n mirrors. Integration branch for the v3.8.13 cycle —
fixes/features land here via per-issue PRs and it merges to main at release time.

* fix(ci): skip auto-deploy when VPS host is unreachable from the runner (#3299)

Integrated into release/v3.8.13

* fix(dev): auto-rebuild better-sqlite3 on Node ABI mismatch at dev startup (#3301)

Integrated into release/v3.8.13

* feat(api): accept path-scoped API keys on client API routes (#3300)

Integrated into release/v3.8.13

* fix(sse): harden against empty responses causing Copilot Chat failures (#3297)

Integrated into release/v3.8.13

* fix(api): remove Completions.me rickroll provider (discussion #3293) (#3302)

Integrated into release/v3.8.13

* fix(opencode-provider): extract contextLength from live model catalog (#3298)

Integrated into release/v3.8.13

* feat(web-cookie): self-service login infrastructure + auto-refresh daemon (#3292)

Integrated into release/v3.8.13

* docs(changelog): record the v3.8.13 PRs merged this round (#3292/#3300/#3297/#3298/#3301/#3302/#3299)

* fix(auth): harden URL token extraction — drop query-string fallback, gate to client routes (security follow-up to #3300) (#3309)

Security follow-up to #3300 — integrated into release/v3.8.13

* docs: rename resolve-issues → review-issues skill references

* fix(dashboard): keep no-auth providers visible under 'Show configured only' (#3290) (#3312)

no-auth providers (opencode, duckduckgo-web, theoldllm, veoaifree-web) never
create a DB connection row so stats.total stays 0, which the configured-only
filter treated as 'unconfigured' and hid them — even though they are always
usable and appear unconditionally in /v1/models. filterConfiguredProviderEntries
now treats displayAuthType === 'no-auth' as configured.

Co-authored-by: uniQta <uniQta@users.noreply.github.com>

* fix(cli): resolve update paths relative to script + recursive backup (#3295) (#3313)

omniroute update always failed on a global install:
- getCurrentVersion() read package.json from process.cwd(), which on a global
  npm/brew install is the user's working dir, not the package root → null →
  'Could not determine current version'.
- createBackup() resolved bin/ from cwd too, and passed the 'cli' directory to
  copyFileSync → EISDIR, swallowed by the catch → 'Failed to create backup'.

Both now resolve package.json/bin relative to the script via import.meta.url,
and the backup uses cpSync({recursive:true}) so the cli/ directory is copied.

Co-authored-by: uniQta <uniQta@users.noreply.github.com>

* fix(theoldllm): read upstream body once to avoid [502] body-already-read (#3296) (#3314)

On the cached-token path the executor never enters the refresh branch, so the
same upstream Response was read with .text() twice (token-rejection check +
final body). A Response body is single-use, so the second read threw
'Body is unusable: Body has already been read', caught and surfaced as [502].

Read the body once into finalBody and only re-read after a token-rejection
refetch.

Co-authored-by: onizukashonan14-png <onizukashonan14-png@users.noreply.github.com>

* fix(sse): strip leaked internal tool envelopes from streaming output (#3311)

Integrated into release/v3.8.13

* fix(sse): expose Claude + Gemini budget tiers in the antigravity catalog (#3184) (#3303)

Integrated into release/v3.8.13 (#3184)

* fix(catalog): compute combo context_length from known targets only (#3304)

Integrated into release/v3.8.13 — live contextLength + known-targets combo context (#3298 follow-up)

* chore(i18n): add message keys for proxy UI + vscode/ollama endpoint (#3307)

Integrated into release/v3.8.13 — i18n message keys for proxy UI + vscode/ollama

* feat(dashboard): i18n the proxy settings UI (#3310)

Integrated into release/v3.8.13 — i18n the proxy settings UI

* feat(api): model catalog enrichment + MCP model-catalog tools (#3306)

Integrated into release/v3.8.13 — model catalog enrichment + MCP model-catalog tools, reconciled with #3309 URL-token hardening

* test(catalog): align Antigravity preview-alias test with #3303 budget tiers

#3303 added the Gemini `-high`/`-low` budget tiers to ANTIGRAVITY_PUBLIC_MODELS
(user-callable on the Antigravity OAuth backend, verified via #3184), but did
not update the catalog-route test that asserted `antigravity/gemini-3.1-pro-high`
must NOT be exposed. The assertion now reflects the intended behavior — the
client-visible budget alias IS surfaced — while keeping the legacy
`gemini-claude-*` alias keys unexposed. Caught running the full catalog suite
on the merged release HEAD (the #3303 round only ran the antigravity-aliases
and usage-hardening files).

* docs(changelog): record the 6 PRs merged this review round into v3.8.13

#3306/#3307/#3310 (New Features — VS Code split: catalog+MCP, i18n keys, proxy
UI i18n), #3311/#3303/#3304 (Bug Fixes — SSE envelope sanitizer, antigravity
budget tiers, combo known-targets context_length).

* chore(release): finalize v3.8.13 changelog and cleanup

Finalize the v3.8.13 changelog with release date, maintenance notes,
and contributor credits. Update MCP docs to reference the correct tool
inventory diagram, exclude nested .claude worktrees from ESLint scans,
and tighten a response sanitizer type guard.

* fix(dashboard): refresh connections after provider auth import (#3320)

Integrated into release/v3.8.13 — refresh connections after provider auth import

* fix(codex): strip client-only params on native /responses passthrough (#3317) (#3325)

A /v1/responses request against the built-in codex/ provider does an
openai-responses -> openai-responses passthrough (CodexExecutor.transformRequest
returns the body early for _nativeCodexPassthrough). It forwarded client-only
fields verbatim and the Codex upstream rejected them with 400 Unsupported
parameter: prompt_cache_retention / safety_identifier / user — breaking Factory
Droid (which injects all three). The chat-completions path already strips these
(base.ts #1884, openai-responses translator #2770) but the passthrough skips
translation. Strip the three fields in the shared block before the passthrough
return; user is removed unconditionally since Codex /responses always rejects it.

Co-authored-by: tycronk20 <tycronk20@users.noreply.github.com>

* fix(dashboard): normalize agent-bridge /state response to stop page crash (#3318) (#3326)

The Agent Bridge page seeded a well-shaped initialData default then replaced it
wholesale with the raw /api/tools/agent-bridge/state response. The route returns
{ server, agents } but the UI reads { serverState, agentStates, bypassPatterns,
mappings }, so serverState became undefined and AgentBridgeServerCard crashed on
serverState.running — surfaced as the full-page 'Internal Server Error' boundary
(client render error, not a real 5xx).

Add a shared normalizeAgentBridgeState() that maps the route shape into the page
contract (server.running/certExists -> serverState) and always returns safe
defaults (never undefined serverState). Wired into both the SSR loader (page.tsx)
and the polling hook. The legacy 'agents' entry shape differs from AgentStateEntry
so it is not coerced; full route<->page contract reconciliation (port, upstreamCa,
bypassPatterns, mappings, agentStates) is a follow-up.

Co-authored-by: tycronk20 <tycronk20@users.noreply.github.com>

* docs: VS Code/Ollama endpoints + env & i18n tooling (#3319)

Integrated into release/v3.8.13 — VS Code/Ollama docs + env & i18n tooling

* feat(provider): test-all endpoint, rate-limit overrides, visibility f… (#3267)

Integrated into release/v3.8.13 — provider test-all endpoint, rate-limit overrides, model visibility

* feat: auto-combo optimization, playground model dropdown, only-configured toggle (#3322)

Integrated into release/v3.8.13 — auto-combo candidate expansion + playground dropdown + only-configured toggle

* feat(api): VS Code Copilot Ollama-compatible BYOK endpoint (#3316)

Integrated into release/v3.8.13 — VS Code Copilot Ollama-compatible BYOK endpoint (reconciled with #3306/#3309 auth hardening)

* chore(release): document #3320 in the v3.8.13 changelog + contributor credits

---------

Co-authored-by: Felipe Almeman <4226997+zhiru@users.noreply.github.com>
Co-authored-by: Wilson <pedbookmed@gmail.com>
Co-authored-by: Hernan Javier Ardila Sanchez <hjasgr@gmail.com>
Co-authored-by: Paijo <14921983+oyi77@users.noreply.github.com>
Co-authored-by: uniQta <uniQta@users.noreply.github.com>
Co-authored-by: onizukashonan14-png <onizukashonan14-png@users.noreply.github.com>
Co-authored-by: tycronk20 <tycronk20@users.noreply.github.com>
Co-authored-by: Vinayrnani <vinayrnani@gmail.com>
2026-06-06 19:13:11 -03:00

387 lines
12 KiB
JavaScript

/**
* LoginManager — Electron BrowserWindow-based web login for cookie providers
*
* Opens a native Electron window navigated to the provider's login page.
* Polls the session cookie store for target cookies after login completes.
*
* Events:
* "status" — { status: string, message: string, providerId: string }
* status values: starting, navigating, waiting, polling, complete, error, cancelled
*/
const { BrowserWindow, session } = require("electron");
const { EventEmitter } = require("events");
const path = require("path");
// In production, the tokenExtractionConfig is bundled under open-sse/services/.
// We resolve relative to the Electron resources path.
let TOKEN_EXTRACTION_CONFIGS = null;
function getConfigs() {
if (TOKEN_EXTRACTION_CONFIGS) return TOKEN_EXTRACTION_CONFIGS;
try {
const mod = require("../open-sse/services/tokenExtractionConfig");
TOKEN_EXTRACTION_CONFIGS = mod.TOKEN_EXTRACTION_CONFIGS;
} catch {
// Fallback: try from app resources
try {
const mod = require("./open-sse/services/tokenExtractionConfig");
TOKEN_EXTRACTION_CONFIGS = mod.TOKEN_EXTRACTION_CONFIGS;
} catch {}
}
return TOKEN_EXTRACTION_CONFIGS;
}
class LoginManager extends EventEmitter {
constructor() {
super();
this.window = null;
this.activeProviderId = null;
this.resolvePromise = null;
this.rejectPromise = null;
this.timeoutId = null;
this.isCompleted = false;
this.pollIntervalId = null;
this.loginSession = null;
}
/**
* Start a login flow for a web-cookie provider.
* @param {string} providerId - e.g. "claude-web", "chatgpt-web"
* @param {object} [options]
* @param {number} [options.timeout] - Total timeout in ms (default: config or 300s)
* @returns {Promise<{success: boolean, credentials?: Record<string, string>, error?: string}>}
*/
startLogin(providerId, options = {}) {
const configs = getConfigs();
if (!configs) {
return Promise.resolve({
success: false,
error: "tokenExtractionConfig module not found",
});
}
const extractionConfig = configs.get(providerId);
if (!extractionConfig) {
return Promise.resolve({
success: false,
error: `No extraction config for provider: ${providerId}`,
});
}
if (this.activeProviderId) {
return Promise.resolve({
success: false,
error: "A login process is already in progress",
});
}
this.activeProviderId = providerId;
this.isCompleted = false;
const timeout = options.timeout || extractionConfig.pollingConfig.timeout || 300_000;
const minLoginTime = extractionConfig.pollingConfig.minLoginTime || 5000;
const pollInterval = extractionConfig.pollingConfig.pollInterval || 1000;
return new Promise((resolve, reject) => {
this.resolvePromise = resolve;
this.rejectPromise = reject;
this.emit("status", {
providerId,
status: "starting",
message: `Opening ${extractionConfig.displayName} login...`,
});
try {
this._openLoginWindow(providerId, extractionConfig, timeout, minLoginTime, pollInterval);
} catch (err) {
this._cleanup();
this.emit("status", {
providerId,
status: "error",
message: `Failed to open window: ${err.message}`,
});
resolve({ success: false, error: err.message });
}
});
}
/**
* Open the Electron BrowserWindow for login
*/
_openLoginWindow(providerId, config, timeout, minLoginTime, pollInterval) {
this.window = new BrowserWindow({
width: 1000,
height: 750,
title: `Login - ${config.displayName}`,
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
session: session.fromPartition(`login-${providerId}-${Date.now()}`),
},
show: true,
autoHideMenuBar: true,
});
const winSession = this.window.webContents.session;
// Track navigation for success URL detection
let navigatedToLogin = false;
const startTime = Date.now();
this.window.webContents.on("did-navigate", (_event, url) => {
if (this.isCompleted) return;
try {
const parsedUrl = new URL(url);
// Check if we've navigated away from the login page (successful login)
if (navigatedToLogin && config.successUrlPattern) {
if (config.successUrlPattern.test(url)) {
this.emit("status", {
providerId,
status: "detected",
message: "Login page redirect detected — extracting cookies...",
});
}
}
if (!navigatedToLogin) {
navigatedToLogin = true;
}
this.emit("status", {
providerId,
status: "navigating",
message: `Navigated to ${parsedUrl.hostname}`,
});
} catch {
// ignore bad URLs
}
});
// Load the login page
this.emit("status", {
providerId,
status: "navigating",
message: `Loading ${config.loginUrl}...`,
});
this.window.loadURL(config.loginUrl);
// Show window when ready
this.window.once("ready-to-show", () => {
this.window.show();
});
// Handle window close by user
this.window.on("closed", () => {
if (!this.isCompleted) {
this._cleanup();
this.emit("status", {
providerId,
status: "cancelled",
message: "Login window closed by user",
});
if (this.resolvePromise) {
this.resolvePromise({ success: false, error: "Login window closed" });
}
}
});
// Start polling for cookies after minLoginTime has elapsed
this.timeoutId = setTimeout(() => {
if (this.isCompleted) return;
this._startPolling(providerId, config, winSession, pollInterval, startTime, minLoginTime);
}, minLoginTime);
// Overall timeout
this._timeoutTimer = setTimeout(() => {
if (!this.isCompleted) {
this._cleanup();
this.emit("status", {
providerId,
status: "error",
message: "Login timed out",
});
if (this.resolvePromise) {
this.resolvePromise({ success: false, error: "Login timed out" });
}
}
}, timeout);
}
/**
* Poll the Electron session cookie store for the target cookies
*/
_startPolling(providerId, config, winSession, pollInterval, startTime, minLoginTime) {
const maxPolls = Math.floor(config.pollingConfig.timeout / pollInterval);
let pollCount = 0;
const poll = () => {
if (this.isCompleted) return;
pollCount++;
// Emit progress every 30 polls
if (pollCount % 30 === 0) {
const elapsed = Math.round((Date.now() - startTime) / 60000);
this.emit("status", {
providerId,
status: "waiting",
message: `Waiting for login... (${elapsed}m)`,
});
}
winSession.cookies
.get({})
.then((cookies) => {
if (this.isCompleted) return;
const tokenSources = config.tokenSources;
const credentials = {};
// Collect all cookie-based sources
const cookieSources = tokenSources.filter((s) => s.type === "cookie");
for (const source of cookieSources) {
const domain = source.domain || undefined;
const matched = cookies.find(
(c) => c.name === source.name && (!domain || c.domain.includes(domain.replace(/^\./, "")))
);
if (matched) {
credentials[source.name] = matched.value;
}
}
// Check localStorage-based tokens via executeJavaScript
const storageSources = tokenSources.filter(
(s) => s.type === "localStorage" || s.type === "sessionStorage"
);
if (storageSources.length > 0 && this.window && !this.window.isDestroyed()) {
// Execute JS to extract all localStorage/sessionStorage tokens
const storageType = storageSources[0].type === "localStorage" ? "localStorage" : "sessionStorage";
const keys = storageSources.map((s) => s.key);
const js = `(() => {
const res = {};
${JSON.stringify(keys)}.forEach(k => {
try { res[k] = ${storageType}.getItem(k); } catch {}
});
return res;
})()`;
this.window.webContents
.executeJavaScript(js)
.then((values) => {
if (values && typeof values === "object") {
Object.assign(credentials, values);
}
this._checkCredentials(providerId, credentials, cookieSources, storageSources, poll, pollInterval);
})
.catch(() => {
this._checkCredentials(providerId, credentials, cookieSources, storageSources, poll, pollInterval);
});
} else {
this._checkCredentials(providerId, credentials, cookieSources, storageSources, poll, pollInterval);
}
})
.catch(() => {
if (!this.isCompleted) {
this.pollIntervalId = setTimeout(poll, pollInterval);
}
});
};
// Start first poll
this.pollIntervalId = setTimeout(poll, 0);
}
/**
* Check if we have all required credentials, otherwise continue polling
*/
_checkCredentials(providerId, credentials, cookieSources, storageSources, poll, pollInterval) {
if (this.isCompleted) return;
// Collect the required source names/keys
const requiredKeys = [
...cookieSources.map((s) => s.name),
...storageSources.map((s) => s.key),
];
const foundKeys = Object.keys(credentials);
const allFound = requiredKeys.every((k) => foundKeys.includes(k));
if (allFound && foundKeys.length > 0) {
// Success — all credentials extracted
this._completeLogin(providerId, foundKeys.reduce((acc, k) => {
acc[k] = credentials[k];
return acc;
}, {}));
} else if (!this.isCompleted) {
// Continue polling using the configured interval
this.pollIntervalId = setTimeout(poll, pollInterval);
}
}
/**
* Complete the login flow successfully
*/
_completeLogin(providerId, credentials) {
this._cleanup();
this.emit("status", {
providerId,
status: "complete",
message: "Credentials extracted successfully",
});
if (this.resolvePromise) {
this.resolvePromise({ success: true, credentials });
}
}
/**
* Cancel the current login flow
*/
cancel() {
if (!this.activeProviderId) return;
this._cleanup();
this.emit("status", {
providerId: this.activeProviderId,
status: "cancelled",
message: "Login cancelled",
});
if (this.resolvePromise) {
this.resolvePromise({ success: false, error: "Login cancelled" });
}
}
/**
* Clean up all resources
*/
_cleanup() {
this.isCompleted = true;
this.activeProviderId = null;
if (this.timeoutId) {
clearTimeout(this.timeoutId);
this.timeoutId = null;
}
if (this._timeoutTimer) {
clearTimeout(this._timeoutTimer);
this._timeoutTimer = null;
}
if (this.pollIntervalId) {
clearTimeout(this.pollIntervalId);
this.pollIntervalId = null;
}
if (this.window && !this.window.isDestroyed()) {
this.window.close();
}
this.window = null;
this.loginSession = null;
}
/**
* Get the active provider ID, if any
*/
getActiveProvider() {
return this.activeProviderId;
}
}
module.exports = { LoginManager, loginManager: new LoginManager() };