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: preserve unpinned forge lookup fallback and normalize hosts
Adam Eivyd57e237cedb1
diff --git a/server/routes/apps/forgeAuth.js b/server/routes/apps/forgeAuth.jsindex c484cb7d8f..cef5a130a0 100644--- a/server/routes/apps/forgeAuth.js+++ b/server/routes/apps/forgeAuth.js@@ -44,18 +44,21 @@ router.post('/:id/forge-auth/refresh', loadApp, asyncHandler(async (req, res) =>code: 'FORGE_REFRESH_UNSUPPORTED',});}- const host = target.webHost || target.apiHost;+ const host = (target.webHost || target.apiHost)?.toLowerCase();if (!host) throw new ServerError("This app's forge host could not be resolved", { status: 409, code: 'FORGE_REFRESH_UNSUPPORTED' });// 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 });- if (resolved.host !== host) throw new ServerError("This app's forge host changed during account resolution. Retry the refresh.", {+ if (!resolved.host) throw new ServerError("This app's forge host could not be resolved", {+ status: 409, code: 'FORGE_REFRESH_UNSUPPORTED',+ });+ if (resolved.host.toLowerCase() !== 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 });+ 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 98729ff7f9..a445626984 100644--- a/server/routes/apps/forgeAuth.test.js+++ b/server/routes/apps/forgeAuth.test.js@@ -58,6 +58,19 @@ describe('app forge-auth routes', () => {expect(startForgeScopeRefresh).toHaveBeenCalledWith(expect.objectContaining({ expectedAccount: 'owner-acct' }));});+ it('normalizes host case and rejects an unresolved origin separately', async () => {+ resolveAppForgeTarget.mockResolvedValue({ target: { forge: 'github', webHost: 'GHE.EXAMPLE.COM' } });+ const response = await request(app).post('/api/apps/app-001/forge-auth/refresh').send({ scopes: ['workflow'] });+ expect(response.status).toBe(202);+ expect(startForgeScopeRefresh).toHaveBeenCalledWith(expect.objectContaining({ host: 'ghe.example.com' }));+ startForgeScopeRefresh.mockClear();+ resolveForgeForRepo.mockResolvedValue({ host: null, account: null });+ const missing = await request(app).post('/api/apps/app-001/forge-auth/refresh').send({ scopes: ['workflow'] });+ expect(missing.status).toBe(409);+ expect(missing.body.code).toBe('FORGE_REFRESH_UNSUPPORTED');+ expect(startForgeScopeRefresh).not.toHaveBeenCalled();+ });+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'] });diff --git a/server/services/forgeAuth.js b/server/services/forgeAuth.jsindex 76dcbeca65..e9586e6f24 100644--- a/server/services/forgeAuth.js+++ b/server/services/forgeAuth.js@@ -9,6 +9,7 @@ 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 { githubApiHost } from '../lib/workTracker.js';import { ServerError } from '../lib/errorHandler.js';import { listForgePinnedApps } from './agentAppWorkspace.js';@@ -174,27 +175,38 @@ async function getGhCommitIdentity(host, token, timeoutMs, signal) {* @returns {Promise<{cli: string, env: object, host: string|null, owner: string|null,* account: string|null, identity: {name: string, email: string}|null}>}*/-export async function resolveForgeForRepo(dir, { timeoutMs = DEFAULT_SPAWN_CLI_TIMEOUT_MS, signal, forgeAccount = null } = {}) {+export function resolveForgeForRepo(dir, opts = {}) {+ return resolveForgeWithPin(dir, opts);+}++// A shared pin state lets the bounded child-overlay lookup distinguish an+// unpinned timeout (ambient is fine) from an unresolved or explicit pin.+async function resolveForgeWithPin(dir, { timeoutMs = DEFAULT_SPAWN_CLI_TIMEOUT_MS, signal, forgeAccount = null } = {}, pinState = {}) {const explicitPin = (typeof forgeAccount === 'string' && forgeAccount.trim()) ? forgeAccount.trim() : null;+ pinState.account = explicitPin || await resolveConfiguredAccount(dir);+ return resolveForgeCredentials(dir, { timeoutMs, signal, pinned: pinState.account }).catch((error) => {+ if (pinState.account) throw error;+ return { cli: 'gh', env: process.env, host: null, owner: null, account: null, identity: null };+ });+}++async function resolveForgeCredentials(dir, { timeoutMs, signal, pinned }) {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.', {+ if (pinned) 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 host = parsed.host.toLowerCase();+ const host = githubApiHost(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 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 refuse execution, not be@@ -240,7 +252,7 @@ export async function resolveForgeForRepo(dir, { timeoutMs = DEFAULT_SPAWN_CLI_T** 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.+ * timed-out pinned 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@@ -254,12 +266,14 @@ export async function resolveForgeTokenEnv(dir, { timeoutMs = 10000, forgeAccoun// gh subprocess keeps its own timeout as a second bound for direct callers.let timer;const controller = new AbortController();+ const pinState = {};const resolved = await Promise.race([- resolveForgeForRepo(dir, { timeoutMs, signal: controller.signal, forgeAccount }),- new Promise((_, reject) => {+ resolveForgeWithPin(dir, { timeoutMs, signal: controller.signal, forgeAccount }, pinState),+ new Promise((resolve, reject) => {timer = setTimeout(() => {controller.abort();- reject(new ServerError('GitHub account resolution timed out. Retry after checking gh auth status.', {+ if (pinState.account === null) return resolve(null);+ reject(new ServerError('Pinned GitHub account resolution timed out. Retry after checking gh auth status.', {status: 503, code: 'FORGE_AUTH_TIMEOUT',}));}, timeoutMs);diff --git a/server/services/forgeAuth.test.js b/server/services/forgeAuth.test.jsindex 9bc5283ede..c5694de00a 100644--- a/server/services/forgeAuth.test.js+++ b/server/services/forgeAuth.test.js@@ -4,7 +4,7 @@ import { mkdirSync, mkdtempSync, rmSync, symlinkSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';-vi.mock('../lib/childProcess.js', () => ({ spawn: vi.fn() }));+vi.mock('../lib/childProcess.js', async (original) => ({ ...(await original()), spawn: vi.fn() }));// The managed-app registry read is the only thing forge auth needs from the app// layer; doubling it keeps this suite off the filesystem and makes the pinned// vs. inferred account split explicit per test.@@ -93,7 +93,7 @@ describe('forge credential resolution', () => {expect(spawn).toHaveBeenCalledTimes(3);});- it('refuses a stalled lookup rather than launching an agent as an unverified account', async () => {+ it('bounds a stalled unpinned lookup so an agent can keep ambient auth', async () => {vi.useFakeTimers();respond({ stdout: '[email protected]:example-owner/project.git\n' });const stalled = new EventEmitter();@@ -102,14 +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' });+ const refused = expect(pending).resolves.toEqual({});await vi.advanceTimersByTimeAsync(25);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).rejects.toMatchObject({ code: 'FORGE_AUTH_TIMEOUT' });+ await expect(pending).resolves.toEqual({});});it('aborts a token probe that starts near the end of the whole lookup budget', async () => {@@ -135,7 +135,7 @@ describe('forge credential resolution', () => {spawn.mockImplementationOnce(() => token);const pending = resolveForgeTokenEnv('/example/repo', { timeoutMs: 10 });- const refused = expect(pending).rejects.toMatchObject({ code: 'FORGE_AUTH_TIMEOUT' });+ const refused = expect(pending).resolves.toEqual({});await vi.advanceTimersByTimeAsync(9);expect(spawn).toHaveBeenCalledTimes(3);await vi.advanceTimersByTimeAsync(1);@@ -153,7 +153,7 @@ describe('forge credential resolution', () => {spawn.mockImplementationOnce(() => git);const pending = resolveForgeTokenEnv('/example/repo', { timeoutMs: 10 });- const refused = expect(pending).rejects.toMatchObject({ code: 'FORGE_AUTH_TIMEOUT' });+ const refused = expect(pending).resolves.toEqual({});await vi.advanceTimersByTimeAsync(10);await refused;@@ -166,14 +166,14 @@ describe('forge credential resolution', () => {});describe('per-app forge account pinning', () => {- // `git remote get-url origin` → `git rev-parse --git-common-dir` (only when an- // app pins an account) → `gh auth token` → `gh api user`. `gh auth status` is+ // `git rev-parse --git-common-dir` (only when an app pins an account)+ // → `git remote get-url origin` → `gh auth token` → `gh api user`. `gh auth status` is// deliberately absent: a named account is not something to second-guess// against the owner.function pinnedAccount({ tokenCode = 0, identity = '4242\tacme-bot\tAcme Bot\n', identityCode = 0 } = {}) {listForgePinnedApps.mockResolvedValue([{ repoPath: '/example/repo', forgeAccount: 'acme-bot' }]);- respond({ stdout: '[email protected]:acme/widget.git\n' });respond({ stdout: '/example/repo/.git\n' });+ respond({ stdout: '[email protected]:acme/widget.git\n' });respond({ stdout: tokenCode === 0 ? 'acme-bot-token\n' : '', code: tokenCode });respond({ stdout: identity, code: identityCode });}@@ -217,10 +217,10 @@ describe('per-app forge account pinning', () => {it('maps an agent worktree back to the checkout the pin is registered against', async () => {listForgePinnedApps.mockResolvedValue([{ repoPath: '/example/repo', forgeAccount: 'acme-bot' }]);- respond({ stdout: '[email protected]:acme/widget.git\n' });// A CoS worktree lives under PortOS's own data dir and never matches an// app repoPath; --git-common-dir is what points back at the checkout.respond({ stdout: '/example/repo/.git\n' });+ respond({ stdout: '[email protected]:acme/widget.git\n' });respond({ stdout: 'acme-bot-token\n' });respond({ stdout: '4242\tacme-bot\t\n' });const env = await resolveForgeTokenEnv('/portos/data/cos/worktrees/agent-1');@@ -239,8 +239,8 @@ describe('per-app forge account pinning', () => {symlinkSync(real, link);try {listForgePinnedApps.mockResolvedValue([{ repoPath: real, forgeAccount: 'acme-bot' }]);- respond({ stdout: '[email protected]:acme/widget.git\n' });respond({ stdout: `${link}/.git\n` });+ respond({ stdout: '[email protected]:acme/widget.git\n' });respond({ stdout: 'acme-bot-token\n' });respond({ stdout: '4242\tacme-bot\tAcme Bot\n' });await expect(resolveForgeTokenEnv(link)).resolves.toMatchObject({ GH_HOST: 'github.com', GH_TOKEN: 'acme-bot-token' });@@ -258,8 +258,8 @@ describe('per-app forge account pinning', () => {it('ignores a pin registered against a different repository', async () => {listForgePinnedApps.mockResolvedValue([{ repoPath: '/other/repo', forgeAccount: 'acme-bot' }]);- respond({ stdout: '[email protected]:example-owner/project.git\n' });respond({ stdout: '/example/repo/.git\n' });+ respond({ stdout: '[email protected]:example-owner/project.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_HOST: 'github.com', GH_TOKEN: 'test-owner-token' });@@ -367,3 +367,36 @@ it('refuses an explicit account pin when its repository cannot be resolved', asy.rejects.toMatchObject({ code: 'FORGE_ACCOUNT_UNAVAILABLE' });expect(spawn).toHaveBeenCalledTimes(1);});++it('refuses a timed-out explicit pin instead of launching with ambient credentials', async () => {+ vi.useFakeTimers();+ respond({ stdout: '[email protected]:acme/widget.git' });+ const child = new EventEmitter();+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ child.kill = vi.fn();+ spawn.mockImplementationOnce(() => child);+ const pending = resolveForgeTokenEnv('/example/repo', { forgeAccount: 'acme-bot', timeoutMs: 10 });+ const refused = expect(pending).rejects.toMatchObject({ code: 'FORGE_AUTH_TIMEOUT' });+ await vi.advanceTimersByTimeAsync(10);+ await refused;+ expect(child.kill).toHaveBeenCalledWith('SIGKILL');+});++it('keeps the public SSH-over-443 alias on github.com credentials', async () => {+ respond({ stdout: '[email protected]:acme/widget.git' });+ respond({ stdout: 'public-token' });+ respond({ stdout: '4242\tacme-bot\tAcme Bot\n' });+ const env = await resolveForgeTokenEnv('/example/repo', { forgeAccount: 'acme-bot' });+ expect(env).toMatchObject({ GH_HOST: 'github.com', GH_TOKEN: 'public-token' });+ expect(env.GH_ENTERPRISE_TOKEN).toBeUndefined();+ expect(spawn.mock.calls[1][1]).toEqual(['auth', 'token', '-u', 'acme-bot', '-h', 'github.com']);+});++it('keeps unpinned transient credential failures on ambient auth', async () => {+ respond({ stdout: '[email protected]:acme/widget.git' });+ spawn.mockImplementationOnce(() => { throw new Error('gh temporarily unavailable'); });+ const options = await resolveForgeExecOptions('/example/repo');+ expect(options.env).toBe(process.env);+ expect(options.customEnv).toBeNull();+});