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: bind managed app accounts to their GitHub host (#13233)
Adam Eivy4ed37ac0f7f3
diff --git a/server/routes/apps/forgeAuth.js b/server/routes/apps/forgeAuth.jsindex ff314e6fe9..c484cb7d8f 100644--- a/server/routes/apps/forgeAuth.js+++ b/server/routes/apps/forgeAuth.js@@ -49,7 +49,11 @@ router.post('/:id/forge-auth/refresh', loadApp, asyncHandler(async (req, res) =>// The account merges actually authenticate as (an owner-match or the app's// pin) — `gh auth refresh` only reaches the host's active one.- const resolved = await resolveForgeForRepo(app.repoPath, { forgeAccount: app.forgeAccount }).catch(() => null);+ const resolved = await resolveForgeForRepo(app.repoPath, { forgeAccount: app.forgeAccount });++ if (resolved.host !== host) throw new ServerError("This app's forge host changed during account resolution. Retry the refresh.", {+ status: 409, code: 'FORGE_REFRESH_HOST_CHANGED',+ });const job = await startForgeScopeRefresh({ host, scopes, expectedAccount: resolved?.account || null });res.status(job.adopted ? 200 : 202).json(job);diff --git a/server/routes/apps/forgeAuth.test.js b/server/routes/apps/forgeAuth.test.jsindex 6834a2d8e6..98729ff7f9 100644--- a/server/routes/apps/forgeAuth.test.js+++ b/server/routes/apps/forgeAuth.test.js@@ -37,7 +37,7 @@ describe('app forge-auth routes', () => {tracker: 'github',target: { forge: 'github', repoSpec: 'ghe.example.com/acme/widget', webHost: 'ghe.example.com', apiHost: 'ghe.example.com' },});- resolveForgeForRepo.mockResolvedValue({ account: null });+ resolveForgeForRepo.mockResolvedValue({ host: 'ghe.example.com', account: null });startForgeScopeRefresh.mockResolvedValue({ jobId: JOB_ID, host: 'ghe.example.com', scopes: ['workflow'], adopted: false });});@@ -51,13 +51,30 @@ describe('app forge-auth routes', () => {});it('hands the account merges authenticate as to the service so a non-active account is caught', async () => {- resolveForgeForRepo.mockResolvedValue({ account: 'owner-acct' });+ resolveForgeForRepo.mockResolvedValue({ host: 'ghe.example.com', account: 'owner-acct' });await request(app).post('/api/apps/app-001/forge-auth/refresh').send({ scopes: ['workflow'] });expect(startForgeScopeRefresh).toHaveBeenCalledWith(expect.objectContaining({ expectedAccount: 'owner-acct' }));});+ it('refuses a changed origin instead of refreshing an account on another host', async () => {+ resolveForgeForRepo.mockResolvedValue({ host: 'github.com', account: 'owner-acct' });+ const response = await request(app).post('/api/apps/app-001/forge-auth/refresh').send({ scopes: ['workflow'] });+ expect(response.status).toBe(409);+ expect(response.body.code).toBe('FORGE_REFRESH_HOST_CHANGED');+ expect(startForgeScopeRefresh).not.toHaveBeenCalled();+ });++ it('does not refresh the active account when the configured pin is unavailable', async () => {+ const error = Object.assign(new Error('Pinned account unavailable'), { status: 409, code: 'FORGE_ACCOUNT_UNAVAILABLE' });+ resolveForgeForRepo.mockRejectedValue(error);+ const response = await request(app).post('/api/apps/app-001/forge-auth/refresh').send({ scopes: ['workflow'] });+ expect(response.status).toBe(409);+ expect(response.body.code).toBe('FORGE_ACCOUNT_UNAVAILABLE');+ expect(startForgeScopeRefresh).not.toHaveBeenCalled();+ });+it('refuses GitLab, where glab has no scope refresh', async () => {resolveAppForgeTarget.mockResolvedValue({ tracker: 'gitlab', target: { forge: 'gitlab', webHost: 'gitlab.example.com' } });diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.jsindex 70e04dddea..a878ecbb5e 100644--- a/server/services/agentFinalization.js+++ b/server/services/agentFinalization.js@@ -606,7 +606,11 @@ async function observePrClaim({ task, workspacePath, success, prExpected, agentS// used. Dropping it would query as whatever ambient account `gh` happens to be// on, which on a multi-login host may not even see the PR — reading as// "no PR" for a run that opened one.- const { cli, env } = await resolveForgeForRepo(workspacePath).catch(() => ({ cli: 'gh', env: null }));+ const forge = await resolveForgeForRepo(workspacePath).catch(() => null);+ if (!forge) return prObservation(PR_OBSERVATION.FORGE_UNAVAILABLE, {+ branch, message: 'Could not resolve the repository forge account', inconclusive: true,+ });+ const { cli, env } = forge;const draft = task?.metadata?.prCompletion === PR_COMPLETIONS.DRAFT;const found = cli === 'glab'? await (await import('./gitlab.js')).findMergeRequestForBranch(branch, workspacePath, ...(draft ? [{ includeDraft: true }] : []))diff --git a/server/services/agentFinalization.prVerification.test.js b/server/services/agentFinalization.prVerification.test.jsindex 766c045d0b..e43718e1ef 100644--- a/server/services/agentFinalization.prVerification.test.js+++ b/server/services/agentFinalization.prVerification.test.js@@ -408,6 +408,14 @@ describe('verifyPrClaim (#3358)', () => {expect(getPullRequestStateMock).not.toHaveBeenCalled();});+ it('reports unavailable credentials without probing the PR as another account', async () => {+ onBranch('claim/issue-1');+ resolveForgeForRepoMock.mockRejectedValueOnce(Object.assign(new Error('Pin unavailable'), { code: 'FORGE_ACCOUNT_UNAVAILABLE' }));+ const verdict = await verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: true });+ expect(verdict).toMatchObject({ ok: false, category: FORGE_UNREACHABLE_CATEGORY });+ expect(findPullRequestForBranchMock).not.toHaveBeenCalled();+ });+it('fails with forge-unreachable — NOT pr-missing — when we could not ask', async () => {onBranch('claim/issue-1');findPullRequestForBranchMock.mockResolvedValue({diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.jsindex 1bdab22dd6..16d3b0cbb6 100644--- a/server/services/agentWorktreeCleanup.js+++ b/server/services/agentWorktreeCleanup.js@@ -229,8 +229,9 @@ async function probeWorktreePr(context, success) {.catch(err => ({ ok: false, category: 'forge-unreachable', message: err.message }));}const { findPullRequestForBranch } = await import('./github.js');- const { env } = await git.resolveForgeForRepo(worktreePath).catch(() => ({ env: null }));- return findPullRequestForBranch(worktreeBranch, { cwd: worktreePath, env: env || null })+ const forge = await git.resolveForgeForRepo(worktreePath).catch(() => null);+ if (!forge) return { status: 'unavailable' };+ return findPullRequestForBranch(worktreeBranch, { cwd: worktreePath, env: forge.env || null }).catch(() => ({ status: 'unavailable' }));}diff --git a/server/services/forgeAuth.js b/server/services/forgeAuth.jsindex b42ece6ebe..76dcbeca65 100644--- a/server/services/forgeAuth.js+++ b/server/services/forgeAuth.js@@ -9,9 +9,24 @@ import { realpath } from 'fs/promises';import { spawn } from '../lib/childProcess.js';import { execGitSafe } from '../lib/execGit.js';import { parseGitRemote, detectForgeCli, pickGhAccountForOwner } from '../lib/gitForge.js';+import { ServerError } from '../lib/errorHandler.js';import { listForgePinnedApps } from './agentAppWorkspace.js';const DEFAULT_SPAWN_CLI_TIMEOUT_MS = 10000;+const TOKEN_ENV_KEYS = ['GH_TOKEN', 'GITHUB_TOKEN', 'GH_ENTERPRISE_TOKEN', 'GITHUB_ENTERPRISE_TOKEN'];++// gh uses the public token family for Enterprise Cloud (*.ghe.com), too.+const tokenKeyForHost = (host) => host === 'github.com' || host.endsWith('.ghe.com')+ ? 'GH_TOKEN' : 'GH_ENTERPRISE_TOKEN';++function ghHostEnv(host, token = null) {+ const env = { ...process.env, GH_HOST: host };+ // Account discovery must read this host's keyring, never an ambient token+ // that can make a different account look like the requested login.+ for (const key of TOKEN_ENV_KEYS) delete env[key];+ if (token) env[tokenKeyForHost(host)] = token;+ return env;+}function spawnCli(cmd, args, timeoutMs = DEFAULT_SPAWN_CLI_TIMEOUT_MS, signal, env = null) {const timedOut = { code: -1, stdout: '', stderr: 'timed out' };@@ -44,19 +59,21 @@ function spawnCli(cmd, args, timeoutMs = DEFAULT_SPAWN_CLI_TIMEOUT_MS, signal, e});}-async function listGhAccounts(timeoutMs, signal) {- const { stdout, stderr } = await spawnCli('gh', ['auth', 'status', '-h', 'github.com'], timeoutMs, signal);+async function listGhAccounts(host, timeoutMs, signal) {+ const { stdout, stderr } = await spawnCli('gh', ['auth', 'status', '-h', host], timeoutMs, signal, ghHostEnv(host));// gh writes status to stderr in older versions, stdout in newer — search both.const text = `${stdout}\n${stderr}`;const accounts = [];- const re = /Logged in to github\.com account (\S+)/g;+ const re = /Logged in to (\S+) account (\S+)/g;let m;- while ((m = re.exec(text))) accounts.push(m[1]);+ while ((m = re.exec(text))) {+ if (m[1].toLowerCase() === host) accounts.push(m[2]);+ }return accounts;}-async function getGhTokenForAccount(login, timeoutMs, signal) {- const { code, stdout } = await spawnCli('gh', ['auth', 'token', '-u', login, '-h', 'github.com'], timeoutMs, signal);+async function getGhTokenForAccount(host, login, timeoutMs, signal) {+ const { code, stdout } = await spawnCli('gh', ['auth', 'token', '-u', login, '-h', host], timeoutMs, signal, ghHostEnv(host));return code === 0 ? stdout.trim() : null;}@@ -117,43 +134,33 @@ async function resolveConfiguredAccount(dir) {}/**- * The git commit identity for a gh account, as GitHub itself attributes it.- *- * `<id>+<login>@users.noreply.github.com` is the address GitHub links back to an- * account, so a commit authored with it shows up under that account — which is- * the point of pinning an app to a non-default account in the first place. The- * numeric id is REQUIRED for the link: the legacy `<login>@users.noreply` form- * predates account renames and no longer attributes reliably, so a probe that- * cannot read the id returns null rather than a plausible-looking address that- * silently attributes to nobody.- *- * @returns {Promise<{name: string, email: string}|null>}+ * Public GitHub retains its stable id+login noreply address. Enterprise hosts+ * define their own addresses; use the authenticated user's returned email or+ * leave commit identity alone if that API does not expose one.*/-async function getGhCommitIdentity(token, timeoutMs, signal) {- // Run the probe AS the pinned account. `gh api` otherwise answers for gh's- // mutable active user, which is exactly the ambient identity this override- // exists to escape — and the mismatch would be invisible, since the wrong- // answer is still a well-formed identity.+async function getGhCommitIdentity(host, token, timeoutMs, signal) {const { code, stdout } = await spawnCli(- 'gh', ['api', 'user', '--hostname', 'github.com', '--jq', '[.id, .login, .name] | @tsv'],- timeoutMs, signal, { ...process.env, GH_TOKEN: token, GITHUB_TOKEN: token }+ 'gh', ['api', 'user', '--hostname', host, '--jq', '[.id, .login, .name, .email] | @tsv'],+ timeoutMs, signal, ghHostEnv(host, token));if (code !== 0) return null;- const [id, login, name] = (stdout || '').trim().split('\t');+ const [id, login, name, email] = (stdout || '').trim().split('\t');if (!id || !login) return null;- return { name: name || login, email: `${id}+${login}@users.noreply.github.com` };+ const commitEmail = host === 'github.com' ? `${id}+${login}@users.noreply.github.com` : email;+ if (!commitEmail) return null;+ return { name: name || login, email: commitEmail };}/*** Resolve the forge CLI + auth env for a given repo directory.- * - For GitHub repos: pins `GH_TOKEN` to a specific logged-in gh account, so PR+ * - For GitHub repos: pins the host-specific token to a specific logged-in gh account, so PR* creation doesn't depend on `hosts.yml`'s mutable `user:` field (avoids the* multi-account "must be a collaborator" failure mode). The account is the* managed app's explicit `forgeAccount` when it has one, and otherwise the* logged-in account whose login matches the repo owner.* - For GitLab repos: uses glab as-is. glab is single-user-per-host, so its keyring* already disambiguates by host without the mutable-active-user pitfall.- * Falls back to ambient env when no match is possible.+ * Falls back to ambient env only without an explicit pin; unavailable pins fail.** `identity` is populated ONLY for an explicitly pinned `forgeAccount` — an* owner-match is an inference about which credential to use, not a statement@@ -168,40 +175,46 @@ async function getGhCommitIdentity(token, timeoutMs, signal) {* account: string|null, identity: {name: string, email: string}|null}>}*/export async function resolveForgeForRepo(dir, { timeoutMs = DEFAULT_SPAWN_CLI_TIMEOUT_MS, signal, forgeAccount = null } = {}) {+ const explicitPin = (typeof forgeAccount === 'string' && forgeAccount.trim()) ? forgeAccount.trim() : null;const remote = await execGitSafe(['remote', 'get-url', 'origin'], dir);const parsed = parseGitRemote(remote.stdout?.trim());if (!parsed) {+ if (explicitPin) throw new ServerError('The pinned GitHub account cannot be resolved without a repository origin.', {+ status: 409, code: 'FORGE_ACCOUNT_UNAVAILABLE',+ });return { cli: 'gh', env: process.env, host: null, owner: null, account: null, identity: null };}- const cli = detectForgeCli(parsed.host);- const base = { cli, env: process.env, host: parsed.host, owner: parsed.owner, identity: null };+ const host = parsed.host.toLowerCase();+ const cli = detectForgeCli(host);+ const base = { cli, env: process.env, host, owner: parsed.owner, identity: null };const ambient = { ...base, account: null };if (cli !== 'gh' || signal?.aborted) return ambient;- const explicitPin = (typeof forgeAccount === 'string' && forgeAccount.trim()) ? forgeAccount.trim() : null;const pinned = explicitPin || await resolveConfiguredAccount(dir);if (signal?.aborted) return ambient;// A pinned account skips the `gh auth status` listing entirely: the user named// the account, so the only question left is whether a token can be minted for- // it — and a pin that gh is not logged into must fail as "no token", not be+ // it — and a pin that gh is not logged into must refuse execution, not be// silently replaced by an owner-match against a different account.- const account = pinned || pickGhAccountForOwner(parsed.owner, await listGhAccounts(timeoutMs, signal));+ const account = pinned || pickGhAccountForOwner(parsed.owner, await listGhAccounts(host, timeoutMs, signal));if (signal?.aborted) return ambient;if (!account) return ambient;- const token = await getGhTokenForAccount(account, timeoutMs, signal);- if (signal?.aborted || !token) return { ...base, account };+ const token = await getGhTokenForAccount(host, account, timeoutMs, signal);+ if (signal?.aborted || !token) {+ if (pinned) throw new ServerError(`The pinned GitHub account ${account} is unavailable on ${host}. Check gh auth status -h ${host}.`, {+ status: 409, code: 'FORGE_ACCOUNT_UNAVAILABLE', context: { host, account },+ });+ return { ...base, account };+ }- const identity = pinned ? await getGhCommitIdentity(token, timeoutMs, signal) : null;+ const identity = pinned ? await getGhCommitIdentity(host, token, timeoutMs, signal) : null;if (signal?.aborted) return { ...base, account };- const env = { ...process.env, GH_TOKEN: token };- delete env.GITHUB_TOKEN;- delete env.GH_ENTERPRISE_TOKEN;- delete env.GITHUB_ENTERPRISE_TOKEN;+ const env = ghHostEnv(host, token);return { ...base, env, account, identity };}@@ -225,13 +238,13 @@ export async function resolveForgeForRepo(dir, { timeoutMs = DEFAULT_SPAWN_CLI_T* agent process instead of mutating a repository PortOS does not own, and git* gives them precedence over every config level.*- * Returns `{}` when no github.com account and token were resolved, so the child- * keeps whatever gh auth it would have used. Best-effort and bounded: never- * throws, and a stalled `gh` probe times out to `{}` so a spawn is never blocked.+ * Returns `{}` when no host-specific account and token were resolved, so the child+ * keeps whatever gh auth it would have used. An unavailable explicit pin or a+ * timed-out lookup refuses the spawn rather than silently using another login.* @param {string} dir - Repo (or worktree) root* @param {object} [opts]* @param {number} [opts.timeoutMs=10000] - Cap on the git+gh probe before giving up- * @returns {Promise<{ GH_TOKEN?: string, GIT_AUTHOR_NAME?: string, GIT_AUTHOR_EMAIL?: string,+ * @returns {Promise<{ GH_TOKEN?: string, GH_ENTERPRISE_TOKEN?: string, GH_HOST?: string, GIT_AUTHOR_NAME?: string, GIT_AUTHOR_EMAIL?: string,* GIT_COMMITTER_NAME?: string, GIT_COMMITTER_EMAIL?: string }>}*/export async function resolveForgeTokenEnv(dir, { timeoutMs = 10000, forgeAccount = null } = {}) {@@ -242,36 +255,28 @@ export async function resolveForgeTokenEnv(dir, { timeoutMs = 10000, forgeAccounlet timer;const controller = new AbortController();const resolved = await Promise.race([- resolveForgeForRepo(dir, { timeoutMs, signal: controller.signal, forgeAccount }).catch(() => null),- new Promise((r) => {+ resolveForgeForRepo(dir, { timeoutMs, signal: controller.signal, forgeAccount }),+ new Promise((_, reject) => {timer = setTimeout(() => {controller.abort();- r(null);+ reject(new ServerError('GitHub account resolution timed out. Retry after checking gh auth status.', {+ status: 503, code: 'FORGE_AUTH_TIMEOUT',+ }));}, timeoutMs);timer.unref?.();}),- ]);- clearTimeout(timer);- // Overlay a token ONLY for a genuinely-minted github.com credential. Two gates:- // - host === 'github.com': detectForgeCli defaults an unrecognized/GHES host to- // `gh`, and resolveForgeForRepo's account/token probes are hardcoded to- // `-h github.com`. Without this gate, a Bitbucket/GHES repo whose owner segment- // happens to match a local github.com login would get that github.com token- // injected into every agent — the wrong (or a leaked) credential.- // - env !== process.env: resolveForgeForRepo returns a NEW env object- // (`{ ...process.env, GH_TOKEN }`) ONLY on a successful mint; every other- // branch (no match, token fetch failed) returns the ambient `process.env` by- // reference. Keying on `account` alone would re-emit the ambient GH_TOKEN when- // the account matched but the token fetch failed.- const minted = resolved && resolved.host === 'github.com' && resolved.env !== process.env;- const token = minted ? resolved.env.GH_TOKEN : null;+ ]).finally(() => clearTimeout(timer));+ // Only a successful host-specific keyring lookup creates a new env. The CLI+ // defaults unknown forges to gh, so neither its name nor an account match is+ // sufficient evidence that a credential was actually found for this host.+ const minted = resolved?.host && resolved.env !== process.env;+ const tokenKey = minted ? tokenKeyForHost(resolved.host) : null;+ const token = tokenKey ? resolved.env[tokenKey] : null;if (!token) return {};- // Identity rides the SAME gates as the token — it is only ever populated for a- // minted github.com credential on an explicitly pinned account, so an identity- // can never be overlaid onto a repo whose token was not.const identity = resolved.identity;return {- GH_TOKEN: token,+ GH_HOST: resolved.host,+ [tokenKey]: token,...(identity ? {GIT_AUTHOR_NAME: identity.name,GIT_AUTHOR_EMAIL: identity.email,diff --git a/server/services/forgeAuth.test.js b/server/services/forgeAuth.test.jsindex 2b16a97931..9bc5283ede 100644--- a/server/services/forgeAuth.test.js+++ b/server/services/forgeAuth.test.js@@ -13,6 +13,7 @@ vi.mock('./agentAppWorkspace.js', () => ({ listForgePinnedApps: vi.fn(async () =import { spawn } from '../lib/childProcess.js';import { listForgePinnedApps } from './agentAppWorkspace.js';import { resolveForgeForRepo, resolveForgeTokenEnv } from './forgeAuth.js';+import { resolveForgeExecOptions } from './forgeExecOptions.js';// Exercise remote discovery and authentication without a real credential store.function respond({ stdout = '', stderr = '', code = 0 } = {}) {@@ -52,24 +53,24 @@ describe('forge credential resolution', () => {const forge = await resolveForgeForRepo('/example/repo');// The resolver strips every other ambient token; derive the expectation the// same way so a CI/proxy environment that exports GITHUB_TOKEN can't fail it.- const expectedEnv = { ...process.env, GH_TOKEN: 'test-owner-token' };+ const expectedEnv = { ...process.env, GH_HOST: 'github.com', GH_TOKEN: 'test-owner-token' };for (const key of ['GITHUB_TOKEN', 'GH_ENTERPRISE_TOKEN', 'GITHUB_ENTERPRISE_TOKEN']) delete expectedEnv[key];expect(forge).toEqual({cli: 'gh', host: 'github.com', owner: 'example-owner', account: 'example-owner',env: expectedEnv, identity: null});- expect(spawn).toHaveBeenNthCalledWith(3, 'gh', ['auth', 'token', '-u', 'example-owner', '-h', 'github.com'], { shell: false });+ expect(spawn).toHaveBeenNthCalledWith(3, 'gh', ['auth', 'token', '-u', 'example-owner', '-h', 'github.com'], { shell: false, env: expect.objectContaining({ GH_HOST: 'github.com' }) });expect(process.env.GH_TOKEN).toBe('test-ambient-token');});it('gives agent launches only the newly resolved token', async () => {githubAccount();- await expect(resolveForgeTokenEnv('/example/repo')).resolves.toEqual({ GH_TOKEN: 'test-owner-token' });+ await expect(resolveForgeTokenEnv('/example/repo')).resolves.toEqual({ GH_HOST: 'github.com', GH_TOKEN: 'test-owner-token' });});it.each([['failed token lookup', { tokenCode: 1 }],- ['a non-github.com host', { host: 'github.example.com' }]+ ['another host returned by gh status', { host: 'github.example.com' }]])('does not overlay ambient or wrong-host credentials after %s', async (_label, options) => {githubAccount(options);await expect(resolveForgeTokenEnv('/example/repo')).resolves.toEqual({});@@ -92,7 +93,7 @@ describe('forge credential resolution', () => {expect(spawn).toHaveBeenCalledTimes(3);});- it('bounds a stalled credential probe so an agent launch can continue', async () => {+ it('refuses a stalled lookup rather than launching an agent as an unverified account', async () => {vi.useFakeTimers();respond({ stdout: '[email protected]:example-owner/project.git\n' });const stalled = new EventEmitter();@@ -101,13 +102,14 @@ describe('forge credential resolution', () => {stalled.kill = vi.fn();spawn.mockImplementationOnce(() => stalled);const pending = resolveForgeTokenEnv('/example/repo', { timeoutMs: 25 });+ const refused = expect(pending).rejects.toMatchObject({ code: 'FORGE_AUTH_TIMEOUT' });await vi.advanceTimersByTimeAsync(25);- await expect(pending).resolves.toEqual({});+ await refused;expect(stalled.kill).toHaveBeenCalledWith('SIGKILL');// A close emitted after the timeout must not change the settled result.stalled.emit('close', 1);- await expect(pending).resolves.toEqual({});+ await expect(pending).rejects.toMatchObject({ code: 'FORGE_AUTH_TIMEOUT' });});it('aborts a token probe that starts near the end of the whole lookup budget', async () => {@@ -133,11 +135,12 @@ describe('forge credential resolution', () => {spawn.mockImplementationOnce(() => token);const pending = resolveForgeTokenEnv('/example/repo', { timeoutMs: 10 });+ const refused = expect(pending).rejects.toMatchObject({ code: 'FORGE_AUTH_TIMEOUT' });await vi.advanceTimersByTimeAsync(9);expect(spawn).toHaveBeenCalledTimes(3);await vi.advanceTimersByTimeAsync(1);- await expect(pending).resolves.toEqual({});+ await refused;expect(token.kill).toHaveBeenCalledWith('SIGKILL');});@@ -150,8 +153,9 @@ describe('forge credential resolution', () => {spawn.mockImplementationOnce(() => git);const pending = resolveForgeTokenEnv('/example/repo', { timeoutMs: 10 });+ const refused = expect(pending).rejects.toMatchObject({ code: 'FORGE_AUTH_TIMEOUT' });await vi.advanceTimersByTimeAsync(10);- await expect(pending).resolves.toEqual({});+ await refused;git.stdout.emit('data', '[email protected]:example-owner/project.git\n');git.emit('close', 0);@@ -177,6 +181,7 @@ describe('per-app forge account pinning', () => {it('authenticates and commits as the pinned account, not the repo owner', async () => {pinnedAccount();await expect(resolveForgeTokenEnv('/example/repo')).resolves.toEqual({+ GH_HOST: 'github.com',GH_TOKEN: 'acme-bot-token',GIT_AUTHOR_NAME: 'Acme Bot',GIT_AUTHOR_EMAIL: '[email protected]',@@ -186,7 +191,7 @@ describe('per-app forge account pinning', () => {// The owner (`acme`) never matched a logged-in login, so the pre-pin code// would have resolved no account at all — and `gh auth status` is not run.expect(spawn).toHaveBeenCalledTimes(4);- expect(spawn).toHaveBeenNthCalledWith(3, 'gh', ['auth', 'token', '-u', 'acme-bot', '-h', 'github.com'], { shell: false });+ expect(spawn).toHaveBeenNthCalledWith(3, 'gh', ['auth', 'token', '-u', 'acme-bot', '-h', 'github.com'], { shell: false, env: expect.objectContaining({ GH_HOST: 'github.com' }) });});it('runs the identity probe as the pinned account rather than gh\u2019s active user', async () => {@@ -201,12 +206,13 @@ describe('per-app forge account pinning', () => {// A commit authored as nobody is worse than one authored ambiently, so an// unreadable identity must drop the override without dropping the credential.pinnedAccount({ identityCode: 1 });- await expect(resolveForgeTokenEnv('/example/repo')).resolves.toEqual({ GH_TOKEN: 'acme-bot-token' });+ await expect(resolveForgeTokenEnv('/example/repo')).resolves.toEqual({ GH_HOST: 'github.com', GH_TOKEN: 'acme-bot-token' });});it('does not fall back to an owner match when the pinned account has no token', async () => {pinnedAccount({ tokenCode: 1 });- await expect(resolveForgeTokenEnv('/example/repo')).resolves.toEqual({});+ await expect(resolveForgeTokenEnv('/example/repo')).rejects.toMatchObject({ code: 'FORGE_ACCOUNT_UNAVAILABLE' });+ expect(spawn).toHaveBeenCalledTimes(3);});it('maps an agent worktree back to the checkout the pin is registered against', async () => {@@ -237,7 +243,7 @@ describe('per-app forge account pinning', () => {respond({ stdout: `${link}/.git\n` });respond({ stdout: 'acme-bot-token\n' });respond({ stdout: '4242\tacme-bot\tAcme Bot\n' });- await expect(resolveForgeTokenEnv(link)).resolves.toMatchObject({ GH_TOKEN: 'acme-bot-token' });+ await expect(resolveForgeTokenEnv(link)).resolves.toMatchObject({ GH_HOST: 'github.com', GH_TOKEN: 'acme-bot-token' });} finally {rmSync(home, { recursive: true, force: true });}@@ -245,7 +251,7 @@ describe('per-app forge account pinning', () => {it('leaves an unpinned app on the inferred account with ambient commit identity', async () => {githubAccount();- await expect(resolveForgeTokenEnv('/example/repo')).resolves.toEqual({ GH_TOKEN: 'test-owner-token' });+ await expect(resolveForgeTokenEnv('/example/repo')).resolves.toEqual({ GH_HOST: 'github.com', GH_TOKEN: 'test-owner-token' });// No rev-parse: nothing pins an account, so the worktree lookup is skipped.expect(spawn).toHaveBeenCalledTimes(3);});@@ -256,7 +262,7 @@ describe('per-app forge account pinning', () => {respond({ stdout: '/example/repo/.git\n' });respond({ stderr: 'Logged in to github.com account example-owner\n' });respond({ stdout: 'test-owner-token\n' });- await expect(resolveForgeTokenEnv('/example/repo')).resolves.toEqual({ GH_TOKEN: 'test-owner-token' });+ await expect(resolveForgeTokenEnv('/example/repo')).resolves.toEqual({ GH_HOST: 'github.com', GH_TOKEN: 'test-owner-token' });});it('honors explicit forgeAccount option directly and strips conflicting env tokens', async () => {@@ -274,3 +280,90 @@ describe('per-app forge account pinning', () => {expect(listForgePinnedApps).not.toHaveBeenCalled();});});+++describe('host-bound execution and child credentials', () => {+ // The same owner and pinned login exist on both hosts; every credential and+ // identity must follow the origin, even when all ambient tokens are present.+ it.each([+ ['github.com', 'GH_TOKEN', '[email protected]'],+ ['ghe.example.com', 'GH_ENTERPRISE_TOKEN', '[email protected]'],+ ['acme.ghe.com', 'GH_TOKEN', '[email protected]'],+ ])('isolates pinned credentials and commit identity on %s', async (host, tokenKey, email) => {+ for (const key of ['GH_TOKEN', 'GITHUB_TOKEN', 'GH_ENTERPRISE_TOKEN', 'GITHUB_ENTERPRISE_TOKEN']) vi.stubEnv(key, `ambient-${key}`);+ vi.stubEnv('GH_HOST', 'other.example.com');+ const queuePin = () => {+ respond({ stdout: `git@${host}:acme/widget.git` });+ respond({ stdout: `${host}-token` });+ respond({ stdout: '4242\tacme-bot\tAcme Bot\[email protected]\n' });+ };+ queuePin();+ const options = await resolveForgeExecOptions('/example/repo', { forgeAccount: 'acme-bot' });+ expect(options).toMatchObject({ cwd: '/example/repo', env: { GH_HOST: host, [tokenKey]: `${host}-token` } });+ expect(options.customEnv).toBe(options.env);+ for (const key of ['GH_TOKEN', 'GITHUB_TOKEN', 'GH_ENTERPRISE_TOKEN', 'GITHUB_ENTERPRISE_TOKEN']) {+ expect(spawn.mock.calls[1][2].env[key]).toBeUndefined();+ if (key !== tokenKey) expect(options.env[key]).toBeUndefined();+ }+ expect(spawn.mock.calls[1][1]).toEqual(['auth', 'token', '-u', 'acme-bot', '-h', host]);+ expect(spawn.mock.calls[2][1]).toEqual(['api', 'user', '--hostname', host, '--jq', '[.id, .login, .name, .email] | @tsv']);+ expect(spawn.mock.calls[2][2].env).toEqual(options.env);++ queuePin();+ const overlay = await resolveForgeTokenEnv('/example/repo', { forgeAccount: 'acme-bot' });+ expect(overlay).toEqual({+ GH_HOST: host, [tokenKey]: `${host}-token`,+ GIT_AUTHOR_NAME: 'Acme Bot', GIT_AUTHOR_EMAIL: email,+ GIT_COMMITTER_NAME: 'Acme Bot', GIT_COMMITTER_EMAIL: email,+ });+ expect(process.env[tokenKey]).toBe(`ambient-${tokenKey}`);+ });++ it('owner-matches only accounts reported for the enterprise origin', async () => {+ respond({ stdout: '[email protected]:acme/widget.git' });+ respond({ stdout: 'Logged in to github.com account acme\nLogged in to ghe.example.com account acme\n' });+ respond({ stdout: 'enterprise-token' });+ const options = await resolveForgeExecOptions('/example/repo');+ expect(options.env.GH_ENTERPRISE_TOKEN).toBe('enterprise-token');+ expect(options.env.GH_TOKEN).toBeUndefined();+ expect(spawn.mock.calls[1][1]).toEqual(['auth', 'status', '-h', 'ghe.example.com']);+ expect(spawn.mock.calls[2][1]).toEqual(['auth', 'token', '-u', 'acme', '-h', 'ghe.example.com']);+ });++ it('refuses unavailable enterprise pins before callers can execute with ambient auth', async () => {+ respond({ stdout: '[email protected]:acme/widget.git' });+ respond({ code: 1 });+ await expect(resolveForgeExecOptions('/example/repo', { forgeAccount: 'acme-bot' }))+ .rejects.toMatchObject({ code: 'FORGE_ACCOUNT_UNAVAILABLE' });+ expect(spawn).toHaveBeenCalledTimes(2);+ expect(spawn.mock.calls[1][1]).toEqual(['auth', 'token', '-u', 'acme-bot', '-h', 'ghe.example.com']);+ });++ it('does not invent a public-host noreply identity when enterprise email is unavailable', async () => {+ respond({ stdout: '[email protected]:acme/widget.git' });+ respond({ stdout: 'enterprise-token' });+ respond({ stdout: '4242\tacme-bot\tAcme Bot\t\n' });+ await expect(resolveForgeTokenEnv('/example/repo', { forgeAccount: 'acme-bot' }))+ .resolves.toEqual({ GH_HOST: 'ghe.example.com', GH_ENTERPRISE_TOKEN: 'enterprise-token' });+ });++ it('keeps an unknown forge ambient without querying public GitHub credentials', async () => {+ respond({ stdout: '[email protected]:acme/widget.git' });+ respond({ code: 1 });+ const options = await resolveForgeExecOptions('/example/repo');+ expect(options.env).toBe(process.env);+ expect(spawn).toHaveBeenCalledTimes(2);+ expect(spawn.mock.calls[1][1]).toEqual(['auth', 'status', '-h', 'bitbucket.org']);+ expect(spawn.mock.calls[1][2].env.GH_TOKEN).toBeUndefined();+ });+});++it('refuses an explicit account pin when its repository cannot be resolved', async () => {+ await expect(resolveForgeExecOptions(null, { forgeAccount: 'acme-bot' }))+ .rejects.toMatchObject({ code: 'FORGE_ACCOUNT_UNAVAILABLE' });+ expect(spawn).not.toHaveBeenCalled();+ respond({ code: 1 });+ await expect(resolveForgeExecOptions('/example/repo', { forgeAccount: 'acme-bot' }))+ .rejects.toMatchObject({ code: 'FORGE_ACCOUNT_UNAVAILABLE' });+ expect(spawn).toHaveBeenCalledTimes(1);+});diff --git a/server/services/forgeExecOptions.js b/server/services/forgeExecOptions.jsindex eb82fc9e52..7761c92641 100644--- a/server/services/forgeExecOptions.js+++ b/server/services/forgeExecOptions.js@@ -8,6 +8,7 @@* living INSIDE it could only be tested against a re-implementation of itself.* Here, a suite mocks whichever of the two layers it is not exercising.*/+import { ServerError } from '../lib/errorHandler.js';import { resolveForgeForRepo } from './forgeAuth.js';/**@@ -23,8 +24,8 @@ import { resolveForgeForRepo } from './forgeAuth.js';* `resolveForgeForRepo` already owner-matches against the locally logged-in* accounts; the explicit pin then covers the rest.*- * Never throws: an unresolvable repo degrades to the ambient env, which is- * exactly the behavior every caller had before threading this through.+ * An unresolvable origin keeps the ambient env. Credential failures propagate:+ * an unavailable pin must never turn into execution as the active account.* `customEnv` is null when nothing was overlaid, so a caller can pass the* overlay to `ensureForgeReachable` only when there is one.*@@ -34,8 +35,11 @@ import { resolveForgeForRepo } from './forgeAuth.js';* @returns {Promise<{cwd: string|undefined, env: object, customEnv: object|null}>}*/export async function resolveForgeExecOptions(repoPath, { forgeAccount = null } = {}) {+ if (!repoPath && forgeAccount) throw new ServerError('The pinned GitHub account requires a repository path.', {+ status: 409, code: 'FORGE_ACCOUNT_UNAVAILABLE',+ });const forgeAuth = repoPath- ? await resolveForgeForRepo(repoPath, { forgeAccount }).catch(() => null)+ ? await resolveForgeForRepo(repoPath, { forgeAccount }): null;const customEnv = forgeAuth?.env && forgeAuth.env !== process.env ? forgeAuth.env : null;return { cwd: repoPath || undefined, env: customEnv || process.env, customEnv };diff --git a/server/services/forgeScopeRefresh.js b/server/services/forgeScopeRefresh.jsindex 198f7c8797..d94e303b46 100644--- a/server/services/forgeScopeRefresh.js+++ b/server/services/forgeScopeRefresh.js@@ -35,11 +35,11 @@ const DEVICE_URL_RE = /(https?:\/\/[^\s]+\/login\/device)/i;const TOKEN_ENV_KEYS = ['GH_TOKEN', 'GITHUB_TOKEN', 'GH_ENTERPRISE_TOKEN', 'GITHUB_ENTERPRISE_TOKEN'];// The variable gh would authenticate with for `host` ahead of the keyring. On-// github.com an owner-matched account's token is minted from the keyring and+// any host an owner-matched account's token is minted from the keyring and// overrides any ambient GH_TOKEN, so it only counts when no account was resolved.const envTokenFor = (host, expectedAccount) => {- const names = host === 'github.com' ? ['GH_TOKEN', 'GITHUB_TOKEN'] : ['GH_ENTERPRISE_TOKEN', 'GITHUB_ENTERPRISE_TOKEN'];- if (host === 'github.com' && expectedAccount) return null;+ const names = (host === 'github.com' || host.endsWith('.ghe.com')) ? ['GH_TOKEN', 'GITHUB_TOKEN'] : ['GH_ENTERPRISE_TOKEN', 'GITHUB_ENTERPRISE_TOKEN'];+ if (expectedAccount) return null;return names.find((name) => process.env[name]) || null;};diff --git a/server/services/forgeScopeRefresh.test.js b/server/services/forgeScopeRefresh.test.jsindex 5d70abe7d4..e27f6e6061 100644--- a/server/services/forgeScopeRefresh.test.js+++ b/server/services/forgeScopeRefresh.test.js@@ -157,6 +157,18 @@ describe('startForgeScopeRefresh', () => {expect(spawnMock).not.toHaveBeenCalled();});+ it('refreshes the pinned enterprise keyring account despite an unrelated ambient token', async () => {+ vi.stubEnv('GH_ENTERPRISE_TOKEN', 'ambient-token');+ execGh.mockResolvedValue('owner-acct');+ const { jobId } = await startForgeScopeRefresh({ host: 'ghe.example.com', scopes: ['workflow'], expectedAccount: 'owner-acct' });+ expect(execGh).toHaveBeenCalledWith(+ ['api', 'user', '--hostname', 'ghe.example.com', '--jq', '.login'],+ expect.any(Number), expect.objectContaining({ env: expect.not.objectContaining({ GH_ENTERPRISE_TOKEN: 'ambient-token' }) }),+ );+ await settle(jobId);+ vi.unstubAllEnvs();+ });+it('refuses when the active account cannot be verified and releases the host reservation', async () => {execGh.mockRejectedValue(new Error('network unavailable'));diff --git a/server/services/jevTraining.js b/server/services/jevTraining.jsindex 5acaf0f546..71bb53a436 100644--- a/server/services/jevTraining.js+++ b/server/services/jevTraining.js@@ -106,7 +106,7 @@ async function runTraining({ repoPath, architecture }) {// Deferred because `forgeAuth.js` reaches the git/forge stack this module has// no other use for.const { resolveForgeForRepo } = await import('./forgeAuth.js');- const forge = await resolveForgeForRepo(repoPath).catch(() => null);+ const forge = await resolveForgeForRepo(repoPath);const { buildScopeAdherenceCorpus } = await corpusBuilder();const corpus = await buildScopeAdherenceCorpus({ repoPath, env: forge?.env || null });if (!corpus.ok) return corpus;diff --git a/server/services/managedAppRepositories.js b/server/services/managedAppRepositories.jsindex 425089f46b..d2a3a368c1 100644--- a/server/services/managedAppRepositories.js+++ b/server/services/managedAppRepositories.js@@ -51,7 +51,7 @@ function remoteIdentity(url) {async function githubRepositoryMetadata(repoPath, origin) {if (!origin?.fullName || !isGithubHost(origin.host)) return null;- const forge = await resolveForgeForRepo(repoPath).catch(() => null);+ const forge = await resolveForgeForRepo(repoPath);const host = githubApiHost(origin.host);const raw = await execGh(['api', ...(host === 'github.com' ? [] : ['--hostname', host]),@@ -130,7 +130,7 @@ async function compareForkWithUpstream(checkout, repoPath) {const upstreamOwner = checkout.upstream.owner;const originOwner = checkout.origin.owner;const basehead = encodeURIComponent(`${upstreamOwner}:${branch}...${originOwner}:${branch}`);- const forge = await resolveForgeForRepo(repoPath).catch(() => null);+ const forge = await resolveForgeForRepo(repoPath);const host = githubApiHost(checkout.origin.host);const raw = await execGh(['api', ...(host === 'github.com' ? [] : ['--hostname', host]),@@ -335,7 +335,7 @@ export async function syncManagedAppFork(app) {);}const branch = upstream.branch || null;- const forge = await resolveForgeForRepo(app.repoPath).catch(() => null);+ const forge = await resolveForgeForRepo(app.repoPath);const args = ['repo', 'sync', origin.fullName, '--source', upstream.fullName];if (branch) args.push('--branch', branch);const output = await execGh(args, GH_TIMEOUT_MS, {diff --git a/server/services/managedAppRepositories.test.js b/server/services/managedAppRepositories.test.jsindex a0ad5791f9..a2c0b460fb 100644--- a/server/services/managedAppRepositories.test.js+++ b/server/services/managedAppRepositories.test.js@@ -85,6 +85,12 @@ describe('managed app repository topology', () => {});});+ it('refuses fork sync before any forge operation when the pinned account is unavailable', async () => {+ mock.resolveForgeForRepo.mockRejectedValue(Object.assign(new Error('Pinned account unavailable'), { code: 'FORGE_ACCOUNT_UNAVAILABLE' }));+ await expect(syncManagedAppFork(app)).rejects.toMatchObject({ code: 'FORGE_ACCOUNT_UNAVAILABLE' });+ expect(mock.execGh).not.toHaveBeenCalled();+ });+it('discovers a canonical upstream from GitHub fork metadata without app-specific constants', async () => {const topology = await resolveRepositoryTopology(REPO);diff --git a/server/services/perpetualWork.forgeAuth.test.js b/server/services/perpetualWork.forgeAuth.test.jsnew file mode 100644index 0000000000..fdef73eb91--- /dev/null+++ b/server/services/perpetualWork.forgeAuth.test.js@@ -0,0 +1,44 @@+import { EventEmitter } from 'node:events';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';++vi.mock('./cosEvents.js', () => ({ cosEvents: { emit: vi.fn() }, emitLog: vi.fn() }));+vi.mock('../lib/childProcess.js', async (original) => ({ ...(await original()), spawn: vi.fn() }));+vi.mock('./forgeAuth.js', () => ({ resolveForgeTokenEnv: vi.fn() }));++import { spawn } from '../lib/childProcess.js';+import { resolveForgeTokenEnv } from './forgeAuth.js';+import { detectGithubIssues } from './perpetualWork.js';++beforeEach(() => {+ vi.resetAllMocks();+ spawn.mockImplementation(() => {+ const child = new EventEmitter();+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ child.kill = vi.fn();+ queueMicrotask(() => { child.stdout.emit('data', '[]'); child.emit('close', 0); });+ return child;+ });+});+afterEach(() => vi.unstubAllEnvs());++it('carries the enterprise account through every issue scan probe', async () => {+ vi.stubEnv('GH_TOKEN', 'public-ambient-token');+ vi.stubEnv('GITHUB_ENTERPRISE_TOKEN', 'enterprise-ambient-token');+ resolveForgeTokenEnv.mockResolvedValue({ GH_HOST: 'ghe.example.com', GH_ENTERPRISE_TOKEN: 'enterprise-pin-token' });+ await detectGithubIssues({ id: 'example', repoPath: '/example/repo' }, { issueAuthorFilter: 'any' });+ const probes = spawn.mock.calls.filter(([cmd]) => cmd === 'gh');+ expect(probes.length).toBeGreaterThan(0);+ for (const [, , { env }] of probes) {+ expect(env).toMatchObject({ GH_HOST: 'ghe.example.com', GH_ENTERPRISE_TOKEN: 'enterprise-pin-token' });+ expect(env.GH_TOKEN).toBeUndefined();+ expect(env.GITHUB_ENTERPRISE_TOKEN).toBeUndefined();+ }+});++it('refuses an issue scan when its account pin is unavailable', async () => {+ resolveForgeTokenEnv.mockRejectedValue(Object.assign(new Error('Pin unavailable'), { code: 'FORGE_ACCOUNT_UNAVAILABLE' }));+ await expect(detectGithubIssues({ id: 'example', repoPath: '/example/repo' }, { issueAuthorFilter: 'any' }))+ .rejects.toMatchObject({ code: 'FORGE_ACCOUNT_UNAVAILABLE' });+ expect(spawn).not.toHaveBeenCalled();+});diff --git a/server/services/perpetualWork.js b/server/services/perpetualWork.jsindex d78f9651d1..c3e13606c4 100644--- a/server/services/perpetualWork.js+++ b/server/services/perpetualWork.js@@ -415,13 +415,11 @@ const MAX_COLLABORATOR_AUTHOR_QUERIES = 25;async function resolveGithubDetectorEnv(repoPath, env) {if (env) return env;const { resolveForgeTokenEnv } = await import('./forgeAuth.js');- const overlay = await resolveForgeTokenEnv(repoPath).catch(() => ({}));- if (!overlay?.GH_TOKEN) return undefined;- const merged = { ...process.env, ...overlay };- delete merged.GITHUB_TOKEN;- delete merged.GH_ENTERPRISE_TOKEN;- delete merged.GITHUB_ENTERPRISE_TOKEN;- return merged;+ const overlay = await resolveForgeTokenEnv(repoPath);+ if (!overlay?.GH_TOKEN && !overlay?.GH_ENTERPRISE_TOKEN) return undefined;+ const merged = { ...process.env };+ for (const key of ['GH_TOKEN', 'GITHUB_TOKEN', 'GH_ENTERPRISE_TOKEN', 'GITHUB_ENTERPRISE_TOKEN']) delete merged[key];+ return { ...merged, ...overlay };}// Per-forge config for the shared issue detector. Each entry captures only what