Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(clone): authenticate share-link clone without gh installed (#2718)

Andrew Mikofalvy6a9aebd2bbb0
diff --git a/.changeset/clone-auth-without-gh.md b/.changeset/clone-auth-without-gh.md
new file mode 100644
index 000000000..6f8146385
--- /dev/null
+++ b/.changeset/clone-auth-without-gh.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Opening a shared document by cloning from GitHub no longer requires the GitHub CLI (`gh`) to be installed. OpenKnowledge now authenticates the clone with the GitHub account you're already connected as, rather than delegating to `gh` or to whatever credential helper your machine's git config happens to point at. "Clone to a new folder" previously failed on a clean machine — or one with a leftover `gh auth setup-git` config after `gh` was removed — with `gh: command not found` and `could not read Username`; it now uses your connected account directly.
diff --git a/packages/cli/src/auth/resolve-auth.test.ts b/packages/cli/src/auth/resolve-auth.test.ts
index 94b1e54e6..5eb890d68 100644
--- a/packages/cli/src/auth/resolve-auth.test.ts
+++ b/packages/cli/src/auth/resolve-auth.test.ts
@@ -3,7 +3,7 @@ import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { GhDetectResult } from './gh-detect.ts';
-import { resolveAuth } from './resolve-auth.ts';
+import { buildCliCredentialHelper, resolveAuth } from './resolve-auth.ts';
import { FileBackend } from './token-store.ts';
function makeStore(tmpDir: string) {
@@ -18,6 +18,27 @@ function ghUnavailable(): () => GhDetectResult {
return () => ({ available: false });
}
+// Deterministic self-argv so gitConfig assertions read cleanly. Production
+// passes `[process.execPath, cliEntry]`.
+const SELF: readonly string[] = ['/node', '/cli.mjs'];
+const SELF_HELPER = "credential.helper=!'/node' '/cli.mjs' auth git-credential";
+// The empty reset that must precede OK's helper — neutralizes a stale ambient
+// `!gh auth git-credential` a past `gh auth setup-git` left in the user's git
+// config on a machine where `gh` is no longer installed.
+const RESET = 'credential.helper=';
+
+describe('buildCliCredentialHelper', () => {
+ test('shell-quotes each argv element so a spaced bundle path survives', () => {
+ const helper = buildCliCredentialHelper([
+ '/Applications/OpenKnowledge.app/Contents/MacOS/OpenKnowledge',
+ '/Applications/OpenKnowledge.app/Contents/Resources/cli/dist/cli.mjs',
+ ]);
+ expect(helper).toBe(
+ "credential.helper=!'/Applications/OpenKnowledge.app/Contents/MacOS/OpenKnowledge' '/Applications/OpenKnowledge.app/Contents/Resources/cli/dist/cli.mjs' auth git-credential",
+ );
+ });
+});
+
describe('resolveAuth', () => {
let tmpDir: string;
beforeEach(() => {
@@ -28,42 +49,48 @@ describe('resolveAuth', () => {
});
// ---------------------------------------------------------------------------
- // Tier A — gh CLI available
+ // Tier A — gh CLI available: relay the gh token, use OK's own helper (no `!gh`)
// ---------------------------------------------------------------------------
- test('Tier A: gh available → returns credential.helper=!gh auth git-credential', async () => {
+ test('Tier A: gh available → reset + self-helper + relayToken (no `!gh` helper)', async () => {
const store = makeStore(tmpDir);
- const result = await resolveAuth('github.com', store, {}, ghAvailable());
+ const result = await resolveAuth(
+ 'github.com',
+ store,
+ { selfCliArgs: SELF },
+ ghAvailable('ghs_A'),
+ );
expect(result.tier).toBe('A');
- expect(result.credentialArgs).toEqual(['-c', 'credential.helper=!gh auth git-credential']);
+ expect(result.gitConfig).toEqual([RESET, SELF_HELPER]);
+ expect(result.relayToken).toEqual({ token: 'ghs_A', host: 'github.com' });
+ // The bare `!gh auth git-credential` form is gone — that's the whole point.
+ expect(result.gitConfig.join(' ')).not.toContain('!gh ');
});
test('Tier A takes priority over stored token', async () => {
const store = makeStore(tmpDir);
await store.set('github.com', 'alice', 'gho_abc');
- const result = await resolveAuth('github.com', store, {}, ghAvailable());
+ const result = await resolveAuth('github.com', store, { selfCliArgs: SELF }, ghAvailable());
expect(result.tier).toBe('A');
});
// ---------------------------------------------------------------------------
- // Tier B — stored token (https)
+ // Tier B — stored token (https): helper reads the store; no relay token
// ---------------------------------------------------------------------------
- test('Tier B: stored token (https protocol) → credential.helper relay', async () => {
+ test('Tier B: stored token (https protocol) → reset + self-helper, no relayToken', async () => {
const store = makeStore(tmpDir);
await store.set('github.com', 'alice', 'gho_abc', { gitProtocol: 'https' });
- const result = await resolveAuth('github.com', store, {}, ghUnavailable());
+ const result = await resolveAuth('github.com', store, { selfCliArgs: SELF }, ghUnavailable());
expect(result.tier).toBe('B');
- expect(result.credentialArgs).toEqual([
- '-c',
- 'credential.helper=!open-knowledge auth git-credential',
- ]);
+ expect(result.gitConfig).toEqual([RESET, SELF_HELPER]);
+ expect(result.relayToken).toBeUndefined();
});
test('Tier B: stored token without gitProtocol defaults to B', async () => {
const store = makeStore(tmpDir);
await store.set('github.com', 'alice', 'gho_abc');
- const result = await resolveAuth('github.com', store, {}, ghUnavailable());
+ const result = await resolveAuth('github.com', store, { selfCliArgs: SELF }, ghUnavailable());
expect(result.tier).toBe('B');
});
@@ -74,30 +101,56 @@ describe('resolveAuth', () => {
test('Tier C: stored token with ssh protocol', async () => {
const store = makeStore(tmpDir);
await store.set('github.com', 'alice', 'gho_abc', { gitProtocol: 'ssh' });
- const result = await resolveAuth('github.com', store, {}, ghUnavailable());
+ const result = await resolveAuth('github.com', store, { selfCliArgs: SELF }, ghUnavailable());
expect(result.tier).toBe('C');
- expect(result.credentialArgs).toEqual([
- '-c',
- 'credential.helper=!open-knowledge auth git-credential',
- ]);
+ expect(result.gitConfig).toEqual([RESET, SELF_HELPER]);
+ expect(result.relayToken).toBeUndefined();
});
// ---------------------------------------------------------------------------
- // none — no auth available
+ // The empty reset is load-bearing: it must come FIRST so a stale ambient
+ // `!gh auth git-credential` is cleared before OK's helper runs.
// ---------------------------------------------------------------------------
- test('none: no gh, no stored token', async () => {
+ test('authenticated tiers prepend an empty credential.helper reset', async () => {
+ const store = makeStore(tmpDir);
+ await store.set('github.com', 'alice', 'gho_abc');
+ const result = await resolveAuth('github.com', store, { selfCliArgs: SELF }, ghUnavailable());
+ expect(result.gitConfig[0]).toBe(RESET);
+ });
+
+ test('default selfCliArgs falls back to the bare open-knowledge helper', async () => {
const store = makeStore(tmpDir);
+ await store.set('github.com', 'alice', 'gho_abc');
const result = await resolveAuth('github.com', store, {}, ghUnavailable());
+ expect(result.gitConfig).toEqual([
+ RESET,
+ "credential.helper=!'open-knowledge' auth git-credential",
+ ]);
+ });
+
+ // ---------------------------------------------------------------------------
+ // none — no auth available: leave ambient config untouched
+ // ---------------------------------------------------------------------------
+
+ test('none: no gh, no stored token → empty gitConfig, no relayToken', async () => {
+ const store = makeStore(tmpDir);
+ const result = await resolveAuth('github.com', store, { selfCliArgs: SELF }, ghUnavailable());
expect(result.tier).toBe('none');
- expect(result.credentialArgs).toEqual([]);
+ expect(result.gitConfig).toEqual([]);
+ expect(result.relayToken).toBeUndefined();
});
test('none: skipGhDetect=true bypasses gh even if available', async () => {
const store = makeStore(tmpDir);
- const result = await resolveAuth('github.com', store, { skipGhDetect: true }, ghAvailable());
+ const result = await resolveAuth(
+ 'github.com',
+ store,
+ { skipGhDetect: true, selfCliArgs: SELF },
+ ghAvailable(),
+ );
expect(result.tier).toBe('none');
- expect(result.credentialArgs).toEqual([]);
+ expect(result.gitConfig).toEqual([]);
});
// ---------------------------------------------------------------------------
@@ -112,24 +165,35 @@ describe('resolveAuth', () => {
seenHosts.push(host);
return host === 'ghes.acme.test' ? { available: false } : { available: true, token: 'x' };
};
- const result = await resolveAuth('ghes.acme.test', store, {}, ghGithubComOnly);
+ const result = await resolveAuth(
+ 'ghes.acme.test',
+ store,
+ { selfCliArgs: SELF },
+ ghGithubComOnly,
+ );
expect(seenHosts).toEqual(['ghes.acme.test']);
expect(result.tier).toBe('none');
- const githubResult = await resolveAuth('github.com', store, {}, ghGithubComOnly);
+ const githubResult = await resolveAuth(
+ 'github.com',
+ store,
+ { selfCliArgs: SELF },
+ ghGithubComOnly,
+ );
expect(githubResult.tier).toBe('A');
+ expect(githubResult.relayToken).toEqual({ token: 'x', host: 'github.com' });
});
test('token for different host returns none', async () => {
const store = makeStore(tmpDir);
await store.set('gitlab.com', 'bob', 'glpat_xyz');
- const result = await resolveAuth('github.com', store, {}, ghUnavailable());
+ const result = await resolveAuth('github.com', store, { selfCliArgs: SELF }, ghUnavailable());
expect(result.tier).toBe('none');
});
test('token for correct host returns Tier B', async () => {
const store = makeStore(tmpDir);
await store.set('gitlab.com', 'bob', 'glpat_xyz');
- const result = await resolveAuth('gitlab.com', store, {}, ghUnavailable());
+ const result = await resolveAuth('gitlab.com', store, { selfCliArgs: SELF }, ghUnavailable());
expect(result.tier).toBe('B');
});
});
diff --git a/packages/cli/src/auth/resolve-auth.ts b/packages/cli/src/auth/resolve-auth.ts
index 371c29fb9..f0bd1611d 100644
--- a/packages/cli/src/auth/resolve-auth.ts
+++ b/packages/cli/src/auth/resolve-auth.ts
@@ -1,34 +1,85 @@
+import { shellSingleQuote } from '@inkeep/open-knowledge-core';
import { detectGh } from './gh-detect.ts';
import type { TokenStore } from './token-store.ts';
type AuthTier = 'A' | 'B' | 'C' | 'none';
-interface ResolvedAuth {
+/**
+ * A gh-resolved token to relay to the credential helper via env. gh is resolved
+ * HERE (where it is reachable — inside the CLI process, which the caller
+ * spawned with the user's env) rather than shelled out to from git's credential
+ * subsystem, whose subprocess PATH may not include `gh` at all (the packaged
+ * desktop app's stripped `launchd` PATH). Mirrors the sync path's `RelayGhToken`.
+ */
+interface RelayGhToken {
+ token: string;
+ /** Host the token authenticates; the helper host-matches before using it. */
+ host: string;
+}
+
+export interface ResolvedAuth {
tier: AuthTier;
/**
- * git -c flags to pass for credential injection.
- * Empty array when tier is 'none' or when using token-store relay.
+ * git `-c` config VALUES to inject (each becomes a `-c <value>` flag, in
+ * order). For an authenticated tier this is a two-element list: an empty
+ * `credential.helper=` reset followed by OK's self-referential helper. The
+ * reset neutralizes any ambient (possibly broken) user-global helper — e.g. a
+ * stale `!gh auth git-credential` left by a past `gh auth setup-git` on a
+ * machine where `gh` is no longer installed, which git would otherwise try
+ * first and fail with "gh: command not found". Empty for tier `none` so a
+ * user's own working helper (osxkeychain, a manual PAT) still authenticates an
+ * anonymous/public clone.
*/
- credentialArgs: string[];
+ gitConfig: string[];
+ /** Tier A only: the gh token to relay via OK_GH_TOKEN/OK_GH_TOKEN_HOST env. */
+ relayToken?: RelayGhToken;
}
interface ResolveAuthOptions {
/** Skip gh detection even if gh is on PATH */
skipGhDetect?: boolean;
+ /**
+ * argv that re-execs THIS CLI (`[execPath, cliEntry]`), used to build the
+ * self-referential credential helper. Defaults to the bare `open-knowledge`
+ * PATH binary for the dev / CLI-on-PATH case. Packaged callers MUST pass the
+ * real argv, since no `open-knowledge` binary exists on the git subprocess
+ * PATH there.
+ */
+ selfCliArgs?: readonly string[];
+}
+
+/**
+ * Build the `credential.helper=` config VALUE that re-invokes THIS CLI as a git
+ * 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` —
+ * the bare `open-knowledge` form this replaces isn't resolvable in the packaged
+ * desktop app (no such binary on the git subprocess PATH).
+ */
+export function buildCliCredentialHelper(selfCliArgs: readonly string[]): string {
+ const prefix = selfCliArgs.map(shellSingleQuote).join(' ');
+ return `credential.helper=!${prefix} auth git-credential`;
}
/**
* Resolve the best available auth method for a given git hostname.
*
+ * All authenticated tiers route through OK's OWN self-referential credential
+ * helper (`!<selfCliArgs> auth git-credential`) and prepend a `credential.helper=`
+ * reset — so the clone authenticates via the token OK already holds regardless of
+ * whether `gh` is installed or what the user's ambient git config points at.
+ *
* Tier A — gh CLI available and authenticated for `host` (detection is
- * host-scoped via `gh auth token --hostname`):
- * credentialArgs = ['-c', "credential.helper=!gh auth git-credential"]
+ * host-scoped via `gh auth token --hostname`): the gh token is relayed via
+ * `relayToken` (env) and the helper returns it (`handleCredentialGet` reads
+ * OK_GH_TOKEN first). No `!gh` shell-out — so it works even when `gh` isn't on
+ * git's subprocess PATH.
*
- * Tier B/C — token stored in TokenStore (keyring or file):
- * credentialArgs = ['-c', "credential.helper=!open-knowledge auth git-credential"]
+ * Tier B/C — token stored in TokenStore (keyring or file): the helper reads it
+ * from the store.
*
- * none — no auth available:
- * credentialArgs = []
+ * none — no OK credential to offer: `gitConfig` empty, ambient config untouched.
*
* @param _detectGhFn - injectable for testing; defaults to the real detectGh
*/
@@ -38,27 +89,25 @@ export async function resolveAuth(
options: ResolveAuthOptions = {},
_detectGhFn: (host?: string) => ReturnType<typeof detectGh> = detectGh,
): Promise<ResolvedAuth> {
- // Tier A: gh CLI
+ const selfHelper = buildCliCredentialHelper(options.selfCliArgs ?? ['open-knowledge']);
+ // Empty reset first, then OK's helper — see ResolvedAuth.gitConfig.
+ const authenticatedConfig = ['credential.helper=', selfHelper];
+
+ // Tier A: gh CLI — relay the gh-resolved token via env.
if (!options.skipGhDetect) {
const gh = _detectGhFn(host);
- if (gh.available) {
- return {
- tier: 'A',
- credentialArgs: ['-c', 'credential.helper=!gh auth git-credential'],
- };
+ if (gh.available && gh.token) {
+ return { tier: 'A', gitConfig: authenticatedConfig, relayToken: { token: gh.token, host } };
}
}
- // Tier B/C: stored token
+ // Tier B/C: stored token — the helper reads it from the TokenStore.
const entry = await tokenStore.get(host);
if (entry != null) {
const tier: AuthTier = entry.gitProtocol === 'ssh' ? 'C' : 'B';
- return {
- tier,
- credentialArgs: ['-c', 'credential.helper=!open-knowledge auth git-credential'],
- };
+ return { tier, gitConfig: authenticatedConfig };
}
// none
- return { tier: 'none', credentialArgs: [] };
+ return { tier: 'none', gitConfig: [] };
}
diff --git a/packages/cli/src/commands/clone.test.ts b/packages/cli/src/commands/clone.test.ts
index 81f390d70..fccaaa008 100644
--- a/packages/cli/src/commands/clone.test.ts
+++ b/packages/cli/src/commands/clone.test.ts
@@ -9,6 +9,7 @@ import type { TokenStore } from '../auth/token-store.ts';
import { OK_DIR } from '../constants.ts';
import {
buildCloneArgs,
+ buildCloneAuthEnv,
buildCloneEnv,
buildCloneGitOptions,
cloneWithBranchFallback,
@@ -19,10 +20,30 @@ import {
isBranchNotFoundError,
resolveClonePrincipal,
resolveCloneUrl,
+ resolveSelfCliArgs,
runClone,
shouldSkipAuthForPublicRepo,
} from './clone.ts';
+describe('resolveSelfCliArgs', () => {
+ it('returns [execPath, cliEntry] from argv', () => {
+ expect(resolveSelfCliArgs(['/usr/bin/node', '/app/cli.mjs', 'clone'], '/usr/bin/node')).toEqual(
+ ['/usr/bin/node', '/app/cli.mjs'],
+ );
+ });
+
+ it('falls back to [execPath] when argv has no entry script', () => {
+ expect(resolveSelfCliArgs(['/usr/bin/node'], '/usr/bin/node')).toEqual(['/usr/bin/node']);
+ });
+
+ // A truthiness check (not `!== undefined`) is load-bearing: an empty-string
+ // argv[1] would otherwise quote into `!'/usr/bin/node' '' auth …` — a broken
+ // shell invocation. Electron startup shapes can produce odd argv.
+ it('treats an empty-string argv[1] as absent and falls back to [execPath]', () => {
+ expect(resolveSelfCliArgs(['/usr/bin/node', ''], '/usr/bin/node')).toEqual(['/usr/bin/node']);
+ });
+});
+
describe('resolveClonePrincipal', () => {
const storeReturning = (entry: { login: string; token: string } | null): TokenStore =>
({ get: async () => entry }) as unknown as TokenStore;
@@ -150,10 +171,10 @@ describe('handleCloneFailure', () => {
});
describe('buildCloneEnv', () => {
- // Regression guard: clone must INHERIT the caller's env (so the Tier-A `gh`
- // credential helper can find `gh` on PATH + its config via HOME), not replace
- // it — simple-git's `.env()` replaces wholesale. A revert to a bare object
- // would silently re-break Tier A on stock (e.g. Homebrew) installs.
+ // Regression guard: clone must INHERIT the caller's env (git's transport
+ // subprocesses + SSH need PATH; the re-invoked credential helper + SSH keys
+ // reach their stores via HOME), not replace it — simple-git's `.env()`
+ // replaces wholesale. A revert to a bare object silently re-breaks auth.
test('inherits PATH and HOME from the source env', () => {
const env = buildCloneEnv({ PATH: '/opt/homebrew/bin:/usr/bin', HOME: '/Users/me' });
expect(env.PATH).toBe('/opt/homebrew/bin:/usr/bin');
@@ -171,6 +192,57 @@ describe('buildCloneEnv', () => {
const env = buildCloneEnv({ PATH: '/usr/bin', SOME_UNSET: undefined });
expect('SOME_UNSET' in env).toBe(false);
});
+
+ // In the packaged desktop app the credential helper re-execs the Electron
+ // binary; without ELECTRON_RUN_AS_NODE=1 that exec boots the GUI app instead
+ // of running the CLI script, so this var surviving the spread is what keeps
+ // the helper a helper. A switch to a curated env allowlist (as the sync
+ // path uses) must carry it explicitly.
+ test('inherits ELECTRON_RUN_AS_NODE so the packaged helper re-execs as Node', () => {
+ const env = buildCloneEnv({ PATH: '/usr/bin', ELECTRON_RUN_AS_NODE: '1' });
+ expect(env.ELECTRON_RUN_AS_NODE).toBe('1');
+ });
+});
+
+describe('buildCloneAuthEnv', () => {
+ // The relay is the Tier-A mechanism: the token resolved in-process must reach
+ // the spawned credential helper via git's env under exactly these keys
+ // (handleCredentialGet reads OK_GH_TOKEN / OK_GH_TOKEN_HOST first).
+ test('sets OK_GH_TOKEN and OK_GH_TOKEN_HOST when a relay token is present', () => {
+ const env = buildCloneAuthEnv(
+ { relayToken: { token: 'ghs_relay', host: 'github.com' } },
+ { PATH: '/usr/bin' },
+ );
+ expect(env.OK_GH_TOKEN).toBe('ghs_relay');
+ expect(env.OK_GH_TOKEN_HOST).toBe('github.com');
+ });
+
+ test('sets no relay vars when relayToken is absent (Tier B/C/none)', () => {
+ const env = buildCloneAuthEnv({}, { PATH: '/usr/bin' });
+ expect('OK_GH_TOKEN' in env).toBe(false);
+ expect('OK_GH_TOKEN_HOST' in env).toBe(false);
+ });
+
+ // A stale token exported in the parent shell must not shadow the token
+ // store inside the helper: without a relay decision from THIS resolution,
+ // inherited relay vars are stripped, not passed through.
+ test('strips an inherited OK_GH_TOKEN when no relay token was resolved', () => {
+ const env = buildCloneAuthEnv(
+ {},
+ { PATH: '/usr/bin', OK_GH_TOKEN: 'ghs_stale', OK_GH_TOKEN_HOST: 'github.com' },
+ );
+ expect('OK_GH_TOKEN' in env).toBe(false);
+ expect('OK_GH_TOKEN_HOST' in env).toBe(false);
+ });
+
+ test('a resolved relay token overrides an inherited stale one', () => {
+ const env = buildCloneAuthEnv(
+ { relayToken: { token: 'ghs_fresh', host: 'ghes.acme.test' } },
+ { PATH: '/usr/bin', OK_GH_TOKEN: 'ghs_stale', OK_GH_TOKEN_HOST: 'github.com' },
+ );
+ expect(env.OK_GH_TOKEN).toBe('ghs_fresh');
+ expect(env.OK_GH_TOKEN_HOST).toBe('ghes.acme.test');
+ });
});
describe('buildCloneGitOptions', () => {
diff --git a/packages/cli/src/commands/clone.ts b/packages/cli/src/commands/clone.ts
index 730434671..63c0d2107 100644
--- a/packages/cli/src/commands/clone.ts
+++ b/packages/cli/src/commands/clone.ts
@@ -15,7 +15,7 @@ import {
} from '@inkeep/open-knowledge-server';
import { Command } from 'commander';
import simpleGit, { type SimpleGitOptions } from 'simple-git';
-import { resolveAuth } from '../auth/resolve-auth.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';
import { parseGitUrl } from '../github/url.ts';
@@ -56,13 +56,14 @@ function emit(json: boolean, obj: Record<string, unknown>): void {
* Build the environment for the spawned clone git process.
*
* Inherits the caller's full environment: clone is a foreground command in the
- * user's own shell context, so the Tier-A `gh` credential helper needs the real
- * PATH (to find `gh`, often Homebrew-only at /opt/homebrew/bin) and HOME (so
- * `gh` and git locate their config). simple-git's `.env()` REPLACES the child
- * env, so we must spread the source env rather than pass a bare object — the
- * earlier `{ GIT_TERMINAL_PROMPT: '0' }`-only form silently stripped both,
- * masking Tier A on stock installs (it only appeared to work where a leftover
- * osxkeychain credential answered first).
+ * user's own shell context, so git needs the real PATH (to resolve its transport
+ * subprocesses and, for an SSH remote, `ssh`) and HOME (so git and SSH locate
+ * `~/.gitconfig` / `~/.ssh`, and so the self-referential credential helper —
+ * re-invoked as `[execPath, cliEntry]`, with `ELECTRON_RUN_AS_NODE` carried
+ * through this spread — reaches its HOME-based token store). simple-git's
+ * `.env()` REPLACES the child env, so we must spread the source env rather than
+ * pass a bare object — the earlier `{ GIT_TERMINAL_PROMPT: '0' }`-only form
+ * silently stripped both, breaking auth on stock installs.
*
* Overrides applied after the spread: `GIT_TERMINAL_PROMPT=0` so a credential
* miss fails fast instead of hanging on a TTY-less prompt, and `LANG`/`LC_ALL=C`
@@ -82,6 +83,48 @@ export function buildCloneEnv(sourceEnv: NodeJS.ProcessEnv = process.env): Recor
return env;
}
+/**
+ * Compose the full clone git env: `buildCloneEnv` plus the gh-token relay for
+ * Tier A. When a gh token was resolved, relay it to the self-referential
+ * credential helper via env (the helper reads OK_GH_TOKEN first) rather than
+ * making git shell out to `gh`, which may not be on the git subprocess PATH.
+ * Without a relay token, any OK_GH_TOKEN inherited from the parent env is
+ * 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.
+ */
+export function buildCloneAuthEnv(
+ resolved: Pick<ResolvedAuth, 'relayToken'>,
+ sourceEnv: NodeJS.ProcessEnv = process.env,
+): Record<string, string> {
+ const env = buildCloneEnv(sourceEnv);
+ if (resolved.relayToken) {
+ env.OK_GH_TOKEN = resolved.relayToken.token;
+ env.OK_GH_TOKEN_HOST = resolved.relayToken.host;
+ } else {
+ delete env.OK_GH_TOKEN;
+ delete env.OK_GH_TOKEN_HOST;
+ }
+ return env;
+}
+
+/**
+ * The argv that re-execs THIS CLI, used to build the self-referential git
+ * credential helper (`!<argv> auth git-credential`). `[execPath, cliEntry]`:
+ * under the packaged `ok.sh` wrapper this resolves to `[<Electron>, <cli.mjs>]`
+ * with `ELECTRON_RUN_AS_NODE=1` inherited via `buildCloneEnv` — the same
+ * Electron-as-Node re-invocation the sync path uses — so git can actually run
+ * the helper, unlike a bare `open-knowledge` that isn't on its subprocess PATH.
+ * `argv` / `execPath` are injectable for tests.
+ */
+export function resolveSelfCliArgs(
+ argv: readonly string[] = process.argv,
+ execPath: string = process.execPath,
+): string[] {
+ const entry = argv[1];
+ return entry ? [execPath, entry] : [execPath];
+}
+
/**
* Compose the `git clone` arg vector for `simple-git`'s `git.clone(url, dir, args)`.
*
@@ -292,18 +335,17 @@ 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 = shouldSkipAuthForPublicRepo(parsed.protocol, parsed.hostname, isPublic)
- ? { tier: 'none' as const, credentialArgs: [] as string[] }
- : await resolveAuth(parsed.hostname, tokenStore, {});
-
- // Inherit the user's env (PATH/HOME for the gh helper) with our fixed
- // overrides — see buildCloneEnv for the env-replacement rationale.
- const env = buildCloneEnv();
+ const resolved: ResolvedAuth = shouldSkipAuthForPublicRepo(
+ parsed.protocol,
+ parsed.hostname,
+ isPublic,
+ )
+ ? { tier: 'none', gitConfig: [] }
+ : await resolveAuth(parsed.hostname, tokenStore, { selfCliArgs: resolveSelfCliArgs() });
- // Build -c credential.helper config if needed
- const gitConfig = resolved.credentialArgs.length >= 2 ? [resolved.credentialArgs[1]] : [];
+ const env = buildCloneAuthEnv(resolved);
- const gitOptions = buildCloneGitOptions(cwd, gitConfig);
+ const gitOptions = buildCloneGitOptions(cwd, resolved.gitConfig);
const git = simpleGit(gitOptions as Partial<SimpleGitOptions>).env(env);
let lastPct = -1;
diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.ts
index df4af47b2..d94e0499d 100644
--- a/packages/server/src/server-factory.ts
+++ b/packages/server/src/server-factory.ts
@@ -396,6 +396,16 @@ const PARK_SNAPSHOT_ORIGIN = (() => {
* 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'];