Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(open-knowledge): derive GitHub host from workspace origin for auth and sync (#2647)

omar-inkeep3542148eeecb
diff --git a/.changeset/ghes-host-aware-auth.md b/.changeset/ghes-host-aware-auth.md
new file mode 100644
index 000000000..4dc72b317
--- /dev/null
+++ b/.changeset/ghes-host-aware-auth.md
@@ -0,0 +1,15 @@
+---
+'@inkeep/open-knowledge': patch
+'@inkeep/open-knowledge-server': patch
+'@inkeep/open-knowledge-core': patch
+---
+
+**Fix:** GitHub Enterprise Server hosts are no longer ignored (#597). Auth
+resolution, the sync token relay, and the push-permission probe now derive
+their host from the workspace's origin remote instead of assuming github.com:
+`resolveAuth` scopes gh detection to the origin host, the sync engine relays
+the origin host's token, origin classification recognizes GHES hostnames
+(with browsable remote links in the sync UI), the `ok auth` subcommands
+default `--host` to the workspace origin, and the app's account panel shows
+the identity for the host the workspace actually syncs with. Sharing remains
+github.com-only for now.
diff --git a/docs/content/features/github-sync.mdx b/docs/content/features/github-sync.mdx
index bcd98fb3e..4da62326e 100644
--- a/docs/content/features/github-sync.mdx
+++ b/docs/content/features/github-sync.mdx
@@ -77,6 +77,8 @@ If you are logged in with the GitHub CLI, OpenKnowledge will use those credentia
Manage the connection from **Settings → Account**. **Connect GitHub** authorizes OpenKnowledge to browse and sync your repositories; **Disconnect** clears OpenKnowledge's GitHub token only. From a terminal, the [`ok auth`](/docs/reference/cli) subcommands manage the same credentials: `ok auth signout` matches **Disconnect**, `ok auth pat` stores a Personal Access Token when device authentication isn't an option, and `--host` targets GitHub Enterprise.
+When a project's `origin` remote points at a GitHub Enterprise Server host, OpenKnowledge resolves credentials and identity for that host automatically: the account shown in settings, the sync token, the push-permission check, and the `ok auth` default `--host` all follow the workspace's remote instead of assuming github.com. Sharing links currently requires a github.com remote.
+
The sync status indicator surfaces an auth-error state when stored credentials stop working, and sync pauses until you reconnect.
## Sync status and conflicts
diff --git a/packages/app/src/lib/transports/auth-query-transport.ts b/packages/app/src/lib/transports/auth-query-transport.ts
index 370dbb1f2..2270495e0 100644
--- a/packages/app/src/lib/transports/auth-query-transport.ts
+++ b/packages/app/src/lib/transports/auth-query-transport.ts
@@ -22,6 +22,13 @@ import type {
OkLocalOpAuthStatusResponse,
} from '@/lib/desktop-bridge-types';
+/**
+ * Client-side fallback only — the coalescing-map key and the display `host`
+ * on error responses when the caller omitted one. Deliberately NOT sent on
+ * the wire: a host-less request lets the server derive the host from the
+ * workspace's origin remote, which the client cannot know. Workspace-scoped
+ * callers should omit `host`.
+ */
const DEFAULT_AUTH_QUERY_HOST = 'github.com';
// Default HTTP transports are created per component; keep status single-flight
// at module scope so overlapping callers share one local-op request.
diff --git a/packages/cli/src/auth/resolve-auth.test.ts b/packages/cli/src/auth/resolve-auth.test.ts
index 8f3e0c179..94b1e54e6 100644
--- a/packages/cli/src/auth/resolve-auth.test.ts
+++ b/packages/cli/src/auth/resolve-auth.test.ts
@@ -104,6 +104,21 @@ describe('resolveAuth', () => {
// Host isolation
// ---------------------------------------------------------------------------
+ test('Tier A detection is scoped to the requested host', async () => {
+ const store = makeStore(tmpDir);
+ const seenHosts: (string | undefined)[] = [];
+ // gh is authenticated for github.com but not the GHES host.
+ const ghGithubComOnly = (host?: string): GhDetectResult => {
+ seenHosts.push(host);
+ return host === 'ghes.acme.test' ? { available: false } : { available: true, token: 'x' };
+ };
+ const result = await resolveAuth('ghes.acme.test', store, {}, ghGithubComOnly);
+ expect(seenHosts).toEqual(['ghes.acme.test']);
+ expect(result.tier).toBe('none');
+ const githubResult = await resolveAuth('github.com', store, {}, ghGithubComOnly);
+ expect(githubResult.tier).toBe('A');
+ });
+
test('token for different host returns none', async () => {
const store = makeStore(tmpDir);
await store.set('gitlab.com', 'bob', 'glpat_xyz');
diff --git a/packages/cli/src/auth/resolve-auth.ts b/packages/cli/src/auth/resolve-auth.ts
index 3118d5450..371c29fb9 100644
--- a/packages/cli/src/auth/resolve-auth.ts
+++ b/packages/cli/src/auth/resolve-auth.ts
@@ -20,7 +20,8 @@ interface ResolveAuthOptions {
/**
* Resolve the best available auth method for a given git hostname.
*
- * Tier A — gh CLI available and authenticated:
+ * 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"]
*
* Tier B/C — token stored in TokenStore (keyring or file):
@@ -35,11 +36,11 @@ export async function resolveAuth(
host: string,
tokenStore: TokenStore,
options: ResolveAuthOptions = {},
- _detectGhFn: () => ReturnType<typeof detectGh> = detectGh,
+ _detectGhFn: (host?: string) => ReturnType<typeof detectGh> = detectGh,
): Promise<ResolvedAuth> {
// Tier A: gh CLI
if (!options.skipGhDetect) {
- const gh = _detectGhFn();
+ const gh = _detectGhFn(host);
if (gh.available) {
return {
tier: 'A',
diff --git a/packages/cli/src/commands/auth/login.ts b/packages/cli/src/commands/auth/login.ts
index f613647f8..c4d5e583d 100644
--- a/packages/cli/src/commands/auth/login.ts
+++ b/packages/cli/src/commands/auth/login.ts
@@ -1,3 +1,4 @@
+import { originGitHubHost } from '@inkeep/open-knowledge-server';
import { Command } from 'commander';
import { runDeviceFlow } from '../../auth/device-flow.ts';
import type { TokenStore } from '../../auth/token-store.ts';
@@ -96,10 +97,14 @@ async function runLogin(
export function loginCommand(getTokenStore: () => Promise<TokenStore>): Command {
return new Command('login')
.description('Authenticate with GitHub via Device Flow')
- .option('--host <host>', 'GitHub or GitHub Enterprise hostname', 'github.com')
+ .option(
+ '--host <host>',
+ 'GitHub or GitHub Enterprise hostname (default: workspace origin host)',
+ )
.option('--json', 'Output JSONL progress events', false)
- .action(async (opts: LoginOptions) => {
+ .action(async (opts: Omit<LoginOptions, 'host'> & { host?: string }) => {
+ const host = opts.host ?? originGitHubHost(process.cwd());
const store = await getTokenStore();
- await runLogin(opts, store);
+ await runLogin({ ...opts, host }, store);
});
}
diff --git a/packages/cli/src/commands/auth/pat.ts b/packages/cli/src/commands/auth/pat.ts
index 306362d64..b623f9bd7 100644
--- a/packages/cli/src/commands/auth/pat.ts
+++ b/packages/cli/src/commands/auth/pat.ts
@@ -1,3 +1,4 @@
+import { originGitHubHost } from '@inkeep/open-knowledge-server';
import password from '@inquirer/password';
import { Octokit } from '@octokit/rest';
import { Command } from 'commander';
@@ -53,9 +54,13 @@ async function runPat(
export function patCommand(getTokenStore: () => Promise<TokenStore>): Command {
return new Command('pat')
.description('Store a Personal Access Token')
- .option('--host <host>', 'GitHub or GitHub Enterprise hostname', 'github.com')
+ .option(
+ '--host <host>',
+ 'GitHub or GitHub Enterprise hostname (default: workspace origin host)',
+ )
.option('--json', 'Output JSON', false)
- .action(async (opts: PatOptions) => {
- await runPat(opts, await getTokenStore());
+ .action(async (opts: Omit<PatOptions, 'host'> & { host?: string }) => {
+ const host = opts.host ?? originGitHubHost(process.cwd());
+ await runPat({ ...opts, host }, await getTokenStore());
});
}
diff --git a/packages/cli/src/commands/auth/repos.ts b/packages/cli/src/commands/auth/repos.ts
index ae3d04b45..f008465d6 100644
--- a/packages/cli/src/commands/auth/repos.ts
+++ b/packages/cli/src/commands/auth/repos.ts
@@ -1,3 +1,4 @@
+import { originGitHubHost } from '@inkeep/open-knowledge-server';
import { Octokit } from '@octokit/rest';
import { Command } from 'commander';
import { detectGh } from '../../auth/gh-detect.ts';
@@ -60,9 +61,13 @@ async function runRepos(opts: ReposOptions, tokenStore: TokenStore): Promise<voi
export function reposCommand(getTokenStore: () => Promise<TokenStore>): Command {
return new Command('repos')
.description('List accessible repositories')
- .option('--host <host>', 'GitHub or GitHub Enterprise hostname', 'github.com')
+ .option(
+ '--host <host>',
+ 'GitHub or GitHub Enterprise hostname (default: workspace origin host)',
+ )
.option('--json', 'Output JSON', false)
- .action(async (opts: ReposOptions) => {
- await runRepos(opts, await getTokenStore());
+ .action(async (opts: Omit<ReposOptions, 'host'> & { host?: string }) => {
+ const host = opts.host ?? originGitHubHost(process.cwd());
+ await runRepos({ ...opts, host }, await getTokenStore());
});
}
diff --git a/packages/cli/src/commands/auth/signout.ts b/packages/cli/src/commands/auth/signout.ts
index 3e3311e66..cd63e39ae 100644
--- a/packages/cli/src/commands/auth/signout.ts
+++ b/packages/cli/src/commands/auth/signout.ts
@@ -1,3 +1,4 @@
+import { originGitHubHost } from '@inkeep/open-knowledge-server';
import { Command } from 'commander';
import { clearTokenFromAllBackends } from '../../auth/token-store.ts';
@@ -26,8 +27,12 @@ async function runSignout(opts: SignoutOptions): Promise<void> {
export function signoutCommand(): Command {
return new Command('signout')
.description('Remove stored credentials')
- .option('--host <host>', 'GitHub hostname', 'github.com')
- .action(async (opts: SignoutOptions) => {
- await runSignout(opts);
+ .option(
+ '--host <host>',
+ 'GitHub or GitHub Enterprise hostname (default: workspace origin host)',
+ )
+ .action(async (opts: Omit<SignoutOptions, 'host'> & { host?: string }) => {
+ const host = opts.host ?? originGitHubHost(process.cwd());
+ await runSignout({ ...opts, host });
});
}
diff --git a/packages/cli/src/commands/auth/status.ts b/packages/cli/src/commands/auth/status.ts
index 4411ed8f8..802be2b82 100644
--- a/packages/cli/src/commands/auth/status.ts
+++ b/packages/cli/src/commands/auth/status.ts
@@ -1,3 +1,4 @@
+import { originGitHubHost } from '@inkeep/open-knowledge-server';
import { Octokit } from '@octokit/rest';
import { Command } from 'commander';
import { detectGh } from '../../auth/gh-detect.ts';
@@ -113,9 +114,13 @@ async function runStatus(opts: StatusOptions, tokenStore: TokenStore): Promise<v
export function statusCommand(getTokenStore: () => Promise<TokenStore>): Command {
return new Command('status')
.description('Show authentication status')
- .option('--host <host>', 'GitHub or GitHub Enterprise hostname', 'github.com')
+ .option(
+ '--host <host>',
+ 'GitHub or GitHub Enterprise hostname (default: workspace origin host)',
+ )
.option('--json', 'Output JSON', false)
- .action(async (opts: StatusOptions) => {
- await runStatus(opts, await getTokenStore());
+ .action(async (opts: Omit<StatusOptions, 'host'> & { host?: string }) => {
+ const host = opts.host ?? originGitHubHost(process.cwd());
+ await runStatus({ ...opts, host }, await getTokenStore());
});
}
diff --git a/packages/cli/src/commands/auth/validate-host.ts b/packages/cli/src/commands/auth/validate-host.ts
index d4d1a7386..4fd4b3fc5 100644
--- a/packages/cli/src/commands/auth/validate-host.ts
+++ b/packages/cli/src/commands/auth/validate-host.ts
@@ -1,19 +1,14 @@
-const KNOWN_NON_GITHUB_HOSTS = new Set([
- 'gitlab.com',
- 'bitbucket.org',
- 'codeberg.org',
- 'gitea.com',
- 'sr.ht',
- 'sourcehut.org',
-]);
+import { KNOWN_NON_GITHUB_GIT_HOSTS } from '@inkeep/open-knowledge-core';
/**
* Reject hosts that are known non-GitHub forges. Unknown hosts are allowed
- * through — they may be GitHub Enterprise Server instances.
+ * through — they may be GitHub Enterprise Server instances. The denylist is
+ * shared with the server's origin-remote classification
+ * (`KNOWN_NON_GITHUB_GIT_HOSTS` in core) so the two can never drift.
*/
export function validateGitHubHost(host: string): void {
const normalized = host.toLowerCase().replace(/:\d+$/, '');
- if (KNOWN_NON_GITHUB_HOSTS.has(normalized)) {
+ if (KNOWN_NON_GITHUB_GIT_HOSTS.has(normalized)) {
process.stderr.write(
`Error: ${host} is not a GitHub host. Only GitHub and GitHub Enterprise Server are supported.\n`,
);
diff --git a/packages/cli/src/project-anchor.test.ts b/packages/cli/src/project-anchor.test.ts
index db0658ea5..9ca2d5200 100644
--- a/packages/cli/src/project-anchor.test.ts
+++ b/packages/cli/src/project-anchor.test.ts
@@ -35,6 +35,9 @@ describe('resolveProjectAnchor — command gating', () => {
'ui',
'mcp',
'preview',
+ // `auth` anchors so its `--host` default derives from the enclosing
+ // project's origin host.
+ 'auth',
])('anchors lifecycle command %s', (name) => {
expect(resolveProjectAnchor(name, '/proj/sub/dir', stubHit)).toBe('/proj');
});
@@ -49,7 +52,6 @@ describe('resolveProjectAnchor — command gating', () => {
'clone',
'open',
'ps',
- 'auth',
'config',
'diagnose',
])('keeps literal-cwd semantics for %s without probing the filesystem', (name) => {
diff --git a/packages/cli/src/project-anchor.ts b/packages/cli/src/project-anchor.ts
index 09ad935fc..f827a34ec 100644
--- a/packages/cli/src/project-anchor.ts
+++ b/packages/cli/src/project-anchor.ts
@@ -36,6 +36,10 @@ const PROJECT_ANCHORED_COMMANDS: ReadonlySet<string> = new Set([
// enclosing project root when run from a subdirectory. `uninstall` is global
// and deliberately NOT anchored (it discovers projects itself).
'deinit',
+ // `auth` defaults `--host` to the enclosing project's origin host, so it
+ // must anchor when run from a subdirectory; auth commands take no path
+ // arguments, so literal-cwd semantics have nothing to preserve.
+ 'auth',
]);
/**
diff --git a/packages/core/src/constants/github.ts b/packages/core/src/constants/github.ts
index 09f147846..799733b59 100644
--- a/packages/core/src/constants/github.ts
+++ b/packages/core/src/constants/github.ts
@@ -4,3 +4,18 @@
* `OPEN_KNOWLEDGE_GITHUB_CLIENT_ID` environment variable.
*/
export const DEFAULT_GITHUB_OAUTH_CLIENT_ID = 'Ov23liqlSd0V1MwR6rhI';
+
+/**
+ * Hosts that are known non-GitHub forges. GHES hostnames are arbitrary, so
+ * GitHub-ness cannot be allowlisted; any host not listed here is treated as
+ * github.com or a GitHub Enterprise Server host. Shared by the CLI `--host`
+ * validation and the server's origin-remote classification.
+ */
+export const KNOWN_NON_GITHUB_GIT_HOSTS: ReadonlySet<string> = new Set([
+ 'gitlab.com',
+ 'bitbucket.org',
+ 'codeberg.org',
+ 'gitea.com',
+ 'sr.ht',
+ 'sourcehut.org',
+]);
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 7282d9edf..2f25d0d12 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -213,7 +213,10 @@ export {
} from './constants/embedded-host.ts';
export { SHOW_INSTALL_SKILL } from './constants/feature-flags.ts';
export type { OkFolderState } from './constants/folder-state.ts';
-export { DEFAULT_GITHUB_OAUTH_CLIENT_ID } from './constants/github.ts';
+export {
+ DEFAULT_GITHUB_OAUTH_CLIENT_ID,
+ KNOWN_NON_GITHUB_GIT_HOSTS,
+} from './constants/github.ts';
export { isOrphanMode, ORPHAN_MODES, type OrphanMode } from './constants/graph.ts';
export { GREP_MAX_RESULTS, MCP_SERVER_NAME, READ_DOCUMENT_HISTORY_DEPTH } from './constants/mcp.ts';
export { MENU_LABELS, type MenuLabelKey } from './constants/menu-labels.ts';
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index 81b8bc0a2..fbe365f02 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -334,6 +334,7 @@ import {
import { computeShareFreshness } from './share/freshness.ts';
import {
branchExistsOnOrigin,
+ originGitHubHost,
readGitHeadBranch,
readOriginGitHubRepo,
} from './share/git-context.ts';
@@ -11637,6 +11638,13 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
const LOCAL_OP_AUTH_REPOS_KEY = '/api/local-op/auth/repos';
const LOCAL_OP_AUTH_SIGNOUT_KEY = '/api/local-op/auth/signout';
+ /**
+ * Default host for the auth relay endpoints when the request omits `host`.
+ * Read per-request (not cached): the origin remote can change over the
+ * server's lifetime.
+ */
+ const defaultAuthHost = (): string => originGitHubHost(projectDir ?? contentDir);
+
// In-flight device-flow controller for the login endpoint. Lets a disconnect
// or a fresh start free/displace the slot synchronously instead of waiting
// for the cancelled child to exit. Object identity is the ownership token:
@@ -11675,7 +11683,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
res: ServerResponse,
body: LocalOpAuthHostRequest,
): Promise<void> {
- const host = body.host ?? 'github.com';
+ const host = body.host ?? defaultAuthHost();
if (!localOpGuard.tryAcquire(LOCAL_OP_AUTH_LOGIN_KEY)) {
const stale = authLoginInFlight;
@@ -11816,7 +11824,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
const handleLocalOpAuthStatus = withValidation(
LocalOpAuthHostRequestSchema,
async (_req, res, body) => {
- const host = body.host ?? 'github.com';
+ const host = body.host ?? defaultAuthHost();
if (!localOpGuard.tryAcquire(LOCAL_OP_AUTH_STATUS_KEY)) {
errorResponse(
@@ -11946,7 +11954,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
res: ServerResponse,
body: LocalOpAuthHostRequest,
): Promise<void> {
- const host = body.host ?? 'github.com';
+ const host = body.host ?? defaultAuthHost();
if (!localOpGuard.tryAcquire(LOCAL_OP_AUTH_REPOS_KEY)) {
errorResponse(
@@ -12094,7 +12102,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
const handleLocalOpAuthSignout = withValidation(
LocalOpAuthHostRequestSchema,
async (_req, res, body) => {
- const host = body.host ?? 'github.com';
+ const host = body.host ?? defaultAuthHost();
if (!localOpGuard.tryAcquire(LOCAL_OP_AUTH_SIGNOUT_KEY)) {
errorResponse(
@@ -16568,7 +16576,9 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
);
return;
}
- if (origin.kind === 'non-github') {
+ // `construct-url.ts` builds github.com-only links, so GHES origins
+ // must keep failing this gate until the builders take a host.
+ if (origin.kind === 'non-github' || origin.host !== 'github.com') {
emitShareConstructUrlLog('non-github-remote', { kind: body.kind });
successResponse(
res,
diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts
index bf5296ca9..ac82a4066 100644
--- a/packages/server/src/index.ts
+++ b/packages/server/src/index.ts
@@ -454,6 +454,7 @@ export {
hasGcLogLatch,
type ShadowObjectStats,
} from './shadow-repo-stats.ts';
+export { originGitHubHost } from './share/git-context.ts';
export {
createEphemeralProjectDir,
prepareSingleFileOpen,
diff --git a/packages/server/src/share/construct-url.test.ts b/packages/server/src/share/construct-url.test.ts
index 0b3af5c93..953ed5f0d 100644
--- a/packages/server/src/share/construct-url.test.ts
+++ b/packages/server/src/share/construct-url.test.ts
@@ -214,6 +214,24 @@ describe('POST /api/share/construct-url', () => {
expect(json).toEqual({ ok: false, error: 'non-github-remote' });
});
+ test('non-github-remote: GHES origins are refused while the URL builders are github.com-only', async () => {
+ // Origin classification recognizes GHES hosts, so this gate is the only
+ // thing preventing share from minting github.com links for a repo that
+ // lives on an enterprise host. Pins the `origin.host !== 'github.com'`
+ // arm of the gate.
+ rig = await bootRig((projectDir) => {
+ seedRemoteAndHead(projectDir, {
+ head: 'ref: refs/heads/main\n',
+ originUrl: 'https://ghes.acme.test/team/notes.git',
+ branchesOnOrigin: ['main'],
+ });
+ });
+ const res = await postConstructUrl(rig.port, { kind: 'doc', docPath: 'a.md' });
+ expect(res.status).toBe(200);
+ const json = await res.json();
+ expect(json).toEqual({ ok: false, error: 'non-github-remote' });
+ });
+
test('invalid-path: rejects .. segment', async () => {
rig = await bootRig((projectDir) => {
seedRemoteAndHead(projectDir, {
diff --git a/packages/server/src/share/git-context.test.ts b/packages/server/src/share/git-context.test.ts
index 9a4779558..11d55f975 100644
--- a/packages/server/src/share/git-context.test.ts
+++ b/packages/server/src/share/git-context.test.ts
@@ -4,6 +4,7 @@ import { tmpdir } from 'node:os';
import { join, relative, resolve } from 'node:path';
import {
branchExistsOnOrigin,
+ originGitHubHost,
readGitHeadBranch,
readOriginGitHubRepo,
readSyncRemoteInfo,
@@ -113,6 +114,7 @@ describe('readOriginGitHubRepo', () => {
seedRepo(dir, { config: CANONICAL_CONFIG_HTTPS });
expect(readOriginGitHubRepo(dir)).toEqual({
kind: 'ok',
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
});
@@ -124,6 +126,7 @@ describe('readOriginGitHubRepo', () => {
});
expect(readOriginGitHubRepo(dir)).toEqual({
kind: 'ok',
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
});
@@ -135,6 +138,7 @@ describe('readOriginGitHubRepo', () => {
});
expect(readOriginGitHubRepo(dir)).toEqual({
kind: 'ok',
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
});
@@ -146,6 +150,7 @@ describe('readOriginGitHubRepo', () => {
});
expect(readOriginGitHubRepo(dir)).toEqual({
kind: 'ok',
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
});
@@ -158,11 +163,70 @@ describe('readOriginGitHubRepo', () => {
expect(readOriginGitHubRepo(dir)).toEqual({ kind: 'non-github' });
});
- test('returns non-github for HTTPS gitlab URL', () => {
+ test('presumes an unknown host is a GitHub Enterprise host', () => {
+ // GHES hostnames are arbitrary, so unknown hosts classify as GitHub with
+ // the host carried in the result. A self-hosted non-GitHub forge on a
+ // custom domain is indistinguishable and lands here too — downstream
+ // consumers degrade gracefully for it.
seedRepo(dir, {
- config: '[remote "origin"]\n\turl = https://gitlab.example.com/inkeep/open-knowledge.git\n',
+ config: '[remote "origin"]\n\turl = https://ghes.acme.test/inkeep/open-knowledge.git\n',
+ });
+ expect(readOriginGitHubRepo(dir)).toEqual({
+ kind: 'ok',
+ host: 'ghes.acme.test',
+ owner: 'inkeep',
+ repo: 'open-knowledge',
+ });
+ });
+
+ test('parses scp-style GHES origin and carries the host', () => {
+ seedRepo(dir, {
+ config: '[remote "origin"]\n\turl = [email protected]:team/kb.git\n',
+ });
+ expect(readOriginGitHubRepo(dir)).toEqual({
+ kind: 'ok',
+ host: 'github.corp.example.com',
+ owner: 'team',
+ repo: 'kb',
+ });
+ });
+
+ test('strips a non-standard port from a GHES host', () => {
+ // Downstream consumers (`gh auth token --hostname`, the `/api/v3` probe
+ // base) address the host by name; a retained `:8443` would break both.
+ seedRepo(dir, {
+ config: '[remote "origin"]\n\turl = https://ghes.acme.test:8443/acme/kb.git\n',
+ });
+ expect(readOriginGitHubRepo(dir)).toEqual({
+ kind: 'ok',
+ host: 'ghes.acme.test',
+ owner: 'acme',
+ repo: 'kb',
+ });
+ });
+
+ test('parses the git:// protocol form', () => {
+ seedRepo(dir, {
+ config: '[remote "origin"]\n\turl = git://github.com/inkeep/open-knowledge.git\n',
+ });
+ expect(readOriginGitHubRepo(dir)).toEqual({
+ kind: 'ok',
+ host: 'github.com',
+ owner: 'inkeep',
+ repo: 'open-knowledge',
+ });
+ });
+
+ test('normalizes host casing, port, and www-folding', () => {
+ seedRepo(dir, {
+ config: '[remote "origin"]\n\turl = https://WWW.GitHub.com:443/inkeep/open-knowledge.git\n',
+ });
+ expect(readOriginGitHubRepo(dir)).toEqual({
+ kind: 'ok',
+ host: 'github.com',
+ owner: 'inkeep',
+ repo: 'open-knowledge',
});
- expect(readOriginGitHubRepo(dir)).toEqual({ kind: 'non-github' });
});
test('returns no-remote when [remote "origin"] section is absent', () => {
@@ -189,6 +253,17 @@ describe('readOriginGitHubRepo', () => {
expect(readOriginGitHubRepo(dir)).toEqual({ kind: 'non-github' });
});
+ test('credential-embedded https URLs classify as non-github (documented limitation)', () => {
+ // The https form deliberately excludes userinfo, matching the cli's
+ // `parseGitUrl` grammar — a `user:pass@host` origin falls through to
+ // `non-github` (and downstream host defaults fall back to github.com),
+ // the same treatment such URLs received for github.com itself.
+ seedRepo(dir, {
+ config: '[remote "origin"]\n\turl = https://user:[email protected]/org/repo.git\n',
+ });
+ expect(readOriginGitHubRepo(dir)).toEqual({ kind: 'non-github' });
+ });
+
test('uses the first url= line and ignores subsequent ones', () => {
seedRepo(dir, {
config:
@@ -196,6 +271,7 @@ describe('readOriginGitHubRepo', () => {
});
expect(readOriginGitHubRepo(dir)).toEqual({
kind: 'ok',
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
});
@@ -208,12 +284,50 @@ describe('readOriginGitHubRepo', () => {
});
expect(readOriginGitHubRepo(dir)).toEqual({
kind: 'ok',
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
});
});
});
+describe('originGitHubHost', () => {
+ let dir: string;
+
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'share-git-host-'));
+ });
+
+ afterEach(() => {
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ test('returns github.com for a github.com origin', () => {
+ seedRepo(dir, {
+ config: '[remote "origin"]\n\turl = https://github.com/inkeep/open-knowledge.git\n',
+ });
+ expect(originGitHubHost(dir)).toBe('github.com');
+ });
+
+ test('returns the enterprise host for a GHES origin', () => {
+ seedRepo(dir, {
+ config: '[remote "origin"]\n\turl = https://ghes.acme.test/acme/kb.git\n',
+ });
+ expect(originGitHubHost(dir)).toBe('ghes.acme.test');
+ });
+
+ test('falls back to github.com for a known non-GitHub forge', () => {
+ seedRepo(dir, {
+ config: '[remote "origin"]\n\turl = [email protected]:team/notes.git\n',
+ });
+ expect(originGitHubHost(dir)).toBe('github.com');
+ });
+
+ test('falls back to github.com when there is no .git at all', () => {
+ expect(originGitHubHost(dir)).toBe('github.com');
+ });
+});
+
describe('branchExistsOnOrigin', () => {
let dir: string;
@@ -304,12 +418,22 @@ describe('readSyncRemoteInfo', () => {
});
});
- test('non-github origin yields a readable label and a null webUrl (no link)', () => {
+ test('GHES origin yields a host-qualified label and a browsable webUrl', () => {
+ seedRepo(dir, {
+ config: '[remote "origin"]\n\turl = https://ghes.acme.test/team/notes.git\n',
+ });
+ expect(readSyncRemoteInfo(dir)).toEqual({
+ label: 'ghes.acme.test/team/notes',
+ webUrl: 'https://ghes.acme.test/team/notes',
+ });
+ });
+
+ test('known non-github forge yields a readable label and a null webUrl (no link)', () => {
seedRepo(dir, {
- config: '[remote "origin"]\n\turl = https://gitlab.example.com/team/notes.git\n',
+ config: '[remote "origin"]\n\turl = https://gitlab.com/team/notes.git\n',
});
expect(readSyncRemoteInfo(dir)).toEqual({
- label: 'gitlab.example.com/team/notes',
+ label: 'gitlab.com/team/notes',
webUrl: null,
});
});
@@ -374,6 +498,7 @@ describe('linked-worktree common-dir resolution', () => {
test('reads origin config via commondir (regression: worktree reported no-remote)', () => {
expect(readOriginGitHubRepo(project)).toEqual({
kind: 'ok',
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
});
diff --git a/packages/server/src/share/git-context.ts b/packages/server/src/share/git-context.ts
index d65127cf1..dc07eb86f 100644
--- a/packages/server/src/share/git-context.ts
+++ b/packages/server/src/share/git-context.ts
@@ -10,20 +10,30 @@
* packed-refs fallback; no `git ls-remote`.
*
* The github-origin parser here is intentionally narrower than
- * `parseGitUrl` in `packages/cli/src/github/url.ts` — share is GitHub-only;
- * non-github remotes return `non-github` so the caller can surface the
- * matching toast. Widening the cli's regex is a STOP rule
- * ; keeping a narrow server-local parser avoids the temptation
- * and stays decoupled from the cli (which depends on `@inkeep/open-knowledge-server`
- * — adding the reverse dependency would create a cycle).
+ * `parseGitUrl` in `packages/cli/src/github/url.ts` — it covers only the four
+ * URL forms produced by real GitHub/GHES clones (https, ssh://, scp-style,
+ * git://), not the cli grammar's shorthand forms. It stays a server-local
+ * parser because the cli depends on `@inkeep/open-knowledge-server` — importing
+ * the cli's parser here would create a cycle.
+ *
+ * Host classification follows the cli's `validateGitHubHost` philosophy:
+ * GHES hostnames are arbitrary, so any parseable origin whose host is not a
+ * known non-GitHub forge (`KNOWN_NON_GITHUB_GIT_HOSTS`) is treated as a
+ * GitHub host and carries its `host` in the result. Known forges (gitlab,
+ * bitbucket, …) classify as `non-github` so callers surface the matching
+ * toast.
*/
import { existsSync, readFileSync, statSync } from 'node:fs';
import { isAbsolute, join, resolve } from 'node:path';
+import { KNOWN_NON_GITHUB_GIT_HOSTS } from '@inkeep/open-knowledge-core';
+import { getLogger } from '../logger.ts';
+
+const log = getLogger('git-context');
/** Outcome of `readOriginGitHubRepo`. */
export type OriginResult =
- | { kind: 'ok'; owner: string; repo: string }
+ | { kind: 'ok'; host: string; owner: string; repo: string }
| { kind: 'no-remote' }
| { kind: 'non-github' };
@@ -156,36 +166,59 @@ export function extractOriginUrl(configContents: string): string | null {
return null;
}
+/** Parsed origin repo: normalized host + owner/repo path segments. */
+interface ParsedOriginRepo {
+ host: string;
+ owner: string;
+ repo: string;
+}
+
/**
- * Match a github.com origin URL and return `{owner, repo}`. Returns null for
- * non-github hosts (gitlab, internal forges) and unparseable strings.
- *
- * Scope is intentionally narrow: only the forms used in production GitHub
- * clones. The full URL grammar lives in `parseGitUrl` in `packages/cli/`;
- * widening this regex to cover GHES wildcard forms would re-create that
- * surface and risk drifting from the cli's source of truth.
+ * Lowercase, strip a trailing `:port`, and fold `www.github.com` →
+ * `github.com`. Ports are dropped because every downstream consumer (token
+ * relay via `gh auth token --hostname`, the `/api/v3` probe base, browse
+ * URLs) addresses the host by name.
+ */
+function normalizeGitHost(rawHost: string): string {
+ const host = rawHost.toLowerCase().replace(/:\d+$/, '');
+ return host === 'www.github.com' ? 'github.com' : host;
+}
+
+/**
+ * Match a GitHub-host origin URL (github.com or GHES) and return
+ * `{host, owner, repo}`. Returns null for known non-GitHub forges
+ * (`KNOWN_NON_GITHUB_GIT_HOSTS`) and unparseable strings. Unknown hosts are
+ * presumed GitHub; the downstream probe/token paths degrade gracefully when
+ * one turns out not to be.
*/
-function parseGitHubOriginUrl(originUrl: string): { owner: string; repo: string } | null {
+function parseGitHubOriginUrl(originUrl: string): ParsedOriginRepo | null {
const raw = originUrl.trim();
if (!raw) return null;
- // https://github.com/<owner>/<repo>(.git)?
- let m = /^https?:\/\/(?:www\.)?github\.com\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(raw);
- if (m) return { owner: m[1], repo: m[2] };
+ const classify = (host: string, owner: string, repo: string): ParsedOriginRepo | null => {
+ const normalized = normalizeGitHost(host);
+ if (KNOWN_NON_GITHUB_GIT_HOSTS.has(normalized)) return null;
+ return { host: normalized, owner, repo };
+ };
- // ssh://[user@]github.com[:port]/<owner>/<repo>(.git)?
- m = /^ssh:\/\/(?:[\w.-]+@)?github\.com(?::\d+)?\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(
+ // https://<host>[:port]/<owner>/<repo>(.git)?
+ let m = /^https?:\/\/([\w.-]+(?::\d+)?)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(raw);
+ if (m) return classify(m[1], m[2], m[3]);
+
+ // ssh://[user@]<host>[:port]/<owner>/<repo>(.git)?
+ m = /^ssh:\/\/(?:[\w.-]+@)?([\w.-]+)(?::\d+)?\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(
raw,
);
- if (m) return { owner: m[1], repo: m[2] };
+ if (m) return classify(m[1], m[2], m[3]);
- // [email protected]:<owner>/<repo>(.git)?
- m = /^[\w.-]+@github\.com:([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(raw);
- if (m) return { owner: m[1], repo: m[2] };
+ // <user>@<host>:<owner>/<repo>(.git)? (scp-style; `@` is required, so
+ // Windows drive paths like `C:\x` can never match)
+ m = /^[\w.-]+@([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(raw);
+ if (m) return classify(m[1], m[2], m[3]);
- // git://github.com/<owner>/<repo>(.git)?
- m = /^git:\/\/github\.com\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(raw);
- if (m) return { owner: m[1], repo: m[2] };
+ // git://<host>[:port]/<owner>/<repo>(.git)?
+ m = /^git:\/\/([\w.-]+(?::\d+)?)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(raw);
+ if (m) return classify(m[1], m[2], m[3]);
return null;
}
@@ -200,7 +233,7 @@ function parseGitHubOriginUrl(originUrl: string): { owner: string; repo: string
*/
function readParsedOrigin(
projectDir: string,
-): { originUrl: string; github: { owner: string; repo: string } | null } | null {
+): { originUrl: string; github: ParsedOriginRepo | null } | null {
const gitDir = resolveGitDir(projectDir);
if (!gitDir) return null;
// Origin config lives in the common dir, which differs from `gitDir` for a
@@ -220,23 +253,46 @@ function readParsedOrigin(
/**
* Read `.git/config`, locate `[remote "origin"]`, and classify the URL.
- * Returns `ok` for github.com origins, `non-github` for parseable origins
- * pointing elsewhere (gitlab, bitbucket, ...), `no-remote` when no origin
- * URL is configured.
+ * Returns `ok` (with the origin `host` — `github.com` or a GHES hostname)
+ * for GitHub-host origins, `non-github` for known non-GitHub forges (gitlab,
+ * bitbucket, ...) and unparseable URLs, `no-remote` when no origin URL is
+ * configured.
*/
export function readOriginGitHubRepo(projectDir: string): OriginResult {
const parsed = readParsedOrigin(projectDir);
if (!parsed) return { kind: 'no-remote' };
- if (parsed.github) return { kind: 'ok', owner: parsed.github.owner, repo: parsed.github.repo };
- // Origin URL present but not parseable as github.com — surface as
- // `non-github` so the caller renders the matching toast.
+ if (parsed.github) {
+ const { host, owner, repo } = parsed.github;
+ return { kind: 'ok', host, owner, repo };
+ }
+ // Origin URL present but a known non-GitHub forge or unparseable — surface
+ // as `non-github` so the caller renders the matching toast.
return { kind: 'non-github' };
}
+/**
+ * The workspace origin's GitHub host (github.com or GHES), falling back to
+ * github.com when there is no parseable GitHub origin. Single source of the
+ * "which host do auth surfaces target by default" rule — the local-op auth
+ * relay and the CLI `--host` defaults both call this. Never throws (all
+ * `.git` reads underneath are individually guarded): the CLI evaluates it
+ * at command registration, where a throw would break every invocation.
+ */
+export function originGitHubHost(projectDir: string): string {
+ const origin = readOriginGitHubRepo(projectDir);
+ if (origin.kind === 'ok') return origin.host;
+ log.debug(
+ { kind: origin.kind },
+ '[git-context] origin is not a GitHub host — falling back to github.com',
+ );
+ return 'github.com';
+}
+
/**
* UI-facing summary of the origin remote for the sync-status payload.
- * `webUrl` is non-null only for github.com origins (the Sync UI renders it as
- * a link); other forges yield a readable `label` with no link.
+ * `webUrl` is non-null for GitHub-host origins — github.com AND GHES (the
+ * Sync UI renders it as a link); known non-GitHub forges yield a readable
+ * `label` with no link.
*/
export interface SyncRemoteInfo {
label: string;
@@ -252,9 +308,11 @@ export function readSyncRemoteInfo(projectDir: string): SyncRemoteInfo | null {
const parsed = readParsedOrigin(projectDir);
if (!parsed) return null;
if (parsed.github) {
+ const { host, owner, repo } = parsed.github;
return {
- label: `${parsed.github.owner}/${parsed.github.repo}`,
- webUrl: `https://github.com/${parsed.github.owner}/${parsed.github.repo}`,
+ // Enterprise hosts keep the host in the label; github.com stays terse.
+ label: host === 'github.com' ? `${owner}/${repo}` : `${host}/${owner}/${repo}`,
+ webUrl: `https://${host}/${owner}/${repo}`,
};
}
// Non-github origin: show a readable host/path label, never linkified.
diff --git a/packages/server/src/sync-engine.test.ts b/packages/server/src/sync-engine.test.ts
index 24e562853..f4ad0d3b8 100644
--- a/packages/server/src/sync-engine.test.ts
+++ b/packages/server/src/sync-engine.test.ts
@@ -92,6 +92,7 @@ async function initGitWithOrigin(originUrl = 'https://github.com/inkeep/open-kno
interface FakeProbeRecorder {
calls: number;
next: import('./github-permissions.ts').PushPermission[];
+ opts: import('./github-permissions.ts').CheckPushPermissionOptions[];
fn: (
opts: import('./github-permissions.ts').CheckPushPermissionOptions,
) => Promise<import('./github-permissions.ts').PushPermission>;
@@ -101,8 +102,10 @@ function fakeProbe(...sequence: Array<import('./github-permissions.ts').PushPerm
const rec: FakeProbeRecorder = {
calls: 0,
next: [...sequence],
- fn: async () => {
+ opts: [],
+ fn: async (opts) => {
rec.calls++;
+ rec.opts.push(opts);
return rec.next.shift() ?? { kind: 'unknown', error: 'network' };
},
};
@@ -1508,6 +1511,23 @@ describe('SyncEngine push-permission probe', () => {
});
});
+ test('probes a GitHub Enterprise origin against the enterprise host', async () => {
+ await initGitWithOrigin('https://ghes.acme.test/inkeep/open-knowledge.git');
+ const probe = fakeProbe({ kind: 'allowed' });
+ const engine = makeProbeEngine({ syncEnabled: false, fakeProbe: probe.fn });
+ await engine.start();
+ await waitForPushPermissionResolved(engine);
+ expect(probe.calls).toBe(1);
+ expect(probe.opts[0]).toMatchObject({
+ owner: 'inkeep',
+ repo: 'open-knowledge',
+ host: 'ghes.acme.test',
+ });
+ expect(engine.getStatus().pushPermission).toEqual({
+ checkStatus: 'allowed',
+ });
+ });
+
test('records `denied` and pauses in-memory when syncEnabled is true', async () => {
await initGitWithOrigin();
const probe = fakeProbe({ kind: 'denied', reason: 'no-collaborator' });
@@ -1920,6 +1940,25 @@ describe('SyncEngine gh-token credential relay', () => {
}
});
+ test('resolves the gh token against a GitHub Enterprise origin host', async () => {
+ await initGitWithOrigin('https://ghes.acme.test/inkeep/open-knowledge.git');
+ const detect = recordDetectGh({ available: true, token: 'gho_relayed' });
+ const engine = new SyncEngine({
+ projectDir,
+ contentDir,
+ contentFilter: stubContentFilter,
+ syncEnabled: true,
+ detectGh: detect.fn,
+ });
+ try {
+ (engine as unknown as { gitHandle: () => unknown }).gitHandle();
+ expect(detect.calls()).toBe(1);
+ expect(detect.lastHost()).toBe('ghes.acme.test');
+ } finally {
+ await engine.destroy();
+ }
+ });
+
test('caches the gh token across handles, then re-resolves after an auth error', () => {
const detect = recordDetectGh({ available: true, token: 'gho_relayed' });
const engine = new SyncEngine({
diff --git a/packages/server/src/sync-engine.ts b/packages/server/src/sync-engine.ts
index 4fc85ebdb..0311542df 100644
--- a/packages/server/src/sync-engine.ts
+++ b/packages/server/src/sync-engine.ts
@@ -43,6 +43,7 @@ import {
import { getLogger } from './logger.ts';
import { toPosix } from './path-utils.ts';
import {
+ originGitHubHost,
readOriginGitHubRepo,
readSyncRemoteInfo,
type SyncRemoteInfo,
@@ -59,14 +60,6 @@ const log = getLogger('sync-engine');
*/
const SHA_HEX_40 = /^[0-9a-f]{40}$/i;
-/**
- * Host the relayed gh token authenticates. The origin parser (`git-context.ts`)
- * is GitHub-only — a GHES or non-github remote classifies as `non-github` and
- * never reaches the credential paths — so the sync engine only ever
- * authenticates against github.com.
- */
-const SYNC_GH_TOKEN_HOST = 'github.com';
-
// ─── Types ───────────────────────────────────────────────────────────────────
export type SyncState =
@@ -391,18 +384,32 @@ export class SyncEngine {
this.conflictStore = new ConflictStore(this.projectDir, this.currentBranch);
}
+ /**
+ * Host the relayed gh token authenticates: the origin remote's GitHub host
+ * (github.com or GHES), falling back to github.com when the origin is
+ * missing or a non-GitHub forge (the relay is then harmless surplus).
+ * Resolved per handle from `.git/config` — a few small file reads, noise
+ * next to the subprocess each handle spawns — so a remote swap mid-session
+ * is picked up without a restart. The token stays cached per host in
+ * `ghTokenSource`.
+ */
+ private syncGhTokenHost(): string {
+ return originGitHubHost(this.projectDir);
+ }
+
/**
* Single construction point for every git handle the engine spawns. Threads
- * the credential args plus the cached gh token (host-scoped to github.com) so
- * fetch/push authenticate via gh when available. Local-only handles (e.g.
- * `remote -v`, `merge --abort`) carry the token harmlessly — the cache keeps
- * resolution to at most one `gh` spawn per minute regardless of handle count.
+ * the credential args plus the cached gh token (scoped to the origin's
+ * GitHub host) so fetch/push authenticate via gh when available. Local-only
+ * handles (e.g. `remote -v`, `merge --abort`) carry the token harmlessly —
+ * the cache keeps resolution to at most one `gh` spawn per minute
+ * regardless of handle count.
*/
private gitHandle(gitIndexFile?: string): GitHandle {
return createGitInstance(this.projectDir, {
credentialArgs: this.credentialArgs,
gitIndexFile,
- ghToken: this.ghTokenSource.get(SYNC_GH_TOKEN_HOST) ?? undefined,
+ ghToken: this.ghTokenSource.get(this.syncGhTokenHost()) ?? undefined,
});
}
@@ -859,10 +866,11 @@ export class SyncEngine {
// attributes that would inflate downstream log indices if pino is ever
// bridged into the OTLP pipeline (pino-opentelemetry-transport).
// Matches the sibling cardinality discipline in github-permissions.ts.
+ // `host` is bounded (one value per project) and safe to log.
log.info(
{
caller,
- host: 'github.com',
+ host: origin.host,
hasDetectGh: this.detectGh !== undefined,
hasTokenStore: this.tokenStore !== undefined && this.tokenStore !== null,
},
@@ -873,7 +881,7 @@ export class SyncEngine {
outcome = await this.checkPushPermissionFn({
owner: origin.owner,
repo: origin.repo,
- host: 'github.com',
+ host: origin.host,
detectGh: this.detectGh,
tokenStore: this.tokenStore,
});