Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

PRD-8069: honor the user's declared GitHub account for git auth (#3754)

miles-kt-inkeep76074eb9be96
diff --git a/.changeset/git-declared-account-identity.md b/.changeset/git-declared-account-identity.md
new file mode 100644
index 000000000..bb5bcffe3
--- /dev/null
+++ b/.changeset/git-declared-account-identity.md
@@ -0,0 +1,9 @@
+---
+"@inkeep/open-knowledge": minor
+---
+
+Git operations now honor the GitHub account you've already declared for a repo, instead of always using whichever GitHub CLI account happens to be active. If the remote URL carries a username (`https://[email protected]/owner/repo`) or your git config has a `credential.<url>.username` entry (HTTPS remotes only), sync pushes, push-permission checks, and `ok clone` all authenticate as that account — read from standard git mechanisms, in the same order git itself resolves them, with no new OpenKnowledge configuration. Multiple accounts on one machine are a GitHub CLI feature, so this needs each account signed in with `gh auth login` (GitHub CLI 2.40 or newer); OpenKnowledge's own GitHub connection stores one account per host, so a declaration changes the error messages you see but not which credentials get used unless the account is also signed in to the GitHub CLI. If the declared account isn't signed in there, OpenKnowledge falls back to the credentials it does have rather than losing them, and picks up a later `gh auth login` fix within a sync cycle or two.
+
+Error messages now tell the truth about identity: access-denied messages end with the account that was actually used ("Authenticated as bob."), a missed declaration is named ("Your remote URL names alice, but that account's credentials couldn't be used."), and "repository not found" failures no longer offer sign-in as the fix — the repo may not exist, or the account used may not be able to see it, and neither git nor GitHub reveals which.
+
+**Behavior change for remotes that embed a username.** A remote like `https://[email protected]/owner/repo` is now recognized as a GitHub origin, so OpenKnowledge's own credential flow takes precedence over ambient system credential helpers for it — as it always has for other GitHub remotes. If such a remote's only working credential lived in Git Credential Manager or your OS keychain, sync will report you as signed out after upgrading: connect GitHub in OpenKnowledge once (or sign in to the GitHub CLI) and it resumes. Two smaller effects of the same recognition: public repos with these URLs clone anonymously without requiring sign-in, and receiving a shared folder accepts them instead of asking you to switch the remote.
diff --git a/docs/content/features/github-sync.mdx b/docs/content/features/github-sync.mdx
index 09f3648d6..4945c3bae 100644
--- a/docs/content/features/github-sync.mdx
+++ b/docs/content/features/github-sync.mdx
@@ -65,7 +65,7 @@ This will open a dialog where you can choose an owner and repository name. You c
## Enable GitHub sync
-When you open a freshly cloned project, you will be prompted to enable sync. If you have full access to the repository, you will be prompted to enable **Full** sync. If you have read only access, you will be prompted to enable **Follow** sync. You can change the sync mode from the sync popover (the <Cloud role="img" aria-label="Sync" className="inline size-4 align-text-bottom" /> icon) or from **Settings → Sync** at any time.
+When you open a freshly cloned project, you will be prompted to enable sync. If you have full access to the repository, you will be prompted to enable **Full** sync. If you have read-only access, you will be prompted to enable **Follow** sync. You can change the sync mode from the sync popover (the <Cloud role="img" aria-label="Sync" className="inline size-4 align-text-bottom" /> icon) or from **Settings → Sync** at any time.
If you want to set a default sync setting for future collaborators, go to the project settings page and navigate to the **Sync** → **Shared default** section. This writes [`autoSync.default`](/docs/reference/configuration) — one of `off`, `follow`, or `full` — to the project's committed `.ok/config.yml`, pre-answering the enable-sync prompt for everyone who clones the repo; each machine's own auto-sync choice overrides it.
@@ -98,7 +98,19 @@ Manage the connection from **Settings → Account**. **Connect GitHub** authoriz
When a project's `origin` remote points at a GitHub Enterprise Server host, OpenKnowledge resolves credentials and identity for that host automatically: the account shown in settings, the sync token, the push-permission check, and the `ok auth` default `--host` all follow the workspace's remote instead of assuming github.com. Share links work with enterprise remotes too — a recipient opening a GHES share is asked to confirm the server unless they are already signed in to it.
-The sync status indicator surfaces an auth-error state when stored credentials stop working, and sync pauses until you reconnect.
+### Which GitHub account is used
+
+If you are signed into multiple accounts with the GitHub CLI, OpenKnowledge will use the account that is active by default. If you want to set a specific account for a project, you can do so by adding a username to the remote URL or a `credential.<url>.username` entry to your [Git configuration](https://github.com/git-ecosystem/git-credential-manager/blob/main/docs/multiple-users.md).
+
+OpenKnowledge will choose the GitHub credential to use for a project in the following order of priority:
+
+| Priority | Declaration | Where it lives | How to set it |
+| --- | --- | --- | --- |
+| 1 | A username in the remote URL — `https://[email protected]/owner/repo` | that clone's `.git/config` | `git remote set-url origin https://[email protected]/owner/repo.git` |
+| 2 | A `credential.<url>.username` entry | git config, any scope | `git config --global credential.https://github.com.username alice` |
+| 3 | Neither | the GitHub CLI's active account, or the account connected in OpenKnowledge | — |
+
+The username entries above apply to HTTPS remotes only. SSH projects follow the GitHub CLI's active account (switch it with `gh auth switch`), and that account decides only which identity the push-permission check runs as — the push itself authenticates with your SSH key, chosen by your SSH configuration. To pin an SSH project to a declared account, switch it to an HTTPS remote.
## Sync status and conflicts
@@ -129,7 +141,7 @@ A few situations stop sync from completing successfully. In each case the sync s
### Project isn't on a normal branch
- **The project is parked on a specific commit, not a branch.** This usually means someone checked out an older commit from the terminal to look around. There's no branch to push to, so sync pauses. Switch back to your normal branch (`main`, your working branch, whichever) and sync resumes.
-- **Diverged history.** When the remote has been rewritten (force-push, rebase, branch reset) in a way OpenKnowledge can't reconcile automatically, sync stops and shows the error. This one usually needs a fix from the command line. Ask whoever rewrote the history, or restore from the [Timeline](/docs/features/timeline-and-recovery).
+- **Diverged history.** When the remote has been rewritten (force-push, rebase, branch reset) in a way OpenKnowledge can't reconcile automatically, sync stops and shows the error. This one usually needs a fix from the command line. Ask whoever rewrote the history for help, or restore from the [Timeline](/docs/features/timeline-and-recovery).
### GitHub-side blockers
diff --git a/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx b/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx
index 34831e445..703ec922c 100644
--- a/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx
+++ b/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx
@@ -1201,6 +1201,37 @@ describe('ShareBranchSwitchDialog — worktree leg', () => {
expect(calls.open).not.toHaveBeenCalled();
});
+ // The repository-not-found masquerade rides the fetch-failed reason with
+ // its own flag: the remote ANSWERED, so the connection copy is wrong, and
+ // the repo may not exist or the account used may not see it. The surface
+ // must render the not-found copy — a transposition of the two boolean-ish
+ // flags (or dropped threading) would silently fall back to the network
+ // dead end this arm exists to avoid.
+ test('a not-found fetch failure shows the not-found copy, not the connection toast', async () => {
+ const store = createShareReceiveStore();
+ const { bridge } = makeBridge({
+ checkout: vi.fn(async () => ({
+ ok: false as const,
+ reason: 'fetch-failed' as const,
+ notFoundAsIdentity: true as const,
+ })),
+ });
+ renderDialog(bridge, store);
+
+ const worktreeBtn = await findEnabledWorktreeButton();
+ await act(async () => {
+ fireEvent.click(worktreeBtn);
+ await Promise.resolve();
+ });
+
+ await waitFor(() => {
+ expect(toastError).toHaveBeenCalledWith(
+ 'Repository not found — it may not exist, or the account used may not have access.',
+ );
+ });
+ expect(toastError).not.toHaveBeenCalledWith('Could not fetch branch. Check your connection.');
+ });
+
test('a branch deleted upstream dismisses the dialog with the no-longer-exists toast', async () => {
const store = createShareReceiveStore();
const { bridge, calls } = makeBridge({
diff --git a/packages/app/src/components/ShareBranchSwitchDialog.tsx b/packages/app/src/components/ShareBranchSwitchDialog.tsx
index 547511e65..a50a7b759 100644
--- a/packages/app/src/components/ShareBranchSwitchDialog.tsx
+++ b/packages/app/src/components/ShareBranchSwitchDialog.tsx
@@ -467,9 +467,24 @@ export function ShareBranchSwitchDialog({
// is a compile error here instead of a silent generic toast.
function showWorktreeFailureToast(
reason: WorktreeCheckoutSideEffectReason,
- helper?: string,
- authFailed?: true,
+ // An options bag, not positional params: `authFailed`/`notFoundAsIdentity` are both
+ // `true | undefined`, so positional passing would let a transposition
+ // compile and silently swap which copy the user sees.
+ {
+ helper,
+ authFailed,
+ notFoundAsIdentity,
+ }: { helper?: string; authFailed?: true; notFoundAsIdentity?: true } = {},
): void {
+ // The repository-not-found masquerade: the remote answered, so the
+ // connection copy is wrong, and a Sign in cannot fix a repo the account
+ // can't see (or that is gone) — name what is actually known instead.
+ if (reason === 'fetch-failed' && notFoundAsIdentity) {
+ toast.error(
+ t`Repository not found — it may not exist, or the account used may not have access.`,
+ );
+ return;
+ }
// A credential miss reaches us as `fetch-failed`, but the connection copy
// below is a dead end for it: the fetch pins credential interactivity off,
// so nothing prompted the user, and retrying without a credential just
@@ -542,6 +557,7 @@ export function ShareBranchSwitchDialog({
let failureReason: WorktreeCheckoutSideEffectReason | null = null;
let failureHelper: string | undefined;
let failureAuth: true | undefined;
+ let failureNotFoundAsIdentity: true | undefined;
let shouldDismiss = false;
let openPath: string | null = null;
setBranchSwitchState((prev) => {
@@ -550,6 +566,7 @@ export function ShareBranchSwitchDialog({
failureReason = sideEffect.reason;
failureHelper = sideEffect.helper;
failureAuth = sideEffect.authFailed;
+ failureNotFoundAsIdentity = sideEffect.notFoundAsIdentity;
shouldDismiss = next.phase === 'dismissed';
}
if (next.phase === 'opening-worktree') {
@@ -564,7 +581,11 @@ export function ShareBranchSwitchDialog({
branch: shareBranch,
}),
);
- showWorktreeFailureToast(failureReason, failureHelper, failureAuth);
+ showWorktreeFailureToast(failureReason, {
+ helper: failureHelper,
+ authFailed: failureAuth,
+ notFoundAsIdentity: failureNotFoundAsIdentity,
+ });
}
if (openPath !== null) {
// The anchor window's cached worktree model is stale now (a worktree was
diff --git a/packages/app/src/components/SyncStatusBadge.dom.test.tsx b/packages/app/src/components/SyncStatusBadge.dom.test.tsx
index 77db0bc3c..d4a8cd0d4 100644
--- a/packages/app/src/components/SyncStatusBadge.dom.test.tsx
+++ b/packages/app/src/components/SyncStatusBadge.dom.test.tsx
@@ -1,5 +1,5 @@
import * as actualLinguiMacro from '@lingui/react/macro';
-import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import { cleanup, render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ReactNode } from 'react';
import { afterEach, describe, expect, test, vi } from 'vitest';
@@ -71,11 +71,11 @@ const baseStatus: GitSyncStatus = {
remote: { label: 'inkeep/open-knowledge', webUrl: 'https://github.com/inkeep/open-knowledge' },
};
-async function renderBadge() {
+async function renderBadge(props: { onSignIn?: () => void } = {}) {
const { SyncStatusBadge } = await import('./SyncStatusBadge');
render(
<TooltipProvider>
- <SyncStatusBadge />
+ <SyncStatusBadge {...props} />
</TooltipProvider>,
);
}
@@ -101,18 +101,128 @@ describe('SyncStatusBadge helper behavior', () => {
test('formats push-permission denial reasons into actionable copy', async () => {
const { formatPushPermissionDenied } = await import('./SyncStatusBadge');
- expect(formatPushPermissionDenied('no-collaborator')).toBe(
- "You don't have permission to push to this repo",
- );
- expect(formatPushPermissionDenied('private-no-access')).toBe(
+ expect(formatPushPermissionDenied('no-collaborator')).toEqual([
+ "You don't have permission to push to this repo.",
+ ]);
+ expect(formatPushPermissionDenied('private-no-access')).toEqual([
"You don't have access to this private repo. Sign in with an account that does.",
- );
- expect(formatPushPermissionDenied('repo-not-found')).toBe(
+ ]);
+ expect(formatPushPermissionDenied('repo-not-found')).toEqual([
'Repository not found. It may have been renamed, deleted, or moved.',
- );
- expect(formatPushPermissionDenied(undefined)).toBe(
- "You don't have permission to push to this repo",
- );
+ ]);
+ expect(formatPushPermissionDenied(undefined)).toEqual([
+ "You don't have permission to push to this repo.",
+ ]);
+ });
+
+ test('denials name the authenticated identity when the wire carries it', async () => {
+ const { formatPushPermissionDenied } = await import('./SyncStatusBadge');
+
+ expect(formatPushPermissionDenied('private-no-access', { resolvedLogin: 'bob' })).toEqual([
+ "You don't have access to this private repo. Sign in with an account that does.",
+ 'Authenticated as bob.',
+ ]);
+ // The read-only-collaborator verdict is exactly as account-dependent as
+ // the private-repo 404 — the personal-token-against-org-repo case lands
+ // here, and the identity is what lets the user spot it.
+ expect(formatPushPermissionDenied('no-collaborator', { resolvedLogin: 'bob' })).toEqual([
+ "You don't have permission to push to this repo.",
+ 'Authenticated as bob.',
+ ]);
+ // No identity on the wire → base copy exactly; the UI never guesses a login.
+ expect(formatPushPermissionDenied('private-no-access', {})).toEqual([
+ "You don't have access to this private repo. Sign in with an account that does.",
+ ]);
+ });
+
+ test('a declared login that missed adds the actionable fact, worded by its source', async () => {
+ const { formatPushPermissionDenied } = await import('./SyncStatusBadge');
+
+ expect(
+ formatPushPermissionDenied('private-no-access', {
+ resolvedLogin: 'bob',
+ declaredLogin: 'alice',
+ declaredSource: 'remote-url',
+ }),
+ ).toEqual([
+ "You don't have access to this private repo. Sign in with an account that does.",
+ 'Authenticated as bob.',
+ "Your remote URL names alice, but that account's credentials couldn't be used.",
+ ]);
+ });
+
+ test('credential-config and unknown declaration sources get their own wording', async () => {
+ const { formatPushPermissionDenied } = await import('./SyncStatusBadge');
+
+ expect(
+ formatPushPermissionDenied('no-collaborator', {
+ declaredLogin: 'workbot',
+ declaredSource: 'credential-config',
+ }),
+ ).toEqual([
+ "You don't have permission to push to this repo.",
+ "Your Git credential configuration names workbot, but that account's credentials couldn't be used.",
+ ]);
+ // declaredSource is an open string on the wire: a newer server's declaration
+ // mechanism must degrade to generic wording, not drop the actionable fact.
+ expect(
+ formatPushPermissionDenied('no-collaborator', {
+ declaredLogin: 'workbot',
+ declaredSource: 'far-future-mechanism',
+ }),
+ ).toEqual([
+ "You don't have permission to push to this repo.",
+ "Your Git configuration names workbot, but that account's credentials couldn't be used.",
+ ]);
+ });
+
+ // The miss copy must not blame a specific tool: the wire does not say
+ // whether the GitHub CLI was consulted, absent, or outdated — and desktop
+ // installs with no gh reach the same path via the signed-out short-circuit.
+ test('the declared-miss sentence asserts the miss without naming a cause', async () => {
+ const { formatPushPermissionDenied } = await import('./SyncStatusBadge');
+
+ const signedOut = formatPushPermissionDenied('not-authenticated', {
+ declaredLogin: 'alice',
+ declaredSource: 'remote-url',
+ });
+ expect(signedOut).toEqual([
+ "You're signed out — sign in to resume syncing.",
+ "Your remote URL names alice, but that account's credentials couldn't be used.",
+ ]);
+ expect(signedOut.join(' ')).not.toContain('GitHub CLI');
+ });
+
+ test('the declared-but-missed login is never named as the authenticated identity', async () => {
+ const { formatPushPermissionDenied } = await import('./SyncStatusBadge');
+
+ const message = formatPushPermissionDenied('private-no-access', {
+ resolvedLogin: 'bob',
+ declaredLogin: 'alice',
+ declaredSource: 'remote-url',
+ }).join(' ');
+ expect(message).toContain('Authenticated as bob.');
+ expect(message).not.toContain('Authenticated as alice');
+ // Without a resolvedLogin the identity sentence is omitted entirely —
+ // the declared login must not be promoted into it.
+ const fallbackUnnamed = formatPushPermissionDenied('private-no-access', {
+ declaredLogin: 'alice',
+ declaredSource: 'remote-url',
+ }).join(' ');
+ expect(fallbackUnnamed).not.toContain('Authenticated as');
+ expect(fallbackUnnamed).toContain('Your remote URL names alice');
+ });
+
+ // The engine parks the not-found masquerade as auth-error, but the badge
+ // must not pair "no prescribed fix" copy with a Sign in affordance — the
+ // predicate is what gates the button, the header, and the paused line.
+ test('hasNotFoundAsIdentityError keys off either direction error code', async () => {
+ const { hasNotFoundAsIdentityError } = await import('./SyncStatusBadge');
+
+ expect(hasNotFoundAsIdentityError({ pushErrorCode: 'auth-not-found-as-identity' })).toBe(true);
+ expect(hasNotFoundAsIdentityError({ pullErrorCode: 'auth-not-found-as-identity' })).toBe(true);
+ expect(hasNotFoundAsIdentityError({ pushErrorCode: 'auth-401' })).toBe(false);
+ expect(hasNotFoundAsIdentityError({})).toBe(false);
});
test('collapses or labels push/pull sync errors by root cause', async () => {
@@ -172,6 +282,43 @@ describe('SyncStatusBadge helper behavior', () => {
}
});
+ test('a not-found failure states not-found-or-no-access without claiming which', async () => {
+ const { formatPullFailureCode, formatPushFailureCode, formatSyncFailureCode } = await import(
+ './SyncStatusBadge'
+ );
+
+ // The classifier cannot tell a missing repo from an invisible one (GitHub
+ // answers 404 for both), so the copy asserts only the ambiguity and never
+ // offers sign-in as the fix.
+ for (const format of [formatSyncFailureCode, formatPushFailureCode, formatPullFailureCode]) {
+ expect(format('auth-not-found-as-identity')).toBe(
+ 'Repository not found — it may not exist, or the account used may not have access.',
+ );
+ }
+ });
+
+ test('an unrecognized sync error code renders generic fallback copy (older client, newer server)', async () => {
+ const { formatPullFailureCode, formatPushFailureCode, formatSyncFailureCode } = await import(
+ './SyncStatusBadge'
+ );
+
+ // A client whose bundle predates a server-added code must render a
+ // meaningful generic line, not an empty styled-red paragraph. The sync
+ // status wire is not schema-validated client-side, so the unknown code
+ // string reaches these formatters as-is — this default branch IS the
+ // version-skew degradation path for the bounded error-code enum.
+ const futureCode = 'auth-far-future' as Parameters<typeof formatPushFailureCode>[0];
+ expect(formatPushFailureCode(futureCode)).toBe(
+ 'Push failed — check the server logs for details.',
+ );
+ expect(formatPullFailureCode(futureCode)).toBe(
+ 'Fetch failed — check the server logs for details.',
+ );
+ expect(formatSyncFailureCode(futureCode)).toBe(
+ 'Sync failed — check the server logs for details.',
+ );
+ });
+
test('only token-invalid unknown push-permission probes offer sign-in again', async () => {
const { shouldOfferSignInAgain } = await import('./SyncStatusBadge');
@@ -460,6 +607,189 @@ describe('SyncStatusBadge runtime behavior', () => {
expect(screen.getByTestId('sync-popover-mode-line')).toBeTruthy();
});
+ // The signed-out reconnect arm: the most common auth failure shape, and one
+ // of the two arms that render a Sign in Button outside the live region.
+ test('a signed-out denial renders the reconnect line and its Sign in button', async () => {
+ status = {
+ ...baseStatus,
+ state: 'idle',
+ pushPermission: { checkStatus: 'denied', deniedReason: 'not-authenticated' },
+ };
+ await renderBadge({ onSignIn: () => {} });
+ await openPopover();
+
+ expect(screen.getByText(/signed out — sign in to resume syncing/)).toBeTruthy();
+ // Exactly one Sign in exists here (the header's is gated on auth-error),
+ // so this resolves to the reconnect arm's own button — and it must sit
+ // OUTSIDE the live region: role="status" is implicitly aria-atomic, so a
+ // button inside it would be re-announced on every status text change.
+ const signIn = screen.getByRole('button', { name: 'Sign in' });
+ expect(signIn).toBeTruthy();
+ expect(within(screen.getByRole('status')).queryByRole('button')).toBeNull();
+ });
+
+ // Precedence: the signed-out reconnect must beat the paused-reason arm. A
+ // parked engine reaches both, and losing the order strands that user with
+ // "Reconnect required" and no affordance — copy prescribing an action the
+ // popover no longer offers.
+ test('a signed-out denial outranks the paused-reason line when the engine is parked', async () => {
+ status = {
+ ...baseStatus,
+ state: 'auth-error',
+ pausedReason: 'auth-error',
+ pushPermission: { checkStatus: 'denied', deniedReason: 'not-authenticated' },
+ };
+ await renderBadge({ onSignIn: () => {} });
+ await openPopover();
+
+ expect(screen.getByText(/signed out — sign in to resume syncing/)).toBeTruthy();
+ // "Reconnect required" is the popover header here, and correctly so — a
+ // signed-out denial IS reconnect-fixable. What must not appear is a
+ // SECOND copy from the paused-reason arm, which would mean that arm won
+ // the chain and the reconnect affordance was dropped.
+ expect(screen.getAllByText('Reconnect required')).toHaveLength(1);
+ // The live region carries status text only — the Sign in row renders
+ // outside it, so a text change never re-announces a button label.
+ expect(within(screen.getByRole('status')).queryByRole('button')).toBeNull();
+ });
+
+ // The probe-401 arm: the other Sign-in-bearing arm, and the last one in the
+ // chain, so an arm reordered above it silently swallows this state.
+ test('a probe-401 renders the sign-in-again line and its button', async () => {
+ status = {
+ ...baseStatus,
+ state: 'idle',
+ pushPermission: { checkStatus: 'unknown', unknownError: 'token-invalid' },
+ };
+ await renderBadge({ onSignIn: () => {} });
+ await openPopover();
+
+ expect(screen.getByText(/GitHub session expired — sign in again/)).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'Sign in' })).toBeTruthy();
+ });
+
+ test('the denied popover line renders the identity sentences from the wire payload', async () => {
+ status = {
+ ...baseStatus,
+ state: 'idle',
+ pushPermission: {
+ checkStatus: 'denied',
+ deniedReason: 'private-no-access',
+ resolvedLogin: 'bob',
+ declaredLogin: 'alice',
+ declaredSource: 'remote-url',
+ },
+ };
+ await renderBadge();
+ await openPopover();
+
+ // Sentences render one per line, so each is asserted as its own element.
+ expect(screen.getByText(/don't have access to this private repo/)).toBeTruthy();
+ expect(screen.getByText('Authenticated as bob.')).toBeTruthy();
+ expect(
+ screen.getByText(
+ "Your remote URL names alice, but that account's credentials couldn't be used.",
+ ),
+ ).toBeTruthy();
+ });
+
+ // The engine parks the not-found masquerade as auth-error, but the popover
+ // must not pair "may not exist / may not have access" copy with a Sign in
+ // button — the copy and the affordance have to agree.
+ test('a not-found-as-identity auth error withdraws the Sign in affordance', async () => {
+ status = {
+ ...baseStatus,
+ state: 'auth-error',
+ pausedReason: 'auth-error',
+ pushErrorCode: 'auth-not-found-as-identity',
+ };
+ await renderBadge();
+ await openPopover();
+
+ expect(screen.getByText(/Repository not found — it may not exist/)).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'Sign in' })).toBeNull();
+ expect(screen.queryByText('Reconnect required')).toBeNull();
+ // The header names the symptom instead.
+ expect(screen.getAllByText('Repository not found').length).toBeGreaterThan(0);
+ // The accessible name reads the same derivation as the visible surfaces —
+ // a screen reader must not hear the reconnect prescription the popover
+ // withdrew (queryByText matches text content, never aria-label, so only
+ // a role+name query can pin this).
+ expect(screen.getByRole('button', { name: 'Sync status: Repository not found' })).toBeTruthy();
+ // The error/guidance block is a polite live region, so the state flip is
+ // announced to an open popover instead of changing silently.
+ expect(screen.getByRole('status')).toBeTruthy();
+ });
+
+ // The parked engine keeps the last probe verdict in `pushPermission`; when
+ // that verdict is a denial, its identity sentences must survive into the
+ // parked popover — the account used is the fact this state turns on.
+ test('a parked not-found error still names the account when a denied verdict is in hand', async () => {
+ status = {
+ ...baseStatus,
+ state: 'auth-error',
+ pausedReason: 'auth-error',
+ pushErrorCode: 'auth-not-found-as-identity',
+ pushPermission: {
+ checkStatus: 'denied',
+ deniedReason: 'private-no-access',
+ resolvedLogin: 'bob',
+ },
+ };
+ await renderBadge();
+ await openPopover();
+
+ // The masquerade's probe also answers `denied`, but that is not a
+ // collaborator verdict — so the Mode chooser stays available here, the
+ // same call Settings makes for the identical status object. Two surfaces,
+ // one status, one answer.
+ expect(screen.getByTestId('sync-popover-mode-toggle')).toBeTruthy();
+ expect(screen.getByText('Authenticated as bob.')).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'Sign in' })).toBeNull();
+ // Only the identity tail rides along — the denial's REASON sentence
+ // re-prescribes the sign-in this state withholds (and asserts more than
+ // the 404 proves), so it must not render next to the not-found copy.
+ expect(screen.queryByText(/Sign in with an account that does/)).toBeNull();
+ expect(screen.queryByText(/don't have access to this private repo/)).toBeNull();
+ });
+
+ // A push-permission pause and a genuine read-only collaborator produce the
+ // same sentence, so without the identity tail a two-account user cannot tell
+ // "wrong account" from "you were never a collaborator".
+ test('a push-permission pause names the account that was actually used', async () => {
+ status = {
+ ...baseStatus,
+ state: 'disabled',
+ syncEnabled: false,
+ pausedReason: 'no-push-permission',
+ pushPermission: {
+ checkStatus: 'denied',
+ deniedReason: 'private-no-access',
+ resolvedLogin: 'bob',
+ },
+ };
+ await renderBadge();
+ await openPopover();
+
+ // The pause is real and stays the headline; the identity rides along.
+ expect(screen.getByText("You don't have permission to push to this repo.")).toBeTruthy();
+ expect(screen.getByText('Authenticated as bob.')).toBeTruthy();
+ });
+
+ test('other auth errors keep the Sign in affordance and the reconnect header', async () => {
+ status = {
+ ...baseStatus,
+ state: 'auth-error',
+ pausedReason: 'auth-error',
+ pushErrorCode: 'auth-401',
+ };
+ await renderBadge();
+ await openPopover();
+
+ expect(screen.getByRole('button', { name: 'Sign in' })).toBeTruthy();
+ expect(screen.getAllByText('Reconnect required').length).toBeGreaterThan(0);
+ });
+
test('a paused (was-enabled) project stays visible and shows the paused popover', async () => {
// Engine reports a paused project as disabled; the config (resumeMode set)
// keeps the badge visible and drives the paused rendering.
diff --git a/packages/app/src/components/SyncStatusBadge.tsx b/packages/app/src/components/SyncStatusBadge.tsx
index 5c7c5ac6a..88c5d2c92 100644
--- a/packages/app/src/components/SyncStatusBadge.tsx
+++ b/packages/app/src/components/SyncStatusBadge.tsx
@@ -23,6 +23,7 @@ import {
AlertTriangle,
ArrowUpRight,
Cloud,
+ CloudAlert,
CloudOff,
LogIn,
Pause,
@@ -133,7 +134,17 @@ function BadgeIcon({ status, paused }: BadgeIconProps) {
case 'offline':
return <CloudOff className={`${cls} text-muted-foreground`} />;
case 'auth-error':
- return <LogIn className={`${cls} text-destructive`} />;
+ // The not-found masquerade withdraws the sign-in affordance, so the
+ // sign-in glyph would prescribe exactly what the popover withholds.
+ // CloudAlert (not AlertTriangle, which already means conflict/disabled
+ // in amber): the collapsed badge is icon-only for this state, so the
+ // glyph shape — not hue alone — has to distinguish it for users who
+ // can't tell amber from red.
+ return hasNotFoundAsIdentityError(status) ? (
+ <CloudAlert className={`${cls} text-destructive`} />
+ ) : (
+ <LogIn className={`${cls} text-destructive`} />
+ );
case 'disabled':
// Reachable only when an auto-disable carries a pausedReason
// (manual user disable hides the badge via early return below).
@@ -214,17 +225,30 @@ export function formatPausedReason(reason: string): string {
case 'protected-branch':
return t`Protected branch — cannot push`;
case 'no-push-permission':
- return t`You don't have permission to push to this repo`;
+ return t`You don't have permission to push to this repo.`;
default:
return reason;
}
}
+/** Identity fields the wire's denied push-permission variant may carry. */
+type PushPermissionDeniedIdentity = Pick<
+ Extract<PushPermissionWire, { checkStatus: 'denied' }>,
+ 'resolvedLogin' | 'declaredLogin' | 'declaredSource'
+>;
+
/**
* Format the cause-specific message for a `denied` push-permission probe.
* Used when the user has not enabled sync yet (so `pausedReason` is unset)
* but the probe says they can't push — they should see the same actionable
* copy as a user whose engine paused after enabling sync.
+ *
+ * When the wire names the identity that was actually authenticated
+ * (`resolvedLogin`, always the post-fallback login), the denial copy ends
+ * with it so the user can spot an account mismatch themselves — for every
+ * denial reason that authenticated at all, since a read-only collaborator
+ * verdict is exactly as account-dependent as a private-repo 404. When it is
+ * absent the sentence is omitted — the message degrades, it never guesses.
*/
export function formatPushPermissionDenied(
reason:
@@ -233,21 +257,121 @@ export function formatPushPermissionDenied(
| 'repo-not-found'
| 'not-authenticated'
| undefined,
-): string {
+ identity?: PushPermissionDeniedIdentity,
+): string[] {
+ const sentences: string[] = [];
switch (reason) {
case 'not-authenticated':
- return t`You're signed out — sign in to resume syncing.`;
+ sentences.push(t`You're signed out — sign in to resume syncing.`);
+ break;
case 'no-collaborator':
- return t`You don't have permission to push to this repo`;
+ sentences.push(t`You don't have permission to push to this repo.`);
+ break;
case 'private-no-access':
- return t`You don't have access to this private repo. Sign in with an account that does.`;
+ sentences.push(
+ t`You don't have access to this private repo. Sign in with an account that does.`,
+ );
+ break;
case 'repo-not-found':
- return t`Repository not found. It may have been renamed, deleted, or moved.`;
+ sentences.push(t`Repository not found. It may have been renamed, deleted, or moved.`);
+ break;
+ default:
+ sentences.push(t`You don't have permission to push to this repo.`);
+ }
+ sentences.push(...formatDeniedIdentitySentences(identity));
+ // Returned as sentences, rendered one per line: a hard-coded joiner would
+ // put a Latin space after the CJK full stop in zh catalogs, and separate
+ // lines keep three distinct facts scannable in the narrow popover.
+ return sentences;
+}
+
+/**
+ * Only the identity tail of a denial — the `Authenticated as …` and
+ * declared-miss sentences, without the leading reason sentence. The parked
+ * not-found popover renders this: its error line already carries the full
+ * not-found copy, and every reason sentence either re-prescribes the sign-in
+ * that state withholds (`private-no-access`) or asserts more than the 404
+ * proves, so only the identity facts may ride along there.
+ */
+export function formatDeniedIdentitySentences(identity?: PushPermissionDeniedIdentity): string[] {
+ const sentences: string[] = [];
+ if (identity?.resolvedLogin) {
+ const login = identity.resolvedLogin;
+ sentences.push(t`Authenticated as ${login}.`);
+ }
+ if (identity?.declaredLogin) {
+ sentences.push(formatDeclaredAccountMiss(identity.declaredLogin, identity.declaredSource));
+ }
+ return sentences;
+}
+
+/**
+ * Name the account the user declared but the credential resolution could not
+ * use, and the mechanism they declared it through. The copy asserts only the
+ * miss itself — it does not name a cause (the wire does not say whether the
+ * GitHub CLI was consulted, absent, or outdated, and a desktop install with
+ * no gh at all reaches this path too) and it does not name the substitute
+ * account (the `Authenticated as` sentence carries that when known).
+ * `declaredSource` is an open string on the wire: a payload from a server
+ * with a newer declaration mechanism must degrade to the generic wording,
+ * never fail or guess.
+ *
+ * Deliberately says more than its CLI twin (`formatDeclaredMissWarning`):
+ * this path reaches the wire only after the server resolved the answering
+ * account, so it can contrast the two identities; the clone path has no such
+ * lookup and asserts only that the request went unconfirmed. Don't collapse
+ * one into the other.
+ */
+function formatDeclaredAccountMiss(declaredLogin: string, declaredSource: string | undefined) {
+ switch (declaredSource) {
+ case 'remote-url':
+ return t`Your remote URL names ${declaredLogin}, but that account's credentials couldn't be used.`;
+ case 'credential-config':
+ return t`Your Git credential configuration names ${declaredLogin}, but that account's credentials couldn't be used.`;
default:
- return t`You don't have permission to push to this repo`;
+ return t`Your Git configuration names ${declaredLogin}, but that account's credentials couldn't be used.`;
}
}
+/**
+ * Whether the current sync error is the repository-not-found masquerade:
+ * git's "repository not found" with a credential attached, where GitHub
+ * deliberately hides "private + no access" behind the same answer as
+ * "doesn't exist". The engine parks it as an auth error (sync genuinely
+ * cannot proceed), but unlike every other auth subclass a re-sign-in is not
+ * the prescribed fix — so the badge suppresses the reconnect affordance and
+ * header for it and lets the error line carry the full copy.
+ */
+export function hasNotFoundAsIdentityError(
+ status: Pick<GitSyncStatus, 'pushErrorCode' | 'pullErrorCode'>,
+): boolean {
+ return (
+ status.pushErrorCode === 'auth-not-found-as-identity' ||
+ status.pullErrorCode === 'auth-not-found-as-identity'
+ );
+}
+
+/**
+ * Whether the engine is parked on the repository-not-found masquerade — the
+ * state where the Sign in affordance is withheld because re-auth cannot fix
+ * it. Keyed on `pausedReason` rather than `state`: the engine refuses to let
+ * a probe denial overwrite this park, so the reason survives even when a
+ * later failure moves `state` (the retryable arm transitions to 'offline'
+ * without clearing the reason).
+ *
+ * Shared by the badge and Settings so the two surfaces cannot describe one
+ * status object differently — the defect class that made the composed
+ * identity copy unreachable during this feature's development.
+ */
+export function isParkedOnNotFoundAsIdentity(
+ status:
+ | Pick<GitSyncStatus, 'pausedReason' | 'pushErrorCode' | 'pullErrorCode'>
+ | null
+ | undefined,
+): boolean {
+ return status?.pausedReason === 'auth-error' && hasNotFoundAsIdentityError(status);
+}
+
/**
* Whether the push-permission denial is a *signed-out* one (no credential
* resolved), which a reconnect fixes — as opposed to a genuine read-only
@@ -279,6 +403,8 @@ export function formatPushFailureCode(code: SyncErrorCode): string {
return t`GitHub sign-in is missing or expired. Reconnect to resume syncing.`;
case 'semantic-protected-branch':
return t`The default branch is protected — pushes need a pull request.`;
+ case 'auth-not-found-as-identity':
+ return t`Repository not found — it may not exist, or the account used may not have access.`;
default:
// Forward-compat: if a future server emits a code this client doesn't
// recognize (server-client version skew, even though OK ships as a
@@ -305,6 +431,8 @@ export function formatPullFailureCode(code: SyncErrorCode): string {
return t`Your GitHub token is missing required scopes. Try signing in again.`;
case 'auth-no-credential':
return t`GitHub sign-in is missing or expired. Reconnect to resume syncing.`;
+ case 'auth-not-found-as-identity':
+ return t`Repository not found — it may not exist, or the account used may not have access.`;
default:
return t`Fetch failed — check the server logs for details.`;
}
@@ -329,6 +457,8 @@ export function formatSyncFailureCode(code: SyncErrorCode): string {
return t`GitHub sign-in is missing or expired. Reconnect to resume syncing.`;
case 'semantic-protected-branch':
return t`The default branch is protected — pushes need a pull request.`;
+ case 'auth-not-found-as-identity':
+ return t`Repository not found — it may not exist, or the account used may not have access.`;
default:
return t`Sync failed — check the server logs for details.`;
}
@@ -453,6 +583,21 @@ export function shouldDisableSyncSwitch(
return false;
}
+/**
+ * One home for the state → label rule every plain-state surface reads (the
+ * tooltip tail, the popover header, and the trigger's accessible name), so
+ * the not-found masquerade cannot read "Repository not found" on one surface
+ * while another still prescribes the reconnect it withdrew.
+ */
+function syncStateLabelFor(status: GitSyncStatus, paused: boolean): string {
+ if (paused) return t`Sync paused`;
+ const state = displayState(status);
+ if (state === 'auth-error' && hasNotFoundAsIdentityError(status)) {
+ return t`Repository not found`;
+ }
+ return stateLabel(state, isFollowingMode(status));
+}
+
export function tooltipLabel(status: GitSyncStatus, paused = false): string {
if (paused) return t`Sync paused`;
const following = isFollowingMode(status);
@@ -479,7 +624,7 @@ export function tooltipLabel(status: GitSyncStatus, paused = false): string {
if (behind > 0) return t`${behind} behind`;
return t`Synced`;
}
- return stateLabel(state, following);
+ return syncStateLabelFor(status, paused);
}
interface PopoverBodyProps {
@@ -512,12 +657,22 @@ function PopoverBody({ status, onSignIn, onSetIdentity }: PopoverBodyProps) {
const following = isFollowingMode(status);
const state = displayState(status);
const lastSyncedRelative = formatRelative(status.lastSyncUtc);
+ // The repository-not-found masquerade parks as auth-error but withdraws the
+ // sign-in affordance — see hasNotFoundAsIdentityError.
+ const notFoundAsIdentity = hasNotFoundAsIdentityError(status);
// The Full/Follow control appears only for a user who can actually choose —
// a genuine read-only collaborator can only follow, so it's hidden for them
- // (a signed-out user may gain push after auth, so they keep it).
+ // (a signed-out user may gain push after auth, so they keep it). The
+ // not-found masquerade is excluded: its probe also answers `denied`, but
+ // that is not a collaborator verdict, and this row is the popover's only
+ // mode control — a failure that says nothing about push rights must not
+ // revoke it. (Settings excludes it from the sibling gate for a related but
+ // distinct reason: there only Full greys out, so the exclusion also stops
+ // one mode being singled out.)
const genuineReadOnly =
status.pushPermission?.checkStatus === 'denied' &&
- status.pushPermission.deniedReason !== 'not-authenticated';
+ status.pushPermission.deniedReason !== 'not-authenticated' &&
+ !notFoundAsIdentity;
const canChooseMode = !genuineReadOnly;
// The "Review conflicts" affordance navigates to the first conflicted file
// (so the editor-area DiffViewBoundary mounts via the lifecycle observer).
@@ -525,21 +680,43 @@ function PopoverBody({ status, onSignIn, onSetIdentity }: PopoverBodyProps) {
const firstConflict = conflicts[0] ?? null;
const showConflictButton = !paused && state === 'conflict' && firstConflict !== null;
- const showAuthButton = !paused && state === 'auth-error';
+ const showAuthButton = !paused && state === 'auth-error' && !notFoundAsIdentity;
const showSyncButton =
everEnabled && !showConflictButton && !showAuthButton && (paused || state !== 'dormant');
// A manual sync from a full-active project pushes too; every other case
// (following, or paused) pulls only.
const manualSyncOp: 'sync' | 'pull' = active && localMode === 'full' ? 'sync' : 'pull';
+ // Which guidance renders under the error lines — one precedence chain,
+ // evaluated once. The signed-out reconnect wins over the button-less
+ // `pausedReason`/`denied` outcomes; a paused engine never falls through to
+ // the mode lines (which would claim edits are syncing while it's parked).
+ // For the parked not-found masquerade, the auth-error paused line would
+ // read "Reconnect required" — the prescription this state withdraws — so
+ // it gets its own outcome and the error line carries the copy instead.
+ const guidance =
+ !following && shouldOfferReconnect(status.pushPermission)
+ ? 'reconnect'
+ : status.pausedReason
+ ? isParkedOnNotFoundAsIdentity(status)
+ ? 'parked-not-found'
+ : 'paused-reason'
+ : following
+ ? 'mode-follow'
+ : active
+ ? 'mode-full'
+ : status.pushPermission?.checkStatus === 'denied'
+ ? 'denied'
+ : shouldOfferSignInAgain(status.pushPermission)
+ ? 'sign-in-again'
+ : 'none';
+
return (
<div className="flex flex-col gap-3.5">
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2 min-w-0">
<BadgeIcon status={status} paused={paused} />
- <span className="text-1sm font-medium truncate">
- {paused ? t`Sync paused` : stateLabel(state, following)}
- </span>
+ <span className="text-1sm font-medium truncate">{syncStateLabelFor(status, paused)}</span>
</div>
<Switch
checked={active}
@@ -562,27 +739,77 @@ function PopoverBody({ status, onSignIn, onSetIdentity }: PopoverBodyProps) {
</p>
) : (
<>
- {computeSyncErrorLines(status).map((line) => (
- <p key={line.key} className="text-xs text-destructive">
- {line.direction === 'push' ? (
- <>
- <span className="font-medium">{t`Push`}: </span>
- {line.message}
- </>
- ) : line.direction === 'pull' ? (
- <>
- <span className="font-medium">{t`Pull`}: </span>
- {line.message}
- </>
- ) : (
- line.message
- )}
- </p>
- ))}
- {!following && shouldOfferReconnect(status.pushPermission) ? (
- // Signed-out denial (no credential resolved) — reconnecting resumes
- // sync, so offer it here. Takes precedence over the button-less
- // `pausedReason`/`denied` branches below.
+ {/* The live region carries only status text — the error lines and
+ the button-less guidance — so a state flip is announced to an
+ open popover without re-reading button labels or mode sentences
+ (role="status" is implicitly aria-atomic, so any text change
+ re-announces the whole region; keep children non-interactive).
+ The rows carrying a Button, and the steady-state mode sentences,
+ render after it. `empty:sr-only` keeps the region mounted and
+ pre-registered while healthy: a region that appears and fills in
+ one commit is missed on VoiceOver/Safari, and `display:none`
+ (like unmounting) drops it from the accessibility tree
+ entirely. `sr-only` is absolutely positioned, so an empty
+ region is not a flex item and adds no gap. */}
+ <div role="status" aria-live="polite" className="flex flex-col gap-3.5 empty:sr-only">
+ {computeSyncErrorLines(status).map((line) => (
+ <p key={line.key} className="text-xs text-destructive">
+ {line.direction === 'push' ? (
+ <>
+ <span className="font-medium">{t`Push`}: </span>
+ {line.message}
+ </>
+ ) : line.direction === 'pull' ? (
+ <>
+ <span className="font-medium">{t`Pull`}: </span>
+ {line.message}
+ </>
+ ) : (
+ line.message
+ )}
+ </p>
+ ))}
+ {guidance === 'parked-not-found' && status.pushPermission?.checkStatus === 'denied'
+ ? // Identity tail only — see formatDeniedIdentitySentences.
+ formatDeniedIdentitySentences(status.pushPermission).map((sentence) => (
+ <p key={sentence} className="text-xs text-muted-foreground">
+ {sentence}
+ </p>
+ ))
+ : null}
+ {guidance === 'paused-reason' && status.pausedReason ? (
+ <p className="text-xs text-muted-foreground">
+ {formatPausedReason(status.pausedReason)}
+ </p>
+ ) : null}
+ {guidance === 'paused-reason' &&
+ status.pausedReason === 'no-push-permission' &&
+ status.pushPermission?.checkStatus === 'denied'
+ ? // A push-permission pause and a genuine read-only collaborator
+ // render the same sentence, so the identity tail is the only
+ // thing that tells a two-account user which account was used.
+ // Additive to the pause line: the engine really is parked, and
+ // that stays the headline.
+ formatDeniedIdentitySentences(status.pushPermission).map((sentence) => (
+ <p key={sentence} className="text-xs text-muted-foreground">
+ {sentence}
+ </p>
+ ))
+ : null}
+ {guidance === 'denied' && status.pushPermission?.checkStatus === 'denied'
+ ? formatPushPermissionDenied(
+ status.pushPermission.deniedReason,
+ status.pushPermission,
+ ).map((sentence) => (
+ <p key={sentence} className="text-xs text-muted-foreground">
+ {sentence}
+ </p>
+ ))
+ : null}
+ </div>
+ {guidance === 'reconnect' ? (
+ // Signed-out denial (no credential resolved) — reconnecting
+ // resumes sync, so offer it here.
<div className="flex items-start gap-2">
<p className="text-xs text-muted-foreground flex-1 min-w-0">
<Trans>You're signed out — sign in to resume syncing.</Trans>
@@ -593,11 +820,7 @@ function PopoverBody({ status, onSignIn, onSetIdentity }: PopoverBodyProps) {
</Button>
)}
</div>
- ) : status.pausedReason ? (
- <p className="text-xs text-muted-foreground">
- {formatPausedReason(status.pausedReason)}
- </p>
- ) : following ? (
+ ) : guidance === 'mode-follow' ? (
// A follower never pushes, so the push-permission verdict is
// irrelevant — say what the project IS (the mode).
<p className="text-xs text-muted-foreground" data-testid="sync-popover-mode-line">
@@ -605,17 +828,13 @@ function PopoverBody({ status, onSignIn, onSetIdentity }: PopoverBodyProps) {
Follow — updates flow in from your remote; your edits stay on this computer.
</Trans>
</p>
- ) : active ? (
+ ) : guidance === 'mode-full' ? (
<p className="text-xs text-muted-foreground" data-testid="sync-popover-mode-line">
<Trans>
Full sync — your edits are committed and pushed to your remote automatically.
</Trans>
</p>
- ) : status.pushPermission?.checkStatus === 'denied' ? (
- <p className="text-xs text-muted-foreground">
- {formatPushPermissionDenied(status.pushPermission.deniedReason)}
- </p>
- ) : shouldOfferSignInAgain(status.pushPermission) ? (
+ ) : guidance === 'sign-in-again' ? (
// Probe-401 branch: surface a "Sign in again" affordance without
// disabling sync — the probe couldn't reach a verdict.
<div className="flex items-start gap-2">
@@ -857,9 +1076,7 @@ export function SyncStatusBadge({ onSignIn, onSetIdentity }: SyncStatusBadgeProp
}
const label = paused ? '' : badgeLabel(status);
- const syncStateLabel = paused
- ? t`Sync paused`
- : stateLabel(displayState(status), isFollowingMode(status));
+ const syncStateLabel = syncStateLabelFor(status, paused);
const showIdentityDot = Boolean(status.identityUnresolved);
return (
diff --git a/packages/app/src/components/settings/SettingsDialogBody.sections.dom.test.tsx b/packages/app/src/components/settings/SettingsDialogBody.sections.dom.test.tsx
index 569d77664..c57781334 100644
--- a/packages/app/src/components/settings/SettingsDialogBody.sections.dom.test.tsx
+++ b/packages/app/src/components/settings/SettingsDialogBody.sections.dom.test.tsx
@@ -821,6 +821,136 @@ describe('SettingsDialogBody section runtime dispatch', () => {
);
});
+ // The not-found masquerade parks as auth-error, whose paused label reads
+ // "Reconnect required" — the prescription the sync badge withdraws for this
+ // subclass. Settings must show the failure's own copy, not the withdrawn fix.
+ test('sync section shows the not-found copy instead of the reconnect prescription', async () => {
+ syncStatus = {
+ state: 'auth-error',
+ hasRemote: true,
+ pausedReason: 'auth-error',
+ pushErrorCode: 'auth-not-found-as-identity',
+ syncEnabled: true,
+ remote: {
+ label: 'inkeep/open-knowledge',
+ webUrl: 'https://github.com/inkeep/open-knowledge',
+ },
+ };
+ projectLocalConfig = { autoSync: { enabled: true } };
+
+ await renderBody({ activeId: 'sync' });
+
+ expect(screen.getByTestId('settings-sync-reason').textContent).toBe(
+ 'Repository not found — it may not exist, or the account used may not have access.',
+ );
+ expect(screen.queryByText('Reconnect required')).toBeNull();
+ });
+
+ // The ordinary shape of this state carries BOTH signals: the parked engine's
+ // not-found code and a denied probe verdict against the same invisible repo.
+ // The permission-flavored affordances must stay suppressed — the failure is
+ // not a collaborator verdict, and Follow fetches the same invisible repo —
+ // so the not-found copy must win over the push-denied short-circuits.
+ test('sync section keeps the not-found copy when a denied probe verdict is also in hand', async () => {
+ syncStatus = {
+ state: 'auth-error',
+ hasRemote: true,
+ pausedReason: 'auth-error',
+ pushErrorCode: 'auth-not-found-as-identity',
+ pushPermission: {
+ checkStatus: 'denied',
+ deniedReason: 'private-no-access',
+ resolvedLogin: 'bob',
+ },
+ syncEnabled: true,
+ remote: {
+ label: 'inkeep/open-knowledge',
+ webUrl: 'https://github.com/inkeep/open-knowledge',
+ },
+ };
+ projectLocalConfig = { autoSync: { mode: 'full' } };
+
+ await renderBody({ activeId: 'sync' });
+
+ expect(screen.getByTestId('settings-sync-reason').textContent).toBe(
+ 'Repository not found — it may not exist, or the account used may not have access.',
+ );
+ expect(screen.queryByTestId('settings-sync-switch-follow')).toBeNull();
+ expect(screen.queryByTestId('settings-sync-denied-hint')).toBeNull();
+ // The notice names an account problem, so it must also name the account —
+ // the badge does, and the docs tell readers the message identifies it.
+ expect(screen.getByTestId('settings-sync-identity').textContent).toBe('Authenticated as bob.');
+ // The mode control is the fourth permission-flavored affordance: greying
+ // Full out behind "you don't have permission" would state a cause the 404
+ // doesn't prove, and would single out Full when Follow fetches the same
+ // unseeable repo. Its tooltip is also the only explanation a pointer user
+ // gets, while the keyboard path relies on the notice above.
+ expect((screen.getByTestId('settings-sync-mode-full') as HTMLButtonElement).disabled).toBe(
+ false,
+ );
+ expect(screen.queryByTestId('settings-sync-mode-full-tip')).toBeNull();
+ });
+
+ // The tail is up to TWO sentences — the account used and the declared-account
+ // miss. That pair is the payload this feature exists to surface, and a
+ // per-paragraph testid would make `getByTestId` throw on exactly it.
+ test('sync section renders both identity sentences when the wire carries a declared miss', async () => {
+ syncStatus = {
+ state: 'auth-error',
+ hasRemote: true,
+ pausedReason: 'auth-error',
+ pushErrorCode: 'auth-not-found-as-identity',
+ pushPermission: {
+ checkStatus: 'denied',
+ deniedReason: 'private-no-access',
+ resolvedLogin: 'bob',
+ declaredLogin: 'alice',
+ declaredSource: 'remote-url',
+ },
+ syncEnabled: true,
+ remote: {
+ label: 'inkeep/open-knowledge',
+ webUrl: 'https://github.com/inkeep/open-knowledge',
+ },
+ };
+ projectLocalConfig = { autoSync: { mode: 'full' } };
+
+ await renderBody({ activeId: 'sync' });
+
+ const identity = screen.getByTestId('settings-sync-identity');
+ expect(identity.textContent).toContain('Authenticated as bob.');
+ expect(identity.textContent).toContain(
+ "Your remote URL names alice, but that account's credentials couldn't be used.",
+ );
+ });
+
+ // The retryable arm transitions to `offline` WITHOUT clearing pausedReason,
+ // so state and reason diverge while the not-found code survives. Both this
+ // surface and the badge key on the REASON, so both must still explain it.
+ test('sync section still explains the not-found failure after an offline transition', async () => {
+ syncStatus = {
+ state: 'offline',
+ hasRemote: true,
+ pausedReason: 'auth-error',
+ pushErrorCode: 'auth-not-found-as-identity',
+ pushPermission: { checkStatus: 'denied', deniedReason: 'private-no-access' },
+ syncEnabled: true,
+ remote: {
+ label: 'inkeep/open-knowledge',
+ webUrl: 'https://github.com/inkeep/open-knowledge',
+ },
+ };
+ projectLocalConfig = { autoSync: { mode: 'full' } };
+
+ await renderBody({ activeId: 'sync' });
+
+ expect(screen.getByTestId('settings-sync-reason').textContent).toBe(
+ 'Repository not found — it may not exist, or the account used may not have access.',
+ );
+ expect(screen.queryByTestId('settings-sync-switch-follow')).toBeNull();
+ expect(screen.queryByTestId('settings-sync-denied-hint')).toBeNull();
+ });
+
test('sync empty state offers Publish wizard and keeps the advanced git remote path', async () => {
syncStatus = { state: 'dormant', hasRemote: false, syncEnabled: false };
diff --git a/packages/app/src/components/settings/SyncSection.tsx b/packages/app/src/components/settings/SyncSection.tsx
index 753998ac1..545f00eb4 100644
--- a/packages/app/src/components/settings/SyncSection.tsx
+++ b/packages/app/src/components/settings/SyncSection.tsx
@@ -23,7 +23,11 @@ import { AuthModal } from '@/components/AuthModal';
import { EnableSyncConfirmDialog } from '@/components/EnableSyncConfirmDialog';
import { PublishToGitHubDialog } from '@/components/PublishToGitHubDialog';
import {
+ formatDeniedIdentitySentences,
formatPausedReason,
+ formatSyncFailureCode,
+ hasNotFoundAsIdentityError,
+ isParkedOnNotFoundAsIdentity,
shouldOfferReconnect,
shouldOfferSignInAgain,
} from '@/components/SyncStatusBadge';
@@ -144,21 +148,53 @@ export function SyncSection() {
// the full sync the user already consented to, so it takes precedence over
// the switch-to-pull-only offer (that one is for genuinely revoked access).
const offerReconnect = shouldOfferReconnect(status?.pushPermission);
+ // The not-found masquerade suppresses every permission-flavored affordance
+ // below: the failure is "repo missing or invisible to the account used",
+ // not a collaborator-permission verdict, and Follow is no way out — an
+ // account that can't see the repo can't fetch it either.
+ const notFoundAsIdentity = status !== null && hasNotFoundAsIdentityError(status);
const showReconnect = localMode === 'full' && isPushDenied && offerReconnect;
- const showSwitchToPullOnly = localMode === 'full' && isPushDenied && !offerReconnect;
+ const showSwitchToPullOnly =
+ localMode === 'full' && isPushDenied && !offerReconnect && !notFoundAsIdentity;
+ // The plain-text reason a push is denied. Deliberately carries NO `localMode`
+ // term: it is the only channel that reaches a keyboard user, because Radix
+ // drops a disabled toggle item from the roving tab order and the tooltip
+ // hangs off a non-focusable wrapper. Gating it on mode left a read-only
+ // collaborator already in Follow with no explanation anywhere.
+ const showDeniedHint =
+ !showSwitchToPullOnly && !showReconnect && isPushDenied && !notFoundAsIdentity;
// Full sync would immediately fail-and-pause for a genuine read-only user, so
// don't offer it. Signed-out denial is excluded — that user may well have push
- // access once they authenticate, so Full stays reachable for them.
+ // access once they authenticate, so Full stays reachable for them. The
+ // masquerade is excluded too: its probe also answers `denied`, but greying
+ // Full out behind permission copy would state a cause the 404 doesn't prove
+ // — and it would single out Full when Follow fetches the same unseeable
+ // repo, implying a mode choice can rescue this.
const genuineReadOnlyDenied =
status?.pushPermission?.checkStatus === 'denied' &&
- status.pushPermission.deniedReason !== 'not-authenticated';
- // A non-permission pause reason (protected-branch, dirty-tree, …) — reachable
- // only under full sync. Suppressed when the switch-to-pull-only affordance
- // already explains a paused full-sync engine.
- const pausedNotice =
- showSwitchToPullOnly || isPushDenied || !status?.pausedReason
- ? null
- : formatPausedReason(status.pausedReason);
+ status.pushPermission.deniedReason !== 'not-authenticated' &&
+ !notFoundAsIdentity;
+ // The masquerade parks as auth-error, whose paused label reads "Reconnect
+ // required" — the prescription every other surface withdraws for it — so it
+ // shows the failure's own copy instead. Keyed on the same (pausedReason,
+ // error-code) pair the badge uses, not on the code alone: a different pause
+ // reason carrying a stale not-found code would otherwise make Settings and
+ // the badge describe one status object differently. It wins over the
+ // push-denied suppression below, since the probe against an unseeable repo
+ // also answers `denied` and would otherwise leave only permission copy.
+ // Shared with the badge so the two surfaces cannot drift apart.
+ const parkedOnNotFound = isParkedOnNotFoundAsIdentity(status);
+ // Otherwise a non-permission pause reason (protected-branch, dirty-tree, …),
+ // reachable only under full sync — suppressed while a push-denied affordance
+ // already explains the paused engine (`showSwitchToPullOnly` is a strict
+ // refinement of `isPushDenied`, so testing the latter covers both).
+ const pausedNotice = !status?.pausedReason
+ ? null
+ : parkedOnNotFound
+ ? formatSyncFailureCode('auth-not-found-as-identity')
+ : isPushDenied
+ ? null
+ : formatPausedReason(status.pausedReason);
function onModeChange(next: string) {
// Radix single ToggleGroup emits '' when the active item is re-pressed
@@ -302,14 +338,19 @@ export function SyncSection() {
<Tooltip>
<TooltipTrigger asChild>
{/* A disabled button emits no pointer events, so the tooltip
- hangs off a wrapper span that still receives hover — the
- only way to surface why Full is greyed out. Keyboard users
- get the same reason from the read-only hint text below. */}
+ hangs off a wrapper span that still receives hover. Radix
+ also drops a disabled item from the roving tab order, so
+ the tooltip is pointer-only — `aria-describedby` points
+ at the plain-text reason below so it reaches assistive
+ tech regardless of which siblings render. */}
<span className="inline-flex">
<ToggleGroupItem
value="full"
className={SYNC_SELECTED_TOGGLE_CLASS}
disabled
+ aria-describedby={
+ showDeniedHint ? 'settings-sync-denied-hint-text' : undefined
+ }
data-testid="settings-sync-mode-full"
>
<Trans>Full</Trans>
@@ -317,7 +358,7 @@ export function SyncSection() {
</span>
</TooltipTrigger>
<TooltipContent data-testid="settings-sync-mode-full-tip">
- <Trans>You don't have permission to push to this repo</Trans>
+ <Trans>You don't have permission to push to this repo.</Trans>
</TooltipContent>
</Tooltip>
) : (
@@ -368,18 +409,25 @@ export function SyncSection() {
</Button>
</div>
)}
- {!showSwitchToPullOnly && !showReconnect && isPushDenied && localMode !== 'follow' && (
- // Push-denied and not yet following: point the receiver at pull-only,
- // which the mode control above already offers. Suppressed for the
- // signed-out shape — permission is unknowable until they sign in.
+ {showDeniedHint && (
+ // Suppressed for the signed-out shape — permission is unknowable
+ // until they sign in — and for the not-found masquerade, where
+ // Follow fails on the same invisible repo. The `id` is what the
+ // disabled Full item points at via `aria-describedby`, so the reason
+ // travels with the control instead of depending on siblings.
<p
+ id="settings-sync-denied-hint-text"
className="text-1sm text-muted-foreground mt-2"
data-testid="settings-sync-denied-hint"
>
- <Trans>
- You don't have permission to push to this repo. Follow can still keep your copy up to
- date.
- </Trans>
+ {localMode === 'follow' ? (
+ <Trans>You don't have permission to push to this repo.</Trans>
+ ) : (
+ <Trans>
+ You don't have permission to push to this repo. Follow can still keep your copy up
+ to date.
+ </Trans>
+ )}
</p>
)}
{pausedNotice !== null && (
@@ -387,6 +435,23 @@ export function SyncSection() {
{pausedNotice}
</p>
)}
+ {/* A notice naming an account problem must name the account. Gated on
+ any denial that produced a notice above, not just the masquerade:
+ the badge appends the same tail after EVERY denial reason, on the
+ grounds that a read-only verdict is exactly as account-dependent
+ as a private-repo 404. One testid on the wrapper — the tail is up
+ to two sentences (the account used, and the declared-account
+ miss), which is the shape this feature exists to surface. */}
+ {status?.pushPermission?.checkStatus === 'denied' &&
+ (parkedOnNotFound || showSwitchToPullOnly || showDeniedHint) ? (
+ <div className="mt-2 space-y-1" data-testid="settings-sync-identity">
+ {formatDeniedIdentitySentences(status.pushPermission).map((sentence) => (
+ <p key={sentence} className="text-1sm text-muted-foreground">
+ {sentence}
+ </p>
+ ))}
+ </div>
+ ) : null}
{shouldOfferSignInAgain(status?.pushPermission) && (
// Probe-401 ('unknown/token-invalid') surfaces a Sign in again
// affordance without disabling sync. Mirrors the popover so both
diff --git a/packages/app/src/lib/share/branch-switch-flow.test.ts b/packages/app/src/lib/share/branch-switch-flow.test.ts
index 99a1b6c94..464a046d1 100644
--- a/packages/app/src/lib/share/branch-switch-flow.test.ts
+++ b/packages/app/src/lib/share/branch-switch-flow.test.ts
@@ -689,6 +689,21 @@ describe('applyWorktreeCheckoutOutcome (worktree leg)', () => {
test('fetch-failed without the flag leaves authFailed unset (network case keeps the retry copy)', () => {
const result = applyWorktreeCheckoutOutcome(creating, { ok: false, reason: 'fetch-failed' });
expect(result.sideEffect?.authFailed).toBeUndefined();
+ expect(result.sideEffect?.notFoundAsIdentity).toBeUndefined();
+ });
+
+ // The repository-not-found masquerade is neither a connection problem nor
+ // sign-in-fixable, so it rides its own flag — the toast names what is
+ // actually known instead of blaming the network.
+ test('fetch-failed carrying notFoundAsIdentity propagates the flag for the not-found copy', () => {
+ const result = applyWorktreeCheckoutOutcome(creating, {
+ ok: false,
+ reason: 'fetch-failed',
+ notFoundAsIdentity: true,
+ });
+ expect(result.state).toEqual({ phase: 'ready', info: cleanInfo() });
+ expect(result.sideEffect?.notFoundAsIdentity).toBe(true);
+ expect(result.sideEffect?.authFailed).toBeUndefined();
});
test('a non-fetch reason can never carry authFailed through the reducer', () => {
diff --git a/packages/app/src/lib/share/branch-switch-flow.ts b/packages/app/src/lib/share/branch-switch-flow.ts
index 423782616..91d579295 100644
--- a/packages/app/src/lib/share/branch-switch-flow.ts
+++ b/packages/app/src/lib/share/branch-switch-flow.ts
@@ -584,6 +584,10 @@ export interface ApplyWorktreeCheckoutOutcomeResult {
* for sign-in copy plus a Sign in action — retrying without a credential
* just fails again. */
readonly authFailed?: true;
+ /** Set iff `reason === 'fetch-failed'` hit the repository-not-found
+ * masquerade: the remote answered, so the connection copy is wrong and a
+ * Sign in cannot fix a repo the account can't see (or that is gone). */
+ readonly notFoundAsIdentity?: true;
};
}
@@ -632,9 +636,10 @@ export function applyWorktreeCheckoutOutcome(
kind: 'toast',
reason: result.reason,
helper: result.helper,
- // Only `fetch-failed` carries this (its own arm on WorktreeCreateResult);
+ // Only `fetch-failed` carries these (its own arm on WorktreeCreateResult);
// every other reason narrows to `undefined` here.
authFailed: result.reason === 'fetch-failed' ? result.authFailed : undefined,
+ notFoundAsIdentity: result.reason === 'fetch-failed' ? result.notFoundAsIdentity : undefined,
},
};
}
diff --git a/packages/app/src/locales/ar/messages.json b/packages/app/src/locales/ar/messages.json
index 63e50468c..23cd243ad 100644
--- a/packages/app/src/locales/ar/messages.json
+++ b/packages/app/src/locales/ar/messages.json
@@ -1116,6 +1116,11 @@
"CGj3gX": ["خطأ في التحليل"],
"CHfFN_": ["إزالة OpenKnowledge من ", ["0"]],
"CKyk7Q": ["رجوع"],
+ "CMd-g-": [
+ "عنوان URL البعيد لديك يشير إلى ",
+ ["declaredLogin"],
+ "، لكن تعذّر استخدام بيانات اعتماد ذلك الحساب."
+ ],
"CMyafZ": ["قيمة ", ["slot"], " الست عشرية"],
"COr1Y7": ["اختر <0>openknowledge.skill</0> من مجلد <1>التنزيلات</1> لديك. يُفعَّل تلقائيًا."],
"CPMLsP": ["مراجعة ما تضيفه هذه الحزمة"],
@@ -1144,7 +1149,6 @@
],
"C_cPoW": ["انتهت صلاحية جلسة GitHub لديك — سجّل الدخول مرة أخرى للتحقق من صلاحية الدفع."],
"CcaU4i": ["تُطبّق التعديلات مباشرة وتُحفظ تلقائيًا في هذه السمة."],
- "ChAtFg": ["ليس لديك إذن بالدفع إلى هذا المستودع"],
"ChMshD": ["إنهاء ", ["appName"]],
"Ck9XRt": ["تعذّر حفظ المفتاح — يرجى المحاولة مرة أخرى."],
"ClII5l": ["اضغط على الشمس أو القمر بجوار «مخصص» أعلاه لاستخدام هذه السمة."],
@@ -1334,6 +1338,7 @@
"تعليقاتك في الانتظار خلف الدور الجاري — تبقى في الطابور إلى أن يلتقط الوكيل الرسالة."
],
"Eji13z": ["بدّل تنسيق التظليل."],
+ "EkEFE3": ["لم يُعثر على المستودع"],
"EkH9pt": ["تحديث"],
"EkUnmS": ["أي"],
"El7NbA": ["عنوان 2"],
@@ -1472,6 +1477,11 @@
"G8t9NN": ["إضافة خاصية"],
"GA-UkN": ["نوع ", ["keyName"], ": ", ["typeLabel"], ". انقر للتغيير."],
"GAohqx": ["حذف العمود"],
+ "GBEqoP": [
+ "إعدادات Git لديك تشير إلى ",
+ ["declaredLogin"],
+ "، لكن تعذّر استخدام بيانات اعتماد ذلك الحساب."
+ ],
"GBQjiV": ["إضافة مهارة"],
"GDvlUT": ["الدور"],
"GGsM4y": ["محدَّد في الرسم البياني"],
@@ -3135,6 +3145,7 @@
"ZGVsOD": ["ادفع هذا الفرع إلى GitHub قبل المشاركة."],
"ZI8uvA": ["لم يُعثر على مشكلات."],
"ZJ99sD": ["إدراج عمود إلى اليسار"],
+ "ZKVuLY": ["تمت المصادقة باسم ", ["login"], "."],
"ZNK2Tq": ["الجذر"],
"ZOVgDv": ["تم نقل ", ["moved"], " مهارات إلى المشروع"],
"ZQJ1IV": ["تنشيط آخر تبويب في المحرر."],
@@ -3335,6 +3346,11 @@
],
"ajz9F8": ["تعذّر تحميل محتوى التعارض لـ ", ["filePath"], ". حاول إعادة تحميل الصفحة."],
"ak4LLg": ["مسح القائمة"],
+ "akOe4q": [
+ "إعدادات بيانات اعتماد Git لديك تشير إلى ",
+ ["declaredLogin"],
+ "، لكن تعذّر استخدام بيانات اعتماد ذلك الحساب."
+ ],
"akmOT9": ["تحرير هذا التعليق"],
"an0aL5": ["اسأل وكيلًا"],
"anmUZq": ["ينقصه ميزة"],
@@ -4093,6 +4109,9 @@
"jPUPvG": ["تعذّر حل التعارض في ", ["filePath"], "."],
"jRAGrQ": ["إعداد الوكلاء"],
"jRHdCz": ["فشل تحميل ملف PDF"],
+ "jRsjlF": [
+ "لم يُعثر على المستودع — ربما لا يكون موجودًا، أو ربما لا يملك الحساب المستخدم صلاحية الوصول."
+ ],
"jSO1X5": ["لا يمكن إعادة تسمية القوالب الموروثة هنا — أعد تسميتها في المجلد الذي يملكها."],
"jSY41h": ["استغرق «", ["docName"], "» وقتًا طويلًا. تحقق من اتصالك."],
"jTLWxh": ["ضمّن صفحة خارجية في إطار مضمَّن (مستندات، عروض، Figma، CodeSandbox)."],
diff --git a/packages/app/src/locales/ar/messages.po b/packages/app/src/locales/ar/messages.po
index caf1e02bc..dee9dfaf4 100644
--- a/packages/app/src/locales/ar/messages.po
+++ b/packages/app/src/locales/ar/messages.po
@@ -1959,6 +1959,10 @@ msgstr "المرفقات"
msgid "Attachments must total under 3 MB."
msgstr "يجب أن يقل إجمالي المرفقات عن 3 ميغابايت."
+#: src/components/SyncStatusBadge.tsx
+msgid "Authenticated as {login}."
+msgstr "تمت المصادقة باسم {login}."
+
#: src/editor/slash-command/component-items.tsx
msgid "Authoritative content; mirrored verbatim everywhere it's referenced."
msgstr "محتوى مرجعي؛ يُعكس حرفيًا في كل مكان يُشار إليه فيه."
@@ -10822,6 +10826,15 @@ msgstr "المستودع"
msgid "Repository name"
msgstr "اسم المستودع"
+#: src/components/SyncStatusBadge.tsx
+msgid "Repository not found"
+msgstr "لم يُعثر على المستودع"
+
+#: src/components/ShareBranchSwitchDialog.tsx
+#: src/components/SyncStatusBadge.tsx
+msgid "Repository not found — it may not exist, or the account used may not have access."
+msgstr "لم يُعثر على المستودع — ربما لا يكون موجودًا، أو ربما لا يملك الحساب المستخدم صلاحية الوصول."
+
#: src/components/SyncStatusBadge.tsx
msgid "Repository not found. It may have been renamed, deleted, or moved."
msgstr "لم يُعثر على المستودع. ربما أُعيدت تسميته أو حُذف أو نُقل."
@@ -14802,10 +14815,6 @@ msgid "You don't have access to this repository."
msgstr "ليس لديك صلاحية الوصول إلى هذا المستودع."
#: src/components/settings/SyncSection.tsx
-#: src/components/SyncStatusBadge.tsx
-msgid "You don't have permission to push to this repo"
-msgstr "ليس لديك إذن بالدفع إلى هذا المستودع"
-
#: src/components/SyncStatusBadge.tsx
msgid "You don't have permission to push to this repo."
msgstr "ليس لديك إذن بالدفع إلى هذا المستودع."
@@ -14888,6 +14897,14 @@ msgstr "تُحفظ نسختك الحالية أولًا، فهذا قابل لل
msgid "Your edits stay on this computer"
msgstr "تبقى تعديلاتك على هذا الجهاز"
+#: src/components/SyncStatusBadge.tsx
+msgid "Your Git configuration names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "إعدادات Git لديك تشير إلى {declaredLogin}، لكن تعذّر استخدام بيانات اعتماد ذلك الحساب."
+
+#: src/components/SyncStatusBadge.tsx
+msgid "Your Git credential configuration names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "إعدادات بيانات اعتماد Git لديك تشير إلى {declaredLogin}، لكن تعذّر استخدام بيانات اعتماد ذلك الحساب."
+
#: src/components/settings/SyncSection.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Your GitHub session expired — sign in again to verify push access."
@@ -14925,6 +14942,10 @@ msgstr "نسختك المحلية من الفرع <0>{branch}</0> متأخرة.
msgid "Your message didn't reach {agentName}."
msgstr "لم تصل رسالتك إلى {agentName}."
+#: src/components/SyncStatusBadge.tsx
+msgid "Your remote URL names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "عنوان URL البعيد لديك يشير إلى {declaredLogin}، لكن تعذّر استخدام بيانات اعتماد ذلك الحساب."
+
#: src/components/BugReportSendToast.tsx
msgid "Your report is saved on this computer, so nothing was lost."
msgstr "تقريرك محفوظ على هذا الحاسوب، فلم يُفقد شيء."
diff --git a/packages/app/src/locales/bn/messages.json b/packages/app/src/locales/bn/messages.json
index c375ae7ef..bf659576a 100644
--- a/packages/app/src/locales/bn/messages.json
+++ b/packages/app/src/locales/bn/messages.json
@@ -917,6 +917,11 @@
"CGj3gX": ["পার্স ত্রুটি"],
"CHfFN_": [["0"], " থেকে OpenKnowledge সরান"],
"CKyk7Q": ["ফিরে যান"],
+ "CMd-g-": [
+ "আপনার রিমোট URL-এ ",
+ ["declaredLogin"],
+ " উল্লেখ করা আছে, কিন্তু সেই অ্যাকাউন্টের ক্রেডেনশিয়াল ব্যবহার করা যায়নি।"
+ ],
"CMyafZ": [["slot"], " হেক্স মান"],
"COr1Y7": [
"আপনার <1>Downloads</1> ফোল্ডার থেকে <0>openknowledge.skill</0> বাছুন। এটি নিজে থেকেই চালু হয়।"
@@ -947,7 +952,6 @@
],
"C_cPoW": ["আপনার GitHub সেশনের মেয়াদ শেষ — পুশের প্রবেশাধিকার যাচাই করতে আবার সাইন ইন করুন।"],
"CcaU4i": ["সম্পাদনাগুলি সঙ্গে সঙ্গে প্রয়োগ হয় এবং এই থিমে স্বয়ংক্রিয়ভাবে সংরক্ষিত হয়।"],
- "ChAtFg": ["এই রিপোজিটরিতে পুশ করার অনুমতি আপনার নেই"],
"ChMshD": [["appName"], " থেকে প্রস্থান"],
"Ck9XRt": ["কী সংরক্ষণ করা যায়নি — অনুগ্রহ করে আবার চেষ্টা করুন।"],
"ClII5l": ["এই থিম ব্যবহার করতে উপরের “কাস্টম”-এ সূর্য বা চাঁদ চাপুন।"],
@@ -1115,6 +1119,7 @@
"আপনার মন্তব্যগুলি চলমান টার্নের পিছনে অপেক্ষা করছে — এজেন্ট বার্তাটি না নেওয়া পর্যন্ত সেগুলি সারিতে থাকে।"
],
"Eji13z": ["হাইলাইট বিন্যাস চালু বা বন্ধ করুন।"],
+ "EkEFE3": ["রিপোজিটরি পাওয়া যায়নি"],
"EkH9pt": ["হালনাগাদ করুন"],
"EkUnmS": ["যেকোনো"],
"El7NbA": ["শিরোনাম ২"],
@@ -1246,6 +1251,11 @@
"G8t9NN": ["একটি প্রপার্টি যোগ করুন"],
"GA-UkN": [["keyName"], " ধরন: ", ["typeLabel"], "। বদলাতে ক্লিক করুন।"],
"GAohqx": ["কলাম মুছুন"],
+ "GBEqoP": [
+ "আপনার Git কনফিগারেশনে ",
+ ["declaredLogin"],
+ " উল্লেখ করা আছে, কিন্তু সেই অ্যাকাউন্টের ক্রেডেনশিয়াল ব্যবহার করা যায়নি।"
+ ],
"GBQjiV": ["স্কিল যোগ করুন"],
"GDvlUT": ["ভূমিকা"],
"GGsM4y": ["গ্রাফে নির্বাচিত"],
@@ -2658,6 +2668,7 @@
"ZGVsOD": ["শেয়ার করার আগে এই ব্রাঞ্চটি GitHub-এ পুশ করুন।"],
"ZI8uvA": ["কোনো সমস্যা পাওয়া যায়নি।"],
"ZJ99sD": ["বাঁয়ে কলাম যোগ করুন"],
+ "ZKVuLY": [["login"], " হিসেবে প্রমাণীকৃত।"],
"ZNK2Tq": ["রুট"],
"ZOVgDv": [["moved"], "টি স্কিল প্রকল্পে সরানো হয়েছে"],
"ZQJ1IV": ["শেষ সম্পাদক ট্যাব সক্রিয় করুন।"],
@@ -2840,6 +2851,11 @@
],
"ajz9F8": [["filePath"], "-এর দ্বন্দ্বের বিষয়বস্তু লোড করা যায়নি। পাতাটি আবার লোড করে দেখুন।"],
"ak4LLg": ["মেনু মুছুন"],
+ "akOe4q": [
+ "আপনার Git ক্রেডেনশিয়াল কনফিগারেশনে ",
+ ["declaredLogin"],
+ " উল্লেখ করা আছে, কিন্তু সেই অ্যাকাউন্টের ক্রেডেনশিয়াল ব্যবহার করা যায়নি।"
+ ],
"akmOT9": ["এই মন্তব্যটি সম্পাদনা করুন"],
"an0aL5": ["একটি এজেন্টকে জিজ্ঞেস করুন"],
"anmUZq": ["একটি বৈশিষ্ট্য অনুপস্থিত"],
@@ -3479,6 +3495,7 @@
"jPUPvG": [["filePath"], "-এর দ্বন্দ্ব মীমাংসা করা যায়নি।"],
"jRAGrQ": ["এজেন্ট কনফিগার করুন"],
"jRHdCz": ["PDF লোড করতে ব্যর্থ"],
+ "jRsjlF": ["রিপোজিটরি পাওয়া যায়নি — হয়তো এটি নেই, অথবা ব্যবহৃত অ্যাকাউন্টের প্রবেশাধিকার নেই।"],
"jSO1X5": ["উত্তরাধিকারসূত্রে পাওয়া টেমপ্লেটের নাম এখানে বদলানো যায় না — যে ফোল্ডারের এটি, সেখানেই নাম বদলান।"],
"jSY41h": ["\"", ["docName"], "\" খুব বেশি সময় নিয়েছে। আপনার সংযোগ দেখুন।"],
"jTLWxh": ["একটি বাইরের পাতা ইনলাইন iframe-এ এমবেড করুন (নথি, ডেমো, Figma, CodeSandbox)।"],
diff --git a/packages/app/src/locales/bn/messages.po b/packages/app/src/locales/bn/messages.po
index b2f2194bc..eb387cc9f 100644
--- a/packages/app/src/locales/bn/messages.po
+++ b/packages/app/src/locales/bn/messages.po
@@ -1955,6 +1955,10 @@ msgstr "সংযুক্তি"
msgid "Attachments must total under 3 MB."
msgstr "সংযুক্তির মোট আকার ৩ MB-র কম হতে হবে।"
+#: src/components/SyncStatusBadge.tsx
+msgid "Authenticated as {login}."
+msgstr "{login} হিসেবে প্রমাণীকৃত।"
+
#: src/editor/slash-command/component-items.tsx
msgid "Authoritative content; mirrored verbatim everywhere it's referenced."
msgstr "প্রামাণিক বিষয়বস্তু; যেখানেই উল্লেখ করা হোক হুবহু প্রতিফলিত।"
@@ -10818,6 +10822,15 @@ msgstr "রিপোজিটরি"
msgid "Repository name"
msgstr "রিপোজিটরির নাম"
+#: src/components/SyncStatusBadge.tsx
+msgid "Repository not found"
+msgstr "রিপোজিটরি পাওয়া যায়নি"
+
+#: src/components/ShareBranchSwitchDialog.tsx
+#: src/components/SyncStatusBadge.tsx
+msgid "Repository not found — it may not exist, or the account used may not have access."
+msgstr "রিপোজিটরি পাওয়া যায়নি — হয়তো এটি নেই, অথবা ব্যবহৃত অ্যাকাউন্টের প্রবেশাধিকার নেই।"
+
#: src/components/SyncStatusBadge.tsx
msgid "Repository not found. It may have been renamed, deleted, or moved."
msgstr "রিপোজিটরি পাওয়া যায়নি। হয়তো এর নাম বদলানো হয়েছে, মুছে ফেলা হয়েছে, বা সরানো হয়েছে।"
@@ -14798,10 +14811,6 @@ msgid "You don't have access to this repository."
msgstr "এই রিপোজিটরিতে আপনার প্রবেশাধিকার নেই।"
#: src/components/settings/SyncSection.tsx
-#: src/components/SyncStatusBadge.tsx
-msgid "You don't have permission to push to this repo"
-msgstr "এই রিপোজিটরিতে পুশ করার অনুমতি আপনার নেই"
-
#: src/components/SyncStatusBadge.tsx
msgid "You don't have permission to push to this repo."
msgstr "এই রিপোজিটরিতে পুশ করার অনুমতি আপনার নেই।"
@@ -14884,6 +14893,14 @@ msgstr "আপনার বর্তমান সংস্করণটি আগ
msgid "Your edits stay on this computer"
msgstr "আপনার সম্পাদনা এই কম্পিউটারেই থাকে"
+#: src/components/SyncStatusBadge.tsx
+msgid "Your Git configuration names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "আপনার Git কনফিগারেশনে {declaredLogin} উল্লেখ করা আছে, কিন্তু সেই অ্যাকাউন্টের ক্রেডেনশিয়াল ব্যবহার করা যায়নি।"
+
+#: src/components/SyncStatusBadge.tsx
+msgid "Your Git credential configuration names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "আপনার Git ক্রেডেনশিয়াল কনফিগারেশনে {declaredLogin} উল্লেখ করা আছে, কিন্তু সেই অ্যাকাউন্টের ক্রেডেনশিয়াল ব্যবহার করা যায়নি।"
+
#: src/components/settings/SyncSection.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Your GitHub session expired — sign in again to verify push access."
@@ -14921,6 +14938,10 @@ msgstr "ব্রাঞ্চ <0>{branch}</0>-এর আপনার স্থ
msgid "Your message didn't reach {agentName}."
msgstr "আপনার বার্তা {agentName}-এ পৌঁছায়নি।"
+#: src/components/SyncStatusBadge.tsx
+msgid "Your remote URL names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "আপনার রিমোট URL-এ {declaredLogin} উল্লেখ করা আছে, কিন্তু সেই অ্যাকাউন্টের ক্রেডেনশিয়াল ব্যবহার করা যায়নি।"
+
#: src/components/BugReportSendToast.tsx
msgid "Your report is saved on this computer, so nothing was lost."
msgstr "আপনার রিপোর্ট এই কম্পিউটারে সংরক্ষিত আছে, তাই কিছুই হারায়নি।"
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 8ab6f022d..5c7f5ae16 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -947,6 +947,11 @@
"CGj3gX": ["parse error"],
"CHfFN_": ["Remove OpenKnowledge from ", ["0"]],
"CKyk7Q": ["Go back"],
+ "CMd-g-": [
+ "Your remote URL names ",
+ ["declaredLogin"],
+ ", but that account's credentials couldn't be used."
+ ],
"CMyafZ": [["slot"], " hex value"],
"COr1Y7": [
"Pick <0>openknowledge.skill</0> from your <1>Downloads</1> folder. It enables automatically."
@@ -977,7 +982,6 @@
],
"C_cPoW": ["Your GitHub session expired — sign in again to verify push access."],
"CcaU4i": ["Edits apply live and save automatically to this theme."],
- "ChAtFg": ["You don't have permission to push to this repo"],
"ChMshD": ["Quit ", ["appName"]],
"Ck9XRt": ["Couldn't save the key — please try again."],
"ClII5l": ["Press the sun or moon on “Custom” above to use this theme."],
@@ -1143,6 +1147,7 @@
"Your comments are waiting behind the running turn — they stay queued until the agent picks the message up."
],
"Eji13z": ["Toggle highlight formatting."],
+ "EkEFE3": ["Repository not found"],
"EkH9pt": ["Update"],
"EkUnmS": ["any"],
"El7NbA": ["Heading 2"],
@@ -1274,6 +1279,11 @@
"G8t9NN": ["Add a property"],
"GA-UkN": [["keyName"], " type: ", ["typeLabel"], ". Click to change."],
"GAohqx": ["Delete column"],
+ "GBEqoP": [
+ "Your Git configuration names ",
+ ["declaredLogin"],
+ ", but that account's credentials couldn't be used."
+ ],
"GBQjiV": ["Add skill"],
"GDvlUT": ["Role"],
"GGsM4y": ["Selected in graph"],
@@ -2718,6 +2728,7 @@
"ZGVsOD": ["Push this branch to GitHub before sharing."],
"ZI8uvA": ["No problems found."],
"ZJ99sD": ["Insert column left"],
+ "ZKVuLY": ["Authenticated as ", ["login"], "."],
"ZNK2Tq": ["root"],
"ZOVgDv": ["Moved ", ["moved"], " skills to Project"],
"ZQJ1IV": ["Activate the last editor tab."],
@@ -2901,6 +2912,11 @@
],
"ajz9F8": ["Couldn't load conflict content for ", ["filePath"], ". Try reloading the page."],
"ak4LLg": ["Clear menu"],
+ "akOe4q": [
+ "Your Git credential configuration names ",
+ ["declaredLogin"],
+ ", but that account's credentials couldn't be used."
+ ],
"akmOT9": ["Edit this comment"],
"an0aL5": ["Ask an agent"],
"anmUZq": ["Missing a feature"],
@@ -3583,6 +3599,7 @@
"jPUPvG": ["Couldn't resolve the conflict for ", ["filePath"], "."],
"jRAGrQ": ["Configure agents"],
"jRHdCz": ["Failed to load PDF"],
+ "jRsjlF": ["Repository not found — it may not exist, or the account used may not have access."],
"jSO1X5": ["Inherited templates can't be renamed here — rename it in the folder that owns it."],
"jSY41h": ["\"", ["docName"], "\" took too long. Check your connection."],
"jTLWxh": ["Embed an external page in an inline iframe (docs, demos, Figma, CodeSandbox)."],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index 5121e93f2..76c3e0af9 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -1959,6 +1959,10 @@ msgstr "Attachments"
msgid "Attachments must total under 3 MB."
msgstr "Attachments must total under 3 MB."
+#: src/components/SyncStatusBadge.tsx
+msgid "Authenticated as {login}."
+msgstr "Authenticated as {login}."
+
#: src/editor/slash-command/component-items.tsx
msgid "Authoritative content; mirrored verbatim everywhere it's referenced."
msgstr "Authoritative content; mirrored verbatim everywhere it's referenced."
@@ -10822,6 +10826,15 @@ msgstr "Repository"
msgid "Repository name"
msgstr "Repository name"
+#: src/components/SyncStatusBadge.tsx
+msgid "Repository not found"
+msgstr "Repository not found"
+
+#: src/components/ShareBranchSwitchDialog.tsx
+#: src/components/SyncStatusBadge.tsx
+msgid "Repository not found — it may not exist, or the account used may not have access."
+msgstr "Repository not found — it may not exist, or the account used may not have access."
+
#: src/components/SyncStatusBadge.tsx
msgid "Repository not found. It may have been renamed, deleted, or moved."
msgstr "Repository not found. It may have been renamed, deleted, or moved."
@@ -14802,10 +14815,6 @@ msgid "You don't have access to this repository."
msgstr "You don't have access to this repository."
#: src/components/settings/SyncSection.tsx
-#: src/components/SyncStatusBadge.tsx
-msgid "You don't have permission to push to this repo"
-msgstr "You don't have permission to push to this repo"
-
#: src/components/SyncStatusBadge.tsx
msgid "You don't have permission to push to this repo."
msgstr "You don't have permission to push to this repo."
@@ -14888,6 +14897,14 @@ msgstr "Your current version is saved first, so this is reversible."
msgid "Your edits stay on this computer"
msgstr "Your edits stay on this computer"
+#: src/components/SyncStatusBadge.tsx
+msgid "Your Git configuration names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "Your Git configuration names {declaredLogin}, but that account's credentials couldn't be used."
+
+#: src/components/SyncStatusBadge.tsx
+msgid "Your Git credential configuration names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "Your Git credential configuration names {declaredLogin}, but that account's credentials couldn't be used."
+
#: src/components/settings/SyncSection.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Your GitHub session expired — sign in again to verify push access."
@@ -14925,6 +14942,10 @@ msgstr "Your local copy of branch <0>{branch}</0> is behind. Pull the latest cha
msgid "Your message didn't reach {agentName}."
msgstr "Your message didn't reach {agentName}."
+#: src/components/SyncStatusBadge.tsx
+msgid "Your remote URL names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "Your remote URL names {declaredLogin}, but that account's credentials couldn't be used."
+
#: src/components/BugReportSendToast.tsx
msgid "Your report is saved on this computer, so nothing was lost."
msgstr "Your report is saved on this computer, so nothing was lost."
diff --git a/packages/app/src/locales/es/messages.json b/packages/app/src/locales/es/messages.json
index eceda2603..e1ed2b97f 100644
--- a/packages/app/src/locales/es/messages.json
+++ b/packages/app/src/locales/es/messages.json
@@ -1124,6 +1124,11 @@
"CGj3gX": ["error de análisis"],
"CHfFN_": ["Quitar OpenKnowledge de ", ["0"]],
"CKyk7Q": ["Volver"],
+ "CMd-g-": [
+ "Tu URL remota indica ",
+ ["declaredLogin"],
+ ", pero no se pudieron usar las credenciales de esa cuenta."
+ ],
"CMyafZ": ["Valor hexadecimal de ", ["slot"]],
"COr1Y7": [
"Elige <0>openknowledge.skill</0> en tu carpeta <1>Descargas</1>. Se activa automáticamente."
@@ -1156,7 +1161,6 @@
"Tu sesión de GitHub ha caducado: inicia sesión de nuevo para verificar el acceso de push."
],
"CcaU4i": ["Los cambios se aplican al instante y se guardan automáticamente en este tema."],
- "ChAtFg": ["No tienes permiso para hacer push a este repositorio"],
"ChMshD": ["Salir de ", ["appName"]],
"Ck9XRt": ["No se pudo guardar la clave; inténtalo de nuevo."],
"ClII5l": ["Pulsa el sol o la luna de “Custom” arriba para usar este tema."],
@@ -1340,6 +1344,7 @@
"Tus comentarios están esperando detrás del turno en curso: permanecen en cola hasta que el agente recoja el mensaje."
],
"Eji13z": ["Activa o desactiva el resaltado."],
+ "EkEFE3": ["No se encontró el repositorio"],
"EkH9pt": ["Actualizar"],
"EkUnmS": ["cualquiera"],
"El7NbA": ["Encabezado 2"],
@@ -1485,6 +1490,11 @@
"G8t9NN": ["Añadir una propiedad"],
"GA-UkN": ["Tipo de ", ["keyName"], ": ", ["typeLabel"], ". Haz clic para cambiarlo."],
"GAohqx": ["Eliminar columna"],
+ "GBEqoP": [
+ "Tu configuración de Git indica ",
+ ["declaredLogin"],
+ ", pero no se pudieron usar las credenciales de esa cuenta."
+ ],
"GBQjiV": ["Añadir habilidad"],
"GDvlUT": ["Función"],
"GGsM4y": ["Seleccionado en el grafo"],
@@ -3181,6 +3191,7 @@
"ZGVsOD": ["Envía esta rama a GitHub antes de compartir."],
"ZI8uvA": ["No se encontraron problemas."],
"ZJ99sD": ["Insertar columna a la izquierda"],
+ "ZKVuLY": ["Autenticado como ", ["login"], "."],
"ZNK2Tq": ["raíz"],
"ZOVgDv": [["moved"], " habilidades movidas a Proyecto"],
"ZQJ1IV": ["Activa la última pestaña del editor."],
@@ -3383,6 +3394,11 @@
". Prueba a recargar la página."
],
"ak4LLg": ["Vaciar menú"],
+ "akOe4q": [
+ "Tu configuración de credenciales de Git indica ",
+ ["declaredLogin"],
+ ", pero no se pudieron usar las credenciales de esa cuenta."
+ ],
"akmOT9": ["Editar este comentario"],
"an0aL5": ["Preguntar a un agente"],
"anmUZq": ["Faltaba una función"],
@@ -4182,6 +4198,9 @@
"jPUPvG": ["No se pudo resolver el conflicto de ", ["filePath"], "."],
"jRAGrQ": ["Configurar agentes"],
"jRHdCz": ["No se pudo cargar el PDF"],
+ "jRsjlF": [
+ "No se encontró el repositorio: puede que no exista o que la cuenta utilizada no tenga acceso."
+ ],
"jSO1X5": [
"Las plantillas heredadas no se pueden renombrar aquí: hazlo en la carpeta que las contiene."
],
diff --git a/packages/app/src/locales/es/messages.po b/packages/app/src/locales/es/messages.po
index 9f700f660..2f560a157 100644
--- a/packages/app/src/locales/es/messages.po
+++ b/packages/app/src/locales/es/messages.po
@@ -1959,6 +1959,10 @@ msgstr "Adjuntos"
msgid "Attachments must total under 3 MB."
msgstr "Los adjuntos deben sumar menos de 3 MB."
+#: src/components/SyncStatusBadge.tsx
+msgid "Authenticated as {login}."
+msgstr "Autenticado como {login}."
+
#: src/editor/slash-command/component-items.tsx
msgid "Authoritative content; mirrored verbatim everywhere it's referenced."
msgstr "Contenido autoritativo; se replica literalmente allí donde se referencia."
@@ -10822,6 +10826,15 @@ msgstr "Repositorio"
msgid "Repository name"
msgstr "Nombre del repositorio"
+#: src/components/SyncStatusBadge.tsx
+msgid "Repository not found"
+msgstr "No se encontró el repositorio"
+
+#: src/components/ShareBranchSwitchDialog.tsx
+#: src/components/SyncStatusBadge.tsx
+msgid "Repository not found — it may not exist, or the account used may not have access."
+msgstr "No se encontró el repositorio: puede que no exista o que la cuenta utilizada no tenga acceso."
+
#: src/components/SyncStatusBadge.tsx
msgid "Repository not found. It may have been renamed, deleted, or moved."
msgstr "No se encontró el repositorio. Puede que lo hayan renombrado, eliminado o movido."
@@ -14802,10 +14815,6 @@ msgid "You don't have access to this repository."
msgstr "No tienes acceso a este repositorio."
#: src/components/settings/SyncSection.tsx
-#: src/components/SyncStatusBadge.tsx
-msgid "You don't have permission to push to this repo"
-msgstr "No tienes permiso para hacer push a este repositorio"
-
#: src/components/SyncStatusBadge.tsx
msgid "You don't have permission to push to this repo."
msgstr "No tienes permiso para hacer push a este repositorio."
@@ -14888,6 +14897,14 @@ msgstr "Tu versión actual se guarda primero, así que esto es reversible."
msgid "Your edits stay on this computer"
msgstr "Tus ediciones se quedan en este equipo"
+#: src/components/SyncStatusBadge.tsx
+msgid "Your Git configuration names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "Tu configuración de Git indica {declaredLogin}, pero no se pudieron usar las credenciales de esa cuenta."
+
+#: src/components/SyncStatusBadge.tsx
+msgid "Your Git credential configuration names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "Tu configuración de credenciales de Git indica {declaredLogin}, pero no se pudieron usar las credenciales de esa cuenta."
+
#: src/components/settings/SyncSection.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Your GitHub session expired — sign in again to verify push access."
@@ -14925,6 +14942,10 @@ msgstr "Tu copia local de la rama <0>{branch}</0> está por detrás. Trae los ú
msgid "Your message didn't reach {agentName}."
msgstr "Tu mensaje no llegó a {agentName}."
+#: src/components/SyncStatusBadge.tsx
+msgid "Your remote URL names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "Tu URL remota indica {declaredLogin}, pero no se pudieron usar las credenciales de esa cuenta."
+
#: src/components/BugReportSendToast.tsx
msgid "Your report is saved on this computer, so nothing was lost."
msgstr "Tu informe está guardado en este equipo, así que no se perdió nada."
diff --git a/packages/app/src/locales/fr/messages.json b/packages/app/src/locales/fr/messages.json
index 5d064d7cc..d3d3228d7 100644
--- a/packages/app/src/locales/fr/messages.json
+++ b/packages/app/src/locales/fr/messages.json
@@ -1144,6 +1144,11 @@
"CGj3gX": ["erreur d'analyse"],
"CHfFN_": ["Retirer OpenKnowledge de ", ["0"]],
"CKyk7Q": ["Retour"],
+ "CMd-g-": [
+ "Votre URL distante indique ",
+ ["declaredLogin"],
+ ", mais les identifiants de ce compte n'ont pas pu être utilisés."
+ ],
"CMyafZ": ["Valeur hexadécimale de ", ["slot"]],
"COr1Y7": [
"Choisissez <0>openknowledge.skill</0> dans votre dossier <1>Téléchargements</1>. Elle s'active automatiquement."
@@ -1178,7 +1183,6 @@
"CcaU4i": [
"Les modifications s’appliquent immédiatement et sont automatiquement enregistrées dans ce thème."
],
- "ChAtFg": ["Vous n'avez pas la permission de pousser vers ce dépôt"],
"ChMshD": ["Quitter ", ["appName"]],
"Ck9XRt": ["Impossible d'enregistrer la clé — veuillez réessayer."],
"ClII5l": ["Appuyez sur le soleil ou la lune de « Custom » ci-dessus pour utiliser ce thème."],
@@ -1370,6 +1374,7 @@
"Vos commentaires attendent derrière le tour en cours : ils restent en file jusqu’à ce que l’agent récupère le message."
],
"Eji13z": ["Bascule la mise en forme surlignée."],
+ "EkEFE3": ["Dépôt introuvable"],
"EkH9pt": ["Mettre à jour"],
"EkUnmS": ["quelconque"],
"El7NbA": ["Titre 2"],
@@ -1512,6 +1517,11 @@
"G8t9NN": ["Ajouter une propriété"],
"GA-UkN": ["Type de ", ["keyName"], " : ", ["typeLabel"], ". Cliquez pour changer."],
"GAohqx": ["Supprimer la colonne"],
+ "GBEqoP": [
+ "Votre configuration Git indique ",
+ ["declaredLogin"],
+ ", mais les identifiants de ce compte n'ont pas pu être utilisés."
+ ],
"GBQjiV": ["Ajouter une compétence"],
"GDvlUT": ["Rôle"],
"GGsM4y": ["Sélectionné dans le graphe"],
@@ -3206,6 +3216,7 @@
"ZGVsOD": ["Envoyez cette branche sur GitHub avant de partager."],
"ZI8uvA": ["Aucun problème trouvé."],
"ZJ99sD": ["Insérer une colonne à gauche"],
+ "ZKVuLY": ["Authentifié en tant que ", ["login"], "."],
"ZNK2Tq": ["racine"],
"ZOVgDv": [["moved"], " compétences déplacées vers Projet"],
"ZQJ1IV": ["Active le dernier onglet de l'éditeur."],
@@ -3408,6 +3419,11 @@
". Essayez de recharger la page."
],
"ak4LLg": ["Effacer le menu"],
+ "akOe4q": [
+ "Votre configuration d'identifiants Git indique ",
+ ["declaredLogin"],
+ ", mais les identifiants de ce compte n'ont pas pu être utilisés."
+ ],
"akmOT9": ["Modifier ce commentaire"],
"an0aL5": ["Demander à un agent"],
"anmUZq": ["Une fonctionnalité manquante"],
@@ -4204,6 +4220,9 @@
"jPUPvG": ["Impossible de résoudre le conflit pour ", ["filePath"], "."],
"jRAGrQ": ["Configurer les agents"],
"jRHdCz": ["Échec du chargement du PDF"],
+ "jRsjlF": [
+ "Dépôt introuvable — il n'existe peut-être pas, ou le compte utilisé n'y a peut-être pas accès."
+ ],
"jSO1X5": [
"Les modèles hérités ne peuvent pas être renommés ici — renommez-le dans le dossier auquel il appartient."
],
diff --git a/packages/app/src/locales/fr/messages.po b/packages/app/src/locales/fr/messages.po
index 124d1bad0..e0b5b412b 100644
--- a/packages/app/src/locales/fr/messages.po
+++ b/packages/app/src/locales/fr/messages.po
@@ -1959,6 +1959,10 @@ msgstr "Pièces jointes"
msgid "Attachments must total under 3 MB."
msgstr "Les pièces jointes doivent totaliser moins de 3 Mo."
+#: src/components/SyncStatusBadge.tsx
+msgid "Authenticated as {login}."
+msgstr "Authentifié en tant que {login}."
+
#: src/editor/slash-command/component-items.tsx
msgid "Authoritative content; mirrored verbatim everywhere it's referenced."
msgstr "Contenu faisant autorité ; reproduit tel quel partout où il est référencé."
@@ -10822,6 +10826,15 @@ msgstr "Dépôt"
msgid "Repository name"
msgstr "Nom du dépôt"
+#: src/components/SyncStatusBadge.tsx
+msgid "Repository not found"
+msgstr "Dépôt introuvable"
+
+#: src/components/ShareBranchSwitchDialog.tsx
+#: src/components/SyncStatusBadge.tsx
+msgid "Repository not found — it may not exist, or the account used may not have access."
+msgstr "Dépôt introuvable — il n'existe peut-être pas, ou le compte utilisé n'y a peut-être pas accès."
+
#: src/components/SyncStatusBadge.tsx
msgid "Repository not found. It may have been renamed, deleted, or moved."
msgstr "Dépôt introuvable. Il a peut-être été renommé, supprimé ou déplacé."
@@ -14802,10 +14815,6 @@ msgid "You don't have access to this repository."
msgstr "Vous n'avez pas accès à ce dépôt."
#: src/components/settings/SyncSection.tsx
-#: src/components/SyncStatusBadge.tsx
-msgid "You don't have permission to push to this repo"
-msgstr "Vous n'avez pas la permission de pousser vers ce dépôt"
-
#: src/components/SyncStatusBadge.tsx
msgid "You don't have permission to push to this repo."
msgstr "Vous n'avez pas la permission de pousser vers ce dépôt."
@@ -14888,6 +14897,14 @@ msgstr "Votre version actuelle est enregistrée au préalable, cette opération
msgid "Your edits stay on this computer"
msgstr "Vos modifications restent sur cet ordinateur"
+#: src/components/SyncStatusBadge.tsx
+msgid "Your Git configuration names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "Votre configuration Git indique {declaredLogin}, mais les identifiants de ce compte n'ont pas pu être utilisés."
+
+#: src/components/SyncStatusBadge.tsx
+msgid "Your Git credential configuration names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "Votre configuration d'identifiants Git indique {declaredLogin}, mais les identifiants de ce compte n'ont pas pu être utilisés."
+
#: src/components/settings/SyncSection.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Your GitHub session expired — sign in again to verify push access."
@@ -14925,6 +14942,10 @@ msgstr "Votre copie locale de la branche <0>{branch}</0> est en retard. Tirez le
msgid "Your message didn't reach {agentName}."
msgstr "Votre message n’est pas parvenu à {agentName}."
+#: src/components/SyncStatusBadge.tsx
+msgid "Your remote URL names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "Votre URL distante indique {declaredLogin}, mais les identifiants de ce compte n'ont pas pu être utilisés."
+
#: src/components/BugReportSendToast.tsx
msgid "Your report is saved on this computer, so nothing was lost."
msgstr "Votre rapport est enregistré sur cet ordinateur, rien n'a donc été perdu."
diff --git a/packages/app/src/locales/hi/messages.json b/packages/app/src/locales/hi/messages.json
index 888c0d824..397b39ec5 100644
--- a/packages/app/src/locales/hi/messages.json
+++ b/packages/app/src/locales/hi/messages.json
@@ -921,6 +921,11 @@
"CGj3gX": ["पार्स त्रुटि"],
"CHfFN_": [["0"], " से OpenKnowledge हटाएँ"],
"CKyk7Q": ["वापस जाएँ"],
+ "CMd-g-": [
+ "आपके रिमोट URL में ",
+ ["declaredLogin"],
+ " नाम दिया गया है, लेकिन उस खाते के क्रेडेंशियल इस्तेमाल नहीं किए जा सके।"
+ ],
"CMyafZ": [["slot"], " हेक्स मान"],
"COr1Y7": [
"अपने <1>Downloads</1> फ़ोल्डर से <0>openknowledge.skill</0> चुनें। यह अपने आप सक्षम हो जाती है।"
@@ -951,7 +956,6 @@
],
"C_cPoW": ["आपका GitHub सत्र समाप्त हो गया — पुश की पहुँच जाँचने के लिए फिर से साइन इन करें।"],
"CcaU4i": ["संपादन तुरंत लागू होते हैं और इस थीम में अपने आप सहेजे जाते हैं।"],
- "ChAtFg": ["आपके पास इस रिपॉज़िटरी में पुश करने की अनुमति नहीं है"],
"ChMshD": [["appName"], " से बाहर निकलें"],
"Ck9XRt": ["कुंजी नहीं सहेजी जा सकी — कृपया फिर कोशिश करें।"],
"ClII5l": ["इस थीम का उपयोग करने के लिए ऊपर “कस्टम” पर सूरज या चाँद दबाएँ।"],
@@ -1117,6 +1121,7 @@
"आपकी टिप्पणियाँ चल रही बारी के पीछे प्रतीक्षा कर रही हैं — एजेंट द्वारा संदेश लिए जाने तक वे क़तार में रहती हैं।"
],
"Eji13z": ["उभारने की फ़ॉर्मैटिंग चालू या बंद करें।"],
+ "EkEFE3": ["रिपॉज़िटरी नहीं मिली"],
"EkH9pt": ["अपडेट करें"],
"EkUnmS": ["कोई भी"],
"El7NbA": ["शीर्षक 2"],
@@ -1242,6 +1247,11 @@
"G8t9NN": ["एक प्रॉपर्टी जोड़ें"],
"GA-UkN": [["keyName"], " प्रकार: ", ["typeLabel"], ". बदलने के लिए क्लिक करें।"],
"GAohqx": ["कॉलम हटाएँ"],
+ "GBEqoP": [
+ "आपके Git कॉन्फ़िगरेशन में ",
+ ["declaredLogin"],
+ " नाम दिया गया है, लेकिन उस खाते के क्रेडेंशियल इस्तेमाल नहीं किए जा सके।"
+ ],
"GBQjiV": ["स्किल जोड़ें"],
"GDvlUT": ["भूमिका"],
"GGsM4y": ["ग्राफ़ में चयनित"],
@@ -2640,6 +2650,7 @@
"ZGVsOD": ["साझा करने से पहले इस ब्रांच को GitHub पर पुश करें।"],
"ZI8uvA": ["कोई समस्या नहीं मिली।"],
"ZJ99sD": ["बाईं ओर कॉलम जोड़ें"],
+ "ZKVuLY": [["login"], " के रूप में प्रमाणित किया गया।"],
"ZNK2Tq": ["रूट"],
"ZOVgDv": [["moved"], " स्किलें प्रोजेक्ट में ले जाई गईं"],
"ZQJ1IV": ["अंतिम संपादक टैब सक्रिय करें।"],
@@ -2821,6 +2832,11 @@
],
"ajz9F8": [["filePath"], " की टकराव सामग्री लोड नहीं हो सकी। पेज फिर से लोड करने की कोशिश करें।"],
"ak4LLg": ["मेन्यू साफ़ करें"],
+ "akOe4q": [
+ "आपके Git क्रेडेंशियल कॉन्फ़िगरेशन में ",
+ ["declaredLogin"],
+ " नाम दिया गया है, लेकिन उस खाते के क्रेडेंशियल इस्तेमाल नहीं किए जा सके।"
+ ],
"akmOT9": ["यह टिप्पणी संपादित करें"],
"an0aL5": ["किसी एजेंट से पूछें"],
"anmUZq": ["एक सुविधा अनुपस्थित"],
@@ -3468,6 +3484,7 @@
"jPUPvG": [["filePath"], " का टकराव नहीं सुलझाया जा सका।"],
"jRAGrQ": ["एजेंट कॉन्फ़िगर करें"],
"jRHdCz": ["PDF लोड करने में विफल"],
+ "jRsjlF": ["रिपॉज़िटरी नहीं मिली — हो सकता है कि वह मौजूद न हो, या इस्तेमाल किए गए खाते की पहुँच न हो।"],
"jSO1X5": [
"विरासत में मिले टेम्पलेट का नाम यहाँ नहीं बदला जा सकता — उसका नाम उसी फ़ोल्डर में बदलें जिसका वह है।"
],
diff --git a/packages/app/src/locales/hi/messages.po b/packages/app/src/locales/hi/messages.po
index 814b6d87f..22dbffad4 100644
--- a/packages/app/src/locales/hi/messages.po
+++ b/packages/app/src/locales/hi/messages.po
@@ -1955,6 +1955,10 @@ msgstr "संलग्नक"
msgid "Attachments must total under 3 MB."
msgstr "संलग्नकों का कुल आकार 3 MB से कम होना चाहिए।"
+#: src/components/SyncStatusBadge.tsx
+msgid "Authenticated as {login}."
+msgstr "{login} के रूप में प्रमाणित किया गया।"
+
#: src/editor/slash-command/component-items.tsx
msgid "Authoritative content; mirrored verbatim everywhere it's referenced."
msgstr "आधिकारिक सामग्री; जहाँ भी संदर्भित हो वहाँ हूबहू प्रतिबिंबित।"
@@ -10818,6 +10822,15 @@ msgstr "रिपॉज़िटरी"
msgid "Repository name"
msgstr "रिपॉज़िटरी का नाम"
+#: src/components/SyncStatusBadge.tsx
+msgid "Repository not found"
+msgstr "रिपॉज़िटरी नहीं मिली"
+
+#: src/components/ShareBranchSwitchDialog.tsx
+#: src/components/SyncStatusBadge.tsx
+msgid "Repository not found — it may not exist, or the account used may not have access."
+msgstr "रिपॉज़िटरी नहीं मिली — हो सकता है कि वह मौजूद न हो, या इस्तेमाल किए गए खाते की पहुँच न हो।"
+
#: src/components/SyncStatusBadge.tsx
msgid "Repository not found. It may have been renamed, deleted, or moved."
msgstr "रिपॉज़िटरी नहीं मिली। शायद इसका नाम बदला गया, इसे हटाया गया, या हिलाया गया।"
@@ -14798,10 +14811,6 @@ msgid "You don't have access to this repository."
msgstr "इस रिपॉज़िटरी तक आपकी पहुँच नहीं है।"
#: src/components/settings/SyncSection.tsx
-#: src/components/SyncStatusBadge.tsx
-msgid "You don't have permission to push to this repo"
-msgstr "आपके पास इस रिपॉज़िटरी में पुश करने की अनुमति नहीं है"
-
#: src/components/SyncStatusBadge.tsx
msgid "You don't have permission to push to this repo."
msgstr "आपके पास इस रिपॉज़िटरी में पुश करने की अनुमति नहीं है।"
@@ -14884,6 +14893,14 @@ msgstr "आपका मौजूदा संस्करण पहले स
msgid "Your edits stay on this computer"
msgstr "आपके संपादन इसी कंप्यूटर पर रहते हैं"
+#: src/components/SyncStatusBadge.tsx
+msgid "Your Git configuration names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "आपके Git कॉन्फ़िगरेशन में {declaredLogin} नाम दिया गया है, लेकिन उस खाते के क्रेडेंशियल इस्तेमाल नहीं किए जा सके।"
+
+#: src/components/SyncStatusBadge.tsx
+msgid "Your Git credential configuration names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "आपके Git क्रेडेंशियल कॉन्फ़िगरेशन में {declaredLogin} नाम दिया गया है, लेकिन उस खाते के क्रेडेंशियल इस्तेमाल नहीं किए जा सके।"
+
#: src/components/settings/SyncSection.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Your GitHub session expired — sign in again to verify push access."
@@ -14921,6 +14938,10 @@ msgstr "ब्रांच <0>{branch}</0> की आपकी स्थान
msgid "Your message didn't reach {agentName}."
msgstr "आपका संदेश {agentName} तक नहीं पहुँचा।"
+#: src/components/SyncStatusBadge.tsx
+msgid "Your remote URL names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "आपके रिमोट URL में {declaredLogin} नाम दिया गया है, लेकिन उस खाते के क्रेडेंशियल इस्तेमाल नहीं किए जा सके।"
+
#: src/components/BugReportSendToast.tsx
msgid "Your report is saved on this computer, so nothing was lost."
msgstr "आपकी रिपोर्ट इस कंप्यूटर पर सेव है, इसलिए कुछ भी नहीं खोया।"
diff --git a/packages/app/src/locales/id/messages.json b/packages/app/src/locales/id/messages.json
index 07278f7c1..d67ea2995 100644
--- a/packages/app/src/locales/id/messages.json
+++ b/packages/app/src/locales/id/messages.json
@@ -936,6 +936,11 @@
"CGj3gX": ["galat penguraian"],
"CHfFN_": ["Hapus OpenKnowledge dari ", ["0"]],
"CKyk7Q": ["Kembali"],
+ "CMd-g-": [
+ "URL remote Anda menyebut ",
+ ["declaredLogin"],
+ ", tetapi kredensial akun itu tidak dapat digunakan."
+ ],
"CMyafZ": ["Nilai heksa ", ["slot"]],
"COr1Y7": [
"Pilih <0>openknowledge.skill</0> dari folder <1>Downloads</1> Anda. Ia aktif otomatis."
@@ -966,7 +971,6 @@
],
"C_cPoW": ["Sesi GitHub Anda kedaluwarsa — masuk lagi untuk memverifikasi akses push."],
"CcaU4i": ["Suntingan langsung diterapkan dan disimpan otomatis ke tema ini."],
- "ChAtFg": ["Anda tidak punya izin push ke repo ini"],
"ChMshD": ["Keluar dari ", ["appName"]],
"Ck9XRt": ["Kuncinya tidak bisa disimpan — silakan coba lagi."],
"ClII5l": ["Tekan ikon matahari atau bulan pada “Custom” di atas untuk memakai tema ini."],
@@ -1141,6 +1145,7 @@
"Komentarmu menunggu di belakang giliran yang sedang berjalan — komentar tetap mengantre sampai agen mengambil pesannya."
],
"Eji13z": ["Menyalakan atau mematikan format sorotan."],
+ "EkEFE3": ["Repositori tidak ditemukan"],
"EkH9pt": ["Perbarui"],
"EkUnmS": ["apa saja"],
"El7NbA": ["Judul 2"],
@@ -1276,6 +1281,11 @@
"G8t9NN": ["Tambahkan properti"],
"GA-UkN": ["Tipe ", ["keyName"], ": ", ["typeLabel"], ". Klik untuk mengubah."],
"GAohqx": ["Hapus kolom"],
+ "GBEqoP": [
+ "Konfigurasi Git Anda menyebut ",
+ ["declaredLogin"],
+ ", tetapi kredensial akun itu tidak dapat digunakan."
+ ],
"GBQjiV": ["Tambahkan keterampilan"],
"GDvlUT": ["Peran"],
"GGsM4y": ["Terpilih di graf"],
@@ -2737,6 +2747,7 @@
"ZGVsOD": ["Push cabang ini ke GitHub sebelum berbagi."],
"ZI8uvA": ["Tidak ada masalah ditemukan."],
"ZJ99sD": ["Sisipkan kolom di kiri"],
+ "ZKVuLY": ["Diautentikasi sebagai ", ["login"], "."],
"ZNK2Tq": ["akar"],
"ZOVgDv": [["moved"], " keterampilan dipindahkan ke Proyek"],
"ZQJ1IV": ["Mengaktifkan tab penyunting terakhir."],
@@ -2916,6 +2927,11 @@
" tidak bisa dimuat. Coba muat ulang halamannya."
],
"ak4LLg": ["Kosongkan menu"],
+ "akOe4q": [
+ "Konfigurasi kredensial Git Anda menyebut ",
+ ["declaredLogin"],
+ ", tetapi kredensial akun itu tidak dapat digunakan."
+ ],
"akmOT9": ["Sunting komentar ini"],
"an0aL5": ["Tanya agen"],
"anmUZq": ["Ada fitur yang kurang"],
@@ -3615,6 +3631,9 @@
"jPUPvG": ["Konflik untuk ", ["filePath"], " tidak bisa diselesaikan."],
"jRAGrQ": ["Atur agen"],
"jRHdCz": ["Gagal memuat PDF"],
+ "jRsjlF": [
+ "Repositori tidak ditemukan — mungkin ia tidak ada, atau akun yang digunakan mungkin tidak punya akses."
+ ],
"jSO1X5": [
"Templat warisan tidak bisa diganti namanya di sini — ganti namanya di folder yang memilikinya."
],
diff --git a/packages/app/src/locales/id/messages.po b/packages/app/src/locales/id/messages.po
index f169df5d8..f3e32274a 100644
--- a/packages/app/src/locales/id/messages.po
+++ b/packages/app/src/locales/id/messages.po
@@ -1955,6 +1955,10 @@ msgstr "Lampiran"
msgid "Attachments must total under 3 MB."
msgstr "Total lampiran harus di bawah 3 MB."
+#: src/components/SyncStatusBadge.tsx
+msgid "Authenticated as {login}."
+msgstr "Diautentikasi sebagai {login}."
+
#: src/editor/slash-command/component-items.tsx
msgid "Authoritative content; mirrored verbatim everywhere it's referenced."
msgstr "Konten otoritatif; dicerminkan apa adanya di mana pun ia dirujuk."
@@ -10818,6 +10822,15 @@ msgstr "Repositori"
msgid "Repository name"
msgstr "Nama repositori"
+#: src/components/SyncStatusBadge.tsx
+msgid "Repository not found"
+msgstr "Repositori tidak ditemukan"
+
+#: src/components/ShareBranchSwitchDialog.tsx
+#: src/components/SyncStatusBadge.tsx
+msgid "Repository not found — it may not exist, or the account used may not have access."
+msgstr "Repositori tidak ditemukan — mungkin ia tidak ada, atau akun yang digunakan mungkin tidak punya akses."
+
#: src/components/SyncStatusBadge.tsx
msgid "Repository not found. It may have been renamed, deleted, or moved."
msgstr "Repositori tidak ditemukan. Mungkin ia sudah diganti nama, dihapus, atau dipindahkan."
@@ -14798,10 +14811,6 @@ msgid "You don't have access to this repository."
msgstr "Anda tidak punya akses ke repositori ini."
#: src/components/settings/SyncSection.tsx
-#: src/components/SyncStatusBadge.tsx
-msgid "You don't have permission to push to this repo"
-msgstr "Anda tidak punya izin push ke repo ini"
-
#: src/components/SyncStatusBadge.tsx
msgid "You don't have permission to push to this repo."
msgstr "Anda tidak punya izin push ke repo ini."
@@ -14884,6 +14893,14 @@ msgstr "Versi Anda saat ini disimpan lebih dulu, jadi ini bisa dikembalikan."
msgid "Your edits stay on this computer"
msgstr "Suntingan Anda tetap di komputer ini"
+#: src/components/SyncStatusBadge.tsx
+msgid "Your Git configuration names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "Konfigurasi Git Anda menyebut {declaredLogin}, tetapi kredensial akun itu tidak dapat digunakan."
+
+#: src/components/SyncStatusBadge.tsx
+msgid "Your Git credential configuration names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "Konfigurasi kredensial Git Anda menyebut {declaredLogin}, tetapi kredensial akun itu tidak dapat digunakan."
+
#: src/components/settings/SyncSection.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Your GitHub session expired — sign in again to verify push access."
@@ -14921,6 +14938,10 @@ msgstr "Salinan lokal cabang <0>{branch}</0> milik Anda tertinggal. Tarik peruba
msgid "Your message didn't reach {agentName}."
msgstr "Pesanmu tidak sampai ke {agentName}."
+#: src/components/SyncStatusBadge.tsx
+msgid "Your remote URL names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "URL remote Anda menyebut {declaredLogin}, tetapi kredensial akun itu tidak dapat digunakan."
+
#: src/components/BugReportSendToast.tsx
msgid "Your report is saved on this computer, so nothing was lost."
msgstr "Laporan Anda tersimpan di komputer ini, jadi tidak ada yang hilang."
diff --git a/packages/app/src/locales/ko/messages.json b/packages/app/src/locales/ko/messages.json
index 59b901e40..d874f579e 100644
--- a/packages/app/src/locales/ko/messages.json
+++ b/packages/app/src/locales/ko/messages.json
@@ -907,6 +907,11 @@
"CGj3gX": ["구문 분석 오류"],
"CHfFN_": [["0"], "에서 OpenKnowledge 제거"],
"CKyk7Q": ["뒤로 가기"],
+ "CMd-g-": [
+ "원격 URL에는 ",
+ ["declaredLogin"],
+ "이(가) 지정되어 있지만, 해당 계정의 자격 증명을 사용할 수 없었습니다."
+ ],
"CMyafZ": [["slot"], " 16진수 값"],
"COr1Y7": ["<0>openknowledge.skill</0> 선택: <1>Downloads</1> 폴더. 자동 활성화."],
"CPMLsP": ["이 팩이 추가하는 항목 검토"],
@@ -935,7 +940,6 @@
],
"C_cPoW": ["GitHub 세션이 만료되었습니다. 푸시 권한을 확인하려면 로그인합니다."],
"CcaU4i": ["편집 내용이 실시간으로 적용되고 이 테마에 자동으로 저장됩니다."],
- "ChAtFg": ["이 저장소에 푸시할 권한이 없습니다"],
"ChMshD": [["appName"], " 종료"],
"Ck9XRt": ["키를 저장하지 못했습니다. 다시 시도합니다."],
"ClII5l": ["위의 사용자 지정에서 태양 또는 달을 눌러 이 테마를 사용합니다."],
@@ -1100,6 +1104,7 @@
"EiVgl5": ["이 저장소에 푸시 권한이 없습니다."],
"Eiowpn": ["현재 실행 뒤 댓글 대기 중. 에이전트 메시지 수신 전까지 대기열 유지."],
"Eji13z": ["강조 표시를 전환합니다."],
+ "EkEFE3": ["저장소를 찾을 수 없음"],
"EkH9pt": ["업데이트"],
"EkUnmS": ["모두"],
"El7NbA": ["제목 2"],
@@ -1227,6 +1232,11 @@
"G8t9NN": ["속성 추가"],
"GA-UkN": [["keyName"], " 유형: ", ["typeLabel"], ". 클릭하여 변경합니다."],
"GAohqx": ["열 삭제"],
+ "GBEqoP": [
+ "Git 설정에는 ",
+ ["declaredLogin"],
+ "이(가) 지정되어 있지만, 해당 계정의 자격 증명을 사용할 수 없었습니다."
+ ],
"GBQjiV": ["스킬 추가"],
"GDvlUT": ["역할"],
"GGsM4y": ["그래프에서 선택됨"],
@@ -2629,6 +2639,7 @@
"ZGVsOD": ["공유 전에 이 브랜치를 GitHub에 푸시하세요."],
"ZI8uvA": ["문제를 찾지 못했습니다."],
"ZJ99sD": ["왼쪽에 열 삽입"],
+ "ZKVuLY": [["login"], "(으)로 인증되었습니다."],
"ZNK2Tq": ["루트"],
"ZOVgDv": ["스킬 ", ["moved"], "개를 프로젝트로 이동함"],
"ZQJ1IV": ["마지막 편집기 탭 활성화"],
@@ -2805,6 +2816,11 @@
],
"ajz9F8": [["filePath"], "의 충돌 내용을 불러오지 못했습니다. 페이지를 다시 로드해 보세요."],
"ak4LLg": ["메뉴 지우기"],
+ "akOe4q": [
+ "Git 자격 증명 설정에는 ",
+ ["declaredLogin"],
+ "이(가) 지정되어 있지만, 해당 계정의 자격 증명을 사용할 수 없었습니다."
+ ],
"akmOT9": ["이 댓글 편집"],
"an0aL5": ["에이전트에게 질문"],
"anmUZq": ["기능 누락"],
@@ -3459,6 +3475,9 @@
"jPUPvG": [["filePath"], "의 충돌을 해결하지 못했습니다."],
"jRAGrQ": ["에이전트 구성"],
"jRHdCz": ["PDF를 불러오지 못했습니다"],
+ "jRsjlF": [
+ "저장소를 찾을 수 없습니다 — 존재하지 않거나, 사용된 계정에 접근 권한이 없을 수 있습니다."
+ ],
"jSO1X5": [
"상속된 템플릿은 여기에서 이름을 바꿀 수 없습니다. 소유한 폴더에서 이름을 바꾸세요."
],
diff --git a/packages/app/src/locales/ko/messages.po b/packages/app/src/locales/ko/messages.po
index dd1cb5fcb..363d1cecf 100644
--- a/packages/app/src/locales/ko/messages.po
+++ b/packages/app/src/locales/ko/messages.po
@@ -1959,6 +1959,10 @@ msgstr "첨부 파일"
msgid "Attachments must total under 3 MB."
msgstr "첨부 파일 총 용량은 3MB 미만이어야 합니다."
+#: src/components/SyncStatusBadge.tsx
+msgid "Authenticated as {login}."
+msgstr "{login}(으)로 인증되었습니다."
+
#: src/editor/slash-command/component-items.tsx
msgid "Authoritative content; mirrored verbatim everywhere it's referenced."
msgstr "기준 콘텐츠이며, 참조되는 모든 곳에 그대로 미러링됩니다."
@@ -10822,6 +10826,15 @@ msgstr "저장소"
msgid "Repository name"
msgstr "저장소 이름"
+#: src/components/SyncStatusBadge.tsx
+msgid "Repository not found"
+msgstr "저장소를 찾을 수 없음"
+
+#: src/components/ShareBranchSwitchDialog.tsx
+#: src/components/SyncStatusBadge.tsx
+msgid "Repository not found — it may not exist, or the account used may not have access."
+msgstr "저장소를 찾을 수 없습니다 — 존재하지 않거나, 사용된 계정에 접근 권한이 없을 수 있습니다."
+
#: src/components/SyncStatusBadge.tsx
msgid "Repository not found. It may have been renamed, deleted, or moved."
msgstr "저장소 검색 실패. 이름 변경, 삭제 또는 이동됐을 수 있습니다."
@@ -14802,10 +14815,6 @@ msgid "You don't have access to this repository."
msgstr "이 저장소에 접근 권한이 없습니다."
#: src/components/settings/SyncSection.tsx
-#: src/components/SyncStatusBadge.tsx
-msgid "You don't have permission to push to this repo"
-msgstr "이 저장소에 푸시할 권한이 없습니다"
-
#: src/components/SyncStatusBadge.tsx
msgid "You don't have permission to push to this repo."
msgstr "이 저장소에 푸시 권한이 없습니다."
@@ -14888,6 +14897,14 @@ msgstr "현재 버전이 먼저 저장되므로 되돌릴 수 있습니다."
msgid "Your edits stay on this computer"
msgstr "편집 내용은 이 컴퓨터에 남습니다."
+#: src/components/SyncStatusBadge.tsx
+msgid "Your Git configuration names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "Git 설정에는 {declaredLogin}이(가) 지정되어 있지만, 해당 계정의 자격 증명을 사용할 수 없었습니다."
+
+#: src/components/SyncStatusBadge.tsx
+msgid "Your Git credential configuration names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "Git 자격 증명 설정에는 {declaredLogin}이(가) 지정되어 있지만, 해당 계정의 자격 증명을 사용할 수 없었습니다."
+
#: src/components/settings/SyncSection.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Your GitHub session expired — sign in again to verify push access."
@@ -14925,6 +14942,10 @@ msgstr "브랜치 <0>{branch}</0>의 로컬 사본이 뒤처져 있습니다.
msgid "Your message didn't reach {agentName}."
msgstr "에이전트에 메시지 도달 실패: {agentName}."
+#: src/components/SyncStatusBadge.tsx
+msgid "Your remote URL names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "원격 URL에는 {declaredLogin}이(가) 지정되어 있지만, 해당 계정의 자격 증명을 사용할 수 없었습니다."
+
#: src/components/BugReportSendToast.tsx
msgid "Your report is saved on this computer, so nothing was lost."
msgstr "보고서는 이 컴퓨터에 저장되어 있으므로 아무것도 잃지 않았습니다."
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index 2fe5634e8..462a67e06 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -947,6 +947,11 @@
"CGj3gX": ["ƥàŕśē ēŕŕōŕ"],
"CHfFN_": ["Ŕēḿōvē ŌƥēńĶńōŵĺēďĝē ƒŕōḿ ", ["0"]],
"CKyk7Q": ["Ĝō ƀàćķ"],
+ "CMd-g-": [
+ "Ŷōũŕ ŕēḿōţē ŨŔĹ ńàḿēś ",
+ ["declaredLogin"],
+ ", ƀũţ ţĥàţ àććōũńţ'ś ćŕēďēńţĩàĺś ćōũĺďń'ţ ƀē ũśēď."
+ ],
"CMyafZ": [["slot"], " ĥēx vàĺũē"],
"COr1Y7": [
"Ƥĩćķ <0>ōƥēńķńōŵĺēďĝē.śķĩĺĺ</0> ƒŕōḿ ŷōũŕ <1>Ďōŵńĺōàďś</1> ƒōĺďēŕ. Ĩţ ēńàƀĺēś àũţōḿàţĩćàĺĺŷ."
@@ -977,7 +982,6 @@
],
"C_cPoW": ["Ŷōũŕ ĜĩţĤũƀ śēśśĩōń ēxƥĩŕēď — śĩĝń ĩń àĝàĩń ţō vēŕĩƒŷ ƥũśĥ àććēśś."],
"CcaU4i": ["Ēďĩţś àƥƥĺŷ ĺĩvē àńď śàvē àũţōḿàţĩćàĺĺŷ ţō ţĥĩś ţĥēḿē."],
- "ChAtFg": ["Ŷōũ ďōń'ţ ĥàvē ƥēŕḿĩśśĩōń ţō ƥũśĥ ţō ţĥĩś ŕēƥō"],
"ChMshD": ["Ǫũĩţ ", ["appName"]],
"Ck9XRt": ["Ćōũĺďń'ţ śàvē ţĥē ķēŷ — ƥĺēàśē ţŕŷ àĝàĩń."],
"ClII5l": ["Ƥŕēśś ţĥē śũń ōŕ ḿōōń ōń “Ćũśţōḿ” àƀōvē ţō ũśē ţĥĩś ţĥēḿē."],
@@ -1143,6 +1147,7 @@
"Ŷōũŕ ćōḿḿēńţś àŕē ŵàĩţĩńĝ ƀēĥĩńď ţĥē ŕũńńĩńĝ ţũŕń — ţĥēŷ śţàŷ ǫũēũēď ũńţĩĺ ţĥē àĝēńţ ƥĩćķś ţĥē ḿēśśàĝē ũƥ."
],
"Eji13z": ["Ţōĝĝĺē ĥĩĝĥĺĩĝĥţ ƒōŕḿàţţĩńĝ."],
+ "EkEFE3": ["Ŕēƥōśĩţōŕŷ ńōţ ƒōũńď"],
"EkH9pt": ["Ũƥďàţē"],
"EkUnmS": ["àńŷ"],
"El7NbA": ["Ĥēàďĩńĝ 2"],
@@ -1274,6 +1279,11 @@
"G8t9NN": ["Àďď à ƥŕōƥēŕţŷ"],
"GA-UkN": [["keyName"], " ţŷƥē: ", ["typeLabel"], ". Ćĺĩćķ ţō ćĥàńĝē."],
"GAohqx": ["Ďēĺēţē ćōĺũḿń"],
+ "GBEqoP": [
+ "Ŷōũŕ Ĝĩţ ćōńƒĩĝũŕàţĩōń ńàḿēś ",
+ ["declaredLogin"],
+ ", ƀũţ ţĥàţ àććōũńţ'ś ćŕēďēńţĩàĺś ćōũĺďń'ţ ƀē ũśēď."
+ ],
"GBQjiV": ["Àďď śķĩĺĺ"],
"GDvlUT": ["Ŕōĺē"],
"GGsM4y": ["Śēĺēćţēď ĩń ĝŕàƥĥ"],
@@ -2718,6 +2728,7 @@
"ZGVsOD": ["Ƥũśĥ ţĥĩś ƀŕàńćĥ ţō ĜĩţĤũƀ ƀēƒōŕē śĥàŕĩńĝ."],
"ZI8uvA": ["Ńō ƥŕōƀĺēḿś ƒōũńď."],
"ZJ99sD": ["Ĩńśēŕţ ćōĺũḿń ĺēƒţ"],
+ "ZKVuLY": ["Àũţĥēńţĩćàţēď àś ", ["login"], "."],
"ZNK2Tq": ["ŕōōţ"],
"ZOVgDv": ["Ḿōvēď ", ["moved"], " śķĩĺĺś ţō ƤŕōĴēćţ"],
"ZQJ1IV": ["Àćţĩvàţē ţĥē ĺàśţ ēďĩţōŕ ţàƀ."],
@@ -2901,6 +2912,11 @@
],
"ajz9F8": ["Ćōũĺďń'ţ ĺōàď ćōńƒĺĩćţ ćōńţēńţ ƒōŕ ", ["filePath"], ". Ţŕŷ ŕēĺōàďĩńĝ ţĥē ƥàĝē."],
"ak4LLg": ["Ćĺēàŕ ḿēńũ"],
+ "akOe4q": [
+ "Ŷōũŕ Ĝĩţ ćŕēďēńţĩàĺ ćōńƒĩĝũŕàţĩōń ńàḿēś ",
+ ["declaredLogin"],
+ ", ƀũţ ţĥàţ àććōũńţ'ś ćŕēďēńţĩàĺś ćōũĺďń'ţ ƀē ũśēď."
+ ],
"akmOT9": ["Ēďĩţ ţĥĩś ćōḿḿēńţ"],
"an0aL5": ["Àśķ àń àĝēńţ"],
"anmUZq": ["Ḿĩśśĩńĝ à ƒēàţũŕē"],
@@ -3583,6 +3599,7 @@
"jPUPvG": ["Ćōũĺďń'ţ ŕēśōĺvē ţĥē ćōńƒĺĩćţ ƒōŕ ", ["filePath"], "."],
"jRAGrQ": ["Ćōńƒĩĝũŕē àĝēńţś"],
"jRHdCz": ["Ƒàĩĺēď ţō ĺōàď ƤĎƑ"],
+ "jRsjlF": ["Ŕēƥōśĩţōŕŷ ńōţ ƒōũńď — ĩţ ḿàŷ ńōţ ēxĩśţ, ōŕ ţĥē àććōũńţ ũśēď ḿàŷ ńōţ ĥàvē àććēśś."],
"jSO1X5": ["Ĩńĥēŕĩţēď ţēḿƥĺàţēś ćàń'ţ ƀē ŕēńàḿēď ĥēŕē — ŕēńàḿē ĩţ ĩń ţĥē ƒōĺďēŕ ţĥàţ ōŵńś ĩţ."],
"jSY41h": ["\"", ["docName"], "\" ţōōķ ţōō ĺōńĝ. Ćĥēćķ ŷōũŕ ćōńńēćţĩōń."],
"jTLWxh": ["Ēḿƀēď àń ēxţēŕńàĺ ƥàĝē ĩń àń ĩńĺĩńē ĩƒŕàḿē (ďōćś, ďēḿōś, Ƒĩĝḿà, ĆōďēŚàńďƀōx)."],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index 1a3406493..15a06d752 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -1955,6 +1955,10 @@ msgstr ""
msgid "Attachments must total under 3 MB."
msgstr ""
+#: src/components/SyncStatusBadge.tsx
+msgid "Authenticated as {login}."
+msgstr ""
+
#: src/editor/slash-command/component-items.tsx
msgid "Authoritative content; mirrored verbatim everywhere it's referenced."
msgstr ""
@@ -10818,6 +10822,15 @@ msgstr ""
msgid "Repository name"
msgstr ""
+#: src/components/SyncStatusBadge.tsx
+msgid "Repository not found"
+msgstr ""
+
+#: src/components/ShareBranchSwitchDialog.tsx
+#: src/components/SyncStatusBadge.tsx
+msgid "Repository not found — it may not exist, or the account used may not have access."
+msgstr ""
+
#: src/components/SyncStatusBadge.tsx
msgid "Repository not found. It may have been renamed, deleted, or moved."
msgstr ""
@@ -14798,10 +14811,6 @@ msgid "You don't have access to this repository."
msgstr ""
#: src/components/settings/SyncSection.tsx
-#: src/components/SyncStatusBadge.tsx
-msgid "You don't have permission to push to this repo"
-msgstr ""
-
#: src/components/SyncStatusBadge.tsx
msgid "You don't have permission to push to this repo."
msgstr ""
@@ -14884,6 +14893,14 @@ msgstr ""
msgid "Your edits stay on this computer"
msgstr ""
+#: src/components/SyncStatusBadge.tsx
+msgid "Your Git configuration names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr ""
+
+#: src/components/SyncStatusBadge.tsx
+msgid "Your Git credential configuration names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr ""
+
#: src/components/settings/SyncSection.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Your GitHub session expired — sign in again to verify push access."
@@ -14921,6 +14938,10 @@ msgstr ""
msgid "Your message didn't reach {agentName}."
msgstr ""
+#: src/components/SyncStatusBadge.tsx
+msgid "Your remote URL names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr ""
+
#: src/components/BugReportSendToast.tsx
msgid "Your report is saved on this computer, so nothing was lost."
msgstr ""
diff --git a/packages/app/src/locales/pt-BR/messages.json b/packages/app/src/locales/pt-BR/messages.json
index 3a4ea722f..a05fe2b85 100644
--- a/packages/app/src/locales/pt-BR/messages.json
+++ b/packages/app/src/locales/pt-BR/messages.json
@@ -1100,6 +1100,11 @@
"CGj3gX": ["erro de análise"],
"CHfFN_": ["Remover o OpenKnowledge de ", ["0"]],
"CKyk7Q": ["Voltar"],
+ "CMd-g-": [
+ "Sua URL remota indica ",
+ ["declaredLogin"],
+ ", mas as credenciais dessa conta não puderam ser usadas."
+ ],
"CMyafZ": ["Valor hexadecimal de ", ["slot"]],
"COr1Y7": [
"Escolha <0>openknowledge.skill</0> na sua pasta <1>Downloads</1>. Ela é ativada automaticamente."
@@ -1130,7 +1135,6 @@
],
"C_cPoW": ["Sua sessão do GitHub expirou — entre de novo para verificar o acesso de envio."],
"CcaU4i": ["As alterações são aplicadas imediatamente e salvas automaticamente neste tema."],
- "ChAtFg": ["Você não tem permissão para enviar a este repositório"],
"ChMshD": ["Encerrar o ", ["appName"]],
"Ck9XRt": ["Não deu para salvar a chave — tente de novo."],
"ClII5l": ["Pressione o sol ou a lua em “Custom” acima para usar este tema."],
@@ -1318,6 +1322,7 @@
"Seus comentários estão aguardando atrás do turno em andamento — eles ficam na fila até o agente pegar a mensagem."
],
"Eji13z": ["Liga ou desliga o destaque."],
+ "EkEFE3": ["Repositório não encontrado"],
"EkH9pt": ["Atualizar"],
"EkUnmS": ["qualquer"],
"El7NbA": ["Título 2"],
@@ -1463,6 +1468,11 @@
"G8t9NN": ["Adicionar uma propriedade"],
"GA-UkN": ["Tipo de ", ["keyName"], ": ", ["typeLabel"], ". Clique para alterar."],
"GAohqx": ["Excluir coluna"],
+ "GBEqoP": [
+ "Sua configuração do Git indica ",
+ ["declaredLogin"],
+ ", mas as credenciais dessa conta não puderam ser usadas."
+ ],
"GBQjiV": ["Adicionar habilidade"],
"GDvlUT": ["Função"],
"GGsM4y": ["Selecionado no grafo"],
@@ -3116,6 +3126,7 @@
"ZGVsOD": ["Envie este ramo para o GitHub antes de compartilhar."],
"ZI8uvA": ["Nenhum problema encontrado."],
"ZJ99sD": ["Inserir coluna à esquerda"],
+ "ZKVuLY": ["Autenticado como ", ["login"], "."],
"ZNK2Tq": ["raiz"],
"ZOVgDv": [["moved"], " habilidades movidas para Projeto"],
"ZQJ1IV": ["Ativa a última aba do editor."],
@@ -3310,6 +3321,11 @@
". Tente recarregar a página."
],
"ak4LLg": ["Limpar menu"],
+ "akOe4q": [
+ "Sua configuração de credenciais do Git indica ",
+ ["declaredLogin"],
+ ", mas as credenciais dessa conta não puderam ser usadas."
+ ],
"akmOT9": ["Editar este comentário"],
"an0aL5": ["Perguntar a um agente"],
"anmUZq": ["Faltava um recurso"],
@@ -4094,6 +4110,9 @@
"jPUPvG": ["Não deu para resolver o conflito de ", ["filePath"], "."],
"jRAGrQ": ["Configurar agentes"],
"jRHdCz": ["Falha ao carregar o PDF"],
+ "jRsjlF": [
+ "Repositório não encontrado — ele pode não existir, ou a conta usada pode não ter acesso."
+ ],
"jSO1X5": ["Modelos herdados não podem ser renomeados aqui — renomeie na pasta que os contém."],
"jSY41h": ["\"", ["docName"], "\" demorou demais. Verifique sua conexão."],
"jTLWxh": [
diff --git a/packages/app/src/locales/pt-BR/messages.po b/packages/app/src/locales/pt-BR/messages.po
index 13ec3ba39..98cf783d9 100644
--- a/packages/app/src/locales/pt-BR/messages.po
+++ b/packages/app/src/locales/pt-BR/messages.po
@@ -1955,6 +1955,10 @@ msgstr "Anexos"
msgid "Attachments must total under 3 MB."
msgstr "Os anexos devem somar menos de 3 MB."
+#: src/components/SyncStatusBadge.tsx
+msgid "Authenticated as {login}."
+msgstr "Autenticado como {login}."
+
#: src/editor/slash-command/component-items.tsx
msgid "Authoritative content; mirrored verbatim everywhere it's referenced."
msgstr "Conteúdo autoritativo; espelhado literalmente em todo lugar onde for referenciado."
@@ -10818,6 +10822,15 @@ msgstr "Repositório"
msgid "Repository name"
msgstr "Nome do repositório"
+#: src/components/SyncStatusBadge.tsx
+msgid "Repository not found"
+msgstr "Repositório não encontrado"
+
+#: src/components/ShareBranchSwitchDialog.tsx
+#: src/components/SyncStatusBadge.tsx
+msgid "Repository not found — it may not exist, or the account used may not have access."
+msgstr "Repositório não encontrado — ele pode não existir, ou a conta usada pode não ter acesso."
+
#: src/components/SyncStatusBadge.tsx
msgid "Repository not found. It may have been renamed, deleted, or moved."
msgstr "Repositório não encontrado. Ele pode ter sido renomeado, excluído ou movido."
@@ -14798,10 +14811,6 @@ msgid "You don't have access to this repository."
msgstr "Você não tem acesso a este repositório."
#: src/components/settings/SyncSection.tsx
-#: src/components/SyncStatusBadge.tsx
-msgid "You don't have permission to push to this repo"
-msgstr "Você não tem permissão para enviar a este repositório"
-
#: src/components/SyncStatusBadge.tsx
msgid "You don't have permission to push to this repo."
msgstr "Você não tem permissão para enviar a este repositório."
@@ -14884,6 +14893,14 @@ msgstr "Sua versão atual é salva antes, então isto é reversível."
msgid "Your edits stay on this computer"
msgstr "Suas edições ficam neste computador"
+#: src/components/SyncStatusBadge.tsx
+msgid "Your Git configuration names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "Sua configuração do Git indica {declaredLogin}, mas as credenciais dessa conta não puderam ser usadas."
+
+#: src/components/SyncStatusBadge.tsx
+msgid "Your Git credential configuration names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "Sua configuração de credenciais do Git indica {declaredLogin}, mas as credenciais dessa conta não puderam ser usadas."
+
#: src/components/settings/SyncSection.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Your GitHub session expired — sign in again to verify push access."
@@ -14921,6 +14938,10 @@ msgstr "Sua cópia local do ramo <0>{branch}</0> está atrasada. Traga as últim
msgid "Your message didn't reach {agentName}."
msgstr "Sua mensagem não chegou a {agentName}."
+#: src/components/SyncStatusBadge.tsx
+msgid "Your remote URL names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "Sua URL remota indica {declaredLogin}, mas as credenciais dessa conta não puderam ser usadas."
+
#: src/components/BugReportSendToast.tsx
msgid "Your report is saved on this computer, so nothing was lost."
msgstr "Seu relatório está salvo neste computador, então nada foi perdido."
diff --git a/packages/app/src/locales/ur/messages.json b/packages/app/src/locales/ur/messages.json
index ec20acf55..ac56ddc24 100644
--- a/packages/app/src/locales/ur/messages.json
+++ b/packages/app/src/locales/ur/messages.json
@@ -963,6 +963,11 @@
"CGj3gX": ["پارس کی خرابی"],
"CHfFN_": ["OpenKnowledge کو ", ["0"], " سے ہٹائیں"],
"CKyk7Q": ["واپس جائیں"],
+ "CMd-g-": [
+ "آپ کے ریموٹ URL میں ",
+ ["declaredLogin"],
+ " درج ہے، لیکن اس اکاؤنٹ کی کریڈینشلز استعمال نہیں ہو سکیں۔"
+ ],
"CMyafZ": [["slot"], " کی ہیکس قدر"],
"COr1Y7": [
"اپنے <1>ڈاؤن لوڈز</1> فولڈر سے <0>openknowledge.skill</0> منتخب کریں۔ یہ خودکار طور پر فعال ہو جاتی ہے۔"
@@ -993,7 +998,6 @@
],
"C_cPoW": ["آپ کا GitHub سیشن ختم ہو گیا — پُش کی رسائی کی توثیق کے لیے دوبارہ سائن اِن کریں۔"],
"CcaU4i": ["ترامیم فوراً لاگو ہوتی ہیں اور خودکار طور پر اس تھیم میں محفوظ ہو جاتی ہیں۔"],
- "ChAtFg": ["آپ کو اس ریپو میں پُش کرنے کی اجازت نہیں"],
"ChMshD": [["appName"], " سے باہر نکلیں"],
"Ck9XRt": ["کلید محفوظ نہیں ہو سکی — براہِ کرم دوبارہ کوشش کریں۔"],
"ClII5l": ["اس تھیم کو استعمال کرنے کے لیے اوپر “حسبِ ضرورت” پر سورج یا چاند دبائیں۔"],
@@ -1169,6 +1173,7 @@
"آپ کے تبصرے جاری باری کے پیچھے انتظار کر رہے ہیں — ایجنٹ کے پیغام اٹھانے تک وہ قطار میں رہتے ہیں۔"
],
"Eji13z": ["نمایاں کرنے کی فارمیٹنگ بدلیں۔"],
+ "EkEFE3": ["ریپازٹری نہیں ملی"],
"EkH9pt": ["اپ ڈیٹ کریں"],
"EkUnmS": ["کوئی بھی"],
"El7NbA": ["عنوان 2"],
@@ -1302,6 +1307,11 @@
"G8t9NN": ["خصوصیت شامل کریں"],
"GA-UkN": [["keyName"], " کی قسم: ", ["typeLabel"], "۔ تبدیل کرنے کے لیے کلک کریں۔"],
"GAohqx": ["کالم حذف کریں"],
+ "GBEqoP": [
+ "آپ کی Git کنفیگریشن میں ",
+ ["declaredLogin"],
+ " درج ہے، لیکن اس اکاؤنٹ کی کریڈینشلز استعمال نہیں ہو سکیں۔"
+ ],
"GBQjiV": ["مہارت شامل کریں"],
"GDvlUT": ["کردار"],
"GGsM4y": ["گراف میں منتخب"],
@@ -2787,6 +2797,7 @@
"ZGVsOD": ["شیئر کرنے سے پہلے اس برانچ کو GitHub پر پش کریں۔"],
"ZI8uvA": ["کوئی مسئلہ نہیں ملا۔"],
"ZJ99sD": ["بائیں طرف کالم داخل کریں"],
+ "ZKVuLY": [["login"], " کے طور پر تصدیق کی گئی۔"],
"ZNK2Tq": ["جڑ"],
"ZOVgDv": [["moved"], " مہارتیں پروجیکٹ میں منتقل ہو گئیں"],
"ZQJ1IV": ["ایڈیٹر کا آخری ٹیب فعال کریں۔"],
@@ -2975,6 +2986,11 @@
" کے تصادم کا مواد لوڈ نہیں ہو سکا۔ صفحہ دوبارہ لوڈ کرنے کی کوشش کریں۔"
],
"ak4LLg": ["مینو صاف کریں"],
+ "akOe4q": [
+ "آپ کی Git کریڈینشل کنفیگریشن میں ",
+ ["declaredLogin"],
+ " درج ہے، لیکن اس اکاؤنٹ کی کریڈینشلز استعمال نہیں ہو سکیں۔"
+ ],
"akmOT9": ["اس تبصرے میں ترمیم کریں"],
"an0aL5": ["ایجنٹ سے پوچھیں"],
"anmUZq": ["ایک خصوصیت غائب ہے"],
@@ -3667,6 +3683,9 @@
"jPUPvG": [["filePath"], " کا تصادم حل نہیں ہو سکا۔"],
"jRAGrQ": ["ایجنٹس ترتیب دیں"],
"jRHdCz": ["PDF لوڈ نہیں ہو سکی"],
+ "jRsjlF": [
+ "ریپازٹری نہیں ملی — ہو سکتا ہے وہ موجود نہ ہو، یا استعمال شدہ اکاؤنٹ کو رسائی حاصل نہ ہو۔"
+ ],
"jSO1X5": [
"وراثت میں ملے ٹیمپلیٹس کا نام یہاں نہیں بدلا جا سکتا — اسے اسی فولڈر میں بدلیں جو اس کا مالک ہے۔"
],
diff --git a/packages/app/src/locales/ur/messages.po b/packages/app/src/locales/ur/messages.po
index e714de4cb..3f30c60cb 100644
--- a/packages/app/src/locales/ur/messages.po
+++ b/packages/app/src/locales/ur/messages.po
@@ -1959,6 +1959,10 @@ msgstr "منسلکات"
msgid "Attachments must total under 3 MB."
msgstr "منسلکات کا مجموعی حجم 3 MB سے کم ہونا چاہیے۔"
+#: src/components/SyncStatusBadge.tsx
+msgid "Authenticated as {login}."
+msgstr "{login} کے طور پر تصدیق کی گئی۔"
+
#: src/editor/slash-command/component-items.tsx
msgid "Authoritative content; mirrored verbatim everywhere it's referenced."
msgstr "مستند مواد؛ جہاں بھی اس کا حوالہ ہو وہاں لفظ بہ لفظ منعکس ہوتا ہے۔"
@@ -10822,6 +10826,15 @@ msgstr "ریپازٹری"
msgid "Repository name"
msgstr "ریپازٹری کا نام"
+#: src/components/SyncStatusBadge.tsx
+msgid "Repository not found"
+msgstr "ریپازٹری نہیں ملی"
+
+#: src/components/ShareBranchSwitchDialog.tsx
+#: src/components/SyncStatusBadge.tsx
+msgid "Repository not found — it may not exist, or the account used may not have access."
+msgstr "ریپازٹری نہیں ملی — ہو سکتا ہے وہ موجود نہ ہو، یا استعمال شدہ اکاؤنٹ کو رسائی حاصل نہ ہو۔"
+
#: src/components/SyncStatusBadge.tsx
msgid "Repository not found. It may have been renamed, deleted, or moved."
msgstr "ریپازٹری نہیں ملی۔ ہو سکتا ہے اس کا نام بدل گیا ہو، حذف ہو گئی ہو، یا منتقل ہو گئی ہو۔"
@@ -14802,10 +14815,6 @@ msgid "You don't have access to this repository."
msgstr "آپ کو اس ریپازٹری تک رسائی نہیں۔"
#: src/components/settings/SyncSection.tsx
-#: src/components/SyncStatusBadge.tsx
-msgid "You don't have permission to push to this repo"
-msgstr "آپ کو اس ریپو میں پُش کرنے کی اجازت نہیں"
-
#: src/components/SyncStatusBadge.tsx
msgid "You don't have permission to push to this repo."
msgstr "آپ کو اس ریپو میں پُش کرنے کی اجازت نہیں۔"
@@ -14888,6 +14897,14 @@ msgstr "آپ کا موجودہ ورژن پہلے محفوظ ہو جاتا ہے،
msgid "Your edits stay on this computer"
msgstr "آپ کی ترامیم اسی کمپیوٹر پر رہتی ہیں"
+#: src/components/SyncStatusBadge.tsx
+msgid "Your Git configuration names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "آپ کی Git کنفیگریشن میں {declaredLogin} درج ہے، لیکن اس اکاؤنٹ کی کریڈینشلز استعمال نہیں ہو سکیں۔"
+
+#: src/components/SyncStatusBadge.tsx
+msgid "Your Git credential configuration names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "آپ کی Git کریڈینشل کنفیگریشن میں {declaredLogin} درج ہے، لیکن اس اکاؤنٹ کی کریڈینشلز استعمال نہیں ہو سکیں۔"
+
#: src/components/settings/SyncSection.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Your GitHub session expired — sign in again to verify push access."
@@ -14925,6 +14942,10 @@ msgstr "برانچ <0>{branch}</0> کی آپ کی مقامی نقل پیچھے
msgid "Your message didn't reach {agentName}."
msgstr "آپ کا پیغام {agentName} تک نہیں پہنچا۔"
+#: src/components/SyncStatusBadge.tsx
+msgid "Your remote URL names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "آپ کے ریموٹ URL میں {declaredLogin} درج ہے، لیکن اس اکاؤنٹ کی کریڈینشلز استعمال نہیں ہو سکیں۔"
+
#: src/components/BugReportSendToast.tsx
msgid "Your report is saved on this computer, so nothing was lost."
msgstr "آپ کی رپورٹ اس کمپیوٹر پر محفوظ ہے، اس لیے کچھ ضائع نہیں ہوا۔"
diff --git a/packages/app/src/locales/zh-Hans/messages.json b/packages/app/src/locales/zh-Hans/messages.json
index 8dbe8966d..e23cc9aa9 100644
--- a/packages/app/src/locales/zh-Hans/messages.json
+++ b/packages/app/src/locales/zh-Hans/messages.json
@@ -840,6 +840,7 @@
"CGj3gX": ["解析错误"],
"CHfFN_": ["把 OpenKnowledge 从 ", ["0"], " 中移除"],
"CKyk7Q": ["返回"],
+ "CMd-g-": ["你的远程 URL 中指定了 ", ["declaredLogin"], ",但无法使用该账户的凭据。"],
"CMyafZ": [["slot"], " 十六进制值"],
"COr1Y7": ["从你的<1>下载</1>文件夹中选择 <0>openknowledge.skill</0>。它会自动启用。"],
"CPMLsP": ["查看此入门包将添加的内容"],
@@ -866,7 +867,6 @@
],
"C_cPoW": ["你的 GitHub 会话已过期——请重新登录以验证推送权限。"],
"CcaU4i": ["编辑会实时生效,并自动保存到此主题。"],
- "ChAtFg": ["你没有推送到这个仓库的权限"],
"ChMshD": ["退出 ", ["appName"]],
"Ck9XRt": ["无法保存密钥——请重试。"],
"ClII5l": ["按上方“自定义”中的太阳或月亮图标以使用此主题。"],
@@ -1018,6 +1018,7 @@
"EiVgl5": ["你没有推送到这个仓库的权限。"],
"Eiowpn": ["你的评论正在当前回合之后等待——它们会排队,直到智能体取用该消息。"],
"Eji13z": ["切换高亮格式。"],
+ "EkEFE3": ["找不到仓库"],
"EkH9pt": ["更新"],
"EkUnmS": ["任意"],
"El7NbA": ["二级标题"],
@@ -1133,6 +1134,7 @@
"G8t9NN": ["添加属性"],
"GA-UkN": [["keyName"], " 类型:", ["typeLabel"], "。点击可更改。"],
"GAohqx": ["删除列"],
+ "GBEqoP": ["你的 Git 配置中指定了 ", ["declaredLogin"], ",但无法使用该账户的凭据。"],
"GBQjiV": ["添加技能"],
"GDvlUT": ["角色"],
"GGsM4y": ["在关系图中已选中"],
@@ -2403,6 +2405,7 @@
"ZGVsOD": ["共享前请先将此分支推送到 GitHub。"],
"ZI8uvA": ["没有发现问题。"],
"ZJ99sD": ["在左侧插入列"],
+ "ZKVuLY": ["已以 ", ["login"], " 身份验证。"],
"ZNK2Tq": ["根目录"],
"ZOVgDv": ["已将 ", ["moved"], " 个技能移至项目"],
"ZQJ1IV": ["激活编辑器的最后一个标签页。"],
@@ -2565,6 +2568,7 @@
"ajHi4O": ["自动同步已暂停——你没有推送到这个仓库的权限。切换到「跟随」以继续接收更新。"],
"ajz9F8": ["无法加载 ", ["filePath"], " 的冲突内容。请尝试重新加载页面。"],
"ak4LLg": ["清空菜单"],
+ "akOe4q": ["你的 Git 凭据配置中指定了 ", ["declaredLogin"], ",但无法使用该账户的凭据。"],
"akmOT9": ["编辑这条评论"],
"an0aL5": ["询问智能体"],
"anmUZq": ["缺少某个功能"],
@@ -3166,6 +3170,7 @@
"jPUPvG": ["无法解决 ", ["filePath"], " 的冲突。"],
"jRAGrQ": ["配置智能体"],
"jRHdCz": ["加载 PDF 失败"],
+ "jRsjlF": ["找不到仓库——它可能不存在,或所用账户可能没有访问权限。"],
"jSO1X5": ["继承来的模板无法在这里重命名——请到拥有它的那个文件夹中重命名。"],
"jSY41h": ["“", ["docName"], "”耗时过长。请检查你的网络连接。"],
"jTLWxh": ["用内联 iframe 嵌入外部页面(文档、演示、Figma、CodeSandbox)。"],
diff --git a/packages/app/src/locales/zh-Hans/messages.po b/packages/app/src/locales/zh-Hans/messages.po
index 1d649ad95..4f11781ef 100644
--- a/packages/app/src/locales/zh-Hans/messages.po
+++ b/packages/app/src/locales/zh-Hans/messages.po
@@ -1959,6 +1959,10 @@ msgstr "附件"
msgid "Attachments must total under 3 MB."
msgstr "附件总大小必须小于 3 MB。"
+#: src/components/SyncStatusBadge.tsx
+msgid "Authenticated as {login}."
+msgstr "已以 {login} 身份验证。"
+
#: src/editor/slash-command/component-items.tsx
msgid "Authoritative content; mirrored verbatim everywhere it's referenced."
msgstr "权威内容;在所有被引用的地方逐字镜像。"
@@ -10822,6 +10826,15 @@ msgstr "仓库"
msgid "Repository name"
msgstr "仓库名"
+#: src/components/SyncStatusBadge.tsx
+msgid "Repository not found"
+msgstr "找不到仓库"
+
+#: src/components/ShareBranchSwitchDialog.tsx
+#: src/components/SyncStatusBadge.tsx
+msgid "Repository not found — it may not exist, or the account used may not have access."
+msgstr "找不到仓库——它可能不存在,或所用账户可能没有访问权限。"
+
#: src/components/SyncStatusBadge.tsx
msgid "Repository not found. It may have been renamed, deleted, or moved."
msgstr "找不到仓库。它可能已被重命名、删除或移动。"
@@ -14802,10 +14815,6 @@ msgid "You don't have access to this repository."
msgstr "你没有这个仓库的访问权限。"
#: src/components/settings/SyncSection.tsx
-#: src/components/SyncStatusBadge.tsx
-msgid "You don't have permission to push to this repo"
-msgstr "你没有推送到这个仓库的权限"
-
#: src/components/SyncStatusBadge.tsx
msgid "You don't have permission to push to this repo."
msgstr "你没有推送到这个仓库的权限。"
@@ -14888,6 +14897,14 @@ msgstr "你当前的版本会先被保存,因此这一步可以撤销。"
msgid "Your edits stay on this computer"
msgstr "你的编辑留在这台电脑上"
+#: src/components/SyncStatusBadge.tsx
+msgid "Your Git configuration names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "你的 Git 配置中指定了 {declaredLogin},但无法使用该账户的凭据。"
+
+#: src/components/SyncStatusBadge.tsx
+msgid "Your Git credential configuration names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "你的 Git 凭据配置中指定了 {declaredLogin},但无法使用该账户的凭据。"
+
#: src/components/settings/SyncSection.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Your GitHub session expired — sign in again to verify push access."
@@ -14925,6 +14942,10 @@ msgstr "你本地的 <0>{branch}</0> 分支副本落后了。请拉取最新改
msgid "Your message didn't reach {agentName}."
msgstr "你的消息未送达 {agentName}。"
+#: src/components/SyncStatusBadge.tsx
+msgid "Your remote URL names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "你的远程 URL 中指定了 {declaredLogin},但无法使用该账户的凭据。"
+
#: src/components/BugReportSendToast.tsx
msgid "Your report is saved on this computer, so nothing was lost."
msgstr "你的报告已保存在这台电脑上,没有丢失任何内容。"
diff --git a/packages/app/src/locales/zh-Hant/messages.json b/packages/app/src/locales/zh-Hant/messages.json
index a4454d790..e7c895041 100644
--- a/packages/app/src/locales/zh-Hant/messages.json
+++ b/packages/app/src/locales/zh-Hant/messages.json
@@ -844,6 +844,7 @@
"CGj3gX": ["解析錯誤"],
"CHfFN_": ["把 OpenKnowledge 從 ", ["0"], " 中移除"],
"CKyk7Q": ["返回"],
+ "CMd-g-": ["你的遠端 URL 中指定了 ", ["declaredLogin"], ",但無法使用該帳戶的憑證。"],
"CMyafZ": [["slot"], " 十六進位值"],
"COr1Y7": ["從你的<1>下載</1>資料夾中選 <0>openknowledge.skill</0>。它會自動啟用。"],
"CPMLsP": ["檢視此入門套件會加入的內容"],
@@ -872,7 +873,6 @@
],
"C_cPoW": ["你的 GitHub 工作階段已過期——請重新登入以確認推送權限。"],
"CcaU4i": ["編輯會即時套用,並自動儲存到這個主題。"],
- "ChAtFg": ["你沒有推送到這個儲存庫的權限"],
"ChMshD": ["結束 ", ["appName"]],
"Ck9XRt": ["無法儲存金鑰——請再試一次。"],
"ClII5l": ["按上方「自訂」中的太陽或月亮圖示以使用這個主題。"],
@@ -1028,6 +1028,7 @@
"EiVgl5": ["你沒有推送到這個儲存庫的權限。"],
"Eiowpn": ["你的評論正在目前回合之後等待——它們會排隊,直到智慧體取用該訊息。"],
"Eji13z": ["切換醒目提示格式。"],
+ "EkEFE3": ["找不到儲存庫"],
"EkH9pt": ["更新"],
"EkUnmS": ["任意"],
"El7NbA": ["標題 2"],
@@ -1143,6 +1144,7 @@
"G8t9NN": ["新增屬性"],
"GA-UkN": [["keyName"], " 類型:", ["typeLabel"], "。點一下可變更。"],
"GAohqx": ["刪除欄"],
+ "GBEqoP": ["你的 Git 設定中指定了 ", ["declaredLogin"], ",但無法使用該帳戶的憑證。"],
"GBQjiV": ["新增技能"],
"GDvlUT": ["角色"],
"GGsM4y": ["在關係圖中已選取"],
@@ -2427,6 +2429,7 @@
"ZGVsOD": ["分享前請先將這個分支推送到 GitHub。"],
"ZI8uvA": ["沒有發現問題。"],
"ZJ99sD": ["在左側插入欄"],
+ "ZKVuLY": ["已以 ", ["login"], " 身分驗證。"],
"ZNK2Tq": ["根目錄"],
"ZOVgDv": ["已將 ", ["moved"], " 個技能移至專案"],
"ZQJ1IV": ["切換到編輯器的最後一個分頁。"],
@@ -2591,6 +2594,7 @@
"ajHi4O": ["自動同步已暫停——你沒有推送到這個儲存庫的權限。切換到「跟隨」以繼續接收更新。"],
"ajz9F8": ["無法載入 ", ["filePath"], " 的衝突內容。請試著重新載入頁面。"],
"ak4LLg": ["清除選單"],
+ "akOe4q": ["你的 Git 憑證設定中指定了 ", ["declaredLogin"], ",但無法使用該帳戶的憑證。"],
"akmOT9": ["編輯這則註解"],
"an0aL5": ["詢問智慧代理"],
"anmUZq": ["缺少某個功能"],
@@ -3192,6 +3196,7 @@
"jPUPvG": ["無法解決 ", ["filePath"], " 的衝突。"],
"jRAGrQ": ["設定代理"],
"jRHdCz": ["載入 PDF 失敗"],
+ "jRsjlF": ["找不到儲存庫——它可能不存在,或所用帳戶可能沒有存取權。"],
"jSO1X5": ["繼承來的範本無法在這裡重新命名——請到擁有它的那個資料夾中重新命名。"],
"jSY41h": ["「", ["docName"], "」耗時過久。請檢查你的網路連線。"],
"jTLWxh": ["用行內 iframe 嵌入外部頁面(說明文件、示範、Figma、CodeSandbox)。"],
diff --git a/packages/app/src/locales/zh-Hant/messages.po b/packages/app/src/locales/zh-Hant/messages.po
index ce5491b01..c7ddcc569 100644
--- a/packages/app/src/locales/zh-Hant/messages.po
+++ b/packages/app/src/locales/zh-Hant/messages.po
@@ -1959,6 +1959,10 @@ msgstr "附件"
msgid "Attachments must total under 3 MB."
msgstr "附件總大小必須小於 3 MB。"
+#: src/components/SyncStatusBadge.tsx
+msgid "Authenticated as {login}."
+msgstr "已以 {login} 身分驗證。"
+
#: src/editor/slash-command/component-items.tsx
msgid "Authoritative content; mirrored verbatim everywhere it's referenced."
msgstr "權威內容;在所有被參照的地方逐字鏡像。"
@@ -10822,6 +10826,15 @@ msgstr "儲存庫"
msgid "Repository name"
msgstr "儲存庫名稱"
+#: src/components/SyncStatusBadge.tsx
+msgid "Repository not found"
+msgstr "找不到儲存庫"
+
+#: src/components/ShareBranchSwitchDialog.tsx
+#: src/components/SyncStatusBadge.tsx
+msgid "Repository not found — it may not exist, or the account used may not have access."
+msgstr "找不到儲存庫——它可能不存在,或所用帳戶可能沒有存取權。"
+
#: src/components/SyncStatusBadge.tsx
msgid "Repository not found. It may have been renamed, deleted, or moved."
msgstr "找不到儲存庫。它可能已被重新命名、刪除或移動。"
@@ -14802,10 +14815,6 @@ msgid "You don't have access to this repository."
msgstr "你沒有這個儲存庫的存取權。"
#: src/components/settings/SyncSection.tsx
-#: src/components/SyncStatusBadge.tsx
-msgid "You don't have permission to push to this repo"
-msgstr "你沒有推送到這個儲存庫的權限"
-
#: src/components/SyncStatusBadge.tsx
msgid "You don't have permission to push to this repo."
msgstr "你沒有推送到這個儲存庫的權限。"
@@ -14888,6 +14897,14 @@ msgstr "你目前的版本會先存起來,所以這一步可以回復。"
msgid "Your edits stay on this computer"
msgstr "你的編輯會留在這台電腦上"
+#: src/components/SyncStatusBadge.tsx
+msgid "Your Git configuration names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "你的 Git 設定中指定了 {declaredLogin},但無法使用該帳戶的憑證。"
+
+#: src/components/SyncStatusBadge.tsx
+msgid "Your Git credential configuration names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "你的 Git 憑證設定中指定了 {declaredLogin},但無法使用該帳戶的憑證。"
+
#: src/components/settings/SyncSection.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Your GitHub session expired — sign in again to verify push access."
@@ -14925,6 +14942,10 @@ msgstr "你本機的 <0>{branch}</0> 分支副本落後了。請拉取最新的
msgid "Your message didn't reach {agentName}."
msgstr "你的訊息未送達 {agentName}。"
+#: src/components/SyncStatusBadge.tsx
+msgid "Your remote URL names {declaredLogin}, but that account's credentials couldn't be used."
+msgstr "你的遠端 URL 中指定了 {declaredLogin},但無法使用該帳戶的憑證。"
+
#: src/components/BugReportSendToast.tsx
msgid "Your report is saved on this computer, so nothing was lost."
msgstr "你的回報已儲存在這台電腦上,沒有遺失任何內容。"
diff --git a/packages/cli/src/auth/gh-detect.test.ts b/packages/cli/src/auth/gh-detect.test.ts
index 5f398cb87..a8f3f9104 100644
--- a/packages/cli/src/auth/gh-detect.test.ts
+++ b/packages/cli/src/auth/gh-detect.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'vitest';
import type { ExecFileSyncFn } from './gh-detect.ts';
-import { detectGh } from './gh-detect.ts';
+import { detectGh, detectGhAccounts } from './gh-detect.ts';
function makeExec(responses: Record<string, { token?: string; error?: NodeJS.ErrnoException }>): {
exec: ExecFileSyncFn;
@@ -21,6 +21,27 @@ function makeExec(responses: Record<string, { token?: string; error?: NodeJS.Err
return { exec, calls };
}
+/**
+ * A scripted `gh` keyed on the full argv, so `--user` handling is observable.
+ * An argv with no scripted answer throws the way a non-zero `gh` exit reaches
+ * `execFileSync` — which is how an unknown account surfaces (`gh auth token
+ * --user <nobody>` exits 1 with empty stdout).
+ */
+function makeScriptedGh(script: Record<string, string>): {
+ exec: ExecFileSyncFn;
+ calls: string[];
+} {
+ const calls: string[] = [];
+ const exec = ((cmd: string, args: readonly string[]) => {
+ const argv = `${cmd} ${args.join(' ')}`;
+ calls.push(argv);
+ const out = script[argv];
+ if (out === undefined) throw new Error(`gh exited 1: ${argv}`);
+ return out;
+ }) as unknown as ExecFileSyncFn;
+ return { exec, calls };
+}
+
describe('detectGh', () => {
test('returns available:true with token when bare `gh` works', () => {
const { exec, calls } = makeExec({ gh: { token: 'ghu_abc123' } });
@@ -109,4 +130,285 @@ describe('detectGh', () => {
});
expect(result).toEqual({ available: false });
});
+ test('requests a specific account with --user when a login is supplied', () => {
+ const { exec, calls } = makeScriptedGh({
+ 'gh auth token --hostname github.com --user alice': 'gho_alice',
+ });
+
+ const result = detectGh('github.com', {
+ login: 'alice',
+ _exec: exec,
+ _fileExists: () => false,
+ });
+
+ expect(result).toEqual({
+ available: true,
+ token: 'gho_alice',
+ resolvedLogin: 'alice',
+ fallback: false,
+ });
+ expect(calls).toEqual(['gh auth token --hostname github.com --user alice']);
+ });
+ test('falls back to the active account when the requested login has no token', () => {
+ const { exec, calls } = makeScriptedGh({
+ 'gh auth token --hostname github.com': 'gho_active_bob',
+ });
+
+ const result = detectGh('github.com', {
+ login: 'alice',
+ _exec: exec,
+ _fileExists: () => false,
+ });
+
+ expect(result).toEqual({ available: true, token: 'gho_active_bob', fallback: true });
+ expect(calls).toEqual([
+ 'gh auth token --hostname github.com --user alice',
+ 'gh auth token --hostname github.com',
+ ]);
+ });
+
+ test('falls back to the active account when gh is too old to know --user', () => {
+ const calls: string[] = [];
+ const exec = ((cmd: string, args: readonly string[]) => {
+ const argv = `${cmd} ${args.join(' ')}`;
+ calls.push(argv);
+ if (args.includes('--user')) throw new Error('unknown flag: --user');
+ return 'gho_active_bob';
+ }) as unknown as ExecFileSyncFn;
+
+ const result = detectGh('github.com', {
+ login: 'alice',
+ _exec: exec,
+ _fileExists: () => false,
+ });
+
+ expect(result).toEqual({ available: true, token: 'gho_active_bob', fallback: true });
+ });
+
+ test('reports unavailable only when neither the requested login nor the active account answers', () => {
+ const { exec, calls } = makeScriptedGh({});
+
+ const result = detectGh('github.com', {
+ login: 'alice',
+ _exec: exec,
+ _fileExists: () => false,
+ });
+
+ expect(result).toEqual({ available: false });
+ expect(calls).toEqual([
+ 'gh auth token --hostname github.com --user alice',
+ 'gh auth token --hostname github.com',
+ ]);
+ });
+
+ test('a login-scoped lookup still reaches gh at a known install path', () => {
+ const { exec } = makeScriptedGh({
+ '/opt/homebrew/bin/gh auth token --hostname github.com --user alice': 'gho_alice',
+ });
+
+ const result = detectGh('github.com', {
+ login: 'alice',
+ _exec: exec,
+ _fileExists: (p) => p === '/opt/homebrew/bin/gh',
+ });
+
+ expect(result).toEqual({
+ available: true,
+ token: 'gho_alice',
+ resolvedLogin: 'alice',
+ fallback: false,
+ });
+ });
+});
+
+describe('detectGhAccounts', () => {
+ test('lists each account for the host and marks the active one', () => {
+ const { exec, calls } = makeScriptedGh({
+ 'gh auth status --hostname github.com --json hosts': JSON.stringify({
+ hosts: {
+ 'github.com': [
+ { state: 'success', active: true, host: 'github.com', login: 'bob' },
+ { state: 'success', active: false, host: 'github.com', login: 'alice' },
+ ],
+ },
+ }),
+ });
+
+ const accounts = detectGhAccounts('github.com', { _exec: exec, _fileExists: () => false });
+
+ expect(accounts).toEqual([
+ { login: 'bob', active: true },
+ { login: 'alice', active: false },
+ ]);
+ expect(calls).toEqual(['gh auth status --hostname github.com --json hosts']);
+ });
+
+ test('parses the text listing when gh is too old to know --json', () => {
+ const statusText = [
+ 'github.com',
+ ' \u2713 Logged in to github.com account bob (keyring)',
+ ' - Active account: true',
+ " - Token scopes: 'gist', 'read:org', 'repo'",
+ ' \u2713 Logged in to github.com account alice (keyring)',
+ ' - Active account: false',
+ " - Token scopes: 'repo'",
+ ].join('\n');
+ const { exec, calls } = makeScriptedGh({
+ 'gh auth status --hostname github.com': statusText,
+ });
+
+ const accounts = detectGhAccounts('github.com', { _exec: exec, _fileExists: () => false });
+
+ expect(accounts).toEqual([
+ { login: 'bob', active: true },
+ { login: 'alice', active: false },
+ ]);
+ expect(calls).toEqual([
+ 'gh auth status --hostname github.com --json hosts',
+ 'gh auth status --hostname github.com',
+ ]);
+ });
+
+ test('reports no list rather than guessing when gh cannot answer at all', () => {
+ const { exec, calls } = makeScriptedGh({});
+
+ const accounts = detectGhAccounts('github.com', { _exec: exec, _fileExists: () => false });
+
+ expect(accounts).toBeUndefined();
+ expect(calls).toEqual([
+ 'gh auth status --hostname github.com --json hosts',
+ 'gh auth status --hostname github.com',
+ ]);
+ });
+
+ test.each([
+ ['output that is not JSON at all', 'gh: unknown JSON fields: hosts'],
+ ['a JSON payload with no hosts key', '{"unexpected": "shape"}'],
+ ['a JSON payload whose host entries are not accounts', '{"hosts": {"github.com": "up"}}'],
+ ])('drops to the text listing given %s', (_case, jsonOutput) => {
+ const { exec } = makeScriptedGh({
+ 'gh auth status --hostname github.com --json hosts': jsonOutput,
+ 'gh auth status --hostname github.com':
+ ' \u2713 Logged in to github.com account alice (keyring)\n - Active account: true',
+ });
+
+ const accounts = detectGhAccounts('github.com', { _exec: exec, _fileExists: () => false });
+
+ expect(accounts).toEqual([{ login: 'alice', active: true }]);
+ });
+
+ // gh filters the payload by --hostname today; this pins that a payload
+ // carrying several hosts anyway cannot let a GHES account name itself as
+ // the identity behind a github.com probe.
+ test('a multi-host JSON payload reads only the requested host', () => {
+ const { exec } = makeScriptedGh({
+ 'gh auth status --hostname github.com --json hosts': JSON.stringify({
+ hosts: {
+ 'ghes.corp.example': [{ state: 'success', active: true, login: 'work-bot' }],
+ 'github.com': [{ state: 'success', active: true, login: 'alice' }],
+ },
+ }),
+ });
+
+ const accounts = detectGhAccounts('github.com', { _exec: exec, _fileExists: () => false });
+
+ expect(accounts).toEqual([{ login: 'alice', active: true }]);
+ });
+
+ // The narrowing must hold even when the payload does NOT key the requested
+ // host at all — flattening every host there would name a GHES account as
+ // the identity behind a github.com probe, the exact attribution the filter
+ // exists to prevent. And "doesn't describe that host" must read as
+ // cannot-tell, not as a confident empty listing: the text tier that
+ // follows can still hold the right answer.
+ test('a JSON payload that omits the requested host falls through to the text listing', () => {
+ const { exec, calls } = makeScriptedGh({
+ 'gh auth status --hostname github.com --json hosts': JSON.stringify({
+ hosts: {
+ 'ghes.corp.example': [{ state: 'success', active: true, login: 'work-bot' }],
+ },
+ }),
+ 'gh auth status --hostname github.com':
+ ' \u2713 Logged in to github.com account alice (keyring)\n - Active account: true',
+ });
+
+ const accounts = detectGhAccounts('github.com', { _exec: exec, _fileExists: () => false });
+
+ expect(accounts).toEqual([{ login: 'alice', active: true }]);
+ expect(calls).toEqual([
+ 'gh auth status --hostname github.com --json hosts',
+ 'gh auth status --hostname github.com',
+ ]);
+ });
+
+ test('a host-omitting payload with no text listing either reports no list — never another host', () => {
+ const { exec } = makeScriptedGh({
+ 'gh auth status --hostname github.com --json hosts': JSON.stringify({
+ hosts: {
+ 'ghes.corp.example': [{ state: 'success', active: true, login: 'work-bot' }],
+ },
+ }),
+ });
+
+ const accounts = detectGhAccounts('github.com', { _exec: exec, _fileExists: () => false });
+
+ expect(accounts).toBeUndefined();
+ });
+
+ // gh prints a failed account's DETAIL lines (including `- Active account:
+ // true`) after its "Failed to log in to" header, even though the header
+ // itself never becomes an account — so without an anchor reset the broken
+ // account's active flag lands on the healthy account parsed before it,
+ // and the identity copy then confidently names the wrong person.
+ test('a failed account\u2019s active flag does not attach to the previous healthy account', () => {
+ const statusText = [
+ 'github.com',
+ ' \u2713 Logged in to github.com account alice (keyring)',
+ ' - Active account: false',
+ ' - Git operations protocol: https',
+ ' X Failed to log in to github.com account bob (keyring)',
+ ' - Active account: true',
+ ' - The token in keyring is invalid.',
+ ].join('\n');
+ const { exec } = makeScriptedGh({
+ 'gh auth status --hostname github.com': statusText,
+ });
+
+ const accounts = detectGhAccounts('github.com', { _exec: exec, _fileExists: () => false });
+
+ expect(accounts).toEqual([{ login: 'alice', active: false }]);
+ });
+
+ test('a timed-out account\u2019s detail lines are dropped the same way', () => {
+ const statusText = [
+ 'github.com',
+ ' \u2713 Logged in to github.com account alice (keyring)',
+ ' - Active account: false',
+ ' X Timeout trying to log in to github.com account bob (keyring)',
+ ' - Active account: true',
+ ].join('\n');
+ const { exec } = makeScriptedGh({
+ 'gh auth status --hostname github.com': statusText,
+ });
+
+ const accounts = detectGhAccounts('github.com', { _exec: exec, _fileExists: () => false });
+
+ expect(accounts).toEqual([{ login: 'alice', active: false }]);
+ });
+
+ test('forced-color output still parses — ANSI codes never reach the login', () => {
+ const bold = (s: string) => `\u001b[1m${s}\u001b[0m`;
+ const statusText = [
+ 'github.com',
+ ` ✓ Logged in to github.com account ${bold('alice')} (keyring)`,
+ ' - Active account: true',
+ ].join('\n');
+ const { exec } = makeScriptedGh({
+ 'gh auth status --hostname github.com': statusText,
+ });
+
+ const accounts = detectGhAccounts('github.com', { _exec: exec, _fileExists: () => false });
+
+ expect(accounts).toEqual([{ login: 'alice', active: true }]);
+ });
});
diff --git a/packages/cli/src/auth/gh-detect.ts b/packages/cli/src/auth/gh-detect.ts
index 450e24858..1a8b87399 100644
--- a/packages/cli/src/auth/gh-detect.ts
+++ b/packages/cli/src/auth/gh-detect.ts
@@ -1,10 +1,24 @@
import { type ExecFileSyncOptionsWithStringEncoding, execFileSync } from 'node:child_process';
import { existsSync } from 'node:fs';
-export interface GhDetectResult {
- available: boolean;
- token?: string;
-}
+export type GhDetectResult =
+ | { available: false }
+ | {
+ available: true;
+ token: string;
+ /**
+ * The `gh` account that produced `token`. Undefined when the host's
+ * active account produced it — `gh auth token` names no account, so the
+ * only way to learn the active login is `detectGhAccounts`.
+ */
+ resolvedLogin?: string;
+ /**
+ * True when a requested account had no token and the active account
+ * answered instead. Callers that surface an identity must read
+ * `resolvedLogin`, not the login they asked for.
+ */
+ fallback?: boolean;
+ };
export type ExecFileSyncFn = typeof execFileSync;
type FileExistsFn = (path: string) => boolean;
@@ -25,14 +39,22 @@ const KNOWN_GH_PATHS: readonly string[] = [
'/usr/bin/gh', // Linux distro packages
];
-const GH_AUTH_TOKEN_OPTIONS: ExecFileSyncOptionsWithStringEncoding = {
+const GH_EXEC_OPTIONS: ExecFileSyncOptionsWithStringEncoding = {
encoding: 'utf-8',
stdio: ['ignore', 'pipe', 'pipe'],
timeout: 5000,
windowsHide: true,
};
-interface DetectGhOptions {
+export interface DetectGhOptions {
+ /**
+ * Scope the lookup to one of several accounts signed in to the same host.
+ * Carried on the options bag rather than as a positional parameter so the
+ * signature grows additively: `detectGh` is re-exported from the published
+ * package, and inserting a parameter ahead of this object would silently
+ * reinterpret an existing two-argument call.
+ */
+ login?: string;
/** Injectable for tests. */
_exec?: ExecFileSyncFn;
/** Injectable for tests. */
@@ -48,23 +70,200 @@ interface DetectGhOptions {
* the flag spelling — `gh auth token` rejects `--host` with "unknown flag";
* the canonical name is `--hostname` (alias `-h`).
*
+ * When `options.login` is provided, scopes the lookup further with `--user <login>` to
+ * pick one of several accounts signed in to the same host. A login that gh
+ * cannot serve is never fatal: the lookup retries without `--user` and returns
+ * the active account's token with `fallback: true`. Returning no credential
+ * instead would turn a wrong-identity push into a failed one, and the same
+ * retry covers gh versions predating `--user`, which reject the flag outright.
+ *
* Lookup order: bare `gh` via `PATH` first (fast path for shell launches),
* then `KNOWN_GH_PATHS` in order (only paths that exist on disk are tried).
* Stops at the first command that returns a non-empty token.
*/
export function detectGh(host?: string, options: DetectGhOptions = {}): GhDetectResult {
+ const { login } = options;
const exec = options._exec ?? execFileSync;
- const fileExists = options._fileExists ?? existsSync;
- const args = ['auth', 'token', ...(host ? ['--hostname', host] : [])];
- const candidates: string[] = ['gh', ...KNOWN_GH_PATHS.filter(fileExists)];
+ const candidates = ghCandidates(options._fileExists ?? existsSync);
+ const hostArgs = host ? ['--hostname', host] : [];
+
+ if (login) {
+ const token = firstNonEmptyOutput(exec, candidates, [
+ 'auth',
+ 'token',
+ ...hostArgs,
+ '--user',
+ login,
+ ]);
+ if (token) return { available: true, token, resolvedLogin: login, fallback: false };
+ }
+
+ const token = firstNonEmptyOutput(exec, candidates, ['auth', 'token', ...hostArgs]);
+ if (!token) return { available: false };
+ return login ? { available: true, token, fallback: true } : { available: true, token };
+}
+function ghCandidates(fileExists: FileExistsFn): string[] {
+ return ['gh', ...KNOWN_GH_PATHS.filter(fileExists)];
+}
+
+/**
+ * Runs one `gh` argv against each candidate path, stopping at the first that
+ * answers. A candidate that is missing, exits non-zero, or prints nothing is
+ * indistinguishable here on purpose: `gh` reports "no such account" the same
+ * way it reports "not installed" — non-zero exit, empty stdout.
+ */
+function firstNonEmptyOutput(
+ exec: ExecFileSyncFn,
+ candidates: readonly string[],
+ args: readonly string[],
+): string | undefined {
for (const cmd of candidates) {
try {
- const token = exec(cmd, args, GH_AUTH_TOKEN_OPTIONS).toString().trim();
- if (token.length > 0) return { available: true, token };
+ const out = exec(cmd, args, GH_EXEC_OPTIONS).toString().trim();
+ if (out.length > 0) return out;
} catch {
// Try next candidate
}
}
- return { available: false };
+ return undefined;
+}
+
+/** One `gh` account on a host, as reported by `gh auth status`. */
+export interface GhAccount {
+ login: string;
+ active: boolean;
+}
+
+/**
+ * List the `gh` accounts signed in to `host`, so a caller can name the identity
+ * behind a token `gh auth token` returned anonymously.
+ *
+ * Three tiers, because the account list is diagnostic and must never take an
+ * auth path down with it: the `--json` listing (gh 2.81+), then the
+ * multi-account text listing (gh 2.40+ — older gh prints
+ * `Logged in to <host> as <login>` with no active-account line and yields no
+ * accounts here, the same release boundary as `--user` itself), then
+ * `undefined` for "cannot tell".
+ */
+export function detectGhAccounts(
+ host?: string,
+ options: DetectGhOptions = {},
+): GhAccount[] | undefined {
+ const exec = options._exec ?? execFileSync;
+ const candidates = ghCandidates(options._fileExists ?? existsSync);
+ const statusArgs = ['auth', 'status', ...(host ? ['--hostname', host] : [])];
+
+ const json = firstNonEmptyOutput(exec, candidates, [...statusArgs, '--json', 'hosts']);
+ if (json !== undefined) {
+ const accounts = parseGhAccountsJson(json, host);
+ if (accounts) return accounts;
+ }
+
+ const text = firstNonEmptyOutput(exec, candidates, statusArgs);
+ if (text !== undefined) {
+ const accounts = parseGhAccountsText(text);
+ if (accounts.length > 0) return accounts;
+ }
+
+ return undefined;
+}
+
+function asRecord(value: unknown): Record<string, unknown> | undefined {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : undefined;
+}
+
+/**
+ * `gh auth status --json hosts` emits `{hosts: {<host>: [{login, active, ...}]}}`.
+ * That shape belongs to gh and moves on gh's release cadence, so anything that
+ * does not match returns undefined and lets the caller drop a tier rather than
+ * throw into a path whose real job is resolving a token.
+ *
+ * Structure is strict, fields are tolerant: a host whose value is not a list of
+ * entries means we are reading a payload we do not understand, and reporting
+ * "no accounts" for it would be a confident wrong answer where the text listing
+ * still holds the right one. An individual entry missing a login is skipped, so
+ * a future entry kind does not cost us the accounts alongside it.
+ *
+ * When `host` is given, only that host's entries are read — a payload that
+ * omits the host yields `undefined` ("this payload doesn't describe that
+ * host"), never another host's accounts and never a confident empty listing
+ * that would suppress the text tier still holding the right answer. gh
+ * already filters the payload by `--hostname` today, so this guards the
+ * future case where a payload carries several hosts: a flattened fallback
+ * would let a GHES account name itself as the identity behind a github.com
+ * probe.
+ */
+function parseGhAccountsJson(raw: string, host?: string): GhAccount[] | undefined {
+ let payload: unknown;
+ try {
+ payload = JSON.parse(raw);
+ } catch {
+ return undefined;
+ }
+
+ const hosts = asRecord(asRecord(payload)?.hosts);
+ if (!hosts) return undefined;
+
+ if (host !== undefined && hosts[host] === undefined) return undefined;
+ const entryLists = host !== undefined ? [hosts[host]] : Object.values(hosts);
+
+ const accounts: GhAccount[] = [];
+ for (const entries of entryLists) {
+ if (!Array.isArray(entries)) return undefined;
+ for (const entry of entries) {
+ const record = asRecord(entry);
+ if (!record) continue;
+ const login = record.login;
+ if (typeof login !== 'string' || login.length === 0) continue;
+ accounts.push({ login, active: record.active === true });
+ }
+ }
+ return accounts;
+}
+
+/**
+ * `gh auth status` prints one header line per account followed by that
+ * account's detail lines, so an `- Active account: true` line qualifies the
+ * header above it. A failed or timed-out account's header ("Failed to log in
+ * to …" / "Timeout trying to log in to …") never becomes an account — but gh
+ * still prints that account's detail lines, INCLUDING `- Active account:
+ * true`, so the parser must drop its anchor at such a header or the broken
+ * account's active flag lands on whichever healthy account came before it
+ * (and the identity copy then confidently names the wrong person).
+ */
+const GH_LOGGED_IN_LINE = /Logged in to \S+ account (\S+) \(/;
+const GH_FAILED_LOGIN_LINE = /(?:Failed to log in to|Timeout trying to log in to) \S+/;
+const GH_ACTIVE_ACCOUNT_LINE = /^\s*-\s*Active account:\s*true\s*$/;
+
+// gh bolds the login under forced color (CLICOLOR_FORCE / GH_FORCE_TTY), and
+// `\S+` would capture the escape codes with it — the ANSI is stripped before
+// matching so a forced-color environment doesn't corrupt every login this
+// parser feeds into identity copy.
+// biome-ignore lint/suspicious/noControlCharactersInRegex: matching the ANSI escape byte is the point
+const ANSI_SGR = /\u001b\[[0-9;]*m/g;
+
+function parseGhAccountsText(raw: string): GhAccount[] {
+ const accounts: GhAccount[] = [];
+ // The account the detail lines currently qualify — explicitly tracked (not
+ // `accounts.at(-1)`) so a failed account's details attach to nothing
+ // rather than to the last healthy account.
+ let anchor: GhAccount | undefined;
+ for (const rawLine of raw.split('\n')) {
+ const line = rawLine.replace(ANSI_SGR, '');
+ const login = GH_LOGGED_IN_LINE.exec(line)?.[1];
+ if (login) {
+ anchor = { login, active: false };
+ accounts.push(anchor);
+ continue;
+ }
+ if (GH_FAILED_LOGIN_LINE.test(line)) {
+ anchor = undefined;
+ continue;
+ }
+ if (anchor && GH_ACTIVE_ACCOUNT_LINE.test(line)) anchor.active = true;
+ }
+ return accounts;
}
diff --git a/packages/cli/src/auth/resolve-auth.test.ts b/packages/cli/src/auth/resolve-auth.test.ts
index aa3ba4530..4dfde15d3 100644
--- a/packages/cli/src/auth/resolve-auth.test.ts
+++ b/packages/cli/src/auth/resolve-auth.test.ts
@@ -2,7 +2,8 @@ import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
-import type { GhDetectResult } from './gh-detect.ts';
+import type { ExecFileSyncFn, GhDetectResult } from './gh-detect.ts';
+import { detectGh } from './gh-detect.ts';
import { buildCliCredentialHelper, resolveAuth } from './resolve-auth.ts';
import { FileBackend } from './token-store.ts';
@@ -74,6 +75,68 @@ describe('resolveAuth', () => {
expect(result.tier).toBe('A');
});
+ // ---------------------------------------------------------------------------
+ // Declared account: the login rides into gh's lookup and the relay names
+ // the account that actually produced the token
+ // ---------------------------------------------------------------------------
+
+ test('forwards the declared login to detectGh alongside the host', async () => {
+ const store = makeStore(tmpDir);
+ const seen: [string | undefined, string | undefined][] = [];
+ const recorder = (host?: string, opts?: { login?: string }): GhDetectResult => {
+ const login = opts?.login;
+ seen.push([host, login]);
+ return { available: true, token: 't' };
+ };
+ await resolveAuth('github.com', store, { selfCliArgs: SELF, login: 'alice' }, recorder);
+ expect(seen).toEqual([['github.com', 'alice']]);
+ });
+
+ test('relayToken names the account that produced the token', async () => {
+ const store = makeStore(tmpDir);
+ const result = await resolveAuth(
+ 'github.com',
+ store,
+ { selfCliArgs: SELF, login: 'alice' },
+ () => ({
+ available: true,
+ token: 'ghs_alice',
+ resolvedLogin: 'alice',
+ fallback: false,
+ }),
+ );
+ expect(result.relayToken).toEqual({ token: 'ghs_alice', host: 'github.com', login: 'alice' });
+ });
+
+ // The fallback floor through the REAL detectGh: a declared account gh
+ // cannot serve must degrade to the active account's token — never to tier
+ // 'none', which would turn a wrong-identity clone into an anonymous one.
+ // The relay then carries no login, so nothing downstream can claim the
+ // missed account.
+ test('a declared login gh cannot serve falls back to the active token, never to tier none', async () => {
+ const store = makeStore(tmpDir);
+ const calls: string[] = [];
+ const exec = ((cmd: string, args: readonly string[]) => {
+ const argv = `${cmd} ${args.join(' ')}`;
+ calls.push(argv);
+ if (argv === 'gh auth token --hostname github.com') return 'ghs_bob_active';
+ throw new Error(`gh exited 1: ${argv}`);
+ }) as unknown as ExecFileSyncFn;
+ const result = await resolveAuth(
+ 'github.com',
+ store,
+ { selfCliArgs: SELF, login: 'alice' },
+ (host, opts) => detectGh(host, { login: opts?.login, _exec: exec, _fileExists: () => false }),
+ );
+ expect(result.tier).toBe('A');
+ expect(result.relayToken).toEqual({ token: 'ghs_bob_active', host: 'github.com' });
+ expect(result.relayToken).not.toHaveProperty('login');
+ expect(calls).toEqual([
+ 'gh auth token --hostname github.com --user alice',
+ 'gh auth token --hostname github.com',
+ ]);
+ });
+
// ---------------------------------------------------------------------------
// Tier B — stored token (https): helper reads the store; no relay token
// ---------------------------------------------------------------------------
diff --git a/packages/cli/src/auth/resolve-auth.ts b/packages/cli/src/auth/resolve-auth.ts
index d7f1ff2eb..0cef52f92 100644
--- a/packages/cli/src/auth/resolve-auth.ts
+++ b/packages/cli/src/auth/resolve-auth.ts
@@ -15,6 +15,12 @@ interface RelayGhToken {
token: string;
/** Host the token authenticates; the helper host-matches before using it. */
host: string;
+ /**
+ * gh account that produced the token, when known. Absent for tokens the
+ * active account answered anonymously (`gh auth token` names no account), so
+ * diagnostics reading this must degrade to "identity unknown", never guess.
+ */
+ login?: string;
}
export interface ResolvedAuth {
@@ -38,6 +44,13 @@ export interface ResolvedAuth {
interface ResolveAuthOptions {
/** Skip gh detection even if gh is on PATH */
skipGhDetect?: boolean;
+ /**
+ * gh account to request the token for (`gh auth token --user <login>`),
+ * as declared by the remote URL's userinfo or a `credential.<url>.username`
+ * entry. A login gh cannot serve falls back to the active account inside
+ * `detectGh` — auth degrades to the active identity, never to no-credential.
+ */
+ login?: string;
/**
* argv that re-execs THIS CLI (`[execPath, cliEntry]`), used to build the
* self-referential credential helper. Defaults to the bare `open-knowledge`
@@ -87,7 +100,10 @@ export async function resolveAuth(
host: string,
tokenStore: TokenStore,
options: ResolveAuthOptions = {},
- _detectGhFn: (host?: string) => ReturnType<typeof detectGh> = detectGh,
+ _detectGhFn: (
+ host?: string,
+ options?: { login?: string },
+ ) => ReturnType<typeof detectGh> = detectGh,
): Promise<ResolvedAuth> {
const selfHelper = buildCliCredentialHelper(options.selfCliArgs ?? ['open-knowledge']);
// Empty reset first, then OK's helper — see ResolvedAuth.gitConfig.
@@ -95,9 +111,21 @@ export async function resolveAuth(
// Tier A: gh CLI — relay the gh-resolved token via env.
if (!options.skipGhDetect) {
- const gh = _detectGhFn(host);
+ const gh = _detectGhFn(host, { login: options.login });
if (gh.available && gh.token) {
- return { tier: 'A', gitConfig: authenticatedConfig, relayToken: { token: gh.token, host } };
+ return {
+ tier: 'A',
+ gitConfig: authenticatedConfig,
+ // `resolvedLogin`, never the requested login: after detectGh's
+ // fallback the token belongs to the active account, and relaying the
+ // missed name would let diagnostics claim an identity the token
+ // does not have.
+ relayToken: {
+ token: gh.token,
+ host,
+ ...(gh.resolvedLogin ? { login: gh.resolvedLogin } : {}),
+ },
+ };
}
}
diff --git a/packages/cli/src/auth/token-store.ts b/packages/cli/src/auth/token-store.ts
index 13924d347..c13e1cacf 100644
--- a/packages/cli/src/auth/token-store.ts
+++ b/packages/cli/src/auth/token-store.ts
@@ -353,17 +353,20 @@ function lazyResolveTokenStore(authFile: string | undefined): () => Promise<Toke
/**
* Push-permission-probe-shaped token store. Returns immediately; defers
* the underlying `createTokenStore()` to the first `.get()` call.
- * Structural shape matches the server's `ProbeTokenStore` interface.
+ * Structural shape matches the server's `ProbeTokenStore` interface —
+ * including `login`, which the probe uses to attribute a denial to the
+ * stored account (the store's `'unknown'` placeholder is filtered on the
+ * server side, not here).
*/
export function makeLazyProbeTokenStore(authFile?: string): {
- get: (host: string) => Promise<{ token?: string } | null>;
+ get: (host: string) => Promise<{ token?: string; login?: string } | null>;
} {
const resolve = lazyResolveTokenStore(authFile);
return {
async get(host: string) {
const store = await resolve();
const entry = await store.get(host);
- return entry === null ? null : { token: entry.token };
+ return entry === null ? null : { token: entry.token, login: entry.login };
},
};
}
diff --git a/packages/cli/src/commands/auth/git-credential.test.ts b/packages/cli/src/commands/auth/git-credential.test.ts
index 99ce80ee7..715205ae4 100644
--- a/packages/cli/src/commands/auth/git-credential.test.ts
+++ b/packages/cli/src/commands/auth/git-credential.test.ts
@@ -283,13 +283,16 @@ describe('handleCredentialGet gh-token relay', () => {
let tmpDir: string;
let savedToken: string | undefined;
let savedHost: string | undefined;
+ let savedLogin: string | undefined;
beforeEach(() => {
tmpDir = mkdtempSync(join(tmpdir(), 'ok-git-cred-relay-'));
savedToken = process.env.OK_GH_TOKEN;
savedHost = process.env.OK_GH_TOKEN_HOST;
+ savedLogin = process.env.OK_GH_TOKEN_LOGIN;
delete process.env.OK_GH_TOKEN;
delete process.env.OK_GH_TOKEN_HOST;
+ delete process.env.OK_GH_TOKEN_LOGIN;
});
afterEach(() => {
rmSync(tmpDir, { recursive: true, force: true });
@@ -297,6 +300,8 @@ describe('handleCredentialGet gh-token relay', () => {
else process.env.OK_GH_TOKEN = savedToken;
if (savedHost === undefined) delete process.env.OK_GH_TOKEN_HOST;
else process.env.OK_GH_TOKEN_HOST = savedHost;
+ if (savedLogin === undefined) delete process.env.OK_GH_TOKEN_LOGIN;
+ else process.env.OK_GH_TOKEN_LOGIN = savedLogin;
});
test('relayed token for a matching host wins over the stored entry', async () => {
@@ -326,6 +331,25 @@ describe('handleCredentialGet gh-token relay', () => {
expect(result()).toBe('username=x-access-token\npassword=gho_relayed\n');
});
+ test('the host is the only relay gate — a username mismatch does not block it', async () => {
+ // git forwards a URL-declared username (`https://bob@…`) with the request,
+ // and the server names the token's account in OK_GH_TOKEN_LOGIN. Neither
+ // may gate the relay: the token was chosen upstream, login-aware, and a
+ // helper-side identity check would re-introduce the stripped-PATH failure
+ // mode that keeps account resolution out of this process.
+ const store = makeStore(tmpDir);
+ process.env.OK_GH_TOKEN = 'gho_relayed';
+ process.env.OK_GH_TOKEN_HOST = 'github.com';
+ process.env.OK_GH_TOKEN_LOGIN = 'alice';
+ const input = makeStream('protocol=https\nhost=github.com\nusername=bob\n\n');
+ const { writable, result } = makeOutput();
+
+ const code = await handleCredentialGet(input, writable, store);
+
+ expect(code).toBe(0);
+ expect(result()).toBe('username=x-access-token\npassword=gho_relayed\n');
+ });
+
test('host mismatch falls through to the stored entry', async () => {
const store = makeStore(tmpDir);
await store.set('github.com', 'alice', 'gho_stored');
diff --git a/packages/cli/src/commands/auth/git-credential.ts b/packages/cli/src/commands/auth/git-credential.ts
index ab99bfa9b..d04857707 100644
--- a/packages/cli/src/commands/auth/git-credential.ts
+++ b/packages/cli/src/commands/auth/git-credential.ts
@@ -66,8 +66,17 @@ export async function handleCredentialGet(
const relayToken = process.env.OK_GH_TOKEN;
const relayTokenHost = process.env.OK_GH_TOKEN_HOST;
if (relayToken && relayTokenHost === host) {
+ // `relayLogin` mirrors the diagnostics-only OK_GH_TOKEN_LOGIN env var —
+ // the one place an operator investigating a wrong-identity push can see
+ // which account's token the relay served. Never a gate: the host guard
+ // above stays the only relay condition.
ctx?.log?.debug(
- { host, outcome: 'gh-env-token', backend: tokenStore.backend },
+ {
+ host,
+ outcome: 'gh-env-token',
+ backend: tokenStore.backend,
+ relayLogin: process.env.OK_GH_TOKEN_LOGIN,
+ },
'[auth] git-credential get',
);
output.write(`username=x-access-token\npassword=${safeLine(relayToken)}\n`);
diff --git a/packages/cli/src/commands/clone.test.ts b/packages/cli/src/commands/clone.test.ts
index e29f3a235..ccdaf13ac 100644
--- a/packages/cli/src/commands/clone.test.ts
+++ b/packages/cli/src/commands/clone.test.ts
@@ -1,11 +1,14 @@
import { execFileSync } from 'node:child_process';
-import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
+import { pathToFileURL } from 'node:url';
import type { Config } from '@inkeep/open-knowledge-server';
import simpleGit, { type SimpleGitOptions } from 'simple-git';
import { afterEach, beforeEach, describe, expect, it, test } from 'vitest';
-import type { TokenStore } from '../auth/token-store.ts';
+import type { ExecFileSyncFn, GhDetectResult } from '../auth/gh-detect.ts';
+import { detectGh } from '../auth/gh-detect.ts';
+import { FileBackend, type TokenStore } from '../auth/token-store.ts';
import { OK_DIR } from '../constants.ts';
import {
buildCloneArgs,
@@ -16,8 +19,10 @@ import {
emitCloneFailure,
ensureOkExcludedFromGit,
formatCloneAuthFailure,
+ formatDeclaredMissWarning,
handleCloneFailure,
isBranchNotFoundError,
+ resolveCloneAuth,
resolveClonePrincipal,
resolveCloneUrl,
resolveSelfCliArgs,
@@ -96,6 +101,275 @@ describe('resolveCloneUrl', () => {
'https://github.com/inkeep/playbooks',
);
});
+
+ // The stored remote is the bridge between clone-time and sync-time identity:
+ // `git clone` records the URL argument verbatim, so passing the userinfo
+ // form through unchanged is what lets the sync engine later resolve the
+ // same declared account from `.git/config` with no further configuration.
+ test('passes a userinfo https URL through unchanged (the stored remote keeps the declared account)', () => {
+ const url = 'https://[email protected]/inkeep/playbooks';
+ expect(resolveCloneUrl(url, parsed('inkeep', 'playbooks'))).toBe(url);
+ });
+});
+
+describe('resolveCloneAuth', () => {
+ let tmpDir: string;
+ beforeEach(() => {
+ tmpDir = mkdtempSync(join(tmpdir(), 'ok-clone-auth-'));
+ });
+ afterEach(() => {
+ rmSync(tmpDir, { recursive: true, force: true });
+ });
+
+ const SELF: readonly string[] = ['/node', '/cli.mjs'];
+ const makeStore = () => new FileBackend(join(tmpDir, 'auth.yml'));
+
+ /**
+ * A scripted `gh` behind the real `detectGh`, keyed on the full argv so
+ * `--user` handling is observable. An argv with no scripted answer throws
+ * the way a non-zero `gh` exit reaches `execFileSync` — which is how an
+ * unknown account surfaces.
+ */
+ function scriptedGh(script: Record<string, string>): {
+ detect: (host?: string, options?: { login?: string }) => GhDetectResult;
+ calls: string[];
+ } {
+ const calls: string[] = [];
+ const exec = ((cmd: string, args: readonly string[]) => {
+ const argv = `${cmd} ${args.join(' ')}`;
+ calls.push(argv);
+ const out = script[argv];
+ if (out === undefined) throw new Error(`gh exited 1: ${argv}`);
+ return out;
+ }) as unknown as ExecFileSyncFn;
+ return {
+ detect: (host?: string, options?: { login?: string }) =>
+ detectGh(host, { login: options?.login, _exec: exec, _fileExists: () => false }),
+ calls,
+ };
+ }
+
+ // Tracer for the whole clone leg: the URL-declared account crosses the
+ // server-side resolver into gh's lookup, and the relay names it.
+ test('a userinfo clone URL authenticates as that account', async () => {
+ const gh = scriptedGh({
+ 'gh auth token --hostname github.com --user alice': 'ghs_alice',
+ 'gh auth token --hostname github.com': 'ghs_bob_active',
+ });
+ const { auth: resolved, declaredMiss } = await resolveCloneAuth(
+ 'https://[email protected]/o/r',
+ makeStore(),
+ {
+ selfCliArgs: SELF,
+ _detectGhFn: gh.detect,
+ },
+ );
+ expect(resolved.tier).toBe('A');
+ expect(resolved.relayToken).toEqual({ token: 'ghs_alice', host: 'github.com', login: 'alice' });
+ expect(gh.calls).toEqual(['gh auth token --hostname github.com --user alice']);
+ // Honored request — nothing to warn about.
+ expect(declaredMiss).toBeUndefined();
+ });
+
+ test('a credential.<url>.username declaration rides into gh the same way', async () => {
+ const gh = scriptedGh({
+ 'gh auth token --hostname github.com --user workbot': 'ghs_workbot',
+ });
+ const { auth: resolved, declaredMiss } = await resolveCloneAuth(
+ 'https://github.com/bigcorp/secret',
+ makeStore(),
+ {
+ selfCliArgs: SELF,
+ _detectGhFn: gh.detect,
+ _readCredentialUrlMatch: () =>
+ 'credential.helper osxkeychain\ncredential.username workbot\n',
+ },
+ );
+ expect(declaredMiss).toBeUndefined();
+ expect(resolved.relayToken).toEqual({
+ token: 'ghs_workbot',
+ host: 'github.com',
+ login: 'workbot',
+ });
+ expect(gh.calls).toEqual(['gh auth token --hostname github.com --user workbot']);
+ });
+
+ test('no declared account: gh is asked without --user — the repo owner never becomes an account selector', async () => {
+ const gh = scriptedGh({ 'gh auth token --hostname github.com': 'ghs_active' });
+ const { auth: resolved, declaredMiss } = await resolveCloneAuth(
+ 'https://github.com/inkeep/some-repo',
+ makeStore(),
+ {
+ selfCliArgs: SELF,
+ _detectGhFn: gh.detect,
+ _readCredentialUrlMatch: () => null,
+ },
+ );
+ expect(resolved.tier).toBe('A');
+ expect(resolved.relayToken).toEqual({ token: 'ghs_active', host: 'github.com' });
+ expect(gh.calls).toEqual(['gh auth token --hostname github.com']);
+ // No declaration — an active-account resolution is never a "miss".
+ expect(declaredMiss).toBeUndefined();
+ });
+
+ test('an unparseable clone URL is rejected the way runClone rejects it', async () => {
+ await expect(resolveCloneAuth('not-a-url', makeStore(), { selfCliArgs: SELF })).rejects.toThrow(
+ 'Invalid git URL: not-a-url',
+ );
+ });
+
+ test('a declared account gh cannot serve falls back to the active token, never to tier none', async () => {
+ const gh = scriptedGh({ 'gh auth token --hostname github.com': 'ghs_bob_active' });
+ const { auth: resolved, declaredMiss } = await resolveCloneAuth(
+ 'https://[email protected]/o/r',
+ makeStore(),
+ {
+ selfCliArgs: SELF,
+ _detectGhFn: gh.detect,
+ },
+ );
+ expect(resolved.tier).toBe('A');
+ expect(resolved.relayToken).toEqual({ token: 'ghs_bob_active', host: 'github.com' });
+ expect(resolved.relayToken).not.toHaveProperty('login');
+ expect(gh.calls).toEqual([
+ 'gh auth token --hostname github.com --user alice',
+ 'gh auth token --hostname github.com',
+ ]);
+ // The proven gh-tier fallback is reported so the caller can leave the
+ // sole trace of a clone that succeeds as the wrong account.
+ expect(declaredMiss).toEqual({ declaredLogin: 'alice', declaredSource: 'remote-url' });
+ });
+
+ // The clone leg's own casing comparison, pinned at the injectable seam: an
+ // implementation that answers a `--user Alice` request under GitHub's
+ // canonical `alice` spelling named the SAME person, so no warning is due.
+ // (The real `detectGh` echoes the requested string, so only an injected or
+ // future implementation exercises this — which is exactly why the seam,
+ // not the caller, is where it has to hold.)
+ test('a resolved login differing only in case is not a declared miss', async () => {
+ const { auth: resolved, declaredMiss } = await resolveCloneAuth(
+ 'https://[email protected]/o/r',
+ makeStore(),
+ {
+ selfCliArgs: SELF,
+ _detectGhFn: () => ({
+ available: true,
+ token: 'ghs_alice',
+ resolvedLogin: 'alice',
+ fallback: false,
+ }),
+ },
+ );
+ expect(resolved.tier).toBe('A');
+ expect(resolved.relayToken?.login).toBe('alice');
+ expect(declaredMiss).toBeUndefined();
+ });
+
+ test('a credential-config declaration gh cannot serve reports the miss with its mechanism', async () => {
+ const gh = scriptedGh({ 'gh auth token --hostname github.com': 'ghs_bob_active' });
+ const { declaredMiss } = await resolveCloneAuth(
+ 'https://github.com/bigcorp/secret',
+ makeStore(),
+ {
+ selfCliArgs: SELF,
+ _detectGhFn: gh.detect,
+ _readCredentialUrlMatch: () =>
+ 'credential.helper osxkeychain\ncredential.username workbot\n',
+ },
+ );
+ expect(declaredMiss).toEqual({ declaredLogin: 'workbot', declaredSource: 'credential-config' });
+ });
+
+ // One host spelling per remote: the account resolver normalizes
+ // (lowercase, www-fold) exactly as the post-clone sync path does, so gh's
+ // `--hostname` scope and the relay's host guard must receive that
+ // normalized form, not the CLI parse's raw spelling — two spellings is how
+ // a clone and its later sync end up authenticating differently.
+ test('a non-canonical host spelling resolves gh and the relay against the normalized host', async () => {
+ const gh = scriptedGh({
+ 'gh auth token --hostname github.com --user alice': 'ghs_alice',
+ });
+ const { auth: resolved } = await resolveCloneAuth(
+ 'https://[email protected]/o/r',
+ makeStore(),
+ {
+ selfCliArgs: SELF,
+ _detectGhFn: gh.detect,
+ },
+ );
+ expect(resolved.relayToken).toEqual({ token: 'ghs_alice', host: 'github.com', login: 'alice' });
+ expect(gh.calls).toEqual(['gh auth token --hostname github.com --user alice']);
+ });
+
+ test('an unparseable URL with an embedded credential is not echoed into the error', async () => {
+ await expect(
+ resolveCloneAuth('https://user:s3cretpw@%%%bogus', makeStore(), { selfCliArgs: SELF }),
+ ).rejects.toThrow(/^(?!.*s3cretpw).*Invalid git URL/);
+ });
+});
+
+describe('formatDeclaredMissWarning', () => {
+ test('names the remote-URL mechanism', () => {
+ expect(
+ formatDeclaredMissWarning({
+ declaredLogin: 'alice',
+ declaredSource: 'remote-url',
+ }),
+ ).toContain(
+ "\u26a0 The clone URL names alice, but the GitHub CLI couldn't confirm that account — the clone used its active account.\n",
+ );
+ });
+
+ test('names the credential-config mechanism', () => {
+ const line = formatDeclaredMissWarning({
+ declaredLogin: 'workbot',
+ declaredSource: 'credential-config',
+ });
+ expect(line).toContain('Your Git credential configuration names workbot');
+ expect(line?.endsWith('\n')).toBe(true);
+ });
+
+ // A declaration mechanism added later must land on neutral wording rather
+ // than silently borrowing another mechanism's sentence.
+ test('an unrecognized mechanism degrades to the generic wording', () => {
+ const line = formatDeclaredMissWarning({
+ declaredLogin: 'alice',
+ declaredSource: 'far-future-mechanism' as 'remote-url',
+ });
+ expect(line).toContain('Your Git configuration names alice');
+ expect(line).not.toContain('clone URL');
+ expect(line).not.toContain('credential configuration');
+ });
+
+ test('an honored declaration produces no warning', () => {
+ expect(formatDeclaredMissWarning(undefined)).toBeNull();
+ });
+
+ // The copy must not claim another account answered: a fallback only proves
+ // gh did not confirm the request (gh < 2.40 rejects --user outright, and a
+ // casing-only difference falls back by design), so the token may well be
+ // the declared person's.
+ test("the copy asserts only that the account wasn't confirmed", () => {
+ const line = formatDeclaredMissWarning({
+ declaredLogin: 'alice',
+ declaredSource: 'remote-url',
+ });
+ expect(line).toContain("couldn't confirm that account");
+ expect(line).not.toContain('credentials couldn');
+ });
+
+ // Both benign causes (gh below the 2.40 --user floor, a casing-only
+ // declaration) are indistinguishable from a real miss here, so the copy
+ // must hand the user a check rather than a verdict they cannot falsify.
+ test('the warning names a command that settles the false-alarm cases', () => {
+ const line = formatDeclaredMissWarning({
+ declaredLogin: 'alice',
+ declaredSource: 'remote-url',
+ });
+ expect(line).toContain('gh auth status');
+ expect(line).toContain('2.40');
+ expect(line).toContain('If alice is listed as active');
+ });
});
describe('handleCloneFailure', () => {
@@ -168,6 +442,88 @@ describe('handleCloneFailure', () => {
expect(c.emitted).toEqual([{ type: 'error', message: 'remote: HTTP 403 Forbidden' }]);
expect(c.stderr).toEqual([]);
});
+
+ // When OK supplied a gh-resolved credential, the identity in hand is
+ // authoritative — the stored-token principal can name an account the clone
+ // never used.
+ test('403 with gh-resolved auth names the resolved login and skips the stored principal', async () => {
+ const c = collectors();
+ let called = false;
+ await handleCloneFailure({
+ error: new Error('remote: HTTP 403 Forbidden'),
+ url: 'https://github.com/owner/repo',
+ branch: null,
+ json: false,
+ emit: c.emit,
+ printStderr: c.printStderr,
+ auth: { tier: 'A', login: 'bob' },
+ resolvePrincipal: async () => {
+ called = true;
+ return 'stored-alice';
+ },
+ });
+ expect(called).toBe(false);
+ expect(c.stderr.join('')).toContain('@bob');
+ expect(c.stderr.join('')).not.toContain('stored-alice');
+ });
+
+ test('403 with an unnamed gh credential omits the hint rather than guessing', async () => {
+ const c = collectors();
+ let called = false;
+ await handleCloneFailure({
+ error: new Error('remote: HTTP 403 Forbidden'),
+ url: 'https://github.com/owner/repo',
+ branch: null,
+ json: false,
+ emit: c.emit,
+ printStderr: c.printStderr,
+ auth: { tier: 'A' },
+ resolvePrincipal: async () => {
+ called = true;
+ return 'stored-alice';
+ },
+ });
+ expect(called).toBe(false);
+ expect(c.stderr.join('')).not.toContain('signed in as');
+ });
+
+ test('the 404 masquerade names the account the clone used when known', async () => {
+ const c = collectors();
+ await handleCloneFailure({
+ error: new Error("fatal: repository 'https://github.com/o/private.git/' not found"),
+ url: 'https://github.com/o/private',
+ branch: null,
+ json: false,
+ emit: c.emit,
+ printStderr: c.printStderr,
+ auth: { tier: 'A', login: 'bob' },
+ });
+ expect(c.stderr.join('')).toContain('Authenticated as bob.');
+ });
+
+ // A `tier: 'none'` clone presented no credential (the public-repo
+ // short-circuit), so a 403 — e.g. rate limiting — authenticated as nobody;
+ // "signed in as @<stored>" would blame an account the request never carried.
+ test('403 on a credential-less clone names nobody and skips the stored principal', async () => {
+ const c = collectors();
+ let called = false;
+ await handleCloneFailure({
+ error: new Error('remote: HTTP 403 Forbidden'),
+ url: 'https://github.com/owner/repo',
+ branch: null,
+ json: false,
+ emit: c.emit,
+ printStderr: c.printStderr,
+ auth: { tier: 'none' },
+ resolvePrincipal: async () => {
+ called = true;
+ return 'stored-alice';
+ },
+ });
+ expect(called).toBe(false);
+ expect(c.stderr.join('')).not.toContain('signed in as');
+ expect(c.stderr.join('')).not.toContain('stored-alice');
+ });
});
describe('buildCloneEnv', () => {
@@ -243,6 +599,31 @@ describe('buildCloneAuthEnv', () => {
expect(env.OK_GH_TOKEN).toBe('ghs_fresh');
expect(env.OK_GH_TOKEN_HOST).toBe('ghes.acme.test');
});
+
+ // OK_GH_TOKEN_LOGIN is diagnostics-only: it names the account behind the
+ // relayed token for the helper's logs. The helper never gates on it — the
+ // host guard remains the only relay condition.
+ test('relays OK_GH_TOKEN_LOGIN when the relay token names its account', () => {
+ const env = buildCloneAuthEnv(
+ { relayToken: { token: 'ghs_relay', host: 'github.com', login: 'alice' } },
+ { PATH: '/usr/bin' },
+ );
+ expect(env.OK_GH_TOKEN_LOGIN).toBe('alice');
+ });
+
+ test('an anonymous relay token sets no login var and strips an inherited one', () => {
+ const env = buildCloneAuthEnv(
+ { relayToken: { token: 'ghs_relay', host: 'github.com' } },
+ { PATH: '/usr/bin', OK_GH_TOKEN_LOGIN: 'stale-name' },
+ );
+ expect(env.OK_GH_TOKEN).toBe('ghs_relay');
+ expect('OK_GH_TOKEN_LOGIN' in env).toBe(false);
+ });
+
+ test('strips an inherited OK_GH_TOKEN_LOGIN when no relay token was resolved', () => {
+ const env = buildCloneAuthEnv({}, { PATH: '/usr/bin', OK_GH_TOKEN_LOGIN: 'stale-name' });
+ expect('OK_GH_TOKEN_LOGIN' in env).toBe(false);
+ });
});
describe('buildCloneGitOptions', () => {
@@ -672,6 +1053,76 @@ describe('isBranchNotFoundError', () => {
});
describe('formatCloneAuthFailure', () => {
+ // Userinfo clone URLs are a supported input, so a `user:password@` form can
+ // reach a failure message. The password half must not be echoed back into
+ // terminal scrollback — while the username half stays, so the suggested
+ // re-run keeps the identity declaration and still clones as that account.
+ test('an embedded password never reaches the message or the re-run command', () => {
+ const out = formatCloneAuthFailure({
+ error: new Error('fatal: could not read Username for https://github.com'),
+ url: 'https://alice:[email protected]/inkeep/playbooks',
+ branch: 'feat-x',
+ });
+ expect(out).not.toBeNull();
+ expect(out).not.toContain('s3cretpw');
+ expect(out).toContain(
+ '2. Then re-run: ok clone https://[email protected]/inkeep/playbooks -b feat-x',
+ );
+ });
+
+ test('the 404 masquerade echo also drops an embedded password', () => {
+ const out = formatCloneAuthFailure({
+ error: new Error("fatal: repository 'https://github.com/o/private.git/' not found"),
+ url: 'https://alice:[email protected]/o/private',
+ });
+ expect(out).not.toBeNull();
+ expect(out).not.toContain('s3cretpw');
+ expect(out).toContain('Repository not found when cloning https://[email protected]/o/private');
+ });
+
+ // GitHub's canonical PAT-in-URL form puts the token in the USERNAME half —
+ // a credential-shaped username must be dropped, not echoed or promoted.
+ test('a bare token-as-username never reaches the message or the re-run command', () => {
+ const tok = `ghp_${'A'.repeat(36)}`;
+ const out = formatCloneAuthFailure({
+ error: new Error('fatal: could not read Username for https://github.com'),
+ url: `https://${tok}@github.com/o/r`,
+ branch: null,
+ });
+ expect(out).not.toBeNull();
+ expect(out).not.toContain(tok);
+ expect(out).toContain('ok clone https://github.com/o/r');
+ });
+
+ test('a token paired with a placeholder password is dropped, not promoted to the username', () => {
+ const tok = `ghp_${'B'.repeat(36)}`;
+ const out = formatCloneAuthFailure({
+ error: new Error("fatal: repository 'https://github.com/o/r.git/' not found"),
+ url: `https://${tok}:[email protected]/o/r`,
+ });
+ expect(out).not.toBeNull();
+ expect(out).not.toContain(tok);
+ });
+
+ test('a fine-grained PAT username is dropped', () => {
+ const tok = `github_pat_${'C'.repeat(70)}`;
+ const out = formatCloneAuthFailure({
+ error: new Error('remote: HTTP 401 Unauthorized'),
+ url: `https://${tok}@github.com/o/r`,
+ });
+ expect(out).not.toBeNull();
+ expect(out).not.toContain(tok);
+ });
+
+ test('a real login survives so the re-run keeps the identity declaration', () => {
+ const out = formatCloneAuthFailure({
+ error: new Error('fatal: could not read Username for https://github.com'),
+ url: 'https://[email protected]/o/r',
+ branch: null,
+ });
+ expect(out).toContain('ok clone https://[email protected]/o/r');
+ });
+
test('returns null for non-auth errors so the caller falls through to the raw git error', () => {
expect(
formatCloneAuthFailure({
@@ -751,6 +1202,24 @@ describe('formatCloneAuthFailure', () => {
expect(out).toContain('may lack access');
});
+ test('repository-not-found (404 masquerade) → not-found-or-no-access copy, no recovery command', () => {
+ const out = formatCloneAuthFailure({
+ error: new Error("fatal: repository 'https://github.com/o/private.git/' not found"),
+ url: 'https://github.com/o/private',
+ branch: 'main',
+ });
+ expect(out).not.toBeNull();
+ expect(out).toContain('Repository not found when cloning https://github.com/o/private');
+ expect(out).toContain('may not exist');
+ expect(out).toContain('may not have access');
+ // Neither recovery flow applies here: re-login mints the same account's
+ // credential, and OAuth scopes are not the problem — offering either
+ // would send the user down a dead end.
+ expect(out).not.toContain('ok auth login');
+ expect(out).not.toContain('ok auth pat');
+ expect(out).not.toContain('scope');
+ });
+
test('scope-mismatch → actionable PAT recovery (ok auth pat + re-run), not ok auth login', () => {
const out = formatCloneAuthFailure({
error: new Error('insufficient scopes'),
@@ -792,6 +1261,132 @@ describe('formatCloneAuthFailure', () => {
});
});
+// A userinfo containing whitespace is the shape that distinguishes the two
+// redactors: `stripUrlPassword` is `^`-anchored on one URL, so excluding `\s`
+// from its userinfo class makes the whole match FAIL and echoes the credential
+// instead of stripping it. The share-publish redactor genuinely needs that
+// exclusion because it scans free-form stderr with /g. Both call paths here
+// reach the user's terminal and the copy-pasteable re-run command.
+// The sole trace on the clone leg when a fallback SUCCEEDS as the wrong
+// account. The formatter tests cover the wording; only this covers whether the
+// warning is emitted at all and on which channel — stdout is the `--json`
+// machine wire. Hermetic: the visibility probe short-circuits for any
+// non-github.com host, and the clone that follows fails instantly against a
+// closed loopback port (no DNS, no external network).
+describe('runClone declared-miss warning', () => {
+ let tmp: string;
+ let stderrChunks: string[];
+ let stdoutChunks: string[];
+ let restore: (() => void) | null = null;
+
+ beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), 'ok-clone-warn-'));
+ stderrChunks = [];
+ stdoutChunks = [];
+ const realErr = process.stderr.write.bind(process.stderr);
+ const realOut = process.stdout.write.bind(process.stdout);
+ process.stderr.write = ((c: string) => {
+ stderrChunks.push(String(c));
+ return true;
+ }) as typeof process.stderr.write;
+ process.stdout.write = ((c: string) => {
+ stdoutChunks.push(String(c));
+ return true;
+ }) as typeof process.stdout.write;
+ restore = () => {
+ process.stderr.write = realErr;
+ process.stdout.write = realOut;
+ };
+ });
+
+ afterEach(() => {
+ restore?.();
+ restore = null;
+ rmSync(tmp, { recursive: true, force: true });
+ });
+
+ /** gh answers, but never for the requested account — the fallback shape. */
+ const fallbackGh = () => ({ available: true as const, token: 'ghs_active', fallback: true });
+
+ async function cloneAndIgnoreFailure(json: boolean): Promise<void> {
+ await runClone(
+ 'https://[email protected]:1/o/r.git',
+ { json, dir: join(tmp, 'out'), _detectGhFn: fallbackGh },
+ {} as never,
+ tmp,
+ ).catch(() => {
+ // The clone itself cannot succeed against a closed port; the warning is
+ // emitted before it runs, which is what this asserts.
+ });
+ }
+
+ test('the human path writes the warning to stderr and never to stdout', async () => {
+ await cloneAndIgnoreFailure(false);
+ expect(stderrChunks.join('')).toContain('The clone URL names alice');
+ expect(stdoutChunks.join('')).not.toContain('\u26a0');
+ });
+
+ test('--json suppresses the warning on both channels', async () => {
+ await cloneAndIgnoreFailure(true);
+ expect(stderrChunks.join('')).not.toContain('The clone URL names alice');
+ expect(stdoutChunks.join('')).not.toContain('\u26a0');
+ });
+
+ // Pins the runClone -> resolveCloneAuth junction itself, not just
+ // resolveCloneAuth's internals. Reverting that call site back to a host-only
+ // resolve would leave every other clone test green while silently dropping
+ // the declared account on the clone path, so the probe and the push would
+ // agree on an identity the clone no longer used.
+ test('the URL-declared login reaches detectGh from runClone itself', async () => {
+ const seen: Array<{ host?: string; login?: string }> = [];
+ const recordingGh = (host?: string, options?: { login?: string }) => {
+ seen.push({ host, login: options?.login });
+ return { available: true as const, token: 'ghs_active', fallback: true };
+ };
+ await runClone(
+ 'https://[email protected]:1/o/r.git',
+ { json: false, dir: join(tmp, 'out'), _detectGhFn: recordingGh },
+ {} as never,
+ tmp,
+ ).catch(() => {
+ // Unreachable port: the clone cannot succeed, but auth resolution has
+ // already run by then, which is what this asserts.
+ });
+
+ expect(seen).toContainEqual({ host: '127.0.0.1', login: 'alice' });
+ expect(seen.every((c) => c.login === 'alice')).toBe(true);
+ });
+});
+
+describe('formatCloneAuthFailure credential redaction', () => {
+ const TOKEN = `ghp_${'a'.repeat(36)}`;
+
+ test('a whitespace-bearing userinfo is still stripped, not echoed', () => {
+ const out = formatCloneAuthFailure({
+ error: new Error("fatal: repository 'https://x/y' not found"),
+ url: `https://foo bar:${TOKEN}@github.com/o/r.git`,
+ branch: null,
+ });
+ expect(out).not.toBeNull();
+ expect(out).not.toContain(TOKEN);
+ expect(out).not.toContain('ghp_');
+ expect(out).not.toContain('foo bar');
+ });
+
+ test('the suggested re-run command carries no credential either', () => {
+ const out = formatCloneAuthFailure({
+ error: new Error('fatal: could not read Username for https://github.com'),
+ url: `https://alice:my ${TOKEN}@github.com/o/r.git`,
+ branch: 'main',
+ });
+ // Login-fixable → the message embeds `ok clone '<url>'` for the user to
+ // paste; the credential must not ride along into a support thread.
+ expect(out).toContain('ok clone');
+ expect(out).not.toContain(TOKEN);
+ expect(out).not.toContain('ghp_');
+ });
+});
+
describe('emitCloneFailure', () => {
function makeCollectors() {
const emitted: Record<string, unknown>[] = [];
@@ -834,6 +1429,46 @@ describe('emitCloneFailure', () => {
expect(c.emitted[0]).toEqual({ type: 'error', message: 'connection timed out' });
});
+ // With prompts disabled, git quotes the URL's username half in its failure
+ // ("could not read Password for 'https://<user>@…'") — the slot where a
+ // bare PAT lives. The --json event feeds the desktop clone toast verbatim
+ // (the IPC path has no redacting hop), so the token must die here.
+ test('--json: a token-as-username in the git error is redacted from the event', () => {
+ const c = makeCollectors();
+ emitCloneFailure({
+ error: new Error(
+ "fatal: could not read Password for 'https://[email protected]': terminal prompts disabled",
+ ),
+ url: 'https://github.com/o/private',
+ json: true,
+ emit: c.emit,
+ printStderr: c.printStderr,
+ });
+ expect(c.emitted).toHaveLength(1);
+ const message = c.emitted[0]?.message as string;
+ expect(message).not.toContain('ghp_c8Fyj2wXaB1LmQ9zK4tUvNs6RdPeYhG3o5A7');
+ expect(message).toContain('could not read Password');
+ expect(message).toContain('github.com');
+ });
+
+ test('interactive fallback line redacts an embedded credential the same way', () => {
+ const c = makeCollectors();
+ emitCloneFailure({
+ // Non-auth classification, so the interactive branch falls through to
+ // the raw-message line — which must be the redacted one.
+ error: new Error(
+ 'fatal: unable to update https://x-access-token:[email protected]/o/r',
+ ),
+ url: 'https://github.com/o/r',
+ json: false,
+ emit: c.emit,
+ printStderr: c.printStderr,
+ });
+ const out = c.stderr.join('');
+ expect(out).not.toContain('ghp_c8Fyj2wXaB1LmQ9zK4tUvNs6RdPeYhG3o5A7');
+ expect(out).toContain('x-access-token');
+ });
+
test('interactive + login-fixable: prints the 2-step instruction; does not emit JSON', () => {
const c = makeCollectors();
emitCloneFailure({
@@ -894,6 +1529,48 @@ describe('emitCloneFailure', () => {
});
});
+// The clone→sync identity bridge: a real `git clone` records the URL argument
+// verbatim in `.git/config` — including its userinfo — so the account declared
+// at clone time is the account the sync engine later resolves from the stored
+// remote. Driven through the same composed pieces `runClone` uses
+// (`buildCloneGitOptions` + `buildCloneAuthEnv` + `git.clone`), with the
+// GitHub-shaped URL redirected to a local seed repo at fetch time via
+// `insteadOf` (a rewrite git applies when contacting the remote, without
+// changing what it records).
+describe('clone stores the remote URL verbatim, userinfo included', () => {
+ test('git clone of a userinfo URL writes that URL into .git/config unchanged', async () => {
+ const base = mkdtempSync(join(tmpdir(), 'ok-clone-userinfo-'));
+ try {
+ const srcDir = join(base, 'seed');
+ mkdirSync(srcDir);
+ execFileSync('git', ['init', '--initial-branch=main'], { cwd: srcDir, stdio: 'ignore' });
+ execFileSync('git', ['config', 'user.email', '[email protected]'], { cwd: srcDir });
+ execFileSync('git', ['config', 'user.name', 'T'], { cwd: srcDir });
+ writeFileSync(join(srcDir, 'README.md'), '# seed\n', 'utf-8');
+ execFileSync('git', ['add', '.'], { cwd: srcDir });
+ execFileSync('git', ['commit', '-m', 'seed'], { cwd: srcDir, stdio: 'ignore' });
+
+ const declaredUrl = 'https://[email protected]/seed-owner/seed-repo';
+ // The rewrite rides the same `-c` config channel runClone's credential
+ // config uses; git applies `insteadOf` when contacting the remote and
+ // still records the original URL.
+ const redirect = `url.${pathToFileURL(srcDir).href}.insteadOf=${declaredUrl}`;
+
+ const targetDir = join(base, 'cloned');
+ const env = buildCloneAuthEnv({}, { PATH: process.env.PATH ?? '' });
+ const git = simpleGit(
+ buildCloneGitOptions(base, [redirect]) as Partial<SimpleGitOptions>,
+ ).env(env);
+ await git.clone(declaredUrl, targetDir, buildCloneArgs(null));
+
+ const config = readFileSync(join(targetDir, '.git', 'config'), 'utf-8');
+ expect(config).toContain(`url = ${declaredUrl}`);
+ } finally {
+ rmSync(base, { recursive: true, force: true });
+ }
+ });
+});
+
describe('runClone git preflight', () => {
it('git unusable everywhere → runClone surfaces the recoverable GitNotAvailableError', async () => {
// Same technique as init.test.ts's git-unavailable case: narrow PATH so the
diff --git a/packages/cli/src/commands/clone.ts b/packages/cli/src/commands/clone.ts
index 97e1f9ff9..ab9500ff0 100644
--- a/packages/cli/src/commands/clone.ts
+++ b/packages/cli/src/commands/clone.ts
@@ -10,11 +10,18 @@ import {
import {
assertGitAvailable,
type Config,
+ type CredentialUrlMatchReader,
+ type GitHubAccountSource,
GitNotAvailableError,
GitTooOldError,
+ loginShapedUserinfoUser,
+ redactShareSubprocessStderr,
+ resolveGitHubAccountFromUrl,
+ sameGitHubLogin,
} from '@inkeep/open-knowledge-server';
import { Command } from 'commander';
import simpleGit, { type SimpleGitOptions } from 'simple-git';
+import type { GhDetectResult } from '../auth/gh-detect.ts';
import { type ResolvedAuth, resolveAuth } from '../auth/resolve-auth.ts';
import { makeLazyTokenStore, type TokenStore } from '../auth/token-store.ts';
import { OK_DIR } from '../constants.ts';
@@ -92,6 +99,10 @@ export function buildCloneEnv(sourceEnv: NodeJS.ProcessEnv = process.env): Recor
* STRIPPED — a stale exported token would otherwise shadow the token store
* inside the helper, and only this process's own resolution may speak for
* which credential the clone uses.
+ *
+ * OK_GH_TOKEN_LOGIN names the account behind the token for diagnostics only —
+ * the helper never gates on it. It is set only when this resolution knows the
+ * account, and stripped otherwise for the same stale-inheritance reason.
*/
export function buildCloneAuthEnv(
resolved: Pick<ResolvedAuth, 'relayToken'>,
@@ -101,9 +112,12 @@ export function buildCloneAuthEnv(
if (resolved.relayToken) {
env.OK_GH_TOKEN = resolved.relayToken.token;
env.OK_GH_TOKEN_HOST = resolved.relayToken.host;
+ if (resolved.relayToken.login) env.OK_GH_TOKEN_LOGIN = resolved.relayToken.login;
+ else delete env.OK_GH_TOKEN_LOGIN;
} else {
delete env.OK_GH_TOKEN;
delete env.OK_GH_TOKEN_HOST;
+ delete env.OK_GH_TOKEN_LOGIN;
}
return env;
}
@@ -189,6 +203,22 @@ interface CloneOptions {
* a toast.
*/
branch?: string | null;
+ /**
+ * Observes which auth the clone actually resolved: the tier plus the login
+ * that produced the credential, when known. The failure path reads this to
+ * name the identity used — re-resolving there could disagree with the
+ * resolution the clone ran with. `login` deliberately mirrors
+ * `RelayGhToken.login` (the resolved, post-fallback account), which is why
+ * it isn't spelled `resolvedLogin` here.
+ */
+ onAuthResolved?: (info: { tier: ResolvedAuth['tier']; login?: string }) => void;
+ /**
+ * gh detector, injectable so a test can drive the tier-A resolution (and the
+ * declared-account miss that rides on it) without a real `gh`. Same seam
+ * `resolveCloneAuth` already exposes; threaded here because the warning it
+ * produces is emitted by this function, not by the resolver.
+ */
+ _detectGhFn?: (host?: string, options?: { login?: string }) => GhDetectResult;
}
type CredentialHelperUnsafeGitOptions = SimpleGitOptions & {
@@ -255,6 +285,140 @@ export function shouldSkipAuthForPublicRepo(
return protocol === 'https' && hostname === 'github.com' && isPublic;
}
+/**
+ * Resolve the auth for a clone as one step: the account the URL (or the
+ * user's own git config) declares, then the token for that account. The
+ * declared login rides into `gh auth token --user <login>`, so cloning
+ * `https://[email protected]/o/r` authenticates as alice regardless of which
+ * gh account is active; a login gh cannot serve falls back to the active
+ * account inside `detectGh`, never to `tier: 'none'`. This is the only path
+ * that builds a clone's `ResolvedAuth`, keeping account resolution and token
+ * resolution one operation — the identity the clone authenticates as is the
+ * identity the post-clone sync engine resolves from the same stored URL.
+ *
+ * The hostname for gh's `--hostname` scope is derived from `cloneUrl` here
+ * rather than accepted from the caller: two sources for the same fact is how
+ * a clone and its later sync end up authenticating differently.
+ */
+export interface CloneAuthResolution {
+ auth: ResolvedAuth;
+ /**
+ * Set when the URL (or the user's git config) declared an account and the
+ * gh resolution did not produce that account's token — the fallback rescued
+ * the clone with the active account instead. Only the gh tier can prove the
+ * miss: a stored-token or credential-less resolution doesn't say which
+ * account will answer the credential request, and claiming a miss there
+ * could be false, so those tiers stay silent. The caller decides how to
+ * surface it (stderr on the human path; the machine path's trace is the
+ * sync engine's own fallback warning once the project opens).
+ */
+ declaredMiss?: {
+ declaredLogin: string;
+ declaredSource: Exclude<GitHubAccountSource, 'active'>;
+ };
+}
+
+/**
+ * The stderr line warning that a declared account did not answer, or `null`
+ * when there is nothing to say. Pure so the wording and the mechanism
+ * mapping are testable without driving a real clone; the `--json` gate lives
+ * at the call site, matching the sibling stderr writes in `runClone`.
+ *
+ * Human channel only: stdout is the machine wire under `--json`, and that
+ * flow's trace is the sync engine's own fallback warning once the cloned
+ * project is opened.
+ *
+ * The copy asserts only what this process can prove. A fallback means gh did
+ * not confirm the requested account — it does NOT prove another account
+ * answered: gh older than 2.40 rejects `--user` outright, and a casing-only
+ * difference falls back by design, so in both cases the token may well be the
+ * declared person's. Naming the GitHub CLI is safe here (unlike the app's
+ * wire copy, which cannot know the tier) because only the gh tier reports a
+ * miss at all.
+ */
+export function formatDeclaredMissWarning(
+ miss: CloneAuthResolution['declaredMiss'],
+): string | null {
+ if (miss === undefined) return null;
+ const { declaredLogin, declaredSource } = miss;
+ // Exhaustive per source rather than a binary ternary: a source added later
+ // must land on the neutral wording, never silently borrow another
+ // mechanism's sentence.
+ let mechanism: string;
+ switch (declaredSource) {
+ case 'remote-url':
+ mechanism = `The clone URL names ${declaredLogin}`;
+ break;
+ case 'credential-config':
+ mechanism = `Your Git credential configuration names ${declaredLogin}`;
+ break;
+ default:
+ mechanism = `Your Git configuration names ${declaredLogin}`;
+ }
+ // Names the one command that settles it. The process cannot name the
+ // answering account itself without a `detectGhAccounts` spawn this path
+ // deliberately avoids, and the two benign causes (gh below the 2.40
+ // `--user` floor, a casing-only declaration) are indistinguishable here —
+ // so hand the user a check rather than a verdict they cannot falsify.
+ return (
+ `⚠ ${mechanism}, but the GitHub CLI couldn't confirm that account — the clone used its active account.\n` +
+ ` Run \`gh auth status\` to see which account that is. If ${declaredLogin} is listed as active, nothing is wrong; confirming an account by name needs GitHub CLI 2.40 or newer.\n`
+ );
+}
+
+export async function resolveCloneAuth(
+ cloneUrl: string,
+ tokenStore: TokenStore,
+ options: {
+ selfCliArgs?: readonly string[];
+ /**
+ * Directory the `credential.<url>.*` lookup runs in, defaulting to the
+ * process cwd. Every scope git resolves from there applies, including the
+ * local scope of an enclosing repository — `ok clone` run from inside
+ * another checkout inherits that checkout's entries. That is git's own
+ * rule (a plain `git clone` from the same directory resolves
+ * identically), but it means this tier can name a different account
+ * pre-clone than the sync path later resolves from the cloned project's
+ * own directory. The URL's userinfo outranks this tier and survives into
+ * `.git/config`, so a URL-declared account cannot diverge that way.
+ */
+ cwd?: string;
+ _detectGhFn?: (host?: string, options?: { login?: string }) => GhDetectResult;
+ _readCredentialUrlMatch?: CredentialUrlMatchReader;
+ } = {},
+): Promise<CloneAuthResolution> {
+ const parsed = parseGitUrl(cloneUrl);
+ if (!parsed) {
+ // Password-stripped: an unparseable input can still carry an embedded
+ // credential, and this message reaches the terminal.
+ throw new Error(`Invalid git URL: ${stripUrlPassword(cloneUrl)}`);
+ }
+ const account = resolveGitHubAccountFromUrl(cloneUrl, {
+ cwd: options.cwd,
+ _readCredentialUrlMatch: options._readCredentialUrlMatch,
+ });
+ // The account resolver's host when it parsed one, the CLI parse otherwise:
+ // the resolver normalizes (lowercase, www-fold) the same way the post-clone
+ // sync path does, so `gh --hostname`, the relay's host guard, and the sync
+ // engine all speak one host spelling for one remote.
+ const auth = await resolveAuth(
+ account.host ?? parsed.hostname,
+ tokenStore,
+ { selfCliArgs: options.selfCliArgs, login: account.login },
+ options._detectGhFn,
+ );
+ // A gh-tier token that the declared account didn't produce is a proven
+ // fallback (a relayed token always names its account when the request was
+ // honored). See CloneAuthResolution for why other tiers never report one.
+ const declaredMiss =
+ account.login !== undefined &&
+ auth.tier === 'A' &&
+ !sameGitHubLogin(auth.relayToken?.login, account.login)
+ ? { declaredLogin: account.login, declaredSource: account.source }
+ : undefined;
+ return { auth, ...(declaredMiss !== undefined ? { declaredMiss } : {}) };
+}
+
/**
* `parseGitUrl` accepts `owner/repo` shorthand, but git itself treats a bare
* `owner/repo` as a local filesystem path and never contacts GitHub (no
@@ -286,7 +450,7 @@ export async function runClone(
): Promise<string> {
const parsed = parseGitUrl(url);
if (!parsed) {
- throw new Error(`Invalid git URL: ${url}`);
+ throw new Error(`Invalid git URL: ${stripUrlPassword(url)}`);
}
const cloneUrl = resolveCloneUrl(url, parsed);
@@ -335,13 +499,26 @@ export async function runClone(
// there's no point paying the up-to-5s network round-trip just to discard the result.
const shouldProbe = parsed.protocol === 'https' && parsed.hostname === 'github.com';
const isPublic = shouldProbe ? await isGitHubRepoPublic(parsed.owner, parsed.name) : false;
- const resolved: ResolvedAuth = shouldSkipAuthForPublicRepo(
+ const resolution: CloneAuthResolution = shouldSkipAuthForPublicRepo(
parsed.protocol,
parsed.hostname,
isPublic,
)
- ? { tier: 'none', gitConfig: [] }
- : await resolveAuth(parsed.hostname, tokenStore, { selfCliArgs: resolveSelfCliArgs() });
+ ? { auth: { tier: 'none', gitConfig: [] } }
+ : await resolveCloneAuth(cloneUrl, tokenStore, {
+ selfCliArgs: resolveSelfCliArgs(),
+ cwd,
+ ...(opts._detectGhFn ? { _detectGhFn: opts._detectGhFn } : {}),
+ });
+ const resolved: ResolvedAuth = resolution.auth;
+ opts.onAuthResolved?.({ tier: resolved.tier, login: resolved.relayToken?.login });
+ // Gate at the call site, like the sibling stderr writes below. The
+ // visibility probe short-circuits for any non-github.com host, so a test
+ // can reach this with an injected detector and a loopback URL.
+ if (!opts.json) {
+ const declaredMissWarning = formatDeclaredMissWarning(resolution.declaredMiss);
+ if (declaredMissWarning) process.stderr.write(declaredMissWarning);
+ }
const env = buildCloneAuthEnv(resolved);
@@ -468,6 +645,36 @@ export function ensureOkExcludedFromGit(
const SHELL_SAFE_TOKEN = /^[A-Za-z0-9._/:@-]+$/;
+/**
+ * Drop every credential a URL's userinfo can carry before it is echoed. The
+ * `:password` half always goes, and the username half goes too when it is
+ * itself credential-shaped — GitHub's canonical PAT-in-URL form is
+ * `https://<token>@github.com/o/r`, so only a login-shaped username (the
+ * user's identity declaration) survives into the message and the suggested
+ * `ok clone` re-run, which then still authenticates as the same account.
+ */
+function stripUrlPassword(url: string): string {
+ // Userinfo is matched greedily up to the LAST `@` before the path, so a
+ // password containing `@` (`user:p@ss@host`) is stripped whole. The class
+ // deliberately does NOT exclude whitespace, unlike the share-publish
+ // redactor: that one scans free-form multi-line stderr with /g, where a
+ // span crossing whitespace would swallow unrelated prose. This one is
+ // `^`-anchored on a single URL argument, so it cannot over-reach — and
+ // excluding `\s` here makes the match FAIL OUTRIGHT on a userinfo
+ // containing a space (`https://foo bar:<token>@host`), echoing the
+ // credential whole instead of stripping it.
+ return url.replace(
+ /^([a-z][a-z0-9+.-]*:\/\/)([^/]*)@/i,
+ (_whole, scheme: string, userinfo: string) => {
+ const colon = userinfo.indexOf(':');
+ const user = colon === -1 ? userinfo : userinfo.slice(0, colon);
+ return user !== '' && loginShapedUserinfoUser(user) !== undefined
+ ? `${scheme}${user}@`
+ : scheme;
+ },
+ );
+}
+
// `shellSingleQuote` is the canonical, test-covered POSIX quoter from core;
// `quoteIfNeeded` stays clone-local (it's not duplicated in core) and defers
// to the canonical quoter for the unsafe case.
@@ -493,14 +700,27 @@ export function formatCloneAuthFailure(opts: {
branch?: string | null;
/** Optional GitHub login for the 403 "signed in as @X" hint. */
principal?: string | null;
+ /**
+ * The login that actually produced the credential the clone ran with, when
+ * known. Appended to the 404 masquerade so the user can spot a
+ * wrong-account mismatch themselves; omitted when unknown — the message
+ * degrades, it never guesses. Named like the wire and server fields for
+ * the same fact: resolved (what answered), in opposition to declared.
+ */
+ resolvedLogin?: string | null;
}): string | null {
const classified: ClassifiedGitAuthError = classifyGitAuthError(opts.error);
if (classified.kind !== 'auth') return null;
+ // Every echo of the clone URL — including the copy-pasteable re-run
+ // command — drops the password half. The username stays so the suggested
+ // re-run keeps the user's identity declaration.
+ const displayUrl = stripUrlPassword(opts.url);
+
if (isLoginFixableGitAuthError(classified)) {
- const reRun = reconstructCloneCommand(opts.url, opts.branch);
+ const reRun = reconstructCloneCommand(displayUrl, opts.branch);
return [
- `✗ Couldn't clone ${opts.url} — authentication is required.`,
+ `✗ Couldn't clone ${displayUrl} — authentication is required.`,
'',
' To fix:',
' 1. Run: ok auth login',
@@ -513,11 +733,26 @@ export function formatCloneAuthFailure(opts: {
typeof opts.principal === 'string' && opts.principal.length > 0
? ` (signed in as @${opts.principal} — may lack access)`
: '';
- return `✗ Access denied when cloning ${opts.url}${principalHint}. Check that your account has access to the repository.`;
+ return `✗ Access denied when cloning ${displayUrl}${principalHint}. Check that your account has access to the repository.`;
}
if (classified.subclass === 'ssh-auth') {
- return `✗ Couldn't clone ${opts.url} over SSH — authentication failed. Check that your SSH key is added to your GitHub account and the host key is trusted, or clone the HTTPS URL instead.`;
+ return `✗ Couldn't clone ${displayUrl} over SSH — authentication failed. Check that your SSH key is added to your GitHub account and the host key is trusted, or clone the HTTPS URL instead.`;
+ }
+
+ // GitHub's 404 masquerade: "not found" covers both a missing repo and a
+ // private repo the credential used can't see, so the copy asserts both and
+ // prescribes no recovery command — re-login mints the same account's
+ // credential, and scopes are not the problem. The identity sentence uses
+ // only the login threaded from the resolution the clone actually ran with;
+ // the stored-token principal is never consulted here, since it could name
+ // an account the clone never used.
+ if (classified.subclass === 'not-found-as-identity') {
+ const identity =
+ typeof opts.resolvedLogin === 'string' && opts.resolvedLogin.length > 0
+ ? ` Authenticated as ${opts.resolvedLogin}.`
+ : '';
+ return `✗ Repository not found when cloning ${displayUrl}. It may not exist, or the account used may not have access.${identity}`;
}
// scope-mismatch. `ok auth login` mints a fixed device-flow scope set that
@@ -528,7 +763,7 @@ export function formatCloneAuthFailure(opts: {
' To fix:',
' 1. Create a token with `repo` scope at https://github.com/settings/tokens',
' 2. Run: ok auth pat',
- ` 3. Then re-run: ${reconstructCloneCommand(opts.url, opts.branch)}`,
+ ` 3. Then re-run: ${reconstructCloneCommand(displayUrl, opts.branch)}`,
].join('\n');
}
@@ -539,6 +774,14 @@ export function formatCloneAuthFailure(opts: {
* interactive mode, an auth failure becomes an actionable instruction; non-
* auth errors fall through to the today's `✗ <message>` line.
*
+ * The raw message is credential-redacted BEFORE the channel branch: both the
+ * `--json` event (rendered verbatim in the desktop clone toast — the IPC
+ * path has no redacting hop of its own) and the interactive fallback line
+ * can otherwise echo a token, since git's disabled-prompt failure quotes the
+ * URL's username half (`could not read Password for 'https://<pat>@…'`),
+ * which is where a bare PAT lives. Classification still reads the
+ * unredacted error — patterns may match the very bytes redaction strips.
+ *
* Dependencies are injected so tests can drive both branches without
* touching `process.stdout` / `process.stderr`.
*/
@@ -550,8 +793,11 @@ export function emitCloneFailure(opts: {
emit: (event: Record<string, unknown>) => void;
printStderr: (text: string) => void;
principal?: string | null;
+ resolvedLogin?: string | null;
}): void {
- const rawMessage = opts.error instanceof Error ? opts.error.message : String(opts.error);
+ const rawMessage = redactShareSubprocessStderr(
+ opts.error instanceof Error ? opts.error.message : String(opts.error),
+ );
if (opts.json) {
opts.emit({ type: 'error', message: rawMessage });
return;
@@ -561,6 +807,7 @@ export function emitCloneFailure(opts: {
url: opts.url,
branch: opts.branch,
principal: opts.principal,
+ resolvedLogin: opts.resolvedLogin,
});
opts.printStderr(`${actionable ?? `✗ ${rawMessage}`}\n`);
}
@@ -581,11 +828,17 @@ export async function resolveClonePrincipal(
}
/**
- * Route a clone failure to the right channel. Only an interactive 403 consumes
- * the principal hint, so the stored login is resolved just for that case — other
- * failure paths (and the `--json` machine path) skip the lazy keyring init.
- * `resolvePrincipal` is injectable so the 403-only guard is unit-testable
- * without a real keyring or git.
+ * Route a clone failure to the right channel. The identity in hand is
+ * authoritative: with a gh-resolved credential the 403 hint names that login
+ * or nothing, and a `tier: 'none'` clone presented no credential at all, so
+ * its hint names nobody — the stored-token principal is consulted only when
+ * the credential could have come from the store (store tiers, or a caller
+ * that didn't observe the resolution). The hint can therefore never
+ * attribute the failure to an account the clone didn't use. Only an
+ * interactive 403 without gh auth resolves the stored login, so other failure
+ * paths (and the `--json` machine path) skip the lazy keyring init.
+ * `resolvePrincipal` is injectable so the guard is unit-testable without a
+ * real keyring or git.
*/
export async function handleCloneFailure(opts: {
error: unknown;
@@ -595,15 +848,25 @@ export async function handleCloneFailure(opts: {
emit: (event: Record<string, unknown>) => void;
printStderr: (text: string) => void;
resolvePrincipal?: (host: string) => Promise<string | null>;
+ /** The auth the clone actually resolved, observed via `onAuthResolved`. */
+ auth?: { tier: ResolvedAuth['tier']; login?: string };
}): Promise<void> {
const classified = classifyGitAuthError(opts.error);
+ const ghAuth = opts.auth?.tier === 'A' ? opts.auth : undefined;
let principal: string | null = null;
if (!opts.json && classified.kind === 'auth' && classified.subclass === '403') {
- const target = parseGitUrl(opts.url);
- if (target) {
- const resolve =
- opts.resolvePrincipal ?? ((host) => resolveClonePrincipal(makeLazyTokenStore(), host));
- principal = await resolve(target.hostname);
+ if (ghAuth) {
+ principal = ghAuth.login ?? null;
+ } else if (opts.auth?.tier !== 'none') {
+ // Skipped for a known credential-less clone: a 403 there (e.g. rate
+ // limiting) authenticated as nobody, and "signed in as @X" would blame
+ // an account the request never carried.
+ const target = parseGitUrl(opts.url);
+ if (target) {
+ const resolve =
+ opts.resolvePrincipal ?? ((host) => resolveClonePrincipal(makeLazyTokenStore(), host));
+ principal = await resolve(target.hostname);
+ }
}
}
emitCloneFailure({
@@ -612,6 +875,7 @@ export async function handleCloneFailure(opts: {
branch: opts.branch,
json: opts.json,
principal,
+ resolvedLogin: ghAuth?.login ?? null,
emit: opts.emit,
printStderr: opts.printStderr,
});
@@ -631,10 +895,18 @@ export function cloneCommand(getConfig: () => Config): Command {
.action(
async (url: string, dir: string | undefined, opts: { json: boolean; branch?: string }) => {
const config = getConfig();
+ let authInfo: { tier: ResolvedAuth['tier']; login?: string } | undefined;
try {
const targetDir = await runClone(
url,
- { json: opts.json, dir, branch: opts.branch ?? null },
+ {
+ json: opts.json,
+ dir,
+ branch: opts.branch ?? null,
+ onAuthResolved: (info) => {
+ authInfo = info;
+ },
+ },
config,
);
if (opts.json) {
@@ -669,6 +941,7 @@ export function cloneCommand(getConfig: () => Config): Command {
url,
branch: opts.branch ?? null,
json: opts.json,
+ auth: authInfo,
emit: (event) => emit(true, event),
printStderr: (text) => process.stderr.write(text),
});
diff --git a/packages/cli/src/commands/start.ts b/packages/cli/src/commands/start.ts
index 973a9b1e6..a7c8e08d9 100644
--- a/packages/cli/src/commands/start.ts
+++ b/packages/cli/src/commands/start.ts
@@ -50,7 +50,7 @@ import {
} from '@inkeep/open-knowledge-server';
import { Command, InvalidArgumentError, Option } from 'commander';
import { makeLazyEmbeddingsKeyStore } from '../auth/embeddings-key-store.ts';
-import { detectGh } from '../auth/gh-detect.ts';
+import { detectGh, detectGhAccounts } from '../auth/gh-detect.ts';
import { makeLazyProbeTokenStore } from '../auth/token-store.ts';
import { PACKAGE_VERSION } from '../constants.ts';
import { getNativeTomlMcpEditor } from '../native/toml-config-engine.ts';
@@ -866,6 +866,7 @@ export async function bootStartServer(opts: BootStartServerOptions): Promise<Boo
host,
quiet: false,
detectGh,
+ detectGhAccounts,
tokenStore,
embeddingsKeyStore,
mcpTomlEditor: getNativeTomlMcpEditor(),
diff --git a/packages/cli/src/github/folder-validator.test.ts b/packages/cli/src/github/folder-validator.test.ts
index 767ec1821..cd5ea5b0b 100644
--- a/packages/cli/src/github/folder-validator.test.ts
+++ b/packages/cli/src/github/folder-validator.test.ts
@@ -40,6 +40,27 @@ describe('validateLocalFolderForShare', () => {
});
});
+ // A userinfo origin used to fall out of `parseGitUrl` entirely and land as
+ // non-github ("switch your remote" toast) — now it validates like any other
+ // GitHub clone. The re-emitted canonical URL is rebuilt from parsed
+ // components, so neither the declared account nor an embedded password can
+ // leak into `gitRemoteUrl`.
+ test('a userinfo origin validates ok, and the canonical URL carries no credential', async () => {
+ const folder = resolve(tmpDir, 'repo');
+ mkdirSync(folder);
+ seedRepo(folder, 'https://alice:[email protected]/inkeep/open-knowledge.git');
+
+ const result = await validateLocalFolderForShare(folder, {
+ host: 'github.com',
+ owner: 'inkeep',
+ repo: 'open-knowledge',
+ });
+ expect(result).toEqual({
+ kind: 'ok',
+ gitRemoteUrl: 'https://github.com/inkeep/open-knowledge.git',
+ });
+ });
+
test('returns ok and normalizes to https for ssh clones', async () => {
const folder = resolve(tmpDir, 'repo');
mkdirSync(folder);
diff --git a/packages/cli/src/github/url.test.ts b/packages/cli/src/github/url.test.ts
index 366113033..c654f9218 100644
--- a/packages/cli/src/github/url.test.ts
+++ b/packages/cli/src/github/url.test.ts
@@ -84,6 +84,67 @@ describe('parseGitUrl', () => {
});
});
+ describe('userinfo handling', () => {
+ // The hostname split is load-bearing: with userinfo folded into the
+ // hostname, the public-repo probe gate never fires and
+ // `gh auth token --hostname [email protected]` fails, so the exact URL
+ // form GCM's multi-account guide tells users to write lost all auth.
+ // Account extraction is NOT this parser's job — the server-side origin
+ // parser owns it (with login-grammar validation); this one only splits
+ // the userinfo off the host and drops it.
+ test('https URL with userinfo yields the real hostname', () => {
+ const result = parseGitUrl('https://[email protected]/owner/repo');
+ expect(result).toEqual({
+ protocol: 'https',
+ hostname: 'github.com',
+ owner: 'owner',
+ name: 'repo',
+ });
+ });
+
+ test('userinfo with a port both split off the hostname', () => {
+ const result = parseGitUrl('https://[email protected]:8443/owner/repo.git');
+ expect(result).toEqual({
+ protocol: 'https',
+ hostname: 'ghes.example.com',
+ owner: 'owner',
+ name: 'repo',
+ });
+ });
+
+ test('user:password userinfo is dropped entirely — no credential survives the parse', () => {
+ const result = parseGitUrl('https://alice:[email protected]/owner/repo');
+ expect(result).toMatchObject({ hostname: 'github.com' });
+ expect(JSON.stringify(result)).not.toContain('s3cretpw');
+ expect(JSON.stringify(result)).not.toContain('alice');
+ });
+
+ test('a `@` inside the password half is not read as the host delimiter', () => {
+ const result = parseGitUrl('https://alice:p@[email protected]/owner/repo');
+ expect(result).toMatchObject({ hostname: 'github.com' });
+ });
+
+ test('ssh:// URL with a user yields the real hostname', () => {
+ const result = parseGitUrl('ssh://[email protected]/owner/repo');
+ expect(result).toEqual({
+ protocol: 'ssh',
+ hostname: 'github.com',
+ owner: 'owner',
+ name: 'repo',
+ });
+ });
+
+ test('SCP-style URL with a non-git user parses', () => {
+ const result = parseGitUrl('[email protected]:owner/repo.git');
+ expect(result).toEqual({
+ protocol: 'ssh',
+ hostname: 'github.com',
+ owner: 'owner',
+ name: 'repo',
+ });
+ });
+ });
+
describe('SCP-style SSH (git@host:owner/repo)', () => {
test('standard git@ SSH', () => {
const result = parseGitUrl('[email protected]:owner/repo');
diff --git a/packages/cli/src/github/url.ts b/packages/cli/src/github/url.ts
index 913fd594f..403c38000 100644
--- a/packages/cli/src/github/url.ts
+++ b/packages/cli/src/github/url.ts
@@ -71,14 +71,20 @@ export function parseGitUrl(input: string): ParsedGitUrl | null {
if (!raw) return null;
// https:// or http://
+ // The userinfo half (dropped — the account/credential resolution consumes
+ // it via the server-side parser, never this one) is matched greedily so a
+ // `@` inside a password (`user:p@ss`) is consumed by it rather than read as
+ // the host delimiter.
{
- const m = /^https?:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(raw);
+ const m = /^https?:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(
+ raw,
+ );
if (m) return { protocol: 'https', hostname: stripPort(m[1]), owner: m[2], name: m[3] };
}
// ssh://[user@]host/owner/repo(.git)?
{
- const m = /^ssh:\/\/(?:[\w.-]+@)?([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(
+ const m = /^ssh:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(
raw,
);
if (m) return { protocol: 'ssh', hostname: stripPort(m[1]), owner: m[2], name: m[3] };
@@ -94,7 +100,7 @@ export function parseGitUrl(input: string): ParsedGitUrl | null {
// The hostname must contain a dot or be a known hostname pattern (prevents
// matching Windows-style paths like C:\path or plain "foo:bar/baz").
{
- const m = /^(?:[\w.-]+@)?([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(raw);
+ const m = /^(?:[\w.\-~%]+@)?([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(raw);
if (m?.[1].includes('.')) {
return { protocol: 'ssh', hostname: m[1], owner: m[2], name: m[3] };
}
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 4455c7acf..53897ccc7 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -10,7 +10,12 @@
// `@inkeep/open-knowledge-server` (alongside the secrets-store), and desktop
// imports it straight from there. Re-exporting an external package's symbol
// through this bundled public surface breaks the .d.ts bundler.
-export { detectGh, type GhDetectResult } from './auth/gh-detect.ts';
+export {
+ detectGh,
+ detectGhAccounts,
+ type GhAccount,
+ type GhDetectResult,
+} from './auth/gh-detect.ts';
export {
createTokenStore,
makeLazyProbeTokenStore,
diff --git a/packages/core/src/git/worktree-selector-model.ts b/packages/core/src/git/worktree-selector-model.ts
index 43a38215e..3a8af36ab 100644
--- a/packages/core/src/git/worktree-selector-model.ts
+++ b/packages/core/src/git/worktree-selector-model.ts
@@ -144,8 +144,9 @@ export type WorktreeCreateResult =
/**
* Set when the fetch failed for want of a usable credential rather than
* for a network/timeout reason, and re-authenticating could plausibly fix
- * it (`isLoginFixableGitAuthError` — so not 403, scope-mismatch, or SSH
- * key failures, which a sign-in doesn't repair).
+ * it (`isLoginFixableGitAuthError` — so not 403, scope-mismatch, SSH key
+ * failures, or the repository-not-found masquerade, none of which a
+ * sign-in repairs).
*
* Its own arm rather than a field on the shared failure arm below: only
* `fetch-failed` reaches git's credential stage, so no other reason can
@@ -154,6 +155,14 @@ export type WorktreeCreateResult =
* pre-existing behavior.
*/
readonly authFailed?: true;
+ /**
+ * Set for the repository-not-found masquerade: the remote answered, so
+ * neither the network copy nor a Sign in affordance fits — the repo may
+ * not exist, or the account used may not see it. Same additive contract
+ * as `authFailed`, and mutually exclusive with it by construction (the
+ * masquerade is excluded from login-fixable).
+ */
+ readonly notFoundAsIdentity?: true;
}
| {
readonly ok: false;
diff --git a/packages/core/src/schemas/api/share.test.ts b/packages/core/src/schemas/api/share.test.ts
index 1923da00c..17f501ef5 100644
--- a/packages/core/src/schemas/api/share.test.ts
+++ b/packages/core/src/schemas/api/share.test.ts
@@ -44,6 +44,23 @@ describe('classifyGitAuthError', () => {
).toEqual({ kind: 'auth', subclass: 'no-credential' });
});
+ // The cohort whose remote carries a userinfo (`https://[email protected]/…`)
+ // and whose working credential lived only in an ambient helper (GCM, os
+ // keychain): recognizing those URLs as GitHub origins routes them through
+ // OK's credential reset, so their first post-upgrade sync fails with git's
+ // promptless no-credential wording. That failure MUST stay login-fixable —
+ // signing in to OpenKnowledge is exactly the remedy — and must not drift
+ // into the withdrawn-affordance not-found bucket.
+ test('a promptless credential miss on a userinfo remote stays login-fixable', () => {
+ const classified = classifyGitAuthError(
+ new Error(
+ "fatal: could not read Username for 'https://[email protected]': terminal prompts disabled",
+ ),
+ );
+ expect(classified).toEqual({ kind: 'auth', subclass: 'no-credential' });
+ expect(isLoginFixableGitAuthError(classified)).toBe(true);
+ });
+
test('classifies "could not read Password" as no-credential', () => {
expect(
classifyGitAuthError(new Error('fatal: could not read Password for https://github.com')),
@@ -144,10 +161,38 @@ describe('classifyGitAuthError', () => {
});
});
- test('classifies "fatal: repository not found" as unknown-auth (private-repo masquerade)', () => {
+ test('classifies "fatal: repository not found" as not-found-as-identity (404 masquerade)', () => {
expect(
classifyGitAuthError(new Error("fatal: repository 'https://github.com/o/r.git' not found")),
- ).toEqual({ kind: 'auth', subclass: 'unknown-auth' });
+ ).toEqual({ kind: 'auth', subclass: 'not-found-as-identity' });
+ });
+
+ test('auth wording co-occurring with "repository not found" still reads as the 404 masquerade', () => {
+ // GitHub's auth-shaped 404s can carry both lines; the not-found signal is
+ // the more specific one, so it wins over generic auth wording.
+ expect(
+ classifyGitAuthError(
+ new Error(
+ "remote: Authentication failed\nfatal: repository 'https://github.com/o/r.git' not found",
+ ),
+ ),
+ ).toEqual({ kind: 'auth', subclass: 'not-found-as-identity' });
+ });
+
+ test('an explicit 401 outranks a co-occurring "repository not found"', () => {
+ expect(
+ classifyGitAuthError(
+ new Error("remote: HTTP 401 Unauthorized\nfatal: repository 'x' not found"),
+ ),
+ ).toEqual({ kind: 'auth', subclass: '401' });
+ });
+
+ test('an explicit 403 outranks a co-occurring "repository not found"', () => {
+ expect(
+ classifyGitAuthError(
+ new Error("remote: HTTP 403 Forbidden\nfatal: repository 'x' not found"),
+ ),
+ ).toEqual({ kind: 'auth', subclass: '403' });
});
test('reads stderr from simple-git-style { message, git } shape', () => {
@@ -192,6 +237,7 @@ describe('isLoginFixableGitAuthError', () => {
{ input: { kind: 'auth', subclass: '403' }, expected: false },
{ input: { kind: 'auth', subclass: 'scope-mismatch' }, expected: false },
{ input: { kind: 'auth', subclass: 'ssh-auth' }, expected: false },
+ { input: { kind: 'auth', subclass: 'not-found-as-identity' }, expected: false },
{ input: { kind: 'non-auth' }, expected: false },
];
diff --git a/packages/core/src/schemas/api/share.ts b/packages/core/src/schemas/api/share.ts
index b196c6206..99757fa61 100644
--- a/packages/core/src/schemas/api/share.ts
+++ b/packages/core/src/schemas/api/share.ts
@@ -414,9 +414,19 @@ export function isBranchNotFoundGitError(error: unknown): boolean {
* - `ssh-auth` — SSH transport auth failure (publickey denied, host-key
* verification). `ok auth login` mints an HTTPS OAuth credential and cannot
* fix SSH keys or host-key trust, so this is NOT login-fixable.
+ * - `not-found-as-identity` — git reported "repository not found" with no
+ * 401/403 signal. GitHub answers 404 for both "doesn't exist" and
+ * "private + no access" (deliberately, to avoid leaking existence), so the
+ * stderr alone cannot say which — the repo may be missing, or the identity
+ * used may not see it. NOT login-fixable: for the repo-gone half a sign-in
+ * is a dead end, and the classifier cannot tell the halves apart, so no
+ * surface prescribes one. (A sign-in CAN fix the access half — a
+ * multi-account user authorizing the other account, or a fine-grained PAT
+ * replaced by a broader OAuth token — the copy names that possibility
+ * without prescribing the command.)
* - `unknown-auth` — generic HTTPS auth wording (authentication/authorization
- * failed, bad credentials, private-repo "repository not found") without a
- * 401/403 signal; re-auth can mint working credentials (login-fixable).
+ * failed, bad credentials) without a 401/403 signal; re-auth can mint
+ * working credentials (login-fixable).
*/
export type GitAuthFailureSubclass =
| 'no-credential'
@@ -424,6 +434,7 @@ export type GitAuthFailureSubclass =
| '403'
| 'scope-mismatch'
| 'ssh-auth'
+ | 'not-found-as-identity'
| 'unknown-auth';
/**
@@ -469,6 +480,13 @@ const GIT_AUTH_SSH_PATTERNS: RegExp[] = [
/host key verification failed/i,
];
+// GitHub's 404 masquerade: "repository not found" covers both a missing repo
+// and a private repo the presented credential can't see. Kept in the general
+// bank (it IS an auth-shaped failure) but discriminated into its own subclass
+// after the explicit 401/403 checks, since those statuses are the stronger
+// signal when they co-occur.
+const GIT_AUTH_REPO_NOT_FOUND_PATTERN = /fatal:.*repository.*not found/i;
+
const GIT_AUTH_GENERAL_PATTERNS: RegExp[] = [
/\b(401|403)\b/,
/authentication failed/i,
@@ -478,7 +496,7 @@ const GIT_AUTH_GENERAL_PATTERNS: RegExp[] = [
/bad credentials/i,
/token.*expired/i,
/expired.*token/i,
- /fatal:.*repository.*not found/i,
+ GIT_AUTH_REPO_NOT_FOUND_PATTERN,
];
function gitAuthExtractStderr(error: unknown): string {
@@ -519,6 +537,12 @@ export function classifyGitAuthError(error: unknown): ClassifiedGitAuthError {
if (/\b403\b/.test(combined)) {
return { kind: 'auth', subclass: '403' };
}
+ // Checked after 401/403 (an explicit status is authoritative) but before
+ // the unknown-auth fall-through: auth wording co-occurs on auth-shaped
+ // 404s, and the not-found signal is the more specific of the two.
+ if (GIT_AUTH_REPO_NOT_FOUND_PATTERN.test(combined)) {
+ return { kind: 'auth', subclass: 'not-found-as-identity' };
+ }
return { kind: 'auth', subclass: 'unknown-auth' };
}
return { kind: 'non-auth' };
@@ -530,6 +554,12 @@ export function classifyGitAuthError(error: unknown): ClassifiedGitAuthError {
* grant new access; `scope-mismatch` is excluded because the device flow
* mints the same fixed scopes each time; `ssh-auth` is excluded because
* `ok auth login` mints an HTTPS OAuth credential, not an SSH key.
+ * `not-found-as-identity` is excluded on ambiguity, not impossibility: a
+ * sign-in as a DIFFERENT account (or an OAuth token replacing a narrow
+ * fine-grained PAT) can reveal a private repo, but the stderr cannot
+ * distinguish that case from a deleted/renamed repo where sign-in is a dead
+ * end — so consumers withdraw the affordance and let the copy name both
+ * possibilities.
*/
export function isLoginFixableGitAuthError(classified: ClassifiedGitAuthError): boolean {
if (classified.kind !== 'auth') return false;
diff --git a/packages/core/src/schemas/api/sync-seed.test.ts b/packages/core/src/schemas/api/sync-seed.test.ts
index 0104d9507..bd66e5576 100644
--- a/packages/core/src/schemas/api/sync-seed.test.ts
+++ b/packages/core/src/schemas/api/sync-seed.test.ts
@@ -121,6 +121,19 @@ describe('SyncStatusSchema', () => {
}).success,
).toBe(true);
});
+ test('parses a status carrying the identity-ambiguous not-found push error code', () => {
+ // The 404-masquerade code rides the same bounded-enum field as the other
+ // auth codes; a current client must accept it. Skew the other way (an
+ // older client receiving this code) cannot fail at parse time — no client
+ // schema-validates sync status — and render-time degradation is the
+ // formatters' default branch, pinned in SyncStatusBadge.dom.test.tsx.
+ expect(
+ SyncStatusSchema.safeParse({
+ ...validStatus,
+ pushErrorCode: 'auth-not-found-as-identity',
+ }).success,
+ ).toBe(true);
+ });
test('rejects negative ahead/behind/conflictCount', () => {
expect(SyncStatusSchema.safeParse({ ...validStatus, ahead: -1 }).success).toBe(false);
expect(SyncStatusSchema.safeParse({ ...validStatus, behind: -1 }).success).toBe(false);
@@ -223,6 +236,45 @@ describe('PushPermissionSchema', () => {
PushPermissionSchema.safeParse({ checkStatus: 'unknown', unknownError: 'bogus' }).success,
).toBe(false);
});
+ test('round-trips a denial naming the authenticated identity and a declared miss', () => {
+ const wire = {
+ checkStatus: 'denied' as const,
+ deniedReason: 'private-no-access' as const,
+ resolvedLogin: 'bob',
+ declaredLogin: 'alice',
+ declaredSource: 'remote-url',
+ };
+ const parsed = PushPermissionSchema.parse(wire);
+ expect(parsed).toEqual(wire);
+ });
+ test('parses a denial without identity fields (payload from an older server)', () => {
+ const parsed = PushPermissionSchema.parse({
+ checkStatus: 'denied',
+ deniedReason: 'private-no-access',
+ });
+ expect(parsed).toEqual({ checkStatus: 'denied', deniedReason: 'private-no-access' });
+ });
+ test('accepts a declaredSource value it has never heard of', () => {
+ // The declaration mechanism is an open string by contract: a future
+ // server-side source must degrade to generic wording on this client,
+ // not fail the whole sync-status parse.
+ const parsed = PushPermissionSchema.safeParse({
+ checkStatus: 'denied',
+ deniedReason: 'private-no-access',
+ declaredLogin: 'alice',
+ declaredSource: 'owner-map',
+ });
+ expect(parsed.success).toBe(true);
+ });
+ test('rejects a non-string resolvedLogin (typed field, not loose passthrough)', () => {
+ expect(
+ PushPermissionSchema.safeParse({
+ checkStatus: 'denied',
+ deniedReason: 'private-no-access',
+ resolvedLogin: 123,
+ }).success,
+ ).toBe(false);
+ });
});
describe('SyncRemoteSchema', () => {
diff --git a/packages/core/src/schemas/api/sync-seed.ts b/packages/core/src/schemas/api/sync-seed.ts
index 09df3e996..32f21b52f 100644
--- a/packages/core/src/schemas/api/sync-seed.ts
+++ b/packages/core/src/schemas/api/sync-seed.ts
@@ -73,6 +73,22 @@ export const PushPermissionSchema = z.discriminatedUnion('checkStatus', [
'repo-not-found',
'not-authenticated',
]),
+ /**
+ * Login whose credential the probe actually authenticated with — what
+ * the token resolution landed on after any fallback, never a declared
+ * account the resolution fell back from. Absent when no identity is
+ * known; the UI must then omit the identity sentence rather than guess.
+ */
+ resolvedLogin: z.string().optional(),
+ /**
+ * Declared account that did NOT produce the credential used, plus the
+ * mechanism it was declared through — currently `'remote-url'` or
+ * `'credential-config'`. Open strings rather than enums: a payload
+ * from a server with a newer declaration mechanism must degrade to
+ * generic wording, not fail the whole sync-status parse.
+ */
+ declaredLogin: z.string().optional(),
+ declaredSource: z.string().optional(),
})
.loose(),
z
@@ -109,6 +125,13 @@ export const SYNC_ERROR_CODES = [
// back to a (no-TTY) interactive prompt. Distinct from `auth-401` (a token
// exists but was rejected): the user must reconnect, not just retry.
'auth-no-credential',
+ // GitHub's 404 masquerade: git said "repository not found" while a
+ // credential WAS attached. The repo may not exist, or the identity used may
+ // not see it — the stderr cannot say which, so the copy asserts both and
+ // never offers a sign-in as the fix. A client older than this code renders
+ // its formatter's generic fallback (the wire is not schema-validated
+ // client-side; the formatters carry an explicit default branch).
+ 'auth-not-found-as-identity',
'semantic-protected-branch',
] as const;
diff --git a/packages/desktop/src/main/git-remote.ts b/packages/desktop/src/main/git-remote.ts
index 80e14c74c..3124d6617 100644
--- a/packages/desktop/src/main/git-remote.ts
+++ b/packages/desktop/src/main/git-remote.ts
@@ -27,7 +27,20 @@ export function readCanonicalGitHubRemoteUrl(projectPath: string): string | null
const origin = inspection.repository.readRemoteUrl('origin');
if (origin.kind !== 'configured') return null;
- const parsed = parseGitUrl(origin.url);
+ return canonicalizeGitHubRemoteUrl(origin.url);
+}
+
+/**
+ * Re-emit a git remote URL in the canonical `https://<host>/<owner>/<repo>.git`
+ * form, or null when it isn't a GitHub-host URL. The rebuild is from parsed
+ * components only, so no userinfo — a declared account or an embedded
+ * credential — can survive into the output. Also the load-time repair for
+ * `RecentProject.gitRemoteUrl` values persisted by builds whose parser folded
+ * userinfo into the hostname and rebuilt credentialed URLs — an in-memory
+ * heal; the persisted copy is replaced by the next whole-file state save.
+ */
+export function canonicalizeGitHubRemoteUrl(url: string): string | null {
+ const parsed = parseGitUrl(url);
if (parsed === null) return null;
// Presume any host that isn't a known non-GitHub forge is github.com or a
// GHES instance, and re-emit the canonical HTTPS form host-qualified so
diff --git a/packages/desktop/src/main/state-store.ts b/packages/desktop/src/main/state-store.ts
index dbdecb161..d552da1e2 100644
Binary files a/packages/desktop/src/main/state-store.ts and b/packages/desktop/src/main/state-store.ts differ
diff --git a/packages/desktop/src/main/worktree-service.test.ts b/packages/desktop/src/main/worktree-service.test.ts
index 5ba0c9d35..c419ea74a 100644
--- a/packages/desktop/src/main/worktree-service.test.ts
+++ b/packages/desktop/src/main/worktree-service.test.ts
@@ -874,6 +874,35 @@ describe('worktree-service — share-branch checkout', () => {
expect(await repoSnapshot(handle.mainRepo)).toEqual(before);
});
+ // The repository-not-found masquerade: git said "not found" while a
+ // credential was presented, which covers both a deleted repo and one the
+ // identity can't see. Not login-fixable, so the dialog must NOT offer
+ // Sign in — the dedicated `notFoundAsIdentity` flag routes it to copy naming both
+ // possibilities, matching the badge's withdrawn affordance for the same
+ // classification.
+ test('checkoutShareBranchWorktree does not flag repository-not-found as authFailed', async () => {
+ handle = await makeRepo();
+ const notFoundRemote = join(handle.root, 'not-found-remote.sh');
+ writeFileSync(
+ notFoundRemote,
+ '#!/bin/sh\necho "remote: Repository not found." >&2\necho "fatal: repository \'https://github.com/acme/gone.git/\' not found" >&2\nexit 1\n',
+ { mode: 0o755 },
+ );
+ await git(handle.mainRepo, 'config', 'protocol.ext.allow', 'always');
+ await git(handle.mainRepo, 'remote', 'add', 'origin', `ext::${notFoundRemote}`);
+
+ const res = await checkoutShareBranchWorktree({
+ anchorPath: handle.mainRepo,
+ branch: 'any-branch',
+ });
+ expect(res.ok).toBe(false);
+ if (res.ok) return;
+ expect(res.reason).toBe('fetch-failed');
+ expect(res.authFailed).toBeUndefined();
+ expect(res.notFoundAsIdentity).toBe(true);
+ expect(res.message).toMatch(/not found/i);
+ });
+
// fetch-leg hang: an ext:: transport that just sleeps stands in for a
// stalled network. The injected bound must kill the fetch (classified
// retryable) long before the transport would give up on its own. The elapsed
diff --git a/packages/desktop/src/main/worktree-service.ts b/packages/desktop/src/main/worktree-service.ts
index e599b7bbe..4d4ba9162 100644
--- a/packages/desktop/src/main/worktree-service.ts
+++ b/packages/desktop/src/main/worktree-service.ts
@@ -40,6 +40,7 @@ import {
type WorktreeListResult,
worktreeRelativeDir,
} from '@inkeep/open-knowledge-core';
+import { redactShareSubprocessStderr } from '@inkeep/open-knowledge-server';
import { gitSpawnEnv } from './git-spawn-env.ts';
import { listGitWorktrees } from './list-git-worktrees.ts';
import { seedWorktreeAutoSync } from './worktree-autosync-inherit.ts';
@@ -368,7 +369,11 @@ async function fetchShareBranch(
// the elapsed-timeout case apart without correlating wall-clock times.
const killed = (err as { killed?: boolean }).killed === true;
const signal = (err as { signal?: string }).signal;
- const raw = gitErrorText(err).replace(/\s+/g, ' ').slice(0, 280);
+ // Redacted like the clone path's sibling: the error classified here
+ // (`fatal: repository 'https://<user>:<pat>@github.com/o/r.git/' not found`)
+ // is exactly the one where git quotes the credentialed remote back, and this
+ // string becomes a WorktreeCreateResult.message that crosses the IPC boundary.
+ const raw = redactShareSubprocessStderr(gitErrorText(err)).replace(/\s+/g, ' ').slice(0, 280);
// A credential miss is not a connection problem, and telling the user to
// check their network when they need to sign in is a dead end — doubly so
// since `buildShareFetchArgs` pins interactivity off, so no helper will
@@ -377,11 +382,17 @@ async function fetchShareBranch(
// in again does not repair, and offering it would be the same dead end.
const classified = classifyGitAuthError(err);
const authFailed = isLoginFixableGitAuthError(classified);
+ // The not-found masquerade is excluded from login-fixable, but routing it
+ // to the connection copy would be the same dead end — the remote answered.
+ // Flag it so the dialog can name what is actually known.
+ const notFoundAsIdentity =
+ classified.kind === 'auth' && classified.subclass === 'not-found-as-identity';
return {
ok: false,
reason: 'fetch-failed',
message: killed ? `[timeout signal=${signal ?? 'SIGTERM'}] ${raw}` : raw,
...(authFailed ? { authFailed: true as const } : {}),
+ ...(notFoundAsIdentity ? { notFoundAsIdentity: true as const } : {}),
};
}
}
diff --git a/packages/desktop/src/utility/server-entry.ts b/packages/desktop/src/utility/server-entry.ts
index 4be4f75c1..01765cb1c 100644
--- a/packages/desktop/src/utility/server-entry.ts
+++ b/packages/desktop/src/utility/server-entry.ts
@@ -24,6 +24,7 @@ import { rename, writeFile } from 'node:fs/promises';
import { isAbsolute, relative, resolve } from 'node:path';
import {
detectGh,
+ detectGhAccounts,
ensurePiBridge,
getNativeTomlMcpEditor,
loadConfig,
@@ -373,6 +374,7 @@ export function setupUtility(deps: SetupUtilityDeps): UtilityHandle {
skipAutoInit: true,
autoInitFn: undefined,
detectGh,
+ detectGhAccounts,
tokenStore,
embeddingsKeyStore,
mcpTomlEditor: getNativeTomlMcpEditor(),
diff --git a/packages/desktop/tests/main/state-store.test.ts b/packages/desktop/tests/main/state-store.test.ts
index e1bf5e80e..4d6bf0c21 100644
--- a/packages/desktop/tests/main/state-store.test.ts
+++ b/packages/desktop/tests/main/state-store.test.ts
@@ -144,6 +144,44 @@ describe('state-store (recent projects + LRU)', () => {
expect(annotated.find((p) => p.path === '/tmp/missing')?.missing).toBe(true);
});
+ // Entries persisted before the userinfo-aware URL parser can hold a
+ // credentialed remote URL at rest (`https://alice:[email protected]/…`), and a
+ // project never re-opened would keep it forever — the writer only re-emits
+ // on open. Load-time canonicalization heals them.
+ test('parseAppState heals a credentialed gitRemoteUrl and keeps canonical ones verbatim', () => {
+ const parsed = parseAppState({
+ recentProjects: [
+ {
+ path: '/tmp/leaky',
+ name: 'leaky',
+ lastOpenedAt: '2026-04-20T00:00:00Z',
+ gitRemoteUrl: 'https://alice:[email protected]/acme/kb.git',
+ },
+ {
+ path: '/tmp/clean',
+ name: 'clean',
+ lastOpenedAt: '2026-04-20T00:00:00Z',
+ gitRemoteUrl: 'https://github.com/acme/other.git',
+ },
+ {
+ path: '/tmp/junk',
+ name: 'junk',
+ lastOpenedAt: '2026-04-20T00:00:00Z',
+ gitRemoteUrl: 'not a url at all',
+ },
+ ],
+ projectSessions: {},
+ });
+ expect(parsed).not.toBeNull();
+ const byPath = Object.fromEntries((parsed?.recentProjects ?? []).map((p) => [p.path, p]));
+ expect(byPath['/tmp/leaky']?.gitRemoteUrl).toBe('https://github.com/acme/kb.git');
+ expect(byPath['/tmp/clean']?.gitRemoteUrl).toBe('https://github.com/acme/other.git');
+ // A value the parser cannot read is dropped, not kept — it was junk-shaped
+ // and could itself be credential-bearing.
+ expect(byPath['/tmp/junk']?.gitRemoteUrl).toBeUndefined();
+ expect(JSON.stringify(parsed)).not.toContain('s3cretpw');
+ });
+
test('parseAppState ignores flat legacy project sessions', () => {
const raw = {
recentProjects: [{ path: '/tmp/a', name: 'a', lastOpenedAt: '2026-04-20T00:00:00Z' }],
diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.ts
index 853b2f8f8..a14319c16 100644
--- a/packages/server/src/boot.ts
+++ b/packages/server/src/boot.ts
@@ -210,6 +210,7 @@ export interface BootServerOptions
| 'enableTestRoutes'
| 'lockKind'
| 'detectGh'
+ | 'detectGhAccounts'
| 'tokenStore'
| 'embeddingsKeyStore'
| 'singleDocRelPath'
@@ -799,6 +800,7 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {
capabilities: opts.reactShellDistDir ? ['http', 'ws', 'ui'] : ['http', 'ws'],
skipStateManifestCheck: opts.skipStateManifestCheck,
detectGh: opts.detectGh,
+ detectGhAccounts: opts.detectGhAccounts,
tokenStore: opts.tokenStore,
embeddingsKeyStore: opts.embeddingsKeyStore,
singleDocRelPath: opts.singleDocRelPath,
diff --git a/packages/server/src/error-classification.test.ts b/packages/server/src/error-classification.test.ts
index 112084a36..77c18a88d 100644
--- a/packages/server/src/error-classification.test.ts
+++ b/packages/server/src/error-classification.test.ts
@@ -203,6 +203,20 @@ describe('classifyGitError', () => {
expect(r.subclass).toBe('unknown-auth');
});
+ test('not-found-as-identity subclass — "repository not found" (404 masquerade)', () => {
+ const r = classifyGitError(
+ mkErr("fatal: repository 'https://github.com/o/private.git/' not found"),
+ );
+ expect(r.class).toBe('auth');
+ expect(r.subclass).toBe('not-found-as-identity');
+ expect(r.retryable).toBe(false);
+ // The message asserts only what the stderr proves: the repo is missing
+ // OR the identity used can't see it — never which, never "wrong account".
+ expect(r.message).toBe(
+ 'Repository not found — it may not exist, or the account used may not have access',
+ );
+ });
+
test('ssh-auth subclass — SSH publickey denied (delegation preserves output)', () => {
const r = classifyGitError(mkErr('Permission denied (publickey).'));
expect(r.class).toBe('auth');
@@ -469,6 +483,15 @@ describe('classifyGitError', () => {
expect(r.userFacingCode).toBe('semantic-protected-branch');
});
+ test('auth/not-found-as-identity → auth-not-found-as-identity code', () => {
+ const r = classifyGitError(
+ mkErr("fatal: repository 'https://github.com/o/r.git/' not found"),
+ );
+ expect(r.class).toBe('auth');
+ expect(r.subclass).toBe('not-found-as-identity');
+ expect(r.userFacingCode).toBe('auth-not-found-as-identity');
+ });
+
test('semantic/non-fast-forward → null (UI falls back to message)', () => {
const r = classifyGitError(
mkErr('error: failed to push some refs', 'rejected non-fast-forward updates'),
diff --git a/packages/server/src/error-classification.ts b/packages/server/src/error-classification.ts
index 9c1968f8e..eb2c9a401 100644
--- a/packages/server/src/error-classification.ts
+++ b/packages/server/src/error-classification.ts
@@ -18,14 +18,9 @@ import {
/** Subclass strings, narrowed per class. */
type NetworkSubclass = 'dns' | 'timeout' | '5xx' | '429' | 'connection-refused' | 'unknown-network';
-type AuthSubclass =
- | '401'
- | '403'
- | 'expired-token'
- | 'scope-mismatch'
- | 'no-credential'
- | 'ssh-auth'
- | 'unknown-auth';
+// Derived from the canonical core union so a new subclass lands here
+// automatically, the same way `AUTH_SUBCLASS_MESSAGES` already tracks it.
+type AuthSubclass = GitAuthFailureSubclass;
type SemanticSubclass =
| 'non-fast-forward'
| 'protected-branch'
@@ -110,6 +105,7 @@ export function deriveUserFacingCode(
if (cls === 'auth' && subclass === '401') return 'auth-401';
if (cls === 'auth' && subclass === 'scope-mismatch') return 'auth-scope-mismatch';
if (cls === 'auth' && subclass === 'no-credential') return 'auth-no-credential';
+ if (cls === 'auth' && subclass === 'not-found-as-identity') return 'auth-not-found-as-identity';
if (cls === 'semantic' && subclass === 'protected-branch') return 'semantic-protected-branch';
return null;
}
@@ -141,6 +137,10 @@ const AUTH_SUBCLASS_MESSAGES: Record<GitAuthFailureSubclass, string> = {
'403': 'Access denied (403)',
'scope-mismatch': 'GitHub token missing required scopes',
'ssh-auth': 'SSH authentication failed — check your SSH key or host-key trust',
+ // Asserts only what the stderr proves: GitHub 404s both "doesn't exist" and
+ // "private + no access", so the copy names both and accuses neither.
+ 'not-found-as-identity':
+ 'Repository not found — it may not exist, or the account used may not have access',
'unknown-auth': 'Authentication failed',
};
diff --git a/packages/server/src/gh-token-source.test.ts b/packages/server/src/gh-token-source.test.ts
index 2ac81aee0..7eb59d3dc 100644
--- a/packages/server/src/gh-token-source.test.ts
+++ b/packages/server/src/gh-token-source.test.ts
@@ -20,6 +20,21 @@ function makeClock(start = 1_000): { now: () => number; advance: (ms: number) =>
return { now: () => t, advance: (ms: number) => (t += ms) };
}
+/** A `detectGh` fake that records each (host, login) request and answers via `behavior`. */
+function makeRecordingDetectGh(
+ behavior: (host?: string, login?: string) => ReturnType<DetectGhFn>,
+): { fn: DetectGhFn; calls: () => Array<{ host?: string; login?: string }> } {
+ const calls: Array<{ host?: string; login?: string }> = [];
+ return {
+ fn: (host?: string, options?: { login?: string }) => {
+ const login = options?.login;
+ calls.push({ host, login });
+ return behavior(host, login);
+ },
+ calls: () => calls,
+ };
+}
+
describe('createGhTokenSource', () => {
test('returns null throughout when no detectGh is injected', () => {
const source = createGhTokenSource(undefined);
@@ -33,7 +48,11 @@ describe('createGhTokenSource', () => {
});
test('returns null when gh is available but carries no token', () => {
- const detect = makeDetectGh({ available: true });
+ // Unrepresentable for a TYPED implementation (the union makes
+ // `available: true` imply a token), but this seam accepts injected
+ // implementations from untyped callers too — the runtime guard must
+ // degrade a tokenless "available" to no-credential, not relay undefined.
+ const detect = makeDetectGh({ available: true } as ReturnType<DetectGhFn>);
const source = createGhTokenSource(detect.fn);
expect(source.get('github.com')).toBeNull();
});
@@ -92,3 +111,242 @@ describe('createGhTokenSource', () => {
expect(detect.calls()).toBe(2);
});
});
+
+describe('createGhTokenSource with a requested account', () => {
+ test('forwards the login to detectGh and names the account that produced the token', () => {
+ const detect = makeRecordingDetectGh(() => ({
+ available: true,
+ token: 'gho_alice',
+ resolvedLogin: 'alice',
+ fallback: false,
+ }));
+ const source = createGhTokenSource(detect.fn);
+
+ expect(source.get('github.com', 'alice')).toEqual({
+ token: 'gho_alice',
+ host: 'github.com',
+ login: 'alice',
+ });
+ expect(detect.calls()).toEqual([{ host: 'github.com', login: 'alice' }]);
+ });
+
+ test('keys the cache per account — bare-host and per-login entries are independent', () => {
+ const detect = makeRecordingDetectGh((_host, login) => {
+ if (login === 'alice')
+ return { available: true, token: 'gho_alice', resolvedLogin: 'alice', fallback: false };
+ if (login === 'bob')
+ return { available: true, token: 'gho_bob', resolvedLogin: 'bob', fallback: false };
+ return { available: true, token: 'gho_active' };
+ });
+ const source = createGhTokenSource(detect.fn);
+
+ expect(source.get('github.com')?.token).toBe('gho_active');
+ expect(source.get('github.com', 'alice')?.token).toBe('gho_alice');
+ expect(source.get('github.com', 'bob')?.token).toBe('gho_bob');
+
+ // Repeat gets serve each key's own cached entry, not each other's.
+ expect(source.get('github.com')?.token).toBe('gho_active');
+ expect(source.get('github.com', 'alice')?.token).toBe('gho_alice');
+ expect(source.get('github.com', 'bob')?.token).toBe('gho_bob');
+ expect(detect.calls()).toHaveLength(3);
+ });
+
+ test('a fallback is cached only briefly, so signing the declared account in takes effect on the next resolution', () => {
+ const known = new Map<string, string>();
+ const detect = makeRecordingDetectGh((_host, login) => {
+ const token = login ? known.get(login) : undefined;
+ if (login && token) return { available: true, token, resolvedLogin: login, fallback: false };
+ return login
+ ? { available: true, token: 'gho_active', fallback: true }
+ : { available: true, token: 'gho_active' };
+ });
+ const clock = makeClock();
+ const source = createGhTokenSource(detect.fn, {
+ ttlMs: 60_000,
+ fallbackTtlMs: 5_000,
+ now: clock.now,
+ });
+
+ // alice is not signed in: the active account's token answers, unattributed —
+ // the relay value must not claim the account that was asked for.
+ expect(source.get('github.com', 'alice')).toEqual({ token: 'gho_active', host: 'github.com' });
+ expect(source.get('github.com', 'alice')).not.toHaveProperty('login');
+
+ // Within the short window the fallback serves from cache: a push cycle's
+ // burst of handles costs one spawn.
+ clock.advance(4_999);
+ expect(source.get('github.com', 'alice')?.token).toBe('gho_active');
+ expect(detect.calls()).toHaveLength(1);
+
+ // The user signs alice in. Past the short TTL — far inside the full TTL —
+ // the next get re-resolves and alice's own token lands under alice's key.
+ known.set('alice', 'gho_alice');
+ clock.advance(2);
+ expect(source.get('github.com', 'alice')).toEqual({
+ token: 'gho_alice',
+ host: 'github.com',
+ login: 'alice',
+ });
+ expect(detect.calls()).toHaveLength(2);
+ });
+
+ // The honored/miss decision routes through the shared login comparison, so
+ // an implementation that answers with GitHub's canonical casing for a
+ // differently-cased request counts as honored — it gets the FULL TTL, not
+ // the escalating miss window. Under an exact-match comparison this key
+ // would re-spawn gh every few seconds for a correctly-configured remote.
+ test('a casing-only difference in the resolved login is honored, not a miss', () => {
+ const detect = makeRecordingDetectGh(() => ({
+ available: true,
+ token: 'gho_alice',
+ resolvedLogin: 'alice',
+ fallback: false,
+ }));
+ const clock = makeClock();
+ const source = createGhTokenSource(detect.fn, {
+ ttlMs: 60_000,
+ fallbackTtlMs: 5_000,
+ now: clock.now,
+ });
+
+ expect(source.get('github.com', 'Alice')?.token).toBe('gho_alice');
+ expect(detect.calls()).toHaveLength(1);
+
+ // Past the miss window but far inside the full TTL: an honored entry is
+ // still cached, so no second spawn.
+ clock.advance(10_000);
+ expect(source.get('github.com', 'Alice')?.token).toBe('gho_alice');
+ expect(detect.calls()).toHaveLength(1);
+ });
+
+ test('a standing miss backs off — the fallback window doubles per resolution up to the full TTL', () => {
+ const detect = makeRecordingDetectGh((_host, login) =>
+ login
+ ? { available: true, token: 'gho_active', fallback: true }
+ : { available: true, token: 'gho_active' },
+ );
+ const clock = makeClock();
+ const source = createGhTokenSource(detect.fn, {
+ ttlMs: 60_000,
+ fallbackTtlMs: 5_000,
+ now: clock.now,
+ });
+
+ source.get('github.com', 'alice'); // miss #1 → 5s window
+ clock.advance(5_001);
+ source.get('github.com', 'alice'); // miss #2 → 10s window
+ expect(detect.calls()).toHaveLength(2);
+
+ // Inside the doubled window the standing miss serves from cache instead
+ // of re-paying the failing candidate walk.
+ clock.advance(5_001);
+ source.get('github.com', 'alice');
+ expect(detect.calls()).toHaveLength(2);
+
+ clock.advance(5_000); // now past the 10s window
+ source.get('github.com', 'alice'); // miss #3 → 20s window
+ expect(detect.calls()).toHaveLength(3);
+
+ // The escalation is capped at the full TTL: after many misses the window
+ // never exceeds what an honored entry would get.
+ for (let i = 0; i < 6; i += 1) {
+ clock.advance(60_001);
+ source.get('github.com', 'alice');
+ }
+ const callsAtCap = detect.calls().length;
+ clock.advance(59_000);
+ source.get('github.com', 'alice');
+ expect(detect.calls()).toHaveLength(callsAtCap);
+ clock.advance(1_001);
+ source.get('github.com', 'alice');
+ expect(detect.calls()).toHaveLength(callsAtCap + 1);
+ });
+
+ test('invalidate() resets the fallback backoff along with the cache', () => {
+ const detect = makeRecordingDetectGh((_host, login) =>
+ login
+ ? { available: true, token: 'gho_active', fallback: true }
+ : { available: true, token: 'gho_active' },
+ );
+ const clock = makeClock();
+ const source = createGhTokenSource(detect.fn, {
+ ttlMs: 60_000,
+ fallbackTtlMs: 5_000,
+ now: clock.now,
+ });
+
+ source.get('github.com', 'alice'); // miss #1 → 5s window
+ clock.advance(5_001);
+ source.get('github.com', 'alice'); // miss #2 → would be a 10s window
+ source.invalidate();
+
+ // Post-invalidate the streak starts over: the fresh miss gets the fast
+ // initial window again, so an explicit credential-change signal recovers
+ // as quickly as the very first resolution did.
+ source.get('github.com', 'alice'); // miss #1 again → 5s window
+ clock.advance(5_001);
+ source.get('github.com', 'alice');
+ expect(detect.calls()).toHaveLength(4);
+ });
+
+ // Constructed the way production constructs it (no TTL options) so the
+ // shipped initial fallback window is pinned — replacing the default with
+ // the full TTL would silently restore the minute-long wrong-account window
+ // the short TTL exists to prevent.
+ test('the default initial fallback window is 5s', () => {
+ const known = new Map<string, string>();
+ const detect = makeRecordingDetectGh((_host, login) => {
+ const token = login ? known.get(login) : undefined;
+ if (login && token) return { available: true, token, resolvedLogin: login, fallback: false };
+ return { available: true, token: 'gho_active', ...(login ? { fallback: true } : {}) };
+ });
+ const clock = makeClock();
+ const source = createGhTokenSource(detect.fn, { now: clock.now });
+
+ expect(source.get('github.com', 'alice')?.login).toBeUndefined();
+ known.set('alice', 'gho_alice');
+ clock.advance(5_001);
+ expect(source.get('github.com', 'alice')?.login).toBe('alice');
+ });
+
+ test('an honored account entry keeps the full TTL — only unhonored results expire early', () => {
+ const detect = makeRecordingDetectGh((_host, login) =>
+ login
+ ? { available: true, token: 'gho_alice', resolvedLogin: login, fallback: false }
+ : { available: false },
+ );
+ const clock = makeClock();
+ const source = createGhTokenSource(detect.fn, {
+ ttlMs: 60_000,
+ fallbackTtlMs: 5_000,
+ now: clock.now,
+ });
+
+ source.get('github.com', 'alice');
+ clock.advance(30_000);
+ expect(source.get('github.com', 'alice')?.token).toBe('gho_alice');
+ expect(detect.calls()).toHaveLength(1);
+ });
+
+ test('a no-credential answer under an account key also expires on the short TTL', () => {
+ const known = new Map<string, string>();
+ const detect = makeRecordingDetectGh((_host, login) => {
+ const token = login ? known.get(login) : undefined;
+ if (login && token) return { available: true, token, resolvedLogin: login, fallback: false };
+ return { available: false };
+ });
+ const clock = makeClock();
+ const source = createGhTokenSource(detect.fn, {
+ ttlMs: 60_000,
+ fallbackTtlMs: 5_000,
+ now: clock.now,
+ });
+
+ expect(source.get('github.com', 'alice')).toBeNull();
+
+ // Signing in is the recovery this short window exists for.
+ known.set('alice', 'gho_alice');
+ clock.advance(5_001);
+ expect(source.get('github.com', 'alice')?.login).toBe('alice');
+ });
+});
diff --git a/packages/server/src/gh-token-source.ts b/packages/server/src/gh-token-source.ts
index dd9ec98e8..2aa1d5868 100644
--- a/packages/server/src/gh-token-source.ts
+++ b/packages/server/src/gh-token-source.ts
@@ -9,69 +9,137 @@
* creates many git handles. Resolving on every handle would spawn `gh`
* repeatedly on the hot path.
*
- * This wraps `detectGh` with a short per-host TTL cache so resolution costs at
- * most one `gh` spawn per host per `ttlMs` window. `invalidate()` drops the
- * cache so a credential change (a fresh `gh auth login`, or a revoked token that
- * just produced a classified auth error) is picked up on the next cycle rather
- * than after the TTL elapses.
+ * This wraps `detectGh` with a TTL cache keyed per host + requested account so
+ * resolution costs at most one `gh` spawn per key per TTL window. Entries whose
+ * requested account did not produce the token (the active account answered
+ * instead, or no token at all) expire on a shorter TTL that escalates while
+ * the miss persists — see the invariant at the set site. `invalidate()` drops
+ * the cache so a credential change (a
+ * fresh `gh auth login`, or a revoked token that just produced a classified
+ * auth error) is picked up on the next cycle rather than after the TTL elapses.
*/
import type { RelayGhToken } from './git-handle.ts';
import type { DetectGhFn } from './github-permissions.ts';
+import { sameGitHubLogin } from './share/git-context.ts';
export interface GhTokenSource {
/**
* Resolve the gh token for `host`, served from cache when fresh. Returns
* `null` when `gh` is unavailable, not authenticated for the host, or no
* `detectGh` was injected.
+ *
+ * When `login` is given the token is requested for that account
+ * specifically; an account gh cannot serve degrades to the active account's
+ * token rather than to no credential. The relay value's `login` names the
+ * account that actually produced the token — absent after such a fallback,
+ * so callers surfacing an identity never claim the account they asked for.
*/
- get(host: string): RelayGhToken | null;
+ get(host: string, login?: string): RelayGhToken | null;
/** Drop all cached entries so the next `get` re-resolves. */
invalidate(): void;
}
interface CacheEntry {
token: string | null;
+ /** Account that produced `token`, as reported by `detectGh`. */
+ resolvedLogin?: string;
expiresAt: number;
}
export interface GhTokenSourceOptions {
- /** Cache lifetime per host. Default 60s. */
+ /** Cache lifetime per key when the request was answered as asked. Default 60s. */
ttlMs?: number;
+ /**
+ * INITIAL cache lifetime for entries whose requested account did not
+ * produce the token. Default 5s — long enough that a push cycle's burst of
+ * git handles shares one `gh` spawn, short enough that signing the declared
+ * account in takes effect within a cycle or two. A miss that persists
+ * doubles this per resolution up to `ttlMs`: the modal miss (a declared
+ * account that is simply never signed in) must not re-pay the doubled
+ * failing candidate walk every few seconds forever, and the worst-case
+ * staleness converges to the same ceiling an honored entry already has.
+ * `invalidate()` — fired on OK sign-in and on classified auth errors —
+ * resets the escalation, so the explicit recovery signal stays instant.
+ */
+ fallbackTtlMs?: number;
/** Injectable clock for tests. Default `Date.now`. */
now?: () => number;
}
const DEFAULT_TTL_MS = 60_000;
+const DEFAULT_FALLBACK_TTL_MS = 5_000;
export function createGhTokenSource(
detectGh: DetectGhFn | undefined,
options: GhTokenSourceOptions = {},
): GhTokenSource {
const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
+ const fallbackTtlMs = options.fallbackTtlMs ?? DEFAULT_FALLBACK_TTL_MS;
const now = options.now ?? Date.now;
const cache = new Map<string, CacheEntry>();
+ // Consecutive unhonored resolutions per key, driving the fallback-TTL
+ // escalation. Cleared alongside the cache and on any honored resolution.
+ const missStreak = new Map<string, number>();
+
+ function toRelay(entry: CacheEntry, host: string): RelayGhToken | null {
+ if (entry.token == null) return null;
+ return {
+ token: entry.token,
+ host,
+ ...(entry.resolvedLogin ? { login: entry.resolvedLogin } : {}),
+ };
+ }
return {
- get(host: string): RelayGhToken | null {
+ get(host: string, login?: string): RelayGhToken | null {
if (!detectGh) return null;
+ // NUL cannot appear in a hostname or a GitHub login, so the compound key
+ // never collides with a bare-host key.
+ const key = `${host}\0${login ?? ''}`;
const t = now();
- const cached = cache.get(host);
- if (cached && cached.expiresAt > t) {
- return cached.token != null ? { token: cached.token, host } : null;
- }
+ const cached = cache.get(key);
+ if (cached && cached.expiresAt > t) return toRelay(cached, host);
- // `detectGh` never throws (it swallows spawn failures into
- // `{ available: false }`), so no try/catch is needed here.
- const result = detectGh(host);
+ // `detectGh` swallows spawn failures into `{ available: false }`, and
+ // its only throw is an argument-shape guard a typed caller cannot trip,
+ // so no try/catch is needed here.
+ const result = detectGh(host, { login });
const token = result.available && result.token ? result.token : null;
- cache.set(host, { token, expiresAt: t + ttlMs });
- return token != null ? { token, host } : null;
+ // Narrowed once here so the rest of the body can read the identity
+ // without re-narrowing — the unavailable arm carries no fields at all,
+ // matching the CLI result shape exactly.
+ const resolvedLogin = result.available ? result.resolvedLogin : undefined;
+
+ // Invariant: an entry under an account key gets the full TTL only when
+ // that account produced the token. A fallback (active account answered)
+ // or a miss expires on the short-but-escalating TTL: fresh misses stay
+ // fast so a `gh auth login` fix lands within a cycle or two, while a
+ // standing miss backs off toward the full TTL instead of re-spawning gh
+ // every few seconds indefinitely.
+ const honored = !login || (token != null && sameGitHubLogin(resolvedLogin, login));
+ let entryTtl: number;
+ if (honored) {
+ missStreak.delete(key);
+ entryTtl = ttlMs;
+ } else {
+ const misses = missStreak.get(key) ?? 0;
+ missStreak.set(key, misses + 1);
+ entryTtl = Math.min(fallbackTtlMs * 2 ** misses, ttlMs);
+ }
+ const entry: CacheEntry = {
+ token,
+ resolvedLogin,
+ expiresAt: t + entryTtl,
+ };
+ cache.set(key, entry);
+ return toRelay(entry, host);
},
invalidate(): void {
cache.clear();
+ missStreak.clear();
},
};
}
diff --git a/packages/server/src/git-handle.test.ts b/packages/server/src/git-handle.test.ts
index 001f9935b..05635ed38 100644
--- a/packages/server/src/git-handle.test.ts
+++ b/packages/server/src/git-handle.test.ts
@@ -125,6 +125,16 @@ describe('buildGitEnv', () => {
expect(withToken.OK_GH_TOKEN).toBe('gho_relayed');
expect(withToken.OK_GH_TOKEN_HOST).toBe('github.com');
});
+
+ test('emits OK_GH_TOKEN_LOGIN only when the relay names its account', () => {
+ const named = buildGitEnv({ token: 'gho_relayed', host: 'github.com', login: 'alice' });
+ expect(named.OK_GH_TOKEN_LOGIN).toBe('alice');
+
+ // A token the active account answered anonymously carries no login, and the
+ // env must not invent one — a wrong name here misdirects auth diagnostics.
+ const anonymous = buildGitEnv({ token: 'gho_relayed', host: 'github.com' });
+ expect('OK_GH_TOKEN_LOGIN' in anonymous).toBe(false);
+ });
});
describe('createGitInstance (credential.helper config)', () => {
diff --git a/packages/server/src/git-handle.ts b/packages/server/src/git-handle.ts
index b7b64ffd9..e88d887b4 100644
--- a/packages/server/src/git-handle.ts
+++ b/packages/server/src/git-handle.ts
@@ -45,6 +45,12 @@ export interface RelayGhToken {
token: string;
/** Host the token authenticates (e.g. `github.com`); the helper host-matches before using it. */
host: string;
+ /**
+ * gh account that produced the token, when known. Absent for tokens the
+ * active account answered anonymously (`gh auth token` names no account), so
+ * diagnostics reading this must degrade to "identity unknown", never guess.
+ */
+ login?: string;
}
interface GitHandleOptions {
@@ -170,7 +176,10 @@ const GIT_AUTH_ENV_KEYS = [
* `OK_GH_TOKEN`/`OK_GH_TOKEN_HOST` are added only when a {@link RelayGhToken} is
* supplied. This is the deliberate, named channel that carries a server-resolved
* gh token to the credential helper across the env replacement — see
- * {@link RelayGhToken}.
+ * {@link RelayGhToken}. `OK_GH_TOKEN_LOGIN` additionally names the account that
+ * produced the token when that is known — diagnostics only: the helper's relay
+ * condition stays host-only, so the var must never gate whether the token is
+ * served.
*/
export function buildGitEnv(ghToken?: RelayGhToken): Record<string, string> {
const env: Record<string, string> = {
@@ -199,6 +208,7 @@ export function buildGitEnv(ghToken?: RelayGhToken): Record<string, string> {
if (ghToken) {
env.OK_GH_TOKEN = ghToken.token;
env.OK_GH_TOKEN_HOST = ghToken.host;
+ if (ghToken.login) env.OK_GH_TOKEN_LOGIN = ghToken.login;
}
return env;
}
diff --git a/packages/server/src/github-account-agreement.test.ts b/packages/server/src/github-account-agreement.test.ts
new file mode 100644
index 000000000..cad76312f
--- /dev/null
+++ b/packages/server/src/github-account-agreement.test.ts
@@ -0,0 +1,275 @@
+/**
+ * Agreement pin across the three consumers of declared-account resolution:
+ * the push-permission probe, the sync engine's git handles, and the clone
+ * path's URL resolution. One remote must resolve to one GitHub identity in
+ * all three — an edit that threads the account into some consumers but not
+ * others lets the probe report `allowed` as one account while the push
+ * authenticates as another.
+ *
+ * Agreement is asserted at the account-resolution layer, via the scripted
+ * gh fake's recorded arguments, not by comparing tokens alone: the three
+ * consumers share no token cache (the probe calls `detectGh` raw), so a
+ * same-token assertion could stay green while a consumer stopped requesting
+ * the declared account.
+ *
+ * The clone leg is `resolveGitHubAccountFromUrl` plus a direct `detectGh`
+ * forward: `ok clone` consumes exactly that resolver, but its forwarding
+ * code lives in `packages/cli`, which this package cannot import (cli
+ * already depends on server). The cli's own suites pin the forwarding; this
+ * file pins that the resolution feeding it matches the server-side
+ * consumers.
+ */
+
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { LOCAL_DIR } from '@inkeep/open-knowledge-core';
+import simpleGit from 'simple-git';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import type { GitHandle } from './git-handle.ts';
+import {
+ type CheckPushPermissionOptions,
+ checkPushPermission,
+ type DetectGhFn,
+ type FetchFn,
+} from './github-permissions.ts';
+import {
+ type CredentialUrlMatchReader,
+ type GitHubAccount,
+ resolveGitHubAccountFromUrl,
+} from './share/github-account.ts';
+import { SyncEngine } from './sync-engine.ts';
+
+const stubContentFilter = {
+ isExcluded: (_path: string) => false,
+ isDirExcluded: (_path: string) => false,
+};
+
+let tmpDir = '';
+let projectDir = '';
+let contentDir = '';
+
+beforeEach(() => {
+ tmpDir = mkdtempSync(join(tmpdir(), 'gh-account-agreement-'));
+ projectDir = join(tmpDir, 'project');
+ contentDir = join(tmpDir, 'content');
+ mkdirSync(join(projectDir, '.ok', LOCAL_DIR), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(tmpDir, { recursive: true, force: true });
+});
+
+async function initGitWithOrigin(originUrl: string): Promise<void> {
+ const git = simpleGit(projectDir);
+ await git.init(['--initial-branch=main']);
+ await git.raw('config', 'user.name', 'Test');
+ await git.raw('config', 'user.email', '[email protected]');
+ writeFileSync(join(projectDir, 'README.md'), 'seed\n', 'utf-8');
+ await git.add('.');
+ await git.commit('seed');
+ await git.addRemote('origin', originUrl);
+}
+
+/**
+ * One gh for the whole scenario: any requested account is honored with its
+ * own token, while a login-less request returns the active account's token,
+ * which `detectGh` leaves unattributed.
+ */
+const scriptedGh = (_host?: string, login?: string): ReturnType<DetectGhFn> =>
+ login
+ ? { available: true, token: `gho_${login}`, resolvedLogin: login }
+ : { available: true, token: 'gho_active' };
+
+function recordDetectGh(): {
+ fn: DetectGhFn;
+ hosts: Array<string | undefined>;
+ logins: Array<string | undefined>;
+} {
+ const hosts: Array<string | undefined> = [];
+ const logins: Array<string | undefined> = [];
+ return {
+ fn: (host?: string, options?: { login?: string }) => {
+ const login = options?.login;
+ hosts.push(host);
+ logins.push(login);
+ return scriptedGh(host, login);
+ },
+ hosts,
+ logins,
+ };
+}
+
+async function waitForPushPermissionResolved(engine: SyncEngine, timeoutMs = 2000): Promise<void> {
+ const deadline = Date.now() + timeoutMs;
+ while (engine.getStatus().pushPermission === undefined) {
+ if (Date.now() > deadline) {
+ throw new Error(`push-permission probe did not resolve within ${timeoutMs}ms`);
+ }
+ await new Promise((r) => setTimeout(r, 5));
+ }
+}
+
+interface AgreementRun {
+ /** The clone path's resolution of the same URL the origin points at. */
+ urlAccount: GitHubAccount;
+ /** What the clone path's forward into gh returned. */
+ cloneResult: ReturnType<DetectGhFn>;
+ /** The options the engine handed the probe, resolved account included. */
+ probeOpts: CheckPushPermissionOptions[];
+ /** Authorization header of every request the probe sent. */
+ probeAuthHeaders: Array<string | null>;
+ pushPermission: ReturnType<SyncEngine['getStatus']>['pushPermission'];
+ handleEnv: GitHandle['env'];
+ ghHosts: Array<string | undefined>;
+ ghLogins: Array<string | undefined>;
+}
+
+/**
+ * Drive all three consumers against one origin URL, one scripted gh, and
+ * one credential-config state: the clone path's URL resolution first
+ * (mirroring the clone-then-sync lifecycle), then a started engine whose
+ * probe runs the real `checkPushPermission` with only the network faked.
+ */
+async function runAgreementScenario(opts: {
+ originUrl: string;
+ credentialUrlMatch: string | null;
+}): Promise<AgreementRun> {
+ await initGitWithOrigin(opts.originUrl);
+ const detect = recordDetectGh();
+ const readUrlMatch: CredentialUrlMatchReader = () => opts.credentialUrlMatch;
+
+ const urlAccount = resolveGitHubAccountFromUrl(opts.originUrl, {
+ _readCredentialUrlMatch: readUrlMatch,
+ });
+ if (urlAccount.host === undefined) {
+ throw new Error('agreement scenarios must use an origin URL that parses as GitHub');
+ }
+ const cloneResult = detect.fn(urlAccount.host, { login: urlAccount.login });
+
+ const probeOpts: CheckPushPermissionOptions[] = [];
+ const probeAuthHeaders: Array<string | null> = [];
+ // A 404 exercises the denied path, making the probe's identity
+ // attribution observable alongside each request's Authorization header.
+ const fetchNotFound: FetchFn = async (_url, init) => {
+ probeAuthHeaders.push(new Headers(init?.headers).get('authorization'));
+ return new Response(JSON.stringify({ message: 'Not Found' }), { status: 404 });
+ };
+
+ const engine = new SyncEngine({
+ projectDir,
+ contentDir,
+ contentFilter: stubContentFilter,
+ syncEnabled: false,
+ detectGh: detect.fn,
+ _readCredentialUrlMatch: readUrlMatch,
+ checkPushPermissionFn: (o) => {
+ probeOpts.push(o);
+ return checkPushPermission({ ...o, _fetchFn: fetchNotFound });
+ },
+ });
+ try {
+ await engine.start();
+ await waitForPushPermissionResolved(engine);
+ const handle = (engine as unknown as { gitHandle: () => GitHandle }).gitHandle();
+ return {
+ urlAccount,
+ cloneResult,
+ probeOpts,
+ probeAuthHeaders,
+ pushPermission: engine.getStatus().pushPermission,
+ handleEnv: handle.env,
+ ghHosts: detect.hosts,
+ ghLogins: detect.logins,
+ };
+ } finally {
+ await engine.destroy();
+ }
+}
+
+describe('declared-account agreement across probe, push, and clone', () => {
+ test('a remote-URL-declared account resolves to one identity in all three consumers', async () => {
+ const run = await runAgreementScenario({
+ originUrl: 'https://[email protected]/acme/kb.git',
+ credentialUrlMatch: null,
+ });
+
+ expect(run.urlAccount).toEqual({ host: 'github.com', login: 'alice', source: 'remote-url' });
+ expect(run.probeOpts).toHaveLength(1);
+ expect(run.probeOpts[0]?.account).toMatchObject({ login: 'alice', source: 'remote-url' });
+
+ // Every gh invocation — the clone forward, the engine's handles, the
+ // probe — asked for alice on the origin's host; none resolved on its own.
+ expect(run.ghLogins.length).toBeGreaterThanOrEqual(3);
+ expect(run.ghLogins.every((l) => l === 'alice')).toBe(true);
+ expect(run.ghHosts.every((h) => h === 'github.com')).toBe(true);
+
+ expect(run.cloneResult).toMatchObject({ token: 'gho_alice', resolvedLogin: 'alice' });
+ expect(run.probeAuthHeaders).toEqual(['Bearer gho_alice']);
+ expect(run.pushPermission).toEqual({
+ checkStatus: 'denied',
+ deniedReason: 'private-no-access',
+ resolvedLogin: 'alice',
+ });
+ expect(run.handleEnv.OK_GH_TOKEN).toBe('gho_alice');
+ expect(run.handleEnv.OK_GH_TOKEN_LOGIN).toBe('alice');
+ });
+
+ test('a credential-config-declared account resolves to one identity in all three consumers', async () => {
+ const run = await runAgreementScenario({
+ originUrl: 'https://github.com/acme/kb.git',
+ credentialUrlMatch: 'credential.helper osxkeychain\ncredential.username workbot\n',
+ });
+
+ expect(run.urlAccount).toEqual({
+ host: 'github.com',
+ login: 'workbot',
+ source: 'credential-config',
+ });
+ expect(run.probeOpts[0]?.account).toMatchObject({
+ login: 'workbot',
+ source: 'credential-config',
+ });
+
+ expect(run.ghLogins.length).toBeGreaterThanOrEqual(3);
+ expect(run.ghLogins.every((l) => l === 'workbot')).toBe(true);
+ expect(run.ghHosts.every((h) => h === 'github.com')).toBe(true);
+
+ expect(run.cloneResult).toMatchObject({ token: 'gho_workbot', resolvedLogin: 'workbot' });
+ expect(run.probeAuthHeaders).toEqual(['Bearer gho_workbot']);
+ expect(run.pushPermission).toEqual({
+ checkStatus: 'denied',
+ deniedReason: 'private-no-access',
+ resolvedLogin: 'workbot',
+ });
+ expect(run.handleEnv.OK_GH_TOKEN).toBe('gho_workbot');
+ expect(run.handleEnv.OK_GH_TOKEN_LOGIN).toBe('workbot');
+ });
+
+ test('with no declared account, all three consumers agree on the active gh account', async () => {
+ const run = await runAgreementScenario({
+ originUrl: 'https://github.com/inkeep/kb.git',
+ credentialUrlMatch: null,
+ });
+
+ expect(run.urlAccount).toEqual({ host: 'github.com', source: 'active' });
+ expect(run.urlAccount.login).toBeUndefined();
+ expect(run.probeOpts[0]?.account).toMatchObject({ source: 'active' });
+ expect(run.probeOpts[0]?.account?.login).toBeUndefined();
+
+ // No consumer passes a login: the repo owner is never an account
+ // selector, and gh answers as whichever account is active.
+ expect(run.ghLogins.length).toBeGreaterThanOrEqual(3);
+ expect(run.ghLogins.every((l) => l === undefined)).toBe(true);
+
+ expect(run.cloneResult.token).toBe('gho_active');
+ expect(run.cloneResult.resolvedLogin).toBeUndefined();
+ expect(run.probeAuthHeaders).toEqual(['Bearer gho_active']);
+ expect(run.pushPermission).toEqual({
+ checkStatus: 'denied',
+ deniedReason: 'private-no-access',
+ });
+ expect(run.handleEnv.OK_GH_TOKEN).toBe('gho_active');
+ expect('OK_GH_TOKEN_LOGIN' in run.handleEnv).toBe(false);
+ });
+});
diff --git a/packages/server/src/github-permissions.test.ts b/packages/server/src/github-permissions.test.ts
index b3dd05d91..882890aeb 100644
--- a/packages/server/src/github-permissions.test.ts
+++ b/packages/server/src/github-permissions.test.ts
@@ -398,6 +398,228 @@ describe('checkPushPermission — token resolution', () => {
});
});
+// ─── Declared-account identity ────────────────────────────────────────────────
+
+/** Recording gh fake: captures each (host, login) request, replays `result`. */
+function ghRecording(result: ReturnType<DetectGhFn>): {
+ fn: DetectGhFn;
+ calls: Array<{ host?: string; login?: string }>;
+} {
+ const calls: Array<{ host?: string; login?: string }> = [];
+ const fn: DetectGhFn = (host, options) => {
+ const login = options?.login;
+ calls.push({ host, login });
+ return result;
+ };
+ return { fn, calls };
+}
+
+describe('checkPushPermission — declared-account identity', () => {
+ test('requests the declared login from gh and names it on a denial', async () => {
+ const { fetch } = mockFetch(() => jsonResponse(404));
+ const gh = ghRecording({
+ available: true,
+ token: 'ghs_alice_token',
+ resolvedLogin: 'alice',
+ fallback: false,
+ });
+ const result = await checkPushPermission({
+ owner: 'o',
+ repo: 'r',
+ account: { login: 'alice', source: 'remote-url' },
+ detectGh: gh.fn,
+ _fetchFn: fetch,
+ });
+ expect(gh.calls).toEqual([{ host: 'github.com', login: 'alice' }]);
+ // Honored declaration: the denial names alice and carries no declared-miss
+ // fields — the account was used; the denial is real.
+ expect(result).toEqual({
+ kind: 'denied',
+ reason: 'private-no-access',
+ resolvedLogin: 'alice',
+ });
+ });
+
+ test('a declared-account fallback names the account actually used, never the declared one', async () => {
+ const { fetch } = mockFetch(() => jsonResponse(404));
+ // gh could not serve alice: the active account answered (no resolvedLogin).
+ const gh = ghRecording({ available: true, token: 'ghs_bob_token', fallback: true });
+ const result = await checkPushPermission({
+ owner: 'o',
+ repo: 'r',
+ account: { login: 'alice', source: 'remote-url' },
+ detectGh: gh.fn,
+ detectGhAccounts: () => [
+ { login: 'alice-work', active: false },
+ { login: 'bob', active: true },
+ ],
+ _fetchFn: fetch,
+ });
+ expect(result).toEqual({
+ kind: 'denied',
+ reason: 'private-no-access',
+ resolvedLogin: 'bob',
+ declaredLogin: 'alice',
+ declaredSource: 'remote-url',
+ });
+ });
+
+ test('identity reporting degrades to an unnamed denial when gh cannot list accounts', async () => {
+ const { fetch } = mockFetch(() => jsonResponse(404));
+ const gh = ghRecording({ available: true, token: 'ghs_bob_token', fallback: true });
+ const result = await checkPushPermission({
+ owner: 'o',
+ repo: 'r',
+ account: { login: 'alice', source: 'credential-config' },
+ detectGh: gh.fn,
+ detectGhAccounts: () => undefined,
+ _fetchFn: fetch,
+ });
+ expect(result).toEqual({
+ kind: 'denied',
+ reason: 'private-no-access',
+ declaredLogin: 'alice',
+ declaredSource: 'credential-config',
+ });
+ expect(result).not.toHaveProperty('resolvedLogin');
+ });
+
+ test('a throwing accounts listing costs the denial its name, not its classification', async () => {
+ const { fetch } = mockFetch(() => jsonResponse(404));
+ const gh = ghRecording({ available: true, token: 'ghs_bob_token', fallback: true });
+ const result = await checkPushPermission({
+ owner: 'o',
+ repo: 'r',
+ account: { login: 'alice', source: 'remote-url' },
+ detectGh: gh.fn,
+ detectGhAccounts: () => {
+ throw new Error('gh exploded');
+ },
+ _fetchFn: fetch,
+ });
+ // Still the real classification — not unknown/network — with the
+ // declared miss intact and only the name missing.
+ expect(result).toEqual({
+ kind: 'denied',
+ reason: 'private-no-access',
+ declaredLogin: 'alice',
+ declaredSource: 'remote-url',
+ });
+ });
+
+ test('with no declared account, a denial names the active gh account', async () => {
+ const { fetch } = mockFetch(() => jsonResponse(200, { permissions: { push: false } }));
+ const gh = ghRecording({ available: true, token: 'ghs_active_token' });
+ const result = await checkPushPermission({
+ owner: 'o',
+ repo: 'r',
+ account: { source: 'active' },
+ detectGh: gh.fn,
+ detectGhAccounts: () => [{ login: 'carol', active: true }],
+ _fetchFn: fetch,
+ });
+ expect(gh.calls).toEqual([{ host: 'github.com', login: undefined }]);
+ expect(result).toEqual({
+ kind: 'denied',
+ reason: 'no-collaborator',
+ resolvedLogin: 'carol',
+ });
+ });
+
+ test('a stored token is named by its own entry login, never a gh account', async () => {
+ const { fetch } = mockFetch(() => jsonResponse(404));
+ const store: ProbeTokenStore = {
+ get: async () => ({ token: 'gho_stored', login: 'dana' }),
+ };
+ const result = await checkPushPermission({
+ owner: 'o',
+ repo: 'r',
+ detectGh: ghUnavailable(),
+ // Would name 'eve' if the stored tier ever borrowed the gh listing.
+ detectGhAccounts: () => [{ login: 'eve', active: true }],
+ tokenStore: store,
+ _fetchFn: fetch,
+ });
+ expect(result).toEqual({
+ kind: 'denied',
+ reason: 'private-no-access',
+ resolvedLogin: 'dana',
+ });
+ });
+
+ test("a stored entry's 'unknown' login sentinel leaves the denial unnamed", async () => {
+ const { fetch } = mockFetch(() => jsonResponse(404));
+ const store: ProbeTokenStore = {
+ get: async () => ({ token: 'gho_stored', login: 'unknown' }),
+ };
+ const result = await checkPushPermission({
+ owner: 'o',
+ repo: 'r',
+ detectGh: ghUnavailable(),
+ detectGhAccounts: () => [{ login: 'eve', active: true }],
+ tokenStore: store,
+ _fetchFn: fetch,
+ });
+ expect(result).toEqual({ kind: 'denied', reason: 'private-no-access' });
+ expect(result).not.toHaveProperty('resolvedLogin');
+ });
+
+ test('an allowed probe carries no identity fields even after a fallback', async () => {
+ const { fetch } = mockFetch(() => jsonResponse(200, { permissions: { push: true } }));
+ const gh = ghRecording({ available: true, token: 'ghs_bob_token', fallback: true });
+ const result = await checkPushPermission({
+ owner: 'o',
+ repo: 'r',
+ account: { login: 'alice', source: 'remote-url' },
+ detectGh: gh.fn,
+ detectGhAccounts: () => [{ login: 'bob', active: true }],
+ _fetchFn: fetch,
+ });
+ // The pino fallback warning is the sole trace of a push that would
+ // succeed as the wrong identity — the result stays bare.
+ expect(result).toEqual({ kind: 'allowed' });
+ });
+
+ test('signed out entirely with a declared account: the denial carries the declared miss', async () => {
+ const { fetch, calls } = mockFetch(() => jsonResponse(200, {}));
+ const result = await checkPushPermission({
+ owner: 'o',
+ repo: 'r',
+ account: { login: 'alice', source: 'remote-url' },
+ detectGh: ghUnavailable(),
+ _fetchFn: fetch,
+ });
+ expect(result).toEqual({
+ kind: 'denied',
+ reason: 'not-authenticated',
+ declaredLogin: 'alice',
+ declaredSource: 'remote-url',
+ });
+ expect(result).not.toHaveProperty('resolvedLogin');
+ expect(calls).toHaveLength(0);
+ });
+
+ // GitHub logins are case-insensitive, and hand-written remote URLs carry
+ // whatever casing the user typed — a casing-only difference is the same
+ // account, and claiming it missed would point a correctly-configured user
+ // at a non-problem.
+ test('a casing-only difference between declared and resolved is not a miss', async () => {
+ const { fetch } = mockFetch(() => jsonResponse(200, { permissions: { push: false } }));
+ const gh = ghRecording({ available: true, token: 'ghs_alice_token', fallback: true });
+ const result = await checkPushPermission({
+ owner: 'o',
+ repo: 'r',
+ account: { login: 'Alice', source: 'remote-url' },
+ detectGh: gh.fn,
+ detectGhAccounts: () => [{ login: 'alice', active: true }],
+ _fetchFn: fetch,
+ });
+ expect(result).toMatchObject({ kind: 'denied', resolvedLogin: 'alice' });
+ expect(result).not.toHaveProperty('declaredLogin');
+ expect(result).not.toHaveProperty('declaredSource');
+ });
+});
+
// ─── Request shape ────────────────────────────────────────────────────────────
describe('checkPushPermission — request shape', () => {
@@ -575,12 +797,14 @@ describe('checkPushPermission — telemetry', () => {
});
});
- test('attributes are bounded — never the repo identifier or URL', async () => {
+ test('attributes are bounded — never the repo identifier, URL, or a login', async () => {
const { fetch } = mockFetch(() => jsonResponse(404));
await checkPushPermission({
owner: 'secret-owner-abc',
repo: 'secret-repo-xyz',
- detectGh: ghAvailable('secret-token-123'),
+ account: { login: 'secret-declared-login', source: 'remote-url' },
+ detectGh: () => ({ available: true, token: 'secret-token-123', fallback: true }),
+ detectGhAccounts: () => [{ login: 'secret-active-login', active: true }],
_fetchFn: fetch,
});
await harness.flush();
@@ -599,6 +823,8 @@ describe('checkPushPermission — telemetry', () => {
expect(serialized).not.toContain('secret-owner-abc');
expect(serialized).not.toContain('secret-repo-xyz');
expect(serialized).not.toContain('secret-token-123');
+ expect(serialized).not.toContain('secret-declared-login');
+ expect(serialized).not.toContain('secret-active-login');
}
});
});
diff --git a/packages/server/src/github-permissions.ts b/packages/server/src/github-permissions.ts
index fd9fc1909..6ae8c30ca 100644
--- a/packages/server/src/github-permissions.ts
+++ b/packages/server/src/github-permissions.ts
@@ -18,7 +18,8 @@
import type { Counter, Histogram } from '@opentelemetry/api';
import { getLogger } from './logger.ts';
-import type { OriginTransport } from './share/git-context.ts';
+import { type OriginTransport, sameGitHubLogin } from './share/git-context.ts';
+import type { GitHubAccountSource } from './share/github-account.ts';
import { getMeter } from './telemetry.ts';
const log = getLogger('github-permissions');
@@ -50,6 +51,13 @@ type PushPermissionUnknownError =
| 'malformed-response'
| 'ssh-unverified';
+/**
+ * Where a user declared an account for a remote: the URL's userinfo or a
+ * `credential.<url>.username` entry. Never `'active'` — an active-account
+ * resolution declares nothing that could go unhonored.
+ */
+type DeclaredAccountSource = Exclude<GitHubAccountSource, 'active'>;
+
/**
* Outcome of a single push-permission probe.
*
@@ -60,20 +68,87 @@ type PushPermissionUnknownError =
*/
export type PushPermission =
| { kind: 'allowed' }
- | { kind: 'denied'; reason: PushPermissionDeniedReason }
+ | {
+ kind: 'denied';
+ reason: PushPermissionDeniedReason;
+ /**
+ * Login whose credential the probe authenticated with — the one the
+ * token resolution landed on after any fallback, so it can differ from
+ * the account the user declared. Absent when no identity is known
+ * (anonymous, an unattributed stored token, gh unable to report its
+ * accounts). Named to match the internal token-resolution chain, and in
+ * opposition to `declaredLogin`: declared is what was asked for,
+ * resolved is what answered.
+ */
+ resolvedLogin?: string;
+ /**
+ * The declared account and the mechanism that declared it, carried only
+ * when that account did NOT produce the credential used. Never copied
+ * into `resolvedLogin` — a message must not claim an identity the
+ * resolution fell back from.
+ */
+ declaredLogin?: string;
+ declaredSource?: DeclaredAccountSource;
+ }
| { kind: 'unknown'; error: PushPermissionUnknownError };
-/** gh-CLI token detector. Structurally compatible with cli's `detectGh`. */
-export type DetectGhFn = (host?: string) => { available: boolean; token?: string };
+/**
+ * gh-CLI token detector. Structurally compatible with cli's `detectGh`, and
+ * declared here rather than imported to keep `packages/server` free of a
+ * dependency on `packages/cli`. The two shapes must be widened together — a
+ * login this side cannot pass is a login the CLI silently never receives.
+ *
+ * `login` requests a specific gh account; when that account has no token the
+ * implementation falls back to the host's active account rather than returning
+ * nothing, so `resolvedLogin` (not the requested login) names whoever produced
+ * `token`, and `fallback` says the request went unhonored.
+ *
+ * A discriminated union mirroring the CLI's `GhDetectResult` arm for arm:
+ * `available: true` implies a token, so a typed injected implementation
+ * cannot claim availability without producing one. Callers still guard
+ * `result.available && result.token` at runtime — this seam accepts
+ * implementations from untyped callers too, and a tokenless "available"
+ * from one must degrade, not relay `undefined` as a credential.
+ */
+export type DetectGhFn = (
+ host?: string,
+ options?: { login?: string },
+) =>
+ | { available: false }
+ | { available: true; token: string; resolvedLogin?: string; fallback?: boolean };
+
+/**
+ * gh-CLI account listing, structurally compatible with cli's
+ * `detectGhAccounts` and injected for the same package-cycle reason as
+ * `DetectGhFn`. Diagnostic only: it names the active account behind a token
+ * `gh auth token` returned anonymously. Any failure degrades to `undefined`;
+ * it must never take the token path down with it.
+ */
+export type DetectGhAccountsFn = (
+ host?: string,
+) => Array<{ login: string; active: boolean }> | undefined;
/**
* Read side of the OK credential store, structurally compatible with cli's
* `TokenStore`. Injected (not imported) for the package-cycle reason above.
+ * `login` names the account the entry was stored for, when the store knows.
*/
export interface ProbeTokenStore {
- get(host: string): Promise<{ token?: string } | null>;
+ get(host: string): Promise<{ token?: string; login?: string } | null>;
}
+/**
+ * Declared-account resolution for the origin being probed — the shape
+ * `resolveGitHubAccountFromUrl` returns, minus the host (the probe's host
+ * arrives from the same origin parse; accepting it twice would let the two
+ * drift). A union mirroring `GitHubAccount`, so "an active resolution names
+ * no login" is a compile error here rather than a prose invariant an
+ * injected caller could quietly break.
+ */
+type ProbeAccount =
+ | { source: 'active'; login?: undefined }
+ | { source: DeclaredAccountSource; login: string };
+
export interface CheckPushPermissionOptions {
owner: string;
repo: string;
@@ -87,8 +162,20 @@ export interface CheckPushPermissionOptions {
* cannot see.
*/
transport?: OriginTransport;
+ /**
+ * The account declared for this origin, from the same resolver the push
+ * path consumes — sharing one resolution is what keeps the probe from
+ * reporting `allowed` as one identity while the push authenticates as
+ * another. Omit for the active-account behavior.
+ */
+ account?: ProbeAccount;
/** Tier A resolver (`gh` CLI). Defaults to "no gh available". */
detectGh?: DetectGhFn;
+ /**
+ * Accounts listing for identity reporting on denials. Omit to leave
+ * denials unnamed — classification is unaffected.
+ */
+ detectGhAccounts?: DetectGhAccountsFn;
/** Tier B/C credential store. Omit to skip stored-token resolution. */
tokenStore?: ProbeTokenStore | null;
/** Injectable for tests; defaults to the global `fetch`. */
@@ -192,18 +279,60 @@ async function classify(resp: Response, hadToken: boolean): Promise<PushPermissi
* the source for diagnostics without leaking the token itself. `'gh'` /
* `'token-store'` / `'anonymous'` are the only three values; everything else
* is a contract violation.
+ *
+ * A declared account is requested from gh; `resolvedLogin` names whoever
+ * actually produced the token (the store entry's own login on the stored
+ * tier) and is absent when no source can attribute it.
*/
async function resolveProbeTokenWithSource(
host: string,
+ account: ProbeAccount | undefined,
detectGh: DetectGhFn,
tokenStore: ProbeTokenStore | null | undefined,
-): Promise<{ token: string | undefined; source: 'gh' | 'token-store' | 'anonymous' }> {
- const gh = detectGh(host);
- if (gh.available && gh.token) return { token: gh.token, source: 'gh' };
+ detectGhAccounts: DetectGhAccountsFn | undefined,
+): Promise<{
+ token: string | undefined;
+ source: 'gh' | 'token-store' | 'anonymous';
+ resolvedLogin?: string;
+}> {
+ const gh = detectGh(host, { login: account?.login });
+ if (gh.available && gh.token) {
+ if (account?.login !== undefined && gh.fallback === true) {
+ // Name the account that actually answered before deciding this was a
+ // miss — the same ordering `withDeniedIdentity` uses. A fallback result
+ // carries no `resolvedLogin`, so warning off `fallback` alone would fire
+ // on the casing-only case too, where the active account IS the declared
+ // one (GitHub logins are case-insensitive) and there is nothing to fix.
+ const activeLogin = activeAccountLogin(detectGhAccounts, host);
+ if (!sameGitHubLogin(activeLogin, account.login)) {
+ // The only trace when a fallback probe then reports `allowed`. Logins
+ // are unbounded-cardinality: pino fields only, never OTel attributes.
+ // `declaredSource` (not a bare `source`): the adjacent probe log lines
+ // carry `tokenSource`, and a consumer filtering on `source` must not
+ // confuse the declaration mechanism with the credential tier.
+ log.warn(
+ {
+ host,
+ declaredLogin: account.login,
+ declaredSource: account.source,
+ resolvedLogin: activeLogin,
+ },
+ '[permissions] declared GitHub account did not produce the gh token — probing as the active account',
+ );
+ }
+ }
+ return { token: gh.token, source: 'gh', resolvedLogin: gh.resolvedLogin };
+ }
if (tokenStore) {
try {
const entry = await tokenStore.get(host);
- if (entry?.token) return { token: entry.token, source: 'token-store' };
+ if (entry?.token) {
+ // 'unknown' is the store's placeholder for entries saved without a
+ // login (cli's `resolveClonePrincipal` filters it the same way) —
+ // a sentinel, not a name to surface.
+ const login = entry.login !== 'unknown' ? entry.login : undefined;
+ return { token: entry.token, source: 'token-store', resolvedLogin: login };
+ }
} catch (err) {
// tokenStore.get() shouldn't normally throw — lazy wrapper
// catches keyring init failures and falls back to FileBackend — but
@@ -217,23 +346,89 @@ async function resolveProbeTokenWithSource(
return { token: undefined, source: 'anonymous' };
}
+/**
+ * Name the identity behind a denial. `resolvedLogin` is whoever actually
+ * produced the credential: the account the gh resolution reported, else —
+ * for a gh token returned anonymously — the host's active account. A stored
+ * token carries its own entry login or nothing; it is never attributed to a
+ * gh account it did not come from.
+ */
+function withDeniedIdentity(
+ denied: Extract<PushPermission, { kind: 'denied' }>,
+ opts: {
+ account: ProbeAccount | undefined;
+ tokenSource: 'gh' | 'token-store' | 'anonymous';
+ resolvedLogin: string | undefined;
+ detectGhAccounts: DetectGhAccountsFn | undefined;
+ host: string;
+ },
+): Extract<PushPermission, { kind: 'denied' }> {
+ const resolvedLogin =
+ opts.resolvedLogin ??
+ (opts.tokenSource === 'gh' ? activeAccountLogin(opts.detectGhAccounts, opts.host) : undefined);
+ return {
+ ...denied,
+ ...(resolvedLogin !== undefined ? { resolvedLogin } : {}),
+ ...declaredMissFields(opts.account, resolvedLogin),
+ };
+}
+
+/**
+ * The declared account, carried only when it did not produce the credential
+ * used — the failure-path fact the user can act on. A denial that
+ * authenticated as the declared account carries nothing extra: the account
+ * was honored and the denial is real.
+ */
+function declaredMissFields(
+ account: ProbeAccount | undefined,
+ resolvedLogin: string | undefined,
+): Pick<Extract<PushPermission, { kind: 'denied' }>, 'declaredLogin' | 'declaredSource'> {
+ if (account?.login === undefined) return {};
+ // GitHub logins are case-insensitive and unique case-insensitively, so a
+ // casing difference between the declared account and the one that answered
+ // is the same person — reporting it as a miss would be false.
+ if (sameGitHubLogin(account.login, resolvedLogin)) return {};
+ return { declaredLogin: account.login, declaredSource: account.source };
+}
+
+/**
+ * Active-account lookup is diagnostic only: a listing that fails or throws
+ * (an injected implementation crossing the package seam, gh itself absent)
+ * must cost the denial its name, never its classification — an uncaught
+ * throw here would surface as a bogus network error instead.
+ */
+function activeAccountLogin(
+ detectGhAccounts: DetectGhAccountsFn | undefined,
+ host: string,
+): string | undefined {
+ if (!detectGhAccounts) return undefined;
+ try {
+ return detectGhAccounts(host)?.find((a) => a.active)?.login;
+ } catch (err) {
+ log.warn({ err, host }, '[permissions] detectGhAccounts failed — denial stays unnamed');
+ return undefined;
+ }
+}
+
async function runProbe(opts: CheckPushPermissionOptions): Promise<PushPermission> {
const {
owner,
repo,
host = 'github.com',
transport = 'https',
+ account,
detectGh = () => ({ available: false }),
+ detectGhAccounts,
tokenStore,
_fetchFn = fetch,
_timeoutMs = PROBE_TIMEOUT_MS,
} = opts;
- const { token, source: tokenSource } = await resolveProbeTokenWithSource(
- host,
- detectGh,
- tokenStore,
- );
+ const {
+ token,
+ source: tokenSource,
+ resolvedLogin,
+ } = await resolveProbeTokenWithSource(host, account, detectGh, tokenStore, detectGhAccounts);
// No credential resolved. What that MEANS depends on the origin transport:
//
@@ -262,7 +457,11 @@ async function runProbe(opts: CheckPushPermissionOptions): Promise<PushPermissio
log.info({ host }, '[permissions] no credential resolved — denying push (read-only)');
// 'not-authenticated' (not 'no-collaborator'): reconnecting resolves this,
// so the UI can offer a sign-in affordance rather than a dead-end.
- return { kind: 'denied', reason: 'not-authenticated' };
+ return {
+ kind: 'denied',
+ reason: 'not-authenticated',
+ ...declaredMissFields(account, undefined),
+ };
}
const url = `${githubApiBase(host)}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`;
@@ -282,7 +481,17 @@ async function runProbe(opts: CheckPushPermissionOptions): Promise<PushPermissio
const timer = setTimeout(() => ac.abort(), _timeoutMs);
try {
const resp = await _fetchFn(url, { signal: ac.signal, headers: buildHeaders(token) });
- const result = await classify(resp, token !== undefined);
+ const classified = await classify(resp, token !== undefined);
+ const result =
+ classified.kind === 'denied'
+ ? withDeniedIdentity(classified, {
+ account,
+ tokenSource,
+ resolvedLogin,
+ detectGhAccounts,
+ host,
+ })
+ : classified;
log.info(
{
host,
diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts
index d579ca5f0..f8943a3e9 100644
--- a/packages/server/src/index.ts
+++ b/packages/server/src/index.ts
@@ -526,7 +526,17 @@ export {
hasGcLogLatch,
type ShadowObjectStats,
} from './shadow-repo-stats.ts';
-export { originGitHubHost } from './share/git-context.ts';
+export {
+ loginShapedUserinfoUser,
+ originGitHubHost,
+ sameGitHubLogin,
+} from './share/git-context.ts';
+export {
+ type CredentialUrlMatchReader,
+ type GitHubAccountSource,
+ resolveGitHubAccountFromUrl,
+} from './share/github-account.ts';
+export { redactShareSubprocessStderr } from './share/publish.ts';
export {
createEphemeralProjectDir,
EPHEMERAL_PROJECT_DIR_PREFIX,
diff --git a/packages/server/src/local-ops/clone-error-classify.ts b/packages/server/src/local-ops/clone-error-classify.ts
index d9ee0f52f..48b1300e0 100644
--- a/packages/server/src/local-ops/clone-error-classify.ts
+++ b/packages/server/src/local-ops/clone-error-classify.ts
@@ -15,14 +15,16 @@
* before either surface sees the stderr (reusing the share-publish
* redactor — same threat model, same regex shape).
*
- * Threat-model inheritance: `redactShareSubprocessStderr` only matches
- * `https?://user:pwd@host` shapes (the form the inline-token push URL
- * uses). Any future clone path that could surface other credential
- * shapes in stderr — bearer tokens, OAuth params, `http.extraHeader`
- * config quoted back — needs the redactor broadened (in
- * `share/publish.ts`) or a clone-specific redactor here. Today's clone
- * flow runs simple-git's `git.clone()` with a plain HTTPS URL and no
- * extra-header config, so the inherited model is sufficient.
+ * Threat-model inheritance: `redactShareSubprocessStderr` covers every
+ * credential-in-URL-userinfo shape — `user:pwd@`, the token-as-username
+ * form GitHub documents (`https://<pat>@host`), and raw-`@` passwords —
+ * so don't add a second clone-local URL redactor. Still open by design:
+ * credential shapes OUTSIDE a URL userinfo (bearer tokens, OAuth params,
+ * `http.extraHeader` config quoted back into stderr) — a future clone
+ * path that could surface those needs the redactor in `share/publish.ts`
+ * broadened. Today's clone flow runs simple-git's `git.clone()` with a
+ * plain HTTPS URL and no extra-header config, so the inherited model is
+ * sufficient.
*/
import { redactShareSubprocessStderr } from '../share/publish.ts';
@@ -50,7 +52,7 @@ const GENERIC_TITLE = 'Clone subprocess reported an error.';
* and bounded-cardinality discipline applies to anything that lands on
* Pino structured logs as well.
*/
-const MAX_DETAIL_LEN = 500;
+export const MAX_DETAIL_LEN = 500;
/**
* Classify a single clone stderr string into envelope shape.
@@ -61,6 +63,12 @@ const MAX_DETAIL_LEN = 500;
* full line. Order matters: "Authentication failed" can co-occur with
* "Repository not found" on some auth-shaped 404s; checking auth first
* would mis-label.
+ *
+ * No identity is named in the 404 title: the login that produced the failed
+ * clone's credential lives in the CLI subprocess, and its `--json` error
+ * event does not carry it across the process boundary — naming an identity
+ * here would require widening that wire. Until then the copy asserts both
+ * 404 possibilities and no account.
*/
export function classifyCloneError(rawStderr: string): CloneErrorClassification {
const detail = redactShareSubprocessStderr(rawStderr).trim().slice(0, MAX_DETAIL_LEN);
diff --git a/packages/server/src/local-ops/clone-flow.test.ts b/packages/server/src/local-ops/clone-flow.test.ts
index 9ab88b5ce..e6e4ff8cd 100644
--- a/packages/server/src/local-ops/clone-flow.test.ts
+++ b/packages/server/src/local-ops/clone-flow.test.ts
@@ -56,6 +56,80 @@ describe('runCloneSubprocess', () => {
}
});
+ // This event is forwarded verbatim to the renderer (clone toast +
+ // share-receive error panel). With prompts disabled git echoes the URL's
+ // username half, which is where a bare PAT lives.
+ test('redacts a credential out of the stderr detail before it reaches the event', async () => {
+ const events: RawCloneEvent[] = [];
+ const token = `ghp_${'a'.repeat(36)}`;
+ const ctrl = runCloneSubprocess({
+ cliArgs: fixtureCli(`
+ process.stderr.write("fatal: could not read Password for 'https://${token}@github.com': terminal prompts disabled\\n");
+ process.exit(128);
+ `),
+ url: 'https://github.com/octocat/private.git',
+ dir: '/tmp/private',
+ onEvent: (e) => events.push(e),
+ });
+ await ctrl.done;
+ expect(events).toHaveLength(1);
+ // Asserted OUTSIDE the narrowing guard: `toHaveLength` does not constrain
+ // the type, so without this a terminal-event change would skip every
+ // assertion below and report green.
+ expect(events[0].type).toBe('error');
+ if (events[0].type === 'error') {
+ expect(events[0].message).not.toContain(token);
+ expect(events[0].message).not.toContain('ghp_');
+ // Redacted, not merely absent — the diagnostic still names the host.
+ expect(events[0].message).toContain('***@github.com');
+ expect(events[0].message).toContain('exited with code 128');
+ }
+ });
+
+ // A git crash dump or multi-page submodule error would otherwise be
+ // interpolated whole into a toast and a persistent error panel, pushing the
+ // load-bearing first line out of view.
+ test('caps a very long stderr detail so the toast stays readable', async () => {
+ const events: RawCloneEvent[] = [];
+ const ctrl = runCloneSubprocess({
+ cliArgs: fixtureCli(`
+ process.stderr.write('x'.repeat(3000) + '\\n');
+ process.exit(128);
+ `),
+ url: 'https://github.com/octocat/huge.git',
+ dir: '/tmp/huge',
+ onEvent: (e) => events.push(e),
+ });
+ await ctrl.done;
+ expect(events).toHaveLength(1);
+ expect(events[0].type).toBe('error');
+ if (events[0].type === 'error') {
+ expect(events[0].message).toContain('exited with code 128');
+ expect(events[0].message.length).toBeLessThan(600);
+ }
+ });
+
+ // Whitespace-only stderr must not leave a dangling separator with nothing
+ // after it — emptiness is decided on the redacted value.
+ test('whitespace-only stderr produces no dangling detail separator', async () => {
+ const events: RawCloneEvent[] = [];
+ const ctrl = runCloneSubprocess({
+ cliArgs: fixtureCli(`
+ process.stderr.write(' \\n');
+ process.exit(128);
+ `),
+ url: 'https://github.com/octocat/blank.git',
+ dir: '/tmp/blank',
+ onEvent: (e) => events.push(e),
+ });
+ await ctrl.done;
+ expect(events[0].type).toBe('error');
+ if (events[0].type === 'error') {
+ expect(events[0].message).toBe('Clone process exited with code 128');
+ expect(events[0].message).not.toContain('—');
+ }
+ });
+
test('emits "Clone timed out" error on timeout', async () => {
const events: RawCloneEvent[] = [];
const ctrl = runCloneSubprocess({
diff --git a/packages/server/src/local-ops/clone-flow.ts b/packages/server/src/local-ops/clone-flow.ts
index a54bf4fe0..85a429d61 100644
--- a/packages/server/src/local-ops/clone-flow.ts
+++ b/packages/server/src/local-ops/clone-flow.ts
@@ -27,6 +27,8 @@ import {
import { emitPreflightFailureSpan } from '../git-preflight-telemetry.ts';
import { expandTilde, isAllowedGitUrl, isSafeLocalPath } from '../local-op-security.ts';
import { getLogger } from '../logger.ts';
+import { redactShareSubprocessStderr } from '../share/publish.ts';
+import { MAX_DETAIL_LEN } from './clone-error-classify.ts';
import { runSubprocess } from './subprocess.ts';
const log = getLogger('clone-flow');
@@ -200,7 +202,16 @@ export function runCloneSubprocess(opts: RunCloneOptions): RunCloneController {
return;
}
if (result.code !== 0) {
- const detail = result.stderr ? ` — ${result.stderr}` : '';
+ // Redacted AND capped: this event is forwarded verbatim to the renderer,
+ // where it becomes a clone toast and the share-receive error panel — so
+ // a credential must never reach it, and a git crash dump must not push
+ // the load-bearing first line out of view. Emptiness is decided on the
+ // REDACTED value, not the raw one: whitespace-only stderr would
+ // otherwise leave a dangling "… — " with nothing after it.
+ const redacted = redactShareSubprocessStderr(result.stderr ?? '')
+ .trim()
+ .slice(0, MAX_DETAIL_LEN);
+ const detail = redacted.length > 0 ? ` — ${redacted}` : '';
opts.onEvent({
type: 'error',
message: `Clone process exited with code ${result.code ?? -1}${detail}`,
diff --git a/packages/server/src/server-factory.test.ts b/packages/server/src/server-factory.test.ts
index 870166857..b21ea3893 100644
--- a/packages/server/src/server-factory.test.ts
+++ b/packages/server/src/server-factory.test.ts
@@ -27,6 +27,7 @@ import { classifyGitError } from './error-classification.ts';
import { applyExternalChange } from './external-change.ts';
import type {
CheckPushPermissionOptions,
+ DetectGhAccountsFn,
DetectGhFn,
ProbeTokenStore,
PushPermission,
@@ -3609,6 +3610,7 @@ describe('createServer() — push-permission auth wiring', () => {
return { token: `store-token-for-${host}` };
},
};
+ const detectGhAccountsStub: DetectGhAccountsFn = () => [{ login: 'stub', active: true }];
// Capture every probe-call's `opts.detectGh` + `opts.tokenStore`.
const probeCalls: CheckPushPermissionOptions[] = [];
@@ -3624,6 +3626,7 @@ describe('createServer() — push-permission auth wiring', () => {
debounce: 60_000,
destroyTimeoutMs: 1_000,
detectGh: detectGhStub,
+ detectGhAccounts: detectGhAccountsStub,
tokenStore: tokenStoreStub,
checkPushPermissionFn: probeSpy,
});
@@ -3644,6 +3647,7 @@ describe('createServer() — push-permission auth wiring', () => {
// intercepted and replaced them, which would silently break gh-token
// resolution under any future `host` param shape.
expect(firstCall.detectGh).toBe(detectGhStub);
+ expect(firstCall.detectGhAccounts).toBe(detectGhAccountsStub);
expect(firstCall.tokenStore).toBe(tokenStoreStub);
// The probe call shape must also carry owner/repo parsed from origin.
expect(firstCall.owner).toBe('inkeep');
diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.ts
index de0fedb2e..d75b21797 100644
--- a/packages/server/src/server-factory.ts
+++ b/packages/server/src/server-factory.ts
@@ -155,6 +155,7 @@ import { normalizeFsPath, tracedAtomicFs, tracedMkdirSync } from './fs-traced.ts
import { buildSyncCredentialConfig } from './git-handle.ts';
import type {
CheckPushPermissionOptions,
+ DetectGhAccountsFn,
DetectGhFn,
ProbeTokenStore,
PushPermission,
@@ -395,6 +396,12 @@ export interface ServerOptions {
* omitted — leaves the probe to anonymous resolution.
*/
detectGh?: DetectGhFn;
+ /**
+ * gh account listing, wired through `SyncEngine` so probe denials can name
+ * the identity they authenticated as. Same dependency-injection rationale
+ * as `detectGh` above; omitting it only leaves denials unnamed.
+ */
+ detectGhAccounts?: DetectGhAccountsFn;
/**
* Tier B/C OK credential store. Wired through `SyncEngine` to the
* push-permission probe. Same dependency-injection rationale as
@@ -5602,6 +5609,7 @@ export function createServer(options: ServerOptions): ServerInstance {
// (`server-factory.test.ts > production wiring: push-permission auth`)
// pins that `createServer(options)` forwards both seams to SyncEngine.
detectGh: options.detectGh,
+ detectGhAccounts: options.detectGhAccounts,
tokenStore: options.tokenStore,
// Test seam — production callers leave this undefined. Forwarded so the
// wiring test can assert detectGh + tokenStore propagate through without
diff --git a/packages/server/src/share/git-context.test.ts b/packages/server/src/share/git-context.test.ts
index f5c41b685..a6787c8f1 100644
--- a/packages/server/src/share/git-context.test.ts
+++ b/packages/server/src/share/git-context.test.ts
@@ -5,9 +5,11 @@ import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
branchExistsOnOrigin,
originGitHubHost,
+ parseGitHubOriginUrl,
readGitHeadBranch,
readOriginGitHubRepo,
readSyncRemoteInfo,
+ sameGitHubLogin,
shouldResetAmbientCredentials,
} from './git-context.ts';
@@ -124,6 +126,29 @@ describe('readOriginGitHubRepo', () => {
});
});
+ // The origin read deliberately omits the URL-declared login — identity
+ // decisions go through the `github-account.ts` resolvers — so the account
+ // is asserted on the parser and the origin result is pinned login-free.
+ test('the parser surfaces an https userinfo account; the origin read stays login-free', () => {
+ seedRepo(dir, {
+ config: '[remote "origin"]\n\turl = https://[email protected]/inkeep/open-knowledge.git\n',
+ });
+ expect(readOriginGitHubRepo(dir)).toEqual({
+ kind: 'ok',
+ host: 'github.com',
+ owner: 'inkeep',
+ repo: 'open-knowledge',
+ transport: 'https',
+ });
+ expect(parseGitHubOriginUrl('https://[email protected]/inkeep/open-knowledge.git')).toEqual({
+ host: 'github.com',
+ owner: 'inkeep',
+ repo: 'open-knowledge',
+ transport: 'https',
+ login: 'alice',
+ });
+ });
+
test('parses SSH SCP-style github.com origin URL', () => {
seedRepo(dir, {
config: '[remote "origin"]\n\turl = [email protected]:inkeep/open-knowledge.git\n',
@@ -150,6 +175,117 @@ describe('readOriginGitHubRepo', () => {
});
});
+ test('surfaces the account declared in an ssh:// origin userinfo', () => {
+ expect(parseGitHubOriginUrl('ssh://[email protected]/inkeep/open-knowledge.git')).toEqual({
+ host: 'github.com',
+ owner: 'inkeep',
+ repo: 'open-knowledge',
+ transport: 'ssh',
+ login: 'alice',
+ });
+ });
+
+ test('surfaces the account declared in an scp-style origin userinfo', () => {
+ expect(parseGitHubOriginUrl('[email protected]:inkeep/open-knowledge.git')).toEqual({
+ host: 'github.com',
+ owner: 'inkeep',
+ repo: 'open-knowledge',
+ transport: 'ssh',
+ login: 'alice',
+ });
+ });
+
+ // `git@` is the SSH transport's conventional placeholder, not an account, so
+ // reading it as one would send every SSH clone chasing a `git` GitHub user.
+ // `git` is also a reserved name on GitHub, so the same holds on https.
+ test('treats the literal git userinfo as absent on every transport', () => {
+ for (const url of [
+ '[email protected]:inkeep/open-knowledge.git',
+ 'ssh://[email protected]/inkeep/open-knowledge.git',
+ 'https://[email protected]/inkeep/open-knowledge.git',
+ ]) {
+ const parsed = parseGitHubOriginUrl(url);
+ expect(parsed).toMatchObject({ host: 'github.com' });
+ expect(parsed).not.toHaveProperty('login');
+ }
+ });
+
+ test('percent-decodes an encoded login before validating it', () => {
+ expect(
+ parseGitHubOriginUrl('https://alice%[email protected]/inkeep/open-knowledge.git'),
+ ).toMatchObject({ login: 'alice-contoso' });
+ });
+
+ // GCM documents `alice%40contoso.com@host` for forges whose logins are
+ // emails, but no GitHub login can contain `@` or `.` — the decoded form
+ // fails the login grammar and reads as no declaration rather than becoming
+ // a value gh could never serve.
+ test('an email-shaped decoded userinfo is not a GitHub login', () => {
+ const parsed = parseGitHubOriginUrl(
+ 'https://alice%[email protected]/inkeep/open-knowledge.git',
+ );
+ expect(parsed).toMatchObject({ host: 'github.com' });
+ expect(parsed).not.toHaveProperty('login');
+ });
+
+ test('a malformed percent escape fails the login grammar and reads as absent', () => {
+ const parsed = parseGitHubOriginUrl('https://ali%[email protected]/inkeep/open-knowledge.git');
+ expect(parsed).toMatchObject({ host: 'github.com' });
+ expect(parsed).not.toHaveProperty('login');
+ });
+
+ // GitHub's canonical PAT-in-URL form puts the token in the USERNAME half
+ // (`https://ghp_…@github.com/o/r`). Reading it as an account would echo the
+ // credential into `gh auth token --user` argv, warn-log fields, the
+ // sync-status wire, and the sync popover — on every resolution, since the
+ // `--user` lookup can never succeed for it.
+ test('a token-shaped username is never an account', () => {
+ const cases = [
+ `https://ghp_${'a'.repeat(36)}@github.com/inkeep/open-knowledge.git`,
+ `https://gho_${'b'.repeat(36)}@github.com/inkeep/open-knowledge.git`,
+ `https://ghs_${'c'.repeat(36)}@github.com/inkeep/open-knowledge.git`,
+ `https://github_pat_${'d'.repeat(70)}@github.com/inkeep/open-knowledge.git`,
+ ];
+ for (const url of cases) {
+ const parsed = parseGitHubOriginUrl(url);
+ expect(parsed).toMatchObject({ host: 'github.com' });
+ expect(parsed).not.toHaveProperty('login');
+ }
+ });
+
+ // The Actions/App convention (`x-access-token:<token>@`) and its cousins
+ // name the auth scheme, not an account — OK's own publish path mints the
+ // x-access-token form.
+ test('token-auth placeholder usernames are never accounts', () => {
+ for (const user of ['x-access-token', 'x-oauth-basic', 'oauth2', 'token']) {
+ const parsed = parseGitHubOriginUrl(
+ `https://${user}:[email protected]/inkeep/open-knowledge.git`,
+ );
+ expect(parsed).toMatchObject({ host: 'github.com' });
+ expect(parsed).not.toHaveProperty('login');
+ }
+ });
+
+ // Enterprise Managed User logins carry an underscore + enterprise
+ // shortcode; the grammar must admit them or EMU users lose the whole
+ // feature.
+ test('an EMU-style login with an underscore is a valid account', () => {
+ expect(
+ parseGitHubOriginUrl('https://[email protected]/inkeep/open-knowledge.git'),
+ ).toMatchObject({ login: 'mona_acme' });
+ });
+
+ // 39 chars is GitHub's login ceiling; every current token format is ≥40
+ // chars, so length alone keeps arbitrary secrets out even when they avoid
+ // the known prefixes.
+ test('a 40-char opaque string is rejected by the login length cap', () => {
+ const parsed = parseGitHubOriginUrl(
+ `https://${'s'.repeat(40)}@github.com/inkeep/open-knowledge.git`,
+ );
+ expect(parsed).toMatchObject({ host: 'github.com' });
+ expect(parsed).not.toHaveProperty('login');
+ });
+
test('returns ok when repo URL omits the .git suffix', () => {
seedRepo(dir, {
config: '[remote "origin"]\n\turl = https://github.com/inkeep/open-knowledge\n',
@@ -281,15 +417,28 @@ describe('readOriginGitHubRepo', () => {
expect(readOriginGitHubRepo(dir)).toEqual({ kind: 'non-github' });
});
- test('credential-embedded https URLs classify as non-github (documented limitation)', () => {
- // The https form deliberately excludes userinfo, matching the cli's
- // `parseGitUrl` grammar — a `user:pass@host` origin falls through to
- // `non-github` (and downstream host defaults fall back to github.com),
- // the same treatment such URLs received for github.com itself.
- seedRepo(dir, {
- config: '[remote "origin"]\n\turl = https://user:[email protected]/org/repo.git\n',
+ test('credential-embedded https URL keeps the username as the login and drops the password', () => {
+ const url = 'https://user:[email protected]/org/repo.git';
+ const parsed = parseGitHubOriginUrl(url);
+ expect(parsed).toEqual({
+ host: 'ghes.corp.example',
+ owner: 'org',
+ repo: 'repo',
+ transport: 'https',
+ login: 'user',
+ });
+ // The password must not survive the parse in any field — it would reach
+ // logs and UI labels from here.
+ expect(JSON.stringify(parsed)).not.toContain('pass');
+ // The origin read of the same URL stays login-free.
+ seedRepo(dir, { config: `[remote "origin"]\n\turl = ${url}\n` });
+ expect(readOriginGitHubRepo(dir)).toEqual({
+ kind: 'ok',
+ host: 'ghes.corp.example',
+ owner: 'org',
+ repo: 'repo',
+ transport: 'https',
});
- expect(readOriginGitHubRepo(dir)).toEqual({ kind: 'non-github' });
});
test('uses the first url= line and ignores subsequent ones', () => {
@@ -411,6 +560,17 @@ describe('shouldResetAmbientCredentials', () => {
expect(shouldResetAmbientCredentials(dir)).toBe(false);
});
+ // A userinfo origin used to fall out of the parser as `non-github` and so
+ // kept its inherited chain. That was an accident of the grammar, not a
+ // policy: the host is still GitHub and OK can still issue a credential for
+ // it, which is the only question this gate asks.
+ test('https origin with userinfo resets — the host is what decides', () => {
+ seedRepo(dir, {
+ config: '[remote "origin"]\n\turl = https://[email protected]/inkeep/open-knowledge.git\n',
+ });
+ expect(shouldResetAmbientCredentials(dir)).toBe(true);
+ });
+
test('no remote resets — nothing ambient to preserve, sync is dormant anyway', () => {
expect(shouldResetAmbientCredentials(dir)).toBe(true);
});
@@ -515,6 +675,19 @@ describe('readSyncRemoteInfo', () => {
});
});
+ // Credential-bearing URLs reach the GitHub branch now that the parser
+ // accepts userinfo, so the browse URL is rebuilt from the normalized host —
+ // a passthrough would publish the password into a clickable link.
+ test('GitHub-host origin with embedded credentials builds a webUrl carrying neither', () => {
+ seedRepo(dir, {
+ config: '[remote "origin"]\n\turl = https://user:[email protected]/org/repo.git\n',
+ });
+ expect(readSyncRemoteInfo(dir)).toEqual({
+ label: 'ghes.corp.example/org/repo',
+ webUrl: 'https://ghes.corp.example/org/repo',
+ });
+ });
+
test('known non-github forge yields a readable label and a null webUrl (no link)', () => {
seedRepo(dir, {
config: '[remote "origin"]\n\turl = https://gitlab.com/team/notes.git\n',
@@ -608,3 +781,26 @@ describe('linked-worktree common-dir resolution', () => {
expect(readGitHeadBranch(project)).toBe('feat-bar');
});
});
+
+describe('sameGitHubLogin', () => {
+ // GitHub logins are unique case-insensitively, so a casing difference is the
+ // same person — treating it as a mismatch would report a declared-account
+ // miss for a correctly-configured remote.
+ test('a casing difference is the same account', () => {
+ expect(sameGitHubLogin('Alice', 'alice')).toBe(true);
+ expect(sameGitHubLogin('alice', 'ALICE')).toBe(true);
+ expect(sameGitHubLogin('alice', 'alice')).toBe(true);
+ });
+
+ test('different accounts are not the same', () => {
+ expect(sameGitHubLogin('alice', 'bob')).toBe(false);
+ });
+
+ // An unattributed credential is never "the same account" as a named one —
+ // the absent side must not read as a match and suppress a real miss.
+ test('an absent side is never a match', () => {
+ expect(sameGitHubLogin('alice', undefined)).toBe(false);
+ expect(sameGitHubLogin(undefined, 'alice')).toBe(false);
+ expect(sameGitHubLogin(undefined, undefined)).toBe(false);
+ });
+});
diff --git a/packages/server/src/share/git-context.ts b/packages/server/src/share/git-context.ts
index c72de3ce7..07abd9a34 100644
--- a/packages/server/src/share/git-context.ts
+++ b/packages/server/src/share/git-context.ts
@@ -44,7 +44,13 @@ export type OriginTransport = 'https' | 'ssh' | 'git';
/** Outcome of `readOriginGitHubRepo`. */
export type OriginResult =
- | { kind: 'ok'; host: string; owner: string; repo: string; transport: OriginTransport }
+ | {
+ kind: 'ok';
+ host: string;
+ owner: string;
+ repo: string;
+ transport: OriginTransport;
+ }
| { kind: 'no-remote' }
| { kind: 'non-github' };
@@ -63,11 +69,19 @@ export function readGitHeadBranch(projectDir: string): string | null {
}
/** Parsed origin repo: normalized host + owner/repo path segments. */
-interface ParsedOriginRepo {
+export interface ParsedOriginRepo {
host: string;
owner: string;
repo: string;
transport: OriginTransport;
+ /**
+ * Account declared in the URL's userinfo, absent when the URL declares
+ * none. URL-declared ONLY — identity decisions must go through the
+ * `github-account.ts` resolvers, which also consult
+ * `credential.<url>.username`; reading this field directly yields an
+ * account that can disagree with what the push path authenticates as.
+ */
+ login?: string;
}
/**
@@ -81,14 +95,149 @@ function normalizeGitHost(rawHost: string): string {
return host === 'www.github.com' ? 'github.com' : host;
}
+/**
+ * Values that mark a transport or a token-auth convention, never an account —
+ * whether declared as URL userinfo or as a `credential.<url>.username`
+ * entry: `git` is SSH's conventional user (and a reserved name on GitHub,
+ * so it can't be anyone's login on https either), and the rest are the
+ * conventional usernames tooling writes next to an embedded token
+ * (`x-access-token:<token>@`, `oauth2:<token>@`, …) — OK's own publish path
+ * mints the `x-access-token` form. All of them pass the login grammar below,
+ * so they need their own set.
+ */
+const USERINFO_PLACEHOLDER_USERS = new Set([
+ 'git',
+ 'x-access-token',
+ 'x-oauth-basic',
+ 'oauth2',
+ 'token',
+]);
+
+/**
+ * GitHub credential prefixes (classic + fine-grained PATs, OAuth, app
+ * installation, user-to-server, and refresh tokens) — the same family the
+ * diagnostic-bundle scrubber redacts. A userinfo carrying one is a leaked
+ * credential, never an account name. Every current format is also ≥40 chars,
+ * so the login grammar's length cap independently rejects them; this check is
+ * belt-and-braces for any future shorter format.
+ */
+const GITHUB_TOKEN_PREFIX = /^(?:gh[opsur]_|github_pat_)/;
+
+/**
+ * GitHub login grammar: 1–39 chars, alphanumeric with single internal
+ * separators, no leading/trailing separator. Hyphens per github.com signup
+ * rules; underscores appear in Enterprise Managed User logins
+ * (`mona_shortcode`). Anything outside this grammar cannot be a GitHub
+ * account, so treating it as one would put an arbitrary string — possibly a
+ * credential — into subprocess argv, log fields, the sync-status wire, and
+ * UI copy.
+ */
+const GITHUB_LOGIN = /^[A-Za-z0-9](?:[A-Za-z0-9]|[-_](?=[A-Za-z0-9])){0,38}$/;
+
+/**
+ * The shared half of the two userinfo predicates below: not credential-shaped
+ * (no GitHub token prefix) and inside the login grammar. Kept in one place so
+ * the declared-account tier and the redaction tier cannot drift on what a
+ * login looks like; the predicates differ only on the placeholder set and on
+ * who percent-decodes.
+ */
+function isGitHubLoginShaped(value: string): boolean {
+ return !GITHUB_TOKEN_PREFIX.test(value) && GITHUB_LOGIN.test(value);
+}
+
+/**
+ * Whether two values name the same GitHub account. GitHub logins are unique
+ * and comparable case-insensitively (the API canonicalizes casing; users
+ * hand-write remote URLs in whatever casing they remember), so a casing
+ * difference is the same person and must not read as an account mismatch.
+ * False when either side is absent — an unattributed credential is never
+ * "the same account" as a named one. Note this governs COMPARISON only:
+ * `gh auth token --user` itself matches its stored login exactly (a plain
+ * keyring/config-key lookup, verified against gh's config code), so a
+ * casing-mismatched declaration still falls back to the active account.
+ */
+export function sameGitHubLogin(a: string | undefined, b: string | undefined): boolean {
+ return a !== undefined && b !== undefined && a.toLowerCase() === b.toLowerCase();
+}
+
+/**
+ * Reduce a URL's userinfo to the GitHub account it declares.
+ *
+ * Git forwards this half of the URL to credential helpers as `username=`, so
+ * it is the user's own statement of which account owns the remote. The
+ * password half of `user:pass@` is dropped here and never returned — it must
+ * not reach a log line, a UI label, or a browse URL. The username half gets
+ * the same protection when it is itself credential-shaped: GitHub's canonical
+ * PAT-in-URL form is `https://<token>@github.com/o/r`, so anything that fails
+ * the GitHub login grammar (or carries a GitHub token prefix, or is a known
+ * transport placeholder like `git` or `x-access-token`) reads as "no account
+ * declared" rather than becoming a value the resolver would echo into argv,
+ * logs, and the sync popover.
+ */
+function loginFromUserinfo(userinfo: string | undefined): string | undefined {
+ if (!userinfo) return undefined;
+ const colon = userinfo.indexOf(':');
+ const user = colon === -1 ? userinfo : userinfo.slice(0, colon);
+ if (!user) return undefined;
+ return asDeclaredGitHubLogin(decodeUserinfo(user));
+}
+
+/**
+ * Reduce an already-decoded value to the GitHub account it declares, or
+ * undefined when it cannot be one: transport/token-convention placeholders
+ * (`git`, `x-access-token`, …), values carrying a GitHub token prefix, and
+ * anything outside the login grammar all read as "no account declared". One
+ * home for the policy so the URL-userinfo tier and the
+ * `credential.<url>.username` tier cannot drift — an unvalidated value would
+ * otherwise flow into subprocess argv, log fields, the sync-status wire, and
+ * UI copy. Percent-decoding and the `user:pass` split are userinfo grammar
+ * and stay in `loginFromUserinfo`; a git-config value is passed as written.
+ */
+export function asDeclaredGitHubLogin(raw: string | undefined): string | undefined {
+ if (!raw) return undefined;
+ if (USERINFO_PLACEHOLDER_USERS.has(raw)) return undefined;
+ return isGitHubLoginShaped(raw) ? raw : undefined;
+}
+
+/**
+ * The username half of a URL userinfo when it is shaped like a GitHub login,
+ * undefined when it is credential-shaped (a GitHub token prefix, or anything
+ * outside the login grammar). Redaction call sites use this to decide whether
+ * a username may be echoed back: a login-shaped one survives — including
+ * transport placeholders like `git` or `x-access-token`, which are
+ * diagnostically useful and never secrets, so unlike
+ * {@link asDeclaredGitHubLogin} this keeps the placeholder set — while a
+ * token-as-username must be dropped.
+ */
+export function loginShapedUserinfoUser(user: string): string | undefined {
+ if (!user) return undefined;
+ const decoded = decodeUserinfo(user);
+ return isGitHubLoginShaped(decoded) ? decoded : undefined;
+}
+
+/**
+ * Percent-decode a userinfo half; a malformed escape (`%zz` in a hand-edited
+ * `.git/config`) keeps the raw form, which then faces the same login-grammar
+ * validation as any other value.
+ */
+function decodeUserinfo(user: string): string {
+ if (!user.includes('%')) return user;
+ try {
+ return decodeURIComponent(user);
+ } catch {
+ return user;
+ }
+}
+
/**
* Match a GitHub-host origin URL (github.com or GHES) and return
- * `{host, owner, repo}`. Returns null for known non-GitHub forges
+ * `{host, owner, repo, transport}` plus any account the URL declares in its
+ * userinfo. Returns null for known non-GitHub forges
* (`KNOWN_NON_GITHUB_GIT_HOSTS`) and unparseable strings. Unknown hosts are
* presumed GitHub; the downstream probe/token paths degrade gracefully when
* one turns out not to be.
*/
-function parseGitHubOriginUrl(originUrl: string): ParsedOriginRepo | null {
+export function parseGitHubOriginUrl(originUrl: string): ParsedOriginRepo | null {
const raw = originUrl.trim();
if (!raw) return null;
@@ -97,26 +246,35 @@ function parseGitHubOriginUrl(originUrl: string): ParsedOriginRepo | null {
owner: string,
repo: string,
transport: OriginTransport,
+ userinfo?: string,
): ParsedOriginRepo | null => {
const normalized = normalizeGitHost(host);
if (KNOWN_NON_GITHUB_GIT_HOSTS.has(normalized)) return null;
- return { host: normalized, owner, repo, transport };
+ const login = loginFromUserinfo(userinfo);
+ return login === undefined
+ ? { host: normalized, owner, repo, transport }
+ : { host: normalized, owner, repo, transport, login };
};
- // https://<host>[:port]/<owner>/<repo>(.git)?
- let m = /^https?:\/\/([\w.-]+(?::\d+)?)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(raw);
- if (m) return classify(m[1], m[2], m[3], 'https');
+ // https://[<userinfo>@]<host>[:port]/<owner>/<repo>(.git)?
+ // The userinfo group is greedy so a `@` inside the password half
+ // (`user:p@ss`) is consumed by it rather than read as the host delimiter.
+ let m =
+ /^https?:\/\/(?:([^/]*)@)?([\w.-]+(?::\d+)?)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(
+ raw,
+ );
+ if (m) return classify(m[2], m[3], m[4], 'https', m[1]);
- // ssh://[user@]<host>[:port]/<owner>/<repo>(.git)?
- m = /^ssh:\/\/(?:[\w.-]+@)?([\w.-]+)(?::\d+)?\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(
+ // ssh://[<userinfo>@]<host>[:port]/<owner>/<repo>(.git)?
+ m = /^ssh:\/\/(?:([^/]*)@)?([\w.-]+)(?::\d+)?\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(
raw,
);
- if (m) return classify(m[1], m[2], m[3], 'ssh');
+ if (m) return classify(m[2], m[3], m[4], 'ssh', m[1]);
- // <user>@<host>:<owner>/<repo>(.git)? (scp-style; `@` is required, so
+ // <userinfo>@<host>:<owner>/<repo>(.git)? (scp-style; `@` is required, so
// Windows drive paths like `C:\x` can never match)
- m = /^[\w.-]+@([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(raw);
- if (m) return classify(m[1], m[2], m[3], 'ssh');
+ m = /^([\w.\-~%]+)@([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(raw);
+ if (m) return classify(m[2], m[3], m[4], 'ssh', m[1]);
// git://<host>[:port]/<owner>/<repo>(.git)?
m = /^git:\/\/([\w.-]+(?::\d+)?)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(raw);
@@ -125,6 +283,16 @@ function parseGitHubOriginUrl(originUrl: string): ParsedOriginRepo | null {
return null;
}
+/**
+ * The raw `origin` URL exactly as `.git/config` spells it, or null when no
+ * origin is configured. Callers that resolve credentials need the unparsed
+ * string: git matches `credential.<url>.*` entries against the URL as written.
+ */
+export function readOriginRemoteUrl(projectDir: string): string | null {
+ const origin = readRepository(projectDir)?.readRemoteUrl('origin');
+ return origin?.kind === 'configured' ? origin.url : null;
+}
+
/** Read and classify the configured origin shared by the two public readers. */
function readParsedOrigin(
projectDir: string,
@@ -140,7 +308,10 @@ function readParsedOrigin(
* Returns `ok` (with the origin `host` — `github.com` or a GHES hostname)
* for GitHub-host origins, `non-github` for known non-GitHub forges (gitlab,
* bitbucket, ...) and unparseable URLs, `no-remote` when no origin URL is
- * configured.
+ * configured. The URL-declared login is deliberately not surfaced here:
+ * identity decisions go through the `github-account.ts` resolvers, which
+ * also consult `credential.<url>.username` — a second reader of the raw
+ * userinfo could disagree with what the push path authenticates as.
*/
export function readOriginGitHubRepo(projectDir: string): OriginResult {
const parsed = readParsedOrigin(projectDir);
diff --git a/packages/server/src/share/github-account.test.ts b/packages/server/src/share/github-account.test.ts
new file mode 100644
index 000000000..eab2d8def
--- /dev/null
+++ b/packages/server/src/share/github-account.test.ts
@@ -0,0 +1,431 @@
+import { spawnSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import {
+ type CredentialUrlMatchReader,
+ createCachedGitHubAccountResolver,
+ resolveGitHubAccountFromUrl,
+} from './github-account.ts';
+
+/**
+ * The credential lookup delegates to a real `git config --get-urlmatch`, so
+ * these tests pin git's own longest-prefix resolution rather than a
+ * reimplementation of it. `GIT_CONFIG_NOSYSTEM` plus a temp `GIT_CONFIG_GLOBAL`
+ * keeps them off the developer's own config, which on a macOS box carries a
+ * system-scope `[credential]` section.
+ */
+let dir: string;
+let globalConfig: string;
+const savedEnv: Record<string, string | undefined> = {};
+
+beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'gh-account-'));
+ globalConfig = join(dir, 'gitconfig');
+ writeFileSync(globalConfig, '', 'utf-8');
+ savedEnv.GIT_CONFIG_GLOBAL = process.env.GIT_CONFIG_GLOBAL;
+ savedEnv.GIT_CONFIG_NOSYSTEM = process.env.GIT_CONFIG_NOSYSTEM;
+ process.env.GIT_CONFIG_GLOBAL = globalConfig;
+ process.env.GIT_CONFIG_NOSYSTEM = '1';
+});
+
+afterEach(() => {
+ for (const [key, value] of Object.entries(savedEnv)) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ rmSync(dir, { recursive: true, force: true });
+});
+
+function writeGlobalConfig(contents: string): void {
+ writeFileSync(globalConfig, contents, 'utf-8');
+}
+
+/** A worktree git recognizes, so repo-local config scope actually applies. */
+function initRepo(name: string, config?: string): string {
+ const root = join(dir, name);
+ mkdirSync(root, { recursive: true });
+ spawnSync('git', ['init', '-q'], { cwd: root, encoding: 'utf-8' });
+ if (config) writeFileSync(join(root, '.git', 'config'), config, 'utf-8');
+ return root;
+}
+
+/** A `.git/config` on disk without a real repo — enough for the origin read. */
+function seedOrigin(name: string, config: string): string {
+ const root = join(dir, name);
+ mkdirSync(join(root, '.git'), { recursive: true });
+ writeFileSync(join(root, '.git', 'config'), config, 'utf-8');
+ return root;
+}
+
+function originConfig(url: string): string {
+ return `[remote "origin"]\n\turl = ${url}\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n`;
+}
+
+describe('resolveGitHubAccountFromUrl', () => {
+ test('an account declared in the remote URL is the resolved account', () => {
+ expect(
+ resolveGitHubAccountFromUrl('https://[email protected]/mona/test.git', { cwd: dir }),
+ ).toEqual({ host: 'github.com', login: 'alice', source: 'remote-url' });
+ });
+
+ test('ssh and scp URLs declare their account the same way', () => {
+ expect(resolveGitHubAccountFromUrl('ssh://[email protected]/mona/test', { cwd: dir })).toEqual({
+ host: 'github.com',
+ login: 'alice',
+ source: 'remote-url',
+ });
+ expect(resolveGitHubAccountFromUrl('[email protected]:mona/test.git', { cwd: dir })).toEqual({
+ host: 'github.com',
+ login: 'alice',
+ source: 'remote-url',
+ });
+ });
+
+ test('the scp transport placeholder is not an account', () => {
+ expect(resolveGitHubAccountFromUrl('[email protected]:mona/test.git', { cwd: dir })).toEqual({
+ host: 'github.com',
+ source: 'active',
+ });
+ });
+
+ // Git consults credential helpers only for http(s) transports, and the scp
+ // form makes `git config --get-urlmatch` exit 128 (no scheme) — so a
+ // non-https origin must land on the floor without spawning the lookup at
+ // all.
+ test('ssh and scp origins never consult the credential-config lookup', () => {
+ let reads = 0;
+ const counting: CredentialUrlMatchReader = () => {
+ reads += 1;
+ return 'credential.username someone\n';
+ };
+ expect(
+ resolveGitHubAccountFromUrl('[email protected]:mona/test.git', {
+ cwd: dir,
+ _readCredentialUrlMatch: counting,
+ }),
+ ).toEqual({ host: 'github.com', source: 'active' });
+ expect(
+ resolveGitHubAccountFromUrl('ssh://[email protected]/mona/test.git', {
+ cwd: dir,
+ _readCredentialUrlMatch: counting,
+ }),
+ ).toEqual({ host: 'github.com', source: 'active' });
+ expect(reads).toBe(0);
+ });
+
+ // `https://:token@host/o/r` and placeholder-user forms reach the lookup
+ // (the userinfo declared no account), but the credential half must never
+ // ride into the subprocess argument.
+ test('the credential-config lookup never receives a URL userinfo', () => {
+ const seen: string[] = [];
+ const recording: CredentialUrlMatchReader = (url) => {
+ seen.push(url);
+ return null;
+ };
+ resolveGitHubAccountFromUrl('https://:[email protected]/mona/test.git', {
+ cwd: dir,
+ _readCredentialUrlMatch: recording,
+ });
+ resolveGitHubAccountFromUrl('https://x-access-token:[email protected]/mona/test.git', {
+ cwd: dir,
+ _readCredentialUrlMatch: recording,
+ });
+ expect(seen).toEqual(['https://github.com/mona/test.git', 'https://github.com/mona/test.git']);
+ });
+
+ test('a URL declaring no account falls through to the active account', () => {
+ expect(resolveGitHubAccountFromUrl('https://github.com/inkeep/repo.git', { cwd: dir })).toEqual(
+ {
+ host: 'github.com',
+ source: 'active',
+ },
+ );
+ });
+
+ test('a known non-GitHub forge resolves to the active account with no host', () => {
+ expect(resolveGitHubAccountFromUrl('https://gitlab.com/o/r.git', { cwd: dir })).toEqual({
+ source: 'active',
+ });
+ });
+
+ test('an unparseable URL resolves to the active account with no host', () => {
+ expect(resolveGitHubAccountFromUrl('not a url', { cwd: dir })).toEqual({ source: 'active' });
+ });
+
+ test('a GHES host carries through as the resolved host', () => {
+ expect(
+ resolveGitHubAccountFromUrl('https://[email protected]/org/repo.git', { cwd: dir }),
+ ).toEqual({ host: 'ghes.corp.example', login: 'alice', source: 'remote-url' });
+ });
+});
+
+describe('credential.<url>.username', () => {
+ test('a bare-host entry names the account', () => {
+ writeGlobalConfig('[credential "https://github.com"]\n\tusername = personal\n');
+ expect(resolveGitHubAccountFromUrl('https://github.com/mona/test.git', { cwd: dir })).toEqual({
+ host: 'github.com',
+ login: 'personal',
+ source: 'credential-config',
+ });
+ });
+
+ test('git longest-prefix matching picks the owner-scoped entry over the bare-host one', () => {
+ writeGlobalConfig(
+ '[credential "https://github.com"]\n\tusername = personal\n' +
+ '[credential "https://github.com/bigcorp"]\n\tusername = workbot\n',
+ );
+ expect(resolveGitHubAccountFromUrl('https://github.com/bigcorp/secret', { cwd: dir })).toEqual({
+ host: 'github.com',
+ login: 'workbot',
+ source: 'credential-config',
+ });
+ expect(resolveGitHubAccountFromUrl('https://github.com/mona/other', { cwd: dir })).toEqual({
+ host: 'github.com',
+ login: 'personal',
+ source: 'credential-config',
+ });
+ });
+
+ test('other credential keys matched alongside the username are ignored', () => {
+ writeGlobalConfig(
+ '[credential "https://github.com"]\n\thelper = osxkeychain\n\tusername = personal\n',
+ );
+ expect(resolveGitHubAccountFromUrl('https://github.com/mona/test', { cwd: dir })).toEqual({
+ host: 'github.com',
+ login: 'personal',
+ source: 'credential-config',
+ });
+ });
+
+ test('a matching entry that declares only a helper is not an account', () => {
+ writeGlobalConfig('[credential "https://github.com"]\n\thelper = osxkeychain\n');
+ expect(resolveGitHubAccountFromUrl('https://github.com/mona/test', { cwd: dir })).toEqual({
+ host: 'github.com',
+ source: 'active',
+ });
+ });
+
+ // rc=128 (as opposed to the benign rc=1 no-match): a syntactically broken
+ // gitconfig fails the whole `git config` invocation. The lookup failure
+ // must read as "no declaration" and fall to the active-account floor —
+ // never throw out of the resolver or kill the credential.
+ test('a broken gitconfig fails the lookup to the active-account floor', () => {
+ writeGlobalConfig('[credential "https://github.com\n\tusername = personal\n');
+ expect(resolveGitHubAccountFromUrl('https://github.com/mona/test', { cwd: dir })).toEqual({
+ host: 'github.com',
+ source: 'active',
+ });
+ });
+
+ test('a credential username outside the GitHub login grammar is not an account', () => {
+ writeGlobalConfig('[credential "https://github.com"]\n\tusername = [email protected]\n');
+ expect(resolveGitHubAccountFromUrl('https://github.com/mona/test.git', { cwd: dir })).toEqual({
+ host: 'github.com',
+ source: 'active',
+ });
+ });
+
+ test('a credential username carrying a token prefix is not an account', () => {
+ writeGlobalConfig(`[credential "https://github.com"]\n\tusername = ghp_${'a'.repeat(36)}\n`);
+ expect(resolveGitHubAccountFromUrl('https://github.com/mona/test.git', { cwd: dir })).toEqual({
+ host: 'github.com',
+ source: 'active',
+ });
+ });
+
+ test('a transport placeholder in credential config is not an account', () => {
+ writeGlobalConfig('[credential "https://github.com"]\n\tusername = x-access-token\n');
+ expect(resolveGitHubAccountFromUrl('https://github.com/mona/test.git', { cwd: dir })).toEqual({
+ host: 'github.com',
+ source: 'active',
+ });
+ });
+
+ // An unscoped `[credential] username` matches every URL git asks about, so a
+ // value set for some corporate non-GitHub host would otherwise be read as a
+ // GitHub account for every github.com remote on the machine.
+ test('an unscoped credential username that is not a login stays out of the chain', () => {
+ writeGlobalConfig('[credential]\n\tusername = [email protected]\n');
+ expect(resolveGitHubAccountFromUrl('https://github.com/mona/test.git', { cwd: dir })).toEqual({
+ host: 'github.com',
+ source: 'active',
+ });
+ });
+
+ test('a repo-local entry names the account', () => {
+ const repo = initRepo(
+ 'local',
+ '[credential "https://github.com/acme"]\n\tusername = repobot\n',
+ );
+ expect(resolveGitHubAccountFromUrl('https://github.com/acme/thing.git', { cwd: repo })).toEqual(
+ {
+ host: 'github.com',
+ login: 'repobot',
+ source: 'credential-config',
+ },
+ );
+ });
+
+ test('a global-scope entry resolves before the repository exists', () => {
+ writeGlobalConfig('[credential "https://github.com"]\n\tusername = personal\n');
+ const nowhere = join(dir, 'not-a-repo');
+ mkdirSync(nowhere, { recursive: true });
+ expect(
+ resolveGitHubAccountFromUrl('https://github.com/mona/fresh-clone.git', { cwd: nowhere }),
+ ).toEqual({ host: 'github.com', login: 'personal', source: 'credential-config' });
+ });
+
+ test('the URL account wins over a more specific credential entry', () => {
+ writeGlobalConfig(
+ '[credential "https://github.com/bigcorp"]\n\tusername = workbot\n\tuseHttpPath = true\n',
+ );
+ expect(
+ resolveGitHubAccountFromUrl('https://[email protected]/bigcorp/secret', { cwd: dir }),
+ ).toEqual({ host: 'github.com', login: 'alice', source: 'remote-url' });
+ });
+
+ test('a declared URL account needs no git lookup', () => {
+ let reads = 0;
+ const counting: CredentialUrlMatchReader = () => {
+ reads += 1;
+ return null;
+ };
+ resolveGitHubAccountFromUrl('https://[email protected]/o/r.git', {
+ cwd: dir,
+ _readCredentialUrlMatch: counting,
+ });
+ expect(reads).toBe(0);
+ });
+
+ test('a lookup that cannot run falls through to the active account', () => {
+ const unavailable: CredentialUrlMatchReader = () => null;
+ expect(
+ resolveGitHubAccountFromUrl('https://github.com/o/r.git', {
+ cwd: dir,
+ _readCredentialUrlMatch: unavailable,
+ }),
+ ).toEqual({ host: 'github.com', source: 'active' });
+ });
+});
+
+describe('createCachedGitHubAccountResolver', () => {
+ /** A credential lookup whose calls the test can count and whose answer it can swap. */
+ function countingReader(initial: string | null): {
+ fn: CredentialUrlMatchReader;
+ calls: () => number;
+ respond: (next: string | null) => void;
+ } {
+ let calls = 0;
+ let response = initial;
+ return {
+ fn: () => {
+ calls += 1;
+ return response;
+ },
+ calls: () => calls,
+ respond: (next) => {
+ response = next;
+ },
+ };
+ }
+
+ test('repeated resolutions within the TTL share one credential lookup', () => {
+ const project = seedOrigin('hot-path', originConfig('https://github.com/acme/kb.git'));
+ const reader = countingReader('credential.username workbot\n');
+ const resolver = createCachedGitHubAccountResolver({ _readCredentialUrlMatch: reader.fn });
+
+ for (let i = 0; i < 3; i += 1) {
+ expect(resolver.resolve(project)).toEqual({
+ host: 'github.com',
+ login: 'workbot',
+ source: 'credential-config',
+ });
+ }
+ expect(reader.calls()).toBe(1);
+ });
+
+ test('invalidate() drops the cached resolution so the next resolve re-runs the lookup', () => {
+ const project = seedOrigin('invalidate', originConfig('https://github.com/acme/kb.git'));
+ const reader = countingReader('credential.username workbot\n');
+ const resolver = createCachedGitHubAccountResolver({ _readCredentialUrlMatch: reader.fn });
+
+ resolver.resolve(project);
+ reader.respond('credential.username otherbot\n');
+ resolver.invalidate();
+ expect(resolver.resolve(project)).toEqual({
+ host: 'github.com',
+ login: 'otherbot',
+ source: 'credential-config',
+ });
+ expect(reader.calls()).toBe(2);
+ });
+
+ test('a credential-config change is picked up once the TTL elapses', () => {
+ const project = seedOrigin('ttl', originConfig('https://github.com/acme/kb.git'));
+ const reader = countingReader(null);
+ let clock = 0;
+ const resolver = createCachedGitHubAccountResolver({
+ ttlMs: 1_000,
+ now: () => clock,
+ _readCredentialUrlMatch: reader.fn,
+ });
+
+ expect(resolver.resolve(project)).toEqual({ host: 'github.com', source: 'active' });
+ reader.respond('credential.username workbot\n');
+ clock = 999;
+ expect(resolver.resolve(project)).toEqual({ host: 'github.com', source: 'active' });
+ clock = 1_000;
+ expect(resolver.resolve(project)).toEqual({
+ host: 'github.com',
+ login: 'workbot',
+ source: 'credential-config',
+ });
+ expect(reader.calls()).toBe(2);
+ });
+
+ test('an origin URL change re-resolves immediately, with no TTL to wait out', () => {
+ const project = seedOrigin('swap', originConfig('https://github.com/mona/kb.git'));
+ const reader = countingReader(null);
+ const resolver = createCachedGitHubAccountResolver({ _readCredentialUrlMatch: reader.fn });
+
+ expect(resolver.resolve(project)).toEqual({ host: 'github.com', source: 'active' });
+ writeFileSync(
+ join(project, '.git', 'config'),
+ originConfig('https://[email protected]/mona/kb.git'),
+ 'utf-8',
+ );
+ expect(resolver.resolve(project)).toEqual({
+ host: 'github.com',
+ login: 'alice',
+ source: 'remote-url',
+ });
+ // The declared-account URL needs no lookup, so the swap costs no spawn.
+ expect(reader.calls()).toBe(1);
+ });
+
+ test('a project with no origin resolves to the active account without a lookup', () => {
+ const project = seedOrigin('bare', '[core]\n\tbare = false\n');
+ const reader = countingReader('credential.username workbot\n');
+ const resolver = createCachedGitHubAccountResolver({ _readCredentialUrlMatch: reader.fn });
+
+ expect(resolver.resolve(project)).toEqual({ source: 'active' });
+ expect(reader.calls()).toBe(0);
+ });
+
+ test('projects do not share a cached resolution even for the same URL', () => {
+ // Repo-local `credential.<url>.username` entries make the answer
+ // project-specific, so a shared entry would leak one project's identity
+ // into another.
+ const url = 'https://github.com/acme/kb.git';
+ const one = seedOrigin('proj-one', originConfig(url));
+ const two = seedOrigin('proj-two', originConfig(url));
+ const reader = countingReader(null);
+ const resolver = createCachedGitHubAccountResolver({ _readCredentialUrlMatch: reader.fn });
+
+ resolver.resolve(one);
+ resolver.resolve(two);
+ expect(reader.calls()).toBe(2);
+ });
+});
diff --git a/packages/server/src/share/github-account.ts b/packages/server/src/share/github-account.ts
new file mode 100644
index 000000000..183d02747
--- /dev/null
+++ b/packages/server/src/share/github-account.ts
@@ -0,0 +1,253 @@
+/**
+ * Resolve which GitHub account a remote belongs to, from identity the user has
+ * already declared through standard git mechanisms.
+ *
+ * The chain mirrors how git itself picks a username for a credential request:
+ *
+ * 1. the remote URL's userinfo (`https://[email protected]/o/r`)
+ * 2. `credential.<url>.username` at any config scope
+ * 3. neither — the caller keeps today's behavior and uses gh's active account
+ *
+ * Step 1 beats step 2 even when a `credential.<url>.username` entry is the more
+ * specific of the two: git resolves the URL's userinfo first, so any other
+ * order would make OpenKnowledge disagree with what plain `git push` does in
+ * the user's terminal on identical config.
+ *
+ * Step 3 is a floor, never a cliff. A URL that names no account, an unparseable
+ * origin, a missing `git` binary, and a non-GitHub forge all land on `active`
+ * with no login — never on "no account at all", which would turn a
+ * wrong-identity failure into a total auth failure.
+ *
+ * This is a sibling of `git-context.ts` rather than part of it because step 2
+ * spawns `git`, which that module deliberately avoids for its sub-100ms budget.
+ * Callers on a hot path must cache the result rather than resolving per
+ * operation — `createCachedGitHubAccountResolver` is that cache.
+ */
+
+import { spawnSync } from 'node:child_process';
+import { withHiddenWindowsConsole } from '../child-process-windows-hide.ts';
+import { getLogger } from '../logger.ts';
+import { asDeclaredGitHubLogin, parseGitHubOriginUrl, readOriginRemoteUrl } from './git-context.ts';
+import { redactShareSubprocessStderr } from './publish.ts';
+
+const log = getLogger('github-account');
+
+/** Which of the three declaration sites produced the account, in chain order. */
+export type GitHubAccountSource = 'remote-url' | 'credential-config' | 'active';
+
+/**
+ * A resolved GitHub identity for one remote.
+ *
+ * `host` is parsed out of the URL and never accepted from the caller — two
+ * sources for the same fact is how the probe and the push end up authenticating
+ * as different accounts. It is absent only when no GitHub host could be parsed.
+ *
+ * A discriminated union so the prose invariant is a compile error instead:
+ * a declared source always carries both `host` and `login`, and `'active'`
+ * never carries a login — the caller's signal to resolve a token the way it
+ * always has.
+ */
+export type GitHubAccount =
+ | { source: 'active'; host?: string; login?: undefined }
+ | { source: Exclude<GitHubAccountSource, 'active'>; host: string; login: string };
+
+/**
+ * Reads `git config --get-urlmatch credential <url>`, returning raw stdout or
+ * null when git exits non-zero, is absent, or produces nothing.
+ *
+ * Injectable so callers that must not spawn (hot paths under test, spawn
+ * accounting) can supply their own; the default is the real subprocess.
+ */
+export type CredentialUrlMatchReader = (url: string, cwd: string) => string | null;
+
+export interface ResolveGitHubAccountOptions {
+ /**
+ * Directory the `git config` lookup runs in, defaulting to the process cwd.
+ * Every config scope git resolves from that directory applies — including
+ * the LOCAL scope of whatever repository encloses it. A pre-clone resolution
+ * run from inside an unrelated checkout therefore sees that checkout's
+ * `credential.<url>.*` entries too, not just global/system scope; callers
+ * that must not inherit an enclosing repo's declarations should pass a cwd
+ * outside any repository.
+ */
+ cwd?: string;
+ _readCredentialUrlMatch?: CredentialUrlMatchReader;
+}
+
+const defaultCredentialUrlMatchReader: CredentialUrlMatchReader = (url, cwd) => {
+ const result = spawnSync(
+ 'git',
+ ['config', '--get-urlmatch', 'credential', url],
+ withHiddenWindowsConsole({ cwd, encoding: 'utf-8', timeout: 5_000 }),
+ );
+ // rc=0 and rc=1 are both benign, and neither one answers "was a username
+ // declared?" — git exits 0 whenever ANY `credential.*` key matches the URL
+ // (it prints `credential.helper` on its own when no username is set) and 1
+ // only when nothing in the section matches at all, so the parse below is
+ // what decides. Everything else — a failed or timed-out spawn
+ // (`error`/`signal`), or git rejecting the invocation (rc=128, e.g. a
+ // broken gitconfig) — is a lookup FAILURE, not an absence of declaration.
+ // Both degrade to the chain's floor (a resolver error must never take auth
+ // down), but the failure class gets a log line so a user whose
+ // `credential.<url>.username` declaration silently stops applying has a
+ // trace to find.
+ if (result.error || result.status === null || (result.status !== 0 && result.status !== 1)) {
+ log.warn(
+ {
+ status: result.status,
+ signal: result.signal,
+ err: result.error,
+ // Redacted before it lands in a pino field: the failure classes that
+ // reach this branch (rc=128 on a broken gitconfig) are exactly the ones
+ // where git echoes config content back, and pino output is persisted to
+ // disk and collected into diagnostic bundles.
+ stderr:
+ typeof result.stderr === 'string'
+ ? redactShareSubprocessStderr(result.stderr).slice(0, 200)
+ : undefined,
+ },
+ '[github-account] git config --get-urlmatch failed — treating the URL as declaring no account',
+ );
+ return null;
+ }
+ if (result.status !== 0 || !result.stdout) return null;
+ return result.stdout;
+};
+
+/**
+ * Strip any `user[:password]@` half out of a URL before it becomes a
+ * subprocess argument. Only reached when the userinfo declared no usable
+ * account (absent, a transport placeholder, or credential-shaped), so nothing
+ * of matching value is lost — and an embedded token must never ride into
+ * argv, which is world-readable on Linux. Host- and path-scoped
+ * `credential.<url>.*` matching is unaffected; only a config key scoped to
+ * that exact userinfo (pathological for a placeholder) would stop matching.
+ */
+function stripUserinfoForLookup(url: string): string {
+ return url.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/]*@/i, '$1');
+}
+
+/**
+ * Pick the username out of `--get-urlmatch` output, which prints one
+ * `credential.<key> <value>` line per matched key. Later lines win, matching
+ * git's own last-value-wins resolution.
+ */
+function credentialUsernameFrom(stdout: string): string | undefined {
+ let username: string | undefined;
+ for (const line of stdout.split('\n')) {
+ const value = line.startsWith('credential.username ')
+ ? line.slice('credential.username '.length).trim()
+ : undefined;
+ if (value) username = value;
+ }
+ return username;
+}
+
+/**
+ * Resolve the account declared for a remote URL. Works before the repository
+ * exists: the userinfo needs only the URL, and `--get-urlmatch` resolves
+ * every config scope reachable from `cwd` — global and system always, plus
+ * the local scope of any repository that encloses `cwd`.
+ */
+export function resolveGitHubAccountFromUrl(
+ url: string,
+ options: ResolveGitHubAccountOptions = {},
+): GitHubAccount {
+ const parsed = parseGitHubOriginUrl(url);
+ // A known non-GitHub forge or an unparseable URL has no GitHub account to
+ // name, and asking gh about it would be meaningless.
+ if (!parsed) return { source: 'active' };
+
+ const host = parsed.host;
+ if (parsed.login) return { host, login: parsed.login, source: 'remote-url' };
+
+ // Credential config is an HTTPS-transport concept: git consults credential
+ // helpers only for http(s) remotes, and `--get-urlmatch` exits 128 outright
+ // on the scp form (no scheme). SSH/git origins go straight to the floor —
+ // no spawn, and no per-TTL fatal for a class of origins the lookup can
+ // never answer for.
+ if (parsed.transport !== 'https') return { host, source: 'active' };
+
+ const read = options._readCredentialUrlMatch ?? defaultCredentialUrlMatchReader;
+ const stdout = read(stripUserinfoForLookup(url), options.cwd ?? process.cwd());
+ // The same declared-account policy the URL-userinfo tier applies: a config
+ // value that cannot be a GitHub login (an email, a pasted token, a
+ // transport placeholder like `x-access-token`) reads as no declaration and
+ // falls to the active-account floor instead of reaching argv, logs, the
+ // wire, and UI copy.
+ const login = stdout ? asDeclaredGitHubLogin(credentialUsernameFrom(stdout)) : undefined;
+ return login ? { host, login, source: 'credential-config' } : { host, source: 'active' };
+}
+
+export interface CachedGitHubAccountResolverOptions {
+ /** Cache lifetime for a resolved account per project + origin URL. Default 60s. */
+ ttlMs?: number;
+ /** Injectable clock for tests. Default `Date.now`. */
+ now?: () => number;
+ _readCredentialUrlMatch?: CredentialUrlMatchReader;
+}
+
+export interface CachedGitHubAccountResolver {
+ /** Resolve the account declared for the project's `origin`, cached. */
+ resolve(projectDir: string): GitHubAccount;
+ /**
+ * Drop the cached resolution so the next `resolve` re-runs the chain.
+ * Called at the same credential-change points that flush the token cache —
+ * after an auth failure or a fresh sign-in, re-requesting a token for a
+ * possibly-stale account choice would defeat the flush.
+ */
+ invalidate(): void;
+}
+
+const DEFAULT_RESOLUTION_TTL_MS = 60_000;
+
+/**
+ * The project-shaped resolver, cached for hot paths: the origin URL is re-read from
+ * `.git/config` on every call — cheap, and what lets an origin edit (a remote
+ * swap, a userinfo change) take effect on the very next resolution — while the
+ * `git config --get-urlmatch` spawn behind the credential-config step runs at
+ * most once per project + URL per TTL window. A config edit that does not
+ * change the URL is picked up when the window rolls over, or immediately via
+ * `invalidate()`.
+ *
+ * The entry is keyed by project as well as URL because repo-local
+ * `credential.<url>.*` entries make the answer project-specific. It is a
+ * single slot, sized for the one-resolver-per-engine (one project) wiring —
+ * a future multi-project caller sharing one resolver would thrash it to a 0%
+ * hit rate and should switch the slot to a Map first.
+ */
+export function createCachedGitHubAccountResolver(
+ options: CachedGitHubAccountResolverOptions = {},
+): CachedGitHubAccountResolver {
+ const ttlMs = options.ttlMs ?? DEFAULT_RESOLUTION_TTL_MS;
+ const now = options.now ?? Date.now;
+ let cached:
+ | { projectDir: string; url: string; account: GitHubAccount; expiresAt: number }
+ | undefined;
+
+ return {
+ resolve(projectDir: string): GitHubAccount {
+ const url = readOriginRemoteUrl(projectDir);
+ if (!url) return { source: 'active' };
+ const t = now();
+ if (
+ cached &&
+ cached.projectDir === projectDir &&
+ cached.url === url &&
+ cached.expiresAt > t
+ ) {
+ return cached.account;
+ }
+ const account = resolveGitHubAccountFromUrl(url, {
+ cwd: projectDir,
+ _readCredentialUrlMatch: options._readCredentialUrlMatch,
+ });
+ cached = { projectDir, url, account, expiresAt: t + ttlMs };
+ return account;
+ },
+
+ invalidate(): void {
+ cached = undefined;
+ },
+ };
+}
diff --git a/packages/server/src/share/publish.test.ts b/packages/server/src/share/publish.test.ts
index dbc59ca51..72b5ca7c1 100644
--- a/packages/server/src/share/publish.test.ts
+++ b/packages/server/src/share/publish.test.ts
@@ -217,4 +217,73 @@ describe('redactShareSubprocessStderr', () => {
test('handles empty input', () => {
expect(redactShareSubprocessStderr('')).toBe('');
});
+
+ test('redacts a bare token-as-username URL', () => {
+ const tok = `ghp_${'a'.repeat(36)}`;
+ const redacted = redactShareSubprocessStderr(
+ `fatal: unable to access https://${tok}@github.com/o/r.git/`,
+ );
+ expect(redacted).not.toContain(tok);
+ expect(redacted).toContain('https://***@github.com');
+ });
+
+ test('redacts a token username paired with an empty password', () => {
+ const tok = `ghs_${'b'.repeat(36)}`;
+ expect(redactShareSubprocessStderr(`https://${tok}:@github.com/o/r`)).not.toContain(tok);
+ });
+
+ test('redacts a token password with an empty username', () => {
+ const tok = `gho_${'c'.repeat(36)}`;
+ expect(redactShareSubprocessStderr(`https://:${tok}@github.com/o/r`)).not.toContain(tok);
+ });
+
+ test('redacts a fine-grained PAT username', () => {
+ const tok = `github_pat_${'d'.repeat(70)}`;
+ expect(redactShareSubprocessStderr(`https://${tok}@github.com/o/r`)).not.toContain(tok);
+ });
+
+ test('redacts every credentialed URL on a line', () => {
+ const redacted = redactShareSubprocessStderr(
+ `push https://ghp_${'e'.repeat(36)}@github.com/a/b and https://user:[email protected]/c/d`,
+ );
+ expect(redacted).not.toContain('ghp_');
+ expect(redacted).not.toContain('s3cret');
+ expect(redacted).toContain('user:***@github.com');
+ });
+
+ test('leaves a plain account-userinfo URL intact', () => {
+ const stderr = 'fetch https://[email protected]/o/r failed';
+ expect(redactShareSubprocessStderr(stderr)).toBe(stderr);
+ });
+
+ // The `\\s` exclusion is now the only thing holding the userinfo span to one
+ // token. These three shapes are not producible by git stderr, but they fail
+ // loudly if a future edit widens the class to `[^/]*` — which would swallow
+ // whole sentences of a diagnostic into a `***`.
+ test('a later email on the line is not swallowed into the URL userinfo', () => {
+ const stderr = "fatal: 'https://github.com' — contact [email protected]";
+ expect(redactShareSubprocessStderr(stderr)).toBe(stderr);
+ });
+
+ test('a whitespace boundary ends the userinfo span', () => {
+ const stderr = 'https://github.com/o/r and then user@host';
+ expect(redactShareSubprocessStderr(stderr)).toBe(stderr);
+ });
+
+ test('an scp-form remote later on the line is left intact', () => {
+ const stderr = 'tried https://github.com/o/r then [email protected]:o/r.git';
+ expect(redactShareSubprocessStderr(stderr)).toBe(stderr);
+ });
+
+ // The userinfo span runs to the LAST @ before a slash or whitespace, like
+ // the clone side's stripUrlPassword: a raw @ inside a hand-written
+ // password must not split the match early and leave the password's tail.
+ test('redacts the whole password even when it contains a raw @', () => {
+ const redacted = redactShareSubprocessStderr(
+ 'fatal: unable to access https://alice:p@[email protected]/o/r',
+ );
+ expect(redacted).toContain('alice:***@github.com');
+ expect(redacted).not.toContain('p@ss');
+ expect(redacted).not.toContain('[email protected]');
+ });
});
diff --git a/packages/server/src/share/publish.ts b/packages/server/src/share/publish.ts
index 7ca334254..6d0244abc 100644
--- a/packages/server/src/share/publish.ts
+++ b/packages/server/src/share/publish.ts
@@ -26,6 +26,7 @@ import type {
SharePublishResponse,
} from '@inkeep/open-knowledge-core';
import { getLogger } from '../logger.ts';
+import { loginShapedUserinfoUser } from './git-context.ts';
// ─── Handler tags + URL keys ─────────────────────────────────────────────────
@@ -225,13 +226,25 @@ export function emitSharePublishLog(
}
/**
- * Strip credentials embedded in URLs of the form
- * `https://x-access-token:<pat>@github.com/...` (the inline-token push URL
- * used by `share publish`). Replaces the token with
- * `***` so a partial git stderr message in a logged subprocess failure
- * doesn't leak the PAT. Also handles the bare `<user>:<pwd>@host` form for
- * completeness.
+ * Strip credentials embedded in URLs before stderr is logged or surfaced.
+ * Covers the inline-token push URL `share publish` mints
+ * (`https://x-access-token:<pat>@github.com/...`), the bare `user:pwd@` form,
+ * and the token-as-username form (`https://<pat>@github.com/...`) — the
+ * password half is always dropped, and the username half survives only when
+ * it is shaped like a login rather than a credential, so `x-access-token`
+ * stays readable while a PAT never does.
+ *
+ * The userinfo span runs greedily to the LAST `@` before a slash or
+ * whitespace, matching `stripUrlPassword` on the clone side: a raw `@`
+ * inside a hand-written password (`user:p@ss@host`) must not split the
+ * match early and leave the password's tail in the output.
*/
export function redactShareSubprocessStderr(stderr: string): string {
- return stderr.replace(/(https?:\/\/)([^:@\s/]+):([^@\s/]+)@/g, '$1$2:***@');
+ return stderr.replace(/(https?:\/\/)([^\s/]*)@/g, (whole, scheme: string, userinfo: string) => {
+ const colon = userinfo.indexOf(':');
+ const user = colon === -1 ? userinfo : userinfo.slice(0, colon);
+ const keepUser = user !== '' && loginShapedUserinfoUser(user) !== undefined;
+ if (colon === -1) return keepUser ? whole : `${scheme}***@`;
+ return `${scheme}${keepUser ? user : '***'}:***@`;
+ });
}
diff --git a/packages/server/src/sync-engine.test.ts b/packages/server/src/sync-engine.test.ts
index dcb7029c4..45ea0e845 100644
--- a/packages/server/src/sync-engine.test.ts
+++ b/packages/server/src/sync-engine.test.ts
@@ -39,9 +39,11 @@ import { LOCAL_DIR, type SyncMode, SyncStatusSchema } from '@inkeep/open-knowled
import simpleGit from 'simple-git';
import { createContentFilter } from './content-filter.ts';
import { classifyGitError } from './error-classification.ts';
+import type { GitHandle } from './git-handle.ts';
import { listNames } from './git-paths.ts';
-import type { DetectGhFn, ProbeTokenStore } from './github-permissions.ts';
+import type { DetectGhAccountsFn, DetectGhFn, ProbeTokenStore } from './github-permissions.ts';
import { getLogger } from './logger.ts';
+import type { CredentialUrlMatchReader } from './share/github-account.ts';
import { classifyFastForwardRefusal, SyncEngine, type SyncState } from './sync-engine.ts';
const execFileAsync = promisify(execFile);
@@ -160,6 +162,9 @@ function makeProbeEngine(opts: {
syncEnabled?: boolean;
mode?: SyncMode;
fakeProbe: FakeProbeRecorder['fn'];
+ detectGhAccounts?: DetectGhAccountsFn;
+ _readCredentialUrlMatch?: CredentialUrlMatchReader;
+ cc1Broadcaster?: ConstructorParameters<typeof SyncEngine>[0]['cc1Broadcaster'];
}) {
return new SyncEngine({
projectDir,
@@ -168,6 +173,9 @@ function makeProbeEngine(opts: {
syncEnabled: opts.syncEnabled,
mode: opts.mode,
checkPushPermissionFn: opts.fakeProbe,
+ detectGhAccounts: opts.detectGhAccounts,
+ _readCredentialUrlMatch: opts._readCredentialUrlMatch,
+ cc1Broadcaster: opts.cc1Broadcaster,
});
}
@@ -3014,6 +3022,251 @@ describe('SyncEngine push-permission probe', () => {
});
});
+ test('threads the origin-declared account and the accounts listing into the probe', async () => {
+ await initGitWithOrigin('https://[email protected]/inkeep/open-knowledge.git');
+ const probe = fakeProbe({ kind: 'allowed' });
+ const accountsFn: DetectGhAccountsFn = () => [{ login: 'alice', active: true }];
+ const engine = makeProbeEngine({
+ syncEnabled: false,
+ fakeProbe: probe.fn,
+ detectGhAccounts: accountsFn,
+ });
+ await engine.start();
+ await waitForPushPermissionResolved(engine);
+ // The account comes from the same cached resolver the push path reads,
+ // so probe and push cannot resolve different identities for one origin.
+ expect(probe.opts[0]?.account).toMatchObject({ login: 'alice', source: 'remote-url' });
+ expect(probe.opts[0]?.detectGhAccounts).toBe(accountsFn);
+ });
+
+ // When a probe re-runs without a state transition, the equality predicate
+ // is the sole gate on the staleness broadcast — an identity change with an
+ // unchanged deniedReason must still reach the UI, or the popover keeps
+ // naming the previous account after a `gh auth switch`.
+ test('a re-probe that changes only the resolved identity still broadcasts', async () => {
+ await initGitWithOrigin();
+ const signal = vi.fn();
+ const probe = fakeProbe(
+ { kind: 'denied', reason: 'private-no-access', resolvedLogin: 'alice' },
+ { kind: 'denied', reason: 'private-no-access', resolvedLogin: 'bob' },
+ );
+ const engine = makeProbeEngine({
+ syncEnabled: false,
+ fakeProbe: probe.fn,
+ cc1Broadcaster: { signal },
+ });
+ await engine.start();
+ await waitForPushPermissionResolved(engine);
+ const before = signal.mock.calls.length;
+
+ await engine.refreshPushPermission();
+
+ expect(probe.calls).toBe(2);
+ expect(signal.mock.calls.length).toBeGreaterThan(before);
+ expect(signal.mock.calls.at(-1)?.[0]).toBe('sync-status');
+ await engine.destroy();
+ });
+
+ test('a re-probe that changes only the declared-miss login still broadcasts', async () => {
+ await initGitWithOrigin();
+ const signal = vi.fn();
+ const probe = fakeProbe(
+ {
+ kind: 'denied',
+ reason: 'private-no-access',
+ resolvedLogin: 'bob',
+ declaredLogin: 'alice',
+ declaredSource: 'remote-url',
+ },
+ {
+ kind: 'denied',
+ reason: 'private-no-access',
+ resolvedLogin: 'bob',
+ declaredLogin: 'carol',
+ declaredSource: 'remote-url',
+ },
+ );
+ const engine = makeProbeEngine({
+ syncEnabled: false,
+ fakeProbe: probe.fn,
+ cc1Broadcaster: { signal },
+ });
+ await engine.start();
+ await waitForPushPermissionResolved(engine);
+ const before = signal.mock.calls.length;
+
+ await engine.refreshPushPermission();
+
+ expect(probe.calls).toBe(2);
+ expect(signal.mock.calls.length).toBeGreaterThan(before);
+ await engine.destroy();
+ });
+
+ test('a re-probe that changes only the declaration mechanism still broadcasts', async () => {
+ await initGitWithOrigin();
+ const signal = vi.fn();
+ const probe = fakeProbe(
+ {
+ kind: 'denied',
+ reason: 'private-no-access',
+ resolvedLogin: 'bob',
+ declaredLogin: 'alice',
+ declaredSource: 'remote-url',
+ },
+ {
+ kind: 'denied',
+ reason: 'private-no-access',
+ resolvedLogin: 'bob',
+ declaredLogin: 'alice',
+ declaredSource: 'credential-config',
+ },
+ );
+ const engine = makeProbeEngine({
+ syncEnabled: false,
+ fakeProbe: probe.fn,
+ cc1Broadcaster: { signal },
+ });
+ await engine.start();
+ await waitForPushPermissionResolved(engine);
+ const before = signal.mock.calls.length;
+
+ await engine.refreshPushPermission();
+
+ expect(probe.calls).toBe(2);
+ expect(signal.mock.calls.length).toBeGreaterThan(before);
+ await engine.destroy();
+ });
+
+ test('a re-probe with an identical outcome does not re-broadcast', async () => {
+ await initGitWithOrigin();
+ const signal = vi.fn();
+ const probe = fakeProbe(
+ { kind: 'denied', reason: 'private-no-access', resolvedLogin: 'alice' },
+ { kind: 'denied', reason: 'private-no-access', resolvedLogin: 'alice' },
+ );
+ const engine = makeProbeEngine({
+ syncEnabled: false,
+ fakeProbe: probe.fn,
+ cc1Broadcaster: { signal },
+ });
+ await engine.start();
+ await waitForPushPermissionResolved(engine);
+ const before = signal.mock.calls.length;
+
+ await engine.refreshPushPermission();
+
+ expect(probe.calls).toBe(2);
+ expect(signal.mock.calls.length).toBe(before);
+ await engine.destroy();
+ });
+
+ // A denied probe must not overwrite an auth park: the park carries a
+ // classified failure and its error code, and the probe cannot see that
+ // code — demoting the pause would strand every surface keyed on the pair.
+ test('a denied probe leaves the repository-not-found park intact', async () => {
+ await initGitWithOrigin();
+ const probe = fakeProbe({ kind: 'allowed' }, { kind: 'denied', reason: 'private-no-access' });
+ const engine = makeProbeEngine({ syncEnabled: true, fakeProbe: probe.fn });
+ await engine.start();
+ await waitForPushPermissionResolved(engine);
+ const internal = engine as unknown as InternalState;
+ internal.state = 'auth-error';
+ internal.pausedReason = 'auth-error';
+ internal.pushErrorCode = 'auth-not-found-as-identity';
+
+ await engine.refreshPushPermission();
+
+ // Load-bearing: without `start()` the probe returns at its `hasRemote`
+ // gate and the assertions below just echo the fields the test wrote.
+ expect(probe.calls).toBe(2);
+ const status = engine.getStatus();
+ expect(status.pausedReason).toBe('auth-error');
+ expect(status.state).toBe('auth-error');
+ expect(status.pushErrorCode).toBe('auth-not-found-as-identity');
+ await engine.destroy();
+ });
+
+ // The masquerade is the ONLY park the probe must not demote. Every other
+ // auth subclass is better diagnosed by the probe, and `trigger()` never
+ // clears those parks — so blocking the demotion would strand a revoked
+ // collaborator on "Reconnect required" behind a sign-in that can't help.
+ test('a denied probe DOES demote a non-masquerade auth park', async () => {
+ await initGitWithOrigin();
+ const probe = fakeProbe({ kind: 'allowed' }, { kind: 'denied', reason: 'no-collaborator' });
+ const engine = makeProbeEngine({ syncEnabled: true, fakeProbe: probe.fn });
+ await engine.start();
+ await waitForPushPermissionResolved(engine);
+ const internal = engine as unknown as InternalState;
+ internal.state = 'auth-error';
+ internal.pausedReason = 'auth-error';
+ internal.pushErrorCode = 'auth-403';
+
+ await engine.refreshPushPermission();
+
+ expect(probe.calls).toBe(2);
+ expect(engine.getStatus().pausedReason).toBe('no-push-permission');
+ await engine.destroy();
+ });
+
+ // The retryable arm transitions to `offline` WITHOUT clearing pausedReason,
+ // so a state-only guard would let the probe demote a masquerade park here.
+ test('the not-found park survives a denied probe even after an offline transition', async () => {
+ await initGitWithOrigin();
+ const probe = fakeProbe({ kind: 'allowed' }, { kind: 'denied', reason: 'private-no-access' });
+ const engine = makeProbeEngine({ syncEnabled: true, fakeProbe: probe.fn });
+ await engine.start();
+ await waitForPushPermissionResolved(engine);
+ const internal = engine as unknown as InternalState;
+ internal.state = 'offline';
+ internal.pausedReason = 'auth-error';
+ internal.pushErrorCode = 'auth-not-found-as-identity';
+
+ await engine.refreshPushPermission();
+
+ expect(probe.calls).toBe(2);
+ expect(engine.getStatus().pausedReason).toBe('auth-error');
+ await engine.destroy();
+ });
+
+ test('an origin with no declared account probes with no login — the owner is never a selector', async () => {
+ await initGitWithOrigin('https://github.com/inkeep/open-knowledge.git');
+ const probe = fakeProbe({ kind: 'allowed' });
+ const engine = makeProbeEngine({
+ syncEnabled: false,
+ fakeProbe: probe.fn,
+ _readCredentialUrlMatch: () => null,
+ });
+ await engine.start();
+ await waitForPushPermissionResolved(engine);
+ expect(probe.opts[0]?.account?.source).toBe('active');
+ expect(probe.opts[0]?.account?.login).toBeUndefined();
+ });
+
+ test('a denied probe result carries its identity fields into getStatus()', async () => {
+ await initGitWithOrigin();
+ const probe = fakeProbe({
+ kind: 'denied',
+ reason: 'private-no-access',
+ resolvedLogin: 'bob',
+ declaredLogin: 'alice',
+ declaredSource: 'remote-url',
+ });
+ const engine = makeProbeEngine({
+ syncEnabled: false,
+ fakeProbe: probe.fn,
+ _readCredentialUrlMatch: () => null,
+ });
+ await engine.start();
+ await waitForPushPermissionResolved(engine);
+ expect(engine.getStatus().pushPermission).toEqual({
+ checkStatus: 'denied',
+ deniedReason: 'private-no-access',
+ resolvedLogin: 'bob',
+ declaredLogin: 'alice',
+ declaredSource: 'remote-url',
+ });
+ });
+
test('records `denied` and pauses in-memory when syncEnabled is true', async () => {
await initGitWithOrigin();
const probe = fakeProbe({ kind: 'denied', reason: 'no-collaborator' });
@@ -3307,6 +3560,8 @@ interface InternalState {
pullError?: string;
pushErrorCode?: string;
pullErrorCode?: string;
+ pullInFlight: boolean;
+ pushInFlight: boolean;
gitHandle: () => unknown;
handleError: (classified: ReturnType<typeof classifyGitError>, op: 'push' | 'pull') => void;
}
@@ -3394,26 +3649,177 @@ describe('SyncEngine auth-error recovery', () => {
await engine.notifyCredentialsChanged();
expect(engine.getStatus().state).toBe(before);
});
+
+ // The not-found park is the one auth state whose badge withholds Sign in
+ // (sign-in cannot restore a deleted repo), and its repairs — declaring the
+ // right account, restoring the repo — all happen outside the app, firing no
+ // credential-changed signal. A manual trigger is the user's explicit retry
+ // signal, so it must un-park; a re-failure just re-parks.
+ test('a manual trigger clears the identity-ambiguous not-found park', async () => {
+ const engine = makeEngine({ syncEnabled: true });
+ const internal = engine as unknown as InternalState;
+ internal.state = 'auth-error';
+ internal.pausedReason = 'auth-error';
+ internal.pushErrorCode = 'auth-not-found-as-identity';
+ expect(engine.getStatus().state).toBe('auth-error');
+
+ await engine.trigger('sync');
+
+ const status = engine.getStatus();
+ expect(status.state).not.toBe('auth-error');
+ expect(status.pausedReason).toBeUndefined();
+ expect(status.pushErrorCode).toBeUndefined();
+ await engine.destroy();
+ });
+
+ test('a manual trigger keeps every other auth park parked', async () => {
+ const engine = makeEngine({ syncEnabled: true });
+ const internal = engine as unknown as InternalState;
+ internal.state = 'auth-error';
+ internal.pausedReason = 'auth-error';
+ internal.pushErrorCode = 'auth-401';
+
+ await engine.trigger('sync');
+
+ expect(engine.getStatus().state).toBe('auth-error');
+ expect(engine.getStatus().pausedReason).toBe('auth-error');
+ await engine.destroy();
+ });
+
+ test('a pull-side not-found park clears on manual trigger too', async () => {
+ const engine = makeEngine({ syncEnabled: true });
+ const internal = engine as unknown as InternalState;
+ internal.state = 'auth-error';
+ internal.pausedReason = 'auth-error';
+ internal.pullErrorCode = 'auth-not-found-as-identity';
+
+ await engine.trigger('sync');
+
+ const status = engine.getStatus();
+ expect(status.state).not.toBe('auth-error');
+ expect(status.pausedReason).toBeUndefined();
+ expect(status.pullErrorCode).toBeUndefined();
+ await engine.destroy();
+ });
+
+ // Both background loops die when a park lands (the first tick early-returns
+ // before the finally that chains the next timer), and the cycles a trigger
+ // runs re-arm only their own direction. The un-park must revive both — this
+ // drives `trigger('push')` and then watches a PULL actually run, which only
+ // happens if the un-park re-armed the pull loop it never touched directly.
+ test('un-parking via trigger(push) revives the pull loop', async () => {
+ const git = simpleGit(projectDir);
+ await git.init(['--initial-branch=main']);
+ await git.raw('config', 'user.name', 'Test');
+ await git.raw('config', 'user.email', '[email protected]');
+ writeFileSync(join(projectDir, 'README.md'), '# Test\n');
+ await git.add('.');
+ await git.commit('Initial');
+ const bareDir = join(tmpDir, 'unpark-bare.git');
+ mkdirSync(bareDir, { recursive: true });
+ await simpleGit(bareDir).init(true);
+ await git.addRemote('origin', bareDir);
+ await git.push(['--set-upstream', 'origin', 'main']);
+
+ // Short pull interval so the re-armed background loop is observable: the
+ // un-park schedules with the NORMAL delay (an immediate timer would race
+ // the cycles trigger() runs inline), and `trigger('push')` never runs a
+ // pull itself — so a pull completing here can only come from the timer
+ // the un-park re-armed.
+ const engine = new SyncEngine({
+ projectDir,
+ contentDir,
+ contentFilter: stubContentFilter,
+ syncEnabled: true,
+ pullIntervalSeconds: 0.05,
+ });
+ const internal = engine as unknown as InternalState;
+ internal.state = 'auth-error';
+ internal.pausedReason = 'auth-error';
+ internal.pushErrorCode = 'auth-not-found-as-identity';
+
+ await engine.trigger('push');
+ expect(engine.getStatus().state).not.toBe('auth-error');
+
+ const deadline = Date.now() + 5000;
+ while (engine.getStatus().lastFetchUtc === null) {
+ if (Date.now() > deadline) throw new Error('pull loop never ran after trigger(push)');
+ await new Promise((r) => setTimeout(r, 10));
+ }
+ await engine.destroy();
+ });
+
+ // The un-park's cache flush is load-bearing: without it the retry replays a
+ // fallback token (and a declared account) cached before the user's
+ // out-of-band fix.
+ test('a manual trigger on the not-found park flushes both identity caches', async () => {
+ await initGitWithOrigin();
+ const detect = recordDetectGh({ available: true, token: 'gho_relayed' });
+ let urlmatchCalls = 0;
+ const probe = fakeProbe({ kind: 'allowed' });
+ const engine = new SyncEngine({
+ projectDir,
+ contentDir,
+ contentFilter: stubContentFilter,
+ // Off-mode: `runPushCycle` returns at its mode gate, so the trigger
+ // below exercises the un-park (and its flush) without reaching git —
+ // no network against the github.com origin the resolver needs.
+ syncEnabled: false,
+ detectGh: detect.fn,
+ _readCredentialUrlMatch: () => {
+ urlmatchCalls++;
+ return null;
+ },
+ checkPushPermissionFn: probe.fn,
+ });
+ const internal = engine as unknown as InternalState;
+
+ internal.gitHandle();
+ const detectAfterPrime = detect.calls();
+ const urlmatchAfterPrime = urlmatchCalls;
+ expect(detectAfterPrime).toBeGreaterThan(0);
+ expect(urlmatchAfterPrime).toBeGreaterThan(0);
+ internal.gitHandle();
+ expect(detect.calls()).toBe(detectAfterPrime);
+ expect(urlmatchCalls).toBe(urlmatchAfterPrime);
+
+ internal.state = 'auth-error';
+ internal.pausedReason = 'auth-error';
+ internal.pushErrorCode = 'auth-not-found-as-identity';
+ await engine.trigger('push');
+
+ internal.gitHandle();
+ expect(detect.calls()).toBeGreaterThan(detectAfterPrime);
+ expect(urlmatchCalls).toBeGreaterThan(urlmatchAfterPrime);
+ await engine.destroy();
+ });
});
// ─── gh-token credential relay ────────────────────────────────────────────────
-/** A `detectGh` recorder: counts calls and captures the host argument. */
-function recordDetectGh(result: ReturnType<DetectGhFn>): {
+/** A `detectGh` recorder: counts calls and captures the host + login arguments. */
+function recordDetectGh(
+ result: ReturnType<DetectGhFn> | ((host?: string, login?: string) => ReturnType<DetectGhFn>),
+): {
fn: DetectGhFn;
calls: () => number;
lastHost: () => string | undefined;
+ logins: () => Array<string | undefined>;
} {
let calls = 0;
let lastHost: string | undefined;
+ const logins: Array<string | undefined> = [];
return {
- fn: (host?: string) => {
+ fn: (host?: string, options?: { login?: string }) => {
+ const login = options?.login;
calls++;
lastHost = host;
- return result;
+ logins.push(login);
+ return typeof result === 'function' ? result(host, login) : result;
},
calls: () => calls,
lastHost: () => lastHost,
+ logins: () => logins,
};
}
@@ -3509,7 +3915,254 @@ describe('SyncEngine gh-token credential relay', () => {
});
});
-// ─── Sync mode representation ─────────────────────────────────────────────────
+// ─── Declared-account identity resolution ─────────────────────────────────────
+
+describe('SyncEngine declared-account resolution', () => {
+ /** A credential-config lookup whose spawns the test can count. */
+ function countingUrlMatch(response: string | null): {
+ fn: CredentialUrlMatchReader;
+ calls: () => number;
+ } {
+ let calls = 0;
+ return {
+ fn: () => {
+ calls += 1;
+ return response;
+ },
+ calls: () => calls,
+ };
+ }
+
+ function makeAccountEngine(
+ detect: DetectGhFn,
+ readUrlMatch: CredentialUrlMatchReader,
+ detectGhAccounts?: DetectGhAccountsFn,
+ ) {
+ return new SyncEngine({
+ projectDir,
+ contentDir,
+ contentFilter: stubContentFilter,
+ syncEnabled: true,
+ detectGh: detect,
+ detectGhAccounts,
+ _readCredentialUrlMatch: readUrlMatch,
+ });
+ }
+
+ /** Honors any requested account; answers login-less requests as the active account. */
+ const honorRequested = (_host?: string, login?: string): ReturnType<DetectGhFn> =>
+ login
+ ? { available: true, token: `gho_${login}`, resolvedLogin: login }
+ : { available: true, token: 'gho_active' };
+
+ test('threads the URL-declared account into gh and names it in the relay env', async () => {
+ await initGitWithOrigin('https://[email protected]/mona/kb.git');
+ const detect = recordDetectGh(honorRequested);
+ const urlMatch = countingUrlMatch(null);
+ const engine = makeAccountEngine(detect.fn, urlMatch.fn);
+
+ const handle = (engine as unknown as { gitHandle: () => GitHandle }).gitHandle();
+
+ expect(detect.logins()).toEqual(['alice']);
+ expect(detect.lastHost()).toBe('github.com');
+ expect(handle.env.OK_GH_TOKEN).toBe('gho_alice');
+ expect(handle.env.OK_GH_TOKEN_LOGIN).toBe('alice');
+ // The URL names the account outright — the credential-config step never runs.
+ expect(urlMatch.calls()).toBe(0);
+ });
+
+ test('an org-owned origin with no declared account resolves exactly as before', async () => {
+ await initGitWithOrigin('https://github.com/inkeep/kb.git');
+ const detect = recordDetectGh(honorRequested);
+ const urlMatch = countingUrlMatch(null);
+ const engine = makeAccountEngine(detect.fn, urlMatch.fn);
+
+ const handle = (engine as unknown as { gitHandle: () => GitHandle }).gitHandle();
+
+ // The owner ("inkeep") is never an account selector: gh is asked for the
+ // host's active account, exactly as before declared-account resolution.
+ expect(detect.logins()).toEqual([undefined]);
+ expect(detect.lastHost()).toBe('github.com');
+ expect(handle.env.OK_GH_TOKEN).toBe('gho_active');
+ expect('OK_GH_TOKEN_LOGIN' in handle.env).toBe(false);
+ });
+
+ test('the credential-config lookup runs once per window across many handles', async () => {
+ await initGitWithOrigin('https://github.com/inkeep/kb.git');
+ const detect = recordDetectGh(honorRequested);
+ const urlMatch = countingUrlMatch(null);
+ const engine = makeAccountEngine(detect.fn, urlMatch.fn);
+ const internal = engine as unknown as { gitHandle: () => GitHandle };
+
+ internal.gitHandle();
+ internal.gitHandle();
+ internal.gitHandle();
+
+ expect(urlMatch.calls()).toBe(1);
+ expect(detect.calls()).toBe(1);
+ });
+
+ test('a remote-URL account edit takes effect on the next handle, no restart', async () => {
+ const git = await initGitWithOrigin('https://[email protected]/mona/kb.git');
+ const detect = recordDetectGh(honorRequested);
+ const engine = makeAccountEngine(detect.fn, countingUrlMatch(null).fn);
+ const internal = engine as unknown as { gitHandle: () => GitHandle };
+
+ expect(internal.gitHandle().env.OK_GH_TOKEN_LOGIN).toBe('alice');
+ await git.raw('remote', 'set-url', 'origin', 'https://[email protected]/mona/kb.git');
+ expect(internal.gitHandle().env.OK_GH_TOKEN_LOGIN).toBe('bob');
+ expect(detect.logins()).toEqual(['alice', 'bob']);
+ });
+
+ test('a declared account gh cannot serve warns once per miss and recovers', async () => {
+ await initGitWithOrigin('https://[email protected]/mona/kb.git');
+ let honor = false;
+ const detect = recordDetectGh((_host, login) => {
+ if (!login) return { available: true, token: 'gho_active' };
+ return honor
+ ? { available: true, token: 'gho_alice', resolvedLogin: login }
+ : { available: true, token: 'gho_active', fallback: true };
+ });
+ const engine = makeAccountEngine(detect.fn, countingUrlMatch(null).fn);
+ const internal = engine as unknown as { gitHandle: () => GitHandle };
+ const logs = captureSyncLogs();
+ const missWarns = () =>
+ logs.entries.filter((e) => e.level === 'warn' && e.msg.includes('declared GitHub account'));
+
+ try {
+ const handle = internal.gitHandle();
+ internal.gitHandle();
+ internal.gitHandle();
+
+ // One warning for the whole burst, naming the miss — and the relay env
+ // does not claim the account that never produced the token.
+ expect(missWarns()).toHaveLength(1);
+ expect(missWarns()[0]?.data).toMatchObject({
+ host: 'github.com',
+ declaredLogin: 'alice',
+ declaredSource: 'remote-url',
+ });
+ expect(handle.env.OK_GH_TOKEN).toBe('gho_active');
+ expect('OK_GH_TOKEN_LOGIN' in handle.env).toBe(false);
+
+ // The user signs alice in; a credential change drops the token cache.
+ honor = true;
+ await engine.notifyCredentialsChanged();
+ expect(internal.gitHandle().env.OK_GH_TOKEN_LOGIN).toBe('alice');
+ expect(missWarns()).toHaveLength(1);
+
+ // A later regression is a new episode and earns a new warning.
+ honor = false;
+ await engine.notifyCredentialsChanged();
+ internal.gitHandle();
+ expect(missWarns()).toHaveLength(2);
+ } finally {
+ logs.restore();
+ }
+ });
+
+ // The strictly worse miss: the declared account produced no token AT ALL.
+ // The failure that follows would otherwise carry no record of the
+ // declaration that led there — this warning is that record.
+ test('a declared account with no gh token at all still warns once', async () => {
+ await initGitWithOrigin('https://[email protected]/mona/kb.git');
+ const detect = recordDetectGh(() => ({ available: false }));
+ const engine = makeAccountEngine(detect.fn, countingUrlMatch(null).fn);
+ const internal = engine as unknown as { gitHandle: () => GitHandle };
+ const logs = captureSyncLogs();
+ const missWarns = () =>
+ logs.entries.filter((e) => e.level === 'warn' && e.msg.includes('declared GitHub account'));
+
+ try {
+ const handle = internal.gitHandle();
+ internal.gitHandle();
+
+ expect(missWarns()).toHaveLength(1);
+ expect(missWarns()[0]?.msg).toContain('no gh token');
+ expect(missWarns()[0]?.data).toMatchObject({
+ host: 'github.com',
+ declaredLogin: 'alice',
+ declaredSource: 'remote-url',
+ });
+ expect('OK_GH_TOKEN' in handle.env).toBe(false);
+ } finally {
+ logs.restore();
+ }
+ });
+
+ test('the fallback warning names the active account that answered instead', async () => {
+ await initGitWithOrigin('https://[email protected]/mona/kb.git');
+ const detect = recordDetectGh((_host, login) =>
+ login
+ ? { available: true, token: 'gho_active', fallback: true }
+ : { available: true, token: 'gho_active' },
+ );
+ const accounts: DetectGhAccountsFn = () => [{ login: 'bob', active: true }];
+ const engine = makeAccountEngine(detect.fn, countingUrlMatch(null).fn, accounts);
+ const internal = engine as unknown as { gitHandle: () => GitHandle };
+ const logs = captureSyncLogs();
+
+ try {
+ internal.gitHandle();
+ const warn = logs.entries.find(
+ (e) => e.level === 'warn' && e.msg.includes('declared GitHub account'),
+ );
+ expect(warn?.data).toMatchObject({ declaredLogin: 'alice', resolvedLogin: 'bob' });
+ } finally {
+ logs.restore();
+ }
+ });
+
+ test('a throwing accounts listing costs the warning its name, not the handle its token', async () => {
+ await initGitWithOrigin('https://[email protected]/mona/kb.git');
+ const detect = recordDetectGh((_host, login) =>
+ login
+ ? { available: true, token: 'gho_active', fallback: true }
+ : { available: true, token: 'gho_active' },
+ );
+ const accounts: DetectGhAccountsFn = () => {
+ throw new Error('gh exploded');
+ };
+ const engine = makeAccountEngine(detect.fn, countingUrlMatch(null).fn, accounts);
+ const internal = engine as unknown as { gitHandle: () => GitHandle };
+ const logs = captureSyncLogs();
+
+ try {
+ const handle = internal.gitHandle();
+ // The token path is unaffected by the diagnostic failure...
+ expect(handle.env.OK_GH_TOKEN).toBe('gho_active');
+ // ...the miss warning still fires, unnamed...
+ const miss = logs.entries.find(
+ (e) => e.level === 'warn' && e.msg.includes('declared GitHub account'),
+ );
+ expect(miss?.data).toMatchObject({ declaredLogin: 'alice' });
+ expect((miss?.data as { resolvedLogin?: string }).resolvedLogin).toBeUndefined();
+ // ...and the listing failure itself is on the record, mirroring the
+ // probe path's twin.
+ const failed = logs.entries.find(
+ (e) => e.level === 'warn' && e.msg.includes('detectGhAccounts failed'),
+ );
+ expect(failed?.data).toMatchObject({ host: 'github.com' });
+ } finally {
+ logs.restore();
+ }
+ });
+
+ test('the auth tier resolves the same declared account as git handles', async () => {
+ await initGitWithOrigin('https://[email protected]/mona/kb.git');
+ const detect = recordDetectGh(honorRequested);
+ const engine = makeAccountEngine(detect.fn, countingUrlMatch(null).fn);
+
+ const tier = await (
+ engine as unknown as { resolveAuthTier: () => Promise<string> }
+ ).resolveAuthTier();
+
+ // Same resolution, same cache key — a tier probe must not spawn gh a
+ // second time for an account the handles already resolved.
+ expect(tier).toBe('authenticated');
+ expect(detect.logins()).toEqual(['alice']);
+ });
+});
describe('SyncEngine sync mode', () => {
test('constructing with a mode reports it in status', () => {
diff --git a/packages/server/src/sync-engine.ts b/packages/server/src/sync-engine.ts
index 81af810ed..d4cfdfef1 100644
--- a/packages/server/src/sync-engine.ts
+++ b/packages/server/src/sync-engine.ts
@@ -42,11 +42,18 @@ import {
} from './error-classification.ts';
import { tracedUnlinkSync, tracedWriteFileSync } from './fs-traced.ts';
import { createGhTokenSource, type GhTokenSource } from './gh-token-source.ts';
-import { applyGitEnv, createGitInstance, type GitHandle, withParentLock } from './git-handle.ts';
+import {
+ applyGitEnv,
+ createGitInstance,
+ type GitHandle,
+ type RelayGhToken,
+ withParentLock,
+} from './git-handle.ts';
import { resolveGitIdentity } from './git-identity.ts';
import { listNames } from './git-paths.ts';
import {
type CheckPushPermissionOptions,
+ type DetectGhAccountsFn,
type DetectGhFn,
checkPushPermission as defaultCheckPushPermission,
type ProbeTokenStore,
@@ -62,11 +69,17 @@ import {
} from './mcp-config-reconciler.ts';
import { toPosix } from './path-utils.ts';
import {
- originGitHubHost,
readOriginGitHubRepo,
readSyncRemoteInfo,
type SyncRemoteInfo,
+ sameGitHubLogin,
} from './share/git-context.ts';
+import {
+ type CachedGitHubAccountResolver,
+ type CredentialUrlMatchReader,
+ createCachedGitHubAccountResolver,
+ type GitHubAccount,
+} from './share/github-account.ts';
import { assertRealpathWithinDir } from './symlink-guard.ts';
import {
computeRemainingMs,
@@ -160,7 +173,7 @@ export type SyncState =
*/
export type PushPermissionStatus =
| { checkStatus: 'allowed' }
- | {
+ | ({
checkStatus: 'denied';
// Both payload unions derive structurally from the source-of-truth
// `PushPermission` in github-permissions.ts so a code added there can't
@@ -168,7 +181,10 @@ export type PushPermissionStatus =
// sync-seed.ts still needs a manual matching update; its round-trip
// test is the runtime net for that half.
deniedReason: Extract<PushPermission, { kind: 'denied' }>['reason'];
- }
+ } & Pick<
+ Extract<PushPermission, { kind: 'denied' }>,
+ 'resolvedLogin' | 'declaredLogin' | 'declaredSource'
+ >)
| {
checkStatus: 'unknown';
unknownError?: Extract<PushPermission, { kind: 'unknown' }>['error'];
@@ -177,7 +193,15 @@ export type PushPermissionStatus =
/** Flatten the tagged `PushPermission` from `github-permissions.ts` to wire shape. */
function pushPermissionStatusFrom(p: PushPermission): PushPermissionStatus {
if (p.kind === 'allowed') return { checkStatus: 'allowed' };
- if (p.kind === 'denied') return { checkStatus: 'denied', deniedReason: p.reason };
+ if (p.kind === 'denied') {
+ return {
+ checkStatus: 'denied',
+ deniedReason: p.reason,
+ ...(p.resolvedLogin !== undefined ? { resolvedLogin: p.resolvedLogin } : {}),
+ ...(p.declaredLogin !== undefined ? { declaredLogin: p.declaredLogin } : {}),
+ ...(p.declaredSource !== undefined ? { declaredSource: p.declaredSource } : {}),
+ };
+ }
return { checkStatus: 'unknown', unknownError: p.error };
}
@@ -190,7 +214,12 @@ function pushPermissionStatusEqual(
if (a === null || b === null) return false;
if (a.checkStatus !== b.checkStatus) return false;
if (a.checkStatus === 'denied' && b.checkStatus === 'denied') {
- return a.deniedReason === b.deniedReason;
+ return (
+ a.deniedReason === b.deniedReason &&
+ a.resolvedLogin === b.resolvedLogin &&
+ a.declaredLogin === b.declaredLogin &&
+ a.declaredSource === b.declaredSource
+ );
}
if (a.checkStatus === 'unknown' && b.checkStatus === 'unknown') {
return a.unknownError === b.unknownError;
@@ -327,8 +356,13 @@ interface SyncEngineOptions {
syncEnabled?: boolean;
/** Ordered credential config values for simple-git (e.g. ['credential.helper=', 'credential.helper=!…']). */
credentialConfig?: string[];
- /** CC1 broadcaster for sync-status channel signals. */
- cc1Broadcaster?: CC1Broadcaster | null;
+ /**
+ * CC1 broadcaster for sync-status channel signals. Narrowed to the one
+ * member the engine calls so a test can inject `{ signal }` without
+ * casting past the class's private fields; the real broadcaster stays
+ * assignable.
+ */
+ cc1Broadcaster?: Pick<CC1Broadcaster, 'signal'> | null;
/** Called on every state transition. */
onStateChange?: (state: SyncState) => void;
/**
@@ -395,6 +429,18 @@ interface SyncEngineOptions {
* falls through to Tier B/C or anonymous.
*/
detectGh?: DetectGhFn;
+ /**
+ * gh account listing for naming the identity behind a probe denial — same
+ * package-cycle seam as `detectGh`. Omit when no auth source is wired;
+ * denials then go unnamed, nothing else changes.
+ */
+ detectGhAccounts?: DetectGhAccountsFn;
+ /**
+ * Injectable `git config --get-urlmatch` reader for the declared-account
+ * resolution behind every git handle, so tests can count or script the one
+ * subprocess that step spawns. Default: the real lookup.
+ */
+ _readCredentialUrlMatch?: CredentialUrlMatchReader;
/**
* Tier B/C credential store, structurally compatible with cli's `TokenStore`.
* Omit when no auth source is wired.
@@ -491,7 +537,7 @@ export class SyncEngine {
*/
private mode: SyncMode;
private credentialConfig: string[];
- private cc1Broadcaster: CC1Broadcaster | null;
+ private cc1Broadcaster: Pick<CC1Broadcaster, 'signal'> | null;
private onStateChange: ((state: SyncState) => void) | undefined;
private onContentConflictsDetected: ((files: string[]) => void | Promise<void>) | undefined;
private onContentConflictsResolved: ((files: string[]) => void | Promise<void>) | undefined;
@@ -505,12 +551,27 @@ export class SyncEngine {
| undefined;
private mcpTomlEditor: NativeTomlMcpEditor | undefined;
private detectGh: DetectGhFn | undefined;
+
+ private detectGhAccounts: DetectGhAccountsFn | undefined;
/**
* Resolves + caches the gh token relayed to the credential helper so sync
* authenticates via the same source clone does (gh-first). Built from the
* injected `detectGh`; returns null throughout when gh is unavailable.
*/
private ghTokenSource: GhTokenSource;
+ /**
+ * Resolves + caches which GitHub account the origin declares (remote-URL
+ * userinfo, then `credential.<url>.username`), so the token above is
+ * requested for the account the user bound to this remote rather than for
+ * whichever gh account happens to be active.
+ */
+ private ghAccountResolver: CachedGitHubAccountResolver;
+ /**
+ * Dedup key for the declared-account-miss warning: set while the declared
+ * account is not producing the relayed token, cleared on recovery. Keeps the
+ * warning to one line per continuous miss instead of one per git handle.
+ */
+ private declaredAccountWarnKey: string | undefined;
private tokenStore: ProbeTokenStore | null | undefined;
private checkPushPermissionFn: (opts: CheckPushPermissionOptions) => Promise<PushPermission>;
/**
@@ -591,7 +652,11 @@ export class SyncEngine {
this.checkpointBeforeOverlayRestore = options.checkpointBeforeOverlayRestore;
this.mcpTomlEditor = options.mcpTomlEditor;
this.detectGh = options.detectGh;
+ this.detectGhAccounts = options.detectGhAccounts;
this.ghTokenSource = createGhTokenSource(options.detectGh);
+ this.ghAccountResolver = createCachedGitHubAccountResolver({
+ _readCredentialUrlMatch: options._readCredentialUrlMatch,
+ });
this.tokenStore = options.tokenStore;
this.checkPushPermissionFn = options.checkPushPermissionFn ?? defaultCheckPushPermission;
this.statePath = resolve(getLocalDir(this.projectDir), 'sync-state.json');
@@ -601,31 +666,138 @@ export class SyncEngine {
}
/**
- * Host the relayed gh token authenticates: the origin remote's GitHub host
- * (github.com or GHES), falling back to github.com when the origin is
- * missing or a non-GitHub forge (the relay is then harmless surplus).
- * Resolved per handle from `.git/config` — a few small file reads, noise
- * next to the subprocess each handle spawns — so a remote swap mid-session
- * is picked up without a restart. The token stays cached per host in
- * `ghTokenSource`.
+ * The origin's declared GitHub account plus the host the relayed token must
+ * authenticate: the remote's GitHub host (github.com or GHES), falling back
+ * to github.com when the origin is missing or a non-GitHub forge (the relay
+ * is then harmless surplus — the helper only serves it to a matching host).
+ * Resolved per call from `.git/config` — a few small file reads, noise next
+ * to the subprocess each handle spawns — so a remote swap mid-session,
+ * including a userinfo edit that changes the declared account, is picked up
+ * without a restart. The subprocess-backed credential-config step stays
+ * cached per origin URL in `ghAccountResolver`.
+ */
+ private syncGhTarget(): { account: GitHubAccount; host: string } {
+ const account = this.ghAccountResolver.resolve(this.projectDir);
+ return { account, host: account.host ?? 'github.com' };
+ }
+
+ /**
+ * The gh token relayed to the credential helper, requested for the origin's
+ * declared account when one is named. A declared account gh cannot serve
+ * degrades to the active account's token (never to no credential), which
+ * `noteDeclaredAccountOutcome` records. The token stays cached per host +
+ * account in `ghTokenSource`.
+ */
+ private resolveRelayGhToken(): RelayGhToken | null {
+ const { account, host } = this.syncGhTarget();
+ const relay = this.ghTokenSource.get(host, account.login);
+ this.noteDeclaredAccountOutcome(account, host, relay);
+ return relay;
+ }
+
+ /**
+ * Warn — once per continuous miss, not once per handle — when the account
+ * the user declared for this origin did not produce the relayed token. Two
+ * shapes of miss: the relay fell back to the active gh account (the push
+ * may then succeed as that identity, making this warning the only trace),
+ * or the declared account produced no token at all (the strictly worse
+ * outcome — the failure that follows would otherwise carry no record of
+ * the declaration that led there). The fallback identity is resolved via
+ * `detectGhAccounts` only on the miss TRANSITION, never per handle — an
+ * account-list spawn per handle is the amplification the token cache
+ * exists to prevent, so a mid-miss active-account switch keeps the
+ * original warning rather than re-warning. Logins are
+ * unbounded-cardinality and belong in pino fields only, never in OTel
+ * span or metric attributes.
+ */
+ private noteDeclaredAccountOutcome(
+ account: GitHubAccount,
+ host: string,
+ relay: RelayGhToken | null,
+ ): void {
+ const declared = account.login;
+ // Resolve the login that actually produced the token BEFORE deciding, the
+ // same ordering `withDeniedIdentity` uses on the probe path: a fallback
+ // relay carries no login, so comparing it directly would report every
+ // fallback as a miss — including the casing-only case, where the active
+ // account IS the declared one and GitHub treats the two as identical.
+ const resolvedLogin = relay === null ? undefined : (relay.login ?? this.activeGhLogin(host));
+ const missed =
+ declared !== undefined && (relay === null || !sameGitHubLogin(resolvedLogin, declared));
+ if (!missed) {
+ this.declaredAccountWarnKey = undefined;
+ return;
+ }
+ const key = `${host}\0${declared}\0${account.source}\0${relay === null ? 'none' : 'fallback'}`;
+ if (key !== this.declaredAccountWarnKey) {
+ if (relay === null) {
+ log.warn(
+ { host, declaredLogin: declared, declaredSource: account.source },
+ '[sync] declared GitHub account produced no gh token — git runs with no relayed credential',
+ );
+ } else {
+ log.warn(
+ {
+ host,
+ declaredLogin: declared,
+ declaredSource: account.source,
+ resolvedLogin,
+ },
+ '[sync] declared GitHub account did not produce the gh token — using the active account',
+ );
+ }
+ }
+ this.declaredAccountWarnKey = key;
+ }
+
+ /**
+ * Parked on the repository-not-found masquerade. Keyed on `pausedReason` as
+ * well as `state` because the retryable arm transitions to `offline`
+ * without clearing the reason, and the UI surfaces key on the reason — so a
+ * `state`-only test would leave `trigger()` unable to un-park exactly the
+ * state the surfaces are already rendering as not-found. Shared by
+ * `trigger()` and the probe-demotion guard so the two cannot drift.
+ */
+ private parkedOnAmbiguousNotFound(): boolean {
+ return (
+ (this.state === 'auth-error' || this.pausedReason === 'auth-error') &&
+ (this.pushErrorCode === 'auth-not-found-as-identity' ||
+ this.pullErrorCode === 'auth-not-found-as-identity')
+ );
+ }
+
+ /**
+ * Best-effort name of the host's active gh account, for the fallback
+ * warning above. Diagnostic only: a listing failure (or an injected
+ * implementation throwing across the package seam) costs the warning its
+ * name, never the handle its token.
*/
- private syncGhTokenHost(): string {
- return originGitHubHost(this.projectDir);
+ private activeGhLogin(host: string): string | undefined {
+ if (!this.detectGhAccounts) return undefined;
+ try {
+ return this.detectGhAccounts(host)?.find((a) => a.active)?.login;
+ } catch (err) {
+ log.warn({ err, host }, '[sync] detectGhAccounts failed — fallback identity stays unnamed');
+ return undefined;
+ }
}
/**
* Single construction point for every git handle the engine spawns. Threads
* the credential config plus the cached gh token (scoped to the origin's
- * GitHub host) so fetch/push authenticate via gh when available. Local-only
- * handles (e.g. `remote -v`, `merge --abort`) carry the token harmlessly —
- * the cache keeps resolution to at most one `gh` spawn per minute
- * regardless of handle count.
+ * GitHub host and requested for its declared account) so fetch/push
+ * authenticate via gh when available. Local-only handles (e.g. `remote -v`,
+ * `merge --abort`) carry the token harmlessly — the caches keep resolution
+ * to at most one `git config` spawn per minute and one `gh` spawn per token
+ * TTL window regardless of handle count (60s when the requested account
+ * answered; a shorter, escalating window after a declared-account miss —
+ * `gh-token-source.ts` owns that contract).
*/
private gitHandle(gitIndexFile?: string): GitHandle {
return createGitInstance(this.projectDir, {
credentialConfig: this.credentialConfig,
gitIndexFile,
- ghToken: this.ghTokenSource.get(this.syncGhTokenHost()) ?? undefined,
+ ghToken: this.resolveRelayGhToken() ?? undefined,
timeoutMs: GIT_BLOCK_TIMEOUT_MS,
});
}
@@ -1045,9 +1217,10 @@ export class SyncEngine {
* stored token is picked up on the next cycle — but the engine parks in
* `auth-error`, where both sync cycles early-return, so the engine makes no
* useful progress while parked until something clears the state. `trigger()`
- * deliberately does NOT clear `auth-error` (retrying with the same missing
- * credential just fails again), and `setEnabled(true)` requires toggling sync
- * off first. This is the dedicated recovery entry point: the auth-login
+ * clears `auth-error` only for the identity-ambiguous not-found park, whose
+ * repairs happen outside the app; for every other subclass a retry with the
+ * same missing credential would just fail again, and `setEnabled(true)`
+ * requires toggling sync off first. This is the dedicated recovery entry point: the auth-login
* success handler calls it so a reconnect resumes sync without a restart.
* No-op unless currently parked on an auth error, so a credential change
* during healthy operation is cheap.
@@ -1059,8 +1232,11 @@ export class SyncEngine {
// user just signed in / switched accounts). Drop it BEFORE the auth-error
// gate below so an account switch during HEALTHY sync is picked up on the
// next already-scheduled cycle, not left stale until the TTL expires. The
- // resume logic below still only runs when parked on an auth error.
+ // account resolution is flushed with it — requesting a fresh token for a
+ // stale account choice would defeat the flush. The resume logic below
+ // still only runs when parked on an auth error.
this.ghTokenSource.invalidate();
+ this.ghAccountResolver.invalidate();
if (this.state !== 'auth-error' && this.pausedReason !== 'auth-error') return;
@@ -1099,6 +1275,37 @@ export class SyncEngine {
this.pausedReason = undefined;
this.clearPullError();
}
+ // A manual trigger also clears the one auth park a re-sign-in cannot fix:
+ // git's "repository not found" with a credential attached. Every repair
+ // for it happens outside the app (declaring the right account, restoring
+ // the deleted repo) and fires no credential-changed signal, and the badge
+ // withholds the Sign in button for it — without this, the only recovery
+ // is an app restart. Other auth subclasses keep the Sign in button, whose
+ // handler resumes via notifyCredentialsChanged; clearing them here would
+ // just re-run a fetch with the same missing credential. Caches are
+ // flushed like the other recovery entry points, so the retry resolves
+ // fresh instead of replaying a fallback token cached before the user's
+ // out-of-band fix; a re-failure simply re-parks.
+ if (this.parkedOnAmbiguousNotFound()) {
+ this.ghTokenSource.invalidate();
+ this.ghAccountResolver.invalidate();
+ this.pausedReason = undefined;
+ this.clearPushError();
+ this.clearPullError();
+ this.transitionTo('idle');
+ // Both background loops died when the park landed: the first tick after
+ // an auth-error early-returns BEFORE the finally that chains the next
+ // timer. The cycles this trigger runs re-arm only their own direction
+ // (`trigger('push')` never reschedules pull), so re-arm both here —
+ // otherwise the un-parked engine reports idle while one direction
+ // silently never runs again. Normal delays, not the immediate
+ // `schedulePull(0)` the credential-change path uses: this trigger runs
+ // its own cycles inline right after, and a 0ms timer would race them
+ // (the inline cycle would then early-return on `pullInFlight` and
+ // resolve the trigger while the pull it reported was still running).
+ this.schedulePull();
+ this.schedulePush();
+ }
// Manual sync is one of the documented refresh triggers for the
// push-permission probe (auth-state change, manual sync, project
// re-open). Fire-and-forget — never blocks the trigger() caller. If
@@ -1371,6 +1578,10 @@ export class SyncEngine {
},
'[sync] push-permission probe dispatching',
);
+ // The same resolution the push path reads (cached resolver), so the
+ // probe can never authenticate as a different identity than the push
+ // it is predicting.
+ const { account } = this.syncGhTarget();
let outcome: PushPermission;
try {
outcome = await this.checkPushPermissionFn({
@@ -1378,7 +1589,9 @@ export class SyncEngine {
repo: origin.repo,
host: origin.host,
transport: origin.transport,
+ account,
detectGh: this.detectGh,
+ detectGhAccounts: this.detectGhAccounts,
tokenStore: this.tokenStore,
});
} catch (err) {
@@ -1403,7 +1616,28 @@ export class SyncEngine {
// persistent-write alternative was rejected at spec time because it
// would silently mutate the user's preference.
let transitioned = false;
- if (next.checkStatus === 'denied' && this.mode === 'full') {
+ // An auth park outranks a probe denial ONLY for the not-found masquerade.
+ // There the park's error code is the more specific diagnosis and the probe
+ // cannot see it. Every other auth subclass is better diagnosed by the
+ // probe — a 403 park plus `denied/no-collaborator` is exactly the
+ // revoked-collaborator case — and `trigger()` clears only the masquerade,
+ // so blocking those demotions would strand the user on "Reconnect
+ // required" behind a sign-in that cannot help. Keyed on `pausedReason` as
+ // well as `state`: the retryable arm transitions to `offline` without
+ // clearing the reason, and the surfaces key on the reason.
+ if (next.checkStatus === 'denied' && this.mode === 'full' && this.parkedOnAmbiguousNotFound()) {
+ // A discarded verdict is otherwise invisible: the park stays, the probe
+ // result is dropped, and nothing records that the two disagreed.
+ log.info(
+ { reason: next.deniedReason, caller },
+ '[sync] probe denial not applied — repository-not-found park is the more specific diagnosis',
+ );
+ }
+ if (
+ next.checkStatus === 'denied' &&
+ this.mode === 'full' &&
+ !this.parkedOnAmbiguousNotFound()
+ ) {
if (this.pausedReason !== 'no-push-permission' || this.state !== 'disabled') {
this.pausedReason = 'no-push-permission';
this.transitionTo('disabled'); // already broadcasts CC1 sync-status
@@ -1693,15 +1927,15 @@ export class SyncEngine {
* Resolve which credential tier the follower fetches as, mirroring the push
* probe's gh → token-store → anonymous order. The probe doesn't surface which
* tier it used, so the engine resolves it from the credential sources it
- * already holds. gh resolution is cached (at most one spawn per minute); the
- * token store is read at most once per pull.
+ * already holds. gh resolution is cached per TTL window (`gh-token-source.ts`
+ * owns the contract, including the shorter declared-account-miss window);
+ * the token store is read at most once per pull.
*/
private async resolveAuthTier(): Promise<PullAuthTier> {
- const host = this.syncGhTokenHost();
- if (this.ghTokenSource.get(host) !== null) return 'authenticated';
+ if (this.resolveRelayGhToken() !== null) return 'authenticated';
if (this.tokenStore) {
try {
- const entry = await this.tokenStore.get(host);
+ const entry = await this.tokenStore.get(this.syncGhTarget().host);
if (entry?.token) return 'authenticated';
} catch (err) {
// A token-store backend can throw on read (corrupted keyring, EACCES).
@@ -3793,8 +4027,12 @@ export class SyncEngine {
// The relayed gh token may be the stale credential that just failed
// (revoked, or a `gh auth logout` since we cached). Drop the cache so the
// next cycle re-resolves — picking up a fresh `gh auth login` without
- // waiting out the TTL.
+ // waiting out the TTL. The account resolution is dropped with it: the
+ // failure may stem from the account choice itself (a fresh
+ // `credential.<url>.username` edit), and re-requesting a token for the
+ // stale choice would waste the flush.
this.ghTokenSource.invalidate();
+ this.ghAccountResolver.invalidate();
this.transitionTo('auth-error');
this.pausedReason = 'auth-error';
} else if (classified.class === 'semantic' && classified.subclass === 'protected-branch') {