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(github): require authenticated account for repo sync
tzioup54ec60777113
diff --git a/client/src/components/settings/CredentialsTab.jsx b/client/src/components/settings/CredentialsTab.jsxindex 3661f9bac2..fd3ec3898c 100644--- a/client/src/components/settings/CredentialsTab.jsx+++ b/client/src/components/settings/CredentialsTab.jsx@@ -71,6 +71,7 @@ export function CredentialsTab() {<div className="space-y-3">{credentials.map((credential) => {const configured = credential.configured === true;+ const verificationUnavailable = credential.verification === 'unavailable';return (<divkey={credential.id}@@ -82,11 +83,19 @@ export function CredentialsTab() {<p className="text-sm text-gray-400 mt-1">{credential.unlocks}</p></div><div className="flex flex-wrap items-center gap-2">- <span className={`inline-flex items-center min-h-[28px] px-2 rounded text-xs ${configured ? 'bg-emerald-500/15 text-emerald-300' : 'bg-port-border/60 text-gray-400'}`}>- {configured ? 'Configured' : 'Not configured'}+ <span className={`inline-flex items-center min-h-[28px] px-2 rounded text-xs ${+ verificationUnavailable+ ? 'bg-amber-500/15 text-amber-300'+ : configured+ ? 'bg-emerald-500/15 text-emerald-300'+ : 'bg-port-border/60 text-gray-400'+ }`}>+ {verificationUnavailable ? 'Could not verify' : configured ? 'Configured' : 'Not configured'}</span><span className="inline-flex items-center min-h-[28px] px-2 rounded text-xs bg-port-bg text-gray-400">- {SOURCE_LABEL[credential.source] || SOURCE_LABEL.none}+ {verificationUnavailable && credential.source === 'none'+ ? 'Status unknown'+ : SOURCE_LABEL[credential.source] || SOURCE_LABEL.none}</span>{credential.tier && credential.tier !== 'none' && (<span className="inline-flex items-center min-h-[28px] px-2 rounded text-xs bg-port-bg text-gray-500">diff --git a/client/src/components/settings/CredentialsTab.test.jsx b/client/src/components/settings/CredentialsTab.test.jsxindex 40ecfed210..ded07a7bd5 100644--- a/client/src/components/settings/CredentialsTab.test.jsx+++ b/client/src/components/settings/CredentialsTab.test.jsx@@ -62,4 +62,29 @@ describe('CredentialsTab', () => {expect(screen.queryByText(/hf_/)).toBeNull();expect(JSON.stringify(PAYLOAD)).not.toMatch(/hf_this/);});++ it('renders verification failures as unknown instead of not configured', async () => {+ mock.getCredentialInventory.mockResolvedValue({+ headline: 'Credential status',+ credentials: [{+ id: 'github',+ label: 'GitHub',+ unlocks: 'Repositories',+ tier: 'free',+ configured: null,+ source: 'none',+ verification: 'unavailable',+ unavailableFeatures: [],+ }],+ });++ render(+ <MemoryRouter>+ <CredentialsTab />+ </MemoryRouter>,+ );++ expect(await screen.findByText('Could not verify')).toBeInTheDocument();+ expect(screen.queryByText('Not configured')).not.toBeInTheDocument();+ });});diff --git a/client/src/pages/GitHub.jsx b/client/src/pages/GitHub.jsxindex b0ca15d357..cd98daa89a 100644--- a/client/src/pages/GitHub.jsx+++ b/client/src/pages/GitHub.jsx@@ -1,7 +1,9 @@import { useState, useEffect, useMemo } from 'react';+import { Link } from 'react-router';import toast from '../components/ui/Toast';import {getGitHubRepos,+ getGitHubStatus,syncGitHubRepos,updateGitHubRepo,getGitHubSecrets,@@ -16,6 +18,15 @@ import Modal from '../components/ui/Modal';import { FormField } from '../components/ui/FormField';const FILTERS = ['all', 'npm', 'secrets', 'archived'];+const GITHUB_LOGIN_COMMAND = 'gh auth login --hostname github.com --web --clipboard';+const GITHUB_SWITCH_COMMAND = 'gh auth switch --hostname github.com';+const UNAVAILABLE_AUTH_STATUS = Object.freeze({+ authenticated: false,+ status: 'unavailable',+ login: null,+ remedy: 'PortOS could not check GitHub authentication. Retry before syncing or changing repositories.',+ githubUser: null,+});export default function GitHub() {const [repos, setRepos] = useState({});@@ -23,6 +34,8 @@ export default function GitHub() {const [loading, setLoading] = useState(true);const [syncing, setSyncing] = useState(false);const [lastSync, setLastSync] = useState(null);+ const [repoListTruncated, setRepoListTruncated] = useState(false);+ const [authStatus, setAuthStatus] = useState(null);const [search, setSearch] = useState('');const [filter, setFilter] = useState('all');const [sort, setSort] = useState('recent'); // 'recent' | 'alpha'@@ -41,12 +54,15 @@ export default function GitHub() {const loadData = async () => {setLoading(true);- const [reposData, secretsData] = await Promise.all([- getGitHubRepos().catch(() => ({})),- getGitHubSecrets().catch(() => ({}))+ const [reposData, secretsData, statusData] = await Promise.all([+ getGitHubRepos({ silent: true }).catch(() => ({})),+ getGitHubSecrets({ silent: true }).catch(() => ({})),+ getGitHubStatus({ silent: true }).catch(() => UNAVAILABLE_AUTH_STATUS)]);setRepos(reposData || {});setSecrets(secretsData || {});+ setAuthStatus(statusData);+ setLastSync(statusData?.lastRepoSync || null);setLoading(false);};@@ -59,7 +75,13 @@ export default function GitHub() {if (result) {setRepos(result.repos || {});setLastSync(result.lastRepoSync);- toast.success(`Synced ${Object.keys(result.repos || {}).length} repos`);+ setAuthStatus(prev => prev ? { ...prev, githubUser: result.githubUser } : prev);+ setRepoListTruncated(result.truncated === true);+ if (result.truncated) {+ toast.warning(`Loaded the first ${Object.keys(result.repos || {}).length} repositories. Narrower or paginated sync is not available yet.`);+ } else {+ toast.success(`Synced ${Object.keys(result.repos || {}).length} repos`);+ }}setSyncing(false);};@@ -158,6 +180,20 @@ export default function GitHub() {}, [repos, search, filter, sort]);const secretEntries = Object.entries(secrets);+ const authStatusUnavailable = ['unavailable', 'unreachable', 'error'].includes(authStatus?.status);+ const authStatusNotInstalled = authStatus?.status === 'not-installed';+ const environmentCredential = authStatus?.credentialSource === 'env';+ const cachedAccountMatches = authStatus?.authenticated === true+ && typeof authStatus.login === 'string'+ && typeof authStatus.githubUser === 'string'+ && authStatus.login.toLowerCase() === authStatus.githubUser.toLowerCase();+ const authHeading = authStatusUnavailable+ ? 'GitHub status unavailable'+ : authStatusNotInstalled+ ? 'GitHub CLI required'+ : environmentCredential+ ? 'GitHub environment credential rejected'+ : 'GitHub sign-in required';if (loading) {return <PageSkeleton label="Loading GitHub repos" padded titleWidthClass="w-44" showAction={false} cards={3} />;@@ -167,6 +203,46 @@ export default function GitHub() {<div className="p-4 sm:p-6"><h1 className="text-xl sm:text-2xl font-bold text-white mb-6">GitHub Repos</h1>+ {!authStatus?.authenticated && (+ <section className="mb-6 rounded-lg border border-port-warning/30 bg-port-warning/10 p-4" aria-label="GitHub account">+ <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">+ <div>+ <h2 className="font-semibold text-white">{authHeading}</h2>+ {!authStatusUnavailable && !authStatusNotInstalled && !environmentCredential && (+ <p className="mt-1 text-sm text-gray-300">+ Sign in through PortOS Shell, complete GitHub's browser prompt, then return here and reload.+ </p>+ )}+ {authStatus?.remedy && (+ <p className="mt-1 text-xs text-gray-500">{authStatus.remedy}</p>+ )}+ {authStatus?.githubUser && !cachedAccountMatches && (+ <p className="mt-2 text-xs text-port-warning">+ The repositories below are cached from @{authStatus.githubUser}. Sign in and sync to replace them; repository actions stay disabled.+ </p>+ )}+ </div>+ {!authStatusUnavailable && !environmentCredential && authStatus?.status !== 'not-installed' && (+ <Link+ to={`/shell?cmd=${encodeURIComponent(GITHUB_LOGIN_COMMAND)}`}+ className="inline-flex min-h-[44px] shrink-0 items-center justify-center rounded bg-port-accent px-4 py-2 text-sm font-medium text-white hover:bg-port-accent/80 sm:min-h-0"+ >+ Sign in with GitHub+ </Link>+ )}+ {authStatusUnavailable && (+ <button+ type="button"+ onClick={loadData}+ className="inline-flex min-h-[44px] shrink-0 items-center justify-center rounded bg-port-accent px-4 py-2 text-sm font-medium text-white hover:bg-port-accent/80 sm:min-h-0"+ >+ Retry+ </button>+ )}+ </div>+ </section>+ )}+{/* Archive Confirmation Modal */}<Modalopen={!!archiveConfirm}@@ -209,22 +285,72 @@ export default function GitHub() {<div className="grid grid-cols-1 lg:grid-cols-[1fr_360px] gap-6 items-start">{/* Repo List */}<div className="bg-port-card rounded-lg border border-port-border p-4 sm:p-6 min-w-0">- <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-4">+ <div className="flex flex-col gap-3 mb-4 sm:flex-row sm:items-center sm:justify-between"><div className="flex items-center gap-3"><h2 className="text-lg font-bold text-white">Repositories</h2>{lastSync && (<span className="text-xs text-gray-500">Last sync: {timeAgo(lastSync)}</span>)}</div>- <button- onClick={handleSync}- disabled={syncing}- className="px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded text-sm disabled:opacity-50"- >- {syncing ? 'Syncing...' : 'Sync Repos'}- </button>+ <div className="flex flex-wrap items-center gap-2">+ {authStatus?.authenticated && environmentCredential && (+ <span className="inline-flex min-h-[36px] min-w-0 max-w-full items-center gap-2 rounded border border-port-border bg-port-bg px-3 text-xs text-gray-300">+ <span className="h-2 w-2 rounded-full bg-port-success" aria-hidden="true" />+ <span className="max-w-28 truncate font-mono text-white sm:max-w-40" title={`@${authStatus.login}`}>+ @{authStatus.login}+ </span>+ <span className="hidden text-gray-500 sm:inline">via environment</span>+ </span>+ )}+ {authStatus?.authenticated && !environmentCredential && (+ <details className="relative min-w-0 max-w-full">+ <summary+ aria-label={`GitHub account @${authStatus.login}`}+ className="inline-flex min-h-[36px] min-w-0 max-w-full cursor-pointer list-none items-center gap-2 rounded border border-port-border bg-port-bg px-3 text-xs text-gray-300 hover:text-white [&::-webkit-details-marker]:hidden"+ >+ <span className="h-2 w-2 rounded-full bg-port-success" aria-hidden="true" />+ <span className="max-w-28 truncate font-mono text-white sm:max-w-40" title={`@${authStatus.login}`}>+ @{authStatus.login}+ </span>+ <span aria-hidden="true">▾</span>+ </summary>+ <div className="absolute left-0 z-20 mt-2 w-52 rounded-lg border border-port-border bg-port-card p-1 shadow-xl sm:left-auto sm:right-0">+ <Link+ to={`/shell?cmd=${encodeURIComponent(GITHUB_LOGIN_COMMAND)}`}+ className="flex min-h-[44px] items-center rounded px-3 py-2 text-sm text-gray-300 hover:bg-port-border/50 hover:text-white"+ >+ Add GitHub account+ </Link>+ <Link+ to={`/shell?cmd=${encodeURIComponent(GITHUB_SWITCH_COMMAND)}`}+ className="flex min-h-[44px] items-center rounded px-3 py-2 text-sm text-gray-300 hover:bg-port-border/50 hover:text-white"+ >+ Switch GitHub account+ </Link>+ </div>+ </details>+ )}+ <button+ onClick={handleSync}+ disabled={syncing || authStatus?.authenticated !== true}+ className="rounded bg-port-accent px-4 py-2 text-sm text-white hover:bg-port-accent/80 disabled:opacity-50"+ >+ {syncing ? 'Syncing...' : 'Sync Repos'}+ </button>+ </div></div>+ {authStatus?.authenticated && environmentCredential && (+ <p className="mb-4 text-xs text-gray-500">+ Environment credentials override stored gh accounts. Update or remove GH_TOKEN/GITHUB_TOKEN to change accounts.+ </p>+ )}+ {authStatus?.authenticated && authStatus?.githubUser && !cachedAccountMatches && (+ <p className="mb-4 text-xs text-port-warning">+ The repositories below are cached from @{authStatus.githubUser}. Their actions are disabled until you sync @{authStatus.login}.+ </p>+ )}+{/* Search + Filter */}<div className="flex flex-col sm:flex-row gap-2 mb-4"><input@@ -264,6 +390,11 @@ export default function GitHub() {{repoList.length} repo{repoList.length !== 1 ? 's' : ''}{filter !== 'all' ? ` (filtered)` : ''}</p>+ {repoListTruncated && (+ <p className="mb-3 text-xs text-port-warning" role="status">+ GitHub returned the 200-repository limit. This list may be incomplete; cached entries were preserved.+ </p>+ )}{Object.keys(repos).length === 0 ? (<div className="text-center py-8">@@ -331,6 +462,7 @@ export default function GitHub() {type="checkbox"checked={!!repo.flags?.npmProject}onChange={() => handleToggleNpm(repo.fullName, repo.flags?.npmProject)}+ disabled={!cachedAccountMatches}className="w-4 h-4 rounded border-gray-600 bg-port-bg text-port-accent focus:ring-port-accent"/><span className="text-xs text-gray-400">NPM</span>@@ -338,7 +470,7 @@ export default function GitHub() {)}<buttononClick={() => handleArchiveClick(repo.fullName, repo.isArchived)}- disabled={archiving === repo.fullName}+ disabled={archiving === repo.fullName || !cachedAccountMatches}className={`px-2 py-1 text-xs rounded ${repo.isArchived? 'bg-port-success/20 text-port-success hover:bg-port-success/30 border border-port-success/30'@@ -376,7 +508,7 @@ export default function GitHub() {</div><buttononClick={() => handleSyncSecret(name)}- disabled={syncingSecret === name || !meta.hasValue}+ disabled={syncingSecret === name || !meta.hasValue || !cachedAccountMatches}className="self-start px-3 py-1 text-sm bg-port-accent hover:bg-port-accent/80 text-white rounded disabled:opacity-50">{syncingSecret === name ? 'Syncing...' : 'Sync to Repos'}@@ -407,7 +539,7 @@ export default function GitHub() {</FormField><buttononClick={handleSaveSecret}- disabled={savingSecret || !newSecretName.trim() || !newSecretValue}+ disabled={savingSecret || !newSecretName.trim() || !newSecretValue || !cachedAccountMatches}className="px-4 py-2 bg-port-success hover:bg-port-success/80 text-white rounded text-sm disabled:opacity-50">{savingSecret ? 'Saving...' : 'Save Secret'}@@ -422,12 +554,12 @@ export default function GitHub() {<div className="bg-port-card rounded-lg border border-port-border p-4 sm:p-6"><h2 className="text-base font-bold text-white mb-3">How it works</h2><div className="space-y-2 text-xs sm:text-sm text-gray-300">- <p>1. Click "Sync Repos" to fetch your GitHub repos via <code>gh repo list</code></p>+ <p>1. Sign in above, then click "Sync Repos" to fetch repositories owned by the active GitHub account</p><p>2. Toggle "NPM" on repos that publish to npm — this auto-adds NPM_TOKEN to their managed secrets</p><p>3. Add secrets (like NPM_TOKEN) with their values — values are stored locally, never in the browser</p><p>4. Click "Sync to Repos" to push secrets to all flagged repos via <code>gh secret set</code></p><p className="text-gray-500 mt-2">- Requires <code>gh</code> CLI authenticated with repo and admin:org scope.+ Uses the account authenticated in the <code>gh</code> CLI. Repository access is required to sync private repos and secrets.</p></div></div>diff --git a/client/src/pages/GitHub.test.jsx b/client/src/pages/GitHub.test.jsxnew file mode 100644index 0000000000..48d69e14e3--- /dev/null+++ b/client/src/pages/GitHub.test.jsx@@ -0,0 +1,281 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen } from '@testing-library/react';+import { MemoryRouter } from 'react-router';++const mock = vi.hoisted(() => ({+ getGitHubRepos: vi.fn(),+ getGitHubSecrets: vi.fn(),+ getGitHubStatus: vi.fn(),+ syncGitHubRepos: vi.fn(),+ updateGitHubRepo: vi.fn(),+ setGitHubSecret: vi.fn(),+ syncGitHubSecret: vi.fn(),+ archiveGitHubRepo: vi.fn(),+ unarchiveGitHubRepo: vi.fn(),+}));++vi.mock('../services/api', () => mock);++import GitHub from './GitHub';++describe('GitHub account setup', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mock.getGitHubRepos.mockResolvedValue({});+ mock.getGitHubSecrets.mockResolvedValue({});+ mock.getGitHubStatus.mockResolvedValue({+ authenticated: false,+ status: 'not-authenticated',+ login: null,+ remedy: 'Run `gh auth login`.',+ githubUser: null,+ lastRepoSync: null,+ });+ });++ it('offers an in-app GitHub login flow and prevents an anonymous repo sync', async () => {+ render(+ <MemoryRouter initialEntries={['/devtools/github']}>+ <GitHub />+ </MemoryRouter>,+ );++ const signIn = await screen.findByRole('link', { name: 'Sign in with GitHub' });+ expect(decodeURIComponent(signIn.getAttribute('href'))).toContain('/shell?cmd=gh auth login');+ expect(screen.getByRole('button', { name: 'Sync Repos' })).toBeDisabled();+ });++ it('describes a signed-out legacy cache without rendering a null account', async () => {+ mock.getGitHubStatus.mockResolvedValue({+ authenticated: false,+ status: 'not-authenticated',+ login: null,+ credentialSource: 'cli',+ remedy: 'Run `gh auth login`.',+ githubUser: 'legacy-owner',+ lastRepoSync: null,+ });++ render(+ <MemoryRouter initialEntries={['/devtools/github']}>+ <GitHub />+ </MemoryRouter>,+ );++ expect(await screen.findByText(/cached from @legacy-owner/i)).toHaveTextContent(+ 'Sign in and sync to replace them',+ );+ expect(screen.queryByText(/@null/)).toBeNull();+ });++ it('shows the active account and enables repo sync when gh is authenticated', async () => {+ mock.getGitHubStatus.mockResolvedValue({+ authenticated: true,+ status: 'ok',+ login: 'example-user',+ remedy: null,+ githubUser: 'example-user',+ lastRepoSync: null,+ });++ render(+ <MemoryRouter initialEntries={['/devtools/github']}>+ <GitHub />+ </MemoryRouter>,+ );++ expect(await screen.findByLabelText('GitHub account @example-user')).toBeTruthy();+ expect(screen.queryByText('GitHub connected')).toBeNull();+ expect(screen.getByRole('button', { name: 'Sync Repos' })).not.toBeDisabled();+ fireEvent.click(screen.getByLabelText('GitHub account @example-user'));+ expect(screen.getByRole('link', { name: 'Add GitHub account' })).toBeTruthy();+ expect(screen.getByRole('link', { name: 'Switch GitHub account' })).toBeTruthy();+ });++ it('explains that an environment token overrides stored CLI accounts', async () => {+ mock.getGitHubStatus.mockResolvedValue({+ authenticated: true,+ status: 'ok',+ login: 'example-user',+ credentialSource: 'env',+ remedy: null,+ githubUser: 'example-user',+ lastRepoSync: null,+ });++ render(+ <MemoryRouter initialEntries={['/devtools/github']}>+ <GitHub />+ </MemoryRouter>,+ );++ expect(await screen.findByText(/environment credentials override stored gh accounts/i)).toBeTruthy();+ expect(screen.queryByRole('link', { name: /GitHub account/ })).toBeNull();+ expect(screen.getByRole('button', { name: 'Sync Repos' })).not.toBeDisabled();+ });++ it('does not offer a CLI login that an invalid environment token would override', async () => {+ mock.getGitHubStatus.mockResolvedValue({+ authenticated: false,+ status: 'not-authenticated',+ login: null,+ credentialSource: 'env',+ remedy: 'GH_TOKEN or GITHUB_TOKEN is set but GitHub rejected it.',+ githubUser: null,+ lastRepoSync: null,+ });++ render(+ <MemoryRouter initialEntries={['/devtools/github']}>+ <GitHub />+ </MemoryRouter>,+ );++ expect(await screen.findByText('GitHub environment credential rejected')).toBeTruthy();+ expect(screen.queryByRole('link', { name: 'Sign in with GitHub' })).toBeNull();+ expect(screen.getByRole('button', { name: 'Sync Repos' })).toBeDisabled();+ });++ it('distinguishes an unavailable status check from signed out and disables sync', async () => {+ mock.getGitHubStatus.mockRejectedValue(new Error('status unavailable'));++ render(+ <MemoryRouter initialEntries={['/devtools/github']}>+ <GitHub />+ </MemoryRouter>,+ );++ expect(await screen.findByText('GitHub status unavailable')).toBeTruthy();+ expect(screen.queryByRole('link', { name: 'Sign in with GitHub' })).toBeNull();+ expect(screen.getByRole('button', { name: 'Sync Repos' })).toBeDisabled();+ expect(screen.getByRole('button', { name: 'Retry' })).toBeTruthy();+ });++ it('retries an unavailable authentication check in place', async () => {+ mock.getGitHubStatus+ .mockRejectedValueOnce(new Error('status unavailable'))+ .mockResolvedValueOnce({+ authenticated: true,+ status: 'ok',+ login: 'example-user',+ githubUser: 'example-user',+ lastRepoSync: null,+ });++ render(+ <MemoryRouter initialEntries={['/devtools/github']}>+ <GitHub />+ </MemoryRouter>,+ );++ fireEvent.click(await screen.findByRole('button', { name: 'Retry' }));+ expect(await screen.findByText('@example-user')).toBeTruthy();+ expect(mock.getGitHubStatus).toHaveBeenCalledTimes(2);+ });++ it('warns when GitHub reaches the repository listing limit', async () => {+ mock.getGitHubStatus.mockResolvedValue({+ authenticated: true,+ status: 'ok',+ login: 'example-user',+ githubUser: 'example-user',+ lastRepoSync: null,+ });+ mock.syncGitHubRepos.mockResolvedValue({+ repos: {},+ githubUser: 'example-user',+ lastRepoSync: '2026-01-01T00:00:00.000Z',+ truncated: true,+ });++ render(+ <MemoryRouter initialEntries={['/devtools/github']}>+ <GitHub />+ </MemoryRouter>,+ );++ fireEvent.click(await screen.findByRole('button', { name: 'Sync Repos' }));+ expect(await screen.findByText(/200-repository limit/i)).toBeTruthy();+ });++ it('does not mislabel a GitHub network failure as signed out', async () => {+ mock.getGitHubStatus.mockResolvedValue({+ authenticated: false,+ status: 'unreachable',+ login: null,+ credentialSource: 'cli',+ remedy: 'GitHub is unreachable.',+ githubUser: null,+ lastRepoSync: null,+ });++ render(+ <MemoryRouter initialEntries={['/devtools/github']}>+ <GitHub />+ </MemoryRouter>,+ );++ expect(await screen.findByText('GitHub status unavailable')).toBeTruthy();+ expect(screen.queryByRole('link', { name: 'Sign in with GitHub' })).toBeNull();+ expect(screen.getByRole('button', { name: 'Sync Repos' })).toBeDisabled();+ });++ it('shows an install state instead of offering login when the GitHub CLI is missing', async () => {+ mock.getGitHubStatus.mockResolvedValue({+ authenticated: false,+ status: 'not-installed',+ login: null,+ credentialSource: 'cli',+ remedy: 'Install the GitHub CLI.',+ githubUser: null,+ lastRepoSync: null,+ });++ render(+ <MemoryRouter initialEntries={['/devtools/github']}>+ <GitHub />+ </MemoryRouter>,+ );++ expect(await screen.findByText('GitHub CLI required')).toBeTruthy();+ expect(screen.queryByRole('link', { name: 'Sign in with GitHub' })).toBeNull();+ expect(screen.getByRole('button', { name: 'Sync Repos' })).toBeDisabled();+ });++ it('blocks cached-repository actions until the newly active account is synced', async () => {+ mock.getGitHubRepos.mockResolvedValue({+ 'legacy-owner/old-repo': {+ name: 'old-repo',+ fullName: 'legacy-owner/old-repo',+ description: '',+ isArchived: false,+ pushedAt: null,+ flags: { npmProject: false },+ managedSecrets: ['EXAMPLE_SECRET'],+ },+ });+ mock.getGitHubSecrets.mockResolvedValue({+ EXAMPLE_SECRET: { hasValue: true, updatedAt: null },+ });+ mock.getGitHubStatus.mockResolvedValue({+ authenticated: true,+ status: 'ok',+ login: 'example-user',+ remedy: null,+ githubUser: 'legacy-owner',+ lastRepoSync: null,+ });++ render(+ <MemoryRouter initialEntries={['/devtools/github']}>+ <GitHub />+ </MemoryRouter>,+ );++ expect(await screen.findByText(/cached from @legacy-owner/i)).toBeTruthy();+ expect(screen.getByRole('button', { name: 'Archive' })).toBeDisabled();+ expect(screen.getByRole('checkbox', { name: 'NPM' })).toBeDisabled();+ expect(screen.getByRole('button', { name: 'Sync to Repos' })).toBeDisabled();+ expect(screen.getByRole('button', { name: 'Sync Repos' })).not.toBeDisabled();+ });+});diff --git a/client/src/services/apiGithub.js b/client/src/services/apiGithub.jsindex 6ac5e6b162..5ad46855db 100644--- a/client/src/services/apiGithub.js+++ b/client/src/services/apiGithub.js@@ -4,6 +4,7 @@ import { request } from './apiCore.js';// `options` lets a caller suppress request()'s auto-toast with `{ silent: true }`// when it already renders its own error UI.export const getGitHubRepos = (options = {}) => request('/github/repos', options);+export const getGitHubStatus = (options = {}) => request('/github/status', options);export const syncGitHubRepos = (options = {}) => request('/github/repos/sync', { method: 'POST', ...options });export const updateGitHubRepo = (fullName, data, options = {}) =>request(`/github/repos/${encodeURIComponent(fullName)}`, { method: 'PUT', body: JSON.stringify(data), ...options });diff --git a/server/routes/github.js b/server/routes/github.jsindex 16fb86549e..f5c725386a 100644--- a/server/routes/github.js+++ b/server/routes/github.js@@ -18,7 +18,12 @@ router.get('/repos', asyncHandler(async (req, res) => {*/router.post('/repos/sync', asyncHandler(async (req, res) => {const data = await githubService.syncRepos();- res.json({ repos: data.repos, lastRepoSync: data.lastRepoSync });+ res.json({+ repos: data.repos,+ lastRepoSync: data.lastRepoSync,+ githubUser: data.githubUser,+ truncated: data.truncated,+ });}));/**diff --git a/server/services/credentialInventory.js b/server/services/credentialInventory.jsindex 5e874ce044..ad02755d46 100644--- a/server/services/credentialInventory.js+++ b/server/services/credentialInventory.js@@ -74,6 +74,28 @@ const detectHuggingFaceCli = async () => {return null;};+const detectGitHubCli = async (entry, { env, envFile }) => {+ const { getGitHubAuthStatus } = await import('./github.js');+ const status = await getGitHubAuthStatus({ env });+ const envResolution = classifyEnvSource(entry.envVars, env, envFile);+ if (!status.authenticated) {+ if (['unreachable', 'error'].includes(status.status)) {+ return {+ configured: envResolution.configured ? true : null,+ source: envResolution.source,+ verification: 'unavailable',+ };+ }+ if (status.status === 'not-installed' && envResolution.configured) {+ return { ...envResolution, verification: 'unavailable' };+ }+ return { configured: false, source: 'none' };+ }+ return status.credentialSource === 'env' && envResolution.configured+ ? envResolution+ : { configured: true, source: 'cli' };+};+const detectJira = async () => {const { hasConfiguredInstances } = await import('./jira.js');return (await hasConfiguredInstances()) ? { configured: true, source: 'config' } : null;@@ -109,6 +131,7 @@ const detectOpenclaw = async () => {const DEFAULT_DETECTORS = Object.freeze({huggingface: detectHuggingFaceCli,+ github: detectGitHubCli,jira: detectJira,datadog: detectDatadog,spotify: detectSpotify,@@ -138,6 +161,7 @@ const publicRow = (entry, resolution, featuresById) => {feature: entry.feature ?? null,configured: resolution.configured,source: resolution.source,+ ...(resolution.verification ? { verification: resolution.verification } : {}),unavailableFeatures,};};@@ -172,7 +196,8 @@ export async function getCredentialInventory({env,envFile: resolvedEnvFile,});- if (!resolution.configured && typeof resolvedDetectors[entry.id] === 'function') {+ const detectorMustVerify = entry.id === 'github';+ if ((detectorMustVerify || !resolution.configured) && typeof resolvedDetectors[entry.id] === 'function') {const detected = await resolvedDetectors[entry.id](entry, {settings: resolvedSettings,env,@@ -181,7 +206,15 @@ export async function getCredentialInventory({console.error(`❌ Credential "${entry.id}" detection failed: ${error.message}`);return null;});- if (detected?.configured) resolution = detected;+ if (detectorMustVerify) {+ resolution = detected || {+ configured: resolution.configured ? true : null,+ source: resolution.source,+ verification: 'unavailable',+ };+ } else if (detected?.configured) {+ resolution = detected;+ }}credentials.push(assertNoSecretPayload(publicRow(entry, resolution, featuresById)));}diff --git a/server/services/credentialInventory.test.js b/server/services/credentialInventory.test.jsindex 90e350282a..84d4d52d9e 100644--- a/server/services/credentialInventory.test.js+++ b/server/services/credentialInventory.test.js@@ -8,6 +8,8 @@ const mock = vi.hoisted(() => ({spotifyStatus: { hasCredentials: false, hasTokens: false },stackerAccounts: [],openclawConfig: {},+ githubAuth: { authenticated: false, status: 'not-authenticated' },+ getGitHubAuthStatus: vi.fn(),}));vi.mock('./settings.js', () => ({@@ -34,6 +36,10 @@ vi.mock('./stackerNews.js', () => ({listAccounts: vi.fn(async () => mock.stackerAccounts),}));+vi.mock('./github.js', () => ({+ getGitHubAuthStatus: mock.getGitHubAuthStatus,+}));+vi.mock('../lib/fileUtils.js', async (importOriginal) => {const actual = await importOriginal();return {@@ -57,6 +63,8 @@ describe('credentialInventory', () => {mock.spotifyStatus = { hasCredentials: false, hasTokens: false };mock.stackerAccounts = [];mock.openclawConfig = {};+ mock.githubAuth = { authenticated: false, status: 'not-authenticated' };+ mock.getGitHubAuthStatus.mockImplementation(async () => mock.githubAuth);});it('reports settings over env when both are set, without echoing the value', async () => {@@ -102,6 +110,105 @@ describe('credentialInventory', () => {expect(JSON.stringify({ credentials })).not.toContain('hf_cliTokenMustNotLeak');});+ it('reports a usable GitHub CLI login as configured', async () => {+ mock.githubAuth = { authenticated: true, status: 'ok', login: 'example-user' };+ const { credentials } = await getCredentialInventory({+ settings: {},+ env: {},+ envFile: new Map(),+ });+ expect(byId(credentials, 'github')).toMatchObject({ configured: true, source: 'cli' });+ expect(JSON.stringify({ credentials })).not.toContain('example-user');+ });++ it('does not report a rejected GitHub environment token as configured', async () => {+ mock.githubAuth = {+ authenticated: false,+ status: 'not-authenticated',+ credentialSource: 'env',+ };+ const { credentials } = await getCredentialInventory({+ settings: {},+ env: { GH_TOKEN: 'fake-invalid-token' },+ envFile: new Map(),+ });++ expect(byId(credentials, 'github')).toMatchObject({ configured: false, source: 'none' });+ });++ it('preserves the environment source after validating a working GitHub token', async () => {+ mock.githubAuth = {+ authenticated: true,+ status: 'ok',+ login: 'example-user',+ credentialSource: 'env',+ };+ const { credentials } = await getCredentialInventory({+ settings: {},+ env: { GH_TOKEN: 'fake-valid-token' },+ envFile: new Map(),+ });++ expect(byId(credentials, 'github')).toMatchObject({ configured: true, source: 'env' });+ expect(mock.getGitHubAuthStatus).toHaveBeenCalledWith({ env: { GH_TOKEN: 'fake-valid-token' } });+ });++ it('reports the credential actually used when an unconsumed .env token exists', async () => {+ mock.githubAuth = {+ authenticated: true,+ status: 'ok',+ login: 'example-user',+ credentialSource: 'cli',+ };+ const env = {};+ const { credentials } = await getCredentialInventory({+ settings: {},+ env,+ envFile: new Map([['GH_TOKEN', 'fake-unconsumed-token']]),+ });++ expect(byId(credentials, 'github')).toMatchObject({ configured: true, source: 'cli' });+ expect(mock.getGitHubAuthStatus).toHaveBeenCalledWith({ env });+ });++ it('preserves known credential presence when GitHub verification is unavailable', async () => {+ mock.githubAuth = {+ authenticated: false,+ status: 'unreachable',+ credentialSource: 'env',+ };+ const { credentials } = await getCredentialInventory({+ settings: {},+ env: { GH_TOKEN: 'fake-present-token' },+ envFile: new Map(),+ });++ expect(byId(credentials, 'github')).toMatchObject({+ configured: true,+ source: 'env',+ verification: 'unavailable',+ });+ });++ it('reports an unknown state instead of not configured when CLI verification fails', async () => {+ mock.githubAuth = {+ authenticated: false,+ status: 'error',+ credentialSource: 'cli',+ };+ const { credentials } = await getCredentialInventory({+ settings: {},+ env: {},+ envFile: new Map(),+ });++ expect(byId(credentials, 'github')).toMatchObject({+ configured: null,+ source: 'none',+ verification: 'unavailable',+ });+ });+it('names the instance feature that stays dark without a JIRA token', async () => {const { credentials } = await getCredentialInventory({settings: {},diff --git a/server/services/github.js b/server/services/github.jsindex cdb3aefc76..1256c9cd6b 100644--- a/server/services/github.js+++ b/server/services/github.js@@ -3,11 +3,19 @@ import { join } from 'path';import { atomicWrite, readJSONFile, PATHS, ensureDir, safeJSONParse } from '../lib/fileUtils.js';import { withSpawnCwdEnv } from '../lib/spawnCwd.js';import { ServerError } from '../lib/errorHandler.js';+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';+import { createMutex } from '../lib/asyncMutex.js';import { getSettings, updateSettings } from './settings.js';const DATA_DIR = PATHS.data;const REPOS_FILE = join(DATA_DIR, 'github-repos.json');const CONCURRENCY = 3;+const GITHUB_HOST = 'github.com';+const GITHUB_ENV_TOKEN_KEYS = ['GH_TOKEN', 'GITHUB_TOKEN'];+const REPO_SYNC_LIMIT = 200;+const SECRET_SYNC_TIMEOUT_MS = 30000;+const queueDataWrite = createFileWriteQueue();+const withGitHubMutation = createMutex();let cache = null;let cacheTimestamp = 0;@@ -17,7 +25,7 @@ const defaultData = () => ({repos: {},secrets: {},lastRepoSync: null,- githubUser: 'atomantic'+ githubUser: null});async function load() {@@ -36,7 +44,37 @@ async function save(data) {cacheTimestamp = Date.now();}+/** Test seam — drops the short-lived persisted-data cache. */+export function __resetGitHubDataCache() {+ cache = null;+ cacheTimestamp = 0;+}+const DEFAULT_EXEC_GH_TIMEOUT_MS = 60000;+const githubDotComEnv = (baseEnv = process.env) => ({ ...baseEnv, GH_HOST: GITHUB_HOST });+const githubEnvironmentToken = (env = process.env) => (+ GITHUB_ENV_TOKEN_KEYS.map((key) => env[key]).find((value) => typeof value === 'string' && value.trim())?.trim() || null+);+const githubCredentialSource = (env = process.env) => (+ githubEnvironmentToken(env)+ ? 'env'+ : 'cli'+);+const githubPinnedEnv = (token, baseEnv = process.env) => {+ const env = githubDotComEnv(baseEnv);+ delete env.GITHUB_TOKEN;+ env.GH_TOKEN = token;+ return env;+};++const repoOwner = (fullName) => typeof fullName === 'string' ? fullName.split('/')[0] : null;+const repoBelongsToAccount = (repo, login) => (+ typeof login === 'string'+ && repoOwner(repo?.fullName)?.toLowerCase() === login.toLowerCase()+);+const reposForAccount = (data, login = data.githubUser) => Object.fromEntries(+ Object.entries(data.repos || {}).filter(([, repo]) => repoBelongsToAccount(repo, login))+);/*** Execute a gh CLI command safely using spawn. `gh` hits the network, so a@@ -49,6 +87,7 @@ const DEFAULT_EXEC_GH_TIMEOUT_MS = 60000;*/export function execGh(args, timeoutMs = DEFAULT_EXEC_GH_TIMEOUT_MS, { cwd = null, env = null, input = null } = {}) {return new Promise((resolve, reject) => {+ const operation = 'gh command';const baseEnv = env || process.env;const child = spawn('gh', args, {shell: false,@@ -61,8 +100,8 @@ export function execGh(args, timeoutMs = DEFAULT_EXEC_GH_TIMEOUT_MS, { cwd = nultimedOut = true;// setTimeout callback boundary — guard so a kill() throw can't crash// the process (e.g. the child already exited between checks).- try { child.kill('SIGKILL'); } catch (err) { console.error(`❌ execGh: failed to kill timed-out 'gh ${args.join(' ')}': ${err.message}`); }- reject(new Error(`gh ${args.join(' ')} timed out after ${timeoutMs}ms`));+ try { child.kill('SIGKILL'); } catch (err) { console.error(`❌ execGh: failed to kill timed-out ${operation}: ${err.message}`); }+ reject(new Error(`${operation} timed out after ${timeoutMs}ms`));}, timeoutMs);child.stdout.on('data', (d) => { stdout += d.toString(); });child.stderr.on('data', (d) => { stderr += d.toString(); });@@ -70,7 +109,10 @@ export function execGh(args, timeoutMs = DEFAULT_EXEC_GH_TIMEOUT_MS, { cwd = nulif (timedOut) return;clearTimeout(timer);if (code !== 0) {- reject(new Error(stderr.trim() || `gh exited with code ${code}`));+ const error = new Error(stderr.trim() || `gh exited with code ${code}`);+ error.ghExitCode = code;+ error.ghStderr = stderr.trim();+ reject(error);} else {resolve(stdout.trim());}@@ -113,48 +155,85 @@ async function runWithConcurrency(tasks, limit) {* Sync repos from GitHub using gh CLI*/export async function syncRepos() {- const data = await load();- const owner = data.githubUser || 'atomantic';- const raw = await execGh([- 'repo', 'list', owner, '--limit', '200',- '--json', 'name,nameWithOwner,description,pushedAt,isArchived,isPrivate,isFork,parent,licenseInfo'- ]);- const remoteRepos = JSON.parse(raw);-- // Build set of remote repo names to detect deletions- const remoteNames = new Set();-- for (const repo of remoteRepos) {- const fullName = repo.nameWithOwner;- remoteNames.add(fullName);- const existing = data.repos[fullName] || {};- data.repos[fullName] = {- name: repo.name,- fullName,- description: repo.description || '',- isArchived: repo.isArchived,- isPrivate: repo.isPrivate,- isFork: repo.isFork,- forkSource: repo.parent ? `${repo.parent.owner.login}/${repo.parent.name}` : null,- pushedAt: repo.pushedAt,- license: repo.licenseInfo?.name || null,- flags: existing.flags || {},- managedSecrets: existing.managedSecrets || [],- lastSecretSync: existing.lastSecretSync || null+ return withGitHubMutation(async () => {+ const auth = await getPinnedGitHubAuth();+ if (!auth.authenticated || !auth.login) {+ throw new ServerError(auth.remedy || 'Sign in to GitHub before syncing repositories.', {+ status: 401,+ code: 'GITHUB_NOT_AUTHENTICATED'+ });+ }+ const owner = auth.login;+ const raw = await execGh([+ 'repo', 'list', owner, '--limit', String(REPO_SYNC_LIMIT),+ '--json', 'name,nameWithOwner,description,pushedAt,isArchived,isPrivate,isFork,parent,licenseInfo'+ ], DEFAULT_EXEC_GH_TIMEOUT_MS, { env: auth.env });+ const remoteRepos = JSON.parse(raw);+ const { data, removed, listingMayBeTruncated } = await queueDataWrite(async () => {+ const current = await load();+ const remoteNames = new Set();++ for (const repo of remoteRepos) {+ const fullName = repo.nameWithOwner;+ remoteNames.add(fullName);+ const existing = current.repos[fullName] || {};+ current.repos[fullName] = {+ name: repo.name,+ fullName,+ description: repo.description || '',+ isArchived: repo.isArchived,+ isPrivate: repo.isPrivate,+ isFork: repo.isFork,+ forkSource: repo.parent ? `${repo.parent.owner.login}/${repo.parent.name}` : null,+ pushedAt: repo.pushedAt,+ license: repo.licenseInfo?.name || null,+ flags: existing.flags || {},+ managedSecrets: existing.managedSecrets || [],+ lastSecretSync: existing.lastSecretSync || null+ };+ }++ const listingMayBeTruncated = remoteRepos.length >= REPO_SYNC_LIMIT;+ const removed = listingMayBeTruncated+ ? []+ : Object.entries(current.repos)+ .filter(([, repo]) => repoBelongsToAccount(repo, owner) && !remoteNames.has(repo.fullName))+ .map(([fullName]) => fullName);+ for (const fullName of removed) delete current.repos[fullName];++ current.lastRepoSync = new Date().toISOString();+ current.githubUser = owner;+ await save(current);+ return { data: current, removed, listingMayBeTruncated };+ });+ const removedMsg = removed.length ? `, removed ${removed.length} deleted` : '';+ console.log(`🔄 Synced ${remoteRepos.length} repos from GitHub${removedMsg}`);+ if (listingMayBeTruncated) {+ console.log(`⚠️ GitHub repo list reached ${REPO_SYNC_LIMIT}; unmatched cached repos were preserved`);+ }+ return {+ ...data,+ repos: reposForAccount(data, owner),+ truncated: listingMayBeTruncated,};- }+ });+}- // Remove repos that no longer exist on GitHub- const removed = Object.keys(data.repos).filter(name => !remoteNames.has(name));- for (const name of removed) {- delete data.repos[name];+async function requireActiveCachedAccount(data) {+ const auth = await getPinnedGitHubAuth();+ if (!auth.authenticated || !auth.login) {+ throw new ServerError(auth.remedy || 'Sign in to GitHub before changing repositories.', {+ status: 401,+ code: 'GITHUB_NOT_AUTHENTICATED'+ });}-- data.lastRepoSync = new Date().toISOString();- await save(data);- const removedMsg = removed.length ? `, removed ${removed.length} deleted` : '';- console.log(`🔄 Synced ${remoteRepos.length} repos from GitHub${removedMsg}`);- return data;+ if (!data.githubUser || data.githubUser.toLowerCase() !== auth.login.toLowerCase()) {+ throw new ServerError('The cached repositories belong to a different GitHub account. Sync repositories before making changes.', {+ status: 409,+ code: 'GITHUB_ACCOUNT_MISMATCH'+ });+ }+ return auth;}/**@@ -162,70 +241,84 @@ export async function syncRepos() {*/export async function getRepos() {const data = await load();- return data.repos;+ return reposForAccount(data);}/*** Update repo flags and managed secrets*/export async function updateRepoFlags(fullName, updates) {- const data = await load();- const repo = data.repos[fullName];- if (!repo) throw new ServerError(`Repo not found: ${fullName}`, { status: 404, code: 'REPO_NOT_FOUND' });+ return queueDataWrite(async () => {+ const data = await load();+ const repo = data.repos[fullName];+ if (!repo || !repoBelongsToAccount(repo, data.githubUser)) {+ throw new ServerError(`Repo not found: ${fullName}`, { status: 404, code: 'REPO_NOT_FOUND' });+ }- if (updates.flags) {- repo.flags = { ...repo.flags, ...updates.flags };+ if (updates.flags) {+ repo.flags = { ...repo.flags, ...updates.flags };- // Auto-manage NPM_TOKEN based on npmProject flag- if (updates.flags.npmProject === true && !repo.managedSecrets.includes('NPM_TOKEN')) {- repo.managedSecrets.push('NPM_TOKEN');- } else if (updates.flags.npmProject === false) {- repo.managedSecrets = repo.managedSecrets.filter(s => s !== 'NPM_TOKEN');+ // Auto-manage NPM_TOKEN based on npmProject flag+ if (updates.flags.npmProject === true && !repo.managedSecrets.includes('NPM_TOKEN')) {+ repo.managedSecrets.push('NPM_TOKEN');+ } else if (updates.flags.npmProject === false) {+ repo.managedSecrets = repo.managedSecrets.filter(s => s !== 'NPM_TOKEN');+ }}- }- if (updates.managedSecrets) {- repo.managedSecrets = updates.managedSecrets;- }+ if (updates.managedSecrets) {+ repo.managedSecrets = updates.managedSecrets;+ }- await save(data);- return repo;+ await save(data);+ return repo;+ });}/*** Set a secret value and sync to all repos with it in managedSecrets*/export async function setSecret(name, value) {- // Store value in settings.json (never returned to client)- const settings = await getSettings();- const secrets = settings.secrets || {};- secrets[name] = value;- await updateSettings({ secrets });-- // Update metadata in github-repos.json- const data = await load();- data.secrets[name] = {- hasValue: true,- updatedAt: new Date().toISOString()- };- await save(data);+ return withGitHubMutation(async () => {+ const accountData = await load();+ await requireActiveCachedAccount(accountData);++ // Store value in settings.json (never returned to client)+ const settings = await getSettings();+ const secrets = settings.secrets || {};+ secrets[name] = value;+ await updateSettings({ secrets });++ // Update metadata in github-repos.json+ await queueDataWrite(async () => {+ const data = await load();+ data.secrets[name] = {+ hasValue: true,+ updatedAt: new Date().toISOString()+ };+ await save(data);+ });- // Sync to repos- const result = await syncSecretToRepos(name);- return result;+ return syncSecretToReposNow(name);+ });}/*** Sync a secret to all repos that have it in managedSecrets*/export async function syncSecretToRepos(name) {+ return withGitHubMutation(() => syncSecretToReposNow(name));+}++async function syncSecretToReposNow(name) {+ const data = await load();+ const auth = await requireActiveCachedAccount(data);const settings = await getSettings();const value = settings.secrets?.[name];if (!value) throw new ServerError(`No value stored for secret: ${name}`, { status: 400, code: 'SECRET_NOT_CONFIGURED' });- const data = await load();const targetRepos = Object.values(data.repos).filter(- r => r.managedSecrets.includes(name) && !r.isArchived+ r => repoBelongsToAccount(r, auth.login) && r.managedSecrets?.includes(name) && !r.isArchived);if (targetRepos.length === 0) {@@ -238,7 +331,7 @@ export async function syncSecretToRepos(name) {const succeeded = new Set();const tasks = targetRepos.map(repo => async () => {- const result = await syncOneSecret(name, value, repo.fullName);+ const result = await syncOneSecret(name, value, repo.fullName, auth.env);if (result.success) {synced++;succeeded.add(repo.fullName);@@ -250,13 +343,16 @@ export async function syncSecretToRepos(name) {await runWithConcurrency(tasks, CONCURRENCY);- // Update last sync timestamp only on repos where sync succeeded- for (const fullName of succeeded) {- if (data.repos[fullName]) {- data.repos[fullName].lastSecretSync = new Date().toISOString();+ await queueDataWrite(async () => {+ const current = await load();+ if (current.githubUser?.toLowerCase() !== auth.login.toLowerCase()) return;+ for (const fullName of succeeded) {+ if (current.repos[fullName]) {+ current.repos[fullName].lastSecretSync = new Date().toISOString();+ }}- }- await save(data);+ await save(current);+ });console.log(`🔑 Secret ${name} synced to ${synced} repos (${failed} failed)`);return { synced, failed, errors };@@ -265,44 +361,43 @@ export async function syncSecretToRepos(name) {/*** Sync a single secret to a single repo via stdin pipe*/-function syncOneSecret(name, value, fullName) {- return new Promise((resolve) => {- const child = spawn('gh', ['secret', 'set', name, '--repo', fullName], {- shell: false- });- let stderr = '';- child.stderr.on('data', (d) => { stderr += d.toString(); });- child.on('close', (code) => {- if (code === 0) {- resolve({ success: true });- } else {- resolve({ success: false, error: stderr.trim() || `exit code ${code}` });- }- });- child.on('error', (err) => {- resolve({ success: false, error: err.message });- });- child.stdin.write(value);- child.stdin.end();- });+async function syncOneSecret(name, value, fullName, env) {+ return execGh(+ ['secret', 'set', name, '--repo', fullName],+ SECRET_SYNC_TIMEOUT_MS,+ { env, input: value },+ ).then(+ () => ({ success: true }),+ (error) => ({ success: false, error: error.message }),+ );}/*** Archive or unarchive a repo on GitHub*/export async function setRepoArchived(fullName, archived) {- const cmd = archived ? 'archive' : 'unarchive';- await execGh(['repo', cmd, fullName, '--yes']);-- // Update local cache- const data = await load();- if (data.repos[fullName]) {- data.repos[fullName].isArchived = archived;- await save(data);- }+ return withGitHubMutation(async () => {+ const data = await load();+ if (!data.repos[fullName] || !repoBelongsToAccount(data.repos[fullName], data.githubUser)) {+ throw new ServerError(`Repo not found: ${fullName}`, { status: 404, code: 'REPO_NOT_FOUND' });+ }+ const auth = await requireActiveCachedAccount(data);+ const cmd = archived ? 'archive' : 'unarchive';+ await execGh(['repo', cmd, fullName, '--yes'], DEFAULT_EXEC_GH_TIMEOUT_MS, { env: auth.env });++ const updated = await queueDataWrite(async () => {+ const current = await load();+ if (!current.repos[fullName] || current.githubUser?.toLowerCase() !== auth.login.toLowerCase()) {+ return { ...data.repos[fullName], isArchived: archived };+ }+ current.repos[fullName].isArchived = archived;+ await save(current);+ return current.repos[fullName];+ });- console.log(`📦 ${archived ? 'Archived' : 'Unarchived'} ${fullName}`);- return data.repos[fullName] || { fullName, isArchived: archived };+ console.log(`📦 ${archived ? 'Archived' : 'Unarchived'} ${fullName}`);+ return updated;+ });}/**@@ -317,9 +412,11 @@ export async function getSecrets() {* Get sync status summary*/export async function getStatus() {- const data = await load();- const repos = Object.values(data.repos);+ const [data, auth] = await Promise.all([load(), getGitHubAuthStatus()]);+ const repos = Object.values(reposForAccount(data));return {+ ...auth,+ githubUser: data.githubUser || null,lastRepoSync: data.lastRepoSync,totalRepos: repos.length,activeRepos: repos.filter(r => !r.isArchived).length,@@ -499,6 +596,62 @@ export async function checkGhHealth({ force = false, timeoutMs = GH_PROBE_TIMEOUreturn health;}+/**+ * Resolve the account the GitHub CLI will actually use. A successful `api user`+ * is stronger than merely finding a token: it proves the credential works and+ * gives repo sync the owner it must query. The login is returned only to the+ * local UI; the credential inventory reduces this to presence/source.+ */+export async function getGitHubAuthStatus({ env = process.env } = {}) {+ const credentialSource = githubCredentialSource(env);+ const attempt = await execGh(+ ['api', 'user', '--hostname', GITHUB_HOST, '--jq', '.login'],+ GH_PROBE_TIMEOUT_MS,+ { env: githubDotComEnv(env) },+ )+ .then((login) => ({ login, error: null }))+ .catch((error) => ({ login: null, error }));+ if (attempt.login) {+ return { authenticated: true, status: 'ok', login: attempt.login, credentialSource, remedy: null };+ }++ const classified = attempt.error?.ghExitCode !== undefined+ ? classifyGhProbe({ code: attempt.error.ghExitCode, stderr: attempt.error.ghStderr })+ : attempt.error?.code+ ? classifyGhProbe({ spawnError: attempt.error })+ : classifyGhProbe({ code: null, stderr: attempt.error?.message });+ const status = classified.status === 'ok' ? 'error' : classified.status;+ return {+ authenticated: false,+ status,+ login: null,+ credentialSource,+ remedy: credentialSource === 'env' && status === 'not-authenticated'+ ? 'GH_TOKEN or GITHUB_TOKEN is set but GitHub rejected it. Update or remove that environment credential before using gh auth login.'+ : ghRemedy(status),+ };+}++async function getPinnedGitHubAuth() {+ const baseEnv = { ...process.env };+ const environmentToken = githubEnvironmentToken(baseEnv);+ const status = await getGitHubAuthStatus({+ env: environmentToken ? githubPinnedEnv(environmentToken, baseEnv) : baseEnv,+ });+ if (!status.authenticated || !status.login) return status;++ const token = environmentToken || await execGh([+ 'auth', 'token', '--user', status.login, '--hostname', GITHUB_HOST,+ ], GH_PROBE_TIMEOUT_MS, { env: githubDotComEnv(baseEnv) }).catch(() => null);+ if (!token) {+ throw new ServerError('Could not pin the active GitHub credential. Re-authenticate with gh and try again.', {+ status: 503,+ code: 'GITHUB_CREDENTIAL_UNAVAILABLE'+ });+ }+ return { ...status, env: githubPinnedEnv(token, baseEnv) };+}+/** Test seam — drops the memoized probe results. */export function __resetGhHealthCache() {ghHealthCache.clear();diff --git a/server/services/github.test.js b/server/services/github.test.jsindex 45397b36d3..518c5348ae 100644--- a/server/services/github.test.js+++ b/server/services/github.test.js@@ -1,19 +1,55 @@-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';-import { EventEmitter } from 'events';+import { EventEmitter } from 'node:events';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const mock = vi.hoisted(() => ({+ spawn: vi.fn(),+ readJSONFile: vi.fn(),+ atomicWrite: vi.fn(async () => {}),+ getSettings: vi.fn(async () => ({ secrets: { EXAMPLE_SECRET: 'fake-value' } })),+ updateSettings: vi.fn(async () => ({})),+}));vi.mock('../lib/childProcess.js', async (importOriginal) => {const actual = await importOriginal();- return { ...actual, spawn: vi.fn() };+ return { ...actual, spawn: mock.spawn };+});++vi.mock('../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ readJSONFile: mock.readJSONFile,+ atomicWrite: mock.atomicWrite,+ ensureDir: vi.fn(async () => {}),+ };+});++vi.mock('./settings.js', () => {+ return {+ getSettings: mock.getSettings,+ updateSettings: mock.updateSettings,+ };});import { spawn } from '../lib/childProcess.js';-import { execGh, getPullRequestState } from './github.js';+import {+ __resetGitHubDataCache,+ execGh,+ getGitHubAuthStatus,+ getPullRequestState,+ setRepoArchived,+ setSecret,+ syncRepos,+ syncSecretToRepos,+ updateRepoFlags,+} from './github.js';const makeChild = () => {const child = new EventEmitter();child.stdout = new EventEmitter();child.stderr = new EventEmitter();child.stdin = new EventEmitter();+ child.stdin.write = vi.fn();child.stdin.end = vi.fn();child.kill = vi.fn();return child;@@ -110,6 +146,18 @@ describe('execGh', () => {child.emit('error', new Error('spawn gh ENOENT'));await expect(promise).rejects.toThrow(/ENOENT/);});++ it('reports a timed-out account check as unreachable rather than signed out', async () => {+ const child = makeChild();+ spawn.mockReturnValue(child);+ const promise = getGitHubAuthStatus();+ vi.advanceTimersByTime(10000);++ await expect(promise).resolves.toMatchObject({+ authenticated: false,+ status: 'unreachable',+ });+ });});// The merge-follow-up reaper turns "the forge says this PR is OPEN" into a@@ -180,3 +228,416 @@ describe('getPullRequestState', () => {expect(spawn).not.toHaveBeenCalled();});});++const childReturning = (stdout) => {+ const child = new EventEmitter();+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ child.stdin = new EventEmitter();+ child.stdin.write = vi.fn();+ child.stdin.end = vi.fn();+ child.kill = vi.fn();+ queueMicrotask(() => {+ child.stdout.emit('data', Buffer.from(stdout));+ child.emit('close', 0);+ });+ return child;+};++const childFailing = (stderr) => {+ const child = new EventEmitter();+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ child.stdin = new EventEmitter();+ child.stdin.write = vi.fn();+ child.stdin.end = vi.fn();+ child.kill = vi.fn();+ queueMicrotask(() => {+ child.stderr.emit('data', Buffer.from(stderr));+ child.emit('close', 1);+ });+ return child;+};++const hangingChild = () => {+ const child = new EventEmitter();+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ child.stdin = new EventEmitter();+ child.stdin.write = vi.fn();+ child.stdin.end = vi.fn();+ child.kill = vi.fn();+ return child;+};++describe('GitHub repository sync account selection', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mock.spawn.mockReset();+ mock.atomicWrite.mockReset();+ mock.atomicWrite.mockResolvedValue(undefined);+ __resetGitHubDataCache();+ mock.readJSONFile.mockResolvedValue({+ repos: { 'legacy-owner/old-repo': { fullName: 'legacy-owner/old-repo' } },+ secrets: {},+ lastRepoSync: null,+ githubUser: 'legacy-owner',+ });+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ });++ it('targets github.com explicitly and reports when an environment token is in control', async () => {+ vi.stubEnv('GH_TOKEN', 'fake-example-token');+ mock.spawn.mockImplementation(() => childReturning('example-user'));++ await expect(getGitHubAuthStatus()).resolves.toMatchObject({+ authenticated: true,+ login: 'example-user',+ credentialSource: 'env',+ });+ expect(mock.spawn.mock.calls[0][1]).toEqual([+ 'api', 'user', '--hostname', 'github.com', '--jq', '.login',+ ]);+ });++ it('redacts command arguments from timeout errors and kill-failure logs', async () => {+ vi.useFakeTimers();+ const child = hangingChild();+ child.kill.mockImplementation(() => { throw new Error('simulated kill failure'); });+ mock.spawn.mockReturnValue(child);+ const errorLog = vi.spyOn(console, 'error').mockImplementation(() => {});++ const result = execGh(['repo', 'list', 'private-account-name'], 10).catch(error => error);+ await vi.advanceTimersByTimeAsync(10);+ const error = await result;++ expect(error.message).toBe('gh command timed out after 10ms');+ expect(error.message).not.toContain('private-account-name');+ expect(errorLog).toHaveBeenCalledWith(expect.stringContaining('failed to kill timed-out gh command'));+ expect(errorLog.mock.calls.flat().join(' ')).not.toContain('private-account-name');+ errorLog.mockRestore();+ vi.useRealTimers();+ });++ it('gives an environment-specific remedy when GitHub rejects an overriding token', async () => {+ vi.stubEnv('GH_TOKEN', 'fake-rejected-token');+ mock.spawn.mockImplementation(() => childFailing('HTTP 401: Bad credentials'));++ await expect(getGitHubAuthStatus()).resolves.toMatchObject({+ authenticated: false,+ status: 'not-authenticated',+ credentialSource: 'env',+ remedy: expect.stringMatching(/update or remove.*environment credential/i),+ });+ });++ it('refuses to sync cached owner data when gh is not authenticated', async () => {+ mock.spawn.mockImplementation(() => childFailing('You are not logged in. Run gh auth login.'));++ await expect(syncRepos()).rejects.toMatchObject({+ status: 401,+ code: 'GITHUB_NOT_AUTHENTICATED',+ });+ expect(mock.spawn).toHaveBeenCalledTimes(1);+ expect(mock.spawn.mock.calls[0][1]).toEqual([+ 'api', 'user', '--hostname', 'github.com', '--jq', '.login',+ ]);+ });++ it('syncs the active gh account instead of the stored legacy owner', async () => {+ vi.stubEnv('GH_TOKEN', 'fake-example-token');+ mock.spawn.mockImplementation((_command, args) => (+ args[0] === 'api' ? childReturning('example-user') : childReturning('[]')+ ));++ const result = await syncRepos();++ expect(mock.spawn).toHaveBeenNthCalledWith(+ 1,+ 'gh',+ ['api', 'user', '--hostname', 'github.com', '--jq', '.login'],+ expect.anything(),+ );+ expect(mock.spawn).toHaveBeenNthCalledWith(+ 2,+ 'gh',+ expect.arrayContaining(['repo', 'list', 'example-user']),+ expect.anything(),+ );+ expect(mock.spawn.mock.calls[1][1]).not.toContain('legacy-owner');+ expect(mock.spawn.mock.calls[1][2].env.GH_HOST).toBe('github.com');+ expect(result.githubUser).toBe('example-user');+ expect(result.repos).toEqual({});+ });++ it('pins a CLI account token into repository listing commands', async () => {+ vi.stubEnv('GH_TOKEN', '');+ vi.stubEnv('GITHUB_TOKEN', '');+ mock.spawn.mockImplementation((_command, args) => {+ if (args[0] === 'api') return childReturning('example-user');+ if (args[0] === 'auth') return childReturning('fake-pinned-token');+ return childReturning('[]');+ });++ await syncRepos();++ expect(mock.spawn.mock.calls[1][1]).toEqual([+ 'auth', 'token', '--user', 'example-user', '--hostname', 'github.com',+ ]);+ expect(mock.spawn.mock.calls[2][2].env).toMatchObject({+ GH_HOST: 'github.com',+ GH_TOKEN: 'fake-pinned-token',+ });+ expect(mock.spawn.mock.calls[2][2].env.GITHUB_TOKEN).toBeUndefined();+ });++ it('refuses to push secrets while cached repositories belong to another account', async () => {+ vi.stubEnv('GH_TOKEN', 'fake-example-token');+ mock.readJSONFile.mockResolvedValue({+ repos: {+ 'legacy-owner/old-repo': {+ fullName: 'legacy-owner/old-repo',+ managedSecrets: ['EXAMPLE_SECRET'],+ isArchived: false,+ },+ },+ secrets: { EXAMPLE_SECRET: { hasValue: true } },+ lastRepoSync: null,+ githubUser: 'legacy-owner',+ });+ mock.spawn.mockImplementation(() => childReturning('example-user'));++ await expect(syncSecretToRepos('EXAMPLE_SECRET')).rejects.toMatchObject({+ status: 409,+ code: 'GITHUB_ACCOUNT_MISMATCH',+ });+ expect(mock.spawn).toHaveBeenCalledTimes(1);+ });++ it('does not store a secret when its automatic sync would target another account cache', async () => {+ mock.spawn.mockImplementation(() => childReturning('example-user'));++ await expect(setSecret('EXAMPLE_SECRET', 'replacement-fake-value')).rejects.toMatchObject({+ status: 409,+ code: 'GITHUB_ACCOUNT_MISMATCH',+ });+ expect(mock.updateSettings).not.toHaveBeenCalled();+ expect(mock.atomicWrite).not.toHaveBeenCalled();+ });++ it('refuses to archive a cached repository owned by another account', async () => {+ vi.stubEnv('GH_TOKEN', 'fake-example-token');+ mock.spawn.mockImplementation(() => childReturning('example-user'));++ await expect(setRepoArchived('legacy-owner/old-repo', true)).rejects.toMatchObject({+ status: 409,+ code: 'GITHUB_ACCOUNT_MISMATCH',+ });+ expect(mock.spawn).toHaveBeenCalledTimes(1);+ });++ it('refuses to archive a repository that is not in the authenticated account cache', async () => {+ mock.readJSONFile.mockResolvedValue({+ repos: {},+ secrets: {},+ lastRepoSync: null,+ githubUser: 'example-user',+ });+ mock.spawn.mockImplementation(() => childReturning('example-user'));++ await expect(setRepoArchived('another-owner/unknown-repo', true)).rejects.toMatchObject({+ status: 404,+ code: 'REPO_NOT_FOUND',+ });+ expect(mock.spawn).not.toHaveBeenCalled();+ });++ it('archives a cached repository when the active account matches', async () => {+ vi.stubEnv('GH_TOKEN', 'fake-example-token');+ mock.readJSONFile.mockResolvedValue({+ repos: {+ 'example-user/example-repo': {+ name: 'example-repo',+ fullName: 'example-user/example-repo',+ isArchived: false,+ flags: {},+ managedSecrets: [],+ },+ },+ secrets: {},+ lastRepoSync: null,+ githubUser: 'example-user',+ });+ mock.spawn.mockImplementation(() => childReturning('example-user'));++ await expect(setRepoArchived('example-user/example-repo', true)).resolves.toMatchObject({+ fullName: 'example-user/example-repo',+ isArchived: true,+ });+ expect(mock.spawn.mock.calls[1][1]).toEqual([+ 'repo', 'archive', 'example-user/example-repo', '--yes',+ ]);+ expect(mock.spawn.mock.calls[1][2].env.GH_HOST).toBe('github.com');+ });++ it('pushes a secret only when the active account matches the repository cache', async () => {+ vi.stubEnv('GH_TOKEN', 'fake-example-token');+ mock.readJSONFile.mockResolvedValue({+ repos: {+ 'example-user/example-repo': {+ name: 'example-repo',+ fullName: 'example-user/example-repo',+ isArchived: false,+ flags: {},+ managedSecrets: ['EXAMPLE_SECRET'],+ },+ },+ secrets: { EXAMPLE_SECRET: { hasValue: true } },+ lastRepoSync: null,+ githubUser: 'example-user',+ });+ mock.spawn.mockImplementation(() => childReturning('example-user'));++ await expect(syncSecretToRepos('EXAMPLE_SECRET')).resolves.toMatchObject({+ synced: 1,+ failed: 0,+ });+ expect(mock.spawn.mock.calls[1][1]).toEqual([+ 'secret', 'set', 'EXAMPLE_SECRET', '--repo', 'example-user/example-repo',+ ]);+ expect(mock.spawn.mock.calls[1][2].env.GH_HOST).toBe('github.com');+ expect(mock.spawn.mock.calls[1][2].env.GH_TOKEN).toBe('fake-example-token');+ });++ it('bounds a hung secret push and releases later GitHub mutations', async () => {+ vi.useFakeTimers();+ vi.stubEnv('GH_TOKEN', 'fake-example-token');+ mock.readJSONFile.mockResolvedValue({+ repos: {+ 'example-user/example-repo': {+ name: 'example-repo',+ fullName: 'example-user/example-repo',+ isArchived: false,+ flags: {},+ managedSecrets: ['EXAMPLE_SECRET'],+ },+ },+ secrets: { EXAMPLE_SECRET: { hasValue: true } },+ lastRepoSync: null,+ githubUser: 'example-user',+ });+ mock.spawn.mockImplementation((_command, args) => (+ args[0] === 'secret' ? hangingChild() : childReturning('example-user')+ ));++ const secretSync = syncSecretToRepos('EXAMPLE_SECRET');+ await vi.advanceTimersByTimeAsync(60000);+ await expect(secretSync).resolves.toMatchObject({ synced: 0, failed: 1 });++ const flagsUpdate = updateRepoFlags('example-user/example-repo', { flags: { npmProject: true } });+ await expect(flagsUpdate).resolves.toMatchObject({ flags: { npmProject: true } });+ vi.useRealTimers();+ });++ it('does not delete cached repositories when the GitHub listing reaches its limit', async () => {+ vi.stubEnv('GH_TOKEN', 'fake-example-token');+ mock.readJSONFile.mockResolvedValue({+ repos: {+ 'example-user/keep-me': {+ name: 'keep-me',+ fullName: 'example-user/keep-me',+ flags: {},+ managedSecrets: [],+ },+ },+ secrets: {},+ lastRepoSync: null,+ githubUser: 'example-user',+ });+ const listed = Array.from({ length: 200 }, (_, index) => ({+ name: `repo-${index}`,+ nameWithOwner: `example-user/repo-${index}`,+ description: '',+ pushedAt: null,+ isArchived: false,+ isPrivate: false,+ isFork: false,+ parent: null,+ licenseInfo: null,+ }));+ mock.spawn.mockImplementation((_command, args) => (+ args[0] === 'api' ? childReturning('example-user') : childReturning(JSON.stringify(listed))+ ));++ const result = await syncRepos();++ expect(result.repos['example-user/keep-me']).toBeTruthy();+ });++ it('preserves another account\'s repository configuration across account switches', async () => {+ vi.stubEnv('GH_TOKEN', 'fake-example-token');+ mock.readJSONFile.mockResolvedValue({+ repos: {+ 'legacy-owner/configured-repo': {+ name: 'configured-repo',+ fullName: 'legacy-owner/configured-repo',+ flags: { npmProject: true },+ managedSecrets: ['NPM_TOKEN'],+ lastSecretSync: '2026-01-01T00:00:00.000Z',+ },+ },+ secrets: {},+ lastRepoSync: null,+ githubUser: 'legacy-owner',+ });+ mock.spawn.mockImplementation((_command, args) => (+ args[0] === 'api' ? childReturning('example-user') : childReturning('[]')+ ));++ const result = await syncRepos();++ expect(result.repos).toEqual({});+ const persisted = JSON.parse(mock.atomicWrite.mock.calls.at(-1)[1]);+ expect(persisted.repos['legacy-owner/configured-repo']).toMatchObject({+ flags: { npmProject: true },+ managedSecrets: ['NPM_TOKEN'],+ lastSecretSync: '2026-01-01T00:00:00.000Z',+ });+ });++ it('serializes concurrent updates to the shared repository cache', async () => {+ let releaseFirstWrite;+ mock.readJSONFile.mockResolvedValue({+ repos: {+ 'example-user/example-repo': {+ name: 'example-repo',+ fullName: 'example-user/example-repo',+ flags: {},+ managedSecrets: [],+ },+ },+ secrets: {},+ lastRepoSync: null,+ githubUser: 'example-user',+ });+ mock.atomicWrite+ .mockImplementationOnce(() => new Promise((resolve) => { releaseFirstWrite = resolve; }))+ .mockResolvedValue(undefined);++ const first = updateRepoFlags('example-user/example-repo', { flags: { npmProject: true } });+ const second = updateRepoFlags('example-user/example-repo', { managedSecrets: ['EXAMPLE_SECRET'] });++ await vi.waitFor(() => expect(mock.atomicWrite).toHaveBeenCalledTimes(1));+ releaseFirstWrite();+ await Promise.all([first, second]);++ const persisted = JSON.parse(mock.atomicWrite.mock.calls[1][1]);+ expect(persisted.repos['example-user/example-repo']).toMatchObject({+ flags: { npmProject: true },+ managedSecrets: ['EXAMPLE_SECRET'],+ });+ });+});