Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(sync): neutralize ambient credential helpers (PRD-8063) (#3612)

miles-kt-inkeep8f64ab81f39e
diff --git a/.changeset/sync-credential-helper-order.md b/.changeset/sync-credential-helper-order.md
new file mode 100644
index 000000000..526651cb1
--- /dev/null
+++ b/.changeset/sync-credential-helper-order.md
@@ -0,0 +1,10 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Git sync no longer gets stuck behind a stale credential stored elsewhere on your machine. Git lets several credential helpers be configured at once and uses the first one that answers, and macOS installs its own keychain helper system-wide by default. Sync was adding OK's helper to the end of that list, so on most Macs the keychain answered first and OK's own credential was never used. If whatever the keychain held had expired, GitHub rejected it, sync stopped, and the app showed "GitHub authentication failed" even though OK had a perfectly good token in hand. Sync now clears the inherited list before adding its own helper, so it authenticates with the credential OK actually resolved. The same approach was already used when cloning a repository; this brings sync in line with it.
+
+Two things worth knowing about who this changes:
+
+- If your project's remote is on GitHub (or GitHub Enterprise) and the only working credential on your machine was one of those ambient helpers, sync will now ask you to sign in rather than quietly borrowing that credential. Signing in from the sync panel restores it.
+- If your remote is on GitLab, Bitbucket, or another non-GitHub host, nothing changes. OK cannot issue a credential for those hosts, so it leaves your existing credential helper alone rather than clearing the one you are actually syncing with.
diff --git a/packages/cli/src/auth/resolve-auth.ts b/packages/cli/src/auth/resolve-auth.ts
index f0bd1611d..d7f1ff2eb 100644
--- a/packages/cli/src/auth/resolve-auth.ts
+++ b/packages/cli/src/auth/resolve-auth.ts
@@ -53,7 +53,7 @@ interface ResolveAuthOptions {
* credential helper. `selfCliArgs` is the argv that re-execs the CLI; each
* element is shell-quoted so a bundled path with spaces
* (`/Applications/OpenKnowledge.app/…`) survives git running the `!`-prefixed
- * helper through `sh -c`. Mirrors the sync path's `buildSyncCredentialArgs` —
+ * helper through `sh -c`. Mirrors the sync path's `buildSyncCredentialConfig` —
* the bare `open-knowledge` form this replaces isn't resolvable in the packaged
* desktop app (no such binary on the git subprocess PATH).
*/
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index f92070a59..8521be968 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -597,7 +597,7 @@ import {
isValidBranchName,
} from './git-branch-info.ts';
import { CHECKOUT_HANDLER_TAG, runCheckoutFlow } from './git-checkout.ts';
-import { withParentLock } from './git-handle.ts';
+import { buildSyncCredentialConfig, withParentLock } from './git-handle.ts';
import { writeGitIdentity } from './git-identity.ts';
import { type ApiRouteTable, createApiRequestPipeline } from './http/api-pipeline.ts';
import { catchErrors } from './http/catch-errors.ts';
@@ -715,6 +715,7 @@ import {
type TimelineRescueEntry,
type WriterIdentity,
} from './shadow-repo.ts';
+import { shouldResetAmbientCredentials } from './share/git-context.ts';
import { createSingleFlight } from './single-flight.ts';
import {
linkEditorSkillFolder,
@@ -20209,6 +20210,11 @@ export function createApiExtension(
body.branch,
body.path,
body.kind,
+ {
+ credentialConfig: buildSyncCredentialConfig(localOpCliArgs, {
+ resetAmbient: shouldResetAmbientCredentials(projectDir),
+ }),
+ },
);
const contentStatus =
status.verdict !== 'renamed' || body.contentRootDepth === undefined
@@ -20274,7 +20280,12 @@ export function createApiExtension(
try {
const outcome = await withParentLock(() =>
- runCheckoutFlow(projectDir, body.branch, { fastForward: body.fastForward === true }),
+ runCheckoutFlow(projectDir, body.branch, {
+ fastForward: body.fastForward === true,
+ credentialConfig: buildSyncCredentialConfig(localOpCliArgs, {
+ resetAmbient: shouldResetAmbientCredentials(projectDir),
+ }),
+ }),
);
successResponse(res, 200, CheckoutResponseSchema, outcome, {
handler: CHECKOUT_HANDLER_TAG,
diff --git a/packages/server/src/conflict-storage.ts b/packages/server/src/conflict-storage.ts
index 6a58b6682..e11e76a72 100644
--- a/packages/server/src/conflict-storage.ts
+++ b/packages/server/src/conflict-storage.ts
@@ -187,14 +187,8 @@ export class ConflictStore {
* @param file File path relative to projectDir.
* @param strategy How to resolve.
* @param content Required when strategy === 'content'.
- * @param credentialArgs Credential args for the git handle.
*/
- async resolveConflict(
- file: string,
- strategy: ResolveStrategy,
- content?: string,
- credentialArgs: string[] = [],
- ): Promise<void> {
+ async resolveConflict(file: string, strategy: ResolveStrategy, content?: string): Promise<void> {
const entry = this.conflicts.find((c) => c.file === file);
if (!entry) {
throw new Error(`[conflicts] no conflict tracked for file: ${file}`);
@@ -209,13 +203,14 @@ export class ConflictStore {
// before the merge-native path so its `git checkout --ours/--theirs` +
// `git commit --no-edit` semantics stay untouched.
if (entry.variant === 'working-tree') {
- await this.resolveWorkingTreeConflict(entry, strategy, content, credentialArgs);
+ await this.resolveWorkingTreeConflict(entry, strategy, content);
return;
}
// Dynamic import so CRUD tests don't load simple-git (broken symlink in test env)
+ // No credential config: every git op below is local (checkout/add/rm/commit).
const { createGitInstance } = await import('./git-handle.ts');
- const handle = createGitInstance(this.projectDir, { credentialArgs });
+ const handle = createGitInstance(this.projectDir, { credentialConfig: [] });
switch (strategy) {
case 'mine':
@@ -358,7 +353,6 @@ export class ConflictStore {
entry: ConflictEntry,
strategy: ResolveStrategy,
content: string | undefined,
- credentialArgs: string[],
): Promise<void> {
const projectRoot = resolve(this.projectDir);
const absPath = resolve(projectRoot, entry.file);
@@ -382,7 +376,8 @@ export class ConflictStore {
);
}
const { createGitInstance } = await import('./git-handle.ts');
- const handle = createGitInstance(this.projectDir, { credentialArgs });
+ // Local-only `cat-file` read — no credential config needed.
+ const handle = createGitInstance(this.projectDir, { credentialConfig: [] });
const theirsBytes = await handle.git.raw(['cat-file', 'blob', entry.theirsSha]);
// The realpath guard above ran before this `await`, which yielded the
// event loop; a concurrent pull cycle could have materialized a symlink
diff --git a/packages/server/src/git-branch-info.ts b/packages/server/src/git-branch-info.ts
index 7b8a4ac00..34f500fc2 100644
--- a/packages/server/src/git-branch-info.ts
+++ b/packages/server/src/git-branch-info.ts
@@ -93,7 +93,8 @@ export async function computeBranchInfo(
path: string,
kind: 'doc' | 'folder',
): Promise<BranchInfo> {
- const { git } = createGitInstance(projectDir);
+ // Local-only: symbolic-ref / rev-parse / cat-file against local refs.
+ const { git } = createGitInstance(projectDir, { credentialConfig: [] });
// Fail-fast on non-git directories so the downstream Promise.all doesn't
// swallow "not a git repository" errors via the per-probe catch handlers.
diff --git a/packages/server/src/git-checkout.test.ts b/packages/server/src/git-checkout.test.ts
index b0474433a..cb61b7a41 100644
--- a/packages/server/src/git-checkout.test.ts
+++ b/packages/server/src/git-checkout.test.ts
@@ -93,14 +93,17 @@ describe('createGitInstance locale stabilization', () => {
}
test('spawns git with LANG=C and LC_ALL=C so stderr stays English', () => {
- const handle = createGitInstance('/tmp');
+ const handle = createGitInstance('/tmp', { credentialConfig: [] });
const env = readEnv(handle);
expect(env.LANG).toBe('C');
expect(env.LC_ALL).toBe('C');
});
test('preserves LANG/LC_ALL when GIT_INDEX_FILE is set', () => {
- const handle = createGitInstance('/tmp', { gitIndexFile: '.git/custom-index' });
+ const handle = createGitInstance('/tmp', {
+ gitIndexFile: '.git/custom-index',
+ credentialConfig: [],
+ });
const env = readEnv(handle);
expect(env.LANG).toBe('C');
expect(env.LC_ALL).toBe('C');
@@ -205,7 +208,7 @@ describe('runCheckoutFlow against real git', () => {
await git(main, 'worktree', 'add', '-b', 'feat-bar', wt);
// Now attempt to check out feat-bar from main — git refuses.
- const outcome = await runCheckoutFlow(main, 'feat-bar');
+ const outcome = await runCheckoutFlow(main, 'feat-bar', { credentialConfig: [] });
expect(outcome.ok).toBe(false);
if (!outcome.ok) {
expect(outcome.reason).toBe('branch-in-other-worktree');
@@ -228,7 +231,7 @@ describe('runCheckoutFlow against real git', () => {
await git(main, 'commit', '-m', 'initial');
await git(main, 'branch', 'feat-bar');
- const outcome = await runCheckoutFlow(main, 'feat-bar');
+ const outcome = await runCheckoutFlow(main, 'feat-bar', { credentialConfig: [] });
expect(outcome.ok).toBe(true);
} finally {
rmSync(root, { recursive: true, force: true });
@@ -276,7 +279,7 @@ describe('fastForwardBranchToOrigin (FR9 FF-only pre-checkout update)', () => {
const receiver = setupReceiverWithLocalFeature(t);
advanceOriginFeature(t);
- const outcome = await fastForwardBranchToOrigin(receiver, 'feature');
+ const outcome = await fastForwardBranchToOrigin(receiver, 'feature', []);
expect(outcome).toBe('advanced');
// The local feature ref now points at origin's advanced tip.
expect(t.git(receiver, ['rev-parse', 'refs/heads/feature'])).toBe(
@@ -298,7 +301,7 @@ describe('fastForwardBranchToOrigin (FR9 FF-only pre-checkout update)', () => {
const localBefore = t.git(receiver, ['rev-parse', 'refs/heads/feature']);
advanceOriginFeature(t);
- const outcome = await fastForwardBranchToOrigin(receiver, 'feature');
+ const outcome = await fastForwardBranchToOrigin(receiver, 'feature', []);
expect(outcome).toBe('diverged');
// Nothing mutated — the divergent local ref stands, untouched.
expect(t.git(receiver, ['rev-parse', 'refs/heads/feature'])).toBe(localBefore);
@@ -307,7 +310,7 @@ describe('fastForwardBranchToOrigin (FR9 FF-only pre-checkout update)', () => {
test('already up to date: local branch equals origin, no-op', async () => {
const t = newTriangle();
const receiver = setupReceiverWithLocalFeature(t);
- const outcome = await fastForwardBranchToOrigin(receiver, 'feature');
+ const outcome = await fastForwardBranchToOrigin(receiver, 'feature', []);
expect(outcome).toBe('up-to-date');
});
@@ -320,7 +323,7 @@ describe('fastForwardBranchToOrigin (FR9 FF-only pre-checkout update)', () => {
t.git(t.senderDir, ['push', 'origin', 'feature']);
t.git(t.senderDir, ['checkout', 'main']);
const receiver = t.cloneReceiver();
- const outcome = await fastForwardBranchToOrigin(receiver, 'feature');
+ const outcome = await fastForwardBranchToOrigin(receiver, 'feature', []);
expect(outcome).toBe('up-to-date');
});
@@ -329,7 +332,7 @@ describe('fastForwardBranchToOrigin (FR9 FF-only pre-checkout update)', () => {
const receiver = setupReceiverWithLocalFeature(t);
const localBefore = t.git(receiver, ['rev-parse', 'refs/heads/feature']);
t.git(receiver, ['remote', 'remove', 'origin']);
- const outcome = await fastForwardBranchToOrigin(receiver, 'feature');
+ const outcome = await fastForwardBranchToOrigin(receiver, 'feature', []);
expect(outcome).toBe('unavailable');
expect(t.git(receiver, ['rev-parse', 'refs/heads/feature'])).toBe(localBefore);
});
@@ -339,7 +342,10 @@ describe('fastForwardBranchToOrigin (FR9 FF-only pre-checkout update)', () => {
const receiver = setupReceiverWithLocalFeature(t);
advanceOriginFeature(t);
- const outcome = await runCheckoutFlow(receiver, 'feature', { fastForward: true });
+ const outcome = await runCheckoutFlow(receiver, 'feature', {
+ fastForward: true,
+ credentialConfig: [],
+ });
expect(outcome.ok).toBe(true);
// HEAD switched to feature AND the working tree carries origin's v2 — the
// FF advanced the stale local ref before the checkout landed on it.
@@ -357,7 +363,10 @@ describe('fastForwardBranchToOrigin (FR9 FF-only pre-checkout update)', () => {
t.git(receiver, ['checkout', 'main']);
advanceOriginFeature(t);
- const outcome = await runCheckoutFlow(receiver, 'feature', { fastForward: true });
+ const outcome = await runCheckoutFlow(receiver, 'feature', {
+ fastForward: true,
+ credentialConfig: [],
+ });
expect(outcome.ok).toBe(false);
if (!outcome.ok) expect(outcome.reason).toBe('ff-diverged');
// Checkout was NOT attempted — the receiver is still on main.
@@ -369,7 +378,7 @@ describe('fastForwardBranchToOrigin (FR9 FF-only pre-checkout update)', () => {
const receiver = setupReceiverWithLocalFeature(t);
advanceOriginFeature(t);
- const outcome = await runCheckoutFlow(receiver, 'feature');
+ const outcome = await runCheckoutFlow(receiver, 'feature', { credentialConfig: [] });
expect(outcome.ok).toBe(true);
// Without the flag the branch is not fast-forwarded, so the checkout lands
// on the receiver's stale local tip (v1), not origin's v2.
diff --git a/packages/server/src/git-checkout.ts b/packages/server/src/git-checkout.ts
index 35ff57acf..04a0faed4 100644
--- a/packages/server/src/git-checkout.ts
+++ b/packages/server/src/git-checkout.ts
@@ -152,16 +152,16 @@ export const isBranchNotFoundFetchError = isBranchNotFoundGitError;
export async function runCheckoutFlow(
projectDir: string,
branch: string,
- opts?: { readonly fastForward?: boolean },
+ opts: { readonly fastForward?: boolean; readonly credentialConfig: string[] },
): Promise<CheckoutOutcome> {
- if (opts?.fastForward) {
- const ff = await fastForwardBranchToOrigin(projectDir, branch);
+ if (opts.fastForward) {
+ const ff = await fastForwardBranchToOrigin(projectDir, branch, opts.credentialConfig);
if (ff === 'diverged') {
return { ok: false, reason: 'ff-diverged' };
}
}
- const { git } = createGitInstance(projectDir);
+ const { git } = createGitInstance(projectDir, { credentialConfig: opts.credentialConfig });
const branchIsLocal = await git
.raw(['rev-parse', '--verify', `refs/heads/${branch}`])
@@ -268,8 +268,12 @@ export type FastForwardOutcome = 'advanced' | 'up-to-date' | 'diverged' | 'unava
export async function fastForwardBranchToOrigin(
projectDir: string,
branch: string,
+ credentialConfig: string[],
): Promise<FastForwardOutcome> {
- const { git } = createGitInstance(projectDir, { timeoutMs: FF_FETCH_TIMEOUT_MS });
+ const { git } = createGitInstance(projectDir, {
+ timeoutMs: FF_FETCH_TIMEOUT_MS,
+ credentialConfig,
+ });
const revParse = (ref: string): Promise<string | null> =>
git
diff --git a/packages/server/src/git-dirty.ts b/packages/server/src/git-dirty.ts
index 99a9709b1..4c9afcc21 100644
--- a/packages/server/src/git-dirty.ts
+++ b/packages/server/src/git-dirty.ts
@@ -36,7 +36,8 @@ export async function dirtyFilesOverlapWith(
cwd: string,
targetRef: string,
): Promise<DirtyOverlapResult> {
- const { git } = createGitInstance(cwd);
+ // Local-only: `rev-parse --git-dir` and status reads never reach a remote.
+ const { git } = createGitInstance(cwd, { credentialConfig: [] });
const [dirtyResult, changedResult] = await Promise.allSettled([
listPorcelainPaths(git),
diff --git a/packages/server/src/git-handle.test.ts b/packages/server/src/git-handle.test.ts
index d619279be..001f9935b 100644
--- a/packages/server/src/git-handle.test.ts
+++ b/packages/server/src/git-handle.test.ts
@@ -1,10 +1,19 @@
import { execSync } from 'node:child_process';
-import { mkdtempSync, rmSync } from 'node:fs';
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { createServer as createHttpServer, type Server as HttpServer } from 'node:http';
+import type { AddressInfo } from 'node:net';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import shellQuote from 'shell-quote';
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
-import { applyGitEnv, buildGitEnv, createGitInstance, type GitHandle } from './git-handle.ts';
+import {
+ applyGitEnv,
+ buildGitEnv,
+ buildSyncCredentialConfig,
+ createGitInstance,
+ type GitHandle,
+} from './git-handle.ts';
import { withParentLock } from './git-mutex.ts';
// simple-git's .env(obj) REPLACES the child env, so these tests set/restore
@@ -140,7 +149,7 @@ describe('createGitInstance (credential.helper config)', () => {
test('accepts credential.helper config without throwing', async () => {
const handle = createGitInstance(tmpDir, {
- credentialArgs: ['-c', 'credential.helper=!open-knowledge auth git-credential'],
+ credentialConfig: buildSyncCredentialConfig(['open-knowledge'], { resetAmbient: true }),
});
// Any command triggers simple-git's block-unsafe-operations plugin, which
// scans argv synchronously before spawning git. `--version` is the lightest
@@ -151,7 +160,10 @@ describe('createGitInstance (credential.helper config)', () => {
test('merges author overrides without dropping git auth env', () => {
withEnvEntries({ USERPROFILE: 'C:\\Users\\alice' }, () => {
- const handle = createGitInstance(tmpDir, { gitIndexFile: '.git/custom-index' });
+ const handle = createGitInstance(tmpDir, {
+ gitIndexFile: '.git/custom-index',
+ credentialConfig: [],
+ });
applyGitEnv(handle, {
GIT_AUTHOR_NAME: 'Alice',
GIT_AUTHOR_EMAIL: '[email protected]',
@@ -172,7 +184,7 @@ describe('createGitInstance (credential.helper config)', () => {
execSync('git config commit.gpgsign true', { cwd: tmpDir });
execSync('git config core.autocrlf true', { cwd: tmpDir });
- const handle = createGitInstance(tmpDir);
+ const handle = createGitInstance(tmpDir, { credentialConfig: [] });
expect((await handle.git.raw(['config', '--get', 'commit.gpgsign'])).trim()).toBe('false');
expect((await handle.git.raw(['config', '--get', 'core.autocrlf'])).trim()).toBe('false');
});
@@ -185,17 +197,17 @@ describe('createGitInstance (credential.helper config)', () => {
test('pins credential.interactive off, overriding repo config', async () => {
execSync('git config credential.interactive true', { cwd: tmpDir });
- const handle = createGitInstance(tmpDir);
+ const handle = createGitInstance(tmpDir, { credentialConfig: [] });
expect((await handle.git.raw(['config', '--get', 'credential.interactive'])).trim()).toBe(
'false',
);
});
- test('keeps pinning credential.interactive off alongside a credential.helper arg', async () => {
- // The helper arg is spliced into the same `-c` list; splicing must not
+ test('keeps pinning credential.interactive off alongside credential.helper config', async () => {
+ // The helper config is spread into the same `-c` list; the spread must not
// displace the interactivity pin.
const handle = createGitInstance(tmpDir, {
- credentialArgs: ['-c', 'credential.helper=!open-knowledge auth git-credential'],
+ credentialConfig: buildSyncCredentialConfig(['open-knowledge'], { resetAmbient: true }),
});
expect((await handle.git.raw(['config', '--get', 'credential.interactive'])).trim()).toBe(
'false',
@@ -203,6 +215,169 @@ describe('createGitInstance (credential.helper config)', () => {
});
});
+// Composes the real producer (buildSyncCredentialConfig) with the real consumer
+// (createGitInstance → simple-git → a real git subprocess), so these tests fail
+// if EITHER side breaks the contract: a producer that never emits the
+// `credential.helper=` reset, or a consumer that forwards only part of the
+// produced entries into git's `-c` list. The assertions read what git itself
+// resolves and invokes — not the strings OK builds — because an ambient-helper
+// shadowing bug is invisible to every string-level assertion.
+//
+// POSIX-only: the stub helpers are `sh` scripts and the ambient entry is
+// planted via a quoted shell command. CI for this package runs on POSIX.
+describe.skipIf(process.platform === 'win32')(
+ 'createGitInstance × buildSyncCredentialConfig — ambient helper neutralization',
+ () => {
+ let repoDir: string;
+ let isolatedHome: string;
+
+ beforeEach(() => {
+ repoDir = mkdtempSync(join(tmpdir(), 'ok-sync-cred-repo-'));
+ isolatedHome = mkdtempSync(join(tmpdir(), 'ok-sync-cred-home-'));
+ execSync('git init -q', { cwd: repoDir });
+ });
+
+ afterEach(() => {
+ rmSync(repoDir, { recursive: true, force: true });
+ rmSync(isolatedHome, { recursive: true, force: true });
+ });
+
+ // Cut off the system and global config scopes, for two distinct reasons:
+ // determinism — `git config --get-all` enumerates raw values across every
+ // scope with no reset applied, so a machine's system/global entries (e.g.
+ // macOS's system-wide osxkeychain) would prefix the enumeration test's
+ // exact-equality list; and fail-safety — should the reset regress (the
+ // exact bug these tests exist to catch), a real system helper re-enters
+ // the EFFECTIVE list and the 401 rejection's erase fan-out would reach
+ // the user's real keychain. Isolation keeps a failing run harmless; only
+ // when the code under test is correct does the reset alone exclude it.
+ function isolateAmbientGitConfig(handle: GitHandle): void {
+ applyGitEnv(handle, {
+ GIT_CONFIG_NOSYSTEM: '1',
+ HOME: isolatedHome,
+ XDG_CONFIG_HOME: isolatedHome,
+ });
+ }
+
+ test('git resolves ambient helper, then reset, then OK helper last', async () => {
+ // Repo-local config stands in for an ambient helper: it sits earlier
+ // than command-line `-c` in git's multi-valued accumulation, exactly
+ // like a system/global entry would.
+ execSync("git config credential.helper '!/ambient/stub'", { cwd: repoDir });
+
+ const handle = createGitInstance(repoDir, {
+ credentialConfig: buildSyncCredentialConfig(['open-knowledge'], { resetAmbient: true }),
+ });
+ isolateAmbientGitConfig(handle);
+
+ const raw = await handle.git.raw(['config', '-z', '--get-all', 'credential.helper']);
+ const entries = raw.split('\0').slice(0, -1);
+ // The empty entry is the reset; it must come after every inherited
+ // entry and before OK's helper, and OK's helper must be LAST — a
+ // consumer that forwards only one of the produced entries fails here
+ // whichever one it drops.
+ expect(entries).toEqual(['!/ambient/stub', '', '!open-knowledge auth git-credential']);
+ });
+
+ // No per-test timeout override: the handle's 15s block (inactivity)
+ // timeout needs the workspace default 30s wall so a hung git is killed,
+ // surfaces its rejection, and the log assertions still get to run — a
+ // tighter wall fires first and reports a bare timeout with no evidence.
+ // Mirror of the enumeration test above for a forge OK cannot authenticate:
+ // the ambient helper must SURVIVE, because it is the user's only working
+ // credential and no OK sign-in can replace it.
+ test('non-GitHub origin keeps its ambient helper and gets no reset', async () => {
+ execSync("git config credential.helper '!/ambient/stub'", { cwd: repoDir });
+
+ const handle = createGitInstance(repoDir, {
+ credentialConfig: buildSyncCredentialConfig(['open-knowledge'], { resetAmbient: false }),
+ });
+ isolateAmbientGitConfig(handle);
+
+ const raw = await handle.git.raw(['config', '-z', '--get-all', 'credential.helper']);
+ // Same parse as the enumeration test above: drop only the trailing NUL
+ // terminator, never empties — the empty entry IS the reset, so filtering
+ // empties out would make this assertion unable to fail.
+ const values = raw.split('\0').slice(0, -1);
+
+ // The ambient entry is still first and still reachable, and no empty
+ // reset was injected ahead of OK's helper to neutralise it.
+ expect(values).toEqual(['!/ambient/stub', '!open-knowledge auth git-credential']);
+ });
+
+ test('with an ambient helper configured, git sends `get` to OK helper only', async () => {
+ const ambientLog = join(isolatedHome, 'ambient.log');
+ const okLog = join(isolatedHome, 'ok.log');
+ const ambientHelper = join(isolatedHome, 'ambient-helper.sh');
+ const okCli = join(isolatedHome, 'ok-cli.sh');
+
+ // Both stubs log every invocation and answer `get` with a complete
+ // credential — the ambient one deliberately so: git stops querying at
+ // the first helper that returns a full credential, so if the ambient
+ // helper is still in the resolved list it wins and OK's helper never
+ // sees `get`. That is the field failure this test reproduces.
+ const stubScript = (log: string, user: string): string =>
+ [
+ '#!/bin/sh',
+ `printf '%s\\n' "$*" >> '${log}'`,
+ 'cat > /dev/null',
+ 'case "$*" in',
+ ` *get) printf 'username=${user}\\npassword=${user}-secret\\n' ;;`,
+ 'esac',
+ '',
+ ].join('\n');
+ writeFileSync(ambientHelper, stubScript(ambientLog, 'ambient'), { mode: 0o755 });
+ writeFileSync(okCli, stubScript(okLog, 'ok'), { mode: 0o755 });
+
+ execSync(`git config credential.helper '!${ambientHelper}'`, { cwd: repoDir });
+
+ // Loopback server that 401s everything: forces git through a real
+ // `credential fill` (and the rejection fan-out) without any network.
+ const server: HttpServer = createHttpServer((req, res) => {
+ req.resume();
+ res.writeHead(401, { 'WWW-Authenticate': 'Basic realm="ok-test"' });
+ res.end('auth required');
+ });
+ await new Promise<void>((resolvePromise) => server.listen(0, '127.0.0.1', resolvePromise));
+
+ try {
+ const { port } = server.address() as AddressInfo;
+ execSync(`git remote add origin http://127.0.0.1:${port}/repo.git`, { cwd: repoDir });
+
+ const handle = createGitInstance(repoDir, {
+ credentialConfig: buildSyncCredentialConfig([okCli], { resetAmbient: true }),
+ timeoutMs: 15_000,
+ });
+ isolateAmbientGitConfig(handle);
+
+ // Both credentials are wrong for the always-401 server, so the fetch
+ // fails either way — WHICH helper git consulted is the discriminator.
+ await expect(handle.git.raw(['fetch', 'origin'])).rejects.toThrow();
+
+ const callsIn = (log: string): string[] =>
+ existsSync(log)
+ ? readFileSync(log, 'utf-8')
+ .split('\n')
+ .filter((line) => line !== '')
+ : [];
+ // OK's helper is invoked as `<cli> auth git-credential <op>`, the
+ // ambient one as `<helper> <op>`, so the logged argv lines differ.
+ expect(callsIn(okLog)).toContain('auth git-credential get');
+ // Nothing at all, not merely no `get`: the reset drops the ambient
+ // helper from the EFFECTIVE list, so git cannot invoke it for any
+ // operation. Asserting only on `get` would stay green if a regression
+ // re-admitted the helper for the 401 rejection's `erase` fan-out —
+ // which would wipe the user's real keychain entry on every retry.
+ expect(callsIn(ambientLog)).toEqual([]);
+ } finally {
+ await new Promise<void>((resolvePromise) => {
+ server.close(() => resolvePromise());
+ });
+ }
+ });
+ },
+);
+
describe('withParentLock', () => {
test('serializes concurrent operations in enqueue order', async () => {
const order: number[] = [];
@@ -255,3 +430,123 @@ describe('withParentLock', () => {
// Suppress unused import warnings for lifecycle hooks
void beforeEach;
void afterEach;
+
+describe('buildSyncCredentialConfig()', () => {
+ // Git runs a `!`-prefixed credential helper through the shell, so the helper
+ // string after `!` is whatever the shell tokenizes back out. Parsing it with
+ // shell-quote reproduces the argv git would exec — the load-bearing property.
+ // OK's helper is the LAST credential.helper value in the returned config
+ // (the empty reset precedes it), so select by position-from-the-end rather
+ // than a hard-coded index.
+ const argvFromHelper = (config: string[]): unknown[] => {
+ const helperValues = config
+ .filter((entry) => entry.startsWith('credential.helper='))
+ .map((entry) => entry.slice('credential.helper='.length));
+ const helper = helperValues.at(-1) ?? '';
+ expect(helper.startsWith('!')).toBe(true);
+ const suffix = ' auth git-credential';
+ expect(helper.endsWith(suffix)).toBe(true);
+ return shellQuote.parse(helper.slice(1));
+ };
+
+ test('packaged macOS bundle path survives the shell as one intact token', () => {
+ // Regression: the bundled CLI lives under "/Applications/OpenKnowledge.app/…".
+ // Unquoted, the shell split at the space, tried to exec "/Applications/Open",
+ // returned no credentials, and git failed with "could not read Username …
+ // Device not configured". The path must round-trip as a single argv element.
+ const bundlePath = '/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh';
+ const config = buildSyncCredentialConfig([bundlePath], { resetAmbient: true });
+ expect(argvFromHelper(config)).toEqual([bundlePath, 'auth', 'git-credential']);
+ });
+
+ test('bare command (dev default) stays unquoted', () => {
+ const config = buildSyncCredentialConfig(['open-knowledge'], { resetAmbient: true });
+ expect(config).toEqual([
+ 'credential.helper=',
+ 'credential.helper=!open-knowledge auth git-credential',
+ ]);
+ expect(argvFromHelper(config)).toEqual(['open-knowledge', 'auth', 'git-credential']);
+ });
+
+ test('undefined / empty argv falls back to the bare CLI name', () => {
+ const expected = [
+ 'credential.helper=',
+ 'credential.helper=!open-knowledge auth git-credential',
+ ];
+ expect(buildSyncCredentialConfig(undefined, { resetAmbient: true })).toEqual(expected);
+ expect(buildSyncCredentialConfig([], { resetAmbient: true })).toEqual(expected);
+ });
+
+ test('multi-element argv escapes each element independently', () => {
+ const argv = ['/Users/me/Library/Application Support/bun', '/opt/ok cli/cli.mjs'];
+ const config = buildSyncCredentialConfig(argv, { resetAmbient: true });
+ expect(argvFromHelper(config)).toEqual([...argv, 'auth', 'git-credential']);
+ });
+
+ test('embedded single quote in the path round-trips safely', () => {
+ const argv = ["/Users/o'brien/OpenKnowledge.app/cli.sh"];
+ const config = buildSyncCredentialConfig(argv, { resetAmbient: true });
+ expect(argvFromHelper(config)).toEqual([...argv, 'auth', 'git-credential']);
+ });
+});
+
+describe('buildSyncCredentialConfig() — ambient helper neutralization', () => {
+ // `credential.helper` is a multi-valued git config key: git accumulates every
+ // configured value (system → global → repo-local → command-line `-c`) and
+ // asks helpers in that order, stopping at the first that returns a complete
+ // credential. An EMPTY value resets the accumulated list. Without a reset
+ // entry ahead of OK's helper, any ambient helper (macOS Command Line Tools
+ // install a system-wide osxkeychain; Git for Windows ships `manager`) answers
+ // `get` first and can hand git a stale credential — sync then 401s while OK
+ // holds a valid token. The clone path already pins reset-then-helper
+ // (resolve-auth.ts); the sync producer must emit the same shape.
+ //
+ // Extracts the credential.helper values from the returned config in order,
+ // so the assertion survives changes to how the entries are laid out while
+ // still pinning the resolved-list order.
+ const credentialHelperValues = (config: string[]): string[] =>
+ config
+ .filter((entry) => entry.startsWith('credential.helper='))
+ .map((entry) => entry.slice('credential.helper='.length));
+
+ test("emits an empty credential.helper reset before OK's own helper", () => {
+ const values = credentialHelperValues(
+ buildSyncCredentialConfig(['open-knowledge'], { resetAmbient: true }),
+ );
+ expect(values).toEqual(['', '!open-knowledge auth git-credential']);
+ });
+
+ test('packaged bundle path keeps the reset ahead of the escaped helper', () => {
+ const bundlePath = '/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh';
+ const values = credentialHelperValues(
+ buildSyncCredentialConfig([bundlePath], { resetAmbient: true }),
+ );
+ expect(values[0]).toBe('');
+ expect(values.at(-1)).toBe(`!${bundlePath} auth git-credential`);
+ });
+
+ // The `false` arm guards origins OK cannot authenticate (gitlab, bitbucket,
+ // ...): their ambient helper is the ONLY credential they have, so emitting
+ // the reset would wipe it on every sync tick with no in-app way back. The
+ // git-level proof of that lives in git-handle.test.ts, but that suite is
+ // POSIX-only (`describe.skipIf(win32)`); without this case the always-running
+ // tier would stay green if the ternary were changed to always reset.
+ test('resetAmbient:false omits the reset, preserving the ambient chain', () => {
+ const values = credentialHelperValues(
+ buildSyncCredentialConfig(['open-knowledge'], { resetAmbient: false }),
+ );
+ expect(values).toEqual(['!open-knowledge auth git-credential']);
+ });
+});
+
+/**
+ * The generated index's WIRING, at real fidelity — a real server, a real
+ * watcher, real disk, a real shadow repo.
+ *
+ * This layer is where the feature's two shipped bugs lived, and neither was
+ * visible to a unit test: the config key was dropped in the persisted→runtime
+ * lift, and the delete branch for an unloaded document never scheduled a
+ * rebuild. Both left every pure test green. So each trigger gets exercised
+ * end-to-end against the index file it is supposed to move, rather than against
+ * the scheduler being called.
+ */
diff --git a/packages/server/src/git-handle.ts b/packages/server/src/git-handle.ts
index e1bfb00bb..b7b64ffd9 100644
--- a/packages/server/src/git-handle.ts
+++ b/packages/server/src/git-handle.ts
@@ -11,6 +11,7 @@ import { homedir } from 'node:os';
import { delimiter, resolve } from 'node:path';
import { augmentGitSpawnPath } from '@inkeep/open-knowledge-core';
import simpleGit, { type SimpleGit, type SimpleGitOptions } from 'simple-git';
+import { shellEscape } from './bash/shell-escape.ts';
/** Existence probe for `augmentGitSpawnPath` — directories only. Named to
* match the `GitSpawnPathOptions.isDir` seam (and the desktop twin in
@@ -47,8 +48,19 @@ export interface RelayGhToken {
}
interface GitHandleOptions {
- /** git -c flags for credential injection (from resolveAuth) */
- credentialArgs?: string[];
+ /**
+ * Ordered `credential.helper=` config VALUES (from
+ * `buildSyncCredentialConfig`: empty reset first, OK's helper last),
+ * forwarded verbatim into the spawn's `-c` config list.
+ *
+ * REQUIRED, and `[]` is a meaningful value rather than a default: omitting it
+ * used to be indistinguishable between "local-only op, needs no credential"
+ * and "remote op, forgot to pass it", and the latter authenticates with
+ * whatever ambient helper the machine happens to have. Every call site now
+ * states its intent, so a remote spawn cannot silently inherit the ambient
+ * chain.
+ */
+ credentialConfig: string[];
/** Override GIT_INDEX_FILE env var for index isolation */
gitIndexFile?: string;
/** gh token relayed to the credential helper via env (see {@link RelayGhToken}). */
@@ -66,7 +78,7 @@ interface GitHandleOptions {
export interface GitHandle {
git: SimpleGit;
projectDir: string;
- credentialArgs: string[];
+ credentialConfig: string[];
env: Record<string, string>;
}
@@ -117,9 +129,13 @@ const GIT_AUTH_ENV_KEYS = [
* a bare command (`!open-knowledge auth git-credential` — the dev /
* CLI-on-PATH path) is found instead of failing "command not found".
* - The `GIT_AUTH_ENV_KEYS` allowlist (`HOME`, `SSH_AUTH_SOCK`, the Windows
- * home/profile vars, etc.): so the SSH transport finds `~/.ssh` and the
- * user's credential helpers reach their home-based stores. Without these,
- * SSH remotes and home-rooted helpers can't authenticate during sync.
+ * home/profile vars, etc.): so the SSH transport finds `~/.ssh`, OK's own
+ * helper can reach its home-based store, and — on origins where the ambient
+ * chain is deliberately preserved (see `shouldResetAmbientCredentials`) —
+ * the user's own helpers reach theirs. Without these, SSH remotes and
+ * home-rooted helpers can't authenticate during sync. Note this is about
+ * REACHING a store, not about ordering: on a GitHub origin the reset means
+ * ambient helpers are not consulted for HTTPS credentials at all.
* - `ELECTRON_RUN_AS_NODE`: in packaged desktop builds the server runs as
* Electron-as-Node and sets `localOpCliArgs` to `[electronBinary, cli.mjs]`,
* so the credential helper re-invokes that binary directly (it bypasses the
@@ -217,8 +233,8 @@ export function applyGitEnv(
* for local-only work (log reads, shadow-ref plumbing) — but the moment such a
* call site grows a `fetch`/`push`/`ls-remote`, it must move to this factory.
*/
-export function createGitInstance(projectDir: string, options: GitHandleOptions = {}): GitHandle {
- const { credentialArgs = [], gitIndexFile, ghToken, timeoutMs } = options;
+export function createGitInstance(projectDir: string, options: GitHandleOptions): GitHandle {
+ const { credentialConfig, gitIndexFile, ghToken, timeoutMs } = options;
const env: Record<string, string | undefined> = buildGitEnv(ghToken);
if (gitIndexFile) {
@@ -253,7 +269,7 @@ export function createGitInstance(projectDir: string, options: GitHandleOptions
'commit.gpgsign=false',
'core.autocrlf=false',
'credential.interactive=false',
- ...(credentialArgs.length >= 2 ? [credentialArgs[1]] : []),
+ ...credentialConfig,
];
// simple-git 3.36 gates credential.helper behind a runtime-only unsafe flag
@@ -267,5 +283,51 @@ export function createGitInstance(projectDir: string, options: GitHandleOptions
const git = simpleGit(gitOptions as Partial<SimpleGitOptions>).env(env as Record<string, string>);
- return { git, projectDir, credentialArgs, env: env as Record<string, string> };
+ return { git, projectDir, credentialConfig, env: env as Record<string, string> };
+}
+
+/**
+ * Build the ordered git config VALUES (spread into `createGitInstance`'s `-c`
+ * list) that let SyncEngine's fetch/push authenticate by shelling out to our
+ * own CLI's `auth git-credential` helper.
+ *
+ * Git runs a `!`-prefixed credential helper through the shell, so every argv
+ * element must be shell-quoted. The packaged macOS CLI path lives under
+ * `/Applications/OpenKnowledge.app/…` — the space splits unquoted, the shell
+ * fails to exec, the helper returns no credentials, and git falls back to an
+ * interactive username prompt with no TTY ("could not read Username … Device
+ * not configured"). `shellEscape` per argv element is the fix.
+ *
+ * The leading empty `credential.helper=` value, when present, is load-bearing.
+ * `credential.helper` is multi-valued — git accumulates every configured value
+ * (system → global → repo-local → `-c`, in that order) and asks helpers in
+ * order, stopping at the first that returns a complete credential. Without the
+ * reset, an ambient helper (macOS Command Line Tools install a system-wide
+ * osxkeychain; Git for Windows ships `manager`) answers `get` with whatever it
+ * holds — possibly stale — before OK's helper is ever consulted, while OK's
+ * valid token sits unused in the relay env. An empty value clears the list
+ * accumulated so far, making OK's helper the only one consulted for these
+ * spawns; `-c` is per-spawn, so the user's own terminal/IDE git is untouched.
+ * Same convention as the clone path's `resolveAuth`
+ * (cli/src/auth/resolve-auth.ts, `ResolvedAuth.gitConfig`) — keep the two in
+ * step: config values, reset first, our helper last. Like clone's `none` tier,
+ * the reset is conditional rather than unconditional: it is emitted only where
+ * OK can actually issue a credential for the origin. On a GitHub or GHES
+ * origin, a user whose only working credential was ambient is deliberately
+ * routed to OK's sign-in rather than silently borrowing it. On a known
+ * non-GitHub forge OK can never issue one — `validateGitHubHost` rejects those
+ * hosts at login and the gh relay is host-scoped — so clearing the chain there
+ * would strand sync with no in-app remedy. `shouldResetAmbientCredentials`
+ * makes that call.
+ */
+export function buildSyncCredentialConfig(
+ localOpCliArgs: string[] | undefined,
+ opts: { resetAmbient: boolean },
+): string[] {
+ const argv = localOpCliArgs && localOpCliArgs.length > 0 ? localOpCliArgs : ['open-knowledge'];
+ const cliPrefix = argv.map(shellEscape).join(' ');
+ const helper = `credential.helper=!${cliPrefix} auth git-credential`;
+ // The reset is what makes OK's helper authoritative, but it is only safe
+ // where OK can actually supply a credential — see shouldResetAmbientCredentials.
+ return opts.resetAmbient ? ['credential.helper=', helper] : [helper];
}
diff --git a/packages/server/src/project-skill-git.ts b/packages/server/src/project-skill-git.ts
index 17d958d70..2c48b943b 100644
--- a/packages/server/src/project-skill-git.ts
+++ b/packages/server/src/project-skill-git.ts
@@ -86,7 +86,8 @@ export async function untrackTrackedProjectSkillProjection(
return { kind: 'skipped', reason: 'operation-in-progress' };
}
- const handle = createGitInstance(projectDir);
+ // Local-only: index and tree plumbing, no remote.
+ const handle = createGitInstance(projectDir, { credentialConfig: [] });
const trackedDirs = await listTrackedProjectionDirs(handle);
if (trackedDirs.length === 0) return { kind: 'nothing-tracked' };
@@ -106,7 +107,7 @@ export async function untrackTrackedProjectSkillProjection(
if (dirsNow.length === 0) return { kind: 'nothing-tracked' };
const tmpIndex = join(tmpdir(), `ok-untrack-idx-${process.pid}-${Date.now()}.idx`);
- const iso = createGitInstance(projectDir, { gitIndexFile: tmpIndex });
+ const iso = createGitInstance(projectDir, { gitIndexFile: tmpIndex, credentialConfig: [] });
// Seed the isolated index from HEAD, drop the projection dirs, write the
// reduced tree. `--ignore-unmatch` tolerates a dir that vanished from the
diff --git a/packages/server/src/server-factory.test.ts b/packages/server/src/server-factory.test.ts
index 5ecb33e25..a227cce41 100644
--- a/packages/server/src/server-factory.test.ts
+++ b/packages/server/src/server-factory.test.ts
@@ -14,7 +14,6 @@ import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { LOCAL_DIR, REMOVED_KEYS } from '@inkeep/open-knowledge-core';
import { readConfigSafely, resolveConfigPath } from '@inkeep/open-knowledge-core/server';
-import shellQuote from 'shell-quote';
import simpleGit from 'simple-git';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { stringify as stringifyYaml } from 'yaml';
@@ -41,7 +40,7 @@ import {
} from './managed-rename-journal.ts';
import { ensureProjectGit } from './project-git.ts';
import { saveRemovedDocsJournal } from './removed-docs-journal.ts';
-import { buildSyncCredentialArgs, createServer, type ServerInstance } from './server-factory.ts';
+import { createServer, type ServerInstance } from './server-factory.ts';
import { releaseServerLock } from './server-lock.ts';
import { initShadowRepo, shadowGit } from './shadow-repo.ts';
import { TagIndex } from './tag-index.ts';
@@ -3690,66 +3689,6 @@ describe('createServer() — push-permission auth wiring', () => {
});
});
-describe('buildSyncCredentialArgs()', () => {
- // Git runs a `!`-prefixed credential helper through the shell, so the helper
- // string after `!` is whatever the shell tokenizes back out. Parsing it with
- // shell-quote reproduces the argv git would exec — the load-bearing property.
- const argvFromHelper = (args: string[]): unknown[] => {
- expect(args[0]).toBe('-c');
- const prefix = 'credential.helper=!';
- expect(args[1].startsWith(prefix)).toBe(true);
- const suffix = ' auth git-credential';
- expect(args[1].endsWith(suffix)).toBe(true);
- const shellCmd = args[1].slice(prefix.length);
- return shellQuote.parse(shellCmd);
- };
-
- test('packaged macOS bundle path survives the shell as one intact token', () => {
- // Regression: the bundled CLI lives under "/Applications/OpenKnowledge.app/…".
- // Unquoted, the shell split at the space, tried to exec "/Applications/Open",
- // returned no credentials, and git failed with "could not read Username …
- // Device not configured". The path must round-trip as a single argv element.
- const bundlePath = '/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh';
- const args = buildSyncCredentialArgs([bundlePath]);
- expect(argvFromHelper(args)).toEqual([bundlePath, 'auth', 'git-credential']);
- });
-
- test('bare command (dev default) stays unquoted', () => {
- const args = buildSyncCredentialArgs(['open-knowledge']);
- expect(args).toEqual(['-c', 'credential.helper=!open-knowledge auth git-credential']);
- expect(argvFromHelper(args)).toEqual(['open-knowledge', 'auth', 'git-credential']);
- });
-
- test('undefined / empty argv falls back to the bare CLI name', () => {
- const expected = ['-c', 'credential.helper=!open-knowledge auth git-credential'];
- expect(buildSyncCredentialArgs(undefined)).toEqual(expected);
- expect(buildSyncCredentialArgs([])).toEqual(expected);
- });
-
- test('multi-element argv escapes each element independently', () => {
- const argv = ['/Users/me/Library/Application Support/bun', '/opt/ok cli/cli.mjs'];
- const args = buildSyncCredentialArgs(argv);
- expect(argvFromHelper(args)).toEqual([...argv, 'auth', 'git-credential']);
- });
-
- test('embedded single quote in the path round-trips safely', () => {
- const argv = ["/Users/o'brien/OpenKnowledge.app/cli.sh"];
- const args = buildSyncCredentialArgs(argv);
- expect(argvFromHelper(args)).toEqual([...argv, 'auth', 'git-credential']);
- });
-});
-
-/**
- * The generated index's WIRING, at real fidelity — a real server, a real
- * watcher, real disk, a real shadow repo.
- *
- * This layer is where the feature's two shipped bugs lived, and neither was
- * visible to a unit test: the config key was dropped in the persisted→runtime
- * lift, and the delete branch for an unloaded document never scheduled a
- * rebuild. Both left every pure test green. So each trigger gets exercised
- * end-to-end against the index file it is supposed to move, rather than against
- * the scheduler being called.
- */
describe('createServer() — generated index wiring', () => {
let projectDir: string;
let contentDir: string;
diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.ts
index 66b11408d..3c82902b5 100644
--- a/packages/server/src/server-factory.ts
+++ b/packages/server/src/server-factory.ts
@@ -72,7 +72,6 @@ import {
type HocuspocusAuthRejectionReason,
parseHocuspocusAuthToken,
} from './auth-token-schema.ts';
-import { shellEscape } from './bash/shell-escape.ts';
import { bootElapsedMs, recordBootPhase, setBootField } from './boot-timings.ts';
import {
type BridgeDeriveLossReporter,
@@ -152,6 +151,7 @@ import {
type WatcherHandle,
} from './file-watcher.ts';
import { normalizeFsPath, tracedAtomicFs, tracedMkdirSync } from './fs-traced.ts';
+import { buildSyncCredentialConfig } from './git-handle.ts';
import type {
CheckPushPermissionOptions,
DetectGhFn,
@@ -249,6 +249,7 @@ import {
saveInMemoryCheckpoint,
shadowGit,
} from './shadow-repo.ts';
+import { readOriginGitHubRepo, shouldResetAmbientCredentials } from './share/git-context.ts';
import { resyncRecordedSkillCopies } from './skill-placements.ts';
import { assertCompatibleStateManifest } from './state-manifest.ts';
import { SyncEngine } from './sync-engine.ts';
@@ -606,33 +607,6 @@ const GENERATED_ARTIFACT_ORIGIN = (() => {
}) satisfies PairedWriteOrigin;
})();
-/**
- * Build the git `-c credential.helper=…` args that let SyncEngine's fetch/push
- * authenticate by shelling out to our own CLI's `auth git-credential` helper.
- *
- * Git runs a `!`-prefixed credential helper through the shell, so every argv
- * element must be shell-quoted. The packaged macOS CLI path lives under
- * `/Applications/OpenKnowledge.app/…` — the space splits unquoted, the shell
- * fails to exec, the helper returns no credentials, and git falls back to an
- * interactive username prompt with no TTY ("could not read Username … Device
- * not configured"). `shellEscape` per argv element is the fix.
- *
- * Deliberately NO empty `credential.helper=` reset here, unlike the clone
- * path's `resolveAuth` (cli/src/auth/resolve-auth.ts), which prepends one to
- * neutralize stale ambient helpers. Sync's helper is append-only: ambient
- * helpers (a broken `!gh` from a past `gh auth setup-git`, osxkeychain) run
- * first and can add stderr noise or answer with a stale credential before
- * ours does — long-standing behavior that background sync's retry/degrade
- * handling already absorbs. Clone is a one-shot user-facing action with no
- * retry, so it needs the determinism; adding the reset HERE changes every
- * user's sync credential order and needs its own change with its own soak.
- */
-export function buildSyncCredentialArgs(localOpCliArgs?: string[]): string[] {
- const argv = localOpCliArgs && localOpCliArgs.length > 0 ? localOpCliArgs : ['open-knowledge'];
- const cliPrefix = argv.map(shellEscape).join(' ');
- return ['-c', `credential.helper=!${cliPrefix} auth git-credential`];
-}
-
export interface UpstreamAuthor {
name: string;
email: string;
@@ -5388,7 +5362,23 @@ export function createServer(options: ServerOptions): ServerInstance {
}
// Start SyncEngine: remote detection + auto-sync.
- const syncCredentialArgs = buildSyncCredentialArgs(localOpCliArgs);
+ const resetAmbientCredentials = shouldResetAmbientCredentials(projectDir);
+ // Which credential chain sync authenticates with is invisible from the
+ // outside: a wrong answer surfaces only as a 401 much later, and the
+ // original ordering defect was diagnosable only by the ABSENCE of helper
+ // log lines. Record the decision and its basis so the next report of
+ // "sync says signed out" can be answered from the log alone. The origin is
+ // re-read rather than derived from the boolean on purpose: inlining the
+ // kind comparison here would give the rule a second home that can drift
+ // from the predicate. Boot-time, once, on a small file. No raw path — the
+ // kind is a bounded enum, the projectDir is not.
+ log.debug(
+ { resetAmbientCredentials, originKind: readOriginGitHubRepo(projectDir).kind },
+ '[sync] ambient credential-chain reset decision at boot',
+ );
+ const syncCredentialConfig = buildSyncCredentialConfig(localOpCliArgs, {
+ resetAmbient: resetAmbientCredentials,
+ });
const bootAutoSyncMode = readProjectAutoSyncMode();
if (bootAutoSyncMode.mode !== 'off') {
// A never-asked machine booting into a committed-default mode is the main
@@ -5409,7 +5399,7 @@ export function createServer(options: ServerOptions): ServerInstance {
mode: bootAutoSyncMode.mode,
pullIntervalSeconds: options.pullIntervalSeconds,
pushIntervalSeconds: options.pushIntervalSeconds,
- credentialArgs: syncCredentialArgs,
+ credentialConfig: syncCredentialConfig,
cc1Broadcaster,
// Push-permission probe auth seam — production callers (CLI `ok start`)
// pass concrete `detectGh` + `tokenStore` so the probe runs under the
diff --git a/packages/server/src/share/endpoint-real-git.test.ts b/packages/server/src/share/endpoint-real-git.test.ts
index 2cb2f3883..08d20d4f8 100644
--- a/packages/server/src/share/endpoint-real-git.test.ts
+++ b/packages/server/src/share/endpoint-real-git.test.ts
@@ -295,6 +295,7 @@ describe('target-status fetch timeout', () => {
try {
const start = performance.now();
const status = await computeShareTargetStatus(receiver, t.branch, 'doc.md', 'doc', {
+ credentialConfig: [],
fetchTimeoutMs: 2000,
});
const elapsed = performance.now() - start;
diff --git a/packages/server/src/share/freshness.ts b/packages/server/src/share/freshness.ts
index 2cda5c13a..5c3896165 100644
--- a/packages/server/src/share/freshness.ts
+++ b/packages/server/src/share/freshness.ts
@@ -43,7 +43,11 @@ export async function computeShareFreshness(
kind: 'doc' | 'folder',
): Promise<ShareFreshness | undefined> {
try {
- const { git } = createGitInstance(projectDir, { timeoutMs: FRESHNESS_PROBE_TIMEOUT_MS });
+ // Local-only: reads already-fetched `refs/remotes/...` via rev-parse/cat-file.
+ const { git } = createGitInstance(projectDir, {
+ timeoutMs: FRESHNESS_PROBE_TIMEOUT_MS,
+ credentialConfig: [],
+ });
const ref = `refs/remotes/origin/${branch}`;
// Fail-fast: the git binary works AND the remote-tracking ref resolves.
diff --git a/packages/server/src/share/git-context.test.ts b/packages/server/src/share/git-context.test.ts
index 3bcc32132..f5c41b685 100644
--- a/packages/server/src/share/git-context.test.ts
+++ b/packages/server/src/share/git-context.test.ts
@@ -8,6 +8,7 @@ import {
readGitHeadBranch,
readOriginGitHubRepo,
readSyncRemoteInfo,
+ shouldResetAmbientCredentials,
} from './git-context.ts';
function seedRepo(
@@ -357,6 +358,64 @@ describe('originGitHubHost', () => {
});
});
+describe('shouldResetAmbientCredentials', () => {
+ let dir: string;
+
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'share-git-reset-'));
+ });
+
+ afterEach(() => {
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ test('github.com origin resets — OK can supply a credential there', () => {
+ seedRepo(dir, {
+ config: '[remote "origin"]\n\turl = https://github.com/inkeep/open-knowledge.git\n',
+ });
+ expect(shouldResetAmbientCredentials(dir)).toBe(true);
+ });
+
+ test('GHES origin resets — sign-in accepts unknown hosts as enterprise', () => {
+ seedRepo(dir, {
+ config: '[remote "origin"]\n\turl = https://ghes.acme.test/acme/kb.git\n',
+ });
+ expect(shouldResetAmbientCredentials(dir)).toBe(true);
+ });
+
+ // The reset follows the HOST, not the transport. An SSH clone still runs
+ // HTTPS sub-operations that consult credential helpers, so a transport
+ // conditional here would silently strand them; the HTTPS cases above cannot
+ // catch that on their own.
+ test('github.com SSH origin resets — the decision is host-scoped', () => {
+ seedRepo(dir, {
+ config: '[remote "origin"]\n\turl = [email protected]:inkeep/open-knowledge.git\n',
+ });
+ expect(shouldResetAmbientCredentials(dir)).toBe(true);
+ });
+
+ // The regression this guards: clearing the chain for a forge OK cannot
+ // authenticate strands the user with no credential and no in-app recovery,
+ // because signing in only ever yields a GitHub token.
+ test('gitlab origin does NOT reset — its ambient credential is the only one', () => {
+ seedRepo(dir, {
+ config: '[remote "origin"]\n\turl = https://gitlab.com/team/notes.git\n',
+ });
+ expect(shouldResetAmbientCredentials(dir)).toBe(false);
+ });
+
+ test('bitbucket origin does NOT reset', () => {
+ seedRepo(dir, {
+ config: '[remote "origin"]\n\turl = [email protected]:team/notes.git\n',
+ });
+ expect(shouldResetAmbientCredentials(dir)).toBe(false);
+ });
+
+ test('no remote resets — nothing ambient to preserve, sync is dormant anyway', () => {
+ expect(shouldResetAmbientCredentials(dir)).toBe(true);
+ });
+});
+
describe('branchExistsOnOrigin', () => {
let dir: string;
diff --git a/packages/server/src/share/git-context.ts b/packages/server/src/share/git-context.ts
index 612a267ee..c72de3ce7 100644
--- a/packages/server/src/share/git-context.ts
+++ b/packages/server/src/share/git-context.ts
@@ -172,6 +172,22 @@ export function originGitHubHost(projectDir: string): string {
return 'github.com';
}
+/**
+ * Whether OK should clear the inherited credential-helper chain for git spawns
+ * against this project's origin.
+ *
+ * OK can only produce a credential for GitHub hosts: sign-in rejects known
+ * non-GitHub forges outright (`validateGitHubHost`), and the relayed gh token
+ * is host-scoped, so neither tier can answer for e.g. gitlab.com. Clearing the
+ * chain there can only subtract — it removes the ambient credential the user is
+ * actually syncing with and leaves nothing in its place, and the in-app "Sign
+ * in" affordance cannot help because it only ever yields a GitHub token. Those
+ * origins keep their inherited chain.
+ */
+export function shouldResetAmbientCredentials(projectDir: string): boolean {
+ return readOriginGitHubRepo(projectDir).kind !== 'non-github';
+}
+
/**
* UI-facing summary of the origin remote for the sync-status payload.
* `webUrl` is non-null for GitHub-host origins — github.com AND GHES (the
diff --git a/packages/server/src/share/target-status.test.ts b/packages/server/src/share/target-status.test.ts
index 624b74cf7..82b1b4c9c 100644
--- a/packages/server/src/share/target-status.test.ts
+++ b/packages/server/src/share/target-status.test.ts
@@ -28,7 +28,9 @@ describe('computeShareTargetStatus', () => {
// Sender pushes a second doc AFTER the clone; the receiver's origin ref is
// now stale and does not know about it — until the fetch.
t.seedAndPush('doc2.md', 'two\n');
- const status = await computeShareTargetStatus(receiver, t.branch, 'doc2.md', 'doc');
+ const status = await computeShareTargetStatus(receiver, t.branch, 'doc2.md', 'doc', {
+ credentialConfig: [],
+ });
expect(status.verdict).toBe('on-origin');
});
@@ -37,7 +39,9 @@ describe('computeShareTargetStatus', () => {
t.seedAndPush('old.md', '# stable content that survives the move intact\n');
const receiver = t.cloneReceiver();
t.renameOnOrigin('old.md', 'new.md');
- const status = await computeShareTargetStatus(receiver, t.branch, 'old.md', 'doc');
+ const status = await computeShareTargetStatus(receiver, t.branch, 'old.md', 'doc', {
+ credentialConfig: [],
+ });
expect(status.verdict).toBe('renamed');
if (status.verdict === 'renamed') expect(status.renamedTo).toBe('new.md');
});
@@ -49,7 +53,9 @@ describe('computeShareTargetStatus', () => {
// The removal lands in a merge commit, whose bare diff-tree is combined
// format — a first-parent diff is what keeps the rename row readable.
t.mergeRenameOnOrigin('old.md', 'new.md');
- const status = await computeShareTargetStatus(receiver, t.branch, 'old.md', 'doc');
+ const status = await computeShareTargetStatus(receiver, t.branch, 'old.md', 'doc', {
+ credentialConfig: [],
+ });
expect(status.verdict).toBe('renamed');
if (status.verdict === 'renamed') expect(status.renamedTo).toBe('new.md');
});
@@ -60,7 +66,9 @@ describe('computeShareTargetStatus', () => {
t.seedAndPush('docs/b.md', 'beta content long enough to match on similarity\n');
const receiver = t.cloneReceiver();
t.renameFolderOnOrigin('docs', 'knowledge');
- const status = await computeShareTargetStatus(receiver, t.branch, 'docs', 'folder');
+ const status = await computeShareTargetStatus(receiver, t.branch, 'docs', 'folder', {
+ credentialConfig: [],
+ });
expect(status.verdict).toBe('renamed');
if (status.verdict === 'renamed') expect(status.renamedTo).toBe('knowledge');
});
@@ -70,14 +78,18 @@ describe('computeShareTargetStatus', () => {
t.seedAndPush('gone.md', '# will be removed with no successor\n');
const receiver = t.cloneReceiver();
t.deleteOnOrigin('gone.md');
- const status = await computeShareTargetStatus(receiver, t.branch, 'gone.md', 'doc');
+ const status = await computeShareTargetStatus(receiver, t.branch, 'gone.md', 'doc', {
+ credentialConfig: [],
+ });
expect(status.verdict).toBe('deleted');
});
test('never-on-branch: a path that never existed is distinct from deleted', async () => {
const t = newTriangle();
const receiver = t.cloneReceiver();
- const status = await computeShareTargetStatus(receiver, t.branch, 'never.md', 'doc');
+ const status = await computeShareTargetStatus(receiver, t.branch, 'never.md', 'doc', {
+ credentialConfig: [],
+ });
expect(status.verdict).toBe('never-on-branch');
});
@@ -88,6 +100,7 @@ describe('computeShareTargetStatus', () => {
// No reachable origin — the fetch fails fast.
t.git(receiver, ['remote', 'remove', 'origin']);
const status = await computeShareTargetStatus(receiver, t.branch, 'doc.md', 'doc', {
+ credentialConfig: [],
fetchTimeoutMs: 5000,
});
expect(status.verdict).toBe('unknown');
@@ -98,6 +111,7 @@ describe('computeShareTargetStatus', () => {
t.seedAndPush('doc.md', 'one\n');
const receiver = t.cloneReceiver();
const status = await computeShareTargetStatus(receiver, t.branch, 'doc.md', 'doc', {
+ credentialConfig: [],
skipFetch: true,
});
expect(status.verdict).toBe('on-origin');
@@ -109,7 +123,9 @@ describe('computeShareTargetStatus', () => {
const receiver = t.cloneReceiver();
t.renameOnOrigin('a.md', 'b.md');
t.renameOnOrigin('b.md', 'c.md');
- const status = await computeShareTargetStatus(receiver, t.branch, 'a.md', 'doc');
+ const status = await computeShareTargetStatus(receiver, t.branch, 'a.md', 'doc', {
+ credentialConfig: [],
+ });
// a.md's removal commit renamed it to b.md, but b.md no longer resolves at
// origin (it became c.md), so the redirect is refused in favor of deleted.
expect(status.verdict).toBe('deleted');
@@ -123,6 +139,7 @@ describe('computeShareTargetStatus', () => {
// the verdict is reachable from local refs with no fetch.
const receiver = t.cloneReceiver();
const status = await computeShareTargetStatus(receiver, t.branch, 'gone.md', 'doc', {
+ credentialConfig: [],
skipFetch: true,
});
expect(status.verdict).toBe('deleted');
@@ -139,7 +156,9 @@ describe('computeShareTargetStatus', () => {
['docs/a.md', 'x/a.md'],
['docs/b.md', 'y/b.md'],
]);
- const status = await computeShareTargetStatus(receiver, t.branch, 'docs', 'folder');
+ const status = await computeShareTargetStatus(receiver, t.branch, 'docs', 'folder', {
+ credentialConfig: [],
+ });
expect(status.verdict).toBe('deleted');
});
@@ -151,7 +170,9 @@ describe('computeShareTargetStatus', () => {
// is still on origin and in their HEAD, but absent from the working tree.
// "Pull" would be wrong guidance — they are not behind.
t.deleteInReceiverWorkingTree('local-del.md');
- const status = await computeShareTargetStatus(receiver, t.branch, 'local-del.md', 'doc');
+ const status = await computeShareTargetStatus(receiver, t.branch, 'local-del.md', 'doc', {
+ credentialConfig: [],
+ });
expect(status.verdict).toBe('changed-locally');
});
@@ -162,7 +183,9 @@ describe('computeShareTargetStatus', () => {
// A local rename looks identical to a local delete from the OLD path's
// vantage: present in HEAD, gone from the working tree.
t.renameInReceiverWorkingTree('local-mv.md', 'renamed-local.md');
- const status = await computeShareTargetStatus(receiver, t.branch, 'local-mv.md', 'doc');
+ const status = await computeShareTargetStatus(receiver, t.branch, 'local-mv.md', 'doc', {
+ credentialConfig: [],
+ });
expect(status.verdict).toBe('changed-locally');
});
});
diff --git a/packages/server/src/share/target-status.ts b/packages/server/src/share/target-status.ts
index 377f9fd9b..628e26f28 100644
--- a/packages/server/src/share/target-status.ts
+++ b/packages/server/src/share/target-status.ts
@@ -2,12 +2,16 @@
* Receive-side verdict for `POST /api/share/target-status`: when a receiver
* opens a share link and the target isn't on their current ref, why — did it
* move, get deleted, or was it never here? Runs a targeted `git fetch origin
- * <branch>` (via `createGitInstance`, so the user's ambient git credential
- * helper authenticates it exactly as checkout's fetch does — no explicit OK
- * token is injected) bounded by a block timeout, so a stale local ref can't
+ * <branch>` via `createGitInstance` with the caller-supplied
+ * `credentialConfig`, bounded by a block timeout, so a stale local ref can't
* misreport a recently-added target as gone, then classifies the miss from
* git's own rename detection.
*
+ * Which credential answers that fetch is the caller's decision, not this
+ * module's: on a GitHub or GHES origin the inherited helper chain is reset and
+ * OK's own helper is the sole authenticator, while on a known non-GitHub forge
+ * the ambient chain is preserved because OK has no credential to offer there.
+ *
* Everything is fail-open: a fetch failure, a broken git, or an ambiguous
* classification returns `unknown`, and the caller falls back to today's
* guidance. A miss degrades to honest `deleted`, never a wrong redirect.
@@ -74,7 +78,7 @@ export async function computeShareTargetStatus(
branch: string,
gitPath: string,
kind: 'doc' | 'folder',
- opts: { skipFetch?: boolean; fetchTimeoutMs?: number } = {},
+ opts: { skipFetch?: boolean; fetchTimeoutMs?: number; credentialConfig: string[] },
): Promise<ShareTargetStatusResponse> {
const log = getLogger('share');
const emit = (result: ShareTargetStatusResponse): ShareTargetStatusResponse => {
@@ -84,7 +88,12 @@ export async function computeShareTargetStatus(
const { git } = createGitInstance(
projectDir,
- opts.skipFetch ? {} : { timeoutMs: opts.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS },
+ opts.skipFetch
+ ? { credentialConfig: [] }
+ : {
+ timeoutMs: opts.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS,
+ credentialConfig: opts.credentialConfig,
+ },
);
if (!opts.skipFetch) {
diff --git a/packages/server/src/sync-engine.ts b/packages/server/src/sync-engine.ts
index 669146753..81af810ed 100644
--- a/packages/server/src/sync-engine.ts
+++ b/packages/server/src/sync-engine.ts
@@ -325,8 +325,8 @@ interface SyncEngineOptions {
* is provided.
*/
syncEnabled?: boolean;
- /** Credential args for simple-git (e.g. ['-c', 'credential.helper=…']). */
- credentialArgs?: string[];
+ /** 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;
/** Called on every state transition. */
@@ -490,7 +490,7 @@ export class SyncEngine {
* a pull-only project.
*/
private mode: SyncMode;
- private credentialArgs: string[];
+ private credentialConfig: string[];
private cc1Broadcaster: CC1Broadcaster | null;
private onStateChange: ((state: SyncState) => void) | undefined;
private onContentConflictsDetected: ((files: string[]) => void | Promise<void>) | undefined;
@@ -580,7 +580,7 @@ export class SyncEngine {
// `mode` wins; fall back to the legacy boolean so callers that still pass
// `syncEnabled` keep their exact prior semantics (true→full, else off).
this.mode = options.mode ?? (options.syncEnabled === true ? 'full' : 'off');
- this.credentialArgs = options.credentialArgs ?? [];
+ this.credentialConfig = options.credentialConfig ?? [];
this.cc1Broadcaster = options.cc1Broadcaster ?? null;
this.onStateChange = options.onStateChange;
this.onContentConflictsDetected = options.onContentConflictsDetected;
@@ -615,7 +615,7 @@ export class SyncEngine {
/**
* Single construction point for every git handle the engine spawns. Threads
- * the credential args plus the cached gh token (scoped to the origin's
+ * 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
@@ -623,7 +623,7 @@ export class SyncEngine {
*/
private gitHandle(gitIndexFile?: string): GitHandle {
return createGitInstance(this.projectDir, {
- credentialArgs: this.credentialArgs,
+ credentialConfig: this.credentialConfig,
gitIndexFile,
ghToken: this.ghTokenSource.get(this.syncGhTokenHost()) ?? undefined,
timeoutMs: GIT_BLOCK_TIMEOUT_MS,