Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: cancel forge auth timeout work (#6938)
[._.]/ Adam Eivya0a9fd8f6b4a
diff --git a/server/services/forgeAuth.js b/server/services/forgeAuth.jsindex d586a81fd5..f89e0b8096 100644--- a/server/services/forgeAuth.js+++ b/server/services/forgeAuth.js@@ -9,31 +9,39 @@ import { parseGitRemote, detectForgeCli, pickGhAccountForOwner } from '../lib/giconst DEFAULT_SPAWN_CLI_TIMEOUT_MS = 10000;-function spawnCli(cmd, args, timeoutMs = DEFAULT_SPAWN_CLI_TIMEOUT_MS) {+function spawnCli(cmd, args, timeoutMs = DEFAULT_SPAWN_CLI_TIMEOUT_MS, signal) {+ const timedOut = { code: -1, stdout: '', stderr: 'timed out' };+ if (signal?.aborted) return Promise.resolve(timedOut);+return new Promise((resolve) => {const child = spawn(cmd, args, { shell: false });let stdout = '', stderr = '';let settled = false;+ let timer;const done = (result) => {if (settled) return;settled = true;clearTimeout(timer);+ signal?.removeEventListener('abort', abort);resolve(result);};- const timer = setTimeout(() => {+ const abort = () => {+ done(timedOut);try { child.kill('SIGKILL'); } catch { /* best-effort process cleanup */ }- done({ code: -1, stdout: '', stderr: 'timed out' });- }, timeoutMs);+ };+ timer = setTimeout(abort, timeoutMs);timer.unref?.();child.stdout.on('data', (d) => { stdout += d.toString(); });child.stderr.on('data', (d) => { stderr += d.toString(); });child.on('close', (code) => done({ code, stdout, stderr }));child.on('error', () => done({ code: -1, stdout: '', stderr: '' }));+ signal?.addEventListener('abort', abort, { once: true });+ if (signal?.aborted) abort();});}-async function listGhAccounts(timeoutMs) {- const { stdout, stderr } = await spawnCli('gh', ['auth', 'status', '-h', 'github.com'], timeoutMs);+async function listGhAccounts(timeoutMs, signal) {+ const { stdout, stderr } = await spawnCli('gh', ['auth', 'status', '-h', 'github.com'], timeoutMs, signal);// gh writes status to stderr in older versions, stdout in newer — search both.const text = `${stdout}\n${stderr}`;const accounts = [];@@ -43,8 +51,8 @@ async function listGhAccounts(timeoutMs) {return accounts;}-async function getGhTokenForAccount(login, timeoutMs) {- const { code, stdout } = await spawnCli('gh', ['auth', 'token', '-u', login, '-h', 'github.com'], timeoutMs);+async function getGhTokenForAccount(login, timeoutMs, signal) {+ const { code, stdout } = await spawnCli('gh', ['auth', 'token', '-u', login, '-h', 'github.com'], timeoutMs, signal);return code === 0 ? stdout.trim() : null;}@@ -59,8 +67,9 @@ async function getGhTokenForAccount(login, timeoutMs) {* @param {string} dir - Repository root* @param {object} [opts]* @param {number} [opts.timeoutMs=10000] - Per-process bound for gh auth probes+ * @param {AbortSignal} [opts.signal] - Cancels active and follow-on gh auth probes*/-export async function resolveForgeForRepo(dir, { timeoutMs = DEFAULT_SPAWN_CLI_TIMEOUT_MS } = {}) {+export async function resolveForgeForRepo(dir, { timeoutMs = DEFAULT_SPAWN_CLI_TIMEOUT_MS, signal } = {}) {const remote = await execGitSafe(['remote', 'get-url', 'origin'], dir);const parsed = parseGitRemote(remote.stdout?.trim());if (!parsed) {@@ -68,17 +77,19 @@ export async function resolveForgeForRepo(dir, { timeoutMs = DEFAULT_SPAWN_CLI_T}const cli = detectForgeCli(parsed.host);+ const ambient = { cli, env: process.env, host: parsed.host, owner: parsed.owner, account: null };- if (cli !== 'gh') {- return { cli, env: process.env, host: parsed.host, owner: parsed.owner, account: null };- }+ if (cli !== 'gh' || signal?.aborted) return ambient;- const accounts = await listGhAccounts(timeoutMs);+ const accounts = await listGhAccounts(timeoutMs, signal);+ if (signal?.aborted) return ambient;const account = pickGhAccountForOwner(parsed.owner, accounts);if (!account) return { cli, env: process.env, host: parsed.host, owner: parsed.owner, account: null };- const token = await getGhTokenForAccount(account, timeoutMs);- if (!token) return { cli, env: process.env, host: parsed.host, owner: parsed.owner, account };+ const token = await getGhTokenForAccount(account, timeoutMs, signal);+ if (signal?.aborted || !token) {+ return { cli, env: process.env, host: parsed.host, owner: parsed.owner, account };+ }return { cli, env: { ...process.env, GH_TOKEN: token }, host: parsed.host, owner: parsed.owner, account };}@@ -104,15 +115,21 @@ export async function resolveForgeForRepo(dir, { timeoutMs = DEFAULT_SPAWN_CLI_T* @returns {Promise<{ GH_TOKEN?: string }>}*/export async function resolveForgeTokenEnv(dir, { timeoutMs = 10000 } = {}) {- // Keep the whole lookup inside the agent-spawn budget. Each gh subprocess has- // the same bound and kills itself on timeout, so losing this race cannot leak- // the auth child that was still pending. A timeout falls through to `{}`- // (ambient auth) exactly like any other miss. The timer is unref'd so it never- // itself keeps the event loop alive.+ // Keep the whole lookup inside the agent-spawn budget. The shared abort signal+ // kills whichever gh subprocess is active when the outer budget expires and+ // prevents a slow git lookup from starting a stale follow-on auth probe. Each+ // gh subprocess keeps its own timeout as a second bound for direct callers.let timer;+ const controller = new AbortController();const resolved = await Promise.race([- resolveForgeForRepo(dir, { timeoutMs }).catch(() => null),- new Promise((r) => { timer = setTimeout(() => r(null), timeoutMs); timer.unref?.(); }),+ resolveForgeForRepo(dir, { timeoutMs, signal: controller.signal }).catch(() => null),+ new Promise((r) => {+ timer = setTimeout(() => {+ controller.abort();+ r(null);+ }, timeoutMs);+ timer.unref?.();+ }),]);clearTimeout(timer);// Overlay a token ONLY for a genuinely-minted github.com credential. Two gates:diff --git a/server/services/forgeAuth.test.js b/server/services/forgeAuth.test.jsindex 6070bc9c53..86237b0364 100644--- a/server/services/forgeAuth.test.js+++ b/server/services/forgeAuth.test.js@@ -96,4 +96,54 @@ describe('forge credential resolution', () => {stalled.emit('close', 1);await expect(pending).resolves.toEqual({});});++ it('aborts a token probe that starts near the end of the whole lookup budget', async () => {+ vi.useFakeTimers();+ respond({ stdout: '[email protected]:example-owner/project.git\n' });++ const status = new EventEmitter();+ status.stdout = new EventEmitter();+ status.stderr = new EventEmitter();+ status.kill = vi.fn();+ spawn.mockImplementationOnce(() => {+ setTimeout(() => {+ status.stderr.emit('data', 'Logged in to github.com account example-owner\n');+ status.emit('close', 0);+ }, 9);+ return status;+ });++ const token = new EventEmitter();+ token.stdout = new EventEmitter();+ token.stderr = new EventEmitter();+ token.kill = vi.fn();+ spawn.mockImplementationOnce(() => token);++ const pending = resolveForgeTokenEnv('/example/repo', { timeoutMs: 10 });+ await vi.advanceTimersByTimeAsync(9);+ expect(spawn).toHaveBeenCalledTimes(3);+ await vi.advanceTimersByTimeAsync(1);++ await expect(pending).resolves.toEqual({});+ expect(token.kill).toHaveBeenCalledWith('SIGKILL');+ });++ it('does not start an auth probe when git finishes after the whole lookup budget', async () => {+ vi.useFakeTimers();+ const git = new EventEmitter();+ git.stdout = new EventEmitter();+ git.stderr = new EventEmitter();+ git.kill = vi.fn();+ spawn.mockImplementationOnce(() => git);++ const pending = resolveForgeTokenEnv('/example/repo', { timeoutMs: 10 });+ await vi.advanceTimersByTimeAsync(10);+ await expect(pending).resolves.toEqual({});++ git.stdout.emit('data', '[email protected]:example-owner/project.git\n');+ git.emit('close', 0);+ await Promise.resolve();+ await Promise.resolve();+ expect(spawn).toHaveBeenCalledTimes(1);+ });});