Skip to content

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

feat: repair a forge token's missing OAuth scope from the Pull Requests tab

Adam Eivy3dc17be88518
diff --git a/client/src/components/apps/ForgeScopeFix.jsx b/client/src/components/apps/ForgeScopeFix.jsx
new file mode 100644
index 0000000000..a9f051d73e
--- /dev/null
+++ b/client/src/components/apps/ForgeScopeFix.jsx
@@ -0,0 +1,85 @@
+import { ExternalLink, KeyRound, Copy } from 'lucide-react';
+import Banner from '../ui/Banner';
+import BrailleSpinner from '../BrailleSpinner';
+import useForgeScopeRefresh from '../../hooks/useForgeScopeRefresh';
+import { copyToClipboard } from '../../lib/clipboard';
+
+export const FORGE_SCOPE_MISSING_CODE = 'FORGE_TOKEN_SCOPE_MISSING';
+
+/** The `{ host, scopes, command, refreshable, message }` a scope-missing API error carries, or null for any other error. */
+export const forgeScopeFailureFrom = err => (err?.code === FORGE_SCOPE_MISSING_CODE && err.context?.host
+ ? { ...err.context, message: err.message }
+ : null);
+
+const buttonClass = 'px-3 py-1.5 bg-port-accent/20 text-port-accent hover:bg-port-accent/30 border border-port-border rounded-lg text-xs flex items-center gap-1 disabled:opacity-50';
+
+/**
+ * What to do when a forge call failed because the token lacks an OAuth scope.
+ * Always shows the exact command to run by hand; when the server says it can
+ * drive the refresh (`refreshable`), also offers to run it and shows the
+ * one-time code to approve in a browser. `onRefreshed` is the caller's cue to
+ * retry whatever failed.
+ */
+export default function ForgeScopeFix({ appId, failure, onRefreshed, onDismiss }) {
+ const { active, pending, device, start, cancel } = useForgeScopeRefresh({ appId, onRefreshed });
+ const scopeList = failure.scopes.join(', ');
+
+ return (
+ <Banner
+ tone="warning"
+ size="md"
+ icon={KeyRound}
+ title={`The ${failure.host} token is missing the ${scopeList} scope`}
+ actions={!active && onDismiss ? (
+ <button type="button" onClick={onDismiss} className="text-xs text-gray-400 hover:text-white">Dismiss</button>
+ ) : null}
+ >
+ <p className="text-gray-300">{failure.message}</p>
+
+ {device && (
+ <div className="mt-3 space-y-2">
+ <p className="text-gray-300">Enter this one-time code on {failure.host} to approve the new scope:</p>
+ <div className="flex flex-wrap items-center gap-3">
+ <code className="px-3 py-1.5 bg-port-bg border border-port-border rounded-lg text-lg font-mono tracking-widest text-white select-all">{device.code}</code>
+ <button type="button" onClick={() => copyToClipboard(device.code, 'Code copied')} className={buttonClass}>
+ <Copy size={12} aria-hidden="true" /> Copy code
+ </button>
+ <a href={device.url} target="_blank" rel="noopener noreferrer" className={buttonClass}>
+ <ExternalLink size={12} aria-hidden="true" /> Open {failure.host}
+ </a>
+ </div>
+ </div>
+ )}
+
+ <div className="mt-3 flex flex-wrap items-center gap-2">
+ {failure.refreshable && !active && (
+ <button type="button" onClick={() => start(failure.scopes)} className={buttonClass}>
+ <KeyRound size={12} aria-hidden="true" /> Authorize {scopeList}
+ </button>
+ )}
+ {active && !device && <BrailleSpinner text={pending ? 'Starting gh auth refresh' : 'Waiting for gh to print a code'} />}
+ {active && device && <BrailleSpinner text="Waiting for you to approve in the browser" />}
+ {active && (
+ <button type="button" onClick={cancel} className={buttonClass}>Cancel</button>
+ )}
+ </div>
+
+ {failure.command ? (
+ <div className="mt-3 text-xs text-gray-400">
+ {failure.refreshable ? 'Or run' : 'Run'} this in a terminal on the PortOS host{failure.refreshable ? '' : ' (PortOS will not request this scope for you)'}:
+ <div className="mt-1 flex flex-wrap items-center gap-2">
+ <code className="px-2 py-1 bg-port-bg border border-port-border rounded text-gray-200 font-mono break-all">{failure.command}</code>
+ <button type="button" onClick={() => copyToClipboard(failure.command, 'Command copied')} className={buttonClass}>
+ <Copy size={12} aria-hidden="true" /> Copy
+ </button>
+ </div>
+ </div>
+ ) : (
+ // A personal access token cannot be re-scoped by gh: it has to be reissued.
+ <p className="mt-3 text-xs text-gray-400">
+ This credential is a personal access token, which can&apos;t be updated in place. Reissue it with the {scopeList} scope and store the new one where PortOS reads it.
+ </p>
+ )}
+ </Banner>
+ );
+}
diff --git a/client/src/components/apps/tabs/PullRequestsTab.jsx b/client/src/components/apps/tabs/PullRequestsTab.jsx
index c84d8e5793..87ca7752b2 100644
--- a/client/src/components/apps/tabs/PullRequestsTab.jsx
+++ b/client/src/components/apps/tabs/PullRequestsTab.jsx
@@ -14,6 +14,7 @@ import ProviderModelSelector from '../../ProviderModelSelector';
import ReviewerPicker from '../../cos/ReviewerPicker';
import { PR_REVIEW_MODES, PR_REVIEW_MODE_OPTIONS, DEFAULT_PR_REVIEW_MODE, prReviewModeOption, REVIEWER_LIST_OVERRIDE_KEYS } from '../../cos/constants';
import ScopeAdherenceCheck from '../ScopeAdherenceCheck';
+import ForgeScopeFix, { forgeScopeFailureFrom } from '../ForgeScopeFix';
import { useConfirmDelete } from '../../../hooks/useConfirmDelete';
import { useCosTaskUpdates } from '../../../hooks/useCosTaskUpdates';
import useRunWithPicker from '../../../hooks/useRunWithPicker';
@@ -344,6 +345,9 @@ export default function PullRequestsTab({ appId, appName }) {
const [merging, setMerging] = useState(false);
const [mergeMethod, setMergeMethod] = useState(DEFAULT_MERGE_METHOD);
const [deleteBranchOnMerge, setDeleteBranchOnMerge] = useState(true);
+ // A merge the forge refused for a missing token scope: not a failure to toast
+ // away, but a credential the user can repair here and then retry.
+ const [scopeFailure, setScopeFailure] = useState(null);
// Resolve & merge and Do:Review default to the active provider. Untrusted:Review
// follows its own scheduled stages unless the user explicitly opts this pin in.
@@ -572,11 +576,14 @@ export default function PullRequestsTab({ appId, appName }) {
method: mergeMethod,
deleteBranch: deleteBranchOnMerge,
}).catch(err => {
- toast.error(err?.message || `Failed to merge #${number}`);
+ const scopeProblem = forgeScopeFailureFrom(err);
+ if (scopeProblem) setScopeFailure(scopeProblem);
+ else toast.error(err?.message || `Failed to merge #${number}`);
return null;
});
setMerging(false);
if (!result) return;
+ setScopeFailure(null);
cancelMerge();
// `deletedBranch` is the server's answer, not the request: it refuses to
@@ -736,6 +743,18 @@ export default function PullRequestsTab({ appId, appName }) {
)}
</div>
+ {scopeFailure && (
+ <ForgeScopeFix
+ appId={appId}
+ failure={scopeFailure}
+ onDismiss={() => setScopeFailure(null)}
+ onRefreshed={() => {
+ setScopeFailure(null);
+ toast('Token updated — press Merge again to retry');
+ }}
+ />
+ )}
+
{error && (
<Banner tone="error" size="md" icon={AlertTriangle}>
Couldn&apos;t load pull requests — {error}
diff --git a/client/src/components/apps/tabs/PullRequestsTab.test.jsx b/client/src/components/apps/tabs/PullRequestsTab.test.jsx
index a70f4d4aef..d438aa5f52 100644
--- a/client/src/components/apps/tabs/PullRequestsTab.test.jsx
+++ b/client/src/components/apps/tabs/PullRequestsTab.test.jsx
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
-import { render, screen, fireEvent, cleanup, waitFor, act } from '@testing-library/react';
+import { render, screen, fireEvent, cleanup, waitFor, act, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
const { socketHandlers, socketMock } = vi.hoisted(() => {
@@ -28,6 +28,15 @@ vi.mock('../../../services/apiLocalLlm', () => ({
getVisionModels: vi.fn().mockResolvedValue({ models: [] }),
}));
vi.mock('../../ui/Toast', () => ({ default: toastMock }));
+// The refresh slot is SSE-backed; its own behavior is the server state machine's
+// contract. Here the tab only has to offer it, drive it and react to its outcome.
+const { refreshSlot, refreshOptions } = vi.hoisted(() => ({
+ refreshSlot: { active: false, pending: false, device: null, start: vi.fn(), cancel: vi.fn() },
+ refreshOptions: {},
+}));
+vi.mock('../../../hooks/useForgeScopeRefresh', () => ({
+ default: (options) => { refreshOptions.current = options; return refreshSlot; },
+}));
vi.mock('../../../services/api', () => ({
getAppPullRequests: vi.fn(),
getInstanceFeatures: vi.fn().mockResolvedValue({ features: {} }),
@@ -529,6 +538,61 @@ describe('PullRequestsTab', () => {
));
});
+ describe('a merge refused for a missing token scope', () => {
+ const scopeError = () => Object.assign(new Error('GraphQL: refusing to allow an OAuth App to create or update workflow without `workflow` scope'), {
+ code: 'FORGE_TOKEN_SCOPE_MISSING',
+ context: { host: 'ghe.example.com', scopes: ['workflow'], command: 'gh auth refresh -h ghe.example.com -s workflow', refreshable: true },
+ });
+ const mergeOnce = async () => {
+ api.mergeAppPullRequest.mockRejectedValue(scopeError());
+ await renderTab();
+ fireEvent.click(await screen.findByRole('button', { name: /^Merge$/ }));
+ fireEvent.click(screen.getByRole('button', { name: /Merge #17/ }));
+ await screen.findByText(/token is missing the workflow scope/);
+ };
+
+ beforeEach(() => {
+ Object.assign(refreshSlot, { active: false, pending: false, device: null });
+ refreshSlot.start.mockClear();
+ });
+
+ it('offers the enterprise host\'s fix instead of a bare error toast', async () => {
+ await mergeOnce();
+
+ expect(screen.getByText(/ghe\.example\.com token is missing/)).toBeInTheDocument();
+ expect(screen.getByText('gh auth refresh -h ghe.example.com -s workflow')).toBeInTheDocument();
+ expect(toastMock.error).not.toHaveBeenCalled();
+ // The confirm row stays, so the merge can be retried straight after the fix.
+ expect(screen.getByLabelText('Merge method for #17')).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: /Authorize workflow/ }));
+ expect(refreshSlot.start).toHaveBeenCalledWith(['workflow']);
+ });
+
+ it('shows the one-time code to approve while gh waits, and can cancel the flow', async () => {
+ Object.assign(refreshSlot, { active: true, device: { code: 'ABCD-1234', url: 'https://ghe.example.com/login/device' } });
+ await mergeOnce();
+
+ expect(screen.getByText('ABCD-1234')).toBeInTheDocument();
+ expect(screen.getByRole('link', { name: /Open ghe\.example\.com/ })).toHaveAttribute('href', 'https://ghe.example.com/login/device');
+ expect(screen.queryByRole('button', { name: /Authorize workflow/ })).not.toBeInTheDocument();
+
+ // The merge confirm row has its own Cancel; this one belongs to the banner.
+ const banner = screen.getByText(/token is missing the workflow scope/).closest('[role="status"]');
+ fireEvent.click(within(banner).getByRole('button', { name: 'Cancel' }));
+ expect(refreshSlot.cancel).toHaveBeenCalled();
+ });
+
+ it('clears the banner and points back at Merge once the scope is granted', async () => {
+ await mergeOnce();
+
+ act(() => refreshOptions.current.onRefreshed());
+
+ expect(screen.queryByText(/token is missing the workflow scope/)).not.toBeInTheDocument();
+ expect(toastMock).toHaveBeenCalledWith(expect.stringContaining('press Merge again'));
+ });
+ });
+
it('keeps the confirm row open so a refused merge method can be changed', async () => {
api.mergeAppPullRequest.mockRejectedValue(new Error('Squash merges are not allowed on this repository'));
diff --git a/client/src/components/apps/tabs/RepositorySourcePanel.jsx b/client/src/components/apps/tabs/RepositorySourcePanel.jsx
index 1be9686203..540030b2ba 100644
--- a/client/src/components/apps/tabs/RepositorySourcePanel.jsx
+++ b/client/src/components/apps/tabs/RepositorySourcePanel.jsx
@@ -22,6 +22,7 @@ import BrailleSpinner from '../../BrailleSpinner';
import Modal from '../../ui/Modal';
import toast from '../../ui/Toast';
import AppOperationBanner from '../AppOperationBanner';
+import ForgeScopeFix, { forgeScopeFailureFrom } from '../ForgeScopeFix';
import GitRecoveryAction from './GitRecoveryAction';
import { useAppOperation } from '../../../hooks/useAppOperation';
@@ -161,6 +162,7 @@ export default function RepositorySourcePanel({ appId, appName, onUpdated, refre
const [syncingFork, setSyncingFork] = useState(false);
const [updateRequested, setUpdateRequested] = useState(false);
const [error, setError] = useState(null);
+ const [scopeFailure, setScopeFailure] = useState(null);
const [updateIntent, setUpdateIntent] = useState(null);
const lastRefreshKey = useRef(refreshKey);
@@ -244,10 +246,13 @@ export default function RepositorySourcePanel({ appId, appName, onUpdated, refre
const handleSyncOnly = async () => {
setSyncingFork(true);
const result = await api.syncAppRepositoryFork(appId, { silent: true }).catch((reason) => {
- toast.error(reason.message || 'Could not sync the app fork');
+ const scopeProblem = forgeScopeFailureFrom(reason);
+ if (scopeProblem) setScopeFailure(scopeProblem);
+ else toast.error(reason.message || 'Could not sync the app fork');
return null;
});
if (result) {
+ setScopeFailure(null);
toast.success(result.alreadyUpToDate ? 'Fork is already current' : 'Fork synced from upstream');
await load();
}
@@ -297,6 +302,20 @@ export default function RepositorySourcePanel({ appId, appName, onUpdated, refre
</button>
</div>
+ {scopeFailure && (
+ <div className="mt-4">
+ <ForgeScopeFix
+ appId={appId}
+ failure={scopeFailure}
+ onDismiss={() => setScopeFailure(null)}
+ onRefreshed={() => {
+ setScopeFailure(null);
+ toast('Token updated — sync the fork again');
+ }}
+ />
+ </div>
+ )}
+
{(isOperating || restarting || operationError || operationCompleted) && (
<div className="mt-4">
<AppOperationBanner
diff --git a/client/src/components/apps/tabs/RepositorySourcePanel.test.jsx b/client/src/components/apps/tabs/RepositorySourcePanel.test.jsx
index c2ffacffb0..c0b2d97ec4 100644
--- a/client/src/components/apps/tabs/RepositorySourcePanel.test.jsx
+++ b/client/src/components/apps/tabs/RepositorySourcePanel.test.jsx
@@ -14,6 +14,9 @@ vi.mock('../../../services/apiLocalLlm', async (importOriginal) => ({
...await importOriginal(),
getToolUseModels: vi.fn().mockResolvedValue({ models: [] }),
}));
+vi.mock('../../../hooks/useForgeScopeRefresh', () => ({
+ default: () => ({ active: false, pending: false, device: null, start: vi.fn(), cancel: vi.fn() }),
+}));
vi.mock('../../../hooks/useAppOperation', () => ({
useAppOperation: vi.fn(),
}));
@@ -162,6 +165,30 @@ describe('managed app repository sources', () => {
expect(useAppOperation.mock.results[0].value.startUpdate).not.toHaveBeenCalled();
});
+ it('offers the credential fix when the fork sync is refused for a missing token scope', async () => {
+ const status = canonicalStatus();
+ status.sources[0] = source({
+ id: 'primary',
+ label: 'Example App',
+ branch: 'main',
+ head: '1'.repeat(40),
+ origin: { fullName: 'example-owner/example-app', isUpstream: false, isFork: true },
+ forkVsUpstream: { available: true, ahead: 0, behind: 2, state: 'behind', error: null },
+ });
+ api.getAppRepositorySources.mockResolvedValue(status);
+ api.syncAppRepositoryFork.mockRejectedValue(Object.assign(new Error('refused without `workflow` scope'), {
+ code: 'FORGE_TOKEN_SCOPE_MISSING',
+ context: { host: 'ghe.example.com', scopes: ['workflow'], command: 'gh auth refresh -h ghe.example.com -s workflow', refreshable: true },
+ }));
+ render(<RepositorySourcePanel appId="app-example" appName="Example App" />);
+
+ await screen.findByTestId('repository-source-primary');
+ fireEvent.click(screen.getByRole('button', { name: 'Sync fork' }));
+
+ expect(await screen.findByText(/ghe\.example\.com token is missing the workflow scope/)).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /Authorize workflow/ })).toBeInTheDocument();
+ });
+
// Eidoverse's video checkout is cloned from `anima-research`'s fork of a third
// project. The drift from upstream is real and worth reporting, but PortOS can
// only read that fork — so the panel must say so instead of offering a sync
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 3c1eba011d..4a9b6798f7 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -255,6 +255,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useVideoGenSubmitFlow` | Builds the current VideoGen wire payload and enveloped prompt from a form-state snapshot. | Internal submission slice composed by `useVideoGenForm`; all local, Grok, and federated request shaping remains in `videoGenSubmission`. |
| `useVideoGenValidation` | Derives keyframe errors and all VideoGen submit-blocking predicates from the current fields and model capabilities. | Internal validation slice composed by `useVideoGenForm`; also exports `validateVideoKeyframes` for focused tests. |
| `useVideoDownload` | One full-video-download job slot (#1946): start/cancel + SSE progress + terminal-frame handling via `POST /api/devtools/video-download`. Returns `{ active, percent, stage, context, start(url, context), cancel }`; `onComplete(video)` fires with the finished video-history entry. | The Dev Tools Video Downloader page. |
+| `useForgeScopeRefresh` | One forge-token scope-refresh slot for a managed app (`useSseJobSlot` over `POST /api/apps/:id/forge-auth/refresh`): `start(scopes)` runs `gh auth refresh` for the app's own forge host (server-derived, enterprise hosts included), `device` is the `{ code, url }` the user approves in a browser (null until gh prints it), `onRefreshed()` fires on confirmation. Returns `{ active, pending, device, start, cancel }`. | Any surface that hits a `FORGE_TOKEN_SCOPE_MISSING` error — pair with `<ForgeScopeFix>`. |
| `useReferenceAudioImport` | One round reference-audio-import job slot (#2120): start/cancel + SSE progress + terminal-frame handling via `POST /api/rounds/reference-audio/import`. Returns `{ active, percent, stage, start(url, context), cancel }`; `onComplete(filename, context)` fires with the uploads-dir filename to persist on the reference. Call once per surface that can independently kick off a download. | The reference-audio attach controls (`ReferenceAudioAttach`) — the "Download from URL" convenience. |
| `useMidiTranscription` | One audio → MIDI transcription job slot (MuScriptor): start/cancel + SSE stage progress + terminal-frame handling, generic over the Rounds and Music Video API surfaces (pass `startRequest`/`eventsUrl`/`cancelRequest`). Returns `{ active, stage, stageLabel, context, start(context), cancel }` (`stageLabel` is the ready-to-render human label for the current STAGE — including a distinct "Downloading model…" for the first-use weight download, which also fires a one-time toast; `context` is the in-flight job's captured target, for per-target UI gates); `onComplete(frame, context)` fires with the terminal frame (`filename`, `model`, any server-merged extras). | The Rounds reference "Transcribe MIDI" control and the Music Video MIDI button. |
| `useMusicVideoYoutubeImport` | The Music Video page's two independent `useYoutubeTrackImport` slots (create form + detail-view track row) plus their URL drafts, the detail slot's captured target project, and the URL-nav backstop that bounces a deep link / Back / ⌘K jump away from an in-flight import back to its project. Returns `{ createUrl, setCreateUrl, editUrl, setEditUrl, createJob, editJob, startCreate, startEdit, switchBlockedMessage }`. | The Music Video page. Reuse `switchBlockedMessage` for any additional guard (delete, list picker) so every surface says the same thing. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index eca4e9a339..6e14b88940 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -30,6 +30,7 @@ export { default as useFieldDraft } from './useFieldDraft.js';
export { default as useFilmLookPresets } from './useFilmLookPresets.js';
export { default as useFableLoomAiRun } from './useFableLoomAiRun.js';
export { default as useFocusTrap } from './useFocusTrap.js';
+export { default as useForgeScopeRefresh } from './useForgeScopeRefresh.js';
export { default as useGallerySidecars } from './useGallerySidecars.js';
export { default as useGalleryPreviewResolver } from './useGalleryPreviewResolver.js';
export { default as useGeneratedPreview } from './useGeneratedPreview.js';
diff --git a/client/src/hooks/useForgeScopeRefresh.js b/client/src/hooks/useForgeScopeRefresh.js
new file mode 100644
index 0000000000..c74623c8b4
--- /dev/null
+++ b/client/src/hooks/useForgeScopeRefresh.js
@@ -0,0 +1,26 @@
+import { startAppForgeRefresh, appForgeRefreshEventsUrl, cancelAppForgeRefresh } from '../services/apiApps.js';
+import useSseJobSlot from './useSseJobSlot.js';
+
+/**
+ * One forge-scope refresh slot for a managed app: `start(scopes)` asks the server
+ * to run `gh auth refresh` for the app's forge host, `device` is the one-time
+ * code + URL the user must approve in a browser (null until `gh` prints it), and
+ * `onRefreshed()` fires once GitHub confirms. Thin wrapper over `useSseJobSlot`,
+ * so a dropped stream or a server-side failure always releases the slot — the UI
+ * is never stuck "refreshing".
+ */
+export default function useForgeScopeRefresh({ appId, onRefreshed } = {}) {
+ const { active, pending, latest, start, cancel } = useSseJobSlot({
+ startRequest: (scopes) => startAppForgeRefresh(appId, scopes, { silent: true }),
+ eventsUrl: (jobId) => appForgeRefreshEventsUrl(appId, jobId),
+ cancelRequest: (jobId, options) => cancelAppForgeRefresh(appId, jobId, options),
+ onComplete: () => onRefreshed?.(),
+ successToast: (frame) => `Token for ${frame.host} now has ${frame.scopes.join(', ')}`,
+ errorFallback: 'Token refresh failed',
+ canceledMessage: 'Token refresh cancelled',
+ lostConnectionMessage: 'Lost connection to the token refresh — start it again',
+ startErrorFallback: 'Failed to start the token refresh',
+ });
+ const device = latest?.type === 'device-code' ? { code: latest.code, url: latest.url } : null;
+ return { active, pending, device, start, cancel };
+}
diff --git a/client/src/services/apiApps.js b/client/src/services/apiApps.js
index 7fc0e4200e..960881c378 100644
--- a/client/src/services/apiApps.js
+++ b/client/src/services/apiApps.js
@@ -167,6 +167,22 @@ export const mergeAppPullRequest = (id, number, { method, deleteBranch } = {}, o
silent: true,
...options,
});
+// Repair a forge token's missing OAuth scope: start `gh auth refresh` for the
+// app's own forge host (the server derives it — never sent). Kickoff returns
+// `{ jobId }`; the device code and outcome stream over SSE (`useForgeScopeRefresh`).
+export const startAppForgeRefresh = (id, scopes, options = {}) =>
+ request(`/apps/${id}/forge-auth/refresh`, {
+ method: 'POST',
+ body: JSON.stringify({ scopes }),
+ ...options,
+ });
+export const appForgeRefreshEventsUrl = (id, jobId) =>
+ `/api/apps/${id}/forge-auth/refresh/${encodeURIComponent(jobId)}/events`;
+export const cancelAppForgeRefresh = (id, jobId, options = {}) =>
+ request(`/apps/${id}/forge-auth/refresh/${encodeURIComponent(jobId)}/cancel`, {
+ method: 'POST',
+ ...options,
+ });
// Effective Layered Intelligence config (self-improvement loop) for an app —
// stored partial merged over the shipped defaults. Read-only; saved through
// updateApp (the `layeredIntelligence` key routes to the merge helper server-
diff --git a/server/lib/README.md b/server/lib/README.md
index 03a44030e0..987c7cf579 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -478,7 +478,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `execGit.js` | `execGit(args, cwd, options)` and `execGitSafe(args, cwd, options)` shared process boundary for Git operations, worktrees, and `services/forgeAuth.js` credential resolution. The safe variant converts rejections into `{ exitCode: 1, stdout: '', stderr }`; `services/git.js` re-exports both for compatibility. `cwd` is REQUIRED — it rejects on a missing/blank one rather than letting `spawn` fall back to `process.cwd()` and run git against PortOS's own checkout (#4554). |
| `ffmpeg.js` | `runFfmpegProcess({ bin, args, signal, timeoutMs })` — `timeoutMs` (opt-in; `FFMPEG_FRAME_TIMEOUT_MS` for one frame, `FFMPEG_SCAN_TIMEOUT_MS` for a full-file pass) SIGTERMs then SIGKILLs a stalled child and resolves `{ ok:false, reason:'timed out after <n>s' }`; the `signal` abort path escalates the same way. Long encodes pass no ceiling. `probeMediaTags` reads container/stream tags, returning null when inspection fails. Shared ffmpeg helpers (videoGen + videoTimeline). `vfrSyncArgs(bin)` probes/caches supported VFR output flags per binary (fps_mode on current builds, vsync on older builds); inconclusive probes stay uncached. `probeVideoGeometry(videoPath)` measures a finished clip's `{ width, height, fps, numFrames, durationSec }` (null when any axis is unreadable) for hosted renders that record no frame count. `generateThumbnail(videoPath, jobId, { atSec } = {})` accepts a clamped poster seek while preserving the single-clip default. Includes `probeFrameCount(videoPath)` (metadata `nb_frames`, falling back to a real `-count_frames` pass — expensive, so call it once per file) and `trimVideoFromFrame(videoPath, outPath, {startFrame, fps})` — a frame-EXACT head cut via the `trim` filter (an `-ss` seek can drift a frame, which reads as a stutter at a stitch seam), keeping audio in sync with `atrim` when the clip has a soundtrack and taking `-an` when it doesn't. Re-encodes by necessity, so a later concat must re-encode too; `outPath` may equal the input (temp-file + rename install). Used by the chained-render context window — see `videoContinuity.js`. `buildTrimConcatArgs({inputs, outPath, width, height, fps, withAudio})` builds the argv for the other half of that job: a concat that drops leading frames from some of its inputs inside a `filter_complex` graph, so the cuts ride along with the timeline encode instead of costing one pre-encode per clip (pass `withAudio` only when EVERY input has an audio stream — check with `hasAudioStream`). `buildExtendSpliceArgs({sourcePath, generatedPath, outPath, keepFrames, newStartFrame, width, height, fps, audio, sourceAudioPath, masterOutPath})` is the plain-Extend counterpart: source frames `[0, keep)` + render frames from `newStartFrame`, one encode, audio crossfaded (~40 ms linear) at the seam; `sourceAudioPath` swaps the source span's audio for a lossless master and `masterOutPath` also writes the mix as a 24-bit FLAC master, so the delivered AAC is encoded once from PCM. Its stream-copy sibling is `buildExtendNewSpanArgs` (encode only the render's new span) + `buildExtendConcatList` + `buildExtendCopyArgs` (join it to the untouched source with `-c:v copy`); `probeVideoCodecSignature` gates it and `videoFrameHashes` (per-frame MD5) proves the join before anything is replaced; `audioFingerprint` / `sealAudioMaster` / `readAudioMasterFingerprint` bind a master to the exact decoded soundtrack it was mixed for so a replaced soundtrack invalidates it — driven by `services/videoGen/extendSplice.js`. `H264_ENCODE_ARGS` / `AAC_ENCODE_ARGS` are the shared encode profile: clips produced by different paths here get concatenated together, so a mismatch shows up as one segment graded differently from its neighbours — spread these rather than re-typing the flags. Every re-encode here also pins BT.709: `BT709_CONTAINER_ARGS` (the `colr` atom, always emitted) plus `bt709TagFilter()` → the `BT709_TAG_FILTER` `setparams=…` string, or `null` on an ffmpeg without that filter (`supportsSetparamsFilter()` probes `-filters` once per process; `null` = not probed, and a probe that couldn't run stays uncached). Both halves are required — from ffmpeg 8 the encoder reads color properties off the FRAMES, silently overriding the container flags, so a flags-only output decodes washed-out. `buildTrimConcatArgs` takes the filter as its `colorTagFilter` option rather than probing, to stay pure. `installEncodedVideo(tmpPath, targetPath, label)` is the shared in-place install: move the original aside to a `.bak` on Windows (where `fs.rename` refuses an existing destination), rename the new file over it, and restore the backup — plus unlink the temp — on any failure, returning `{ok:true,outPath}` / `{ok:false,reason}` so the worst case is "skipped", never "the video is gone". Use it for EVERY replace-a-video-with-its-re-encode path; `pipeline/audioMux.js` is the out-of-module caller. `edgeFadeFilter(durationSec)` is the `-af` fade-in/fade-out fragment a mid-song clip (a social cut) appends to its trim. Loudness mastering (#10249): `MASTER_LOUDNESS` (-14 LUFS / -1.5 dBTP / LRA 11), `planLoudnessMaster` (measure then build the linear apply filter; throws on a silent source), `reportMasteredLoudness` (post-encode before/after numbers). |
| `ffmpegFilterGraph.js` | `filterGraphViaFile(bin, args, path)` moves a `-filter_complex` graph over `FILTER_GRAPH_ARG_LIMIT` into a file (`-/filter_complex`, or `-filter_complex_script` before ffmpeg 7), since Linux and Windows cap argument length. Used by the music video render and excerpt encodes. |
-| `forgeAccessErrors.js` | `isForgeNoAccessError(err)` / `isForgeNoAccessMessage(text)` / `logForgeNoAccessOnce(scope, repoSpec, detail)` / `forgeNoAccessRemedy(repoSpec)` — tells a PERMANENT `gh` no-access 404 (`Could not resolve to a Repository`, `HTTP 404`) apart from a transient blip. `execGh` stamps `ghNoAccess` on the rejection and keeps it OUT of the consecutive-failure backoff (which caps at 15 min and then re-fires forever), and the polling jobs (`branchReconcile`, `prWatcher`) narrate it exactly once per scope+repo per process with a remedy line instead of once per tick. `__resetForgeNoAccessLog()` is the test seam. |
+| `forgeAccessErrors.js` | `isForgeNoAccessError(err)` / `isForgeNoAccessMessage(text)` / `logForgeNoAccessOnce(scope, repoSpec, detail)` / `forgeNoAccessRemedy(repoSpec)` — tells a PERMANENT `gh` no-access 404 (`Could not resolve to a Repository`, `HTTP 404`) apart from a transient blip. `execGh` stamps `ghNoAccess` on the rejection and keeps it OUT of the consecutive-failure backoff (which caps at 15 min and then re-fires forever), and the polling jobs (`branchReconcile`, `prWatcher`) narrate it exactly once per scope+repo per process with a remedy line instead of once per tick. `__resetForgeNoAccessLog()` is the test seam. The same file classifies a MISSING OAuth scope (`parseForgeMissingScopes(text)` / `forgeMissingScopesOf(err)` — GraphQL ``without `workflow` scope``, REST `needs the "x" scope`, gh's `missing required scopes [x]`; never `Resource not accessible by integration`): `execGh` stamps `ghMissingScopes` and keeps it out of backoff, `forgeScopeRefreshCommand(host, scopes)` builds the hand-run `gh auth refresh` fix, and `REFRESHABLE_FORGE_SCOPES` is the closed set PortOS will drive itself (`services/forgeScopeRefresh.js`). |
| `forkHead.js` | `normalizeForkHead(value)` / `forkRemoteName(ownerLogin)` / `resolveTaskForkHead(metadata)` — the validated `{remoteUrl, ownerLogin}` address of a cross-repository PR's head branch, which has no `origin/<branch>` to attach to. Fail-closed: anything that isn't a usable pair (or that starts with `-`, which git would read as an option) is `null`, so every caller falls back to origin-only behavior instead of guessing. `forkRemoteName` is the deterministic `fork-<owner>` remote name that makes a re-attach reuse the remote it already added. Shared by `appPullRequests.js` (produces), `agentWorktreeCleanup.js`/`prRemediationFollowUp.js` (persist in task metadata), `agentWorkspacePrep.js` (threads), and `worktreeManager.js` (consumes — it has no forge client of its own). `resolveTaskForkHead` is the single reader of the generic `forkHead` task-metadata key, the fork-side counterpart to `taskTargetBranch.js`. |
| `frameQuality.js` | Scores decoded video frames so a chained render can CHOOSE its continuation anchor instead of taking whatever an end-seek lands on. `scoreFrame({width,height,data},{recency})` combines three terms over a raw single-channel buffer: log-compressed `gradientVariance` (focus), distance of `meanLuma` from mid-grey (exposure penalty, which rejects a fade-to-black or a blown highlight), and a small linear recency bonus that keeps the anchor near the cut when candidates are comparably clean. Usability and ranking are deliberately separate: `usable` gates on raw gradient variance against `MIN_SIGNAL_VARIANCE` alone, so only a mathematically degenerate frame is rejected and a legitimately dark low-key tail still qualifies — the same contract `imageFrameStats.js` keeps. Gating on the composite score instead would reject every night scene on the exposure term. `TAIL_WINDOW_SECONDS` is capped at the reach of the single `-sseof -1.0` seek this replaces: focus is systematically highest at the OLDEST candidate, so a wider window would widen the backward jump at each chain seam rather than tightening it. `pickBestFrame(paths)` decodes each candidate through `sharp` and returns the winner (or `null` when nothing decodes or every candidate is degenerate, so the caller degrades rather than failing a render); its `index` is the position in the array AS PASSED, because the caller turns that into the anchor's time offset. `MAX_CANDIDATES` is derived from the window, never set independently — the ffmpeg-side `-frames:v` cap truncates from the NEWEST end, exactly the frames recency prefers. `TAIL_WINDOW_SECONDS` / `CANDIDATE_FPS` / `MAX_CANDIDATES` define the window the caller decodes from. Consumer: `services/videoGen/local.js#extractLastFrame`. |
| `ffmpegRenderGuard.js` | `attachFfmpegRenderGuard(proc, {label, onSpawnError, onProcessError, onClose})` — shared spawn-state tracking + exactly-once `terminal` guard + pre-vs-post-spawn dispatch for the SSE ffmpeg render runners (musicVideo/render + videoTimeline/local). Owns the 'spawn'/'error'/'close' wiring (only the pre-spawn 'error' or 'close' finalizes; a post-spawn 'error' records only) and takes the service-specific finalize bodies as callbacks so each renderer keeps its own project-status/history behavior. |
diff --git a/server/lib/forgeAccessErrors.js b/server/lib/forgeAccessErrors.js
index e2e6868fc1..4e4543468a 100644
--- a/server/lib/forgeAccessErrors.js
+++ b/server/lib/forgeAccessErrors.js
@@ -65,6 +65,84 @@ export function forgeNoAccessRemedy(repoSpec) {
+ 'log in to the owning account (`gh auth login`) or pin it on the app record\'s Forge account field';
}
+// A credential that REACHES the repo but lacks an OAuth scope. Like no-access it
+// is permanent until the credential changes, so `execGh` keeps it out of the
+// backoff too. Three phrasings, because GitHub answers per transport: GraphQL
+// ("refusing to allow an OAuth App to create or update workflow … without
+// `workflow` scope"), REST ("needs the \"gist\" scope"), and gh's own preflight
+// ("missing required scopes [workflow]"). Deliberately NOT
+// "Resource not accessible by integration": that is a permission grant on an
+// App token, which no scope refresh fixes.
+const MISSING_SCOPE_PATTERNS = [
+ /without [`'"]?([\w:.-]+)[`'"]? scope/i,
+ /needs? the [`'"]?([\w:.-]+)[`'"]? scope/i,
+ /missing required scopes? \[([^\]]+)\]/i,
+ /requires one of the following scopes: \[([^\]]+)\]/i,
+];
+const SCOPE_NAME = /^[a-z][a-z0-9:_.-]*$/i;
+
+/**
+ * The OAuth scope names a `gh` failure says the token lacks, [] when it says
+ * nothing of the kind. Names are validated: they end up in a displayed command
+ * and a spawn argument, so a malformed capture never reaches either.
+ * @param {string|null|undefined} text
+ * @returns {string[]}
+ */
+export function parseForgeMissingScopes(text) {
+ if (typeof text !== 'string' || !text.trim()) return [];
+ for (const pattern of MISSING_SCOPE_PATTERNS) {
+ const match = pattern.exec(text);
+ if (!match) continue;
+ const scopes = match[1].split(',').map((scope) => scope.replace(/['"`\s]/g, '')).filter((scope) => SCOPE_NAME.test(scope));
+ if (scopes.length > 0) return [...new Set(scopes)];
+ }
+ return [];
+}
+
+/**
+ * Whether the refusal names a personal access token rather than an OAuth login.
+ * `gh auth refresh` only re-scopes the keyring's OAuth token; a PAT has to be
+ * reissued with the scope, so the refresh must not be offered for it.
+ * @param {string|null|undefined} text
+ * @returns {boolean}
+ */
+export const isForgePersonalTokenRefusal = (text) => typeof text === 'string' && /personal access token/i.test(text);
+
+/**
+ * Scopes a missing-scope `execGh` rejection names. Prefers the `ghMissingScopes`
+ * `execGh` stamps on, falling back to re-reading stderr/message for a caller that
+ * received the error through a wrapper that dropped it.
+ * @param {unknown} err
+ * @returns {string[]}
+ */
+export function forgeMissingScopesOf(err) {
+ if (!err || typeof err !== 'object') return [];
+ if (Array.isArray(err.ghMissingScopes) && err.ghMissingScopes.length > 0) return err.ghMissingScopes;
+ const fromStderr = parseForgeMissingScopes(err.ghStderr);
+ return fromStderr.length > 0 ? fromStderr : parseForgeMissingScopes(err.message);
+}
+
+/**
+ * Scopes the one-click refresh may request. Refreshing grants whatever is named
+ * once the user approves it in their browser, so this is a closed set of
+ * ordinary working scopes — never `admin:*` or `delete_repo`. A scope outside it
+ * still gets the printed command; PortOS just won't drive it.
+ */
+export const REFRESHABLE_FORGE_SCOPES = Object.freeze([
+ 'repo', 'workflow', 'read:org', 'gist', 'project', 'read:project',
+ 'read:packages', 'write:packages', 'notifications', 'read:user', 'user:email',
+]);
+
+/**
+ * The command that fixes a missing scope by hand.
+ * @param {string} host - forge host, e.g. `github.com` or an enterprise host
+ * @param {string[]} scopes
+ * @returns {string}
+ */
+export function forgeScopeRefreshCommand(host, scopes) {
+ return `gh auth refresh -h ${host} -s ${scopes.join(',')}`;
+}
+
const loggedNoAccess = new Set();
/**
diff --git a/server/lib/forgeAccessErrors.test.js b/server/lib/forgeAccessErrors.test.js
new file mode 100644
index 0000000000..d377900da5
--- /dev/null
+++ b/server/lib/forgeAccessErrors.test.js
@@ -0,0 +1,51 @@
+import { describe, it, expect } from 'vitest';
+import {
+ parseForgeMissingScopes,
+ forgeMissingScopesOf,
+ forgeScopeRefreshCommand,
+ REFRESHABLE_FORGE_SCOPES,
+} from './forgeAccessErrors.js';
+
+describe('parseForgeMissingScopes', () => {
+ it.each([
+ ['GraphQL workflow refusal', 'GraphQL: refusing to allow an OAuth App to create or update workflow `.github/workflows/admin.yml` without `workflow` scope (mergePullRequest)', ['workflow']],
+ ['REST needs-the-scope', 'This API operation needs the "gist" scope. (HTTP 404)', ['gist']],
+ ['gh preflight list', 'error: your authentication token is missing required scopes [workflow, read:org]', ['workflow', 'read:org']],
+ ['GraphQL one-of list', "The 'id' field requires one of the following scopes: ['read:org'], but your token has only been granted the: ['repo']", ['read:org']],
+ ])('reads %s', (_label, text, scopes) => {
+ expect(parseForgeMissingScopes(text)).toEqual(scopes);
+ });
+
+ // A permission grant on an App token is not a scope; refreshing cannot fix it.
+ it.each([
+ 'Resource not accessible by integration',
+ 'Could not resolve to a Repository with the name acme/widget',
+ 'Head commit changed',
+ '',
+ null,
+ ])('ignores %j', (text) => {
+ expect(parseForgeMissingScopes(text)).toEqual([]);
+ });
+
+ it('drops a captured name that is not a plausible scope', () => {
+ expect(parseForgeMissingScopes('missing required scopes [workflow; rm -rf /]')).toEqual([]);
+ });
+});
+
+describe('forgeMissingScopesOf', () => {
+ it('prefers the stamp execGh set and falls back to the message', () => {
+ expect(forgeMissingScopesOf({ ghMissingScopes: ['workflow'], message: 'x' })).toEqual(['workflow']);
+ expect(forgeMissingScopesOf(new Error('needs the "gist" scope'))).toEqual(['gist']);
+ expect(forgeMissingScopesOf(new Error('boom'))).toEqual([]);
+ });
+});
+
+describe('forgeScopeRefreshCommand', () => {
+ it('names the host and joins the scopes', () => {
+ expect(forgeScopeRefreshCommand('ghe.example.com', ['workflow', 'gist'])).toBe('gh auth refresh -h ghe.example.com -s workflow,gist');
+ });
+
+ it('never offers an admin-level scope for one-click refresh', () => {
+ expect(REFRESHABLE_FORGE_SCOPES.filter((scope) => scope.startsWith('admin:') || scope === 'delete_repo')).toEqual([]);
+ });
+});
diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.js
index 2bd779ad23..86e57aca09 100644
--- a/server/lib/hostControlRoutes.js
+++ b/server/lib/hostControlRoutes.js
@@ -454,6 +454,9 @@ export const HOST_CONTROL_ROUTES = Object.freeze([
'POST /api/apps/:id/pull-requests/:number/merge',
'POST /api/apps/:id/pull-requests/:number/review',
'POST /api/apps/:id/pull-requests/:number/do-review',
+ 'POST /api/apps/:id/forge-auth/refresh',
+ 'GET /api/apps/:id/forge-auth/refresh/:jobId/events',
+ 'POST /api/apps/:id/forge-auth/refresh/:jobId/cancel',
// Enable or queue CoS agent work against an app.
'POST /api/apps/:id/launch-videos',
'POST /api/apps/:id/launch-videos/publish',
diff --git a/server/routes/apps/forgeAuth.js b/server/routes/apps/forgeAuth.js
new file mode 100644
index 0000000000..ff314e6fe9
--- /dev/null
+++ b/server/routes/apps/forgeAuth.js
@@ -0,0 +1,70 @@
+/**
+ * Forge credential repair for a managed app.
+ *
+ * POST /:id/forge-auth/refresh → start `gh auth refresh` for the app's forge host
+ * GET /:id/forge-auth/refresh/:jobId/events → SSE: device-code → complete | error | canceled
+ * POST /:id/forge-auth/refresh/:jobId/cancel → stop it
+ *
+ * The host is always derived from the app's own origin, never taken from the
+ * request. All three are host-control routes (lib/hostControlRoutes.js): the
+ * device-code stream matters as much as the start — whoever approves a code
+ * decides which account the host's gh token belongs to.
+ */
+
+import { Router } from 'express';
+import { z } from 'zod';
+import { asyncHandler, ServerError } from '../../lib/errorHandler.js';
+import { validateRequest } from '../../lib/validation.js';
+import { resolveAppForgeTarget } from '../../lib/workTracker.js';
+import { resolveForgeForRepo } from '../../services/forgeAuth.js';
+import {
+ attachForgeScopeRefreshClient,
+ cancelForgeScopeRefresh,
+ hasForgeScopeRefresh,
+ startForgeScopeRefresh,
+} from '../../services/forgeScopeRefresh.js';
+import { loadApp } from './shared.js';
+
+const router = Router();
+
+const refreshBodySchema = z.object({
+ scopes: z.array(z.string().regex(/^[a-z][a-z0-9:_.-]*$/i)).min(1).max(8),
+});
+const jobParamsSchema = z.object({ id: z.string().min(1), jobId: z.string().uuid() });
+
+router.post('/:id/forge-auth/refresh', loadApp, asyncHandler(async (req, res) => {
+ const app = req.loadedApp;
+ const { scopes } = validateRequest(refreshBodySchema, req.body ?? {});
+
+ const { target } = await resolveAppForgeTarget(app);
+ if (!target || target.forge !== 'github') {
+ // glab keeps one token per host with no scope refresh; nothing to drive.
+ throw new ServerError('Only GitHub hosts can be refreshed from PortOS. For GitLab, update the token with glab auth login.', {
+ status: 409,
+ code: 'FORGE_REFRESH_UNSUPPORTED',
+ });
+ }
+ const host = target.webHost || target.apiHost;
+ 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 }).catch(() => null);
+
+ const job = await startForgeScopeRefresh({ host, scopes, expectedAccount: resolved?.account || null });
+ res.status(job.adopted ? 200 : 202).json(job);
+}));
+
+router.get('/:id/forge-auth/refresh/:jobId/events', asyncHandler(async (req, res) => {
+ const { jobId } = validateRequest(jobParamsSchema, req.params);
+ if (!hasForgeScopeRefresh(jobId) || !attachForgeScopeRefreshClient(jobId, res)) {
+ throw new ServerError('No such refresh in progress', { status: 404, code: 'NOT_FOUND' });
+ }
+}));
+
+router.post('/:id/forge-auth/refresh/:jobId/cancel', asyncHandler(async (req, res) => {
+ const { jobId } = validateRequest(jobParamsSchema, req.params);
+ res.json({ canceled: cancelForgeScopeRefresh(jobId) });
+}));
+
+export default router;
diff --git a/server/routes/apps/forgeAuth.test.js b/server/routes/apps/forgeAuth.test.js
new file mode 100644
index 0000000000..6834a2d8e6
--- /dev/null
+++ b/server/routes/apps/forgeAuth.test.js
@@ -0,0 +1,98 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../../lib/testHelper.js';
+import forgeAuthRoutes from './forgeAuth.js';
+
+vi.mock('../../services/apps.js', () => ({ getAppById: vi.fn() }));
+vi.mock('../../lib/workTracker.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ resolveAppForgeTarget: vi.fn(),
+}));
+vi.mock('../../services/forgeAuth.js', () => ({ resolveForgeForRepo: vi.fn() }));
+vi.mock('../../services/forgeScopeRefresh.js', () => ({
+ startForgeScopeRefresh: vi.fn(),
+ attachForgeScopeRefreshClient: vi.fn(),
+ cancelForgeScopeRefresh: vi.fn(),
+ hasForgeScopeRefresh: vi.fn(),
+}));
+
+import * as appsService from '../../services/apps.js';
+import { resolveAppForgeTarget } from '../../lib/workTracker.js';
+import { resolveForgeForRepo } from '../../services/forgeAuth.js';
+import { startForgeScopeRefresh, cancelForgeScopeRefresh, hasForgeScopeRefresh } from '../../services/forgeScopeRefresh.js';
+
+const APP = { id: 'app-001', name: 'Widget', repoPath: '/repo', forgeAccount: null };
+const JOB_ID = '11111111-1111-4111-8111-111111111111';
+
+describe('app forge-auth routes', () => {
+ let app;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ app = express();
+ app.use(express.json());
+ app.use('/api/apps', forgeAuthRoutes);
+ appsService.getAppById.mockResolvedValue(APP);
+ resolveAppForgeTarget.mockResolvedValue({
+ tracker: 'github',
+ target: { forge: 'github', repoSpec: 'ghe.example.com/acme/widget', webHost: 'ghe.example.com', apiHost: 'ghe.example.com' },
+ });
+ resolveForgeForRepo.mockResolvedValue({ account: null });
+ startForgeScopeRefresh.mockResolvedValue({ jobId: JOB_ID, host: 'ghe.example.com', scopes: ['workflow'], adopted: false });
+ });
+
+ it('starts the refresh for the host derived from the app origin, never from the request', async () => {
+ const response = await request(app).post('/api/apps/app-001/forge-auth/refresh')
+ .send({ scopes: ['workflow'], host: 'attacker.example.net' });
+
+ expect(response.status).toBe(202);
+ expect(response.body).toMatchObject({ jobId: JOB_ID, host: 'ghe.example.com' });
+ expect(startForgeScopeRefresh).toHaveBeenCalledWith({ host: 'ghe.example.com', scopes: ['workflow'], expectedAccount: null });
+ });
+
+ it('hands the account merges authenticate as to the service so a non-active account is caught', async () => {
+ resolveForgeForRepo.mockResolvedValue({ 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 GitLab, where glab has no scope refresh', async () => {
+ resolveAppForgeTarget.mockResolvedValue({ tracker: 'gitlab', target: { forge: 'gitlab', webHost: 'gitlab.example.com' } });
+
+ 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_UNSUPPORTED');
+ expect(startForgeScopeRefresh).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['no scopes', {}],
+ ['an empty list', { scopes: [] }],
+ ['a malformed scope', { scopes: ['workflow; rm -rf /'] }],
+ ])('rejects %s before touching gh', async (_label, body) => {
+ const response = await request(app).post('/api/apps/app-001/forge-auth/refresh').send(body);
+
+ expect(response.status).toBe(400);
+ expect(startForgeScopeRefresh).not.toHaveBeenCalled();
+ });
+
+ it('answers 404 for the event stream of a refresh that does not exist', async () => {
+ hasForgeScopeRefresh.mockReturnValue(false);
+
+ const response = await request(app).get(`/api/apps/app-001/forge-auth/refresh/${JOB_ID}/events`);
+
+ expect(response.status).toBe(404);
+ });
+
+ it('cancels a refresh by id', async () => {
+ cancelForgeScopeRefresh.mockReturnValue(true);
+
+ const response = await request(app).post(`/api/apps/app-001/forge-auth/refresh/${JOB_ID}/cancel`);
+
+ expect(response.body).toEqual({ canceled: true });
+ expect(cancelForgeScopeRefresh).toHaveBeenCalledWith(JOB_ID);
+ });
+});
diff --git a/server/routes/apps/index.js b/server/routes/apps/index.js
index 73b85aaa03..ead83e50f7 100644
--- a/server/routes/apps/index.js
+++ b/server/routes/apps/index.js
@@ -13,6 +13,7 @@
* taskTypes — per-app task-type overrides, work-tracker, layered-intelligence
* issues — open GitHub/GitLab issues for the Issues tab
* pullRequests — open GitHub/GitLab PRs/MRs and review-loop actions
+ * forgeAuth — repair a forge token's missing OAuth scope via `gh auth refresh`
* launch — open-editor, open-claude, open-folder, open-xcode
* documents — planning-doc read/list/commit
* agents — recent CoS agent history
@@ -36,6 +37,7 @@ import iconRoutes from './icons.js';
import taskTypeRoutes from './taskTypes.js';
import issueRoutes from './issues.js';
import pullRequestRoutes from './pullRequests.js';
+import forgeAuthRoutes from './forgeAuth.js';
import launchRoutes from './launch.js';
import launchVideoRoutes from './launchVideos.js';
import documentRoutes from './documents.js';
@@ -54,6 +56,7 @@ router.use(iconRoutes);
router.use(taskTypeRoutes);
router.use(issueRoutes);
router.use(pullRequestRoutes);
+router.use(forgeAuthRoutes);
router.use(launchRoutes);
router.use(launchVideoRoutes);
router.use(documentRoutes);
diff --git a/server/routes/apps/pullRequests.js b/server/routes/apps/pullRequests.js
index d24d011061..27d14a54da 100644
--- a/server/routes/apps/pullRequests.js
+++ b/server/routes/apps/pullRequests.js
@@ -44,6 +44,7 @@ import {
isDirectlyMergeablePullRequest,
mergeAppPullRequest,
} from '../../services/appPullRequestMerge.js';
+import { forgeScopeMissingError } from '../../services/forgeScopeRefresh.js';
import { isDoReviewTask, spawnPrDoReviewTask } from '../../services/prDoReviewTask.js';
import {
isReviewablePullRequest,
@@ -357,6 +358,7 @@ router.post('/:id/pull-requests/:number/merge', loadApp, asyncHandler(async (req
const merge = await mergeAppPullRequest(app, pullRequest, { method, deleteBranch });
if (!merge.ok) {
+ if (merge.code === 'missing-scope') throw forgeScopeMissingError(merge);
const refused = merge.code === 'method-not-allowed';
throw new ServerError(merge.error, {
// Only the forge failing the merge itself is a bad gateway; everything
diff --git a/server/routes/apps/pullRequests.test.js b/server/routes/apps/pullRequests.test.js
index 20cf7d7c9d..e8a2d57e1f 100644
--- a/server/routes/apps/pullRequests.test.js
+++ b/server/routes/apps/pullRequests.test.js
@@ -756,6 +756,27 @@ describe('app pull-request routes', () => {
expect(response.body.error).toContain('Squash merges are not allowed');
});
+ it('answers a missing token scope with a 403 carrying the host, scopes and the fix command', async () => {
+ mergeAppPullRequest.mockResolvedValue({
+ ok: false,
+ code: 'missing-scope',
+ error: 'GraphQL: refusing to allow an OAuth App to create or update workflow without `workflow` scope',
+ scopes: ['workflow'],
+ host: 'ghe.example.com',
+ });
+
+ const response = await request(app).post('/api/apps/app-001/pull-requests/17/merge').send({});
+
+ expect(response.status).toBe(403);
+ expect(response.body.code).toBe('FORGE_TOKEN_SCOPE_MISSING');
+ expect(response.body.context).toEqual({
+ host: 'ghe.example.com',
+ scopes: ['workflow'],
+ command: 'gh auth refresh -h ghe.example.com -s workflow',
+ refreshable: true,
+ });
+ });
+
it('rejects an unknown merge method before reaching the forge', async () => {
const response = await request(app).post('/api/apps/app-001/pull-requests/17/merge')
.send({ method: 'fast-forward' });
diff --git a/server/services/appPullRequestMerge.js b/server/services/appPullRequestMerge.js
index ea96853c90..af4eb28906 100644
--- a/server/services/appPullRequestMerge.js
+++ b/server/services/appPullRequestMerge.js
@@ -16,6 +16,7 @@ import { execGlab } from './gitlab.js';
import { resolveForgeExecOptions } from './forgeExecOptions.js';
import { resolveAppForgeTarget } from '../lib/workTracker.js';
import { PROTECTED_BRANCHES } from '../lib/gitArgs.js';
+import { forgeMissingScopesOf } from '../lib/forgeAccessErrors.js';
export const MERGE_METHODS = Object.freeze(['merge', 'squash', 'rebase']);
export const DEFAULT_MERGE_METHOD = 'merge';
@@ -58,11 +59,16 @@ const isLongLivedSourceBranch = (headBranch, baseBranch) => {
return !head || PROTECTED_BRANCHES.includes(head) || head === String(baseBranch || '').trim();
};
-const classifyFailure = detail => ({
- ok: false,
- code: METHOD_REFUSED.test(detail) ? 'method-not-allowed' : 'merge-failed',
- error: detail,
-});
+// A token missing an OAuth scope is neither a bad method nor a forge outage: the
+// merge would succeed once the credential is refreshed, so it gets its own code
+// (and the scopes) for the route to turn into a fix the user can act on.
+const classifyFailure = (detail, scopes = []) => (scopes.length > 0
+ ? { ok: false, code: 'missing-scope', error: detail, scopes }
+ : {
+ ok: false,
+ code: METHOD_REFUSED.test(detail) ? 'method-not-allowed' : 'merge-failed',
+ error: detail,
+ });
async function mergeGithubCore({ cwd, env, repoSpec, number, method, deleteBranch, timeoutMs, expectedHeadSha }) {
const args = ['pr', 'merge', String(number)];
@@ -78,7 +84,9 @@ async function mergeGithubCore({ cwd, env, repoSpec, number, method, deleteBranc
if (expectedHeadSha) args.push('--match-head-commit', expectedHeadSha);
const error = await execGh(args, timeoutMs, { cwd, env }).then(() => null, err => err);
- return error ? classifyFailure(error.ghStderr || error.message || 'gh pr merge failed') : { ok: true };
+ return error
+ ? classifyFailure(error.ghStderr || error.message || 'gh pr merge failed', forgeMissingScopesOf(error))
+ : { ok: true };
}
async function mergeGitlabCore({ cwd, env, number, method, deleteBranch, timeoutMs }) {
@@ -143,7 +151,7 @@ export async function runForgeMerge({ cwd, env, forge, repoSpec = null, number,
* @param {object} [options]
* @param {'merge'|'squash'|'rebase'} [options.method='merge']
* @param {boolean} [options.deleteBranch=false] - delete the source branch, unless it is long-lived
- * @returns {Promise<{ok:boolean, code?:string, error?:string, method?:string, deletedBranch?:boolean}>}
+ * @returns {Promise<{ok:boolean, code?:string, error?:string, scopes?:string[], host?:string|null, method?:string, deletedBranch?:boolean}>}
*/
export async function mergeAppPullRequest(app, pullRequest, { method = DEFAULT_MERGE_METHOD, deleteBranch = false } = {}) {
if (!MERGE_METHODS.includes(method)) {
@@ -175,7 +183,9 @@ export async function mergeAppPullRequest(app, pullRequest, { method = DEFAULT_M
expectedHeadSha: target.forge === 'github' ? pullRequest.headSha ?? '' : null,
timeoutMs: MERGE_TIMEOUT_MS,
});
- if (!result.ok) return result;
+ // The host rides along on a missing-scope failure so the route can name the
+ // forge the token must be refreshed for (an enterprise host, not github.com).
+ if (!result.ok) return result.code === 'missing-scope' ? { ...result, host: target.webHost || target.apiHost || null } : result;
console.log(`🔀 Merged ${target.forge === 'gitlab' ? 'MR' : 'PR'} #${pullRequest.number} for app ${app.id} via ${method}${deleting ? ' (source branch deleted)' : ''}`);
return { ok: true, method, deletedBranch: deleting };
diff --git a/server/services/appPullRequestMerge.test.js b/server/services/appPullRequestMerge.test.js
index c3432c6b25..ad249cac7d 100644
--- a/server/services/appPullRequestMerge.test.js
+++ b/server/services/appPullRequestMerge.test.js
@@ -92,6 +92,25 @@ describe('mergeAppPullRequest', () => {
expect(result).toMatchObject({ ok: false, code: 'merge-failed' });
});
+ // Enterprise hosts are the common case for this failure: the host must come
+ // from the app's own forge target, not default to github.com.
+ it('reports a token missing an OAuth scope with the scopes and the forge host', async () => {
+ resolveAppForgeTarget.mockResolvedValue({
+ tracker: 'github',
+ target: { forge: 'github', fullName: 'acme/widget', repoSpec: 'ghe.example.com/acme/widget', apiHost: 'ghe.example.com', webHost: 'ghe.example.com' },
+ });
+ const workflowRefusal = 'GraphQL: refusing to allow an OAuth App to create or update workflow `.github/workflows/admin.yml` without `workflow` scope (mergePullRequest)';
+ execGh.mockRejectedValue(Object.assign(new Error(workflowRefusal), { ghStderr: workflowRefusal }));
+
+ expect(await mergeAppPullRequest(APP, PR)).toMatchObject({
+ ok: false,
+ code: 'missing-scope',
+ scopes: ['workflow'],
+ host: 'ghe.example.com',
+ error: workflowRefusal,
+ });
+ });
+
it('merges a GitLab request immediately instead of waiting on its pipeline', async () => {
resolveAppForgeTarget.mockResolvedValue({
tracker: 'gitlab',
diff --git a/server/services/forgeScopeRefresh.js b/server/services/forgeScopeRefresh.js
new file mode 100644
index 0000000000..d634b8cc0c
--- /dev/null
+++ b/server/services/forgeScopeRefresh.js
@@ -0,0 +1,217 @@
+/**
+ * Drive `gh auth refresh -h <host> -s <scopes>` for the Pull Requests tab, so a
+ * token that lacks an OAuth scope can be fixed from the UI instead of a terminal.
+ *
+ * `gh` needs no TTY for this: with piped stdio it prints the one-time code and
+ * the device URL on stderr and then waits for the user to approve in a browser.
+ * The user is usually NOT on this host (the tailnet), so the browser launch is
+ * disabled and the code + URL travel to the UI as an SSE frame instead.
+ *
+ * Frames (per job, `broadcastSse`): `device-code` {code,url} → `complete` |
+ * `error` {error} | `canceled`. The device-code frame is retained, so a client
+ * that attaches late (a reload mid-flow) still sees what to enter.
+ *
+ * One refresh per host at a time: a second request for the same host adopts the
+ * running job rather than starting another device flow.
+ *
+ * `gh auth refresh` has no account flag — it refreshes the host's ACTIVE login.
+ * When the merge ran as a different owner-matched account, refreshing the active
+ * one would leave the merge failing, so that mismatch refuses up front.
+ */
+
+import { spawn } from 'child_process';
+import { randomUUID } from 'crypto';
+import { execGh } from './github.js';
+import { REFRESHABLE_FORGE_SCOPES, forgeScopeRefreshCommand, isForgePersonalTokenRefusal } from '../lib/forgeAccessErrors.js';
+import { ServerError } from '../lib/errorHandler.js';
+import { attachSseClient, broadcastSse, closeJobAfterDelay } from '../lib/sseUtils.js';
+
+// GitHub's device codes live 15 minutes; past that the flow cannot succeed.
+export const FORGE_REFRESH_TIMEOUT_MS = 15 * 60 * 1000;
+const ACTIVE_USER_TIMEOUT_MS = 15_000;
+
+const DEVICE_CODE_RE = /one-time code:\s*([A-Z0-9]{4}-[A-Z0-9]{4})/i;
+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
+// 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;
+ return names.find((name) => process.env[name]) || null;
+};
+
+const jobs = new Map();
+const jobIdByHost = new Map();
+
+// An env token takes precedence over the keyring and `gh auth refresh` refuses to
+// touch it, so the refresh must run against the keyring login alone.
+const refreshEnv = () => {
+ const env = { ...process.env, GH_BROWSER: 'true', BROWSER: 'true', GH_PROMPT_DISABLED: '1' };
+ for (const key of TOKEN_ENV_KEYS) delete env[key];
+ return env;
+};
+
+const finish = (job, frame) => {
+ if (job.settled) return;
+ job.settled = true;
+ clearTimeout(job.timer);
+ if (jobIdByHost.get(job.host) === job.id) jobIdByHost.delete(job.host);
+ broadcastSse(job, frame);
+ closeJobAfterDelay(jobs, job.id, undefined, job);
+};
+
+const lastLine = (text) => text.trim().split('\n').filter(Boolean).pop() || '';
+
+function spawnRefresh(job) {
+ const child = spawn('gh', ['auth', 'refresh', '-h', job.host, '-s', job.scopes.join(',')], {
+ shell: false,
+ env: refreshEnv(),
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ // Terminal listeners go on in this same tick: a failed spawn reports on the
+ // next tick, and an unlistened `error` would take the server down.
+ job.child = child;
+ let stderr = '';
+ child.stderr.on('data', (chunk) => {
+ stderr += chunk.toString();
+ if (job.deviceCode) return;
+ const code = DEVICE_CODE_RE.exec(stderr)?.[1];
+ const url = DEVICE_URL_RE.exec(stderr)?.[1];
+ if (!code || !url) return;
+ job.deviceCode = { code, url };
+ console.log(`🔑 Forge scope refresh for ${job.host} is waiting for browser approval`);
+ broadcastSse(job, { type: 'device-code', host: job.host, scopes: job.scopes, code, url });
+ });
+ child.stdout.on('data', () => {});
+ child.on('error', (err) => {
+ console.error(`❌ Forge scope refresh could not start gh: ${err.message}`);
+ finish(job, { type: 'error', error: `Could not run gh: ${err.message}` });
+ });
+ child.on('close', (code) => {
+ if (job.canceled) return finish(job, { type: 'canceled' });
+ if (code === 0) {
+ console.log(`✅ Forge scope refresh for ${job.host} granted ${job.scopes.join(',')}`);
+ return finish(job, { type: 'complete', host: job.host, scopes: job.scopes });
+ }
+ // The user declining in the browser or a restricted OAuth app is an expected
+ // outcome, not a defect: stdout, not stderr.
+ console.log(`🚫 Forge scope refresh for ${job.host} ended with code ${code}`);
+ finish(job, { type: 'error', error: lastLine(stderr) || `gh auth refresh exited with code ${code}` });
+ });
+ job.timer = setTimeout(() => {
+ job.timedOut = true;
+ try { child.kill('SIGTERM'); } catch (err) { console.error(`❌ Forge scope refresh: failed to stop timed-out gh: ${err.message}`); }
+ finish(job, { type: 'error', error: 'The one-time code expired before it was approved. Start the refresh again.' });
+ }, FORGE_REFRESH_TIMEOUT_MS);
+ job.timer.unref?.();
+}
+
+async function activeLogin(host) {
+ const env = refreshEnv();
+ return execGh(['api', 'user', '--hostname', host, '--jq', '.login'], ACTIVE_USER_TIMEOUT_MS, { env })
+ .catch(() => null);
+}
+
+/**
+ * Start (or adopt) the scope refresh for `host`.
+ *
+ * @param {object} options
+ * @param {string} options.host - forge host derived from the app's origin, never client-supplied
+ * @param {string[]} options.scopes - must all be in `REFRESHABLE_FORGE_SCOPES`
+ * @param {string|null} [options.expectedAccount] - login the merge actually authenticates as, when known
+ * @returns {Promise<{jobId: string, host: string, scopes: string[], adopted: boolean}>}
+ */
+export async function startForgeScopeRefresh({ host, scopes, expectedAccount = null }) {
+ const refused = scopes.filter((scope) => !REFRESHABLE_FORGE_SCOPES.includes(scope));
+ if (refused.length > 0) {
+ throw new ServerError(`PortOS will not request the ${refused.join(', ')} scope. Run the gh command in a terminal instead.`, {
+ status: 400,
+ code: 'FORGE_SCOPE_NOT_REFRESHABLE',
+ });
+ }
+
+ const envToken = envTokenFor(host, expectedAccount);
+ if (envToken) {
+ throw new ServerError(
+ `The ${host} credential PortOS uses comes from the ${envToken} environment variable, which gh auth refresh cannot re-scope. Reissue that token with the ${scopes.join(', ')} scope instead.`,
+ { status: 409, code: 'FORGE_TOKEN_FROM_ENV', context: { host, variable: envToken } },
+ );
+ }
+
+ const running = jobs.get(jobIdByHost.get(host));
+ if (running && !running.settled) return { jobId: running.id, host, scopes: running.scopes, adopted: true };
+
+ // Reserve the host before the first await so two requests cannot both start a flow.
+ const job = { id: randomUUID(), host, scopes, clients: [], lastPayload: null, settled: false, canceled: false, child: null, timer: null, deviceCode: null };
+ jobs.set(job.id, job);
+ jobIdByHost.set(host, job.id);
+
+ const active = expectedAccount ? await activeLogin(host) : null;
+ if (expectedAccount && active && active.toLowerCase() !== expectedAccount.toLowerCase()) {
+ jobs.delete(job.id);
+ if (jobIdByHost.get(host) === job.id) jobIdByHost.delete(host);
+ throw new ServerError(
+ `PortOS merges as ${expectedAccount} on ${host}, but gh's active account there is ${active}, and gh can only refresh the active one. `
+ + `Run gh auth switch -h ${host} -u ${expectedAccount}, then try again.`,
+ { status: 409, code: 'FORGE_ACCOUNT_NOT_ACTIVE', context: { host, expectedAccount, active } },
+ );
+ }
+ // Cancelled while the account check was in flight: never spawn.
+ if (job.canceled) {
+ finish(job, { type: 'canceled' });
+ return { jobId: job.id, host, scopes, adopted: false };
+ }
+
+ spawnRefresh(job);
+ return { jobId: job.id, host, scopes, adopted: false };
+}
+
+/** Attach an SSE response to a refresh job. False when no such job exists. */
+export const attachForgeScopeRefreshClient = (jobId, res) => attachSseClient(jobs, jobId, res);
+
+/** Whether a refresh job exists (running, or inside its post-terminal replay window). */
+export const hasForgeScopeRefresh = (jobId) => jobs.has(jobId);
+
+/** Stop a refresh. Idempotent; false when the job is unknown or already finished. */
+export function cancelForgeScopeRefresh(jobId) {
+ const job = jobs.get(jobId);
+ if (!job || job.settled) return false;
+ job.canceled = true;
+ if (!job.child) return true;
+ try {
+ job.child.kill('SIGTERM');
+ } catch (err) {
+ console.error(`❌ Forge scope refresh: failed to stop gh: ${err.message}`);
+ finish(job, { type: 'canceled' });
+ }
+ return true;
+}
+
+/**
+ * The one error a route throws when a forge call failed on a missing OAuth scope.
+ * Carries the hand-run command AND whether PortOS can drive the refresh itself,
+ * so the client never has to re-derive either.
+ *
+ * @param {{host: string|null, scopes: string[], error: string}} failure
+ * @returns {ServerError}
+ */
+export function forgeScopeMissingError({ host, scopes, error }) {
+ const forgeHost = host || 'github.com';
+ // A PAT cannot be re-scoped by `gh auth refresh`: offering it would "succeed"
+ // on the keyring and leave the failing credential untouched, forever.
+ const personalToken = isForgePersonalTokenRefusal(error);
+ return new ServerError(error, {
+ status: 403,
+ code: 'FORGE_TOKEN_SCOPE_MISSING',
+ context: {
+ host: forgeHost,
+ scopes,
+ command: personalToken ? null : forgeScopeRefreshCommand(forgeHost, scopes),
+ credential: personalToken ? 'personal-access-token' : 'oauth',
+ refreshable: !personalToken && scopes.every((scope) => REFRESHABLE_FORGE_SCOPES.includes(scope)),
+ },
+ });
+}
diff --git a/server/services/forgeScopeRefresh.test.js b/server/services/forgeScopeRefresh.test.js
new file mode 100644
index 0000000000..235fe5bcac
--- /dev/null
+++ b/server/services/forgeScopeRefresh.test.js
@@ -0,0 +1,188 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { EventEmitter } from 'events';
+
+const spawnMock = vi.fn();
+vi.mock('child_process', () => ({ spawn: (...args) => spawnMock(...args) }));
+vi.mock('./github.js', () => ({ execGh: vi.fn() }));
+
+import { execGh } from './github.js';
+import {
+ startForgeScopeRefresh,
+ attachForgeScopeRefreshClient,
+ cancelForgeScopeRefresh,
+ forgeScopeMissingError,
+ FORGE_REFRESH_TIMEOUT_MS,
+} from './forgeScopeRefresh.js';
+
+const DEVICE_PROMPT = '\n! First copy your one-time code: ABCD-1234\nOpen this URL to continue in your web browser: https://ghe.example.com/login/device\n';
+
+const fakeChild = () => {
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ child.kill = vi.fn(() => { setImmediate(() => child.emit('close', null)); return true; });
+ return child;
+};
+
+// An SSE response double: every frame the job broadcasts, parsed.
+const attachFrames = (jobId) => {
+ const frames = [];
+ const res = { writeHead: vi.fn(), write: (msg) => frames.push(JSON.parse(msg.replace(/^data: /, ''))), end: vi.fn(), req: { on: vi.fn() } };
+ expect(attachForgeScopeRefreshClient(jobId, res)).toBe(true);
+ return frames;
+};
+
+let child;
+// Settle a job so the per-host slot frees between tests.
+const settle = async (jobId) => { cancelForgeScopeRefresh(jobId); await vi.advanceTimersByTimeAsync(10); };
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ child = fakeChild();
+ spawnMock.mockReset().mockReturnValue(child);
+ execGh.mockReset();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe('startForgeScopeRefresh', () => {
+ it('runs gh against the host with no env token and publishes the device code, then completes', async () => {
+ process.env.GH_TOKEN = 'ambient-token';
+ const { jobId, adopted } = await startForgeScopeRefresh({ host: 'ghe.example.com', scopes: ['workflow'] });
+ delete process.env.GH_TOKEN;
+ const frames = attachFrames(jobId);
+
+ const [cmd, args, options] = spawnMock.mock.calls[0];
+ expect([cmd, args]).toEqual(['gh', ['auth', 'refresh', '-h', 'ghe.example.com', '-s', 'workflow']]);
+ // An env token outranks the keyring and gh refuses to refresh it.
+ expect(options.env.GH_TOKEN).toBeUndefined();
+ expect(options.shell).toBe(false);
+ expect(adopted).toBe(false);
+
+ child.stderr.emit('data', Buffer.from(DEVICE_PROMPT));
+ expect(frames).toEqual([{ type: 'device-code', host: 'ghe.example.com', scopes: ['workflow'], code: 'ABCD-1234', url: 'https://ghe.example.com/login/device' }]);
+
+ child.emit('close', 0);
+ expect(frames.at(-1)).toEqual({ type: 'complete', host: 'ghe.example.com', scopes: ['workflow'] });
+ });
+
+ it('replays the device code to a client that attaches after it was printed', async () => {
+ const { jobId } = await startForgeScopeRefresh({ host: 'ghe.example.com', scopes: ['workflow'] });
+ child.stderr.emit('data', Buffer.from(DEVICE_PROMPT));
+
+ expect(attachFrames(jobId)).toEqual([expect.objectContaining({ type: 'device-code', code: 'ABCD-1234' })]);
+ await settle(jobId);
+ });
+
+ it('reports gh failing (user declined, restricted OAuth app) as an error frame', async () => {
+ const { jobId } = await startForgeScopeRefresh({ host: 'ghe.example.com', scopes: ['workflow'] });
+ const frames = attachFrames(jobId);
+
+ child.stderr.emit('data', Buffer.from('X Authentication failed: access_denied\n'));
+ child.emit('close', 1);
+
+ expect(frames.at(-1)).toEqual({ type: 'error', error: 'X Authentication failed: access_denied' });
+ });
+
+ it('reports a gh that cannot start as an error frame, not a crash', async () => {
+ const { jobId } = await startForgeScopeRefresh({ host: 'ghe.example.com', scopes: ['workflow'] });
+ const frames = attachFrames(jobId);
+
+ child.emit('error', new Error('spawn gh ENOENT'));
+
+ expect(frames.at(-1)).toMatchObject({ type: 'error', error: expect.stringContaining('ENOENT') });
+ });
+
+ it('cancel stops gh and ends the stream with a canceled frame', async () => {
+ const { jobId } = await startForgeScopeRefresh({ host: 'ghe.example.com', scopes: ['workflow'] });
+ const frames = attachFrames(jobId);
+
+ expect(cancelForgeScopeRefresh(jobId)).toBe(true);
+ await vi.advanceTimersByTimeAsync(10);
+
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');
+ expect(frames.at(-1)).toEqual({ type: 'canceled' });
+ expect(cancelForgeScopeRefresh(jobId)).toBe(false);
+ });
+
+ it('gives up when the one-time code expires unapproved', async () => {
+ const { jobId } = await startForgeScopeRefresh({ host: 'ghe.example.com', scopes: ['workflow'] });
+ const frames = attachFrames(jobId);
+
+ await vi.advanceTimersByTimeAsync(FORGE_REFRESH_TIMEOUT_MS + 1);
+
+ expect(child.kill).toHaveBeenCalled();
+ expect(frames.at(-1)).toMatchObject({ type: 'error', error: expect.stringContaining('expired') });
+ });
+
+ it('adopts the running refresh for a host instead of starting a second device flow', async () => {
+ const first = await startForgeScopeRefresh({ host: 'ghe.example.com', scopes: ['workflow'] });
+ const second = await startForgeScopeRefresh({ host: 'ghe.example.com', scopes: ['workflow'] });
+
+ expect(second).toMatchObject({ jobId: first.jobId, adopted: true });
+ expect(spawnMock).toHaveBeenCalledTimes(1);
+ await settle(first.jobId);
+ });
+
+ it('refuses a scope outside the closed set before spawning anything', async () => {
+ await expect(startForgeScopeRefresh({ host: 'ghe.example.com', scopes: ['admin:org'] }))
+ .rejects.toMatchObject({ status: 400, code: 'FORGE_SCOPE_NOT_REFRESHABLE' });
+ expect(spawnMock).not.toHaveBeenCalled();
+ });
+
+ // `gh auth refresh` re-scopes the keyring only; an env token outranks it, so a
+ // "successful" refresh would leave the failing credential untouched.
+ it('refuses when the credential in use comes from an environment token', async () => {
+ process.env.GH_ENTERPRISE_TOKEN = 'ambient-token';
+ try {
+ await expect(startForgeScopeRefresh({ host: 'ghe.example.com', scopes: ['workflow'] }))
+ .rejects.toMatchObject({ status: 409, code: 'FORGE_TOKEN_FROM_ENV', context: { variable: 'GH_ENTERPRISE_TOKEN' } });
+ } finally {
+ delete process.env.GH_ENTERPRISE_TOKEN;
+ }
+ expect(spawnMock).not.toHaveBeenCalled();
+ });
+
+ // gh refreshes only the host's ACTIVE login; refreshing it would leave a merge
+ // that runs as another account failing with the same error.
+ it('refuses when the account merges run as is not the host\'s active gh account', async () => {
+ execGh.mockResolvedValue('someone-else');
+
+ await expect(startForgeScopeRefresh({ host: 'github.com', scopes: ['workflow'], expectedAccount: 'owner-acct' }))
+ .rejects.toMatchObject({ status: 409, code: 'FORGE_ACCOUNT_NOT_ACTIVE' });
+ expect(spawnMock).not.toHaveBeenCalled();
+
+ // The reservation is released, so the user can switch and retry at once.
+ execGh.mockResolvedValue('owner-acct');
+ const { jobId } = await startForgeScopeRefresh({ host: 'github.com', scopes: ['workflow'], expectedAccount: 'owner-acct' });
+ expect(spawnMock).toHaveBeenCalledTimes(1);
+ await settle(jobId);
+ });
+});
+
+describe('forgeScopeMissingError', () => {
+ it('does not offer a refresh, or a command, for a personal access token', () => {
+ const error = forgeScopeMissingError({
+ host: 'ghe.example.com',
+ scopes: ['workflow'],
+ error: 'refusing to allow a Personal Access Token to create or update workflow without `workflow` scope',
+ });
+
+ expect(error.context).toMatchObject({ credential: 'personal-access-token', refreshable: false, command: null });
+ });
+
+ it('marks a scope PortOS will not request as not refreshable, but still gives the command', () => {
+ const error = forgeScopeMissingError({ host: null, scopes: ['admin:org'], error: 'needs the "admin:org" scope' });
+
+ expect(error.status).toBe(403);
+ expect(error.context).toEqual({
+ host: 'github.com',
+ scopes: ['admin:org'],
+ command: 'gh auth refresh -h github.com -s admin:org',
+ credential: 'oauth',
+ refreshable: false,
+ });
+ });
+});
diff --git a/server/services/github.js b/server/services/github.js
index 72a84b3472..58e4b83bc5 100644
--- a/server/services/github.js
+++ b/server/services/github.js
@@ -8,7 +8,7 @@ import { ServerError } from '../lib/errorHandler.js';
import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
import { createMutex } from '../lib/asyncMutex.js';
import { dispatchHintFromLabels } from '../lib/dispatchLabels.js';
-import { isForgeNoAccessMessage } from '../lib/forgeAccessErrors.js';
+import { isForgeNoAccessMessage, parseForgeMissingScopes } from '../lib/forgeAccessErrors.js';
const DATA_DIR = PATHS.data;
const REPOS_FILE = join(DATA_DIR, 'github-repos.json');
@@ -180,11 +180,15 @@ export function execGh(args, timeoutMs = DEFAULT_EXEC_GH_TIMEOUT_MS, { cwd = nul
// never clear. `settle(null)` preserves whatever backoff a genuinely
// transient failure already recorded. See lib/forgeAccessErrors.js.
const noAccess = isForgeNoAccessMessage(detail);
- settle(noAccess ? null : false);
+ // A missing OAuth scope is permanent until the token is refreshed, the
+ // same as no-access: retrying cannot clear it, so it stays out of backoff.
+ const missingScopes = parseForgeMissingScopes(detail);
+ settle(noAccess || missingScopes.length > 0 ? null : false);
const error = new Error(detail || `gh exited with ${signal ? `signal ${signal}` : `code ${code}`}`);
error.ghExitCode = code;
error.ghStderr = detail;
if (noAccess) error.ghNoAccess = true;
+ if (missingScopes.length > 0) error.ghMissingScopes = missingScopes;
reject(error);
} else {
settle(true);
diff --git a/server/services/managedAppRepositories.js b/server/services/managedAppRepositories.js
index 1d045a9ac7..425089f46b 100644
--- a/server/services/managedAppRepositories.js
+++ b/server/services/managedAppRepositories.js
@@ -5,6 +5,8 @@ import { getOriginInfo, parseGitRemoteUrl, readRemoteUrl } from '../lib/gitRemot
import { githubApiHost, hostToWorkTracker, isGithubHost } from '../lib/workTracker.js';
import { execGitSafe, fetchOrigin, isFetchFresh, resolveForgeForRepo } from './git.js';
import { execGh } from './github.js';
+import { forgeMissingScopesOf } from '../lib/forgeAccessErrors.js';
+import { forgeScopeMissingError } from './forgeScopeRefresh.js';
const GH_TIMEOUT_MS = 60_000;
@@ -340,6 +342,12 @@ export async function syncManagedAppFork(app) {
cwd: app.repoPath,
env: { ...(forge?.env || process.env), GH_HOST: githubApiHost(origin.host) },
}).catch((error) => {
+ // Syncing upstream commits that touch `.github/workflows/` needs the token's
+ // `workflow` scope: a credential fix, not a failed sync.
+ const missingScopes = forgeMissingScopesOf(error);
+ if (missingScopes.length > 0) {
+ throw forgeScopeMissingError({ host: githubApiHost(origin.host), scopes: missingScopes, error: error.message });
+ }
if (/fast forward|diverge|non-fast/i.test(error.message || '')) {
throw new ServerError(
`The ${origin.fullName} fork has commits that cannot be fast-forwarded from ${upstream.fullName}. Reconcile those commits on GitHub before syncing.`,
diff --git a/server/services/managedAppRepositories.test.js b/server/services/managedAppRepositories.test.js
index e92c6e3b25..a0ad5791f9 100644
--- a/server/services/managedAppRepositories.test.js
+++ b/server/services/managedAppRepositories.test.js
@@ -254,6 +254,21 @@ describe('managed app repository topology', () => {
expect(result).toMatchObject({ fullName: 'example-owner/example-app', source: 'example-org/example-app' });
});
+ it('reports a fork sync refused for a missing token scope as a credential fix, not a failed sync', async () => {
+ const refusal = 'GraphQL: refusing to allow an OAuth App to create or update workflow `.github/workflows/ci.yml` without `workflow` scope';
+ const topologyImpl = mock.execGh.getMockImplementation();
+ mock.execGh.mockImplementation(async (args, ...rest) => {
+ if (args[0] === 'repo' && args[1] === 'sync') throw Object.assign(new Error(refusal), { ghStderr: refusal });
+ return topologyImpl ? topologyImpl(args, ...rest) : '';
+ });
+
+ await expect(syncManagedAppFork(app)).rejects.toMatchObject({
+ status: 403,
+ code: 'FORGE_TOKEN_SCOPE_MISSING',
+ context: { host: 'github.com', scopes: ['workflow'], command: 'gh auth refresh -h github.com -s workflow' },
+ });
+ });
+
it('uses an explicit upstream remote when forge metadata is unavailable', async () => {
mock.execGh.mockResolvedValue(null);
mock.readRemoteUrl.mockResolvedValue('[email protected]:example-org/example-app.git');