Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(open-knowledge): GitHub Enterprise Server support for share links (PRD-7351) (#2687)

omar-inkeep092653c8c2ae
diff --git a/.changeset/ghes-share-links.md b/.changeset/ghes-share-links.md
new file mode 100644
index 000000000..1b73ef143
--- /dev/null
+++ b/.changeset/ghes-share-links.md
@@ -0,0 +1,18 @@
+---
+'@inkeep/open-knowledge': patch
+'@inkeep/open-knowledge-server': patch
+'@inkeep/open-knowledge-core': patch
+'@inkeep/open-knowledge-desktop': patch
+'@inkeep/open-knowledge-app': patch
+'@inkeep/open-knowledge-docs': patch
+---
+
+**Feat:** share links now work with GitHub Enterprise Server remotes
+(PRD-7351). The construct side threads the origin host into the share URL,
+and the receive pipeline carries the host as part of the repo identity end
+to end — so a GHES `owner/repo` share never resolves to a same-named
+github.com clone. Because a decoded deep link is untrusted input, a share
+pointing at a non-github.com host is gated: it proceeds silently only for a
+host the recipient is already authenticated to, otherwise the app prompts to
+open the link in a browser instead. The web splash renders enterprise shares
+with the host shown prominently.
diff --git a/docs/content/features/github-sync.mdx b/docs/content/features/github-sync.mdx
index 4da62326e..254ba3c1f 100644
--- a/docs/content/features/github-sync.mdx
+++ b/docs/content/features/github-sync.mdx
@@ -77,7 +77,7 @@ 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.
+When a project's `origin` remote points at a GitHub Enterprise Server host, OpenKnowledge resolves credentials and identity for that host automatically: the account shown in settings, the sync token, the push-permission check, and the `ok auth` default `--host` all follow the workspace's remote instead of assuming github.com. Share links work with enterprise remotes too — a recipient opening a GHES share is asked to confirm the server unless they are already signed in to it.
The sync status indicator surfaces an auth-error state when stored credentials stop working, and sync pauses until you reconnect.
diff --git a/docs/src/app/d/[encoded]/splash-share-view.tsx b/docs/src/app/d/[encoded]/splash-share-view.tsx
index 8cf953b58..63d51d61d 100644
--- a/docs/src/app/d/[encoded]/splash-share-view.tsx
+++ b/docs/src/app/d/[encoded]/splash-share-view.tsx
@@ -55,7 +55,7 @@ export function SplashShareView({ encoded, view }: { encoded: string; view: OkSp
</svg>
</a>
</h1>
- <div className="flex flex-col sm:flex-row items-start sm:items-center gap-2 mt-8">
+ <div className="flex flex-col sm:flex-row items-start sm:items-center gap-3 mt-8">
<a
href={view.githubUrl}
target="_blank"
@@ -77,6 +77,15 @@ export function SplashShareView({ encoded, view }: { encoded: string; view: OkSp
<span className="font-medium">{view.branch}</span>
</p>
)}
+
+ {view.isEnterpriseHost ? (
+ <p
+ className="inline-flex w-fit items-center gap-1.5 rounded bg-slide-muted/10 px-2 py-0.5 text-sm text-slide-muted"
+ data-testid="splash-enterprise-host"
+ >
+ GitHub Enterprise Server · <span className="font-medium">{view.host}</span>
+ </p>
+ ) : null}
</div>
<SplashCtaPanel
downloadUrl={`/d/${encoded}/download`}
diff --git a/docs/src/lib/share-splash.test.ts b/docs/src/lib/share-splash.test.ts
index 73ceb311a..7b53875d5 100644
--- a/docs/src/lib/share-splash.test.ts
+++ b/docs/src/lib/share-splash.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
-import { encodeShareUrl } from '@inkeep/open-knowledge-core';
+import { encodeShareUrl, KNOWN_NON_GITHUB_GIT_HOSTS } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { STABLE_DMG_URL } from './download-links.ts';
import {
buildCloneCommand,
@@ -56,6 +56,8 @@ describe('buildSplashViewModel', () => {
kind: 'ok',
target: 'doc',
filename: 'marketing-playbook.md',
+ host: 'github.com',
+ isEnterpriseHost: false,
owner: 'inkeep',
repo: 'playbooks',
repoPath: 'inkeep/playbooks',
@@ -77,6 +79,8 @@ describe('buildSplashViewModel', () => {
kind: 'ok',
target: 'folder',
filename: 'campaigns',
+ host: 'github.com',
+ isEnterpriseHost: false,
owner: 'inkeep',
repo: 'playbooks',
repoPath: 'inkeep/playbooks',
@@ -248,10 +252,49 @@ describe('buildSplashViewModel', () => {
expect(view).toEqual({ kind: 'invalid' });
});
- test('returns `invalid` for a github-spoofed hostname', () => {
+ test('renders an unknown host (incl. a github.com lookalike) as an enterprise share', () => {
+ // GHES hostnames are arbitrary — the splash cannot tell a lookalike from a
+ // real enterprise host by structure. It renders it as an enterprise share
+ // with `isEnterpriseHost: true` so the page shows the host prominently
+ // (the recipient sees which server before acting); the receive-side trust
+ // gate is what actually prevents an untrusted host from being cloned.
const view = buildSplashViewModel(
encodeV1('https://github.com.evil.example/owner/repo/blob/main/README.md'),
);
+ expect(view).toMatchObject({
+ kind: 'ok',
+ host: 'github.com.evil.example',
+ isEnterpriseHost: true,
+ repoPath: 'owner/repo',
+ });
+ });
+
+ test('returns `invalid` for a known non-GitHub forge host', () => {
+ const view = buildSplashViewModel(
+ encodeV1('https://gitlab.com/owner/repo/blob/main/README.md'),
+ );
+ expect(view).toEqual({ kind: 'invalid' });
+ });
+
+ // Drift guard: the splash keeps a copy-local `KNOWN_NON_GITHUB_GIT_HOSTS`
+ // (the docs build can't import the package graph). Iterate the CANONICAL set
+ // so a forge added to core but not the splash copy fails here rather than
+ // silently rendering as an enterprise share.
+ for (const forge of KNOWN_NON_GITHUB_GIT_HOSTS) {
+ test(`returns \`invalid\` for canonical forge host ${forge}`, () => {
+ const view = buildSplashViewModel(
+ encodeV1(`https://${forge}/owner/repo/blob/main/README.md`),
+ );
+ expect(view).toEqual({ kind: 'invalid' });
+ });
+ }
+
+ test('returns `invalid` for a non-https scheme with an otherwise-valid shape', () => {
+ // A crafted deep link can carry any scheme with a valid host + path. The
+ // parser must reject non-https so the URL never reaches an <a href>.
+ const view = buildSplashViewModel(
+ encodeV1('vscode://ghes.internal.example/owner/repo/blob/main/README.md'),
+ );
expect(view).toEqual({ kind: 'invalid' });
});
diff --git a/docs/src/lib/share-splash.ts b/docs/src/lib/share-splash.ts
index 35c109d75..4fe86798d 100644
--- a/docs/src/lib/share-splash.ts
+++ b/docs/src/lib/share-splash.ts
@@ -98,7 +98,29 @@ function base64UrlToUint8Array(input: string): Uint8Array {
return bytes;
}
+/**
+ * Known non-GitHub forges — copy-local mirror of `KNOWN_NON_GITHUB_GIT_HOSTS`
+ * in `@inkeep/open-knowledge-core` (kept inline so the static docs build has
+ * no runtime dep on the package graph, per the file-header note). Any host not
+ * listed is presumed github.com or a GitHub Enterprise Server instance.
+ */
+const KNOWN_NON_GITHUB_GIT_HOSTS = new Set([
+ 'gitlab.com',
+ 'bitbucket.org',
+ 'codeberg.org',
+ 'gitea.com',
+ 'sr.ht',
+ 'sourcehut.org',
+]);
+
+function classifyGitHubShareHost(hostname: string): string | null {
+ const host = hostname.toLowerCase();
+ const folded = host === 'www.github.com' ? 'github.com' : host;
+ return KNOWN_NON_GITHUB_GIT_HOSTS.has(folded) ? null : folded;
+}
+
export interface ParsedGitHubBlobUrl {
+ host: string;
owner: string;
repo: string;
branch: string;
@@ -106,6 +128,7 @@ export interface ParsedGitHubBlobUrl {
}
export interface ParsedGitHubTreeUrl {
+ host: string;
owner: string;
repo: string;
branch: string;
@@ -117,8 +140,8 @@ export interface ParsedGitHubTreeUrl {
* URL is a `folder` (whose `path` MAY be empty for the repo/branch root).
*/
export type ParsedGitHubShareTarget =
- | { kind: 'doc'; owner: string; repo: string; branch: string; path: string }
- | { kind: 'folder'; owner: string; repo: string; branch: string; path: string };
+ | { kind: 'doc'; host: string; owner: string; repo: string; branch: string; path: string }
+ | { kind: 'folder'; host: string; owner: string; repo: string; branch: string; path: string };
/**
* Decode-boundary validation for the owner/repo/branch pulled out of a
@@ -169,9 +192,14 @@ function parseGitHubBlobUrl(input: string): ParsedGitHubBlobUrl | null {
return null;
}
- if (url.hostname !== 'github.com' && url.hostname !== 'www.github.com') {
- return null;
- }
+ // Share links are always https. Reject any other scheme: a crafted deep
+ // link could carry a non-https scheme (vscode:, ms-msdt:, …) with a valid
+ // host and otherwise parse — that URL renders into an <a href> on this
+ // public splash page.
+ if (url.protocol !== 'https:') return null;
+
+ const host = classifyGitHubShareHost(url.hostname);
+ if (host === null) return null;
const rawSegments = url.pathname.split('/').filter((s) => s.length > 0);
@@ -195,7 +223,7 @@ function parseGitHubBlobUrl(input: string): ParsedGitHubBlobUrl | null {
if (pathParts.some((p) => p.length === 0)) return null;
if (!isShareSegmentSafe(owner, repo, branch)) return null;
- return { owner, repo, branch, path: pathParts.join('/') };
+ return { host, owner, repo, branch, path: pathParts.join('/') };
}
/**
@@ -212,9 +240,14 @@ function parseGitHubTreeUrl(input: string): ParsedGitHubTreeUrl | null {
return null;
}
- if (url.hostname !== 'github.com' && url.hostname !== 'www.github.com') {
- return null;
- }
+ // Share links are always https. Reject any other scheme: a crafted deep
+ // link could carry a non-https scheme (vscode:, ms-msdt:, …) with a valid
+ // host and otherwise parse — that URL renders into an <a href> on this
+ // public splash page.
+ if (url.protocol !== 'https:') return null;
+
+ const host = classifyGitHubShareHost(url.hostname);
+ if (host === null) return null;
// Split WITHOUT filtering empties so empty intermediate path segments
// (`a//b`) remain detectable. The pathname always starts with `/`, so
@@ -249,7 +282,7 @@ function parseGitHubTreeUrl(input: string): ParsedGitHubTreeUrl | null {
if (pathParts.some((p) => p.length === 0)) return null;
if (!isShareSegmentSafe(owner, repo, branch)) return null;
- return { owner, repo, branch, path: pathParts.join('/') };
+ return { host, owner, repo, branch, path: pathParts.join('/') };
}
/**
@@ -449,6 +482,12 @@ export type SplashView =
* or the repo name when the folder is the repo/branch root (empty path).
*/
filename: string;
+ /** GitHub host: `github.com` or a GHES hostname. */
+ host: string;
+ /** True when the share targets a GitHub Enterprise host (not github.com).
+ * The splash renders the host prominently in this case so a share can
+ * never borrow openknowledge.ai's credibility for an unfamiliar server. */
+ isEnterpriseHost: boolean;
owner: string;
repo: string;
repoPath: string;
@@ -493,7 +532,7 @@ export function buildSplashViewModel(encoded: string): SplashView {
return { kind: 'invalid' };
}
- const { kind, owner, repo, branch, path } = parsed;
+ const { kind, host, owner, repo, branch, path } = parsed;
const segments = path.split('/').filter((s) => s.length > 0);
const basename = segments[segments.length - 1];
// Doc shares always have a path basename. Folder shares fall back to the
@@ -504,6 +543,8 @@ export function buildSplashViewModel(encoded: string): SplashView {
kind: 'ok',
target: kind,
filename,
+ host,
+ isEnterpriseHost: host !== 'github.com',
owner,
repo,
repoPath: `${owner}/${repo}`,
diff --git a/packages/app/src/App.tsx b/packages/app/src/App.tsx
index 20ce28ddb..2ecd3fa2c 100644
--- a/packages/app/src/App.tsx
+++ b/packages/app/src/App.tsx
@@ -44,7 +44,11 @@ import {
import { mark, ProfilerBoundary } from '@/lib/perf';
import { SingleFileModeProvider, useSingleFileMode } from '@/lib/single-file-mode';
import { useServerKeepalive } from '@/lib/use-server-keepalive';
-import { isSettingsShortcut, SETTINGS_OPEN_HASH } from '@/lib/use-settings-route';
+import {
+ isSettingsHashOpen,
+ isSettingsShortcut,
+ SETTINGS_OPEN_HASH,
+} from '@/lib/use-settings-route';
// Cold-path receive surface: only mounts when main routes a
// 'project-branch-switch' payload. Lazy so its branch-info / checkout / variant
@@ -78,7 +82,7 @@ const ShareReceiveMissDialog = lazy(() =>
const INSTALL_DIALOG_HASH = '#install-claude-desktop';
const MARKDOWN_EXTENSION_QUALIFIED_DOC_PATTERN = /\.(md|mdx)$/i;
function isAuxiliaryDialogHash(hash: string): boolean {
- return hash === SETTINGS_OPEN_HASH || hash === INSTALL_DIALOG_HASH;
+ return isSettingsHashOpen(hash) || hash === INSTALL_DIALOG_HASH;
}
function exactOpenMarkdownTabTarget(
diff --git a/packages/app/src/components/AuthModal.tsx b/packages/app/src/components/AuthModal.tsx
index 558897591..24e27f850 100644
--- a/packages/app/src/components/AuthModal.tsx
+++ b/packages/app/src/components/AuthModal.tsx
@@ -4,6 +4,16 @@
* Device Flow: shows user_code, polls for completion, 2-minute timeout.
* Calls POST /api/local-op/auth/login (streaming JSONL).
*
+ * Entry patterns (what happens on open):
+ * 1. Caller-supplied `host` — no probe; the step resolves directly from the
+ * host (enterprise → PAT / gh-device, github.com → device flow). Used by
+ * known-host contexts, e.g. the share-receive trust gate.
+ * 2. `identityPrompt` — probes to decide whether sign-in can be skipped (see
+ * below).
+ * 3. Neither — probes `/auth/status` for host discovery: a non-github.com
+ * sync host resolves the step to 'pat' (GHES), github.com to the device
+ * flow. The "Checking sign-in status" spinner is this probe.
+ *
* Variant props:
* identityPrompt — when true, this is the "set git identity" entry point (the
* sync popover's "Set identity" nudge). An already-signed-in
@@ -12,7 +22,8 @@
* user is NOT authenticated (then it falls back to sign-in,
* showing the identity fields after success). Setting git
* identity does not require re-authenticating.
- * reauth — when true, shows "Re-authenticate" heading instead of "Connect".
+ * reauth — when true, shows "Re-authenticate" heading instead of "Connect"
+ * (host-accurate: the GHES steps get the Enterprise variant).
*
* On success: calls onSuccess({ login, name, avatarUrl }) and closes.
*
@@ -32,7 +43,11 @@ import {
type AuthQueryTransport,
httpAuthQueryTransport,
} from '@/lib/transports/auth-query-transport';
-import { type AuthTransport, httpAuthTransport } from '@/lib/transports/auth-transport';
+import {
+ type AuthTransport,
+ type AuthTransportHandle,
+ httpAuthTransport,
+} from '@/lib/transports/auth-transport';
import { Button } from './ui/button';
import {
Dialog,
@@ -82,18 +97,37 @@ interface AuthModalProps {
* path (POST /api/local-op/auth/status). Injectable for tests.
*/
queryTransport?: AuthQueryTransport;
+ /**
+ * The GitHub host to connect. When it's a non-github.com host (a GitHub
+ * Enterprise Server), the modal shows the Personal Access Token panel instead
+ * of the OAuth device flow (which only works on github.com). Absent/github.com
+ * keeps the device flow.
+ */
+ host?: string;
+ /**
+ * Whether the gh CLI is installed (from the auth-status probe). When true and
+ * `host` is enterprise, the connect panel offers "Continue in browser" (gh
+ * flow) as the primary path, with the PAT field as the fallback.
+ */
+ ghAvailable?: boolean;
}
// ── Device Flow panel ─────────────────────────────────────────────────────────
interface DeviceFlowPanelProps {
onSuccess: (result: AuthSuccessResult) => void;
- transport: AuthTransport;
+ /**
+ * Opens the streaming flow (verification → complete/error). Injected so the
+ * same panel drives both OK's own device flow (`transport.start`) and the
+ * gh-CLI browser flow (`transport.ghLogin`) — identical event shape, different
+ * endpoint.
+ */
+ startFlow: () => AuthTransportHandle;
}
const DEVICE_TIMEOUT_MS = 2 * 60 * 1000; // 2 minutes
-function DeviceFlowPanel({ onSuccess, transport }: DeviceFlowPanelProps) {
+function DeviceFlowPanel({ onSuccess, startFlow }: DeviceFlowPanelProps) {
const { t } = useLingui();
const [userCode, setUserCode] = useState<string | null>(null);
const [verificationUri, setVerificationUri] = useState('https://github.com/login/device');
@@ -106,7 +140,7 @@ function DeviceFlowPanel({ onSuccess, transport }: DeviceFlowPanelProps) {
async function startDeviceFlow() {
setError(null);
try {
- const handle = transport.start();
+ const handle = startFlow();
cancelRef.current = handle.cancel;
// Manual iterator drive — React Compiler (BuildHIR) does not yet
// support `for await ... of` lowering, so we walk the iterator with
@@ -302,11 +336,115 @@ function IdentityBody({ login, name, onNameChange, email, onEmailChange }: Ident
);
}
+// ── PAT (enterprise) panel ────────────────────────────────────────────────────
+// Presentational token field for the GHES sign-in path. Token + submit state
+// live in the main modal so the footer "Connect" button can drive them.
+
+interface PatBodyProps {
+ host: string;
+ token: string;
+ onTokenChange: (value: string) => void;
+ error: string | null;
+ onSubmit: () => void;
+ /** Show "Continue in browser" as the primary path (gh is installed). */
+ showGhOption: boolean;
+ /** Start the gh browser sign-in (transition to the gh device step). */
+ onGhSignIn: () => void;
+}
+
+function PatBody({
+ host,
+ token,
+ onTokenChange,
+ error,
+ onSubmit,
+ showGhOption,
+ onGhSignIn,
+}: PatBodyProps) {
+ const { t } = useLingui();
+ const createUrl = `https://${host}/settings/tokens/new?scopes=repo,read:user&description=OpenKnowledge`;
+ return (
+ <div className="flex flex-col gap-3">
+ {showGhOption ? (
+ <>
+ {/* Primary path when gh is installed: browser sign-in, no token.
+ Labeled by outcome ("browser"), not the gh implementation detail. */}
+ <Button type="button" onClick={onGhSignIn}>
+ <Trans>Continue in browser</Trans>
+ </Button>
+ <div className="flex items-center gap-3 text-xs text-muted-foreground">
+ <span className="h-px flex-1 bg-border" />
+ <Trans>or paste a token</Trans>
+ <span className="h-px flex-1 bg-border" />
+ </div>
+ </>
+ ) : (
+ <p className="text-sm text-muted-foreground">
+ <Trans>
+ Paste a personal access token for{' '}
+ <span className="font-medium text-foreground">{host}</span>.
+ </Trans>
+ </p>
+ )}
+ <a
+ href={createUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ onClick={(e) => dispatchExternalLinkClick(e, createUrl)}
+ onAuxClick={(e) => dispatchExternalLinkClick(e, createUrl)}
+ className="inline-flex w-fit items-center gap-0.5 text-sm text-foreground hover:text-primary hover:underline"
+ >
+ <Trans>Create a token on {host}</Trans>
+ <ArrowUpRight className="inline size-3.5" aria-hidden />
+ </a>
+ {/* The create-link pre-selects these scopes, but a manually created or
+ pre-existing token won't have gone through it — name them so a
+ wrong-scope 403 isn't the first hint. */}
+ <p className="text-xs text-muted-foreground">
+ <Trans>The token needs the repo and read:user scopes.</Trans>
+ </p>
+ <Input
+ type="password"
+ aria-label={t`Personal access token`}
+ placeholder="ghp_"
+ value={token}
+ onChange={(e) => onTokenChange(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') onSubmit();
+ }}
+ />
+ {error && <p className="text-1sm text-destructive">{error}</p>}
+ {/* gh-absent only: point the user at the browser path without pushing it.
+ The steps are honest because the server re-probes for gh on each
+ status check (see cachedGhBinaryPath) and AccountSection re-probes when
+ this dialog closes — so reopening it after installing gh shows the
+ "Continue in browser" button. */}
+ {!showGhOption && (
+ <div className="mt-1 rounded-md border border-border/60 bg-muted/40 p-3 text-sm text-muted-foreground">
+ <p>
+ <Trans>Or to use browser sign-in instead:</Trans>
+ </p>
+ <ol className="mt-1.5 list-decimal space-y-0.5 pl-5">
+ <li>
+ <Trans>Install the gh CLI</Trans>
+ </li>
+ <li>
+ <Trans>Reopen this window to sign in with your browser</Trans>
+ </li>
+ </ol>
+ </div>
+ )}
+ </div>
+ );
+}
+
// ── Main modal ────────────────────────────────────────────────────────────────
// `checking` is the brief on-open auth-status probe for the identityPrompt
-// path (deciding skip-to-identity vs fall-back-to-device-flow).
-type AuthStep = 'checking' | 'auth' | 'identity' | 'done';
+// path (deciding skip-to-identity vs fall-back-to-device-flow). `pat` is the
+// enterprise (non-github.com) sign-in path — a token field instead of the
+// device flow, which GHES can't use.
+type AuthStep = 'checking' | 'auth' | 'pat' | 'gh-device' | 'identity' | 'done';
// Upper bound on the on-open status probe. The relay is localhost and answers
// near-instantly when healthy, but the HTTP transport's `fetch` has no timeout
@@ -323,6 +461,8 @@ export function AuthModal({
reauth,
transport,
queryTransport,
+ host,
+ ghAvailable,
}: AuthModalProps) {
const { t } = useLingui();
// Default to the HTTP path so existing editor / web callers don't need
@@ -336,6 +476,27 @@ export function AuthModal({
const [idName, setIdName] = useState('');
const [idEmail, setIdEmail] = useState('');
+ // Enterprise (PAT) sign-in state, lifted so the footer "Connect" can read it.
+ const [patToken, setPatToken] = useState('');
+ const [patError, setPatError] = useState<string | null>(null);
+ const [patSubmitting, setPatSubmitting] = useState(false);
+ // When a caller doesn't pass `host` (e.g. the editor's "Reconnect required"
+ // affordance), we probe auth-status on open to discover it — otherwise every
+ // host-less entry point would default to the github.com device flow, which
+ // FAILS on GHES (OK's OAuth app isn't registered there). The probed values
+ // back-fill the props; a passed prop always wins.
+ const [probedHost, setProbedHost] = useState<string | undefined>(undefined);
+ const [probedGhAvailable, setProbedGhAvailable] = useState<boolean | undefined>(undefined);
+ const effectiveHost = host ?? probedHost;
+ const effectiveGhAvailable = ghAvailable ?? probedGhAvailable;
+ const isEnterpriseHost = !!effectiveHost && effectiveHost !== 'github.com';
+ // gh's browser sign-in works on GHES (its OAuth app is preregistered) where
+ // OK's device flow can't. Offer it as the primary path when gh is installed.
+ const canUseGh =
+ isEnterpriseHost && !!effectiveGhAvailable && typeof resolvedTransport.ghLogin === 'function';
+ // Sign-in path with no caller-supplied host → probe first (shows 'checking').
+ const needsHostProbe = !identityPrompt && host === undefined;
+
// Synchronous step decision in a layout effect so it commits BEFORE the
// browser paints. In a passive effect the first painted frame would show the
// stale `step` (often 'auth', since this modal stays mounted and `step`
@@ -346,10 +507,23 @@ export function AuthModal({
setAuthResult(null);
setIdName('');
setIdEmail('');
- // Sign-in path: device flow as before. Set-identity path: show the probe
- // spinner; the async effect below resolves it to 'identity' or 'auth'.
- setStep(identityPrompt ? 'checking' : 'auth');
- }, [open, identityPrompt]);
+ setPatToken('');
+ setPatError(null);
+ setPatSubmitting(false);
+ setProbedHost(undefined);
+ setProbedGhAvailable(undefined);
+ // Set-identity path OR a host-less sign-in: show the probe spinner; the
+ // async effect below resolves it to 'identity' / 'pat' / 'auth'. Host known
+ // and enterprise → straight to the PAT panel (GHES can't use the device
+ // flow). Host known and github.com → the device flow.
+ //
+ // Decide from the PROP host, never `isEnterpriseHost` (which folds in the
+ // *probed* host): depending on the derived value would re-run this effect
+ // when the probe resolves, which resets `probedHost` and bounces the step
+ // back to 'checking' — an infinite "Checking sign-in status" loop.
+ const propEnterpriseHost = !!host && host !== 'github.com';
+ setStep(identityPrompt || needsHostProbe ? 'checking' : propEnterpriseHost ? 'pat' : 'auth');
+ }, [open, identityPrompt, host, needsHostProbe]);
// Set-identity path only: probe auth status to decide skip-to-identity vs
// fall-back-to-device-flow. The user reached this from the "git identity
@@ -399,6 +573,41 @@ export function AuthModal({
};
}, [open, identityPrompt]);
+ // Host-less sign-in path: probe auth-status to discover the origin host (and
+ // whether gh is available) so the modal routes to the enterprise PAT/gh panel
+ // on GHES instead of the github.com device flow. Without this, host-less
+ // entry points (the editor's "Reconnect required", clone/navigator sign-in)
+ // fire the device flow, which errors on a GHES host. Mirrors the identity
+ // probe's settle/timeout race discipline.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: probe runs on open; resolvedQueryTransport is a fresh object each render and excluded intentionally
+ useEffect(() => {
+ if (!open || !needsHostProbe) return;
+ let settled = false;
+ const settle = (next: AuthStep) => {
+ if (settled) return;
+ settled = true;
+ setStep(next);
+ };
+ const timer = setTimeout(() => settle('auth'), IDENTITY_PROBE_TIMEOUT_MS);
+ void resolvedQueryTransport
+ .status()
+ .then((status) => {
+ if (settled) return;
+ const enterprise = !!status.host && status.host !== 'github.com';
+ setProbedHost(status.host);
+ setProbedGhAvailable(status.ghAvailable);
+ settle(enterprise ? 'pat' : 'auth');
+ })
+ .catch(() => {
+ // Probe failed (offline, server hiccup) — fall back to the device flow.
+ settle('auth');
+ });
+ return () => {
+ settled = true;
+ clearTimeout(timer);
+ };
+ }, [open, needsHostProbe]);
+
function handleAuthSuccess(result: AuthSuccessResult) {
setAuthResult(result);
// identityPrompt = the set-identity entry point. Reaching device-flow
@@ -415,7 +624,25 @@ export function AuthModal({
onSuccess?.(result);
onOpenChange(false);
const login = result.login;
- toast.success(t`Connected as @${login}`);
+ toast.success(login ? t`Connected as @${login}` : t`Connected to GitHub`);
+ }
+ }
+
+ async function handlePatConnect() {
+ const token = patToken.trim();
+ if (!token || !effectiveHost || patSubmitting) return;
+ if (!resolvedTransport.pat) {
+ setPatError(t`This window can't store a token — open Settings from the main app window.`);
+ return;
+ }
+ setPatSubmitting(true);
+ setPatError(null);
+ const result = await resolvedTransport.pat(effectiveHost, token);
+ setPatSubmitting(false);
+ if (result.ok) {
+ handleAuthSuccess({ login: result.login ?? '' });
+ } else {
+ setPatError(result.error ?? t`Failed to store the token — try again`);
}
}
@@ -438,7 +665,7 @@ export function AuthModal({
onSuccess?.(result);
onOpenChange(false);
const login = result.login;
- toast.success(t`Connected as @${login}`);
+ toast.success(login ? t`Connected as @${login}` : t`Connected to GitHub`);
}
function handleIdentitySkip() {
@@ -447,7 +674,7 @@ export function AuthModal({
onSuccess?.(authResult);
onOpenChange(false);
const login = authResult.login;
- toast.success(t`Connected as @${login}`);
+ toast.success(login ? t`Connected as @${login}` : t`Connected to GitHub`);
}
function handleCancel() {
@@ -459,8 +686,14 @@ export function AuthModal({
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>
- {reauth ? (
+ {reauth && (step === 'pat' || step === 'gh-device') ? (
+ // Enterprise re-auth: the PAT / gh steps mean the host resolved
+ // to a GHES, so keep the reauth framing host-accurate.
+ <Trans>Re-authenticate with GitHub Enterprise Server</Trans>
+ ) : reauth ? (
<Trans>Re-authenticate with GitHub</Trans>
+ ) : step === 'pat' || step === 'gh-device' ? (
+ <Trans>Connect to GitHub Enterprise Server</Trans>
) : identityPrompt && step !== 'auth' ? (
// identityPrompt + non-`auth` step = the set-identity path with a
// signed-in user; `auth` means the probe fell back to sign-in.
@@ -482,7 +715,10 @@ export function AuthModal({
{step === 'auth' && (
<>
<DialogBody>
- <DeviceFlowPanel onSuccess={handleAuthSuccess} transport={resolvedTransport} />
+ <DeviceFlowPanel
+ onSuccess={handleAuthSuccess}
+ startFlow={() => resolvedTransport.start()}
+ />
</DialogBody>
<DialogFooter>
@@ -493,6 +729,53 @@ export function AuthModal({
</>
)}
+ {step === 'pat' && (
+ <>
+ <DialogBody>
+ <PatBody
+ host={effectiveHost ?? ''}
+ token={patToken}
+ onTokenChange={setPatToken}
+ error={patError}
+ onSubmit={handlePatConnect}
+ showGhOption={canUseGh}
+ onGhSignIn={() => setStep('gh-device')}
+ />
+ </DialogBody>
+
+ <DialogFooter>
+ <Button variant="outline" className="font-mono uppercase" onClick={handleCancel}>
+ <Trans>Cancel</Trans>
+ </Button>
+ <Button onClick={handlePatConnect} disabled={!patToken.trim() || patSubmitting}>
+ {patSubmitting ? <Trans>Connecting</Trans> : <Trans>Connect</Trans>}
+ </Button>
+ </DialogFooter>
+ </>
+ )}
+
+ {step === 'gh-device' && (
+ <>
+ <DialogBody>
+ <DeviceFlowPanel
+ onSuccess={handleAuthSuccess}
+ startFlow={() =>
+ resolvedTransport.ghLogin?.(effectiveHost ?? '') ?? resolvedTransport.start()
+ }
+ />
+ </DialogBody>
+
+ <DialogFooter>
+ <Button variant="ghost" onClick={() => setStep('pat')}>
+ <Trans>Use a token instead</Trans>
+ </Button>
+ <Button variant="outline" className="font-mono uppercase" onClick={handleCancel}>
+ <Trans>Cancel</Trans>
+ </Button>
+ </DialogFooter>
+ </>
+ )}
+
{step === 'identity' && authResult && (
<>
<DialogBody>
diff --git a/packages/app/src/components/ShareReceiveDialog.dom.test.tsx b/packages/app/src/components/ShareReceiveDialog.dom.test.tsx
index 255af61e3..df374f455 100644
--- a/packages/app/src/components/ShareReceiveDialog.dom.test.tsx
+++ b/packages/app/src/components/ShareReceiveDialog.dom.test.tsx
@@ -1,6 +1,6 @@
-import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { OkShareReceivedPayload } from '@/lib/desktop-bridge-types';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
@@ -10,7 +10,7 @@ function createTestStore(initial: SharePayload) {
let current = initial;
const listeners = new Set<() => void>();
return {
- dismiss: mock(() => {
+ dismiss: vi.fn(() => {
current = null;
for (const listener of listeners) listener();
}),
@@ -33,6 +33,7 @@ function okPayload(
return {
kind: 'launcher-miss',
share: {
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
branch: 'main',
@@ -44,24 +45,24 @@ function okPayload(
}
const toast = {
- error: mock((_message: string, _opts?: unknown) => {}),
- info: mock((_message: string, _opts?: unknown) => {}),
- success: mock((_message: string, _opts?: unknown) => {}),
+ error: vi.fn((_message: string, _opts?: unknown) => {}),
+ info: vi.fn((_message: string, _opts?: unknown) => {}),
+ success: vi.fn((_message: string, _opts?: unknown) => {}),
};
import * as actualLinguiMacro from '@lingui/react/macro';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children?: ReactNode }) => <>{children}</>,
useLingui: () => ({ t: renderLinguiTemplate }),
}));
-mock.module('sonner', () => ({
+vi.doMock('sonner', () => ({
toast,
}));
-mock.module('@/components/ui/button', () => ({
+vi.doMock('@/components/ui/button', () => ({
Button: ({
children,
className: _className,
@@ -79,7 +80,7 @@ mock.module('@/components/ui/button', () => ({
),
}));
-mock.module('@/components/ui/dialog', () => ({
+vi.doMock('@/components/ui/dialog', () => ({
Dialog: ({ children, open }: { children?: ReactNode; open?: boolean }) =>
open ? <div data-testid="dialog-root">{children}</div> : null,
DialogBody: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
@@ -109,15 +110,15 @@ function createBridge() {
__folderPicks: folderPicks,
__validationResults: validationResults,
dialog: {
- openFolder: mock(() => Promise.resolve(folderPicks.shift() ?? null)),
+ openFolder: vi.fn(() => Promise.resolve(folderPicks.shift() ?? null)),
},
navigator: {
- open: mock(() => Promise.resolve()),
+ open: vi.fn(() => Promise.resolve()),
},
project: {
- awaitBranchSwitched: mock(() => Promise.resolve({ ok: true as const })),
- checkDocExists: mock(() => Promise.resolve('exists')),
- fetchBranchInfo: mock(() =>
+ awaitBranchSwitched: vi.fn(() => Promise.resolve({ ok: true as const })),
+ checkDocExists: vi.fn(() => Promise.resolve('exists')),
+ fetchBranchInfo: vi.fn(() =>
Promise.resolve({
branchIsLocal: true,
currentBranch: 'main',
@@ -127,15 +128,15 @@ function createBridge() {
shareFileExists: true,
}),
),
- listRecent: mock(() => Promise.resolve([])),
- open: mock(() => Promise.resolve()),
- readHeadBranch: mock(() =>
+ listRecent: vi.fn(() => Promise.resolve([])),
+ open: vi.fn(() => Promise.resolve()),
+ readHeadBranch: vi.fn(() =>
Promise.resolve({ currentBranch: 'main', detached: false, headSha: null }),
),
- runCheckout: mock(() => Promise.resolve({ ok: true as const })),
+ runCheckout: vi.fn(() => Promise.resolve({ ok: true as const })),
},
share: {
- validateLocalFolder: mock(() =>
+ validateLocalFolder: vi.fn(() =>
Promise.resolve(validationResults.shift() ?? { kind: 'ok', gitRemoteUrl: '' }),
),
},
@@ -167,13 +168,13 @@ async function renderDialog({
}
describe('ShareReceiveDialog runtime behavior', () => {
- let consoleLogSpy: ReturnType<typeof spyOn>;
- let consoleWarnSpy: ReturnType<typeof spyOn>;
+ let consoleLogSpy: ReturnType<typeof vi.spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
for (const fn of [toast.error, toast.info, toast.success]) fn.mockClear();
- consoleLogSpy = spyOn(console, 'log').mockImplementation(() => {});
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
@@ -189,9 +190,9 @@ describe('ShareReceiveDialog runtime behavior', () => {
test('clone failure leaves the dialog mounted and the sign-in affordance visible', async () => {
const cloneController = {
- getAuthStatus: mock(() => Promise.resolve({ authenticated: false, host: 'github.com' })),
- runClone: mock(() => Promise.resolve({ kind: 'error' })),
- startSignIn: mock(() => Promise.resolve(null)),
+ getAuthStatus: vi.fn(() => Promise.resolve({ authenticated: false, host: 'github.com' })),
+ runClone: vi.fn(() => Promise.resolve({ kind: 'error' })),
+ startSignIn: vi.fn(() => Promise.resolve(null)),
};
await renderDialog({ cloneController });
@@ -213,8 +214,8 @@ describe('ShareReceiveDialog runtime behavior', () => {
test('clone failure surfaces a persistent in-dialog error view with the GitHub error, reasons, and recovery', async () => {
const cloneController = {
- getAuthStatus: mock(() => Promise.resolve({ authenticated: false, host: 'github.com' })),
- runClone: mock(() =>
+ getAuthStatus: vi.fn(() => Promise.resolve({ authenticated: false, host: 'github.com' })),
+ runClone: vi.fn(() =>
Promise.resolve({
kind: 'error',
detail: [
@@ -224,7 +225,7 @@ describe('ShareReceiveDialog runtime behavior', () => {
].join('\n'),
}),
),
- startSignIn: mock(() => Promise.resolve(null)),
+ startSignIn: vi.fn(() => Promise.resolve(null)),
};
await renderDialog({ cloneController });
@@ -269,9 +270,9 @@ describe('ShareReceiveDialog runtime behavior', () => {
test('clone error with no detail omits the error-message line but still shows the error view', async () => {
const cloneController = {
- getAuthStatus: mock(() => Promise.resolve({ authenticated: false, host: 'github.com' })),
- runClone: mock(() => Promise.resolve({ kind: 'error' })),
- startSignIn: mock(() => Promise.resolve(null)),
+ getAuthStatus: vi.fn(() => Promise.resolve({ authenticated: false, host: 'github.com' })),
+ runClone: vi.fn(() => Promise.resolve({ kind: 'error' })),
+ startSignIn: vi.fn(() => Promise.resolve(null)),
};
await renderDialog({ cloneController });
@@ -290,14 +291,14 @@ describe('ShareReceiveDialog runtime behavior', () => {
test('"Try again" clears the error view and re-invokes the clone', async () => {
let call = 0;
const cloneController = {
- getAuthStatus: mock(() => Promise.resolve({ authenticated: false, host: 'github.com' })),
- runClone: mock(() => {
+ getAuthStatus: vi.fn(() => Promise.resolve({ authenticated: false, host: 'github.com' })),
+ runClone: vi.fn(() => {
call += 1;
return Promise.resolve(
call === 1 ? { kind: 'error', detail: 'boom' } : { kind: 'cancelled' },
);
}),
- startSignIn: mock(() => Promise.resolve(null)),
+ startSignIn: vi.fn(() => Promise.resolve(null)),
};
await renderDialog({ cloneController });
@@ -317,9 +318,9 @@ describe('ShareReceiveDialog runtime behavior', () => {
test('error view "I already have it locally" clears the error and opens the folder picker', async () => {
const bridge = createBridge(); // openFolder returns null by default (user cancels)
const cloneController = {
- getAuthStatus: mock(() => Promise.resolve({ authenticated: false, host: 'github.com' })),
- runClone: mock(() => Promise.resolve({ kind: 'error', detail: 'boom' })),
- startSignIn: mock(() => Promise.resolve(null)),
+ getAuthStatus: vi.fn(() => Promise.resolve({ authenticated: false, host: 'github.com' })),
+ runClone: vi.fn(() => Promise.resolve({ kind: 'error', detail: 'boom' })),
+ startSignIn: vi.fn(() => Promise.resolve(null)),
};
await renderDialog({ bridge, cloneController });
@@ -348,13 +349,50 @@ describe('ShareReceiveDialog runtime behavior', () => {
expect(screen.queryByTestId('share-receive-dialog')).toBeNull();
});
+ test('GHES miss: the auth banner shows the identity for the share host, not github.com', async () => {
+ const store = createTestStore(
+ okPayload({
+ host: 'ghes.acme.test',
+ owner: 'acme',
+ repo: 'kb',
+ sharedUrl: 'https://ghes.acme.test/acme/kb/blob/main/README.md',
+ }),
+ );
+ const seenHosts: Array<string | undefined> = [];
+ const cloneController = {
+ getAuthStatus: vi.fn((host?: string) => {
+ seenHosts.push(host);
+ // The enterprise host knows you as omar-acme; github.com would be a
+ // different account. The dialog must probe (and show) the share host.
+ return Promise.resolve(
+ host === 'ghes.acme.test'
+ ? { authenticated: true, host, login: 'omar-acme' }
+ : { authenticated: true, host: 'github.com', login: 'omar-inkeep' },
+ );
+ }),
+ runClone: vi.fn(() => Promise.resolve({ kind: 'ok', dir: '/cloned/kb' })),
+ startSignIn: vi.fn(() => Promise.resolve(null)),
+ };
+
+ await renderDialog({ cloneController, store });
+
+ expect(await screen.findByTestId('share-receive-dialog')).toBeTruthy();
+ await waitFor(() =>
+ expect(screen.getByTestId('share-receive-auth-banner').textContent).toContain('omar-acme'),
+ );
+ expect(screen.getByTestId('share-receive-auth-banner').textContent).not.toContain(
+ 'omar-inkeep',
+ );
+ expect(seenHosts).toEqual(['ghes.acme.test']);
+ });
+
test('Q2 miss renders metadata, anonymous clone without sign-in, sign-in affordance, clone success, and local picker recovery', async () => {
const bridge = createBridge();
const store = createTestStore(okPayload({ branch: 'feat/share' }));
const cloneController = {
- getAuthStatus: mock(() => Promise.resolve({ authenticated: false, host: 'github.com' })),
- runClone: mock(() => Promise.resolve({ kind: 'ok', dir: '/cloned/open-knowledge' })),
- startSignIn: mock(() =>
+ getAuthStatus: vi.fn(() => Promise.resolve({ authenticated: false, host: 'github.com' })),
+ runClone: vi.fn(() => Promise.resolve({ kind: 'ok', dir: '/cloned/open-knowledge' })),
+ startSignIn: vi.fn(() =>
Promise.resolve({ authenticated: true, host: 'github.com', login: 'alice' }),
),
};
@@ -415,7 +453,7 @@ describe('ShareReceiveDialog runtime behavior', () => {
// surface rather than open the doc directly on the wrong branch.
await waitFor(() => expect(bridge.project.readHeadBranch).toHaveBeenCalledWith('/right'));
await waitFor(() => {
- const openArg = (bridge.project.open as ReturnType<typeof mock>).mock.calls.at(-1)?.[0] as {
+ const openArg = (bridge.project.open as ReturnType<typeof vi.fn>).mock.calls.at(-1)?.[0] as {
path?: string;
pendingDeepLinkTarget?: unknown;
pendingShareBranchSwitch?: { projectPath?: string; currentBranch?: string | null };
@@ -453,7 +491,7 @@ describe('ShareReceiveDialog runtime behavior', () => {
// editor window mounts ShareBranchSwitchDialog), NOT a plain deep-link open
// on the current branch.
await waitFor(() => expect(bridge.project.open).toHaveBeenCalled());
- const openArg = (bridge.project.open as ReturnType<typeof mock>).mock.calls.at(-1)?.[0] as {
+ const openArg = (bridge.project.open as ReturnType<typeof vi.fn>).mock.calls.at(-1)?.[0] as {
path?: string;
pendingDeepLinkTarget?: unknown;
pendingShareBranchSwitch?: {
@@ -497,7 +535,7 @@ describe('ShareReceiveDialog runtime behavior', () => {
fireEvent.click(screen.getByTestId('share-receive-local'));
await waitFor(() => expect(bridge.project.open).toHaveBeenCalled());
- const openArg = (bridge.project.open as ReturnType<typeof mock>).mock.calls.at(-1)?.[0] as {
+ const openArg = (bridge.project.open as ReturnType<typeof vi.fn>).mock.calls.at(-1)?.[0] as {
pendingDeepLinkTarget?: unknown;
pendingShareBranchSwitch?: unknown;
};
@@ -517,7 +555,7 @@ describe('ShareReceiveDialog runtime behavior', () => {
gitRemoteUrl: 'https://github.com/inkeep/open-knowledge.git',
});
// Detached HEAD is not on the share's branch -> route to the switch surface.
- bridge.project.readHeadBranch = mock(() =>
+ bridge.project.readHeadBranch = vi.fn(() =>
Promise.resolve({ currentBranch: null, detached: true, headSha: '1234567' }),
);
@@ -527,7 +565,7 @@ describe('ShareReceiveDialog runtime behavior', () => {
fireEvent.click(screen.getByTestId('share-receive-local'));
await waitFor(() => expect(bridge.project.open).toHaveBeenCalled());
- const openArg = (bridge.project.open as ReturnType<typeof mock>).mock.calls.at(-1)?.[0] as {
+ const openArg = (bridge.project.open as ReturnType<typeof vi.fn>).mock.calls.at(-1)?.[0] as {
pendingDeepLinkTarget?: unknown;
pendingShareBranchSwitch?: {
currentBranch?: string | null;
@@ -554,7 +592,7 @@ describe('ShareReceiveDialog runtime behavior', () => {
// Graceful-fail sentinel (missing / unreadable .git/HEAD): classify as a
// match so a single broken clone never forces a needless branch-switch
// prompt — symmetric with the recents path's silent dispatch.
- bridge.project.readHeadBranch = mock(() =>
+ bridge.project.readHeadBranch = vi.fn(() =>
Promise.resolve({ currentBranch: null, detached: false, headSha: null }),
);
@@ -564,7 +602,7 @@ describe('ShareReceiveDialog runtime behavior', () => {
fireEvent.click(screen.getByTestId('share-receive-local'));
await waitFor(() => expect(bridge.project.open).toHaveBeenCalled());
- const openArg = (bridge.project.open as ReturnType<typeof mock>).mock.calls.at(-1)?.[0] as {
+ const openArg = (bridge.project.open as ReturnType<typeof vi.fn>).mock.calls.at(-1)?.[0] as {
pendingDeepLinkTarget?: unknown;
pendingShareBranchSwitch?: unknown;
};
@@ -589,7 +627,7 @@ describe('ShareReceiveDialog runtime behavior', () => {
fireEvent.click(screen.getByTestId('share-receive-local'));
await waitFor(() => expect(bridge.project.open).toHaveBeenCalled());
- const openArg = (bridge.project.open as ReturnType<typeof mock>).mock.calls.at(-1)?.[0] as {
+ const openArg = (bridge.project.open as ReturnType<typeof vi.fn>).mock.calls.at(-1)?.[0] as {
pendingDeepLinkTarget?: unknown;
pendingShareBranchSwitch?: unknown;
};
@@ -609,7 +647,7 @@ describe('ShareReceiveDialog runtime behavior', () => {
// Distinct from the graceful-fail sentinel (a resolved all-null value):
// an IPC-transport rejection hits the catch, which leaves the all-null
// sentinel in place -> classifies as a match -> plain open, never a dead end.
- bridge.project.readHeadBranch = mock(() => Promise.reject(new Error('ipc channel closed')));
+ bridge.project.readHeadBranch = vi.fn(() => Promise.reject(new Error('ipc channel closed')));
await renderDialog({ bridge, store });
@@ -617,7 +655,7 @@ describe('ShareReceiveDialog runtime behavior', () => {
fireEvent.click(screen.getByTestId('share-receive-local'));
await waitFor(() => expect(bridge.project.open).toHaveBeenCalled());
- const openArg = (bridge.project.open as ReturnType<typeof mock>).mock.calls.at(-1)?.[0] as {
+ const openArg = (bridge.project.open as ReturnType<typeof vi.fn>).mock.calls.at(-1)?.[0] as {
pendingDeepLinkTarget?: unknown;
pendingShareBranchSwitch?: unknown;
};
diff --git a/packages/app/src/components/ShareReceiveDialog.tsx b/packages/app/src/components/ShareReceiveDialog.tsx
index e1fcf1ca2..766689b45 100644
--- a/packages/app/src/components/ShareReceiveDialog.tsx
+++ b/packages/app/src/components/ShareReceiveDialog.tsx
@@ -78,7 +78,9 @@ export type ShareReceiveCloneResult =
| { readonly kind: 'error'; readonly detail?: string };
export interface ShareReceiveCloneController {
- getAuthStatus(): Promise<OkLocalOpAuthStatusResponse>;
+ /** `host` scopes the identity probe to the share's GitHub host (github.com
+ * or GHES) so the dialog shows the account for that host, not github.com. */
+ getAuthStatus(host?: string): Promise<OkLocalOpAuthStatusResponse>;
startSignIn(): Promise<OkLocalOpAuthStatusResponse | null>;
runClone(args: { url: string; branch?: string | null }): Promise<ShareReceiveCloneResult>;
}
@@ -232,8 +234,9 @@ function ShareReceiveDialogInner({
if (authProbeStartedRef.current) return;
authProbeStartedRef.current = true;
setAuthChecking(true);
+ const shareHost = payload.share.host;
void cloneController
- .getAuthStatus()
+ .getAuthStatus(shareHost)
.then((result) => {
setAuthStatus(result);
})
@@ -245,7 +248,7 @@ function ShareReceiveDialogInner({
'[receive] auth pre-flight probe failed',
err instanceof Error ? err.message : err,
);
- setAuthStatus({ authenticated: false, host: 'github.com' });
+ setAuthStatus({ authenticated: false, host: shareHost });
})
.finally(() => {
setAuthChecking(false);
@@ -255,7 +258,7 @@ function ShareReceiveDialogInner({
const launcherMiss = isLauncherMissPayload(payload) ? payload : null;
const launcherConsent = isLauncherConsentPayload(payload) ? payload : null;
const share = launcherMiss?.share ?? launcherConsent?.share ?? null;
- const expected = share ? { owner: share.owner, repo: share.repo } : null;
+ const expected = share ? { host: share.host, owner: share.owner, repo: share.repo } : null;
// Kind-aware noun so the dialog title reads correctly for folder shares as
// well as single-doc shares; defaults to "document" when no share is active.
const targetNoun = share?.target.kind === 'folder' ? t`folder` : t`document`;
@@ -357,6 +360,7 @@ function ShareReceiveDialogInner({
if (!folderPath) break;
const result = await bridge.share.validateLocalFolder({
folderPath,
+ host: expected.host,
owner: expected.owner,
repo: expected.repo,
});
diff --git a/packages/app/src/components/SyncStatusBadge.tsx b/packages/app/src/components/SyncStatusBadge.tsx
index e5dab3ba0..88f06b699 100644
--- a/packages/app/src/components/SyncStatusBadge.tsx
+++ b/packages/app/src/components/SyncStatusBadge.tsx
@@ -179,9 +179,16 @@ export function formatPausedReason(reason: string): string {
* copy as a user whose engine paused after enabling sync.
*/
export function formatPushPermissionDenied(
- reason: 'no-collaborator' | 'private-no-access' | 'repo-not-found' | undefined,
+ reason:
+ | 'no-collaborator'
+ | 'private-no-access'
+ | 'repo-not-found'
+ | 'not-authenticated'
+ | undefined,
): string {
switch (reason) {
+ case 'not-authenticated':
+ return t`You're signed out — sign in to resume syncing.`;
case 'no-collaborator':
return t`You don't have permission to push to this repo`;
case 'private-no-access':
@@ -193,6 +200,18 @@ export function formatPushPermissionDenied(
}
}
+/**
+ * Whether the push-permission denial is a *signed-out* one (no credential
+ * resolved), which a reconnect fixes — as opposed to a genuine read-only
+ * collaborator, where re-auth won't help. Drives the "Connect" affordance on
+ * the otherwise button-less denied surfaces.
+ */
+export function shouldOfferReconnect(pushPermission: PushPermissionWire | undefined): boolean {
+ return (
+ pushPermission?.checkStatus === 'denied' && pushPermission.deniedReason === 'not-authenticated'
+ );
+}
+
/**
* Map a server-emitted `errorCode` to a Lingui-localized string. The server
* never carries English in `errorCode`; the wire payload is the bounded
@@ -463,7 +482,23 @@ function PopoverBody({ status, onSignIn, onSetIdentity }: PopoverBodyProps) {
)}
</p>
))}
- {status.pausedReason ? (
+ {shouldOfferReconnect(status.pushPermission) ? (
+ // Signed-out denial (no credential resolved) — reconnecting resumes
+ // sync, so offer it here. Takes precedence over the button-less
+ // `pausedReason`/`denied` branches below, which is exactly the stuck
+ // state (sync was enabled, then the credential went away). The genuine
+ // read-only-collaborator denial keeps the button-less copy.
+ <div className="flex items-start gap-2">
+ <p className="text-xs text-muted-foreground flex-1 min-w-0">
+ <Trans>You're signed out — sign in to resume syncing.</Trans>
+ </p>
+ {onSignIn && (
+ <Button variant="outline" size="xs" className="self-start" onClick={onSignIn}>
+ <Trans>Sign in</Trans>
+ </Button>
+ )}
+ </div>
+ ) : status.pausedReason ? (
<p className="text-xs text-muted-foreground">{formatPausedReason(status.pausedReason)}</p>
) : status.pushPermission?.checkStatus === 'denied' ? (
<p className="text-xs text-muted-foreground">
@@ -574,7 +609,7 @@ function PopoverBody({ status, onSignIn, onSetIdentity }: PopoverBodyProps) {
)}
{enabled && status.state === 'auth-error' && (
<Button variant="outline" size="xs" onClick={onSignIn}>
- <Trans>Connect GitHub</Trans>
+ <Trans>Sign in</Trans>
</Button>
)}
{enabled && status.state === 'offline' && (
@@ -605,7 +640,7 @@ function PopoverBody({ status, onSignIn, onSetIdentity }: PopoverBodyProps) {
// ── public component ──────────────────────────────────────────────────────────
interface SyncStatusBadgeProps {
- /** Called when "Connect GitHub" is clicked in the auth-error popover or enable-sync prompt. */
+ /** Called when "Sign in" is clicked in the auth-error popover or enable-sync prompt. */
onSignIn?: () => void;
/** Called when "Set identity" is clicked in the identity-unresolved nudge. */
onSetIdentity?: () => void;
diff --git a/packages/app/src/components/settings/AccountSection.dom.test.tsx b/packages/app/src/components/settings/AccountSection.dom.test.tsx
index f0f3e625a..75958e0d0 100644
--- a/packages/app/src/components/settings/AccountSection.dom.test.tsx
+++ b/packages/app/src/components/settings/AccountSection.dom.test.tsx
@@ -7,9 +7,9 @@
* results.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { act, cleanup, render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import { getLastKnownSignedIn, setLastKnownSignedIn } from '@/lib/auth-state-cache';
import type { OkLocalOpAuthEvent, OkLocalOpAuthStatusResponse } from '@/lib/desktop-bridge-types';
@@ -112,20 +112,20 @@ describe('AccountSection', () => {
expect(screen.queryByTestId('settings-account-connect')).toBeNull();
});
- test('shows "Not connected" and a Connect GitHub control when unauthenticated', async () => {
+ test('shows "Not connected" and a Sign in control when unauthenticated', async () => {
renderSection(makeQueryTransport({ status: async () => NOT_CONNECTED }));
expect(await screen.findByText('Not connected')).toBeDefined();
- const connect = screen.getByRole('button', { name: 'Connect GitHub' });
+ const connect = screen.getByRole('button', { name: 'Sign in' });
expect(connect).toBeDefined();
expect(screen.queryByTestId('settings-account-disconnect')).toBeNull();
});
- test('clicking Connect GitHub opens the AuthModal in connect mode (not reauth)', async () => {
+ test('clicking Sign in opens the AuthModal in connect mode (not reauth)', async () => {
const user = userEvent.setup();
renderSection(makeQueryTransport({ status: async () => NOT_CONNECTED }));
- await user.click(await screen.findByRole('button', { name: 'Connect GitHub' }));
+ await user.click(await screen.findByRole('button', { name: 'Sign in' }));
const dialog = await screen.findByRole('dialog');
expect(within(dialog).getByText('Connect GitHub')).toBeDefined();
diff --git a/packages/app/src/components/settings/AccountSection.tsx b/packages/app/src/components/settings/AccountSection.tsx
index 1d832dbe3..dedc2f721 100644
--- a/packages/app/src/components/settings/AccountSection.tsx
+++ b/packages/app/src/components/settings/AccountSection.tsx
@@ -170,8 +170,22 @@ export function AccountSection({ authQueryTransport, authTransport }: AccountSec
<AuthModal
open={authModalOpen}
- onOpenChange={setAuthModalOpen}
+ onOpenChange={(open) => {
+ setAuthModalOpen(open);
+ // Re-probe on close so a gh installed while the dialog was open is
+ // reflected next time it opens — this is what makes the token panel's
+ // "reopen this window to sign in with your browser" hint come true
+ // (the server caches only a positive gh lookup, so a fresh status
+ // check re-detects it). Harmless on the success path, which already
+ // reloads via onSuccess.
+ if (!open) void loadStatus();
+ }}
transport={authTransport}
+ // Drive the sign-in method by the probed origin host: a non-github.com
+ // (GHES) host shows the PAT panel, since the OAuth device flow can't work
+ // there. github.com / unknown keeps the device flow.
+ host={status.phase === 'loaded' ? status.result.host : undefined}
+ ghAvailable={status.phase === 'loaded' ? status.result.ghAvailable : undefined}
onSuccess={() => {
void loadStatus();
}}
@@ -266,7 +280,7 @@ function DisconnectedRow({ onConnect }: { onConnect: () => void }) {
</p>
</div>
<Button onClick={onConnect} data-testid="settings-account-connect">
- <Trans>Connect GitHub</Trans>
+ <Trans>Sign in</Trans>
</Button>
</div>
</div>
diff --git a/packages/app/src/components/settings/SettingsDialogBody.tsx b/packages/app/src/components/settings/SettingsDialogBody.tsx
index 7ff4aab1c..533e59e6b 100644
--- a/packages/app/src/components/settings/SettingsDialogBody.tsx
+++ b/packages/app/src/components/settings/SettingsDialogBody.tsx
@@ -57,6 +57,7 @@ import { PublishToGitHubDialog } from '@/components/PublishToGitHubDialog';
import {
formatPausedReason,
shouldDisableSyncSwitch,
+ shouldOfferReconnect,
shouldOfferSignInAgain,
} from '@/components/SyncStatusBadge';
import { SharingSection } from '@/components/settings/SharingSection';
@@ -991,7 +992,16 @@ function SyncSection() {
// already on when probe denied). Replace the standard body copy
// with the permission-specific message — the redundant
// sectionMessage paragraph below is suppressed in this case.
- <Trans>Auto-sync is off — you don't have permission to push to this repo</Trans>
+ // "Paused", not "off": the user's preference is still on (the
+ // toggle shows it), sync is just blocked. Signed-out vs genuine
+ // read-only get different remedies.
+ shouldOfferReconnect(status?.pushPermission) ? (
+ <Trans>Auto-sync is paused — sign in to resume.</Trans>
+ ) : (
+ <Trans>
+ Auto-sync is paused — you don't have permission to push to this repo.
+ </Trans>
+ )
) : enabled ? (
<Trans>
Auto-sync is on — your commits push and remote changes pull on intervals.
@@ -1069,6 +1079,18 @@ function SyncSection() {
</Button>
</div>
)}
+ {shouldOfferReconnect(status?.pushPermission) && (
+ // Signed-out denial ('denied/not-authenticated') — reconnecting
+ // resumes sync (the body copy above reads "sign in to resume"), so
+ // surface the button. Mirrors the popover's reconnect affordance.
+ <div className="mt-2 flex justify-start" data-testid="settings-sync-reconnect">
+ {/* Default size (not xs) to match the None/On/Off toggle row above:
+ both resolve to h-8 / px-2.5 / text-sm. */}
+ <Button variant="outline" onClick={() => setAuthModalOpen(true)}>
+ <Trans>Sign in</Trans>
+ </Button>
+ </div>
+ )}
</div>
<div className="rounded-md border p-3 space-y-2" data-testid="settings-sync-default">
<div className="space-y-0.5">
@@ -1124,6 +1146,10 @@ function SyncSection() {
open={authModalOpen}
onOpenChange={setAuthModalOpen}
onSuccess={() => setAuthModalOpen(false)}
+ // Both affordances that open this modal are expired/signed-out
+ // recoveries (probe-401 "sign in again" and the signed-out reconnect),
+ // never a first connection — title accordingly.
+ reauth
/>
</section>
);
diff --git a/packages/app/src/components/settings/SettingsDialogShell.tsx b/packages/app/src/components/settings/SettingsDialogShell.tsx
index 851508b37..7da2ba07e 100644
--- a/packages/app/src/components/settings/SettingsDialogShell.tsx
+++ b/packages/app/src/components/settings/SettingsDialogShell.tsx
@@ -88,8 +88,9 @@ export function SettingsDialogShell({
useConfigContext();
const { desktopPresent } = useClaudeDesktopIntegration();
- // On each fresh open, honor the deep-link section (`#settings/<id>`) if one
- // was given, else default to USER → Preferences. No in-session memory of
+ // On each fresh open, honor the deep-link section (`#settings/<id>`, e.g.
+ // `#settings/account` from the GHES trust-gate "Connect" flow) if one was
+ // given, else default to USER → Preferences. No in-session memory of
// last-viewed section beyond the open edge; sidebar clicks update activeId
// locally without touching the hash.
const [activeId, setActiveId] = useState(initialSection ?? 'preferences');
diff --git a/packages/app/src/lib/desktop-bridge-types.ts b/packages/app/src/lib/desktop-bridge-types.ts
index d5363b7a4..cdd46bc4c 100644
--- a/packages/app/src/lib/desktop-bridge-types.ts
+++ b/packages/app/src/lib/desktop-bridge-types.ts
@@ -343,6 +343,8 @@ interface OkUpdateStuckHintInfo {
/** Local copy — see canonical `OkSharePayloadFields` in
* `packages/desktop/src/shared/bridge-contract.ts`. */
export interface OkSharePayloadFields {
+ /** GitHub host of the shared repo: `github.com` or a GHES hostname. */
+ readonly host: string;
readonly owner: string;
readonly repo: string;
readonly branch: string;
@@ -390,6 +392,7 @@ export type ShareFolderValidationResult =
| { readonly kind: 'not-git' }
| { readonly kind: 'no-origin' }
| { readonly kind: 'wrong-repo'; readonly actualOwner: string; readonly actualRepo: string }
+ | { readonly kind: 'wrong-host'; readonly actualHost: string }
| { readonly kind: 'non-github' }
| { readonly kind: 'symlink-escape' };
@@ -672,8 +675,10 @@ export type OkLocalOpAuthStatusResponse =
tier?: 'A' | 'B' | 'C';
name?: string;
email?: string;
+ /** Whether the gh CLI is installed (offer "Sign in with gh" for GHES). */
+ ghAvailable?: boolean;
}
- | { authenticated: false; host: string; error?: string };
+ | { authenticated: false; host: string; error?: string; ghAvailable?: boolean };
interface OkLocalOpRepoEntry {
full_name: string;
@@ -1373,6 +1378,7 @@ export interface OkDesktopBridge {
share: {
validateLocalFolder(args: {
folderPath: string;
+ host: string;
owner: string;
repo: string;
}): Promise<ShareFolderValidationResult>;
diff --git a/packages/app/src/lib/share/clone-controller.ts b/packages/app/src/lib/share/clone-controller.ts
index 03ea1688e..4d60c2877 100644
--- a/packages/app/src/lib/share/clone-controller.ts
+++ b/packages/app/src/lib/share/clone-controller.ts
@@ -54,8 +54,8 @@ function repoNameFromCloneUrl(url: string): string {
export function createCloneController(deps: CloneControllerDeps): ShareReceiveCloneController {
return {
- async getAuthStatus() {
- return deps.authQueryTransport.status();
+ async getAuthStatus(host?: string) {
+ return deps.authQueryTransport.status(host ? { host } : undefined);
},
async startSignIn() {
return deps.openSignIn();
diff --git a/packages/app/src/lib/share/receive-flow.test.ts b/packages/app/src/lib/share/receive-flow.test.ts
index 57fd7623a..fed1db140 100644
--- a/packages/app/src/lib/share/receive-flow.test.ts
+++ b/packages/app/src/lib/share/receive-flow.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import type {
OkShareReceivedPayload,
@@ -68,14 +68,14 @@ describe('formatCloneErrorMessage', () => {
describe('buildCloneUrl', () => {
test('matches the canonical .git form (the clone wizard accepts both forms equally)', () => {
- expect(buildCloneUrl({ owner: 'inkeep', repo: 'open-knowledge' })).toBe(
+ expect(buildCloneUrl({ host: 'github.com', owner: 'inkeep', repo: 'open-knowledge' })).toBe(
'https://github.com/inkeep/open-knowledge.git',
);
});
});
describe('mapValidationToToast', () => {
- const expected = { owner: 'inkeep', repo: 'open-knowledge' };
+ const expected = { host: 'github.com', owner: 'inkeep', repo: 'open-knowledge' };
function withKind<K extends ShareFolderValidationResult['kind']>(
kind: K,
@@ -91,6 +91,13 @@ describe('mapValidationToToast', () => {
actualRepo: extras && 'actualRepo' in extras ? (extras.actualRepo ?? 'b') : 'b',
};
}
+ if (kind === 'wrong-host') {
+ return {
+ kind: 'wrong-host',
+ actualHost:
+ extras && 'actualHost' in extras ? (extras.actualHost ?? 'other.host') : 'other.host',
+ };
+ }
return { kind } as ShareFolderValidationResult;
}
@@ -111,6 +118,13 @@ describe('mapValidationToToast', () => {
);
});
+ test('wrong-host names the server so the user sees "right repo, wrong host"', () => {
+ const result = withKind('wrong-host', { actualHost: 'ghes.acme.test' });
+ expect(mapValidationToToast(result, expected)).toBe(
+ 'This folder is a clone of inkeep/open-knowledge on ghes.acme.test, not github.com. Pick a folder cloned from github.com?',
+ );
+ });
+
test('non-github + symlink-escape + no-origin all surface the wrong-repo generic prompt (Q-A9 v1 simplification)', () => {
expect(mapValidationToToast(withKind('non-github'), expected)).toBe(
"This folder isn't a clone of inkeep/open-knowledge. Pick a different folder?",
diff --git a/packages/app/src/lib/share/receive-flow.ts b/packages/app/src/lib/share/receive-flow.ts
index 994e60277..ceb79c58c 100644
--- a/packages/app/src/lib/share/receive-flow.ts
+++ b/packages/app/src/lib/share/receive-flow.ts
@@ -48,6 +48,8 @@ export function mapValidationToToast(
return "This folder doesn't contain a git repository. Pick a different folder?";
case 'wrong-repo':
return `This folder is a clone of ${result.actualOwner}/${result.actualRepo}, not ${expected.owner}/${expected.repo}. Pick a different folder?`;
+ case 'wrong-host':
+ return `This folder is a clone of ${expected.owner}/${expected.repo} on ${result.actualHost}, not ${expected.host}. Pick a folder cloned from ${expected.host}?`;
case 'no-origin':
case 'non-github':
case 'symlink-escape':
diff --git a/packages/app/src/lib/transports/auth-query-transport.test.ts b/packages/app/src/lib/transports/auth-query-transport.test.ts
index dfdfdd0ed..6a655a45f 100644
--- a/packages/app/src/lib/transports/auth-query-transport.test.ts
+++ b/packages/app/src/lib/transports/auth-query-transport.test.ts
@@ -5,7 +5,7 @@
* handler in tests/integration/api-error-envelope.
*/
-import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { httpAuthQueryTransport } from './auth-query-transport';
type FetchFn = typeof globalThis.fetch;
@@ -52,7 +52,12 @@ describe('httpAuthQueryTransport().status', () => {
);
const [resA, resB] = await Promise.all([a, b]);
- expect(resA).toEqual({ authenticated: true, host: 'github.com', login: 'octocat' });
+ expect(resA).toEqual({
+ authenticated: true,
+ host: 'github.com',
+ login: 'octocat',
+ ghAvailable: false,
+ });
expect(resB).toEqual(resA);
});
@@ -91,10 +96,12 @@ describe('httpAuthQueryTransport().status', () => {
authenticated: true,
host: 'github.com',
login: 'octocat',
+ ghAvailable: false,
});
await expect(gitlabStatus).resolves.toEqual({
authenticated: false,
host: 'gitlab.com',
+ ghAvailable: false,
});
});
@@ -121,6 +128,7 @@ describe('httpAuthQueryTransport().status', () => {
await expect(transport.status()).resolves.toEqual({
authenticated: false,
host: 'github.com',
+ ghAvailable: false,
});
expect(fetchCalls).toHaveLength(2);
diff --git a/packages/app/src/lib/transports/auth-query-transport.ts b/packages/app/src/lib/transports/auth-query-transport.ts
index 2270495e0..0d2bcfd17 100644
--- a/packages/app/src/lib/transports/auth-query-transport.ts
+++ b/packages/app/src/lib/transports/auth-query-transport.ts
@@ -81,6 +81,10 @@ async function requestAuthStatus(request?: {
}
const data = (await res.json()) as Record<string, unknown>;
const h = typeof data.host === 'string' ? data.host : host;
+ // Whether the server found a usable gh CLI. Carried on both the connected and
+ // disconnected responses — the disconnected case is exactly when the AuthModal
+ // needs it, to decide whether to offer "Sign in with gh" on an enterprise host.
+ const ghAvailable = data.ghAvailable === true;
if (data.authenticated === true && typeof data.login === 'string') {
// Mirror the whitelist in auth-query.ts so the HTTP and IPC paths
// surface `tier` consistently — without this, only IPC carries it.
@@ -93,12 +97,14 @@ async function requestAuthStatus(request?: {
tier,
name: typeof data.name === 'string' ? data.name : undefined,
email: typeof data.email === 'string' ? data.email : undefined,
+ ghAvailable,
};
}
return {
authenticated: false,
host: h,
error: typeof data.error === 'string' ? data.error : undefined,
+ ghAvailable,
};
}
diff --git a/packages/app/src/lib/transports/auth-transport.test.ts b/packages/app/src/lib/transports/auth-transport.test.ts
new file mode 100644
index 000000000..4a39fd95e
--- /dev/null
+++ b/packages/app/src/lib/transports/auth-transport.test.ts
@@ -0,0 +1,144 @@
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { httpAuthTransport } from './auth-transport';
+
+const realFetch = globalThis.fetch;
+afterEach(() => {
+ globalThis.fetch = realFetch;
+});
+
+/** Drain a handle's async-iterable into an array (ends on terminal event). */
+async function collectEvents(handle: {
+ events: AsyncIterable<unknown>;
+}): Promise<Array<Record<string, unknown>>> {
+ const out: Array<Record<string, unknown>> = [];
+ for await (const e of handle.events) out.push(e as Record<string, unknown>);
+ return out;
+}
+
+/** An NDJSON Response whose body streams the given lines. */
+function ndjsonResponse(lines: string[]): Response {
+ return new Response(new Blob([lines.map((l) => `${l}\n`).join('')]).stream(), { status: 200 });
+}
+
+describe('httpAuthTransport().pat', () => {
+ test('POSTs { host, token } to the pat relay and returns the login on success', async () => {
+ const calls: Array<{ url: string; body: unknown }> = [];
+ globalThis.fetch = vi.fn(async (url: string, init?: RequestInit) => {
+ calls.push({ url, body: JSON.parse(String(init?.body)) });
+ return new Response(JSON.stringify({ host: 'ghes.acme.test', login: 'omar-acme' }), {
+ status: 200,
+ });
+ }) as unknown as typeof fetch;
+
+ const result = await httpAuthTransport().pat?.('ghes.acme.test', 'ghp_secret');
+ expect(result).toEqual({ ok: true, login: 'omar-acme' });
+ expect(calls).toHaveLength(1);
+ expect(calls[0]?.url).toBe('/api/local-op/auth/pat');
+ expect(calls[0]?.body).toEqual({ host: 'ghes.acme.test', token: 'ghp_secret' });
+ });
+
+ test('surfaces the problem+json detail on a rejected token (bounded reason)', async () => {
+ globalThis.fetch = vi.fn(
+ async () =>
+ new Response(
+ JSON.stringify({
+ type: 'urn:ok:error:auth-failed',
+ title: 'Authentication failed',
+ status: 400,
+ detail: 'Token invalid for ghes.acme.test',
+ }),
+ { status: 400, headers: { 'Content-Type': 'application/problem+json' } },
+ ),
+ ) as unknown as typeof fetch;
+
+ const result = await httpAuthTransport().pat?.('ghes.acme.test', 'bad');
+ expect(result).toEqual({ ok: false, error: 'Token invalid for ghes.acme.test' });
+ });
+
+ test('returns a generic connection error when the request throws', async () => {
+ globalThis.fetch = vi.fn(async () => {
+ throw new Error('network down');
+ }) as unknown as typeof fetch;
+
+ const result = await httpAuthTransport().pat?.('ghes.acme.test', 'x');
+ expect(result?.ok).toBe(false);
+ expect(result?.error).toBe('Connection error — try again');
+ });
+});
+
+describe('httpAuthTransport().start / ghLogin (streamAuthEndpoint)', () => {
+ test('a pre-stream problem+json failure surfaces the typed title as a single error event', async () => {
+ globalThis.fetch = vi.fn(
+ async () =>
+ new Response(
+ JSON.stringify({
+ type: 'urn:ok:error:auth-failed',
+ title: 'The GitHub CLI (gh) is not installed.',
+ status: 400,
+ }),
+ { status: 400, headers: { 'Content-Type': 'application/problem+json' } },
+ ),
+ ) as unknown as typeof fetch;
+
+ const events = await collectEvents(httpAuthTransport().ghLogin?.('ghes.acme.test') as never);
+ expect(events).toEqual([{ type: 'error', message: 'The GitHub CLI (gh) is not installed.' }]);
+ });
+
+ test('a pre-stream failure with an unparseable body falls back to the generic message', async () => {
+ globalThis.fetch = vi.fn(
+ async () => new Response('<html>gateway error</html>', { status: 502 }),
+ ) as unknown as typeof fetch;
+
+ const events = await collectEvents(httpAuthTransport().start() as never);
+ expect(events).toEqual([{ type: 'error', message: 'Failed to start sign-in — try again' }]);
+ });
+
+ test('streams verification then complete, ending iteration on the terminal event', async () => {
+ globalThis.fetch = vi.fn(async () =>
+ ndjsonResponse([
+ JSON.stringify({
+ type: 'verification',
+ user_code: 'AB-12',
+ verification_uri: 'https://github.com/login/device',
+ expires_in: 900,
+ }),
+ JSON.stringify({ type: 'complete', host: 'github.com', login: 'octocat' }),
+ ]),
+ ) as unknown as typeof fetch;
+
+ const events = await collectEvents(httpAuthTransport().start() as never);
+ expect(events.map((e) => e.type)).toEqual(['verification', 'complete']);
+ expect(events[1]?.login).toBe('octocat');
+ });
+
+ test('a mid-stream {type:error, problem} line is bridged to {type:error, message}', async () => {
+ globalThis.fetch = vi.fn(async () =>
+ ndjsonResponse([
+ JSON.stringify({
+ type: 'error',
+ problem: { title: 'Authentication failed', detail: 'Device flow was denied' },
+ }),
+ ]),
+ ) as unknown as typeof fetch;
+
+ const events = await collectEvents(httpAuthTransport().start() as never);
+ expect(events).toEqual([{ type: 'error', message: 'Device flow was denied' }]);
+ });
+
+ test('a stream that ends without a terminal event surfaces the no-confirmation error', async () => {
+ globalThis.fetch = vi.fn(async () =>
+ ndjsonResponse([
+ JSON.stringify({
+ type: 'verification',
+ user_code: 'AB-12',
+ verification_uri: 'https://github.com/login/device',
+ expires_in: 900,
+ }),
+ ]),
+ ) as unknown as typeof fetch;
+
+ const events = await collectEvents(httpAuthTransport().start() as never);
+ expect(events.map((e) => e.type)).toEqual(['verification', 'error']);
+ expect(events[1]?.message).toContain('without confirmation');
+ });
+});
diff --git a/packages/app/src/lib/transports/auth-transport.ts b/packages/app/src/lib/transports/auth-transport.ts
index dbd0d2595..61b58dcb7 100644
--- a/packages/app/src/lib/transports/auth-transport.ts
+++ b/packages/app/src/lib/transports/auth-transport.ts
@@ -27,109 +27,155 @@ import { createBufferedAsyncStream } from './buffered-async-stream';
*/
type AuthEvent = OkLocalOpAuthEvent;
-interface AuthTransportHandle {
+export interface AuthTransportHandle {
/** Async iterable of events. Iteration ends after `complete` / `error` / `cancel()`. */
readonly events: AsyncIterable<AuthEvent>;
/** Cancel the in-flight flow. Idempotent. */
cancel(): void;
}
+/** Result of a one-shot Personal Access Token sign-in. */
+interface PatResult {
+ ok: boolean;
+ /** The authenticated login on success. */
+ login?: string;
+ /** A bounded, user-facing failure reason (bad token / cert / network). */
+ error?: string;
+}
+
export interface AuthTransport {
/** Start a new device-flow login. */
start(): AuthTransportHandle;
+ /**
+ * One-shot Personal Access Token sign-in for enterprise (non-github.com)
+ * hosts, where the OAuth device flow can't work (OpenKnowledge's OAuth app
+ * isn't registered on arbitrary GHES servers). Optional — the HTTP path (the
+ * Account settings panel, where GHES connect happens) implements it.
+ */
+ pat?(host: string, token: string): Promise<PatResult>;
+ /**
+ * "Sign in with gh" — a browser device flow driven by the gh CLI, for
+ * enterprise hosts where gh's OAuth app works but OpenKnowledge's doesn't.
+ * Same event stream as `start()`. Optional — only the HTTP path implements it,
+ * and it's only offered when the server reports gh is installed (`ghAvailable`).
+ */
+ ghLogin?(host: string): AuthTransportHandle;
}
/**
- * HTTP transport — wraps `fetch('/api/local-op/auth/login')` and the
- * existing NDJSON line reader. Identical wire shape to the editor-window
- * path; safe to swap in here.
+ * Shared streaming client for the two device-flow endpoints (`auth/login` and
+ * `auth/gh-login`). Both stream the same NDJSON AuthEvent shape; only the URL +
+ * body differ, so the reader/parser lives here once.
*/
-export function httpAuthTransport(): AuthTransport {
- return {
- start(): AuthTransportHandle {
- return createBufferedAsyncStream<AuthEvent>((push, signal) => {
- void (async () => {
+function streamAuthEndpoint(url: string, requestBody: unknown): AuthTransportHandle {
+ return createBufferedAsyncStream<AuthEvent>((push, signal) => {
+ void (async () => {
+ try {
+ const res = await fetch(url, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(requestBody),
+ signal,
+ });
+ if (!res.ok) {
+ // Pre-stream RFC 9457 problem+json: the server emitted an error before
+ // committing to the NDJSON stream. Surface the typed `title`.
+ let message = 'Failed to start sign-in — try again';
try {
- const res = await fetch('/api/local-op/auth/login', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ json: true }),
- signal,
- });
- if (!res.ok) {
- // Pre-stream RFC 9457 problem+json: the server emitted an error
- // before committing to the NDJSON stream. Surface the typed
- // `title` so the user sees the actual reason instead of a
- // generic message.
- let message = 'Failed to start sign-in — try again';
- try {
- const body = (await res.json()) as unknown;
- const result = ProblemDetailsSchema.safeParse(body);
- if (result.success) message = result.data.title;
- } catch {
- /* keep generic message */
- }
- push({ type: 'error', message });
- return;
- }
- if (!res.body) {
- push({ type: 'error', message: 'Failed to start sign-in — try again' });
- return;
+ const result = ProblemDetailsSchema.safeParse((await res.json()) as unknown);
+ if (result.success) message = result.data.title;
+ } catch {
+ /* keep generic message */
+ }
+ push({ type: 'error', message });
+ return;
+ }
+ if (!res.body) {
+ push({ type: 'error', message: 'Failed to start sign-in — try again' });
+ return;
+ }
+ const terminatedByEvent = await consumeAuthEventStream(
+ res.body,
+ (line): 'terminal' | 'continue' => {
+ // Narrow try/catch to JSON.parse only — event-processing errors
+ // propagate instead of being swallowed with malformed JSON lines.
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(line);
+ } catch {
+ // A stream of malformed lines would otherwise hang silently until
+ // completion. Surface the drop (bounded) for DevTools visibility.
+ console.warn('[auth-transport] Dropped unparseable NDJSON line:', line.slice(0, 100));
+ return 'continue';
}
- const terminatedByEvent = await consumeAuthEventStream(
- res.body,
- (line): 'terminal' | 'continue' => {
- // Narrow try/catch to JSON.parse only — event-processing
- // errors (e.g. push() throwing) propagate instead of being
- // silently swallowed alongside malformed JSON lines.
- let parsed: unknown;
- try {
- parsed = JSON.parse(line);
- } catch {
- // A corrupted stream of malformed JSON lines would otherwise
- // appear to hang silently until completion. Surface the drop
- // at warn level for DevTools / observability visibility, and
- // bound the slice so a giant garbled line doesn't dump the
- // entire payload into the console. Mirrors clone-transport.
- console.warn(
- '[auth-transport] Dropped unparseable NDJSON line:',
- line.slice(0, 100),
- );
- return 'continue'; // malformed JSON line
- }
- // Server wraps mid-stream errors in `StreamingProblemEvent`
- // shape (`{type:'error', problem: ProblemDetails}`). The
- // `AuthEvent` consumer union expects `{type:'error',
- // message: string}`. Bridge at the transport boundary so
- // consumers stay simple.
- if (
- parsed &&
- typeof parsed === 'object' &&
- (parsed as { type?: unknown }).type === 'error' &&
- 'problem' in parsed
- ) {
- const p = (parsed as { problem: { title?: string; detail?: string } }).problem;
- push({ type: 'error', message: p?.detail || p?.title || 'Unknown error' });
- return 'terminal';
- }
- const event = parsed as AuthEvent;
- push(event);
- if (event.type === 'complete' || event.type === 'error') return 'terminal';
- return 'continue';
- },
- );
- if (!terminatedByEvent && !signal.aborted) {
- push({
- type: 'error',
- message: 'Sign-in stream ended without confirmation — please try again',
- });
+ // Server wraps mid-stream errors as `{type:'error', problem}`; the
+ // consumer union expects `{type:'error', message}`. Bridge here.
+ if (
+ parsed &&
+ typeof parsed === 'object' &&
+ (parsed as { type?: unknown }).type === 'error' &&
+ 'problem' in parsed
+ ) {
+ const p = (parsed as { problem: { title?: string; detail?: string } }).problem;
+ push({ type: 'error', message: p?.detail || p?.title || 'Unknown error' });
+ return 'terminal';
}
- } catch (err) {
- if (err instanceof Error && err.name === 'AbortError') return;
- push({ type: 'error', message: 'Connection error — try again' });
- }
- })();
- });
+ const event = parsed as AuthEvent;
+ push(event);
+ if (event.type === 'complete' || event.type === 'error') return 'terminal';
+ return 'continue';
+ },
+ );
+ if (!terminatedByEvent && !signal.aborted) {
+ push({
+ type: 'error',
+ message: 'Sign-in stream ended without confirmation — please try again',
+ });
+ }
+ } catch (err) {
+ if (err instanceof Error && err.name === 'AbortError') return;
+ push({ type: 'error', message: 'Connection error — try again' });
+ }
+ })();
+ });
+}
+
+/**
+ * HTTP transport — the device flow (`start`) and gh sign-in (`ghLogin`) both
+ * stream via `streamAuthEndpoint`; `pat` is the one-shot token path.
+ */
+export function httpAuthTransport(): AuthTransport {
+ return {
+ start(): AuthTransportHandle {
+ return streamAuthEndpoint('/api/local-op/auth/login', { json: true });
+ },
+ ghLogin(host: string): AuthTransportHandle {
+ return streamAuthEndpoint('/api/local-op/auth/gh-login', { host, json: true });
+ },
+ async pat(host: string, token: string): Promise<PatResult> {
+ try {
+ const res = await fetch('/api/local-op/auth/pat', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ host, token }),
+ });
+ if (res.ok) {
+ const body = (await res.json()) as { login?: unknown };
+ return { ok: true, login: typeof body.login === 'string' ? body.login : '' };
+ }
+ // The relay returns RFC 9457 problem+json on a rejected token / TLS /
+ // network error; surface the bounded `detail` (the CLI's real reason).
+ let error = 'Failed to store the token — try again';
+ try {
+ const result = ProblemDetailsSchema.safeParse(await res.json());
+ if (result.success) error = result.data.detail || result.data.title;
+ } catch {
+ /* keep generic message */
+ }
+ return { ok: false, error };
+ } catch {
+ return { ok: false, error: 'Connection error — try again' };
+ }
},
};
}
diff --git a/packages/app/src/lib/use-settings-route.test.ts b/packages/app/src/lib/use-settings-route.test.ts
index 4830bac5e..305fd842c 100644
--- a/packages/app/src/lib/use-settings-route.test.ts
+++ b/packages/app/src/lib/use-settings-route.test.ts
@@ -48,6 +48,20 @@ describe('isSettingsHashOpen', () => {
expect(settingsHashSection('#settings/')).toBeNull();
expect(settingsHashSection('#settings')).toBeNull();
});
+
+ test('`#settings/account` (the trust-gate Connect target) → true', () => {
+ expect(isSettingsHashOpen('#settings/account')).toBe(true);
+ });
+});
+
+describe('settingsHashSection', () => {
+ test('`#settings/account` (the trust-gate Connect target) → "account"', () => {
+ expect(settingsHashSection('#settings/account')).toBe('account');
+ });
+
+ test('non-settings hash → null', () => {
+ expect(settingsHashSection('#/some-doc')).toBeNull();
+ });
});
describe('SETTINGS_OPEN_HASH', () => {
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 03fe1521d..15a5e884f 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -363,6 +363,7 @@
"6g2jsp": ["Update skill"],
"6gRgw8": ["Retry"],
"6h4zVU": ["What would you like to create?"],
+ "6hYjww": ["Create a token on ", ["host"]],
"6hfDJr": ["Server error: ", ["status"]],
"6iDEWA": ["Show panel"],
"6ibbCg": ["Create your first file"],
@@ -433,6 +434,7 @@
"8Gzz2G": ["worktree of ", ["worktreeOf"]],
"8IP5jY": ["Each selected tool gets an OpenKnowledge MCP entry."],
"8Jm2EP": ["Toggle heading levels 1 through 6."],
+ "8L0EPw": ["or paste a token"],
"8OGgNM": ["Open or close visual-editor find."],
"8OxKZy": ["Move succeeded but the sidebar may be out of date — refresh to resync"],
"8PifYj": ["Mermaid diagram"],
@@ -448,6 +450,7 @@
"8eW0WQ": ["No matching repositories."],
"8fRyLo": ["Invalid patch payload"],
"8fc_3j": ["Protected branch — cannot push"],
+ "8k6INX": ["Paste a personal access token for <0>", ["host"], "</0>."],
"8lwQlE": [["0"], " added, ", ["1"], " removed"],
"8m8diM": ["No location selected. Use Browse to choose a folder."],
"8nWu1k": ["Empty diagram"],
@@ -472,6 +475,7 @@
"9V0W-R": [
"Adds the OpenKnowledge skill to the <0>Claude Desktop App</0> so it's available in Chat and Cowork sessions."
],
+ "9Vh9Jf": ["Reopen this window to sign in with your browser"],
"9XIEYq": ["Attach the file in an email to <0/>"],
"9bCiQ8": ["No pages are missing incoming graph links."],
"9clcD5": ["Open documents tagged #", ["chip"]],
@@ -647,6 +651,7 @@
["shareBranch"],
"</0>. You have uncommitted changes that prevent switching here — open it in a worktree to leave your changes untouched."
],
+ "DUWgfT": ["Re-authenticate with GitHub Enterprise Server"],
"DVh_Tb": ["Failed to clean up after trash"],
"DXd9LM": ["New worktree"],
"D_WKe_": ["Click an agent's avatar in the presence bar to view their session."],
@@ -1158,6 +1163,7 @@
"NgZwB0": [["enabledCount"], "/", ["0"], " on"],
"NjrIak": ["File: <0>", ["fixedName"], ".md</0>"],
"NkXEFS": ["Restore failed — document unchanged"],
+ "Nm-3m-": ["Auto-sync is paused — you don't have permission to push to this repo."],
"NmPNJJ": ["Copy code"],
"Nn4GgW": ["Will be created as <0>", ["sanitizedName"], "</0>"],
"NnQapF": ["Open with AI ", ["targetDisplayName"]],
@@ -1586,6 +1592,7 @@
"Xet9MX": ["Failed to load backlinks"],
"Xewl6B": ["Your local copy is behind. Pull the latest changes, then open the link again."],
"XfzqjK": ["template \"", ["name"], "\""],
+ "Xg-Ntj": ["The token needs the repo and read:user scopes."],
"Xisk4u": ["Edited ", ["editedAgo"]],
"Xk0-VC": [
"Previews of links to other documents in this project are always on and read from the local index — nothing leaves your computer for those."
@@ -1729,6 +1736,7 @@
"_RcqUM": [
"You picked your home directory. OpenKnowledge will index everything in your home tree — large and may surface personal files."
],
+ "_SDGzH": ["Continue in browser"],
"_TDESN": ["Network error - ", ["kind"], " \"", ["createdPath"], "\" still exists on disk"],
"_TF8ep": ["Failed to render PDF"],
"_VRtd7": ["Couldn't send the selection — please try again."],
@@ -1852,6 +1860,7 @@
"cd5EXh": ["Report a bug"],
"cdm00A": ["No Incoming"],
"cdmk8A": ["Uncommitted changes"],
+ "cgl-gn": ["Connected to GitHub"],
"chL5IG": ["Community"],
"cklVjM": ["Timeline"],
"cn1sLi": ["Couldn't connect OpenKnowledge tools to Claude Code. Please try again."],
@@ -2053,6 +2062,7 @@
"hGmuTc": ["Docs tagged #", ["tagDocsName"]],
"hHMv6l": ["Delete block"],
"hItdtk": ["Browse folder"],
+ "hLKfZe": ["Use a token instead"],
"hLod4_": ["Convert to template"],
"hLy8b1": ["Updated to Version ", ["version"]],
"hQXiDc": ["Search branches..."],
@@ -2105,6 +2115,7 @@
"iIaSUD": ["Whitespace"],
"iKSP5j": ["Word wrap"],
"iKZkk1": ["Property value"],
+ "iMYFJM": ["This window can't store a token — open Settings from the main app window."],
"iMkWoF": ["Turn on"],
"iO8V-7": ["Create worktree"],
"iOHg1t": ["Open embedded URL in new tab"],
@@ -2177,6 +2188,7 @@
["trimmedSlug"],
"</0> already exists here. Saving creates a local copy that overrides it for this folder."
],
+ "jxtXZI": ["Install the gh CLI"],
"k0dL2I": ["Reconnecting to the agent service…"],
"k0vc0N": ["New terminal tab"],
"k2fEi7": [
@@ -2262,7 +2274,6 @@
["4"],
") that won't touch the rest of your system."
],
- "l8G3S9": ["Auto-sync is off — you don't have permission to push to this repo"],
"lAiyU_": ["Only the current document uses <0>#", ["tag"], "</0>."],
"lCC_D5": ["Subscribing..."],
"lGs_bQ": ["Page <0>*</0>"],
@@ -2473,6 +2484,7 @@
"\" could not be cleared. Reload to retry."
],
"p0Iq25": ["Insert link"],
+ "p2LEhJ": ["Personal access token"],
"p8TjFD": ["Collapse session dock"],
"p9sdCy": ["New ignore pattern"],
"pAgkuZ": ["Reopening \"", ["docName"], "\" with a fresh local collaboration cache."],
@@ -2523,6 +2535,7 @@
"qSKu2v": ["Source navigation and selection"],
"qSxaOz": ["Accept their deletion"],
"qUB_o_": ["Auto-sync is off — your edits stay local until you commit and push manually."],
+ "qX-ABr": ["Or to use browser sign-in instead:"],
"qXN416": ["Couldn't share skills: internal error. Please restart the app."],
"qXg5W9": ["File saves to <0>~/Downloads/openknowledge.skill</0>."],
"qXsafh": ["Publish to GitHub"],
@@ -2607,6 +2620,7 @@
"sIxSSP": ["Resolve conflict in your terminal"],
"sJK6pq": ["Permission denied"],
"sJWhgo": ["Unknown component: ", ["unregisteredComponentName"]],
+ "sNeKjP": ["Failed to store the token — try again"],
"sOxZaS": ["Failed to load graph"],
"sZ2IOu": [
"This ",
@@ -2665,9 +2679,11 @@
"ti6aF_": ["Ask ", ["0"], " CLI"],
"tiWX6q": ["Source editor"],
"tjXez2": ["blog-post"],
+ "tnG-m6": ["Auto-sync is paused — sign in to resume."],
"toyw51": ["Mermaid diagram controls"],
"tsiTqO": ["Paste your API key"],
"tsyExA": ["Connect your AI tools to OpenKnowledge"],
+ "tzZ6ha": ["Connect to GitHub Enterprise Server"],
"u-9fWA": ["See <0>Architecture</0> for the system overview."],
"u3BOHd": [["fileCount", "plural", { "one": ["#", " file"], "other": ["#", " files"] }]],
"u3YnKw": ["Could not construct share URL."],
@@ -2873,6 +2889,7 @@
"y_5CE8": ["Item ", ["0"]],
"y_K0Dz": ["What happened?"],
"yaPGPa": ["Open a project to manage its AI tool connections."],
+ "ycIX5i": ["You're signed out — sign in to resume syncing."],
"yf5auF": ["Search rules by id, alias, or name"],
"yf5r22": [
["keyName"],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index fd15a1907..5de378edd 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -1213,10 +1213,6 @@ msgstr "Auto-denied"
msgid "Auto-save"
msgstr "Auto-save"
-#: src/components/settings/SettingsDialogBody.tsx
-msgid "Auto-sync is off — you don't have permission to push to this repo"
-msgstr "Auto-sync is off — you don't have permission to push to this repo"
-
#: src/components/settings/SettingsDialogBody.tsx
msgid "Auto-sync is off — your edits stay local until you commit and push manually."
msgstr "Auto-sync is off — your edits stay local until you commit and push manually."
@@ -1233,6 +1229,14 @@ msgstr "Auto-sync is on — your commits push and remote changes pull on interva
msgid "Auto-sync is on for this worktree, inherited from {project}. Change it in Settings → Sync."
msgstr "Auto-sync is on for this worktree, inherited from {project}. Change it in Settings → Sync."
+#: src/components/settings/SettingsDialogBody.tsx
+msgid "Auto-sync is paused — sign in to resume."
+msgstr "Auto-sync is paused — sign in to resume."
+
+#: src/components/settings/SettingsDialogBody.tsx
+msgid "Auto-sync is paused — you don't have permission to push to this repo."
+msgstr "Auto-sync is paused — you don't have permission to push to this repo."
+
#: src/components/AutoSyncEnableWarning.tsx
msgid "Auto-sync periodically fetches, pulls, and pushes commits to your remote git repository so your edits stay in sync across machines."
msgstr "Auto-sync periodically fetches, pulls, and pushes commits to your remote git repository so your edits stay in sync across machines."
@@ -1916,6 +1920,7 @@ msgid "Conflict"
msgstr "Conflict"
#. Primary button that writes MCP config for the selected AI tools
+#: src/components/AuthModal.tsx
#: src/components/McpConsentDialogBody.tsx
msgid "Connect"
msgstr "Connect"
@@ -1930,9 +1935,7 @@ msgstr "Connect an existing repository"
#: src/components/AuthModal.tsx
#: src/components/CloneDialog.tsx
-#: src/components/settings/AccountSection.tsx
#: src/components/ShareReceiveDialog.tsx
-#: src/components/SyncStatusBadge.tsx
msgid "Connect GitHub"
msgstr "Connect GitHub"
@@ -1962,6 +1965,10 @@ msgstr "Connect to AI tools"
msgid "Connect to GitHub"
msgstr "Connect to GitHub"
+#: src/components/AuthModal.tsx
+msgid "Connect to GitHub Enterprise Server"
+msgstr "Connect to GitHub Enterprise Server"
+
#: src/components/ClaudeReadinessBanner.tsx
msgid "Connect tools"
msgstr "Connect tools"
@@ -1983,6 +1990,11 @@ msgstr "Connected as <0>@{signedInLogin}</0>"
msgid "Connected to"
msgstr "Connected to"
+#: src/components/AuthModal.tsx
+msgid "Connected to GitHub"
+msgstr "Connected to GitHub"
+
+#: src/components/AuthModal.tsx
#: src/components/PropertyPanel.tsx
msgid "Connecting"
msgstr "Connecting"
@@ -2036,6 +2048,10 @@ msgstr "Context window:"
msgid "Context window: {percent}% used, {usedLabel} of {sizeLabel} tokens"
msgstr "Context window: {percent}% used, {usedLabel} of {sizeLabel} tokens"
+#: src/components/AuthModal.tsx
+msgid "Continue in browser"
+msgstr "Continue in browser"
+
#: src/components/FileTree.tsx
msgid "Convert"
msgstr "Convert"
@@ -2595,6 +2611,10 @@ msgstr "Create a new OpenKnowledge project in the folder of your choice."
msgid "Create a new spec file for my user story"
msgstr "Create a new spec file for my user story"
+#: src/components/AuthModal.tsx
+msgid "Create a token on {host}"
+msgstr "Create a token on {host}"
+
#: src/components/RecentProjectsMenu.tsx
msgid "Create a worktree from this branch"
msgstr "Create a worktree from this branch"
@@ -3716,6 +3736,10 @@ msgstr "Failed to save content rules — {0}"
msgid "Failed to save theme setting"
msgstr "Failed to save theme setting"
+#: src/components/AuthModal.tsx
+msgid "Failed to store the token — try again"
+msgstr "Failed to store the token — try again"
+
#: src/components/settings/SettingsDialogBody.tsx
msgid "Failed to update attachment location — {detail}"
msgstr "Failed to update attachment location — {detail}"
@@ -4546,6 +4570,10 @@ msgstr "Install on all"
msgid "Install skills into"
msgstr "Install skills into"
+#: src/components/AuthModal.tsx
+msgid "Install the gh CLI"
+msgstr "Install the gh CLI"
+
#: src/components/settings/AiToolsSection.tsx
#: src/components/settings/ProjectAiToolsSection.tsx
#: src/components/SkillEditorActions.tsx
@@ -6117,6 +6145,14 @@ msgstr "Opens in a new tab"
msgid "or create a new file <0/>"
msgstr "or create a new file <0/>"
+#: src/components/AuthModal.tsx
+msgid "or paste a token"
+msgstr "or paste a token"
+
+#: src/components/AuthModal.tsx
+msgid "Or to use browser sign-in instead:"
+msgstr "Or to use browser sign-in instead:"
+
#: src/components/EmptyEditorState.tsx
msgid "Or use a starter pack"
msgstr "Or use a starter pack"
@@ -6240,6 +6276,10 @@ msgstr "Paragraph"
msgid "Parse failed"
msgstr "Parse failed"
+#: src/components/AuthModal.tsx
+msgid "Paste a personal access token for <0>{host}</0>."
+msgstr "Paste a personal access token for <0>{host}</0>."
+
#: src/lib/keyboard-shortcuts.ts
msgid "Paste duplicate"
msgstr "Paste duplicate"
@@ -6320,6 +6360,10 @@ msgstr "Permanently deletes <0>{targetGitPath}</0> and all its git history. Work
msgid "Permission denied"
msgstr "Permission denied"
+#: src/components/AuthModal.tsx
+msgid "Personal access token"
+msgstr "Personal access token"
+
#: src/components/settings/ScopeBadge.tsx
msgid "Personal to this device — stored in your user config, not shared."
msgstr "Personal to this device — stored in your user config, not shared."
@@ -6602,6 +6646,10 @@ msgstr "Quote"
msgid "Re-authenticate with GitHub"
msgstr "Re-authenticate with GitHub"
+#: src/components/AuthModal.tsx
+msgid "Re-authenticate with GitHub Enterprise Server"
+msgstr "Re-authenticate with GitHub Enterprise Server"
+
#: src/components/empty-state/use-create-suggestions.ts
msgid "Read through this codebase and draft a technical spec for the most complex module: an overview, the architecture, key files, and open questions, all linked from a specs index page."
msgstr "Read through this codebase and draft a technical spec for the most complex module: an overview, the architecture, key files, and open questions, all linked from a specs index page."
@@ -6853,6 +6901,10 @@ msgstr "Reopen closed tab"
msgid "Reopen the most recently closed editor tab."
msgstr "Reopen the most recently closed editor tab."
+#: src/components/AuthModal.tsx
+msgid "Reopen this window to sign in with your browser"
+msgstr "Reopen this window to sign in with your browser"
+
#: src/components/EditorActivityPool.tsx
msgid "Reopening \"{docName}\" with a fresh local collaboration cache."
msgstr "Reopening \"{docName}\" with a fresh local collaboration cache."
@@ -7742,6 +7794,7 @@ msgstr "Showing top matches — keep typing to narrow"
msgid "Shows above the code body. Round-trips as `title=\"...\"` in markdown."
msgstr "Shows above the code body. Round-trips as `title=\"...\"` in markdown."
+#: src/components/settings/AccountSection.tsx
#: src/components/settings/SettingsDialogBody.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Sign in"
@@ -8448,6 +8501,10 @@ msgstr "The terminal session ended."
msgid "The terminal stopped unexpectedly."
msgstr "The terminal stopped unexpectedly."
+#: src/components/AuthModal.tsx
+msgid "The token needs the repo and read:user scopes."
+msgstr "The token needs the repo and read:user scopes."
+
#: src/components/settings/settings-fields.ts
msgid "Theme"
msgstr "Theme"
@@ -8696,6 +8753,10 @@ msgstr "This template lives in a parent folder — deleting it affects every fol
msgid "This usually means one of:"
msgstr "This usually means one of:"
+#: src/components/AuthModal.tsx
+msgid "This window can't store a token — open Settings from the main app window."
+msgstr "This window can't store a token — open Settings from the main app window."
+
#: src/components/DocPanel.tsx
#: src/components/TimelinePanel.tsx
msgid "Timeline"
@@ -9066,6 +9127,10 @@ msgstr "Use a folder you already have."
msgid "Use a starter pack"
msgstr "Use a starter pack"
+#: src/components/AuthModal.tsx
+msgid "Use a token instead"
+msgstr "Use a token instead"
+
#: src/components/settings/SearchSection.tsx
msgid "Use an https:// URL — http:// is only allowed for localhost."
msgstr "Use an https:// URL — http:// is only allowed for localhost."
@@ -9439,6 +9504,10 @@ msgstr "You picked your home directory. OpenKnowledge will index everything in y
msgid "You're all set up!"
msgstr "You're all set up!"
+#: src/components/SyncStatusBadge.tsx
+msgid "You're signed out — sign in to resume syncing."
+msgstr "You're signed out — sign in to resume syncing."
+
#: src/components/SubscribeForm.tsx
msgid "You're subscribed!"
msgstr "You're subscribed!"
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index dae1369b8..99a2fef53 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -363,6 +363,7 @@
"6g2jsp": ["Ũƥďàţē śķĩĺĺ"],
"6gRgw8": ["Ŕēţŕŷ"],
"6h4zVU": ["Ŵĥàţ ŵōũĺď ŷōũ ĺĩķē ţō ćŕēàţē?"],
+ "6hYjww": ["Ćŕēàţē à ţōķēń ōń ", ["host"]],
"6hfDJr": ["Śēŕvēŕ ēŕŕōŕ: ", ["status"]],
"6iDEWA": ["Śĥōŵ ƥàńēĺ"],
"6ibbCg": ["Ćŕēàţē ŷōũŕ ƒĩŕśţ ƒĩĺē"],
@@ -433,6 +434,7 @@
"8Gzz2G": ["ŵōŕķţŕēē ōƒ ", ["worktreeOf"]],
"8IP5jY": ["Ēàćĥ śēĺēćţēď ţōōĺ ĝēţś àń ŌƥēńĶńōŵĺēďĝē ḾĆƤ ēńţŕŷ."],
"8Jm2EP": ["Ţōĝĝĺē ĥēàďĩńĝ ĺēvēĺś 1 ţĥŕōũĝĥ 6."],
+ "8L0EPw": ["ōŕ ƥàśţē à ţōķēń"],
"8OGgNM": ["Ōƥēń ōŕ ćĺōśē vĩśũàĺ-ēďĩţōŕ ƒĩńď."],
"8OxKZy": ["Ḿōvē śũććēēďēď ƀũţ ţĥē śĩďēƀàŕ ḿàŷ ƀē ōũţ ōƒ ďàţē — ŕēƒŕēśĥ ţō ŕēśŷńć"],
"8PifYj": ["Ḿēŕḿàĩď ďĩàĝŕàḿ"],
@@ -448,6 +450,7 @@
"8eW0WQ": ["Ńō ḿàţćĥĩńĝ ŕēƥōśĩţōŕĩēś."],
"8fRyLo": ["Ĩńvàĺĩď ƥàţćĥ ƥàŷĺōàď"],
"8fc_3j": ["Ƥŕōţēćţēď ƀŕàńćĥ — ćàńńōţ ƥũśĥ"],
+ "8k6INX": ["Ƥàśţē à ƥēŕśōńàĺ àććēśś ţōķēń ƒōŕ <0>", ["host"], "</0>."],
"8lwQlE": [["0"], " àďďēď, ", ["1"], " ŕēḿōvēď"],
"8m8diM": ["Ńō ĺōćàţĩōń śēĺēćţēď. Ũśē ßŕōŵśē ţō ćĥōōśē à ƒōĺďēŕ."],
"8nWu1k": ["Ēḿƥţŷ ďĩàĝŕàḿ"],
@@ -472,6 +475,7 @@
"9V0W-R": [
"Àďďś ţĥē ŌƥēńĶńōŵĺēďĝē śķĩĺĺ ţō ţĥē <0>Ćĺàũďē Ďēśķţōƥ Àƥƥ</0> śō ĩţ'ś àvàĩĺàƀĺē ĩń Ćĥàţ àńď Ćōŵōŕķ śēśśĩōńś."
],
+ "9Vh9Jf": ["Ŕēōƥēń ţĥĩś ŵĩńďōŵ ţō śĩĝń ĩń ŵĩţĥ ŷōũŕ ƀŕōŵśēŕ"],
"9XIEYq": ["Àţţàćĥ ţĥē ƒĩĺē ĩń àń ēḿàĩĺ ţō <0/>"],
"9bCiQ8": ["Ńō ƥàĝēś àŕē ḿĩśśĩńĝ ĩńćōḿĩńĝ ĝŕàƥĥ ĺĩńķś."],
"9clcD5": ["Ōƥēń ďōćũḿēńţś ţàĝĝēď #", ["chip"]],
@@ -647,6 +651,7 @@
["shareBranch"],
"</0>. Ŷōũ ĥàvē ũńćōḿḿĩţţēď ćĥàńĝēś ţĥàţ ƥŕēvēńţ śŵĩţćĥĩńĝ ĥēŕē — ōƥēń ĩţ ĩń à ŵōŕķţŕēē ţō ĺēàvē ŷōũŕ ćĥàńĝēś ũńţōũćĥēď."
],
+ "DUWgfT": ["Ŕē-àũţĥēńţĩćàţē ŵĩţĥ ĜĩţĤũƀ Ēńţēŕƥŕĩśē Śēŕvēŕ"],
"DVh_Tb": ["Ƒàĩĺēď ţō ćĺēàń ũƥ àƒţēŕ ţŕàśĥ"],
"DXd9LM": ["Ńēŵ ŵōŕķţŕēē"],
"D_WKe_": ["Ćĺĩćķ àń àĝēńţ'ś àvàţàŕ ĩń ţĥē ƥŕēśēńćē ƀàŕ ţō vĩēŵ ţĥēĩŕ śēśśĩōń."],
@@ -1158,6 +1163,7 @@
"NgZwB0": [["enabledCount"], "/", ["0"], " ōń"],
"NjrIak": ["Ƒĩĺē: <0>", ["fixedName"], ".ḿď</0>"],
"NkXEFS": ["Ŕēśţōŕē ƒàĩĺēď — ďōćũḿēńţ ũńćĥàńĝēď"],
+ "Nm-3m-": ["Àũţō-śŷńć ĩś ƥàũśēď — ŷōũ ďōń'ţ ĥàvē ƥēŕḿĩśśĩōń ţō ƥũśĥ ţō ţĥĩś ŕēƥō."],
"NmPNJJ": ["Ćōƥŷ ćōďē"],
"Nn4GgW": ["Ŵĩĺĺ ƀē ćŕēàţēď àś <0>", ["sanitizedName"], "</0>"],
"NnQapF": ["Ōƥēń ŵĩţĥ ÀĨ ", ["targetDisplayName"]],
@@ -1586,6 +1592,7 @@
"Xet9MX": ["Ƒàĩĺēď ţō ĺōàď ƀàćķĺĩńķś"],
"Xewl6B": ["Ŷōũŕ ĺōćàĺ ćōƥŷ ĩś ƀēĥĩńď. Ƥũĺĺ ţĥē ĺàţēśţ ćĥàńĝēś, ţĥēń ōƥēń ţĥē ĺĩńķ àĝàĩń."],
"XfzqjK": ["ţēḿƥĺàţē \"", ["name"], "\""],
+ "Xg-Ntj": ["Ţĥē ţōķēń ńēēďś ţĥē ŕēƥō àńď ŕēàď:ũśēŕ śćōƥēś."],
"Xisk4u": ["Ēďĩţēď ", ["editedAgo"]],
"Xk0-VC": [
"Ƥŕēvĩēŵś ōƒ ĺĩńķś ţō ōţĥēŕ ďōćũḿēńţś ĩń ţĥĩś ƥŕōĴēćţ àŕē àĺŵàŷś ōń àńď ŕēàď ƒŕōḿ ţĥē ĺōćàĺ ĩńďēx — ńōţĥĩńĝ ĺēàvēś ŷōũŕ ćōḿƥũţēŕ ƒōŕ ţĥōśē."
@@ -1729,6 +1736,7 @@
"_RcqUM": [
"Ŷōũ ƥĩćķēď ŷōũŕ ĥōḿē ďĩŕēćţōŕŷ. ŌƥēńĶńōŵĺēďĝē ŵĩĺĺ ĩńďēx ēvēŕŷţĥĩńĝ ĩń ŷōũŕ ĥōḿē ţŕēē — ĺàŕĝē àńď ḿàŷ śũŕƒàćē ƥēŕśōńàĺ ƒĩĺēś."
],
+ "_SDGzH": ["Ćōńţĩńũē ĩń ƀŕōŵśēŕ"],
"_TDESN": ["Ńēţŵōŕķ ēŕŕōŕ - ", ["kind"], " \"", ["createdPath"], "\" śţĩĺĺ ēxĩśţś ōń ďĩśķ"],
"_TF8ep": ["Ƒàĩĺēď ţō ŕēńďēŕ ƤĎƑ"],
"_VRtd7": ["Ćōũĺďń'ţ śēńď ţĥē śēĺēćţĩōń — ƥĺēàśē ţŕŷ àĝàĩń."],
@@ -1852,6 +1860,7 @@
"cd5EXh": ["Ŕēƥōŕţ à ƀũĝ"],
"cdm00A": ["Ńō Ĩńćōḿĩńĝ"],
"cdmk8A": ["Ũńćōḿḿĩţţēď ćĥàńĝēś"],
+ "cgl-gn": ["Ćōńńēćţēď ţō ĜĩţĤũƀ"],
"chL5IG": ["Ćōḿḿũńĩţŷ"],
"cklVjM": ["Ţĩḿēĺĩńē"],
"cn1sLi": ["Ćōũĺďń'ţ ćōńńēćţ ŌƥēńĶńōŵĺēďĝē ţōōĺś ţō Ćĺàũďē Ćōďē. Ƥĺēàśē ţŕŷ àĝàĩń."],
@@ -2053,6 +2062,7 @@
"hGmuTc": ["Ďōćś ţàĝĝēď #", ["tagDocsName"]],
"hHMv6l": ["Ďēĺēţē ƀĺōćķ"],
"hItdtk": ["ßŕōŵśē ƒōĺďēŕ"],
+ "hLKfZe": ["Ũśē à ţōķēń ĩńśţēàď"],
"hLod4_": ["Ćōńvēŕţ ţō ţēḿƥĺàţē"],
"hLy8b1": ["Ũƥďàţēď ţō Vēŕśĩōń ", ["version"]],
"hQXiDc": ["Śēàŕćĥ ƀŕàńćĥēś..."],
@@ -2105,6 +2115,7 @@
"iIaSUD": ["Ŵĥĩţēśƥàćē"],
"iKSP5j": ["Ŵōŕď ŵŕàƥ"],
"iKZkk1": ["Ƥŕōƥēŕţŷ vàĺũē"],
+ "iMYFJM": ["Ţĥĩś ŵĩńďōŵ ćàń'ţ śţōŕē à ţōķēń — ōƥēń Śēţţĩńĝś ƒŕōḿ ţĥē ḿàĩń àƥƥ ŵĩńďōŵ."],
"iMkWoF": ["Ţũŕń ōń"],
"iO8V-7": ["Ćŕēàţē ŵōŕķţŕēē"],
"iOHg1t": ["Ōƥēń ēḿƀēďďēď ŨŔĹ ĩń ńēŵ ţàƀ"],
@@ -2177,6 +2188,7 @@
["trimmedSlug"],
"</0> àĺŕēàďŷ ēxĩśţś ĥēŕē. Śàvĩńĝ ćŕēàţēś à ĺōćàĺ ćōƥŷ ţĥàţ ōvēŕŕĩďēś ĩţ ƒōŕ ţĥĩś ƒōĺďēŕ."
],
+ "jxtXZI": ["Ĩńśţàĺĺ ţĥē ĝĥ ĆĹĨ"],
"k0dL2I": ["Ŕēćōńńēćţĩńĝ ţō ţĥē àĝēńţ śēŕvĩćē…"],
"k0vc0N": ["Ńēŵ ţēŕḿĩńàĺ ţàƀ"],
"k2fEi7": [
@@ -2262,7 +2274,6 @@
["4"],
") ţĥàţ ŵōń'ţ ţōũćĥ ţĥē ŕēśţ ōƒ ŷōũŕ śŷśţēḿ."
],
- "l8G3S9": ["Àũţō-śŷńć ĩś ōƒƒ — ŷōũ ďōń'ţ ĥàvē ƥēŕḿĩśśĩōń ţō ƥũśĥ ţō ţĥĩś ŕēƥō"],
"lAiyU_": ["Ōńĺŷ ţĥē ćũŕŕēńţ ďōćũḿēńţ ũśēś <0>#", ["tag"], "</0>."],
"lCC_D5": ["Śũƀśćŕĩƀĩńĝ..."],
"lGs_bQ": ["Ƥàĝē <0>*</0>"],
@@ -2473,6 +2484,7 @@
"\" ćōũĺď ńōţ ƀē ćĺēàŕēď. Ŕēĺōàď ţō ŕēţŕŷ."
],
"p0Iq25": ["Ĩńśēŕţ ĺĩńķ"],
+ "p2LEhJ": ["Ƥēŕśōńàĺ àććēśś ţōķēń"],
"p8TjFD": ["Ćōĺĺàƥśē śēśśĩōń ďōćķ"],
"p9sdCy": ["Ńēŵ ĩĝńōŕē ƥàţţēŕń"],
"pAgkuZ": ["Ŕēōƥēńĩńĝ \"", ["docName"], "\" ŵĩţĥ à ƒŕēśĥ ĺōćàĺ ćōĺĺàƀōŕàţĩōń ćàćĥē."],
@@ -2523,6 +2535,7 @@
"qSKu2v": ["Śōũŕćē ńàvĩĝàţĩōń àńď śēĺēćţĩōń"],
"qSxaOz": ["Àććēƥţ ţĥēĩŕ ďēĺēţĩōń"],
"qUB_o_": ["Àũţō-śŷńć ĩś ōƒƒ — ŷōũŕ ēďĩţś śţàŷ ĺōćàĺ ũńţĩĺ ŷōũ ćōḿḿĩţ àńď ƥũśĥ ḿàńũàĺĺŷ."],
+ "qX-ABr": ["Ōŕ ţō ũśē ƀŕōŵśēŕ śĩĝń-ĩń ĩńśţēàď:"],
"qXN416": ["Ćōũĺďń'ţ śĥàŕē śķĩĺĺś: ĩńţēŕńàĺ ēŕŕōŕ. Ƥĺēàśē ŕēśţàŕţ ţĥē àƥƥ."],
"qXg5W9": ["Ƒĩĺē śàvēś ţō <0>~/Ďōŵńĺōàďś/ōƥēńķńōŵĺēďĝē.śķĩĺĺ</0>."],
"qXsafh": ["Ƥũƀĺĩśĥ ţō ĜĩţĤũƀ"],
@@ -2607,6 +2620,7 @@
"sIxSSP": ["Ŕēśōĺvē ćōńƒĺĩćţ ĩń ŷōũŕ ţēŕḿĩńàĺ"],
"sJK6pq": ["Ƥēŕḿĩśśĩōń ďēńĩēď"],
"sJWhgo": ["Ũńķńōŵń ćōḿƥōńēńţ: ", ["unregisteredComponentName"]],
+ "sNeKjP": ["Ƒàĩĺēď ţō śţōŕē ţĥē ţōķēń — ţŕŷ àĝàĩń"],
"sOxZaS": ["Ƒàĩĺēď ţō ĺōàď ĝŕàƥĥ"],
"sZ2IOu": [
"Ţĥĩś ",
@@ -2665,9 +2679,11 @@
"ti6aF_": ["Àśķ ", ["0"], " ĆĹĨ"],
"tiWX6q": ["Śōũŕćē ēďĩţōŕ"],
"tjXez2": ["ƀĺōĝ-ƥōśţ"],
+ "tnG-m6": ["Àũţō-śŷńć ĩś ƥàũśēď — śĩĝń ĩń ţō ŕēśũḿē."],
"toyw51": ["Ḿēŕḿàĩď ďĩàĝŕàḿ ćōńţŕōĺś"],
"tsiTqO": ["Ƥàśţē ŷōũŕ ÀƤĨ ķēŷ"],
"tsyExA": ["Ćōńńēćţ ŷōũŕ ÀĨ ţōōĺś ţō ŌƥēńĶńōŵĺēďĝē"],
+ "tzZ6ha": ["Ćōńńēćţ ţō ĜĩţĤũƀ Ēńţēŕƥŕĩśē Śēŕvēŕ"],
"u-9fWA": ["Śēē <0>Àŕćĥĩţēćţũŕē</0> ƒōŕ ţĥē śŷśţēḿ ōvēŕvĩēŵ."],
"u3BOHd": [["fileCount", "plural", { "one": ["#", " ƒĩĺē"], "other": ["#", " ƒĩĺēś"] }]],
"u3YnKw": ["Ćōũĺď ńōţ ćōńśţŕũćţ śĥàŕē ŨŔĹ."],
@@ -2873,6 +2889,7 @@
"y_5CE8": ["Ĩţēḿ ", ["0"]],
"y_K0Dz": ["Ŵĥàţ ĥàƥƥēńēď?"],
"yaPGPa": ["Ōƥēń à ƥŕōĴēćţ ţō ḿàńàĝē ĩţś ÀĨ ţōōĺ ćōńńēćţĩōńś."],
+ "ycIX5i": ["Ŷōũ'ŕē śĩĝńēď ōũţ — śĩĝń ĩń ţō ŕēśũḿē śŷńćĩńĝ."],
"yf5auF": ["Śēàŕćĥ ŕũĺēś ƀŷ ĩď, àĺĩàś, ōŕ ńàḿē"],
"yf5r22": [
["keyName"],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index 050f02889..2325c1bdf 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -1209,10 +1209,6 @@ msgstr ""
msgid "Auto-save"
msgstr ""
-#: src/components/settings/SettingsDialogBody.tsx
-msgid "Auto-sync is off — you don't have permission to push to this repo"
-msgstr ""
-
#: src/components/settings/SettingsDialogBody.tsx
msgid "Auto-sync is off — your edits stay local until you commit and push manually."
msgstr ""
@@ -1229,6 +1225,14 @@ msgstr ""
msgid "Auto-sync is on for this worktree, inherited from {project}. Change it in Settings → Sync."
msgstr ""
+#: src/components/settings/SettingsDialogBody.tsx
+msgid "Auto-sync is paused — sign in to resume."
+msgstr ""
+
+#: src/components/settings/SettingsDialogBody.tsx
+msgid "Auto-sync is paused — you don't have permission to push to this repo."
+msgstr ""
+
#: src/components/AutoSyncEnableWarning.tsx
msgid "Auto-sync periodically fetches, pulls, and pushes commits to your remote git repository so your edits stay in sync across machines."
msgstr ""
@@ -1912,6 +1916,7 @@ msgid "Conflict"
msgstr ""
#. Primary button that writes MCP config for the selected AI tools
+#: src/components/AuthModal.tsx
#: src/components/McpConsentDialogBody.tsx
msgid "Connect"
msgstr ""
@@ -1926,9 +1931,7 @@ msgstr ""
#: src/components/AuthModal.tsx
#: src/components/CloneDialog.tsx
-#: src/components/settings/AccountSection.tsx
#: src/components/ShareReceiveDialog.tsx
-#: src/components/SyncStatusBadge.tsx
msgid "Connect GitHub"
msgstr ""
@@ -1958,6 +1961,10 @@ msgstr ""
msgid "Connect to GitHub"
msgstr ""
+#: src/components/AuthModal.tsx
+msgid "Connect to GitHub Enterprise Server"
+msgstr ""
+
#: src/components/ClaudeReadinessBanner.tsx
msgid "Connect tools"
msgstr ""
@@ -1979,6 +1986,11 @@ msgstr ""
msgid "Connected to"
msgstr ""
+#: src/components/AuthModal.tsx
+msgid "Connected to GitHub"
+msgstr ""
+
+#: src/components/AuthModal.tsx
#: src/components/PropertyPanel.tsx
msgid "Connecting"
msgstr ""
@@ -2032,6 +2044,10 @@ msgstr ""
msgid "Context window: {percent}% used, {usedLabel} of {sizeLabel} tokens"
msgstr ""
+#: src/components/AuthModal.tsx
+msgid "Continue in browser"
+msgstr ""
+
#: src/components/FileTree.tsx
msgid "Convert"
msgstr ""
@@ -2591,6 +2607,10 @@ msgstr ""
msgid "Create a new spec file for my user story"
msgstr ""
+#: src/components/AuthModal.tsx
+msgid "Create a token on {host}"
+msgstr ""
+
#: src/components/RecentProjectsMenu.tsx
msgid "Create a worktree from this branch"
msgstr ""
@@ -3712,6 +3732,10 @@ msgstr ""
msgid "Failed to save theme setting"
msgstr ""
+#: src/components/AuthModal.tsx
+msgid "Failed to store the token — try again"
+msgstr ""
+
#: src/components/settings/SettingsDialogBody.tsx
msgid "Failed to update attachment location — {detail}"
msgstr ""
@@ -4542,6 +4566,10 @@ msgstr ""
msgid "Install skills into"
msgstr ""
+#: src/components/AuthModal.tsx
+msgid "Install the gh CLI"
+msgstr ""
+
#: src/components/settings/AiToolsSection.tsx
#: src/components/settings/ProjectAiToolsSection.tsx
#: src/components/SkillEditorActions.tsx
@@ -6113,6 +6141,14 @@ msgstr ""
msgid "or create a new file <0/>"
msgstr ""
+#: src/components/AuthModal.tsx
+msgid "or paste a token"
+msgstr ""
+
+#: src/components/AuthModal.tsx
+msgid "Or to use browser sign-in instead:"
+msgstr ""
+
#: src/components/EmptyEditorState.tsx
msgid "Or use a starter pack"
msgstr ""
@@ -6236,6 +6272,10 @@ msgstr ""
msgid "Parse failed"
msgstr ""
+#: src/components/AuthModal.tsx
+msgid "Paste a personal access token for <0>{host}</0>."
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Paste duplicate"
msgstr ""
@@ -6316,6 +6356,10 @@ msgstr ""
msgid "Permission denied"
msgstr ""
+#: src/components/AuthModal.tsx
+msgid "Personal access token"
+msgstr ""
+
#: src/components/settings/ScopeBadge.tsx
msgid "Personal to this device — stored in your user config, not shared."
msgstr ""
@@ -6598,6 +6642,10 @@ msgstr ""
msgid "Re-authenticate with GitHub"
msgstr ""
+#: src/components/AuthModal.tsx
+msgid "Re-authenticate with GitHub Enterprise Server"
+msgstr ""
+
#: src/components/empty-state/use-create-suggestions.ts
msgid "Read through this codebase and draft a technical spec for the most complex module: an overview, the architecture, key files, and open questions, all linked from a specs index page."
msgstr ""
@@ -6849,6 +6897,10 @@ msgstr ""
msgid "Reopen the most recently closed editor tab."
msgstr ""
+#: src/components/AuthModal.tsx
+msgid "Reopen this window to sign in with your browser"
+msgstr ""
+
#: src/components/EditorActivityPool.tsx
msgid "Reopening \"{docName}\" with a fresh local collaboration cache."
msgstr ""
@@ -7738,6 +7790,7 @@ msgstr ""
msgid "Shows above the code body. Round-trips as `title=\"...\"` in markdown."
msgstr ""
+#: src/components/settings/AccountSection.tsx
#: src/components/settings/SettingsDialogBody.tsx
#: src/components/SyncStatusBadge.tsx
msgid "Sign in"
@@ -8444,6 +8497,10 @@ msgstr ""
msgid "The terminal stopped unexpectedly."
msgstr ""
+#: src/components/AuthModal.tsx
+msgid "The token needs the repo and read:user scopes."
+msgstr ""
+
#: src/components/settings/settings-fields.ts
msgid "Theme"
msgstr ""
@@ -8692,6 +8749,10 @@ msgstr ""
msgid "This usually means one of:"
msgstr ""
+#: src/components/AuthModal.tsx
+msgid "This window can't store a token — open Settings from the main app window."
+msgstr ""
+
#: src/components/DocPanel.tsx
#: src/components/TimelinePanel.tsx
msgid "Timeline"
@@ -9062,6 +9123,10 @@ msgstr ""
msgid "Use a starter pack"
msgstr ""
+#: src/components/AuthModal.tsx
+msgid "Use a token instead"
+msgstr ""
+
#: src/components/settings/SearchSection.tsx
msgid "Use an https:// URL — http:// is only allowed for localhost."
msgstr ""
@@ -9435,6 +9500,10 @@ msgstr ""
msgid "You're all set up!"
msgstr ""
+#: src/components/SyncStatusBadge.tsx
+msgid "You're signed out — sign in to resume syncing."
+msgstr ""
+
#: src/components/SubscribeForm.tsx
msgid "You're subscribed!"
msgstr ""
diff --git a/packages/app/tests/integration/attribution-sweep-coverage.test.ts b/packages/app/tests/integration/attribution-sweep-coverage.test.ts
index 0d88db47c..7d1cf2681 100644
--- a/packages/app/tests/integration/attribution-sweep-coverage.test.ts
+++ b/packages/app/tests/integration/attribution-sweep-coverage.test.ts
@@ -216,6 +216,13 @@ const EXEMPT_HANDLERS = new Set([
'handleLocalOpAuthRepos',
'handleLocalOpAuthSignout',
'handleLocalOpAuthSetIdentity',
+ // POST /api/local-op/auth/pat + /api/local-op/auth/gh-login — GHES sign-in
+ // surfaces (validate + store a PAT; run `gh auth login --web` and stream its
+ // progress). Machine-local credential operations, not agent-authored content —
+ // same rationale as the sibling local-op auth handlers. No agent identity to
+ // thread.
+ 'handleLocalOpAuthPat',
+ 'handleLocalOpAuthGhLogin',
// POST /api/local-op/embeddings/{set-key,clear-key} — loopback-gated writes of
// the machine-global embeddings key to ~/.ok/secrets.yml. Operate on the local
// user's credential file, not agent-authored content — same rationale as the
diff --git a/packages/app/tests/integration/conflict-gate-coverage.test.ts b/packages/app/tests/integration/conflict-gate-coverage.test.ts
index 2ad0461cf..730f58868 100644
--- a/packages/app/tests/integration/conflict-gate-coverage.test.ts
+++ b/packages/app/tests/integration/conflict-gate-coverage.test.ts
@@ -171,6 +171,11 @@ const EXEMPT_HANDLERS = new Set([
'handleLocalOpAuthRepos',
'handleLocalOpAuthSignout',
'handleLocalOpAuthSetIdentity',
+ // GHES sign-in surfaces (PAT store; `gh auth login --web` stream) — credential
+ // operations on the user's machine, no Y.Doc target, so the per-doc conflict
+ // gate doesn't apply.
+ 'handleLocalOpAuthPat',
+ 'handleLocalOpAuthGhLogin',
// Loopback-gated writes of the machine-global embeddings key to the user's
// secrets file — no Y.Doc mutation, so the conflict-refusal gate doesn't apply.
'handleLocalOpEmbeddingsSetKey',
diff --git a/packages/app/tests/integration/error-envelope-coverage.test.ts b/packages/app/tests/integration/error-envelope-coverage.test.ts
index 9c21147ea..bddc1b785 100644
--- a/packages/app/tests/integration/error-envelope-coverage.test.ts
+++ b/packages/app/tests/integration/error-envelope-coverage.test.ts
@@ -16,9 +16,9 @@
* Failure mode: file:line + handler name + the offending pattern.
*/
-import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
const API_EXT_PATH = join(import.meta.dirname, '../../../server/src/api-extension.ts');
const source = readFileSync(API_EXT_PATH, 'utf8');
@@ -103,7 +103,16 @@ const INLINE_BARE_SUCCESS_RE = /\bjson\(\s*res\s*,\s*2[0-9]{2}\s*,/;
const NON_JSON_LITERAL_CT_RE =
/['"]Content-Type['"]\s*:\s*['"](?!application\/json['"])([^'"]+)['"]/;
const NON_JSON_VARIABLE_CT_RE = /['"]Content-Type['"]\s*:\s*[A-Za-z_$][\w$.]*\s*[,}]/;
+// (d) Delegation to the shared `streamAuthFlow(...)` emitter — the auth
+// sign-in handlers (`handleLocalOpAuthLogin`, `handleLocalOpAuthGhLogin`)
+// hand the response to a helper that owns the whole streaming lifecycle:
+// the `application/x-ndjson` writeHead, the RFC 9457 streaming error
+// envelope (`createStreamingErrorWriter`), and the 429
+// concurrent-operation `errorResponse(...)`. The handler body therefore
+// contains none of those emits itself; the helper is the emit surface.
+const STREAM_AUTH_DELEGATION_RE = /\bstreamAuthFlow\(\s*\{/;
function isNonJsonEmit(body: string): boolean {
+ if (STREAM_AUTH_DELEGATION_RE.test(body)) return true;
if (!/res\.writeHead\(/.test(body)) return false;
if (NON_JSON_LITERAL_CT_RE.test(body)) return true;
if (NON_JSON_VARIABLE_CT_RE.test(body) && /pipeline\(|res\.write\(/.test(body)) return true;
@@ -205,7 +214,10 @@ describe('error envelope coverage (FR17, D36 a) — fail-on-any-occurrence', ()
`${name}: contains inline json(res, 2xx, ...) — must use successResponse(...)`,
);
}
- if (!body.includes('errorResponse(')) {
+ if (!body.includes('errorResponse(') && !STREAM_AUTH_DELEGATION_RE.test(body)) {
+ // `streamAuthFlow` delegators: every error emit (429 concurrency
+ // envelope, RFC 9457 streaming errors) lives inside the shared helper,
+ // so the handler body legitimately contains no `errorResponse(` call.
failures.push(`${name}: missing errorResponse(...) usage`);
}
}
diff --git a/packages/cli/src/auth/describe-auth-error.test.ts b/packages/cli/src/auth/describe-auth-error.test.ts
new file mode 100644
index 000000000..98c6eb023
--- /dev/null
+++ b/packages/cli/src/auth/describe-auth-error.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, test } from 'vitest';
+import { describeAuthFailure } from './describe-auth-error.ts';
+
+describe('describeAuthFailure', () => {
+ test('a self-signed / untrusted TLS cert is reported as a cert problem, not a bad token', () => {
+ // undici surfaces TLS failures via err.cause.code
+ const err = { cause: { code: 'DEPTH_ZERO_SELF_SIGNED_CERT' } };
+ const failure = describeAuthFailure(err, 'ghes.acme.test');
+ expect(failure.kind).toBe('tls');
+ expect(failure.message).toContain('TLS certificate');
+ expect(failure.message).toContain('ghes.acme.test');
+ expect(failure.message).not.toContain('Token invalid');
+ });
+
+ test('other CERT_* codes are also classified as TLS', () => {
+ for (const code of ['UNABLE_TO_VERIFY_LEAF_SIGNATURE', 'SELF_SIGNED_CERT_IN_CHAIN']) {
+ expect(describeAuthFailure({ cause: { code } }, 'h').kind).toBe('tls');
+ }
+ });
+
+ test('a genuine 401 is reported as an invalid token', () => {
+ const failure = describeAuthFailure({ status: 401 }, 'github.com');
+ expect(failure.kind).toBe('token');
+ expect(failure.message).toBe('Token invalid for github.com');
+ });
+
+ test('a 403 is reported as a scope/SSO problem, not an invalid token', () => {
+ const failure = describeAuthFailure({ status: 403 }, 'ghes.acme.test');
+ expect(failure.kind).toBe('token');
+ expect(failure.message).toContain('scopes');
+ expect(failure.message).toContain('SSO');
+ expect(failure.message).not.toContain('invalid');
+ });
+
+ test('a non-cert network error names the code instead of blaming the token', () => {
+ const failure = describeAuthFailure({ cause: { code: 'ECONNREFUSED' } }, 'ghes.acme.test');
+ expect(failure.kind).toBe('network');
+ expect(failure.message).toContain('ECONNREFUSED');
+ expect(failure.message).not.toContain('Token invalid');
+ });
+
+ test('an unclassifiable error falls back to invalid-token (fail-safe default)', () => {
+ expect(describeAuthFailure(new Error('boom'), 'h').kind).toBe('token');
+ expect(describeAuthFailure(undefined, 'h').kind).toBe('token');
+ });
+});
diff --git a/packages/cli/src/auth/describe-auth-error.ts b/packages/cli/src/auth/describe-auth-error.ts
new file mode 100644
index 000000000..18a4a7444
--- /dev/null
+++ b/packages/cli/src/auth/describe-auth-error.ts
@@ -0,0 +1,63 @@
+/**
+ * Classify a failed GitHub API auth check so a TLS/certificate-trust failure
+ * isn't reported as an invalid token.
+ *
+ * A GitHub Enterprise Server on a self-signed or internal-CA certificate fails
+ * the TLS handshake in Node/undici (surfaced via `err.cause.code`, e.g.
+ * `DEPTH_ZERO_SELF_SIGNED_CERT`) even when the token is perfectly valid — `git`
+ * accepts the same host via the system trust store. The app launches Node with
+ * `--use-system-ca` so it trusts that same store; this classifier keeps the
+ * message honest for the cases where the CA still isn't trusted (a bare terminal
+ * `ok`, or a CA that was never added to the system store).
+ */
+type AuthFailureKind = 'token' | 'tls' | 'network';
+
+export interface AuthFailure {
+ readonly kind: AuthFailureKind;
+ readonly message: string;
+}
+
+function errorCode(err: unknown): string | undefined {
+ const cause = (err as { cause?: { code?: unknown } } | undefined)?.cause;
+ if (typeof cause?.code === 'string') return cause.code;
+ const code = (err as { code?: unknown } | undefined)?.code;
+ return typeof code === 'string' ? code : undefined;
+}
+
+/**
+ * Node/OpenSSL error-code fragments that mean "the TLS certificate chain
+ * couldn't be trusted" — covers self-signed certs (DEPTH_ZERO_SELF_SIGNED_CERT,
+ * SELF_SIGNED_CERT_IN_CHAIN), untrusted internal CAs (UNABLE_TO_VERIFY_LEAF_
+ * SIGNATURE, UNABLE_TO_GET_ISSUER_CERT), and expiry/altname (CERT_HAS_EXPIRED,
+ * ERR_TLS_CERT_ALTNAME_INVALID). Substring match so the family stays covered.
+ */
+const TLS_CODE_FRAGMENTS = ['CERT', 'SELF_SIGNED', 'SIGNATURE', 'ISSUER'];
+
+export function describeAuthFailure(err: unknown, host: string): AuthFailure {
+ const code = errorCode(err);
+ if (code && TLS_CODE_FRAGMENTS.some((f) => code.includes(f))) {
+ return {
+ kind: 'tls',
+ message:
+ `Could not verify the TLS certificate for ${host}. If this is a GitHub ` +
+ `Enterprise Server with a self-signed or internal-CA certificate, add its ` +
+ `CA to your system trust store (macOS Keychain).`,
+ };
+ }
+ const status = (err as { status?: unknown } | undefined)?.status;
+ if (status === 401) return { kind: 'token', message: `Token invalid for ${host}` };
+ if (status === 403) {
+ // The token authenticated but the request was refused — wrong scopes, or an
+ // organization SSO policy the token isn't authorized for. Calling this
+ // "invalid" sends the user to regenerate a token that would fail the same
+ // way; name the actual resolution path instead.
+ return {
+ kind: 'token',
+ message:
+ `Token rejected by ${host} — check that it has the repo and read:user ` +
+ `scopes, and that it is authorized for SSO if the organization requires it`,
+ };
+ }
+ if (code) return { kind: 'network', message: `Could not reach ${host} (${code})` };
+ return { kind: 'token', message: `Authentication failed for ${host}` };
+}
diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts
index 837318290..82d0be8bf 100644
--- a/packages/cli/src/cli.ts
+++ b/packages/cli/src/cli.ts
@@ -14,9 +14,14 @@ if (process.argv.includes('--no-color')) {
delete process.env.NO_COLOR;
}
+// Trust the OS certificate store before any TLS work: a GitHub Enterprise Server
+// on a self-signed or internal-CA cert (already trusted by git) must work for
+// the CLI's Node/undici API calls rather than failing as "Token invalid".
+trustSystemCertificates();
+
import { spawn } from 'node:child_process';
import { resolve } from 'node:path';
-import { type Config, ConfigSchema } from '@inkeep/open-knowledge-server';
+import { type Config, ConfigSchema, trustSystemCertificates } from '@inkeep/open-knowledge-server';
/**
* CLI entry point for @inkeep/open-knowledge.
*
diff --git a/packages/cli/src/commands/auth/pat.ts b/packages/cli/src/commands/auth/pat.ts
index b623f9bd7..c8c6b1529 100644
--- a/packages/cli/src/commands/auth/pat.ts
+++ b/packages/cli/src/commands/auth/pat.ts
@@ -2,6 +2,7 @@ import { originGitHubHost } from '@inkeep/open-knowledge-server';
import password from '@inquirer/password';
import { Octokit } from '@octokit/rest';
import { Command } from 'commander';
+import { describeAuthFailure } from '../../auth/describe-auth-error.ts';
import type { TokenStore } from '../../auth/token-store.ts';
import { validateGitHubHost } from './validate-host.ts';
@@ -10,6 +11,19 @@ interface PatOptions {
json: boolean;
}
+/**
+ * Read a token from stdin — the non-interactive path used when the desktop app
+ * (or any automation) drives `auth pat`. The parent writes the token to the
+ * child's stdin and closes it; we read to EOF and trim the trailing newline.
+ */
+async function readTokenFromStdin(): Promise<string> {
+ const chunks: Buffer[] = [];
+ for await (const chunk of process.stdin) {
+ chunks.push(chunk as Buffer);
+ }
+ return Buffer.concat(chunks).toString('utf8').trim();
+}
+
async function runPat(
opts: PatOptions,
tokenStore: TokenStore,
@@ -37,8 +51,15 @@ async function runPat(
login = data.login;
name = data.name ?? undefined;
email = data.email ?? undefined;
- } catch {
- process.stderr.write('Token validation failed\n');
+ } catch (err) {
+ const message = describeAuthFailure(err, host).message;
+ if (json) {
+ // Bounded, structured error so the relay/UI can show the real cause
+ // (bad token vs. cert vs. network) without leaking paths from raw stderr.
+ process.stdout.write(`${JSON.stringify({ type: 'error', message })}\n`);
+ } else {
+ process.stderr.write(`${message}\n`);
+ }
process.exit(1);
}
@@ -59,8 +80,10 @@ export function patCommand(getTokenStore: () => Promise<TokenStore>): Command {
'GitHub or GitHub Enterprise hostname (default: workspace origin host)',
)
.option('--json', 'Output JSON', false)
- .action(async (opts: Omit<PatOptions, 'host'> & { host?: string }) => {
+ .option('--token-stdin', 'Read the token from stdin instead of prompting', false)
+ .action(async (opts: Omit<PatOptions, 'host'> & { host?: string; tokenStdin?: boolean }) => {
const host = opts.host ?? originGitHubHost(process.cwd());
- await runPat({ ...opts, host }, await getTokenStore());
+ const readToken = opts.tokenStdin ? readTokenFromStdin : undefined;
+ await runPat({ host, json: opts.json }, await getTokenStore(), readToken);
});
}
diff --git a/packages/cli/src/commands/auth/status.ts b/packages/cli/src/commands/auth/status.ts
index 802be2b82..efb8bc5a2 100644
--- a/packages/cli/src/commands/auth/status.ts
+++ b/packages/cli/src/commands/auth/status.ts
@@ -1,6 +1,7 @@
import { originGitHubHost } from '@inkeep/open-knowledge-server';
import { Octokit } from '@octokit/rest';
import { Command } from 'commander';
+import { describeAuthFailure } from '../../auth/describe-auth-error.ts';
import { detectGh } from '../../auth/gh-detect.ts';
import type { TokenStore } from '../../auth/token-store.ts';
import { validateGitHubHost } from './validate-host.ts';
@@ -97,15 +98,16 @@ async function runStatus(opts: StatusOptions, tokenStore: TokenStore): Promise<v
} else {
process.stderr.write(`✓ Logged in as ${data.login} on ${host}\n`);
}
- } catch {
+ } catch (err) {
+ const failure = describeAuthFailure(err, host);
if (json) {
process.stdout.write(
`${JSON.stringify(
- buildStatusPayload(host, backend, { authenticated: false, error: 'token invalid' }),
+ buildStatusPayload(host, backend, { authenticated: false, error: failure.message }),
)}\n`,
);
} else {
- process.stderr.write(`✗ Token invalid for ${host}\n`);
+ process.stderr.write(`✗ ${failure.message}\n`);
}
process.exit(1);
}
diff --git a/packages/cli/src/github/folder-validator.test.ts b/packages/cli/src/github/folder-validator.test.ts
index a6dee0b6a..767ec1821 100644
--- a/packages/cli/src/github/folder-validator.test.ts
+++ b/packages/cli/src/github/folder-validator.test.ts
@@ -30,6 +30,7 @@ describe('validateLocalFolderForShare', () => {
seedRepo(folder, 'https://github.com/inkeep/open-knowledge.git');
const result = await validateLocalFolderForShare(folder, {
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
});
@@ -45,6 +46,7 @@ describe('validateLocalFolderForShare', () => {
seedRepo(folder, '[email protected]:inkeep/open-knowledge.git');
const result = await validateLocalFolderForShare(folder, {
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
});
@@ -54,12 +56,57 @@ describe('validateLocalFolderForShare', () => {
});
});
+ test('accepts a GHES clone and re-emits a host-qualified canonical url', async () => {
+ const folder = resolve(tmpDir, 'repo');
+ mkdirSync(folder);
+ seedRepo(folder, 'https://ghes.acme.test/acme/kb.git');
+
+ const result = await validateLocalFolderForShare(folder, {
+ host: 'ghes.acme.test',
+ owner: 'acme',
+ repo: 'kb',
+ });
+ expect(result).toEqual({
+ kind: 'ok',
+ gitRemoteUrl: 'https://ghes.acme.test/acme/kb.git',
+ });
+ });
+
+ test('a github.com clone of the same owner/repo is a host mismatch, not wrong-repo', async () => {
+ const folder = resolve(tmpDir, 'repo');
+ mkdirSync(folder);
+ seedRepo(folder, 'https://github.com/acme/kb.git');
+
+ const result = await validateLocalFolderForShare(folder, {
+ host: 'ghes.acme.test',
+ owner: 'acme',
+ repo: 'kb',
+ });
+ // Right owner/repo, wrong server — surfaced as `wrong-host` so the UI can
+ // say "right repo, wrong server" instead of a confusing "wrong repo".
+ expect(result).toEqual({ kind: 'wrong-host', actualHost: 'github.com' });
+ });
+
+ test('a GHES clone offered for a github.com share is also a host mismatch', async () => {
+ const folder = resolve(tmpDir, 'repo');
+ mkdirSync(folder);
+ seedRepo(folder, 'https://ghes.acme.test/acme/kb.git');
+
+ const result = await validateLocalFolderForShare(folder, {
+ host: 'github.com',
+ owner: 'acme',
+ repo: 'kb',
+ });
+ expect(result).toEqual({ kind: 'wrong-host', actualHost: 'ghes.acme.test' });
+ });
+
test('owner / repo comparison is case-insensitive', async () => {
const folder = resolve(tmpDir, 'repo');
mkdirSync(folder);
seedRepo(folder, 'https://github.com/Inkeep/Open-Knowledge.git');
const result = await validateLocalFolderForShare(folder, {
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
});
@@ -76,6 +123,7 @@ describe('validateLocalFolderForShare', () => {
mkdirSync(folder);
const result = await validateLocalFolderForShare(folder, {
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
});
@@ -86,6 +134,7 @@ describe('validateLocalFolderForShare', () => {
const folder = resolve(tmpDir, 'does-not-exist');
const result = await validateLocalFolderForShare(folder, {
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
});
@@ -98,6 +147,7 @@ describe('validateLocalFolderForShare', () => {
// No config file at all — the "shell-only" git state.
const result = await validateLocalFolderForShare(folder, {
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
});
@@ -110,6 +160,7 @@ describe('validateLocalFolderForShare', () => {
seedRepo(folder, null);
const result = await validateLocalFolderForShare(folder, {
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
});
@@ -144,6 +195,7 @@ describe('validateLocalFolderForShare', () => {
writeFileSync(resolve(worktreeFolder, '.git'), `gitdir: ${primaryGitDir}\n`, 'utf-8');
const result = await validateLocalFolderForShare(worktreeFolder, {
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
});
@@ -176,6 +228,7 @@ describe('validateLocalFolderForShare', () => {
writeFileSync(resolve(worktreeFolder, '.git'), `gitdir: ${worktreeGitDir}\n`, 'utf-8');
const result = await validateLocalFolderForShare(worktreeFolder, {
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
});
@@ -191,6 +244,7 @@ describe('validateLocalFolderForShare', () => {
writeFileSync(resolve(folder, '.git'), 'this is not a worktree pointer\n', 'utf-8');
const result = await validateLocalFolderForShare(folder, {
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
});
@@ -203,6 +257,7 @@ describe('validateLocalFolderForShare', () => {
writeFileSync(resolve(folder, '.git'), `gitdir: ${resolve(tmpDir, 'no-such-dir')}\n`, 'utf-8');
const result = await validateLocalFolderForShare(folder, {
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
});
@@ -215,6 +270,7 @@ describe('validateLocalFolderForShare', () => {
seedRepo(folder, '[email protected]:inkeep/open-knowledge.git');
const result = await validateLocalFolderForShare(folder, {
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
});
@@ -227,6 +283,7 @@ describe('validateLocalFolderForShare', () => {
seedRepo(folder, 'this-is-not-a-url');
const result = await validateLocalFolderForShare(folder, {
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
});
@@ -239,6 +296,7 @@ describe('validateLocalFolderForShare', () => {
seedRepo(folder, 'https://github.com/someone-else/open-knowledge.git');
const result = await validateLocalFolderForShare(folder, {
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
});
@@ -255,6 +313,7 @@ describe('validateLocalFolderForShare', () => {
seedRepo(folder, 'https://github.com/inkeep/different-repo.git');
const result = await validateLocalFolderForShare(folder, {
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
});
@@ -278,6 +337,7 @@ describe('validateLocalFolderForShare', () => {
symlinkSync(escapeTarget, picked);
const result = await validateLocalFolderForShare(picked, {
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
});
@@ -301,6 +361,7 @@ describe('validateLocalFolderForShare', () => {
symlinkSync(elsewhere, resolve(folder, '.git'));
const result = await validateLocalFolderForShare(folder, {
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
});
@@ -318,6 +379,7 @@ describe('validateLocalFolderForShare', () => {
symlinkSync(realFolder, linkFolder);
const result = await validateLocalFolderForShare(linkFolder, {
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
});
@@ -339,6 +401,7 @@ describe('validateLocalFolderForShare', () => {
writeFileSync(resolve(folder, '.git', 'config'), config, 'utf-8');
const result = await validateLocalFolderForShare(folder, {
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
});
diff --git a/packages/cli/src/github/folder-validator.ts b/packages/cli/src/github/folder-validator.ts
index d2ad50b40..a9e050682 100644
--- a/packages/cli/src/github/folder-validator.ts
+++ b/packages/cli/src/github/folder-validator.ts
@@ -24,6 +24,7 @@
import { statSync } from 'node:fs';
import { realpath } from 'node:fs/promises';
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
+import { classifyGitHubShareHost } from '@inkeep/open-knowledge-core';
import { inspectGitRepository } from '@inkeep/open-knowledge-core/git-repository';
import { parseGitUrl } from './url.ts';
@@ -33,10 +34,14 @@ export type ShareFolderValidationResult =
| { kind: 'not-git' }
| { kind: 'no-origin' }
| { kind: 'wrong-repo'; actualOwner: string; actualRepo: string }
+ | { kind: 'wrong-host'; actualHost: string }
| { kind: 'non-github' }
| { kind: 'symlink-escape' };
+/** Mirrors `ExpectedShareRepo` in `@inkeep/open-knowledge-core` — keep in sync. */
export interface ExpectedShareRepo {
+ /** GitHub host the share targets: `github.com` or a GHES hostname. */
+ readonly host: string;
readonly owner: string;
readonly repo: string;
}
@@ -110,16 +115,26 @@ export async function validateLocalFolderForShare(
const originUrl = origin.url;
// 4. Parse origin via the shared `parseGitUrl`. Anything we can't parse
- // OR that points off-github lands as `non-github` — same downstream
- // surface (the receive dialog renders the "switch your remote" toast).
+ // OR that points at a known non-GitHub forge lands as `non-github` —
+ // same downstream surface (the receive dialog renders the "switch your
+ // remote" toast). Unknown hosts are presumed GitHub (GHES) and matched
+ // against the share's host below.
const parsed = parseGitUrl(originUrl);
if (parsed === null) return { kind: 'non-github' };
- if (parsed.hostname !== 'github.com') return { kind: 'non-github' };
+ const foldedHost = classifyGitHubShareHost(parsed.hostname);
+ if (foldedHost === null) return { kind: 'non-github' };
- // 5. Compare owner/repo case-insensitively (GitHub URL semantics).
+ // 5. Compare host + owner/repo case-insensitively (GitHub URL semantics).
+ const hostMatch = foldedHost === expected.host.toLowerCase();
const ownerMatch = parsed.owner.toLowerCase() === expected.owner.toLowerCase();
const repoMatch = parsed.name.toLowerCase() === expected.repo.toLowerCase();
- if (!ownerMatch || !repoMatch) {
+ // Same owner/repo but a different host (a github.com clone offered for a
+ // GHES share, or vice versa) is surfaced distinctly so the UI can say
+ // "right repo, wrong server" rather than a misleading "wrong repo".
+ if (!hostMatch && ownerMatch && repoMatch) {
+ return { kind: 'wrong-host', actualHost: foldedHost };
+ }
+ if (!hostMatch || !ownerMatch || !repoMatch) {
return { kind: 'wrong-repo', actualOwner: parsed.owner, actualRepo: parsed.name };
}
@@ -128,7 +143,7 @@ export async function validateLocalFolderForShare(
// SSH and HTTPS clones converge on one lookup key.
return {
kind: 'ok',
- gitRemoteUrl: `https://github.com/${parsed.owner}/${parsed.name}.git`,
+ gitRemoteUrl: `https://${foldedHost}/${parsed.owner}/${parsed.name}.git`,
};
}
diff --git a/packages/cli/src/github/url.test.ts b/packages/cli/src/github/url.test.ts
index e16e4f8cb..366113033 100644
--- a/packages/cli/src/github/url.test.ts
+++ b/packages/cli/src/github/url.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { parseGitHubBlobUrl, parseGitHubShareUrl, parseGitHubTreeUrl, parseGitUrl } from './url.ts';
describe('parseGitUrl', () => {
@@ -295,6 +295,7 @@ describe('parseGitHubBlobUrl', () => {
'https://github.com/inkeep/open-knowledge/blob/main/README.md',
);
expect(result).toEqual({
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
branch: 'main',
@@ -307,6 +308,7 @@ describe('parseGitHubBlobUrl', () => {
'https://github.com/inkeep/open-knowledge/blob/feat-x/docs/sub/page.md',
);
expect(result).toEqual({
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
branch: 'feat-x',
@@ -319,6 +321,7 @@ describe('parseGitHubBlobUrl', () => {
'https://github.com/inkeep/open-knowledge/blob/feat%2Ffoo/docs/page.md',
);
expect(result).toEqual({
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
branch: 'feat/foo',
@@ -331,6 +334,7 @@ describe('parseGitHubBlobUrl', () => {
'https://github.com/owner/repo/blob/main/docs/Q4%20OKRs%20%E2%80%94%20Marketing.md',
);
expect(result).toEqual({
+ host: 'github.com',
owner: 'owner',
repo: 'repo',
branch: 'main',
@@ -343,6 +347,7 @@ describe('parseGitHubBlobUrl', () => {
'https://github.com/owner/repo/blob/main/README.md?ref=campaign#L5',
);
expect(result).toEqual({
+ host: 'github.com',
owner: 'owner',
repo: 'repo',
branch: 'main',
@@ -353,6 +358,7 @@ describe('parseGitHubBlobUrl', () => {
test('accepts www.github.com host', () => {
const result = parseGitHubBlobUrl('https://www.github.com/owner/repo/blob/main/README.md');
expect(result).toEqual({
+ host: 'github.com',
owner: 'owner',
repo: 'repo',
branch: 'main',
@@ -364,10 +370,26 @@ describe('parseGitHubBlobUrl', () => {
expect(parseGitHubBlobUrl('https://gitlab.com/owner/repo/blob/main/README.md')).toBeNull();
});
- test('subdomain spoofing returns null', () => {
+ test('an unknown host (incl. a github.com lookalike) parses as an enterprise host', () => {
+ // GHES hostnames are arbitrary, so the parser cannot distinguish a
+ // lookalike like `github.com.evil.example` from a legitimate enterprise
+ // host by structure alone — both parse, carrying the host verbatim. The
+ // defense is the receive-side trust gate (`url-scheme.ts`), which prompts
+ // for any host the recipient is not authenticated to; it is NOT the
+ // parser's job to guess trust.
expect(
parseGitHubBlobUrl('https://github.com.evil.example/owner/repo/blob/main/README.md'),
- ).toBeNull();
+ ).toEqual({
+ host: 'github.com.evil.example',
+ owner: 'owner',
+ repo: 'repo',
+ branch: 'main',
+ path: 'README.md',
+ });
+ });
+
+ test('a known non-GitHub forge host still returns null', () => {
+ expect(parseGitHubBlobUrl('https://gitlab.com/owner/repo/blob/main/README.md')).toBeNull();
});
// REGRESSION PIN: the blob-only parser treats a
@@ -424,6 +446,7 @@ describe('parseGitHubBlobUrl', () => {
const url = `https://github.com/owner/repo/blob/${encodedBranch}/docs/page.md`;
const result = parseGitHubBlobUrl(url);
expect(result).toEqual({
+ host: 'github.com',
owner: 'owner',
repo: 'repo',
branch,
@@ -434,12 +457,33 @@ describe('parseGitHubBlobUrl', () => {
});
});
+describe('parser scheme guard (https-only)', () => {
+ // A crafted deep link can pair a non-https scheme with a valid host + path
+ // and otherwise parse; the parser must reject it so the URL never reaches an
+ // <a href> or shell.openExternal. Legitimate share links are always https.
+ for (const url of [
+ 'vscode://ghes.internal.example/owner/repo/blob/main/README.md',
+ 'http://github.com/owner/repo/blob/main/README.md',
+ ]) {
+ test(`parseGitHubBlobUrl rejects non-https scheme: ${url}`, () => {
+ expect(parseGitHubBlobUrl(url)).toBeNull();
+ });
+ }
+
+ test('parseGitHubTreeUrl rejects a non-https scheme', () => {
+ expect(
+ parseGitHubTreeUrl('vscode://ghes.internal.example/owner/repo/tree/main/docs'),
+ ).toBeNull();
+ });
+});
+
describe('parseGitHubTreeUrl', () => {
test('happy path: tree URL with a folder path', () => {
const result = parseGitHubTreeUrl(
'https://github.com/inkeep/open-knowledge/tree/main/docs/sub',
);
expect(result).toEqual({
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
branch: 'main',
@@ -449,12 +493,24 @@ describe('parseGitHubTreeUrl', () => {
test('root folder: tree/<branch> (no path, no trailing slash) -> path ""', () => {
const result = parseGitHubTreeUrl('https://github.com/owner/repo/tree/main');
- expect(result).toEqual({ owner: 'owner', repo: 'repo', branch: 'main', path: '' });
+ expect(result).toEqual({
+ host: 'github.com',
+ owner: 'owner',
+ repo: 'repo',
+ branch: 'main',
+ path: '',
+ });
});
test('root folder: tree/<branch>/ (trailing slash) -> path ""', () => {
const result = parseGitHubTreeUrl('https://github.com/owner/repo/tree/main/');
- expect(result).toEqual({ owner: 'owner', repo: 'repo', branch: 'main', path: '' });
+ expect(result).toEqual({
+ host: 'github.com',
+ owner: 'owner',
+ repo: 'repo',
+ branch: 'main',
+ path: '',
+ });
});
test('branch containing slash (percent-encoded) round-trips', () => {
@@ -462,6 +518,7 @@ describe('parseGitHubTreeUrl', () => {
'https://github.com/inkeep/open-knowledge/tree/feat%2Ffoo/docs',
);
expect(result).toEqual({
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
branch: 'feat/foo',
@@ -471,7 +528,13 @@ describe('parseGitHubTreeUrl', () => {
test('%2F-encoded slashed branch at root round-trips', () => {
const result = parseGitHubTreeUrl('https://github.com/owner/repo/tree/feat%2Ffoo');
- expect(result).toEqual({ owner: 'owner', repo: 'repo', branch: 'feat/foo', path: '' });
+ expect(result).toEqual({
+ host: 'github.com',
+ owner: 'owner',
+ repo: 'repo',
+ branch: 'feat/foo',
+ path: '',
+ });
});
test('percent-encoded path segments round-trip', () => {
@@ -479,6 +542,7 @@ describe('parseGitHubTreeUrl', () => {
'https://github.com/owner/repo/tree/main/docs/Q4%20OKRs%20%E2%80%94%20Marketing',
);
expect(result).toEqual({
+ host: 'github.com',
owner: 'owner',
repo: 'repo',
branch: 'main',
@@ -488,12 +552,24 @@ describe('parseGitHubTreeUrl', () => {
test('accepts www.github.com host', () => {
const result = parseGitHubTreeUrl('https://www.github.com/owner/repo/tree/main/docs');
- expect(result).toEqual({ owner: 'owner', repo: 'repo', branch: 'main', path: 'docs' });
+ expect(result).toEqual({
+ host: 'github.com',
+ owner: 'owner',
+ repo: 'repo',
+ branch: 'main',
+ path: 'docs',
+ });
});
test('ignores query string and fragment', () => {
const result = parseGitHubTreeUrl('https://github.com/owner/repo/tree/main/docs?ref=x#frag');
- expect(result).toEqual({ owner: 'owner', repo: 'repo', branch: 'main', path: 'docs' });
+ expect(result).toEqual({
+ host: 'github.com',
+ owner: 'owner',
+ repo: 'repo',
+ branch: 'main',
+ path: 'docs',
+ });
});
test('blob URL returns null', () => {
@@ -504,10 +580,22 @@ describe('parseGitHubTreeUrl', () => {
expect(parseGitHubTreeUrl('https://gitlab.com/owner/repo/tree/main/docs')).toBeNull();
});
- test('subdomain spoofing returns null', () => {
- expect(
- parseGitHubTreeUrl('https://github.com.evil.example/owner/repo/tree/main/docs'),
- ).toBeNull();
+ test('an unknown host (incl. a github.com lookalike) parses as an enterprise host', () => {
+ // See the blob parser's companion test: structural parsing accepts any
+ // non-forge host; trust is enforced downstream by the receive-side gate.
+ expect(parseGitHubTreeUrl('https://github.com.evil.example/owner/repo/tree/main/docs')).toEqual(
+ {
+ host: 'github.com.evil.example',
+ owner: 'owner',
+ repo: 'repo',
+ branch: 'main',
+ path: 'docs',
+ },
+ );
+ });
+
+ test('a known non-GitHub forge host still returns null', () => {
+ expect(parseGitHubTreeUrl('https://gitlab.com/owner/repo/tree/main/docs')).toBeNull();
});
test('empty intermediate path segment returns null', () => {
@@ -534,6 +622,7 @@ describe('parseGitHubShareUrl (dispatcher)', () => {
);
expect(result).toEqual({
kind: 'doc',
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
branch: 'main',
@@ -545,6 +634,7 @@ describe('parseGitHubShareUrl (dispatcher)', () => {
const result = parseGitHubShareUrl('https://github.com/owner/repo/tree/main/docs/sub');
expect(result).toEqual({
kind: 'folder',
+ host: 'github.com',
owner: 'owner',
repo: 'repo',
branch: 'main',
@@ -556,6 +646,7 @@ describe('parseGitHubShareUrl (dispatcher)', () => {
const result = parseGitHubShareUrl('https://github.com/owner/repo/tree/main');
expect(result).toEqual({
kind: 'folder',
+ host: 'github.com',
owner: 'owner',
repo: 'repo',
branch: 'main',
@@ -567,6 +658,7 @@ describe('parseGitHubShareUrl (dispatcher)', () => {
const result = parseGitHubShareUrl('https://github.com/owner/repo/tree/main/');
expect(result).toEqual({
kind: 'folder',
+ host: 'github.com',
owner: 'owner',
repo: 'repo',
branch: 'main',
@@ -578,6 +670,7 @@ describe('parseGitHubShareUrl (dispatcher)', () => {
const result = parseGitHubShareUrl('https://github.com/owner/repo/tree/feat%2Ffoo/docs');
expect(result).toEqual({
kind: 'folder',
+ host: 'github.com',
owner: 'owner',
repo: 'repo',
branch: 'feat/foo',
diff --git a/packages/cli/src/github/url.ts b/packages/cli/src/github/url.ts
index ae708b16b..913fd594f 100644
--- a/packages/cli/src/github/url.ts
+++ b/packages/cli/src/github/url.ts
@@ -1,3 +1,5 @@
+import { classifyGitHubShareHost } from '@inkeep/open-knowledge-core';
+
/**
* Parsed Git URL result.
*/
@@ -9,9 +11,11 @@ interface ParsedGitUrl {
}
/**
- * Parsed GitHub blob URL result.
+ * Parsed GitHub blob URL result. `host` is the normalized GitHub host
+ * (github.com or a GHES hostname).
*/
export interface ParsedGitHubBlobUrl {
+ host: string;
owner: string;
repo: string;
branch: string;
@@ -24,6 +28,7 @@ export interface ParsedGitHubBlobUrl {
* (`tree/<branch>` or `tree/<branch>/`).
*/
export interface ParsedGitHubTreeUrl {
+ host: string;
owner: string;
repo: string;
branch: string;
@@ -36,8 +41,8 @@ export interface ParsedGitHubTreeUrl {
* for the repo/branch root).
*/
export type ParsedGitHubShareTarget =
- | { kind: 'doc'; owner: string; repo: string; branch: string; path: string }
- | { kind: 'folder'; owner: string; repo: string; branch: string; path: string };
+ | { kind: 'doc'; host: string; owner: string; repo: string; branch: string; path: string }
+ | { kind: 'folder'; host: string; owner: string; repo: string; branch: string; path: string };
/**
* Strip a trailing :port from a hostname string.
@@ -135,9 +140,14 @@ export function parseGitHubBlobUrl(input: string): ParsedGitHubBlobUrl | null {
return null;
}
- if (url.hostname !== 'github.com' && url.hostname !== 'www.github.com') {
- return null;
- }
+ // Share links are always https. Reject any other scheme: a crafted deep
+ // link could carry a non-https scheme (vscode:, ms-msdt:, …) with a valid
+ // host and otherwise parse — that URL must never reach an <a href> or
+ // shell.openExternal.
+ if (url.protocol !== 'https:') return null;
+
+ const host = classifyGitHubShareHost(url.hostname);
+ if (host === null) return null;
const rawSegments = url.pathname.split('/').filter((s) => s.length > 0);
@@ -161,7 +171,7 @@ export function parseGitHubBlobUrl(input: string): ParsedGitHubBlobUrl | null {
if (!owner || !repo || !branch || pathParts.length === 0) return null;
if (pathParts.some((p) => p.length === 0)) return null;
- return { owner, repo, branch, path: pathParts.join('/') };
+ return { host, owner, repo, branch, path: pathParts.join('/') };
}
/**
@@ -188,9 +198,14 @@ export function parseGitHubTreeUrl(input: string): ParsedGitHubTreeUrl | null {
return null;
}
- if (url.hostname !== 'github.com' && url.hostname !== 'www.github.com') {
- return null;
- }
+ // Share links are always https. Reject any other scheme: a crafted deep
+ // link could carry a non-https scheme (vscode:, ms-msdt:, …) with a valid
+ // host and otherwise parse — that URL must never reach an <a href> or
+ // shell.openExternal.
+ if (url.protocol !== 'https:') return null;
+
+ const host = classifyGitHubShareHost(url.hostname);
+ if (host === null) return null;
// Split WITHOUT filtering empties so empty intermediate path segments
// (`a//b`) remain detectable. The pathname always starts with `/`, so
@@ -226,7 +241,7 @@ export function parseGitHubTreeUrl(input: string): ParsedGitHubTreeUrl | null {
// Empty intermediate segments (e.g. `a//b`) are malformed.
if (pathParts.some((p) => p.length === 0)) return null;
- return { owner, repo, branch, path: pathParts.join('/') };
+ return { host, owner, repo, branch, path: pathParts.join('/') };
}
/**
diff --git a/packages/core/src/constants/github.ts b/packages/core/src/constants/github.ts
index 799733b59..6e83944a1 100644
--- a/packages/core/src/constants/github.ts
+++ b/packages/core/src/constants/github.ts
@@ -19,3 +19,16 @@ export const KNOWN_NON_GITHUB_GIT_HOSTS: ReadonlySet<string> = new Set([
'sr.ht',
'sourcehut.org',
]);
+
+/**
+ * Classify a git host for share purposes: lowercase, fold `www.github.com` to
+ * `github.com`, and reject known non-GitHub forges. Returns the normalized
+ * host (github.com or a presumed-GHES hostname) or `null` for a forge we know
+ * isn't GitHub. Single source of truth for the share URL parsers, the folder
+ * validator, and the desktop git-remote canonicalizer.
+ */
+export function classifyGitHubShareHost(hostname: string): string | null {
+ const host = hostname.toLowerCase();
+ const folded = host === 'www.github.com' ? 'github.com' : host;
+ return KNOWN_NON_GITHUB_GIT_HOSTS.has(folded) ? null : folded;
+}
diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.ts
index 8d4ef2166..2d7fe3196 100644
--- a/packages/core/src/desktop-bridge.ts
+++ b/packages/core/src/desktop-bridge.ts
@@ -288,6 +288,8 @@ type ShareTarget =
/** Local copy — see canonical `OkSharePayloadFields` in
* `packages/desktop/src/shared/bridge-contract.ts`. */
interface OkSharePayloadFields {
+ /** GitHub host of the shared repo: `github.com` or a GHES hostname. */
+ readonly host: string;
readonly owner: string;
readonly repo: string;
readonly branch: string;
@@ -335,6 +337,7 @@ type ShareFolderValidationResult =
| { readonly kind: 'not-git' }
| { readonly kind: 'no-origin' }
| { readonly kind: 'wrong-repo'; readonly actualOwner: string; readonly actualRepo: string }
+ | { readonly kind: 'wrong-host'; readonly actualHost: string }
| { readonly kind: 'non-github' }
| { readonly kind: 'symlink-escape' };
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 39f0d847a..3681841fb 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -240,6 +240,7 @@ export {
export { SHOW_INSTALL_SKILL } from './constants/feature-flags.ts';
export type { OkFolderState } from './constants/folder-state.ts';
export {
+ classifyGitHubShareHost,
DEFAULT_GITHUB_OAUTH_CLIENT_ID,
KNOWN_NON_GITHUB_GIT_HOSTS,
} from './constants/github.ts';
@@ -728,6 +729,10 @@ export {
LocalOpAuthEmptySuccessSchema,
type LocalOpAuthHostRequest,
LocalOpAuthHostRequestSchema,
+ type LocalOpAuthPatRequest,
+ LocalOpAuthPatRequestSchema,
+ type LocalOpAuthPatSuccess,
+ LocalOpAuthPatSuccessSchema,
type LocalOpAuthSetIdentityRequest,
LocalOpAuthSetIdentityRequestSchema,
type LocalOpAuthStatusSuccess,
diff --git a/packages/core/src/schemas/api/local-op.ts b/packages/core/src/schemas/api/local-op.ts
index 40c1b2f0f..020529a46 100644
--- a/packages/core/src/schemas/api/local-op.ts
+++ b/packages/core/src/schemas/api/local-op.ts
@@ -89,6 +89,30 @@ export const LocalOpAuthHostRequestSchema = z
.loose() satisfies StandardSchemaV1;
export type LocalOpAuthHostRequest = z.infer<typeof LocalOpAuthHostRequestSchema>;
+/**
+ * Request body for `POST /api/local-op/auth/pat` — store a Personal Access
+ * Token for a host (the enterprise sign-in path, since the OAuth device flow
+ * only works on github.com). `host` optional (defaults to the workspace origin
+ * host server-side); `token` REQUIRED. The token travels renderer → loopback
+ * POST and is handed to the CLI over stdin, never argv/env.
+ */
+export const LocalOpAuthPatRequestSchema = z
+ .object({
+ host: z.string().min(1).optional(),
+ token: z.string().min(1),
+ })
+ .loose() satisfies StandardSchemaV1;
+export type LocalOpAuthPatRequest = z.infer<typeof LocalOpAuthPatRequestSchema>;
+
+/** Success payload for `POST /api/local-op/auth/pat`: the stored identity. */
+export const LocalOpAuthPatSuccessSchema = z
+ .object({
+ host: z.string(),
+ login: z.string(),
+ })
+ .loose() satisfies StandardSchemaV1;
+export type LocalOpAuthPatSuccess = z.infer<typeof LocalOpAuthPatSuccessSchema>;
+
/**
* Request body for `POST /api/local-op/embeddings/set-key`. `key` REQUIRED
* non-empty — the embeddings provider API key. Travels renderer → loopback POST
diff --git a/packages/core/src/schemas/api/share.ts b/packages/core/src/schemas/api/share.ts
index 336de1049..b149ca273 100644
--- a/packages/core/src/schemas/api/share.ts
+++ b/packages/core/src/schemas/api/share.ts
@@ -67,8 +67,9 @@ export type ShareConstructUrlRequest = z.infer<typeof ShareConstructUrlRequestSc
* the branch before sharing (by local-ref contract, this is checked locally — no
* `git ls-remote` is issued, so a stale local fetch may mis-fire as a
* false negative; the user re-pushes, no harm done).
- * - `non-github-remote` — origin URL parses but the host is not `github.com`
- * (gitlab, bitbucket, internal forge). Share is GitHub-only in v1.
+ * - `non-github-remote` — origin URL parses but the host is a known non-GitHub
+ * forge (gitlab, bitbucket, codeberg, …). GitHub Enterprise Server hosts are
+ * supported; only non-GitHub forges land here.
* - `invalid-path` — the share target path (a doc's file path or a folder's
* directory path) traverses outside the project root or names the `.git/`
* subtree. An empty path is NOT invalid: it is a legitimate content-root
diff --git a/packages/core/src/schemas/api/sync-seed.ts b/packages/core/src/schemas/api/sync-seed.ts
index 1af19f7ad..7cbfd3ccc 100644
--- a/packages/core/src/schemas/api/sync-seed.ts
+++ b/packages/core/src/schemas/api/sync-seed.ts
@@ -66,7 +66,12 @@ export const PushPermissionSchema = z.discriminatedUnion('checkStatus', [
z
.object({
checkStatus: z.literal('denied'),
- deniedReason: z.enum(['no-collaborator', 'private-no-access', 'repo-not-found']),
+ deniedReason: z.enum([
+ 'no-collaborator',
+ 'private-no-access',
+ 'repo-not-found',
+ 'not-authenticated',
+ ]),
})
.loose(),
z
diff --git a/packages/core/src/sharing/candidate-selection.test.ts b/packages/core/src/sharing/candidate-selection.test.ts
index daa322ed1..86f3ad5e3 100644
--- a/packages/core/src/sharing/candidate-selection.test.ts
+++ b/packages/core/src/sharing/candidate-selection.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import type { BridgeWorktreeEntry } from '../git/worktree-list-parser.ts';
import {
type Candidate,
@@ -81,6 +81,7 @@ function makeBridge(opts: StubOptions): CandidateBridgeDeps {
}
const PAYLOAD: CandidateSelectionPayload = {
+ host: 'github.com',
owner: 'inkeep',
repo: 'open-knowledge',
branch: 'feat-bar',
diff --git a/packages/core/src/sharing/candidate-selection.ts b/packages/core/src/sharing/candidate-selection.ts
index cf468e1a1..c6979eb0e 100644
--- a/packages/core/src/sharing/candidate-selection.ts
+++ b/packages/core/src/sharing/candidate-selection.ts
@@ -80,10 +80,12 @@ export interface CandidateBridgeDeps {
}
/**
- * The minimum slice of the share payload needed for selection — owner,
- * repo, and branch.
+ * The minimum slice of the share payload needed for selection — host, owner,
+ * repo, and branch. `host` is part of the repo identity so a GHES share never
+ * matches a same-owner/repo github.com clone.
*/
export interface CandidateSelectionPayload {
+ readonly host: string;
readonly owner: string;
readonly repo: string;
readonly branch: string;
@@ -212,6 +214,7 @@ export async function selectCandidate(
}
const recentMatches = findRecentProjectsForRepo(recents, {
+ host: payload.host,
owner: payload.owner,
repo: payload.repo,
});
diff --git a/packages/core/src/sharing/receive-flow.test.ts b/packages/core/src/sharing/receive-flow.test.ts
index 177e8b704..fd6f7c48f 100644
--- a/packages/core/src/sharing/receive-flow.test.ts
+++ b/packages/core/src/sharing/receive-flow.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
canonicalGitHubRemoteUrl,
@@ -10,20 +10,26 @@ import {
describe('canonicalGitHubRemoteUrl', () => {
test('emits https github.git form for plain owner/repo', () => {
- expect(canonicalGitHubRemoteUrl({ owner: 'inkeep', repo: 'open-knowledge' })).toBe(
- 'https://github.com/inkeep/open-knowledge.git',
- );
+ expect(
+ canonicalGitHubRemoteUrl({ host: 'github.com', owner: 'inkeep', repo: 'open-knowledge' }),
+ ).toBe('https://github.com/inkeep/open-knowledge.git');
});
test('preserves casing in the canonical form', () => {
- expect(canonicalGitHubRemoteUrl({ owner: 'Inkeep', repo: 'Open-Knowledge' })).toBe(
- 'https://github.com/Inkeep/Open-Knowledge.git',
+ expect(
+ canonicalGitHubRemoteUrl({ host: 'github.com', owner: 'Inkeep', repo: 'Open-Knowledge' }),
+ ).toBe('https://github.com/Inkeep/Open-Knowledge.git');
+ });
+
+ test('carries an enterprise host into the canonical form', () => {
+ expect(canonicalGitHubRemoteUrl({ host: 'ghes.acme.test', owner: 'acme', repo: 'kb' })).toBe(
+ 'https://ghes.acme.test/acme/kb.git',
);
});
});
describe('findRecentProjectsForRepo', () => {
- const expected = { owner: 'inkeep', repo: 'open-knowledge' };
+ const expected = { host: 'github.com', owner: 'inkeep', repo: 'open-knowledge' };
function recent(overrides: Partial<RecentProjectEntry> = {}): RecentProjectEntry {
return {
@@ -89,6 +95,22 @@ describe('findRecentProjectsForRepo', () => {
expect(findRecentProjectsForRepo([r], expected)).toEqual([]);
});
+ test('a same-owner/repo clone on a different host does NOT match (no cross-host collision)', () => {
+ // A GHES acme/kb share must never resolve to a github.com acme/kb clone.
+ const githubClone = recent({
+ path: '/gh',
+ gitRemoteUrl: 'https://github.com/acme/kb.git',
+ });
+ const ghesExpected = { host: 'ghes.acme.test', owner: 'acme', repo: 'kb' };
+ expect(findRecentProjectsForRepo([githubClone], ghesExpected)).toEqual([]);
+ // ...and the GHES clone matches the GHES share.
+ const ghesClone = recent({
+ path: '/ghes',
+ gitRemoteUrl: 'https://ghes.acme.test/acme/kb.git',
+ });
+ expect(findRecentProjectsForRepo([ghesClone], ghesExpected)).toEqual([ghesClone]);
+ });
+
test('all matching entries marked missing yields [] (graceful degradation anchor)', () => {
const a = recent({
path: '/a',
diff --git a/packages/core/src/sharing/receive-flow.ts b/packages/core/src/sharing/receive-flow.ts
index 8e8b7310e..e4117ab98 100644
--- a/packages/core/src/sharing/receive-flow.ts
+++ b/packages/core/src/sharing/receive-flow.ts
@@ -70,6 +70,8 @@ export interface RecentProjectEntry {
}
export interface ExpectedShareRepo {
+ /** GitHub host the share's repo lives on: `github.com` or a GHES hostname. */
+ readonly host: string;
readonly owner: string;
readonly repo: string;
}
@@ -78,10 +80,12 @@ export interface ExpectedShareRepo {
* Canonical GitHub remote URL used as the share-receive lookup key. Matches
* the form `readCanonicalGitHubRemoteUrl` writes during open-time backfill
* and `validateLocalFolderForShare` returns, so SSH-cloned and HTTPS-cloned
- * receivers converge on a single key.
+ * receivers converge on a single key. The host is part of the key: a GHES
+ * `acme/kb` and a github.com `acme/kb` are different repositories and must
+ * never match the same local clone.
*/
export function canonicalGitHubRemoteUrl(expected: ExpectedShareRepo): string {
- return `https://github.com/${expected.owner}/${expected.repo}.git`;
+ return `https://${expected.host}/${expected.owner}/${expected.repo}.git`;
}
function normalizeForMatch(url: string): string {
diff --git a/packages/desktop/src/main/git-remote.test.ts b/packages/desktop/src/main/git-remote.test.ts
index 3974cfb29..edba16ea0 100644
--- a/packages/desktop/src/main/git-remote.test.ts
+++ b/packages/desktop/src/main/git-remote.test.ts
@@ -37,6 +37,19 @@ describe('readCanonicalGitHubRemoteUrl (filesystem round-trip)', () => {
expect(result).toBe('https://github.com/inkeep/open-knowledge.git');
});
+ test('returns a host-qualified canonical url for a GHES origin', () => {
+ // A GHES clone MUST get a gitRemoteUrl (else it never matches a share),
+ // and the host must be preserved so it stays distinct from github.com.
+ const result = withTempProject((projectDir) => {
+ mkdirSync(join(projectDir, '.git'));
+ writeFileSync(
+ join(projectDir, '.git', 'config'),
+ '[remote "origin"]\n\turl = https://ghes.acme.test/acme/kb.git\n',
+ );
+ });
+ expect(result).toBe('https://ghes.acme.test/acme/kb.git');
+ });
+
test('returns null when .git/config is absent (not a git repo)', () => {
const result = withTempProject(() => {
// No .git directory at all.
diff --git a/packages/desktop/src/main/git-remote.ts b/packages/desktop/src/main/git-remote.ts
index b5f8b710f..80e14c74c 100644
--- a/packages/desktop/src/main/git-remote.ts
+++ b/packages/desktop/src/main/git-remote.ts
@@ -9,6 +9,7 @@
*/
import { parseGitUrl } from '@inkeep/open-knowledge';
+import { classifyGitHubShareHost } from '@inkeep/open-knowledge-core';
import { inspectGitRepository } from '@inkeep/open-knowledge-core/git-repository';
/**
@@ -28,6 +29,11 @@ export function readCanonicalGitHubRemoteUrl(projectPath: string): string | null
const parsed = parseGitUrl(origin.url);
if (parsed === null) return null;
- if (parsed.hostname !== 'github.com') return null;
- return `https://github.com/${parsed.owner}/${parsed.name}.git`;
+ // Presume any host that isn't a known non-GitHub forge is github.com or a
+ // GHES instance, and re-emit the canonical HTTPS form host-qualified so
+ // GHES clones get a `gitRemoteUrl` (else they never match a share) and a
+ // GHES `acme/kb` stays distinct from a github.com `acme/kb`.
+ const foldedHost = classifyGitHubShareHost(parsed.hostname);
+ if (foldedHost === null) return null;
+ return `https://${foldedHost}/${parsed.owner}/${parsed.name}.git`;
}
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 252947148..3d365c3d8 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -99,6 +99,8 @@ import {
recordSkillInstallEvent,
resolveBundledSkillDir,
resolveLockDir,
+ runAuthStatusSubprocess,
+ trustSystemCertificates,
USER_GLOBAL_BUNDLE_IDS,
untrackTrackedProjectSkillProjection,
withSpan,
@@ -307,7 +309,7 @@ import {
import { handleRevealExternal } from './reveal-external.ts';
import { createServerExitRecorder, type ServerExitRecorder } from './server-exit-record.ts';
import { startFirstRunHandshake } from './share-handoff.ts';
-import { handleShellOpenExternal } from './shell-allowlist.ts';
+import { checkOutboundUrl, handleShellOpenExternal } from './shell-allowlist.ts';
import { createShowGateRegistry, type ShowGateRegistry } from './show-gate.ts';
import { reclaimProjectSkillsOnProjectOpen, reclaimUserSkillsOnLaunch } from './skill-reclaim.ts';
import { attachSpellcheckContextMenu } from './spellcheck-context-menu.ts';
@@ -4257,6 +4259,7 @@ function registerIpcHandlers() {
handle('ok:share:validate-folder', async (_event, request) => {
return validateLocalFolderForShare(request.folderPath, {
+ host: request.host,
owner: request.owner,
repo: request.repo,
});
@@ -5076,6 +5079,15 @@ installStdioBrokenPipeGuard(process, {
},
});
+// Trust the OS certificate store (macOS Keychain / enterprise CA) so a GHES on
+// a self-signed or internal-CA cert — already trusted by `git` — works for the
+// app's TLS. `appendSwitch` covers Chromium's network stack; the runtime call
+// covers Node's fetch/undici in THIS main process (the two are separate trust
+// stores). The server fork and the CLI subprocess each apply the same trust on
+// their own boot.
+app.commandLine.appendSwitch('use-system-ca');
+trustSystemCertificates();
+
// Driver-mode exception: when the env triplet
// `OK_DEBUG_KEYRING_SMOKE=1 + OK_DEBUG_KEYRING_SMOKE_EXIT=1` is set, the
// packaged app is being launched by the `verify-keyring-in-packaged-dmg.mjs`
@@ -5337,6 +5349,76 @@ function bootPrimaryInstance(): void {
// the same list).
listRecent: () => annotateMissing(appState),
}),
+ // Trust gate for GHES share hosts: an already-authenticated host proceeds
+ // silently; an unfamiliar one prompts, since deep links are untrusted.
+ gateForeignShareHost: async (host, sharedUrl) => {
+ let authenticated = false;
+ try {
+ const status = await runAuthStatusSubprocess({
+ cliArgs: resolveLocalOpCliArgs(),
+ host,
+ });
+ authenticated = status.authenticated;
+ } catch {
+ // Probe failure ⇒ treat as untrusted and fall through to the prompt.
+ }
+ if (authenticated) return 'proceed';
+
+ // Focus first: a deep-link launch may have no active window, so the
+ // prompt would otherwise render behind other apps or not show at all.
+ app.focus({ steal: true });
+ const parentWindow = BrowserWindow.getAllWindows().find((w) => !w.isDestroyed());
+ const messageBoxOptions = {
+ type: 'warning' as const,
+ buttons: [`Connect to ${host}…`, 'Open in browser', 'Cancel'],
+ // Cancel is the safe keyboard default for an unfamiliar, attacker-
+ // suppliable host — neither connecting nor opening happens on a stray
+ // Enter/Escape. The user must choose Connect or Open deliberately.
+ defaultId: 2,
+ cancelId: 2,
+ message: `This share points at ${host}`,
+ detail:
+ `You aren't connected to this GitHub Enterprise Server in OpenKnowledge. ` +
+ `After connecting, open the share link again to receive it.`,
+ };
+ const { response } = parentWindow
+ ? await dialog.showMessageBox(parentWindow, messageBoxOptions)
+ : await dialog.showMessageBox(messageBoxOptions);
+ if (response === 0) {
+ // Connect: land the user on Account settings to sign in to this host
+ // (the PAT panel, since GHES can't use the browser sign-in). The share
+ // isn't received now — they re-open the link once connected. Same drop
+ // as the browser/cancel branches on the receive side.
+ if (parentWindow) {
+ (parentWindow as BrowserWindowLike).webContents.executeJavaScript(
+ "window.location.hash = '#settings/account'; undefined",
+ );
+ } else {
+ // App running with every window closed: open one so Connect isn't a
+ // silent no-op. (Routing that fresh window straight to Account is a
+ // follow-up — it needs the editor renderer + a ready-gate.)
+ openNavigator();
+ }
+ return 'connect';
+ }
+ if (response === 1) {
+ // Route through the outbound-scheme allowlist rather than calling
+ // shell.openExternal directly: sharedUrl comes from an untrusted deep
+ // link, and a non-https scheme (vscode:, ms-msdt:, …) must never reach
+ // the OS protocol handler. Legitimate shares are always https.
+ const check = checkOutboundUrl(sharedUrl);
+ if (!check.ok) {
+ getLogger('share-receive').warn(
+ { host, reason: check.reason },
+ '[receive] refused to open share URL with disallowed scheme',
+ );
+ return 'cancel';
+ }
+ await shell.openExternal(sharedUrl);
+ return 'open-browser';
+ }
+ return 'cancel';
+ },
// Kind-aware target-existence gate, run after `branch-match-ok` and before
// dispatch (see `dispatchResolvedShare`). Native synchronous probe — no IPC.
checkShareTargetExists: (projectPath, kind, path) =>
diff --git a/packages/desktop/src/main/resolve-share-target.test.ts b/packages/desktop/src/main/resolve-share-target.test.ts
index 2966d1e55..d3b9016a4 100644
--- a/packages/desktop/src/main/resolve-share-target.test.ts
+++ b/packages/desktop/src/main/resolve-share-target.test.ts
@@ -1,10 +1,10 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import { execFile } from 'node:child_process';
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { promisify } from 'node:util';
import type { RecentProjectEntry } from '@inkeep/open-knowledge-core';
+import { afterEach, describe, expect, test } from 'vitest';
import { filterShareEligibleRecents, resolveShareTarget } from './resolve-share-target.ts';
import { annotateMissing, emptyState } from './state-store.ts';
@@ -71,7 +71,7 @@ function seedOkProject(projectPath: string): void {
writeFileSync(join(projectPath, '.ok', 'config.yml'), 'content:\n dir: .\n');
}
-const PAYLOAD = { owner: 'acme', repo: 'widget', branch: 'feat-foo' } as const;
+const PAYLOAD = { host: 'github.com', owner: 'acme', repo: 'widget', branch: 'feat-foo' } as const;
describe('resolveShareTarget — main-side adapter parity with the shared algorithm', () => {
let handle: TempRepoHandle | null = null;
diff --git a/packages/desktop/src/main/url-scheme.test.ts b/packages/desktop/src/main/url-scheme.test.ts
index 5ac92aeec..62901877a 100644
--- a/packages/desktop/src/main/url-scheme.test.ts
+++ b/packages/desktop/src/main/url-scheme.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import { encodeShareUrl } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { parseOpenKnowledgeUrl, parseScreenUrl, parseShareUrl } from './url-scheme.ts';
/**
@@ -271,6 +271,7 @@ describe('parseShareUrl — universal-link happy path', () => {
kind: 'ok',
source: 'universal-link',
payload: {
+ host: 'github.com',
owner: 'inkeep',
repo: 'playbooks',
branch: 'main',
@@ -380,6 +381,7 @@ describe('parseShareUrl — universal-link error states', () => {
kind: 'ok',
source: 'universal-link',
payload: {
+ host: 'github.com',
owner: 'inkeep',
repo: 'playbooks',
branch: 'main',
@@ -407,6 +409,7 @@ describe('parseShareUrl — custom-scheme happy path', () => {
kind: 'ok',
source: 'custom-scheme',
payload: {
+ host: 'github.com',
owner: 'inkeep',
repo: 'playbooks',
branch: 'main',
diff --git a/packages/desktop/src/main/url-scheme.ts b/packages/desktop/src/main/url-scheme.ts
index ce8833db9..a9134f852 100644
--- a/packages/desktop/src/main/url-scheme.ts
+++ b/packages/desktop/src/main/url-scheme.ts
@@ -300,6 +300,7 @@ function finalizeShareResult(sharedUrl: string, source: ShareUrlSource): SharePa
kind: 'ok',
source,
payload: {
+ host: parsed.host,
owner: parsed.owner,
repo: parsed.repo,
branch: parsed.branch,
@@ -488,6 +489,13 @@ export function parseScreenUrl(input: string): ParsedScreenUrl | null {
return { host: 'screen', name };
}
+/**
+ * User's decision from the foreign-host trust gate (see `gateForeignShareHost`).
+ * `connect` = the user chose to sign in to the host; the gate navigates the app
+ * to Account settings and does not drive the clone (same drop as cancel/browser).
+ */
+export type ForeignHostDecision = 'proceed' | 'open-browser' | 'connect' | 'cancel';
+
/**
* Side-effect surface for `registerProtocolHandler`. Injected so the main-
* process glue can pass real `openProject` / `focusWindowForProject` / `send`
@@ -618,6 +626,23 @@ interface ProtocolHandlerDeps {
* Production main always wires it.
*/
resolveShareTarget?(share: ShareUrlPayload): Promise<CandidateSelection>;
+ /**
+ * Trust gate for shares whose repo lives on a host other than github.com
+ * (issue #597 follow-up — GHES support). Deep links are attacker-suppliable,
+ * so an unfamiliar host must never silently drive the clone/receive flow.
+ * Called with the normalized host + the decoded `sharedUrl` BEFORE
+ * resolution; returns the user's decision:
+ * - `'proceed'` — treat like github.com and continue to resolution
+ * (main returns this without prompting for a host the recipient is
+ * already authenticated to);
+ * - `'open-browser'` — the URL was handed to the system browser; drop
+ * the in-app flow;
+ * - `'cancel'` — user declined; drop silently.
+ * Optional — when omitted, non-github.com shares are dropped (fail-closed),
+ * matching the pre-GHES "invalid host" behavior. github.com shares never
+ * reach this gate.
+ */
+ gateForeignShareHost?(host: string, sharedUrl: string): Promise<ForeignHostDecision>;
/**
* Kind-aware target-existence gate, run AFTER `resolveShareTarget` returns
* `branch-match-ok` and BEFORE dispatch: probes `<projectPath>/<path>` for a
@@ -1137,6 +1162,41 @@ export function registerProtocolHandler(deps: ProtocolHandlerDeps): ProtocolHand
deps.log?.warn({ url }, '[receive] resolveShareTarget dep missing — share dropped');
return;
}
+ // Non-github.com shares must clear the foreign-host trust gate before
+ // driving resolution/clone; github.com shares skip it.
+ if (result.payload.host !== 'github.com') {
+ const gate = deps.gateForeignShareHost;
+ if (!gate) {
+ // Fail-closed: no gate wired ⇒ drop the foreign-host share.
+ deps.log?.warn(
+ { url, host: result.payload.host },
+ '[receive] foreign-host share with no gate — dropped',
+ );
+ return;
+ }
+ void gate(result.payload.host, result.payload.sharedUrl).then(
+ (decision) => {
+ if (decision === 'proceed') {
+ void resolver(result.payload).then(
+ (selection) => dispatchResolvedShare(url, result.payload, selection),
+ () => dispatchResolvedShare(url, result.payload, { kind: 'miss' }),
+ );
+ } else {
+ deps.log?.info?.(
+ { url, host: result.payload.host, decision },
+ '[receive] foreign-host share not proceeded',
+ );
+ }
+ },
+ (err) => {
+ deps.log?.warn(
+ { err: err instanceof Error ? err.message : String(err), url },
+ '[receive] foreign-host gate rejected — share dropped',
+ );
+ },
+ );
+ return;
+ }
void resolver(result.payload).then(
(selection) => dispatchResolvedShare(url, result.payload, selection),
(err) => {
diff --git a/packages/desktop/src/shared/bridge-contract.ts b/packages/desktop/src/shared/bridge-contract.ts
index 629ba3f8b..27a1397c8 100644
--- a/packages/desktop/src/shared/bridge-contract.ts
+++ b/packages/desktop/src/shared/bridge-contract.ts
@@ -683,6 +683,10 @@ export type OkLocalOpAuthReposResponse =
* shares (`ShareTarget`); the bare path is recovered via `shareTargetPath`.
*/
export interface OkSharePayloadFields {
+ /** GitHub host of the shared repo: `github.com` or a GHES hostname. Part
+ * of the receiver's repo identity, so a GHES `acme/kb` and a github.com
+ * `acme/kb` never resolve to the same local clone. */
+ readonly host: string;
readonly owner: string;
readonly repo: string;
readonly branch: string;
@@ -767,6 +771,7 @@ export type ShareFolderValidationResult =
| { readonly kind: 'not-git' }
| { readonly kind: 'no-origin' }
| { readonly kind: 'wrong-repo'; readonly actualOwner: string; readonly actualRepo: string }
+ | { readonly kind: 'wrong-host'; readonly actualHost: string }
| { readonly kind: 'non-github' }
| { readonly kind: 'symlink-escape' };
@@ -1861,6 +1866,7 @@ export interface OkDesktopBridge {
share: {
validateLocalFolder(args: {
folderPath: string;
+ host: string;
owner: string;
repo: string;
}): Promise<ShareFolderValidationResult>;
diff --git a/packages/desktop/src/shared/ipc-channels.ts b/packages/desktop/src/shared/ipc-channels.ts
index f5f3d08b5..d1a198366 100644
--- a/packages/desktop/src/shared/ipc-channels.ts
+++ b/packages/desktop/src/shared/ipc-channels.ts
@@ -229,6 +229,8 @@ interface ProjectOpenRequest {
/** Folder-validation request + result for IPC `ok:share:validate-folder`. */
interface ShareValidateFolderRequest {
readonly folderPath: string;
+ /** GitHub host the share targets: `github.com` or a GHES hostname. */
+ readonly host: string;
readonly owner: string;
readonly repo: string;
}
@@ -238,6 +240,7 @@ type ShareValidateFolderResult =
| { readonly kind: 'not-git' }
| { readonly kind: 'no-origin' }
| { readonly kind: 'wrong-repo'; readonly actualOwner: string; readonly actualRepo: string }
+ | { readonly kind: 'wrong-host'; readonly actualHost: string }
| { readonly kind: 'non-github' }
| { readonly kind: 'symlink-escape' };
diff --git a/packages/desktop/tests/main/url-scheme-handler.test.ts b/packages/desktop/tests/main/url-scheme-handler.test.ts
index 8796eed28..55e8f1025 100644
--- a/packages/desktop/tests/main/url-scheme-handler.test.ts
+++ b/packages/desktop/tests/main/url-scheme-handler.test.ts
@@ -1,7 +1,9 @@
-import { beforeEach, describe, expect, mock, test } from 'bun:test';
import type { Candidate, CandidateSelection } from '@inkeep/open-knowledge-core';
import { encodeShareUrl } from '@inkeep/open-knowledge-core';
+import type { Mock } from 'vitest';
+import { beforeEach, describe, expect, test, vi } from 'vitest';
import type {
+ ForeignHostDecision,
ScreenTarget,
ShareDeepLinkPayload,
ShareNavigatorPayload,
@@ -18,6 +20,9 @@ import { parseOpenKnowledgeFileUrl, registerProtocolHandler } from '../../src/ma
* stub.
*/
+// biome-ignore lint/suspicious/noExplicitAny: bun's `mock()` default was any-callable; the fakes below are assigned to precisely-typed SUT deps, which is where the checking happens.
+type AnyMock = Mock<(...args: any[]) => any>;
+
type AppEvent = 'open-url' | 'open-file' | 'second-instance' | 'before-quit' | 'continue-activity';
type OpenUrlListener = (event: { preventDefault: () => void }, url: string) => void;
type OpenFileListener = (event: { preventDefault: () => void }, path: string) => void;
@@ -37,20 +42,20 @@ type AppListener =
| ContinueActivityListener;
interface FakeApp {
- on: ReturnType<typeof mock>;
+ on: AnyMock;
whenReady: () => Promise<void>;
isPackaged: boolean;
- setAsDefaultProtocolClient: ReturnType<typeof mock>;
- removeAsDefaultProtocolClient: ReturnType<typeof mock>;
+ setAsDefaultProtocolClient: AnyMock;
+ removeAsDefaultProtocolClient: AnyMock;
fireOpenUrl: (url: string) => void;
- fireOpenFile: (path: string) => { preventDefault: ReturnType<typeof mock> };
+ fireOpenFile: (path: string) => { preventDefault: AnyMock };
fireSecondInstance: (argv: readonly string[]) => void;
fireBeforeQuit: () => void;
fireContinueActivity: (
type: string,
userInfo: unknown,
details?: { webpageURL?: string },
- ) => { preventDefault: ReturnType<typeof mock> };
+ ) => { preventDefault: AnyMock };
resolveReady: () => void;
}
@@ -61,25 +66,25 @@ function makeFakeApp(opts?: { isPackaged?: boolean }): FakeApp {
new Promise<void>((resolve) => {
resolveReadyFn = resolve;
});
- const on = mock((event: AppEvent, cb: AppListener) => {
+ const on = vi.fn((event: AppEvent, cb: AppListener) => {
listeners.set(event, cb);
});
return {
on,
whenReady,
isPackaged: opts?.isPackaged ?? true,
- setAsDefaultProtocolClient: mock(() => true),
- removeAsDefaultProtocolClient: mock(() => true),
+ setAsDefaultProtocolClient: vi.fn(() => true),
+ removeAsDefaultProtocolClient: vi.fn(() => true),
fireOpenUrl: (url) => {
const cb = listeners.get('open-url') as OpenUrlListener | undefined;
if (!cb) throw new Error('open-url listener not registered');
- const event = { preventDefault: mock(() => {}) };
+ const event = { preventDefault: vi.fn(() => {}) };
cb(event, url);
},
fireOpenFile: (path) => {
const cb = listeners.get('open-file') as OpenFileListener | undefined;
if (!cb) throw new Error('open-file listener not registered');
- const event = { preventDefault: mock(() => {}) };
+ const event = { preventDefault: vi.fn(() => {}) };
cb(event, path);
return event;
},
@@ -96,7 +101,7 @@ function makeFakeApp(opts?: { isPackaged?: boolean }): FakeApp {
fireContinueActivity: (type, userInfo, details) => {
const cb = listeners.get('continue-activity') as ContinueActivityListener | undefined;
if (!cb) throw new Error('continue-activity listener not registered');
- const event = { preventDefault: mock(() => {}) };
+ const event = { preventDefault: vi.fn(() => {}) };
cb(event, type, userInfo, details);
return event;
},
@@ -113,11 +118,11 @@ interface FakeWindowHandle {
interface TestEnv {
app: FakeApp;
- focusWindowForProject: ReturnType<typeof mock>;
- openProject: ReturnType<typeof mock>;
- openEphemeralFile: ReturnType<typeof mock>;
- sendDeepLink: ReturnType<typeof mock>;
- getAnyReadyWindow: ReturnType<typeof mock>;
+ focusWindowForProject: AnyMock;
+ openProject: AnyMock;
+ openEphemeralFile: AnyMock;
+ sendDeepLink: AnyMock;
+ getAnyReadyWindow: AnyMock;
timers: Array<{ cb: () => void; ms: number }>;
warnLog: Array<{ obj: object; msg: string }>;
existingWindows: Map<string, FakeWindowHandle>;
@@ -131,8 +136,8 @@ function makeEnv(opts?: { isPackaged?: boolean }): TestEnv {
const warnLog: Array<{ obj: object; msg: string }> = [];
return {
app: makeFakeApp(opts),
- focusWindowForProject: mock((p: string) => existingWindows.get(p) ?? null),
- openProject: mock(
+ focusWindowForProject: vi.fn((p: string) => existingWindows.get(p) ?? null),
+ openProject: vi.fn(
async (
p: string,
_opts?: { pendingDeepLinkDoc?: string },
@@ -143,9 +148,9 @@ function makeEnv(opts?: { isPackaged?: boolean }): TestEnv {
return win;
},
),
- openEphemeralFile: mock(async (_filePath: string): Promise<void> => {}),
- sendDeepLink: mock(() => {}),
- getAnyReadyWindow: mock(() => readyWindow),
+ openEphemeralFile: vi.fn(async (_filePath: string): Promise<void> => {}),
+ sendDeepLink: vi.fn(() => {}),
+ getAnyReadyWindow: vi.fn(() => readyWindow),
timers,
warnLog,
existingWindows,
@@ -204,7 +209,7 @@ describe('registerProtocolHandler — setAsDefaultProtocolClient', () => {
// refused the binding. Must surface as a warn so developers don't stare
// at "dev deep-links not working" without a breadcrumb.
const env = makeEnv({ isPackaged: false });
- env.app.setAsDefaultProtocolClient = mock(() => false);
+ env.app.setAsDefaultProtocolClient = vi.fn(() => false);
const warnLog: Array<{ obj: object; msg: string }> = [];
registerProtocolHandler({
app: env.app,
@@ -259,7 +264,7 @@ describe('registerProtocolHandler — before-quit Launch Services cleanup', () =
// NOT call `removeAsDefaultProtocolClient` on quit — it would remove a
// binding that another app owns, breaking their deep-links.
const env = makeEnv({ isPackaged: false });
- env.app.setAsDefaultProtocolClient = mock(() => false);
+ env.app.setAsDefaultProtocolClient = vi.fn(() => false);
registerProtocolHandler({
app: env.app,
focusWindowForProject: env.focusWindowForProject,
@@ -274,7 +279,7 @@ describe('registerProtocolHandler — before-quit Launch Services cleanup', () =
test('swallows removeAsDefaultProtocolClient throws with a warn log line', () => {
const env = makeEnv({ isPackaged: false });
- env.app.removeAsDefaultProtocolClient = mock(() => {
+ env.app.removeAsDefaultProtocolClient = vi.fn(() => {
throw new Error('launch services refused');
});
const warnLog: Array<{ obj: object; msg: string }> = [];
@@ -302,8 +307,8 @@ describe('registerProtocolHandler — deferred-share routeUrl + dedup', () => {
test('routeUrl feeds a redeemed /d/ universal link through the share spine; a near-simultaneous duplicate is deduped', async () => {
env.readyWindow = { id: 'pre-existing' };
- const resolveShareTarget = mock(async (): Promise<CandidateSelection> => ({ kind: 'miss' }));
- const routeShareToNavigator = mock(() => {});
+ const resolveShareTarget = vi.fn(async (): Promise<CandidateSelection> => ({ kind: 'miss' }));
+ const routeShareToNavigator = vi.fn(() => {});
let clock = 1_000_000;
const control = registerProtocolHandler({
@@ -349,6 +354,66 @@ describe('registerProtocolHandler — deferred-share routeUrl + dedup', () => {
});
});
+describe('registerProtocolHandler — foreign-host trust gate', () => {
+ let env: TestEnv;
+
+ beforeEach(() => {
+ env = makeEnv();
+ });
+
+ function ghesShareUrl(): string {
+ const token = encodeShareUrl('https://ghes.acme.test/acme/kb/blob/main/README.md');
+ return `https://openknowledge.ai/d/${token}`;
+ }
+
+ async function driveGhesShare(overrides: {
+ gateForeignShareHost?: (host: string, sharedUrl: string) => Promise<ForeignHostDecision>;
+ }): Promise<{ resolveShareTarget: AnyMock }> {
+ env.readyWindow = { id: 'pre-existing' };
+ const resolveShareTarget = vi.fn(async (): Promise<CandidateSelection> => ({ kind: 'miss' }));
+ const control = registerProtocolHandler({
+ app: env.app,
+ focusWindowForProject: env.focusWindowForProject,
+ openProject: env.openProject,
+ sendDeepLink: env.sendDeepLink,
+ getAnyReadyWindow: env.getAnyReadyWindow,
+ resolveShareTarget: resolveShareTarget as unknown as (
+ share: ShareUrlPayload,
+ ) => Promise<CandidateSelection>,
+ routeShareToNavigator: vi.fn(() => {}),
+ gateForeignShareHost: overrides.gateForeignShareHost,
+ setTimeout: (cb, ms) => env.timers.push({ cb, ms }),
+ now: () => 1_000_000,
+ });
+ env.app.resolveReady();
+ await flushPromises();
+ control.routeUrl(ghesShareUrl());
+ await flushPromises();
+ await flushPromises();
+ return { resolveShareTarget };
+ }
+
+ test('a foreign-host share is dropped when no gate is wired (fail-closed)', async () => {
+ const { resolveShareTarget } = await driveGhesShare({ gateForeignShareHost: undefined });
+ expect(resolveShareTarget).not.toHaveBeenCalled();
+ });
+
+ test('a foreign-host share does NOT resolve when the gate declines', async () => {
+ const gate = vi.fn(async (): Promise<ForeignHostDecision> => 'cancel');
+ const { resolveShareTarget } = await driveGhesShare({ gateForeignShareHost: gate });
+ expect(gate).toHaveBeenCalledTimes(1);
+ expect(gate.mock.calls[0][0]).toBe('ghes.acme.test');
+ expect(resolveShareTarget).not.toHaveBeenCalled();
+ });
+
+ test('a foreign-host share resolves when the gate proceeds (trusted host)', async () => {
+ const gate = vi.fn(async (): Promise<ForeignHostDecision> => 'proceed');
+ const { resolveShareTarget } = await driveGhesShare({ gateForeignShareHost: gate });
+ expect(gate).toHaveBeenCalledTimes(1);
+ expect(resolveShareTarget).toHaveBeenCalledTimes(1);
+ });
+});
+
describe('registerProtocolHandler — queue-then-flush', () => {
let env: TestEnv;
@@ -567,7 +632,7 @@ describe('registerProtocolHandler — queue-then-flush', () => {
// inside window-manager via dom-ready), so the null return just means
// "no window was created, nothing more to do." Regression assertion is
// "no throw, no stray sendDeepLink," not "sendDeepLink skipped."
- const openProjectStub = mock(
+ const openProjectStub = vi.fn(
async (
_p: string,
_opts?: { pendingDeepLinkDoc?: string },
@@ -885,7 +950,7 @@ describe('registerProtocolHandler — share-flow routing', () => {
const env = makeEnv();
const focusedWin: FakeWindowHandle = { id: 'focused' };
env.readyWindow = focusedWin;
- const resolveShareTarget = mock(async (): Promise<CandidateSelection> => ({ kind: 'miss' }));
+ const resolveShareTarget = vi.fn(async (): Promise<CandidateSelection> => ({ kind: 'miss' }));
registerProtocolHandler({
app: env.app,
@@ -907,6 +972,7 @@ describe('registerProtocolHandler — share-flow routing', () => {
// The custom-scheme URL is parsed and reaches main-side resolution.
expect(resolveShareTarget).toHaveBeenCalledTimes(1);
expect(resolveShareTarget).toHaveBeenCalledWith({
+ host: 'github.com',
owner: 'inkeep',
repo: 'playbooks',
branch: 'main',
@@ -922,7 +988,7 @@ describe('registerProtocolHandler — share-flow routing', () => {
const focusedWin: FakeWindowHandle = { id: 'focused' };
env.readyWindow = focusedWin;
const warnLog: Array<{ obj: object; msg: string }> = [];
- const sendShareDeepLink = mock((_win: FakeWindowHandle, _payload: ShareDeepLinkPayload) => {});
+ const sendShareDeepLink = vi.fn((_win: FakeWindowHandle, _payload: ShareDeepLinkPayload) => {});
registerProtocolHandler({
app: env.app,
@@ -965,7 +1031,7 @@ describe('registerProtocolHandler — share-flow routing', () => {
const focusedWin: FakeWindowHandle = { id: 'focused' };
env.readyWindow = focusedWin;
const warnLog: Array<{ obj: object; msg: string }> = [];
- const sendShareDeepLink = mock((_win: FakeWindowHandle, _payload: ShareDeepLinkPayload) => {});
+ const sendShareDeepLink = vi.fn((_win: FakeWindowHandle, _payload: ShareDeepLinkPayload) => {});
registerProtocolHandler({
app: env.app,
@@ -1000,7 +1066,7 @@ describe('registerProtocolHandler — share-flow routing', () => {
// unwired the share drops with a debuggable warn rather than guessing.
const env = makeEnv();
env.readyWindow = { id: 'ready' };
- const sendShareDeepLink = mock((_win: FakeWindowHandle, _payload: ShareDeepLinkPayload) => {});
+ const sendShareDeepLink = vi.fn((_win: FakeWindowHandle, _payload: ShareDeepLinkPayload) => {});
const warnLog: Array<{ obj: object; msg: string }> = [];
registerProtocolHandler({
@@ -1035,7 +1101,7 @@ describe('registerProtocolHandler — share-flow routing', () => {
const focusedWin: FakeWindowHandle = { id: 'focused' };
env.existingWindows.set('/tmp/p', focusedWin);
env.readyWindow = focusedWin;
- const sendShareDeepLink = mock((_win: FakeWindowHandle, _payload: ShareDeepLinkPayload) => {});
+ const sendShareDeepLink = vi.fn((_win: FakeWindowHandle, _payload: ShareDeepLinkPayload) => {});
registerProtocolHandler({
app: env.app,
@@ -1082,6 +1148,7 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
function expectedSharePayload(): ShareUrlPayload {
return {
+ host: 'github.com',
owner: 'inkeep',
repo: 'playbooks',
branch: 'main',
@@ -1118,14 +1185,14 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
test('branch-match-ok routes to openProject with pendingDeepLinkDoc + pendingMultiCandidate', async () => {
const env = makeEnv();
env.readyWindow = { id: 'pre-existing' };
- const resolveShareTarget = mock(
+ const resolveShareTarget = vi.fn(
async (_share: ShareUrlPayload): Promise<CandidateSelection> => ({
kind: 'branch-match-ok',
candidate: makeCandidate({ path: '/Users/me/playbooks', currentBranch: 'main' }),
multiCandidate: true,
}),
);
- const sendShareDeepLink = mock((_w: FakeWindowHandle, _p: ShareDeepLinkPayload) => {});
+ const sendShareDeepLink = vi.fn((_w: FakeWindowHandle, _p: ShareDeepLinkPayload) => {});
registerProtocolHandler({
app: env.app,
@@ -1160,7 +1227,7 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
test('branch-match-ok with multiCandidate=false omits the toast hint', async () => {
const env = makeEnv();
env.readyWindow = { id: 'pre-existing' };
- const resolveShareTarget = mock(
+ const resolveShareTarget = vi.fn(
async (): Promise<CandidateSelection> => ({
kind: 'branch-match-ok',
candidate: makeCandidate({ path: '/Users/me/solo-clone', currentBranch: 'main' }),
@@ -1200,7 +1267,7 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
const editorWin: FakeWindowHandle = { id: 'editor' };
env.existingWindows.set('/Users/me/playbooks', editorWin);
env.readyWindow = editorWin;
- const resolveShareTarget = mock(
+ const resolveShareTarget = vi.fn(
async (): Promise<CandidateSelection> => ({
kind: 'branch-match-ok',
candidate: makeCandidate({ path: '/Users/me/playbooks', currentBranch: 'main' }),
@@ -1241,7 +1308,7 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
const editorWin: FakeWindowHandle = { id: 'editor' };
env.existingWindows.set('/Users/me/playbooks', editorWin);
env.readyWindow = editorWin;
- const resolveShareTarget = mock(
+ const resolveShareTarget = vi.fn(
async (): Promise<CandidateSelection> => ({
kind: 'fallback',
anchor: makeCandidate({
@@ -1252,7 +1319,7 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
reason: 'main-checkout',
}),
);
- const sendShareDeepLink = mock((_w: FakeWindowHandle, _p: ShareDeepLinkPayload) => {});
+ const sendShareDeepLink = vi.fn((_w: FakeWindowHandle, _p: ShareDeepLinkPayload) => {});
registerProtocolHandler({
app: env.app,
@@ -1289,7 +1356,7 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
const editorWin: FakeWindowHandle = { id: 'editor' };
env.existingWindows.set('/Users/me/playbooks', editorWin);
env.readyWindow = editorWin;
- const resolveShareTarget = mock(
+ const resolveShareTarget = vi.fn(
async (): Promise<CandidateSelection> => ({
kind: 'fallback',
anchor: makeCandidate({
@@ -1334,7 +1401,7 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
test('fallback (cold) opens project with pendingShareBranchSwitch', async () => {
const env = makeEnv();
env.readyWindow = { id: 'some-other-editor' };
- const resolveShareTarget = mock(
+ const resolveShareTarget = vi.fn(
async (): Promise<CandidateSelection> => ({
kind: 'fallback',
anchor: makeCandidate({
@@ -1345,7 +1412,7 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
reason: 'main-checkout',
}),
);
- const sendShareDeepLink = mock((_w: FakeWindowHandle, _p: ShareDeepLinkPayload) => {});
+ const sendShareDeepLink = vi.fn((_w: FakeWindowHandle, _p: ShareDeepLinkPayload) => {});
registerProtocolHandler({
app: env.app,
@@ -1388,7 +1455,7 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
const editorWin: FakeWindowHandle = { id: 'editor' };
env.existingWindows.set('/Users/me/playbooks/worktrees/wt-1', editorWin);
env.readyWindow = editorWin;
- const resolveShareTarget = mock(
+ const resolveShareTarget = vi.fn(
async (): Promise<CandidateSelection> => ({
kind: 'fallback',
anchor: makeCandidate({
@@ -1399,7 +1466,7 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
reason: 'only-worktrees',
}),
);
- const sendShareDeepLink = mock((_w: FakeWindowHandle, _p: ShareDeepLinkPayload) => {});
+ const sendShareDeepLink = vi.fn((_w: FakeWindowHandle, _p: ShareDeepLinkPayload) => {});
registerProtocolHandler({
app: env.app,
@@ -1432,7 +1499,7 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
test('branch-match-non-ok routes to Navigator via launcher-consent payload', async () => {
const env = makeEnv();
env.readyWindow = { id: 'pre-existing' };
- const resolveShareTarget = mock(
+ const resolveShareTarget = vi.fn(
async (): Promise<CandidateSelection> => ({
kind: 'branch-match-non-ok',
candidate: makeCandidate({
@@ -1443,7 +1510,7 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
anchorRecent: null,
}),
);
- const routeShareToNavigator = mock((_p: ShareNavigatorPayload) => {});
+ const routeShareToNavigator = vi.fn((_p: ShareNavigatorPayload) => {});
registerProtocolHandler({
app: env.app,
@@ -1476,7 +1543,7 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
test('branch-match-non-ok threads anchorRecent.name through as parentProjectName', async () => {
const env = makeEnv();
env.readyWindow = { id: 'pre-existing' };
- const resolveShareTarget = mock(
+ const resolveShareTarget = vi.fn(
async (): Promise<CandidateSelection> => ({
kind: 'branch-match-non-ok',
candidate: makeCandidate({
@@ -1492,7 +1559,7 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
},
}),
);
- const routeShareToNavigator = mock((_p: ShareNavigatorPayload) => {});
+ const routeShareToNavigator = vi.fn((_p: ShareNavigatorPayload) => {});
registerProtocolHandler({
app: env.app,
@@ -1523,8 +1590,8 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
test('miss routes to Navigator via launcher-miss payload', async () => {
const env = makeEnv();
env.readyWindow = { id: 'pre-existing' };
- const resolveShareTarget = mock(async (): Promise<CandidateSelection> => ({ kind: 'miss' }));
- const routeShareToNavigator = mock((_p: ShareNavigatorPayload) => {});
+ const resolveShareTarget = vi.fn(async (): Promise<CandidateSelection> => ({ kind: 'miss' }));
+ const routeShareToNavigator = vi.fn((_p: ShareNavigatorPayload) => {});
registerProtocolHandler({
app: env.app,
@@ -1561,17 +1628,17 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
// `launcher-miss` so the share metadata + clone/locate cards appear.
const env = makeEnv();
env.readyWindow = { id: 'pre-existing' };
- const openProjectStub = mock(
+ const openProjectStub = vi.fn(
async (_p: string, _opts?: object): Promise<FakeWindowHandle | null> => null,
);
- const resolveShareTarget = mock(
+ const resolveShareTarget = vi.fn(
async (): Promise<CandidateSelection> => ({
kind: 'branch-match-ok',
candidate: makeCandidate({ path: '/Users/me/missing-project', currentBranch: 'main' }),
multiCandidate: true,
}),
);
- const routeShareToNavigator = mock((_p: ShareNavigatorPayload) => {});
+ const routeShareToNavigator = vi.fn((_p: ShareNavigatorPayload) => {});
registerProtocolHandler({
app: env.app,
@@ -1604,10 +1671,10 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
// shared and get a forward path (clone elsewhere, locate manually).
const env = makeEnv();
env.readyWindow = { id: 'some-other-editor' };
- const openProjectStub = mock(
+ const openProjectStub = vi.fn(
async (_p: string, _opts?: object): Promise<FakeWindowHandle | null> => null,
);
- const resolveShareTarget = mock(
+ const resolveShareTarget = vi.fn(
async (): Promise<CandidateSelection> => ({
kind: 'fallback',
anchor: makeCandidate({
@@ -1618,7 +1685,7 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
reason: 'main-checkout',
}),
);
- const routeShareToNavigator = mock((_p: ShareNavigatorPayload) => {});
+ const routeShareToNavigator = vi.fn((_p: ShareNavigatorPayload) => {});
registerProtocolHandler({
app: env.app,
@@ -1648,11 +1715,11 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
test('resolveShareTarget rejection degrades to Navigator (miss), not a silent drop', async () => {
const env = makeEnv();
env.readyWindow = { id: 'pre-existing' };
- const resolveShareTarget = mock(async (): Promise<CandidateSelection> => {
+ const resolveShareTarget = vi.fn(async (): Promise<CandidateSelection> => {
throw new Error('git fetch failed');
});
- const sendShareDeepLink = mock((_w: FakeWindowHandle, _p: ShareDeepLinkPayload) => {});
- const routeShareToNavigator = mock((_p: ShareNavigatorPayload) => {});
+ const sendShareDeepLink = vi.fn((_w: FakeWindowHandle, _p: ShareDeepLinkPayload) => {});
+ const routeShareToNavigator = vi.fn((_p: ShareNavigatorPayload) => {});
const warnLog: Array<{ obj: object; msg: string }> = [];
registerProtocolHandler({
@@ -1689,7 +1756,7 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
test('branch-match-non-ok with no routeShareToNavigator dep surfaces warn + no dispatch', async () => {
const env = makeEnv();
env.readyWindow = { id: 'pre-existing' };
- const resolveShareTarget = mock(
+ const resolveShareTarget = vi.fn(
async (): Promise<CandidateSelection> => ({
kind: 'branch-match-non-ok',
candidate: makeCandidate({
@@ -1730,7 +1797,7 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
// via second-instance argv, not an Apple Event. Share resolution must run.
const env = makeEnv();
env.readyWindow = { id: 'primary' };
- const resolveShareTarget = mock(async (): Promise<CandidateSelection> => ({ kind: 'miss' }));
+ const resolveShareTarget = vi.fn(async (): Promise<CandidateSelection> => ({ kind: 'miss' }));
registerProtocolHandler({
app: env.app,
@@ -1760,7 +1827,7 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
// no second-instance). The queue-then-flush path must still resolve it.
const env = makeEnv();
env.readyWindow = { id: 'pre-existing' };
- const resolveShareTarget = mock(async (): Promise<CandidateSelection> => ({ kind: 'miss' }));
+ const resolveShareTarget = vi.fn(async (): Promise<CandidateSelection> => ({ kind: 'miss' }));
registerProtocolHandler({
app: env.app,
@@ -1792,7 +1859,7 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
env.readyWindow = { id: 'ready' };
let resolveA: (s: CandidateSelection) => void = () => {};
let resolveB: (s: CandidateSelection) => void = () => {};
- const resolveShareTarget = mock(
+ const resolveShareTarget = vi.fn(
(share: ShareUrlPayload): Promise<CandidateSelection> =>
share.repo === 'repo-a'
? new Promise<CandidateSelection>((r) => {
@@ -1861,7 +1928,7 @@ describe('registerProtocolHandler — screen-flow routing', () => {
const env = makeEnv();
const focusedWin: FakeWindowHandle = { id: 'focused' };
env.readyWindow = focusedWin;
- const openScreen = mock((_win: FakeWindowHandle, _screen: ScreenTarget) => {});
+ const openScreen = vi.fn((_win: FakeWindowHandle, _screen: ScreenTarget) => {});
registerProtocolHandler({
app: env.app,
@@ -1890,7 +1957,7 @@ describe('registerProtocolHandler — screen-flow routing', () => {
const env = makeEnv();
const focusedWin: FakeWindowHandle = { id: 'focused' };
env.readyWindow = focusedWin;
- const openScreen = mock((_win: FakeWindowHandle, _screen: ScreenTarget) => {});
+ const openScreen = vi.fn((_win: FakeWindowHandle, _screen: ScreenTarget) => {});
registerProtocolHandler({
app: env.app,
@@ -1919,7 +1986,7 @@ describe('registerProtocolHandler — screen-flow routing', () => {
const env = makeEnv();
const readyWin: FakeWindowHandle = { id: 'fallback' };
env.readyWindow = readyWin;
- const openScreen = mock((_win: FakeWindowHandle, _screen: ScreenTarget) => {});
+ const openScreen = vi.fn((_win: FakeWindowHandle, _screen: ScreenTarget) => {});
registerProtocolHandler({
app: env.app,
@@ -1971,7 +2038,7 @@ describe('registerProtocolHandler — screen-flow routing', () => {
test('screen URL with no window available surfaces warn + no dispatch', async () => {
const env = makeEnv();
env.readyWindow = { id: 'ready' };
- const openScreen = mock((_win: FakeWindowHandle, _screen: ScreenTarget) => {});
+ const openScreen = vi.fn((_win: FakeWindowHandle, _screen: ScreenTarget) => {});
const warnLog: Array<{ obj: object; msg: string }> = [];
registerProtocolHandler({
@@ -1980,7 +2047,7 @@ describe('registerProtocolHandler — screen-flow routing', () => {
openProject: env.openProject,
sendDeepLink: env.sendDeepLink,
// Both window-finders return null.
- getAnyReadyWindow: mock(() => null),
+ getAnyReadyWindow: vi.fn(() => null),
openScreen,
getFocusedWindow: () => null,
setTimeout: (cb, ms) => env.timers.push({ cb, ms }),
@@ -2018,7 +2085,7 @@ describe('registerProtocolHandler — continue-activity Handoff path', () => {
const env = makeEnv();
const focusedWin: FakeWindowHandle = { id: 'focused' };
env.readyWindow = focusedWin;
- const resolveShareTarget = mock(async (): Promise<CandidateSelection> => ({ kind: 'miss' }));
+ const resolveShareTarget = vi.fn(async (): Promise<CandidateSelection> => ({ kind: 'miss' }));
registerProtocolHandler({
app: env.app,
@@ -2046,6 +2113,7 @@ describe('registerProtocolHandler — continue-activity Handoff path', () => {
// The Handoff Universal Link is parsed and reaches main-side resolution.
expect(resolveShareTarget).toHaveBeenCalledTimes(1);
expect(resolveShareTarget).toHaveBeenCalledWith({
+ host: 'github.com',
owner: 'inkeep',
repo: 'playbooks',
branch: 'main',
@@ -2058,7 +2126,7 @@ describe('registerProtocolHandler — continue-activity Handoff path', () => {
const env = makeEnv();
const focusedWin: FakeWindowHandle = { id: 'focused' };
env.readyWindow = focusedWin;
- const resolveShareTarget = mock(async (): Promise<CandidateSelection> => ({ kind: 'miss' }));
+ const resolveShareTarget = vi.fn(async (): Promise<CandidateSelection> => ({ kind: 'miss' }));
registerProtocolHandler({
app: env.app,
@@ -2090,7 +2158,7 @@ describe('registerProtocolHandler — continue-activity Handoff path', () => {
const env = makeEnv();
const focusedWin: FakeWindowHandle = { id: 'focused' };
env.readyWindow = focusedWin;
- const resolveShareTarget = mock(async (): Promise<CandidateSelection> => ({ kind: 'miss' }));
+ const resolveShareTarget = vi.fn(async (): Promise<CandidateSelection> => ({ kind: 'miss' }));
registerProtocolHandler({
app: env.app,
@@ -2120,7 +2188,7 @@ describe('registerProtocolHandler — continue-activity Handoff path', () => {
const env = makeEnv();
const focusedWin: FakeWindowHandle = { id: 'focused' };
env.readyWindow = focusedWin;
- const sendShareDeepLink = mock((_win: FakeWindowHandle, _payload: ShareDeepLinkPayload) => {});
+ const sendShareDeepLink = vi.fn((_win: FakeWindowHandle, _payload: ShareDeepLinkPayload) => {});
const warnLog: Array<{ obj: object; msg: string }> = [];
registerProtocolHandler({
@@ -2156,7 +2224,7 @@ describe('registerProtocolHandler — continue-activity Handoff path', () => {
const env = makeEnv();
const focusedWin: FakeWindowHandle = { id: 'focused' };
env.readyWindow = focusedWin;
- const sendShareDeepLink = mock((_win: FakeWindowHandle, _payload: ShareDeepLinkPayload) => {});
+ const sendShareDeepLink = vi.fn((_win: FakeWindowHandle, _payload: ShareDeepLinkPayload) => {});
const warnLog: Array<{ obj: object; msg: string }> = [];
registerProtocolHandler({
@@ -2187,7 +2255,7 @@ describe('registerProtocolHandler — continue-activity Handoff path', () => {
const env = makeEnv();
const focusedWin: FakeWindowHandle = { id: 'focused' };
env.readyWindow = focusedWin;
- const sendShareDeepLink = mock((_win: FakeWindowHandle, _payload: ShareDeepLinkPayload) => {});
+ const sendShareDeepLink = vi.fn((_win: FakeWindowHandle, _payload: ShareDeepLinkPayload) => {});
registerProtocolHandler({
app: env.app,
@@ -2213,7 +2281,7 @@ describe('registerProtocolHandler — continue-activity Handoff path', () => {
const env = makeEnv();
const focusedWin: FakeWindowHandle = { id: 'focused' };
env.readyWindow = focusedWin;
- const sendShareDeepLink = mock((_win: FakeWindowHandle, _payload: ShareDeepLinkPayload) => {});
+ const sendShareDeepLink = vi.fn((_win: FakeWindowHandle, _payload: ShareDeepLinkPayload) => {});
registerProtocolHandler({
app: env.app,
@@ -2241,7 +2309,7 @@ describe('registerProtocolHandler — continue-activity Handoff path', () => {
const env = makeEnv();
const focusedWin: FakeWindowHandle = { id: 'focused' };
env.readyWindow = focusedWin;
- const sendShareDeepLink = mock((_win: FakeWindowHandle, _payload: ShareDeepLinkPayload) => {});
+ const sendShareDeepLink = vi.fn((_win: FakeWindowHandle, _payload: ShareDeepLinkPayload) => {});
const warnLog: Array<{ obj: object; msg: string }> = [];
registerProtocolHandler({
@@ -2280,7 +2348,7 @@ describe('registerProtocolHandler — continue-activity Handoff path', () => {
const env = makeEnv();
const focusedWin: FakeWindowHandle = { id: 'focused' };
env.readyWindow = focusedWin;
- const resolveShareTarget = mock(async (): Promise<CandidateSelection> => ({ kind: 'miss' }));
+ const resolveShareTarget = vi.fn(async (): Promise<CandidateSelection> => ({ kind: 'miss' }));
registerProtocolHandler({
app: env.app,
@@ -2316,7 +2384,7 @@ describe('registerProtocolHandler — continue-activity Handoff path', () => {
const focusedWin: FakeWindowHandle = { id: 'focused' };
env.existingWindows.set('/tmp/p', focusedWin);
env.readyWindow = focusedWin;
- const resolveShareTarget = mock(async (): Promise<CandidateSelection> => ({ kind: 'miss' }));
+ const resolveShareTarget = vi.fn(async (): Promise<CandidateSelection> => ({ kind: 'miss' }));
registerProtocolHandler({
app: env.app,
diff --git a/packages/server/src/api-extension.test.ts b/packages/server/src/api-extension.test.ts
index 3eb61aae1..2c3687a62 100644
--- a/packages/server/src/api-extension.test.ts
+++ b/packages/server/src/api-extension.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, symlinkSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { resumeSyncOnAuthEvent, safeSubdir, sanitizeFilename } from './api-extension.ts';
import type { AuthEvent } from './local-ops/types.ts';
import { listenOnLoopback } from './loopback-rig-test-helpers.ts';
@@ -663,13 +663,20 @@ describe('resumeSyncOnAuthEvent (reconnect → resume wiring)', () => {
// the subprocess, the streaming response, and the concurrency guard.
const makeEngineStub = (impl?: () => Promise<void>) => {
const calls: number[] = [];
+ const refreshCalls: number[] = [];
const engine = {
notifyCredentialsChanged: () => {
calls.push(Date.now());
return impl ? impl() : Promise.resolve();
},
+ // A reconnect must also re-probe push permission — a repo paused with
+ // 'no-push-permission' while signed out has to resume without a restart.
+ refreshPushPermission: () => {
+ refreshCalls.push(Date.now());
+ return Promise.resolve(null);
+ },
} as unknown as SyncEngine;
- return { engine, calls, getSyncEngine: () => engine };
+ return { engine, calls, refreshCalls, getSyncEngine: () => engine };
};
const completeEvent: AuthEvent = { type: 'complete', host: 'github.com', login: 'octocat' };
@@ -681,17 +688,21 @@ describe('resumeSyncOnAuthEvent (reconnect → resume wiring)', () => {
};
const errorEvent: AuthEvent = { type: 'error', message: 'denied' };
- test('a complete event resumes sync via notifyCredentialsChanged', () => {
+ test('a complete event resumes sync AND re-probes push permission', () => {
const stub = makeEngineStub();
resumeSyncOnAuthEvent(completeEvent, stub.getSyncEngine);
expect(stub.calls.length).toBe(1);
+ // The reconnect must re-probe push permission too, or a repo paused with
+ // 'no-push-permission' while signed out stays stuck until an app restart.
+ expect(stub.refreshCalls.length).toBe(1);
});
- test('non-complete events do not resume sync', () => {
+ test('non-complete events do not resume sync or re-probe', () => {
const stub = makeEngineStub();
resumeSyncOnAuthEvent(verificationEvent, stub.getSyncEngine);
resumeSyncOnAuthEvent(errorEvent, stub.getSyncEngine);
expect(stub.calls.length).toBe(0);
+ expect(stub.refreshCalls.length).toBe(0);
});
test('absent getSyncEngine is a no-op (engine dormant / not yet constructed)', () => {
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index 203bf9bb1..681416dac 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -117,6 +117,8 @@ import {
LocalOpAuthEmptySuccessSchema,
type LocalOpAuthHostRequest,
LocalOpAuthHostRequestSchema,
+ LocalOpAuthPatRequestSchema,
+ LocalOpAuthPatSuccessSchema,
LocalOpAuthSetIdentityRequestSchema,
LocalOpAuthStatusSuccessSchema,
type LocalOpCloneRequest,
@@ -534,9 +536,12 @@ import {
} from './local-op-security.ts';
import {
type AuthEvent,
+ cachedGhBinaryPath,
classifyCloneError,
runCloneSubprocess,
runDeviceFlowSubprocess,
+ runGhDeviceLoginSubprocess,
+ runPatSubprocess,
} from './local-ops/index.ts';
import { getLogger } from './logger.ts';
import { isAllowedWorkspaceHostHeader, isLoopbackAddress } from './loopback.ts';
@@ -770,16 +775,40 @@ export function __resetRenameTelemetryForTesting(): void {
* Best-effort: a rejected promise is swallowed because sync status catches up on
* the next cycle or restart. Non-`complete` events are ignored.
*/
+/**
+ * Server-authoritative "a GitHub credential just landed" hook. A fresh sign-in
+ * (OK device flow, gh browser flow, or PAT) can change TWO independent bits of
+ * sync state, and healing only one silently under-recovers:
+ *
+ * - a SyncEngine parked in `auth-error` (invalid / missing token) →
+ * `notifyCredentialsChanged()` un-parks it; and
+ * - a push-permission verdict of `denied` that paused the engine with
+ * `no-push-permission` while signed out → `refreshPushPermission()` re-probes
+ * so an now-pushable repo clears the pause and sync resumes.
+ *
+ * The second was the gap: connect never re-probed permission, so a repo that
+ * probed `denied` while signed out stayed paused ("you don't have permission to
+ * push") until an app restart, even after a successful reconnect. Both calls are
+ * best-effort and idempotent — a lost signal just heals on the next cycle /
+ * restart. Shared by the streaming (device/gh) and PAT sign-in paths.
+ */
+function onAuthCredentialLanded(getSyncEngine?: () => SyncEngine | null): void {
+ const engine = getSyncEngine?.();
+ if (!engine) return;
+ void engine.notifyCredentialsChanged().catch(() => {
+ /* best-effort — sync status catches up next cycle / restart */
+ });
+ void engine.refreshPushPermission().catch(() => {
+ /* best-effort — the verdict refreshes on the next probe / restart */
+ });
+}
+
export function resumeSyncOnAuthEvent(
event: AuthEvent,
getSyncEngine?: () => SyncEngine | null,
): void {
if (event.type !== 'complete') return;
- void getSyncEngine?.()
- ?.notifyCredentialsChanged()
- .catch(() => {
- /* best-effort — sync status catches up next cycle / restart */
- });
+ onAuthCredentialLanded(getSyncEngine);
}
/**
@@ -12032,6 +12061,8 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
const LOCAL_OP_AUTH_STATUS_KEY = '/api/local-op/auth/status';
const LOCAL_OP_AUTH_REPOS_KEY = '/api/local-op/auth/repos';
const LOCAL_OP_AUTH_SIGNOUT_KEY = '/api/local-op/auth/signout';
+ const LOCAL_OP_AUTH_PAT_KEY = '/api/local-op/auth/pat';
+ const LOCAL_OP_AUTH_GH_LOGIN_KEY = '/api/local-op/auth/gh-login';
/**
* Default host for the auth relay endpoints when the request omits `host`.
@@ -12040,84 +12071,72 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
*/
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:
- // only the current owner releases the slot, so a displaced/disconnected flow
- // can never free a successor's slot. Mirrors the IPC twin's `authInFlight`
- // (desktop/src/main/ipc/local-op.ts).
- let authLoginInFlight: ReturnType<typeof runDeviceFlowSubprocess> | null = null;
+ // In-flight controllers for the two streaming auth flows (device-flow login and
+ // gh-login). A disconnect or fresh start frees/displaces the slot synchronously
+ // instead of waiting for the cancelled child to exit. Object identity is the
+ // ownership token: only the current owner releases its slot, so a displaced/
+ // disconnected flow can never free a successor's. Held in `{ current }` refs so
+ // the shared `streamAuthFlow` helper below can mutate them by reference.
+ // Mirrors the IPC twin's `authInFlight` (desktop/src/main/ipc/local-op.ts).
+ type StreamingAuthController = { done: Promise<void>; cancel(): void };
+ const authLoginInFlight: { current: StreamingAuthController | null } = { current: null };
+ const authGhLoginInFlight: { current: StreamingAuthController | null } = { current: null };
/**
- * POST /api/local-op/auth/login
- *
- * Body: { host?: string }
- * Spawns: auth login --json [--host <host>]
- * Streams: NDJSON lines (verification + complete events) via chunked HTTP.
- * The device-flow subprocess manages its own timeout.
- *
- * Streaming endpoint: pre-stream errors emit
- * `application/problem+json`; mid-stream errors emit a typed event
- * `{ type: 'error', problem: ProblemDetails }`. The CLI's own
- * `{ type: 'error', message }` events are intercepted and wrapped so the
- * client always sees the canonical streaming envelope.
+ * Shared streaming envelope for the auth flows. The flows themselves differ —
+ * device-flow login runs OK's `auth login` (github.com-only OAuth app, token →
+ * OK's store) while gh-login runs `gh auth login --web` (gh's OAuth app, works
+ * on GHES, token → gh keyring → tier A) — so the caller supplies `makeFlow`.
+ * Everything else is identical and lives here once: the concurrency slot with
+ * displace-on-restart, NDJSON streaming, client-disconnect cancel, sync-resume,
+ * and the ownership-guarded slot release.
*/
- const HANDLE_LOCAL_OP_AUTH_LOGIN = 'local-op-auth-login';
- const handleLocalOpAuthLogin = withValidation(
- LocalOpAuthHostRequestSchema,
- handleLocalOpAuthLoginInner,
- {
- handler: HANDLE_LOCAL_OP_AUTH_LOGIN,
- method: 'POST',
- preBodyGate: (req, res) =>
- checkLocalOpSecurity(req, res, { handler: HANDLE_LOCAL_OP_AUTH_LOGIN }),
- },
- );
- async function handleLocalOpAuthLoginInner(
- _req: IncomingMessage,
- res: ServerResponse,
- body: LocalOpAuthHostRequest,
- ): Promise<void> {
- const host = body.host ?? defaultAuthHost();
-
- if (!localOpGuard.tryAcquire(LOCAL_OP_AUTH_LOGIN_KEY)) {
- const stale = authLoginInFlight;
+ function streamAuthFlow(cfg: {
+ res: ServerResponse;
+ handler: string;
+ guardKey: string;
+ inFlight: { current: StreamingAuthController | null };
+ concurrentMessage: string;
+ streamErrorMessage: string;
+ makeFlow: (onEvent: (event: AuthEvent) => void) => StreamingAuthController;
+ }): void {
+ const { res, handler, guardKey, inFlight, concurrentMessage, streamErrorMessage, makeFlow } =
+ cfg;
+
+ if (!localOpGuard.tryAcquire(guardKey)) {
+ const stale = inFlight.current;
if (!stale) {
- // Structurally unreachable: the Set key and `authLoginInFlight` are
+ // Structurally unreachable: the slot key and `inFlight.current` are
// assigned with no `await` between them, so a held slot always has a
- // controller. Log at `error` (a distinct event, not a 429 that looks
- // like normal concurrency) so a refactor that breaks that coupling is
- // diagnosable, then keep the 429 as the loud fallback rather than
- // silently re-owning a slot whose owner we can't identify.
+ // controller. Log at `error` (a distinct event, not a normal-concurrency
+ // 429) so a refactor breaking that coupling is diagnosable, then 429 as
+ // the loud fallback rather than silently re-owning an unidentifiable slot.
console.error(
JSON.stringify({
- event: 'ok-local-op:auth-login-slot-no-controller',
+ event: 'ok-local-op:auth-flow-slot-no-controller',
channel: 'auth',
transport: 'http',
+ handler,
}),
);
- errorResponse(
- res,
- 429,
- 'urn:ok:error:concurrent-operation',
- 'An auth login operation is already in progress.',
- { handler: HANDLE_LOCAL_OP_AUTH_LOGIN, extraHeaders: { 'Retry-After': '5' } },
- );
+ errorResponse(res, 429, 'urn:ok:error:concurrent-operation', concurrentMessage, {
+ handler,
+ extraHeaders: { 'Retry-After': '5' },
+ });
return;
}
- // A missed/late disconnect left a stale login holding the slot. Displace
- // it so a fresh login is always admittable: SIGTERM the stale child so it
- // can't keep polling and write an unconfirmed token, then re-own the slot
- // (the Set key stays held — this request claims it below). The displacement
- // is logged at `warn` because it signals the disconnect cleanup was missed,
- // so ops can grep for it before users hit a stuck slot.
+ // A missed/late disconnect left a stale flow holding the slot. Displace it
+ // (SIGTERM the child so it can't keep polling and write an unconfirmed
+ // token), then re-own the slot below. Logged at `warn` so a missed
+ // disconnect is greppable before users hit a stuck slot.
stale.cancel();
- authLoginInFlight = null;
+ inFlight.current = null;
console.warn(
JSON.stringify({
event: 'ok-local-op:idempotent-start-replaced-stale-slot',
channel: 'auth',
transport: 'http',
+ handler,
}),
);
}
@@ -12128,86 +12147,161 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
'X-Content-Type-Options': 'nosniff',
'Cache-Control': 'no-cache',
});
+ // Wrap raw `error` events in the RFC 9457 streaming envelope.
+ const writeStreamError = createStreamingErrorWriter(res, handler);
- // Wrap CLI raw `error` events in RFC 9457 streaming envelope.
- const writeStreamError = createStreamingErrorWriter(res, HANDLE_LOCAL_OP_AUTH_LOGIN);
-
- const flow = runDeviceFlowSubprocess({
- cliArgs: localOpCliArgs,
- host,
- timeoutMs: LOCAL_OP_TIMEOUT_MS,
- onEvent: (event: AuthEvent) => {
- if (event.type === 'error') {
- writeStreamError(500, 'urn:ok:error:auth-failed', 'Auth subprocess reported an error.', {
- cause: event.message ? new Error(event.message) : undefined,
- });
- return;
- }
- // On `complete`, resume a SyncEngine parked in `auth-error` so a
- // reconnect restores sync without an app restart. Server-authoritative:
- // works regardless of which UI surface (sync badge or Settings →
- // Account) ran the login.
- resumeSyncOnAuthEvent(event, getSyncEngine);
- // Three-way guard + try-catch matches `createStreamingErrorWriter`
- // race-window defense. Lost progress event is not crashworthy.
- if (!res.writableEnded && !res.destroyed) {
- try {
- res.write(`${JSON.stringify(event)}\n`);
- } catch {
- /* socket destroyed between guard and write — event lost */
- }
+ const flow = makeFlow((event: AuthEvent) => {
+ if (event.type === 'error') {
+ writeStreamError(500, 'urn:ok:error:auth-failed', streamErrorMessage, {
+ cause: event.message ? new Error(event.message) : undefined,
+ });
+ return;
+ }
+ // On `complete`, resume a SyncEngine parked in `auth-error` so a reconnect
+ // restores sync without an app restart. Server-authoritative: works
+ // regardless of which UI surface ran the sign-in.
+ resumeSyncOnAuthEvent(event, getSyncEngine);
+ // Three-way guard + try-catch matches the writer's race-window defense; a
+ // lost progress event is not crashworthy.
+ if (!res.writableEnded && !res.destroyed) {
+ try {
+ res.write(`${JSON.stringify(event)}\n`);
+ } catch {
+ /* socket destroyed between guard and write — event lost */
}
- },
+ }
});
- authLoginInFlight = flow;
+ inFlight.current = flow;
- // Kill the child if the client disconnects so `auth login` doesn't keep
- // polling in the background and write a token to the keychain that the
- // user never saw confirmation for.
+ // Kill the child if the client disconnects so the flow doesn't keep polling
+ // and write a token the user never saw confirmed. Free the slot synchronously
+ // (ownership-guarded) rather than waiting for the SIGTERM'd child to exit —
+ // that window would otherwise 429 a reopen.
const onClientClose = () => {
flow.cancel();
- // Free the slot synchronously rather than waiting for the cancelled
- // child to exit — the SIGTERM-to-exit window would otherwise 429 a
- // reopen. Ownership-guarded so we only release a slot we still own.
- if (authLoginInFlight === flow) {
- authLoginInFlight = null;
- localOpGuard.release(LOCAL_OP_AUTH_LOGIN_KEY);
+ if (inFlight.current === flow) {
+ inFlight.current = null;
+ localOpGuard.release(guardKey);
}
};
res.on('close', onClientClose);
- // Sibling clone handler at handleLocalOpClone wraps an equivalent
- // cleanup in a full `void (async () => { try {...} catch {...} finally {...} })()`
- // IIFE because clone has post-flow work (`startServerAtDirAndGetPort`)
- // that can genuinely throw. Auth-login has no post-flow work and
- // `flow.done` cannot reject — `proc.done` (local-ops/subprocess.ts) only
- // ever resolves, and the `.then` callback deriving `flow.done` only calls
- // `opts.onEvent`, which is throw-safe here (both the writeStreamError and
- // the res.write branches carry their own try/catch). So the simpler
- // `.finally()` form needs no IIFE-level try/catch — the asymmetry is
- // intentional, not a missing safeguard. The release is ownership-guarded:
- // a displaced/disconnected flow that already freed or handed off the slot
- // must not release a successor's slot when its child finally exits.
+ // `flow.done` cannot reject (`proc.done` only resolves; the onEvent callback
+ // is throw-safe), so `.finally` needs no IIFE-level try/catch. The release is
+ // ownership-guarded: a displaced/disconnected flow that already freed or
+ // handed off the slot must not release a successor's when its child exits.
void flow.done.finally(() => {
res.off('close', onClientClose);
- // Same guard + try-catch as the `onEvent` writer above: the socket can be
- // destroyed between this check and `res.end()` (client gone), and an
- // uncaught throw would skip the ownership-guarded release below — the
- // exact orphaned-slot failure this handler exists to prevent.
if (!res.writableEnded && !res.destroyed) {
try {
res.end();
} catch {
- /* socket destroyed between guard and end — response already closed */
+ /* socket destroyed between guard and end — already closed */
}
}
- if (authLoginInFlight === flow) {
- authLoginInFlight = null;
- localOpGuard.release(LOCAL_OP_AUTH_LOGIN_KEY);
+ if (inFlight.current === flow) {
+ inFlight.current = null;
+ localOpGuard.release(guardKey);
}
});
}
+ /**
+ * POST /api/local-op/auth/login
+ *
+ * Body: { host?: string }
+ * Spawns: auth login --json [--host <host>]
+ * Streams: NDJSON lines (verification + complete events) via chunked HTTP.
+ * The device-flow subprocess manages its own timeout.
+ *
+ * Streaming endpoint: pre-stream errors emit
+ * `application/problem+json`; mid-stream errors emit a typed event
+ * `{ type: 'error', problem: ProblemDetails }`. The CLI's own
+ * `{ type: 'error', message }` events are intercepted and wrapped so the
+ * client always sees the canonical streaming envelope.
+ */
+ const HANDLE_LOCAL_OP_AUTH_LOGIN = 'local-op-auth-login';
+ const handleLocalOpAuthLogin = withValidation(
+ LocalOpAuthHostRequestSchema,
+ handleLocalOpAuthLoginInner,
+ {
+ handler: HANDLE_LOCAL_OP_AUTH_LOGIN,
+ method: 'POST',
+ preBodyGate: (req, res) =>
+ checkLocalOpSecurity(req, res, { handler: HANDLE_LOCAL_OP_AUTH_LOGIN }),
+ },
+ );
+ async function handleLocalOpAuthLoginInner(
+ _req: IncomingMessage,
+ res: ServerResponse,
+ body: LocalOpAuthHostRequest,
+ ): Promise<void> {
+ const host = body.host ?? defaultAuthHost();
+ streamAuthFlow({
+ res,
+ handler: HANDLE_LOCAL_OP_AUTH_LOGIN,
+ guardKey: LOCAL_OP_AUTH_LOGIN_KEY,
+ inFlight: authLoginInFlight,
+ concurrentMessage: 'An auth login operation is already in progress.',
+ streamErrorMessage: 'Auth subprocess reported an error.',
+ makeFlow: (onEvent) =>
+ runDeviceFlowSubprocess({
+ cliArgs: localOpCliArgs,
+ host,
+ timeoutMs: LOCAL_OP_TIMEOUT_MS,
+ onEvent,
+ }),
+ });
+ }
+
+ /**
+ * POST /api/local-op/auth/gh-login
+ *
+ * Body: { host?: string }
+ * Runs `gh auth login --hostname <host> --web` and streams the same
+ * verification / complete / error NDJSON as the device flow. gh's OAuth app is
+ * preregistered on GHES (OpenKnowledge's isn't), so this gives enterprise hosts
+ * a browser sign-in; gh stores the token in its keyring and OK reads it via
+ * tier A. 400 if gh isn't installed (the UI falls back to the PAT panel).
+ */
+ const HANDLE_LOCAL_OP_AUTH_GH_LOGIN = 'local-op-auth-gh-login';
+ const handleLocalOpAuthGhLogin = withValidation(
+ LocalOpAuthHostRequestSchema,
+ async (_req, res, body) => {
+ const host = body.host ?? defaultAuthHost();
+ const ghPath = await cachedGhBinaryPath();
+ if (ghPath === null) {
+ // Precondition failure — the UI falls back to the PAT panel. Reuse the
+ // auth-failed URN (the detail names the specific cause).
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:auth-failed',
+ 'The GitHub CLI (gh) is not installed.',
+ { handler: HANDLE_LOCAL_OP_AUTH_GH_LOGIN },
+ );
+ return;
+ }
+
+ streamAuthFlow({
+ res,
+ handler: HANDLE_LOCAL_OP_AUTH_GH_LOGIN,
+ guardKey: LOCAL_OP_AUTH_GH_LOGIN_KEY,
+ inFlight: authGhLoginInFlight,
+ concurrentMessage: 'A gh sign-in is already in progress.',
+ streamErrorMessage: 'gh sign-in reported an error.',
+ makeFlow: (onEvent) =>
+ runGhDeviceLoginSubprocess({ host, ghPath, timeoutMs: LOCAL_OP_TIMEOUT_MS, onEvent }),
+ });
+ },
+ {
+ handler: HANDLE_LOCAL_OP_AUTH_GH_LOGIN,
+ method: 'POST',
+ preBodyGate: (req, res) =>
+ checkLocalOpSecurity(req, res, { handler: HANDLE_LOCAL_OP_AUTH_GH_LOGIN }),
+ },
+ );
+
/**
* POST /api/local-op/auth/status
*
@@ -12288,16 +12382,24 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
/* skip non-JSON line */
}
}
+ // `ghAvailable` tells the UI whether to offer "Sign in with gh" (the
+ // browser path that works on GHES where OK's device flow can't). Machine
+ // property, not per-host; cached so this frequent probe doesn't re-shell.
+ const ghAvailable = (await cachedGhBinaryPath()) !== null;
if (parsed !== null) {
- successResponse(res, 200, LocalOpAuthStatusSuccessSchema, parsed, {
- handler: HANDLE_LOCAL_OP_AUTH_STATUS,
- });
+ successResponse(
+ res,
+ 200,
+ LocalOpAuthStatusSuccessSchema,
+ { ...(parsed as Record<string, unknown>), ghAvailable },
+ { handler: HANDLE_LOCAL_OP_AUTH_STATUS },
+ );
} else {
successResponse(
res,
200,
LocalOpAuthStatusSuccessSchema,
- { authenticated: false },
+ { authenticated: false, ghAvailable },
{ handler: HANDLE_LOCAL_OP_AUTH_STATUS },
);
}
@@ -12321,6 +12423,75 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
},
);
+ /**
+ * POST /api/local-op/auth/pat
+ *
+ * Body: { host?: string, token: string }
+ * Spawns: auth pat --json --host <host> --token-stdin (token via stdin).
+ * Returns: { host, login } on success; 400 auth-failed with a bounded reason
+ * on a rejected token / TLS / network error.
+ *
+ * The enterprise sign-in path — a GHES host stores a PAT because the OAuth
+ * device flow only works on github.com. The token is written to the child's
+ * stdin, never argv/env.
+ */
+ const HANDLE_LOCAL_OP_AUTH_PAT = 'local-op-auth-pat';
+ const handleLocalOpAuthPat = withValidation(
+ LocalOpAuthPatRequestSchema,
+ async (_req, res, body) => {
+ const host = body.host ?? defaultAuthHost();
+
+ if (!localOpGuard.tryAcquire(LOCAL_OP_AUTH_PAT_KEY)) {
+ errorResponse(
+ res,
+ 429,
+ 'urn:ok:error:concurrent-operation',
+ 'An auth operation is already in progress.',
+ { handler: HANDLE_LOCAL_OP_AUTH_PAT, extraHeaders: { 'Retry-After': '5' } },
+ );
+ return;
+ }
+
+ try {
+ const result = await runPatSubprocess({ cliArgs: localOpCliArgs, host, token: body.token });
+ if (result.ok) {
+ // A stored PAT is a credential change just like a device/gh sign-in —
+ // re-probe so a repo paused with 'no-push-permission' while signed out
+ // resumes without an app restart. The streaming paths get this via
+ // resumeSyncOnAuthEvent; PAT is a plain POST, so call it directly.
+ onAuthCredentialLanded(getSyncEngine);
+ successResponse(
+ res,
+ 200,
+ LocalOpAuthPatSuccessSchema,
+ { host: result.host, login: result.login },
+ { handler: HANDLE_LOCAL_OP_AUTH_PAT },
+ );
+ } else {
+ // A rejected token / cert / network failure is client-actionable, not
+ // a server fault. `result.error` is bounded (the CLI's structured
+ // describeAuthFailure message), safe to surface.
+ errorResponse(res, 400, 'urn:ok:error:auth-failed', result.error, {
+ handler: HANDLE_LOCAL_OP_AUTH_PAT,
+ });
+ }
+ } catch (err) {
+ errorResponse(res, 500, 'urn:ok:error:auth-failed', 'Storing the token failed.', {
+ handler: HANDLE_LOCAL_OP_AUTH_PAT,
+ cause: err,
+ });
+ } finally {
+ localOpGuard.release(LOCAL_OP_AUTH_PAT_KEY);
+ }
+ },
+ {
+ handler: HANDLE_LOCAL_OP_AUTH_PAT,
+ method: 'POST',
+ preBodyGate: (req, res) =>
+ checkLocalOpSecurity(req, res, { handler: HANDLE_LOCAL_OP_AUTH_PAT }),
+ },
+ );
+
/**
* POST /api/local-op/auth/repos
*
@@ -17382,9 +17553,11 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
);
return;
}
- // `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') {
+ // Known non-GitHub forges (gitlab, bitbucket) can't produce a GitHub
+ // share URL. GitHub hosts — github.com AND GHES — are supported: the
+ // builders below take `origin.host` and the receive side accepts the
+ // enterprise host behind its trust gate.
+ if (origin.kind === 'non-github') {
emitShareConstructUrlLog('non-github-remote', { kind: body.kind });
successResponse(
res,
@@ -17438,14 +17611,20 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
}
let sharedUrl: string;
if (body.kind === 'doc') {
- sharedUrl = buildGitHubBlobUrl(origin.owner, origin.repo, branch, body.docPath);
+ sharedUrl = buildGitHubBlobUrl(
+ origin.host,
+ origin.owner,
+ origin.repo,
+ branch,
+ body.docPath,
+ );
} else {
// Folder ROOT (empty folderPath) maps to the content dir:
// `tree/<branch>/<content.dir>`, degenerating to `tree/<branch>`
// when `content.dir === '.'` (contentRel is '' then). Non-root folder
// paths pass straight through.
const treePath = body.folderPath === '' ? contentRel : body.folderPath;
- sharedUrl = buildGitHubTreeUrl(origin.owner, origin.repo, branch, treePath);
+ sharedUrl = buildGitHubTreeUrl(origin.host, origin.owner, origin.repo, branch, treePath);
}
const shareUrl = `${SHARE_BASE_URL}${encodeShareUrl(sharedUrl)}`;
// Freshness probes the repo-relative path of the shared target: it
@@ -18964,6 +19143,8 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
'/api/local-op/ok-init': handleLocalOpOkInit,
'/api/local-op/auth/login': handleLocalOpAuthLogin,
'/api/local-op/auth/status': handleLocalOpAuthStatus,
+ '/api/local-op/auth/pat': handleLocalOpAuthPat,
+ '/api/local-op/auth/gh-login': handleLocalOpAuthGhLogin,
'/api/local-op/auth/repos': handleLocalOpAuthRepos,
'/api/local-op/auth/signout': handleLocalOpAuthSignout,
'/api/local-op/auth/set-identity': handleLocalOpAuthSetIdentity,
diff --git a/packages/server/src/github-permissions.test.ts b/packages/server/src/github-permissions.test.ts
index 564ad482c..4dba0c0d8 100644
--- a/packages/server/src/github-permissions.test.ts
+++ b/packages/server/src/github-permissions.test.ts
@@ -6,7 +6,7 @@
* logic is exercised for real. Telemetry assertions use the InMemoryMetric
* harness from `frontmatter-telemetry.test.ts`.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+
import { metrics } from '@opentelemetry/api';
import {
AggregationTemporality,
@@ -16,6 +16,7 @@ import {
MeterProvider,
PeriodicExportingMetricReader,
} from '@opentelemetry/sdk-metrics';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
__resetGithubPermissionsTelemetryForTests,
checkPushPermission,
@@ -274,7 +275,7 @@ describe('checkPushPermission — token resolution', () => {
expect(hosts).toEqual(['github.com']);
});
- test('anonymous: no credential → denied/no-collaborator with NO HTTP call (short-circuit)', async () => {
+ test('anonymous: no credential → denied/not-authenticated with NO HTTP call (short-circuit)', async () => {
const { fetch, calls } = mockFetch(() => jsonResponse(200, {}));
const { store } = fakeStore(null);
const result = await checkPushPermission({
@@ -284,7 +285,9 @@ describe('checkPushPermission — token resolution', () => {
tokenStore: store,
_fetchFn: fetch,
});
- expect(result).toEqual({ kind: 'denied', reason: 'no-collaborator' });
+ // Signed-out — distinct from a working-but-read-only credential so the UI
+ // can offer a reconnect affordance.
+ expect(result).toEqual({ kind: 'denied', reason: 'not-authenticated' });
expect(calls).toHaveLength(0); // no credential ⇒ no push ⇒ no probe
});
@@ -295,7 +298,7 @@ describe('checkPushPermission — token resolution', () => {
repo: 'open-knowledge',
_fetchFn: fetch,
});
- expect(result).toEqual({ kind: 'denied', reason: 'no-collaborator' });
+ expect(result).toEqual({ kind: 'denied', reason: 'not-authenticated' });
expect(calls).toHaveLength(0);
});
diff --git a/packages/server/src/github-permissions.ts b/packages/server/src/github-permissions.ts
index e570620fe..6d1c80fbf 100644
--- a/packages/server/src/github-permissions.ts
+++ b/packages/server/src/github-permissions.ts
@@ -26,7 +26,15 @@ const PROBE_TIMEOUT_MS = 5000;
export type FetchFn = typeof fetch;
-type PushPermissionDeniedReason = 'no-collaborator' | 'private-no-access' | 'repo-not-found';
+// 'not-authenticated' = no credential resolved at all (signed out), distinct
+// from 'no-collaborator' (a working credential that lacks push access). The UI
+// keys off it to offer a reconnect affordance — reconnecting fixes signed-out,
+// but not a genuine read-only collaborator.
+type PushPermissionDeniedReason =
+ | 'no-collaborator'
+ | 'private-no-access'
+ | 'repo-not-found'
+ | 'not-authenticated';
type PushPermissionUnknownError =
| 'network'
@@ -219,7 +227,9 @@ async function runProbe(opts: CheckPushPermissionOptions): Promise<PushPermissio
// instead land directly in the suppressed-onboarding, no-push UX.
if (tokenSource === 'anonymous') {
log.info({ host }, '[permissions] no credential resolved — denying push (read-only)');
- return { kind: 'denied', reason: 'no-collaborator' };
+ // 'not-authenticated' (not 'no-collaborator'): reconnecting resolves this,
+ // so the UI can offer a sign-in affordance rather than a dead-end.
+ return { kind: 'denied', reason: 'not-authenticated' };
}
const url = `${githubApiBase(host)}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`;
@@ -309,7 +319,7 @@ let _outcomeCounter: Counter | null = null;
function outcomeCounter(): Counter {
_outcomeCounter ||= getMeter().createCounter('ok.permissions.probe.outcome_total', {
description:
- 'Push-permission probe outcomes. Bounded labels: outcome ∈ {allowed,denied,unknown}; denied_reason ∈ {no-collaborator,private-no-access,repo-not-found,none}; error_class ∈ {network,timeout,rate-limit,token-invalid,malformed-response,none}.',
+ 'Push-permission probe outcomes. Bounded labels: outcome ∈ {allowed,denied,unknown}; denied_reason ∈ {no-collaborator,private-no-access,repo-not-found,not-authenticated,none}; error_class ∈ {network,timeout,rate-limit,token-invalid,malformed-response,none}.',
});
return _outcomeCounter;
}
diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts
index 54d95e4d4..8e771d423 100644
--- a/packages/server/src/index.ts
+++ b/packages/server/src/index.ts
@@ -586,6 +586,7 @@ export {
type ToleranceFireLine,
teardownToleranceTelemetryWriter,
} from './tolerance-telemetry-writer.ts';
+export { trustSystemCertificates } from './trust-system-ca.ts';
export {
acquireUiLock,
readUiLock,
diff --git a/packages/server/src/local-ops/auth-pat.test.ts b/packages/server/src/local-ops/auth-pat.test.ts
new file mode 100644
index 000000000..64482ea81
--- /dev/null
+++ b/packages/server/src/local-ops/auth-pat.test.ts
@@ -0,0 +1,58 @@
+/**
+ * PAT runner — covers the stdin token hand-off, the complete/error JSON
+ * parsing, and the generic fallback on an unexpected exit.
+ *
+ * Fixture subprocesses are spawned via `process.execPath -e <script>` so the
+ * tests exercise the real spawn + stdin-write + NDJSON-parse path.
+ */
+import { describe, expect, test } from 'vitest';
+import { runPatSubprocess } from './auth-pat.ts';
+
+const fixtureCli = (script: string): readonly string[] => [process.execPath, '-e', script];
+
+// Reads stdin to EOF; echoes it into the `login` on success so the test can
+// prove the token reached the child over stdin (not argv/env).
+const ECHO_STDIN_CLI = `
+let d='';
+process.stdin.on('data', c => { d += c; });
+process.stdin.on('end', () => {
+ if (d.trim() === 'good-token') {
+ process.stdout.write(JSON.stringify({ type: 'complete', host: 'ghes.test', login: 'got:' + d.trim() }) + '\\n');
+ process.exit(0);
+ }
+ process.stdout.write(JSON.stringify({ type: 'error', message: 'Token invalid for ghes.test' }) + '\\n');
+ process.exit(1);
+});
+`;
+
+describe('runPatSubprocess', () => {
+ test('feeds the token via stdin and returns the stored identity on complete', async () => {
+ const result = await runPatSubprocess({
+ cliArgs: fixtureCli(ECHO_STDIN_CLI),
+ host: 'ghes.test',
+ token: 'good-token',
+ });
+ expect(result).toEqual({ ok: true, host: 'ghes.test', login: 'got:good-token' });
+ });
+
+ test('surfaces the CLI error message on a rejected token', async () => {
+ const result = await runPatSubprocess({
+ cliArgs: fixtureCli(ECHO_STDIN_CLI),
+ host: 'ghes.test',
+ token: 'wrong-token',
+ });
+ expect(result).toEqual({ ok: false, host: 'ghes.test', error: 'Token invalid for ghes.test' });
+ });
+
+ test('falls back to a bounded generic error when the child exits with no terminal event', async () => {
+ const result = await runPatSubprocess({
+ cliArgs: fixtureCli('process.exit(3)'),
+ host: 'ghes.test',
+ token: 'x',
+ });
+ expect(result.ok).toBe(false);
+ if (!result.ok) {
+ expect(result.error).toBe('Token validation failed.');
+ }
+ });
+});
diff --git a/packages/server/src/local-ops/auth-pat.ts b/packages/server/src/local-ops/auth-pat.ts
new file mode 100644
index 000000000..f6f3532f1
--- /dev/null
+++ b/packages/server/src/local-ops/auth-pat.ts
@@ -0,0 +1,69 @@
+/**
+ * Personal Access Token runner — spawns `<cli> auth pat --json --host <host>
+ * --token-stdin`, writes the token to the child's stdin (never argv/env), and
+ * resolves with the stored identity or an error.
+ *
+ * The enterprise sign-in path: the OAuth device flow only works on github.com
+ * (OpenKnowledge's OAuth app isn't registered on arbitrary GHES instances), so
+ * a GHES host authenticates by storing a PAT instead. On success the CLI emits
+ * `{type:'complete', host, login}`; on failure it writes the reason to stderr
+ * (via describeAuthFailure) and exits non-zero, which we surface verbatim.
+ */
+
+import { runSubprocess } from './subprocess.ts';
+
+export interface RunPatOptions {
+ /** Command + base argv prefix; e.g. `['open-knowledge']` or `[process.execPath, scriptPath]`. */
+ cliArgs: readonly string[];
+ /** GitHub host. Defaults to `'github.com'`. */
+ host?: string;
+ /** The Personal Access Token to validate + store. */
+ token: string;
+ /** Wall-clock subprocess timeout. Defaults to 30s. */
+ timeoutMs?: number;
+}
+
+export type RunPatResult =
+ | { ok: true; host: string; login: string }
+ | { ok: false; host: string; error: string };
+
+const DEFAULT_TIMEOUT_MS = 30_000;
+
+export async function runPatSubprocess(opts: RunPatOptions): Promise<RunPatResult> {
+ const host = opts.host ?? 'github.com';
+ let terminal: RunPatResult | null = null;
+
+ const proc = runSubprocess({
+ cliArgs: opts.cliArgs,
+ trailingArgs: ['auth', 'pat', '--json', '--host', host, '--token-stdin'],
+ stdinData: opts.token,
+ timeoutMs: opts.timeoutMs ?? DEFAULT_TIMEOUT_MS,
+ onLine: ({ parsed }) => {
+ if (!parsed) return;
+ if (parsed.type === 'complete') {
+ terminal = {
+ ok: true,
+ host: typeof parsed.host === 'string' ? parsed.host : host,
+ login: typeof parsed.login === 'string' ? parsed.login : '',
+ };
+ } else if (parsed.type === 'error') {
+ terminal = {
+ ok: false,
+ host,
+ error: typeof parsed.message === 'string' ? parsed.message : 'Token validation failed',
+ };
+ }
+ },
+ });
+
+ const result = await proc.done;
+ if (terminal) return terminal;
+ // The CLI emits a bounded {type:'error'} on --json failures, so reaching here
+ // means an unexpected exit (crash / killed). Keep the wire message generic and
+ // bounded — raw stderr can carry filesystem paths.
+ return {
+ ok: false,
+ host,
+ error: result.timedOut ? 'Token validation timed out.' : 'Token validation failed.',
+ };
+}
diff --git a/packages/server/src/local-ops/gh-login.test.ts b/packages/server/src/local-ops/gh-login.test.ts
new file mode 100644
index 000000000..c004df099
--- /dev/null
+++ b/packages/server/src/local-ops/gh-login.test.ts
@@ -0,0 +1,110 @@
+import { chmodSync, mkdtempSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
+import { resolveGhBinaryPath, runGhDeviceLoginSubprocess } from './gh-login.ts';
+import type { AuthEvent } from './types.ts';
+
+// A fake `gh` that emits the real device-flow stderr lines, then exits with
+// $FAKE_GH_EXIT (default 0). Trailing args are ignored.
+const dir = mkdtempSync(join(tmpdir(), 'gh-login-test-'));
+const fakeGh = join(dir, 'gh');
+writeFileSync(
+ fakeGh,
+ `#!/bin/bash
+# The post-login username lookup ("gh api ... user --jq .login") prints the login.
+if [ "$1" = "api" ]; then echo "octocat"; exit 0; fi
+echo "! First copy your one-time code: TEST-1234" >&2
+echo "Open this URL to continue in your web browser: https://ghes.test/login/device" >&2
+exit \${FAKE_GH_EXIT:-0}
+`,
+);
+chmodSync(fakeGh, 0o755);
+
+async function collect(exitCode: string): Promise<AuthEvent[]> {
+ process.env.FAKE_GH_EXIT = exitCode;
+ const events: AuthEvent[] = [];
+ const ctl = runGhDeviceLoginSubprocess({
+ host: 'ghes.test',
+ ghPath: fakeGh,
+ onEvent: (e) => events.push(e),
+ });
+ await ctl.done;
+ delete process.env.FAKE_GH_EXIT;
+ return events;
+}
+
+describe('runGhDeviceLoginSubprocess', () => {
+ test('parses gh output into a verification event, then complete on exit 0', async () => {
+ const events = await collect('0');
+ expect(events).toEqual([
+ {
+ type: 'verification',
+ user_code: 'TEST-1234',
+ verification_uri: 'https://ghes.test/login/device',
+ expires_in: 900,
+ },
+ { type: 'complete', host: 'ghes.test', login: 'octocat' },
+ ]);
+ });
+
+ test('emits a bounded error on non-zero exit (still surfaces the code first)', async () => {
+ const events = await collect('1');
+ expect(events[0]?.type).toBe('verification');
+ const terminal = events[events.length - 1];
+ expect(terminal?.type).toBe('error');
+ if (terminal?.type === 'error') expect(terminal.message).toContain('gh sign-in failed');
+ });
+
+ test('unrecognizable stderr trips the verification deadline with a single actionable error', async () => {
+ // A fake gh whose stderr never matches CODE_RE/URL_RE (format change or an
+ // early failure) and that would otherwise run far past the deadline.
+ const stallGh = join(dir, 'gh-stall');
+ writeFileSync(
+ stallGh,
+ `#!/bin/bash
+echo "unexpected output format" >&2
+# exec + /dev/null stdio: SIGTERM from cancel() hits sleep itself, and no
+# orphan holds the stdio pipes open past the kill (close fires promptly).
+exec sleep 60 1>/dev/null 2>/dev/null
+`,
+ );
+ chmodSync(stallGh, 0o755);
+ const events: AuthEvent[] = [];
+ const ctl = runGhDeviceLoginSubprocess({
+ host: 'ghes.test',
+ ghPath: stallGh,
+ verificationDeadlineMs: 300,
+ onEvent: (e) => events.push(e),
+ });
+ await ctl.done;
+ expect(events).toHaveLength(1);
+ expect(events[0]?.type).toBe('error');
+ if (events[0]?.type === 'error') {
+ expect(events[0].message).toContain('personal access token');
+ }
+ });
+});
+
+describe('resolveGhBinaryPath', () => {
+ test('returns the first candidate whose --version succeeds (falls back past a missing PATH gh)', async () => {
+ const path = await resolveGhBinaryPath({
+ _exec: async (cmd: string) => {
+ if (cmd === 'gh') throw new Error('not on PATH');
+ return '';
+ },
+ _fileExists: (p: string) => p === '/opt/homebrew/bin/gh',
+ });
+ expect(path).toBe('/opt/homebrew/bin/gh');
+ });
+
+ test('returns null when gh is nowhere', async () => {
+ const path = await resolveGhBinaryPath({
+ _exec: async () => {
+ throw new Error('nope');
+ },
+ _fileExists: () => false,
+ });
+ expect(path).toBeNull();
+ });
+});
diff --git a/packages/server/src/local-ops/gh-login.ts b/packages/server/src/local-ops/gh-login.ts
new file mode 100644
index 000000000..e12534241
--- /dev/null
+++ b/packages/server/src/local-ops/gh-login.ts
@@ -0,0 +1,242 @@
+/**
+ * "Sign in with gh" runner — spawns `gh auth login --hostname <host> --web` and
+ * adapts gh's human-readable output into the same AuthEvent stream OpenKnowledge's
+ * own device flow uses.
+ *
+ * Why this exists: GitHub Enterprise Server ships gh's OAuth app preregistered
+ * (OpenKnowledge's is not), so gh CAN do a browser sign-in against a GHES where
+ * OK's own device flow can't. When spawned without a TTY, gh degrades to a
+ * device-code flow, printing to stderr:
+ *
+ * ! First copy your one-time code: XXXX-XXXX
+ * Open this URL to continue in your web browser: https://<host>/login/device
+ *
+ * then polls the device endpoint until the user authorizes, storing the token
+ * in gh's keyring — which OpenKnowledge reads via tier A. No token is handled by
+ * OpenKnowledge on this path.
+ */
+
+import { execFile } from 'node:child_process';
+import { existsSync } from 'node:fs';
+import { promisify } from 'node:util';
+import { getLogger } from '../logger.ts';
+import { runSubprocess } from './subprocess.ts';
+import type { AuthEvent } from './types.ts';
+
+const execFileAsync = promisify(execFile);
+
+/**
+ * Run a command and resolve its stdout, rejecting on non-zero exit / timeout.
+ * Async so a slow or hung binary never blocks the server event loop — this
+ * process also serves CRDT updates, WebSocket heartbeats, and the editor API.
+ */
+async function execForStdout(cmd: string, args: string[], timeoutMs: number): Promise<string> {
+ const { stdout } = await execFileAsync(cmd, args, {
+ encoding: 'utf-8',
+ timeout: timeoutMs,
+ windowsHide: true,
+ });
+ return stdout;
+}
+
+/**
+ * Standard `gh` install locations. Mirrors `KNOWN_GH_PATHS` in
+ * `packages/cli/src/auth/gh-detect.ts` — the packaged app's launchd PATH omits
+ * Homebrew dirs, so a bare `gh` lookup misses them.
+ */
+const KNOWN_GH_PATHS: readonly string[] = [
+ '/opt/homebrew/bin/gh',
+ '/usr/local/bin/gh',
+ '/opt/local/bin/gh',
+ '/snap/bin/gh',
+ '/usr/bin/gh',
+];
+
+interface ResolveGhDeps {
+ /** Resolve stdout of `cmd args…`, reject on failure. */
+ _exec?: (cmd: string, args: string[], timeoutMs: number) => Promise<string>;
+ _fileExists?: (path: string) => boolean;
+}
+
+/**
+ * Resolve a working `gh` binary — bare `gh` via PATH first, then the known
+ * install locations — or `null` if gh isn't installed. Verified with
+ * `gh --version` so a dangling path isn't returned. Used both to decide whether
+ * to offer "Sign in with gh" and to spawn gh by absolute path from the app.
+ */
+export async function resolveGhBinaryPath(deps: ResolveGhDeps = {}): Promise<string | null> {
+ const exec = deps._exec ?? execForStdout;
+ const fileExists = deps._fileExists ?? existsSync;
+ const candidates = ['gh', ...KNOWN_GH_PATHS.filter(fileExists)];
+ for (const cmd of candidates) {
+ try {
+ await exec(cmd, ['--version'], 5000);
+ return cmd;
+ } catch {
+ // Try the next candidate.
+ }
+ }
+ return null;
+}
+
+/**
+ * Resolve the signed-in username after gh has stored its token, by asking the
+ * host's API (`gh api user`, routed to the GHES `/api/v3` by `--hostname`). gh's
+ * own sign-in stderr never prints the login, so without this the completion
+ * event — and the success toast built from it — has no name to show. Returns ''
+ * on any failure; the client's follow-up status poll is the backstop.
+ */
+async function resolveGhLogin(
+ ghPath: string,
+ host: string,
+ exec: (cmd: string, args: string[], timeoutMs: number) => Promise<string> = execForStdout,
+): Promise<string> {
+ try {
+ const out = await exec(ghPath, ['api', '--hostname', host, 'user', '--jq', '.login'], 10000);
+ return out.trim();
+ } catch (err) {
+ // Fallback is by design (the client's status poll backfills the name), but
+ // leave a breadcrumb — a blank username in the success toast is otherwise
+ // untraceable to this lookup.
+ getLogger('gh-login').warn({ err }, 'post-login username lookup failed');
+ return '';
+ }
+}
+
+let ghPathCache: string | null | undefined;
+let ghProbeInFlight: Promise<string | null> | undefined;
+
+/**
+ * Cached `resolveGhBinaryPath`. Caches only a *positive* result — gh's install
+ * location doesn't move once found, so the auth-status probe reuses it. A
+ * "not installed" answer is deliberately NOT cached: it's re-probed on each
+ * call so a user who installs gh mid-session sees the browser path appear on
+ * the next status check (i.e. by reopening the connect dialog), with no app
+ * restart. The re-probe is cheap when gh is absent — a failed `gh --version`
+ * spawn plus a few `existsSync` checks, no shell.
+ */
+export async function cachedGhBinaryPath(): Promise<string | null> {
+ if (ghPathCache) return ghPathCache;
+ // Dedupe concurrent first-access callers (e.g. auth/status + auth/login at
+ // dialog open) onto one probe; a settled negative still re-probes next call.
+ ghProbeInFlight ??= resolveGhBinaryPath().then((path) => {
+ ghProbeInFlight = undefined;
+ if (path !== null) ghPathCache = path;
+ return path;
+ });
+ return ghProbeInFlight;
+}
+
+export interface RunGhDeviceLoginOptions {
+ /** GitHub host to sign in to. */
+ host: string;
+ /** Resolved gh binary (from `resolveGhBinaryPath`). */
+ ghPath: string;
+ /** Wall-clock subprocess timeout. Defaults to 10 minutes. */
+ timeoutMs?: number;
+ /** Deadline for gh to print the code/URL. Defaults to 30 seconds. */
+ verificationDeadlineMs?: number;
+ /** Called for every adapted event (`verification` / `complete` / `error`). */
+ onEvent: (event: AuthEvent) => void;
+}
+
+export interface RunGhDeviceLoginController {
+ /** Resolves once gh has exited and the terminal event is emitted. */
+ done: Promise<void>;
+ /** SIGTERM the gh child (e.g. the user cancelled). */
+ cancel(): void;
+}
+
+const DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;
+/**
+ * How long to wait for gh to print the one-time code + URL before giving up.
+ * gh's stderr format isn't contractual — a version change, locale, or an early
+ * error ("no internet", rate limit) can mean the regexes below never match.
+ * Without this deadline the modal would sit in its loading state for the full
+ * 10-minute wall clock with zero feedback. Normal emission is near-instant.
+ */
+const VERIFICATION_DEADLINE_MS = 30_000;
+// gh's stderr, e.g. "! First copy your one-time code: 7625-A0A2"
+const CODE_RE = /one-time code:\s*([A-Za-z0-9-]+)/i;
+// "...web browser: https://<host>/login/device"
+const URL_RE = /(https?:\/\/\S+?\/login\/device)\b/i;
+
+export function runGhDeviceLoginSubprocess(
+ opts: RunGhDeviceLoginOptions,
+): RunGhDeviceLoginController {
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
+ let emittedVerification = false;
+ let deadlineExpired = false;
+ let stderrBuf = '';
+
+ const proc = runSubprocess({
+ cliArgs: [opts.ghPath],
+ trailingArgs: [
+ 'auth',
+ 'login',
+ '--hostname',
+ opts.host,
+ '--web',
+ '--git-protocol',
+ 'https',
+ '--skip-ssh-key',
+ ],
+ timeoutMs,
+ // gh writes its prompts to stderr, not NDJSON on stdout.
+ onLine: () => {},
+ onStderr: (chunk) => {
+ stderrBuf += chunk.toString('utf-8');
+ if (emittedVerification) return;
+ const code = stderrBuf.match(CODE_RE)?.[1];
+ const url = stderrBuf.match(URL_RE)?.[1];
+ if (code && url) {
+ emittedVerification = true;
+ opts.onEvent({
+ type: 'verification',
+ user_code: code,
+ verification_uri: url,
+ expires_in: 900,
+ });
+ }
+ },
+ });
+
+ const verificationDeadline = setTimeout(() => {
+ if (emittedVerification) return;
+ // gh never produced a recognizable code/URL — surface an actionable error
+ // now instead of letting the modal spin until the 10-minute wall clock.
+ deadlineExpired = true;
+ opts.onEvent({
+ type: 'error',
+ message:
+ 'Could not start the browser sign-in — try updating the GitHub CLI (gh), ' +
+ 'or use a personal access token instead',
+ });
+ proc.cancel();
+ }, opts.verificationDeadlineMs ?? VERIFICATION_DEADLINE_MS);
+ verificationDeadline.unref?.();
+
+ const done = proc.done.then(async (result) => {
+ clearTimeout(verificationDeadline);
+ // The deadline already emitted the terminal error and SIGTERMed gh; the
+ // resulting non-zero exit must not emit a second one.
+ if (deadlineExpired) return;
+ if (result.code === 0) {
+ // gh stored the token in its keyring; OK reads it via tier A. Resolve the
+ // login now so the completion event (and its toast) name the user; the
+ // client's follow-up status poll is the backstop if this lookup fails.
+ const login = await resolveGhLogin(opts.ghPath, opts.host);
+ opts.onEvent({ type: 'complete', host: opts.host, login });
+ } else {
+ // Bounded message — gh's raw stderr can carry paths; keep the wire clean.
+ opts.onEvent({
+ type: 'error',
+ message: result.timedOut
+ ? 'gh sign-in timed out — please try again'
+ : 'gh sign-in failed — please try again',
+ });
+ }
+ });
+
+ return { done, cancel: proc.cancel };
+}
diff --git a/packages/server/src/local-ops/index.ts b/packages/server/src/local-ops/index.ts
index 1b3476508..2f79f1749 100644
--- a/packages/server/src/local-ops/index.ts
+++ b/packages/server/src/local-ops/index.ts
@@ -3,6 +3,7 @@ export {
type RunDeviceFlowOptions,
runDeviceFlowSubprocess,
} from './auth-flow.ts';
+export { runPatSubprocess } from './auth-pat.ts';
export {
type AuthReposResponse,
type AuthStatusResponse,
@@ -19,6 +20,7 @@ export {
runCloneSubprocess,
validateCloneInputs,
} from './clone-flow.ts';
+export { cachedGhBinaryPath, runGhDeviceLoginSubprocess } from './gh-login.ts';
export type {
AuthEvent,
CloneCompleteEvent,
diff --git a/packages/server/src/local-ops/subprocess.ts b/packages/server/src/local-ops/subprocess.ts
index e534ff362..4eb105107 100644
--- a/packages/server/src/local-ops/subprocess.ts
+++ b/packages/server/src/local-ops/subprocess.ts
@@ -15,10 +15,6 @@ import { spawn } from 'node:child_process';
import { delimiter as PATH_DELIMITER } from 'node:path';
import { withHiddenWindowsConsole } from '../child-process-windows-hide.ts';
-const SUBPROCESS_PIPE_STDIO_OPTIONS: { stdio: ['ignore', 'pipe', 'pipe'] } = {
- stdio: ['ignore', 'pipe', 'pipe'],
-};
-
/** A parsed JSON line plus the raw line (for HTTP NDJSON pass-through). */
interface ParsedLine {
/** Raw NDJSON line (no trailing newline). */
@@ -48,6 +44,13 @@ interface SubprocessRunOptions {
onLine: (line: ParsedLine) => void;
/** Optional stderr observer (receives raw chunks). */
onStderr?: (chunk: Buffer) => void;
+ /**
+ * When set, the child is spawned with a piped stdin and this string is written
+ * to it (then closed) — the non-interactive channel for `auth pat
+ * --token-stdin`, so the token never appears in argv or the environment.
+ * Absent leaves stdin ignored (the default for every other flow).
+ */
+ stdinData?: string;
}
interface SubprocessRunResult {
@@ -101,16 +104,26 @@ export function runSubprocess(opts: SubprocessRunOptions): SubprocessController
.join(PATH_DELIMITER);
}
+ const stdio: ['ignore' | 'pipe', 'pipe', 'pipe'] =
+ opts.stdinData !== undefined ? ['pipe', 'pipe', 'pipe'] : ['ignore', 'pipe', 'pipe'];
const child = spawn(
cmd,
argv,
withHiddenWindowsConsole({
- ...SUBPROCESS_PIPE_STDIO_OPTIONS,
+ stdio,
cwd: opts.cwd,
env: childEnv,
}),
);
+ if (opts.stdinData !== undefined && child.stdin) {
+ // The child may exit before draining stdin (e.g. an unknown flag) — swallow
+ // the resulting EPIPE rather than crashing the parent.
+ child.stdin.on('error', () => {});
+ child.stdin.write(opts.stdinData);
+ child.stdin.end();
+ }
+
const killTimer = setTimeout(() => {
timedOut = true;
child.kill('SIGTERM');
@@ -128,14 +141,16 @@ export function runSubprocess(opts: SubprocessRunOptions): SubprocessController
opts.onLine({ raw, parsed });
};
- child.stdout.on('data', (chunk: Buffer) => {
+ // stdout/stderr are always piped (stdio[1]/[2] are 'pipe'); the optional
+ // chaining only satisfies the type widened by the conditional stdin mode.
+ child.stdout?.on('data', (chunk: Buffer) => {
stdoutBuffer += chunk.toString('utf-8');
const lines = stdoutBuffer.split('\n');
stdoutBuffer = lines.pop() ?? '';
for (const line of lines) flushLine(line);
});
- child.stderr.on('data', (chunk: Buffer) => {
+ child.stderr?.on('data', (chunk: Buffer) => {
stderrChunks.push(chunk);
opts.onStderr?.(chunk);
});
diff --git a/packages/server/src/mcp/tools/share-link.ts b/packages/server/src/mcp/tools/share-link.ts
index f12c53669..6b024d04d 100644
--- a/packages/server/src/mcp/tools/share-link.ts
+++ b/packages/server/src/mcp/tools/share-link.ts
@@ -48,7 +48,7 @@ const DESCRIPTION = [
"- `kind` (optional) — `'doc'` or `'folder'`. Omit to auto-probe disk (`.mdx` → `.md` → directory, first hit wins). REQUIRED when `path` is empty (`\"\"`), since auto-probe cannot disambiguate the root.",
'- `cwd` (optional) — Project root (see `cwd` description below).',
'',
- '**Preconditions:** project on a named branch (not detached HEAD); origin set to a `github.com` remote; the branch already pushed to origin.',
+ '**Preconditions:** project on a named branch (not detached HEAD); origin set to a GitHub remote (`github.com` or a GitHub Enterprise Server host); the branch already pushed to origin.',
].join('\n');
export interface ShareLinkDeps {
@@ -130,7 +130,7 @@ function messageForShareError(error: ShareConstructUrlErrorCode, branch?: string
: `The current branch is not on origin yet. Ask the user to push it (\`git push -u origin <branch>\`), then retry.${fetchHint}`;
}
case 'non-github-remote':
- return 'Origin is not a `github.com` remote. Share links are GitHub-only in v1.';
+ return 'Origin is a non-GitHub remote (GitLab, Bitbucket, etc.). Share links require a GitHub remote (`github.com` or GitHub Enterprise Server).';
case 'invalid-path':
return 'The resolved share path is not shareable (escapes the project root or names the `.git` subtree). Pass a normal target path under the content directory.';
default: {
diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.ts
index 7c9c16370..0fce5b441 100644
--- a/packages/server/src/server-factory.ts
+++ b/packages/server/src/server-factory.ts
@@ -194,6 +194,7 @@ import { SyncEngine } from './sync-engine.ts';
import { createSyncHandshakeSpanExtension } from './sync-handshake-span-extension.ts';
import { TagIndex } from './tag-index.ts';
import { initTelemetry, shutdownTelemetry, withSpan } from './telemetry.ts';
+import { trustSystemCertificates } from './trust-system-ca.ts';
import { cleanupOrphanUploadTempfiles } from './upload-streaming.ts';
export interface ServerOptions {
@@ -557,6 +558,11 @@ export function resolveUpstreamChanges(
}
export function createServer(options: ServerOptions): ServerInstance {
+ // Trust the OS certificate store before the sync engine's GitHub permission
+ // probe (or any Octokit call) reaches a GHES host on a self-signed/internal-CA
+ // cert. Idempotent — covers every server-launch path (utility fork, detached,
+ // in-process) from one place; the CLI and desktop-main processes call it too.
+ trustSystemCertificates();
const {
contentDir,
projectDir = contentDir,
diff --git a/packages/server/src/share/construct-url.test.ts b/packages/server/src/share/construct-url.test.ts
index 953ed5f0d..42cab1718 100644
--- a/packages/server/src/share/construct-url.test.ts
+++ b/packages/server/src/share/construct-url.test.ts
@@ -1,10 +1,10 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import { mkdirSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import type { Server } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { decodeShareUrl } from '@inkeep/open-knowledge-core';
+import { afterEach, describe, expect, test } from 'vitest';
import { loggerFactory, PinoLogger } from '../logger.ts';
import {
buildGitHubBlobUrl,
@@ -214,11 +214,11 @@ 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.
+ test('GHES origins produce an enterprise-host share URL', async () => {
+ // Origin classification recognizes GHES hosts, the builders take the
+ // origin host, and the receive side accepts enterprise hosts behind its
+ // trust gate — so a GHES workspace mints a working share URL pointing at
+ // its own server, not github.com.
rig = await bootRig((projectDir) => {
seedRemoteAndHead(projectDir, {
head: 'ref: refs/heads/main\n',
@@ -228,8 +228,9 @@ describe('POST /api/share/construct-url', () => {
});
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' });
+ const json = (await res.json()) as Record<string, unknown>;
+ expect(json.ok).toBe(true);
+ expect(json.sharedUrl).toBe('https://ghes.acme.test/team/notes/blob/main/a.md');
});
test('invalid-path: rejects .. segment', async () => {
@@ -458,44 +459,50 @@ describe('buildGitHubBlobUrl branch encoding', () => {
}
test('simple single-segment branch is plain text', () => {
- const url = buildGitHubBlobUrl('owner', 'repo', 'main', 'README.md');
+ const url = buildGitHubBlobUrl('github.com', 'owner', 'repo', 'main', 'README.md');
expect(url).toBe('https://github.com/owner/repo/blob/main/README.md');
expect(roundTripBranch(url)).toBe('main');
});
test('slashed branch encodes slash as %2F (single URL segment)', () => {
- const url = buildGitHubBlobUrl('owner', 'repo', 'feat/foo', 'docs/page.md');
+ const url = buildGitHubBlobUrl('github.com', 'owner', 'repo', 'feat/foo', 'docs/page.md');
expect(url).toBe('https://github.com/owner/repo/blob/feat%2Ffoo/docs/page.md');
expect(extractBranchSegment(url)).toBe('feat%2Ffoo');
expect(roundTripBranch(url)).toBe('feat/foo');
});
test('deeper-slash branch encodes every slash as %2F', () => {
- const url = buildGitHubBlobUrl('owner', 'repo', 'release/2026-05/foo', 'a.md');
+ const url = buildGitHubBlobUrl('github.com', 'owner', 'repo', 'release/2026-05/foo', 'a.md');
expect(url).toBe('https://github.com/owner/repo/blob/release%2F2026-05%2Ffoo/a.md');
expect(roundTripBranch(url)).toBe('release/2026-05/foo');
});
test('branch with # encodes as %23 (would otherwise be parsed as fragment)', () => {
- const url = buildGitHubBlobUrl('owner', 'repo', 'feat#nest', 'a.md');
+ const url = buildGitHubBlobUrl('github.com', 'owner', 'repo', 'feat#nest', 'a.md');
expect(url).toBe('https://github.com/owner/repo/blob/feat%23nest/a.md');
expect(new URL(url).hash).toBe('');
expect(roundTripBranch(url)).toBe('feat#nest');
});
test('branch with space encodes as %20', () => {
- const url = buildGitHubBlobUrl('owner', 'repo', 'feat space', 'a.md');
+ const url = buildGitHubBlobUrl('github.com', 'owner', 'repo', 'feat space', 'a.md');
expect(url).toBe('https://github.com/owner/repo/blob/feat%20space/a.md');
expect(roundTripBranch(url)).toBe('feat space');
});
test('path segments still split on / and encoded individually (separator preserved)', () => {
- const url = buildGitHubBlobUrl('owner', 'repo', 'main', 'docs/sub/page name.md');
+ const url = buildGitHubBlobUrl('github.com', 'owner', 'repo', 'main', 'docs/sub/page name.md');
expect(url).toBe('https://github.com/owner/repo/blob/main/docs/sub/page%20name.md');
});
test('docPath with unicode round-trips through per-segment encoding', () => {
- const url = buildGitHubBlobUrl('owner', 'repo', 'main', 'docs/Q4 OKRs — Marketing.md');
+ const url = buildGitHubBlobUrl(
+ 'github.com',
+ 'owner',
+ 'repo',
+ 'main',
+ 'docs/Q4 OKRs — Marketing.md',
+ );
const pathSegments = new URL(url).pathname.split('/').slice(5);
expect(pathSegments.map((s) => decodeURIComponent(s)).join('/')).toBe(
'docs/Q4 OKRs — Marketing.md',
@@ -510,26 +517,26 @@ describe('buildGitHubTreeUrl', () => {
}
test('folder path: segments encoded individually, no trailing slash', () => {
- const url = buildGitHubTreeUrl('owner', 'repo', 'main', 'docs/sub folder');
+ const url = buildGitHubTreeUrl('github.com', 'owner', 'repo', 'main', 'docs/sub folder');
expect(url).toBe('https://github.com/owner/repo/tree/main/docs/sub%20folder');
expect(url.endsWith('/')).toBe(false);
});
test('slashed branch encodes slash as %2F (single URL segment)', () => {
- const url = buildGitHubTreeUrl('owner', 'repo', 'feat/foo', 'docs');
+ const url = buildGitHubTreeUrl('github.com', 'owner', 'repo', 'feat/foo', 'docs');
expect(url).toBe('https://github.com/owner/repo/tree/feat%2Ffoo/docs');
expect(extractBranchSegment(url)).toBe('feat%2Ffoo');
expect(decodeURIComponent(extractBranchSegment(url))).toBe('feat/foo');
});
test('empty folderPath (root) -> tree/<branch> with no trailing slash', () => {
- const url = buildGitHubTreeUrl('owner', 'repo', 'main', '');
+ const url = buildGitHubTreeUrl('github.com', 'owner', 'repo', 'main', '');
expect(url).toBe('https://github.com/owner/repo/tree/main');
expect(url.endsWith('/')).toBe(false);
});
test('empty folderPath with slashed branch encodes branch, no trailing slash', () => {
- const url = buildGitHubTreeUrl('owner', 'repo', 'feat/foo', '');
+ const url = buildGitHubTreeUrl('github.com', 'owner', 'repo', 'feat/foo', '');
expect(url).toBe('https://github.com/owner/repo/tree/feat%2Ffoo');
});
});
diff --git a/packages/server/src/share/construct-url.ts b/packages/server/src/share/construct-url.ts
index efa33df8e..f7fdd2437 100644
--- a/packages/server/src/share/construct-url.ts
+++ b/packages/server/src/share/construct-url.ts
@@ -65,6 +65,7 @@ export function isValidSharePath(path: string, kind: 'doc' | 'folder'): boolean
* remains a separator there.
*/
export function buildGitHubBlobUrl(
+ host: string,
owner: string,
repo: string,
branch: string,
@@ -72,7 +73,7 @@ export function buildGitHubBlobUrl(
): string {
const encodedBranch = encodeURIComponent(branch);
const encodedSegments = docPath.split('/').map(encodeURIComponent).join('/');
- return `https://github.com/${owner}/${repo}/blob/${encodedBranch}/${encodedSegments}`;
+ return `https://${host}/${owner}/${repo}/blob/${encodedBranch}/${encodedSegments}`;
}
/**
@@ -87,13 +88,14 @@ export function buildGitHubBlobUrl(
* accepts that root shape and yields `path: ''`.
*/
export function buildGitHubTreeUrl(
+ host: string,
owner: string,
repo: string,
branch: string,
folderPath: string,
): string {
const encodedBranch = encodeURIComponent(branch);
- const base = `https://github.com/${owner}/${repo}/tree/${encodedBranch}`;
+ const base = `https://${host}/${owner}/${repo}/tree/${encodedBranch}`;
if (folderPath === '') return base;
const encodedSegments = folderPath.split('/').map(encodeURIComponent).join('/');
return `${base}/${encodedSegments}`;
diff --git a/packages/server/src/sync-engine.ts b/packages/server/src/sync-engine.ts
index b6a9eb70b..64a1fa81e 100644
--- a/packages/server/src/sync-engine.ts
+++ b/packages/server/src/sync-engine.ts
@@ -92,7 +92,11 @@ export type PushPermissionStatus =
| { checkStatus: 'allowed' }
| {
checkStatus: 'denied';
- deniedReason: 'no-collaborator' | 'private-no-access' | 'repo-not-found';
+ deniedReason:
+ | 'no-collaborator'
+ | 'private-no-access'
+ | 'repo-not-found'
+ | 'not-authenticated';
}
| {
checkStatus: 'unknown';
diff --git a/packages/server/src/trust-system-ca.test.ts b/packages/server/src/trust-system-ca.test.ts
new file mode 100644
index 000000000..f5b6e139a
--- /dev/null
+++ b/packages/server/src/trust-system-ca.test.ts
@@ -0,0 +1,70 @@
+import tls from 'node:tls';
+import { describe, expect, test } from 'vitest';
+import {
+ _resetTrustSystemCertificatesForTest,
+ trustSystemCertificates,
+} from './trust-system-ca.ts';
+
+describe('trustSystemCertificates', () => {
+ test('never throws (feature-detected; no-ops on older Node)', () => {
+ _resetTrustSystemCertificatesForTest();
+ expect(() => trustSystemCertificates()).not.toThrow();
+ });
+
+ test('is idempotent — a second call is a no-op', () => {
+ _resetTrustSystemCertificatesForTest();
+ let sets = 0;
+ const api = tls as unknown as { setDefaultCACertificates?: unknown };
+ const original = api.setDefaultCACertificates;
+ if (typeof original !== 'function') return; // older Node — nothing to assert
+ api.setDefaultCACertificates = () => {
+ sets += 1;
+ };
+ try {
+ trustSystemCertificates();
+ trustSystemCertificates();
+ expect(sets).toBe(1);
+ } finally {
+ api.setDefaultCACertificates = original;
+ }
+ });
+
+ test('a failed apply stays retryable — the next call tries again and can succeed', () => {
+ _resetTrustSystemCertificatesForTest();
+ const api = tls as unknown as { setDefaultCACertificates?: (c: readonly string[]) => void };
+ const original = api.setDefaultCACertificates;
+ if (typeof original !== 'function') return; // older Node — nothing to assert
+ let calls = 0;
+ api.setDefaultCACertificates = () => {
+ calls += 1;
+ // e.g. a locked Keychain at cold start — transient, not permanent.
+ if (calls === 1) throw new Error('keychain locked');
+ };
+ try {
+ trustSystemCertificates(); // fails, must not latch the guard
+ trustSystemCertificates(); // retries and succeeds, latches
+ trustSystemCertificates(); // idempotent after success
+ expect(calls).toBe(2);
+ } finally {
+ api.setDefaultCACertificates = original;
+ _resetTrustSystemCertificatesForTest();
+ }
+ });
+
+ test('on a runtime with the CA APIs, it installs a superset of the default bundle', () => {
+ _resetTrustSystemCertificatesForTest();
+ const api = tls as unknown as {
+ getCACertificates?: (type?: string) => string[];
+ setDefaultCACertificates?: (c: readonly string[]) => void;
+ };
+ if (
+ typeof api.getCACertificates !== 'function' ||
+ typeof api.setDefaultCACertificates !== 'function'
+ ) {
+ return; // older Node — nothing to assert
+ }
+ const bundledCount = api.getCACertificates('default').length;
+ trustSystemCertificates();
+ expect(api.getCACertificates('default').length).toBeGreaterThanOrEqual(bundledCount);
+ });
+});
diff --git a/packages/server/src/trust-system-ca.ts b/packages/server/src/trust-system-ca.ts
new file mode 100644
index 000000000..be845a1aa
--- /dev/null
+++ b/packages/server/src/trust-system-ca.ts
@@ -0,0 +1,62 @@
+import tls from 'node:tls';
+import { getLogger } from './logger.ts';
+
+let applied = false;
+
+/**
+ * Trust the OS certificate store (macOS Keychain, enterprise CA, …) for all TLS
+ * in this process — the same store `git` already uses — so a GitHub Enterprise
+ * Server on a self-signed or internal-CA certificate works for Node/undici API
+ * calls instead of failing `DEPTH_ZERO_SELF_SIGNED_CERT` (which the auth path
+ * otherwise mislabels "Token invalid", and which breaks the sync permission
+ * probe).
+ *
+ * This is the in-process, runtime equivalent of `node --use-system-ca`. It runs
+ * in every Node process that talks to the GitHub API — the CLI, the server
+ * fork, and the desktop main process — because an Electron `use-system-ca`
+ * command-line switch only reaches Chromium's network stack, not Node's
+ * `fetch`/undici. Idempotent (safe to call from multiple entry points) and
+ * feature-detected: `getCACertificates` / `setDefaultCACertificates` landed in
+ * Node 22.15 / 23.8, so on older runtimes it no-ops and the bundled CA set
+ * stays in place (today's behavior).
+ */
+export function trustSystemCertificates(): void {
+ if (applied) return;
+ const api = tls as unknown as {
+ getCACertificates?: (type?: 'default' | 'system' | 'bundled' | 'extra') => string[];
+ setDefaultCACertificates?: (certs: readonly string[]) => void;
+ };
+ if (
+ typeof api.getCACertificates !== 'function' ||
+ typeof api.setDefaultCACertificates !== 'function'
+ ) {
+ // Runtime lacks the API entirely — retrying can never succeed.
+ applied = true;
+ return;
+ }
+ try {
+ // Union of Node's default bundle + the OS store, so public CAs keep working
+ // while enterprise/self-signed roots also become trusted.
+ api.setDefaultCACertificates([
+ ...api.getCACertificates('default'),
+ ...api.getCACertificates('system'),
+ ]);
+ // Only a successful apply latches the guard: a transient failure (e.g. a
+ // locked Keychain at cold start) stays retryable on the next entry-point
+ // call instead of being permanent for the process lifetime.
+ applied = true;
+ } catch (err) {
+ // Never let CA setup block startup — fall back to the bundled bundle. But
+ // leave a breadcrumb: the downstream symptom is a DEPTH_ZERO_SELF_SIGNED_CERT
+ // auth/sync failure on GHES, which is hard to trace back here without it.
+ getLogger('trust-system-ca').warn(
+ { err },
+ 'system CA setup failed; falling back to the bundled CA set',
+ );
+ }
+}
+
+/** Test-only: reset the once-guard so a unit test can exercise the body. */
+export function _resetTrustSystemCertificatesForTest(): void {
+ applied = false;
+}