Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Cross-platform share-link receive: splash CLI + clone auth hints (#1998)

miles-kt-inkeepeaa5cc939974
diff --git a/.changeset/share-link-cross-platform-receive.md b/.changeset/share-link-cross-platform-receive.md
new file mode 100644
index 000000000..e0213d600
--- /dev/null
+++ b/.changeset/share-link-cross-platform-receive.md
@@ -0,0 +1,9 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Give share-link recipients on Linux and Intel Macs a working way in, and make `ok clone` fail helpfully on private repos.
+
+The share-link splash now always shows a copyable CLI block — `npm install -g @inkeep/open-knowledge` followed by `ok clone <owner/repo> -b <branch>` — alongside the macOS desktop options. After the page loads it adapts to the visitor's OS: Linux promotes the CLI and hides the desktop-only buttons, Windows shows a clear "Open Knowledge isn't supported on Windows yet" notice (keeping the View on GitHub link), and macOS keeps the desktop app primary with the CLI tucked behind a "Have an Intel Mac? Open with the CLI" disclosure. The clone command always pins the shared branch with `-b`, and a post-clone breadcrumb tells the recipient which file or folder to open once the clone lands them at the repo root.
+
+`ok clone` now explains how to recover from an authentication failure instead of printing a raw git error. When you're not signed in, it prints `ok auth login` and the exact `ok clone` command to re-run afterward. A 403 names the signed-in account that may lack access, and a scope problem points at the missing `repo` OAuth scope.
diff --git a/docs/content/features/share.mdx b/docs/content/features/share.mdx
index 8b6078927..e6af1982f 100644
--- a/docs/content/features/share.mdx
+++ b/docs/content/features/share.mdx
@@ -24,10 +24,10 @@ If the push fails after the repo was created (auth lost mid-flow, network blip),
The recipient clicks the URL and lands on a splash page showing the target (file or folder) name, the `owner/repo` path, and the branch from which it was shared.
-Two CTAs sit on the splash page:
+The splash offers two ways to receive:
-- **Open in Open Knowledge** fires the deep link and opens the Open Knowledge desktop app — on the shared doc, folder overview, or project root depending on what was shared.
-- **Download for macOS** downloads the arm64 DMG for users who do not yet have the desktop app.
+- **Desktop app (macOS).** Click **Open in Open Knowledge** to fire the deep link into the Open Knowledge desktop app — on the shared doc, folder overview, or project root depending on what was shared. **Download for macOS** ships the arm64 DMG for recipients who don't yet have the app.
+- **CLI (macOS and Linux).** Copy the pre-filled `npm install -g @inkeep/open-knowledge` then `ok clone <owner/repo> -b <branch>` from the splash to clone the repo locally and open the editor. The clone command is always branch-pinned, but if the feature branch has been deleted, it will fall back to the default branch. See the [CLI reference](/docs/reference/cli#clone-from-github) for `ok clone` and related commands.
## What the desktop app does when it receives the link
diff --git a/docs/content/reference/cli.mdx b/docs/content/reference/cli.mdx
index 4d076ab81..00dd10010 100644
--- a/docs/content/reference/cli.mdx
+++ b/docs/content/reference/cli.mdx
@@ -47,8 +47,27 @@ This opens your file directly in the WYSIWYG/source editor without any of the ve
You can pull repositories directly from GitHub and open them with Open Knowledge:
-1. Run `ok auth login` to complete device authentication (if you are already logged in with the `gh` CLI you can skip this step)
-2. Clone your repo with `ok clone <repo-url>`. This will clone the repository and initialize Open Knowledge if it is not already.
+```bash
+ok clone <owner/repo>
+```
+
+`ok clone` accepts a full `https://github.com/...` URL or the `owner/repo` shorthand. It clones the repository, initializes Open Knowledge if it isn't already, and opens the editor.
+
+Pin a branch with `-b <branch>`:
+
+```bash
+ok clone <owner/repo> -b <branch>
+```
+
+If the branch no longer exists, `ok clone` falls back to the repository's default branch.
+
+A **public** repo clones without authentication. For a **private** repo, sign in first:
+
+```bash
+ok auth login
+```
+
+If you're already logged in with the `gh` CLI, you can skip this step.
## Manage local servers
diff --git a/docs/src/app/d/[encoded]/page.tsx b/docs/src/app/d/[encoded]/page.tsx
index f044ae33b..87fa6ea23 100644
--- a/docs/src/app/d/[encoded]/page.tsx
+++ b/docs/src/app/d/[encoded]/page.tsx
@@ -1,12 +1,18 @@
-import { FolderIcon, GitBranchIcon } from 'lucide-react';
+import { ChevronDown, FolderIcon, GitBranchIcon } from 'lucide-react';
import type { Metadata } from 'next';
import Link from 'next/link';
import { OkWordmark } from '@/components/ok-wordmark';
-import { buildSplashViewModel, SPLASH_DOWNLOAD_URL } from '@/lib/share-splash';
+import {
+ buildCloneCommand,
+ buildSplashViewModel,
+ SPLASH_DOWNLOAD_URL,
+ SPLASH_INSTALL_COMMAND,
+} from '@/lib/share-splash';
import { SITE_URL } from '@/lib/site';
+import { cn } from '@/lib/utils';
import { DotTexture } from '../../(home)/dot-texture';
import { SplashButtonLabel, splashOutlineButton, splashPrimaryButton } from './splash-buttons';
-import { SplashCtaCluster } from './splash-cta-cluster';
+import { SplashCtaPanel } from './splash-cta-panel';
export const dynamic = 'force-static';
@@ -118,10 +124,16 @@ export default async function SplashPage({ params }: SplashPageProps) {
</p>
)}
- <SplashCtaCluster
+ <SplashCtaPanel
downloadUrl={`/d/${encoded}/download`}
customSchemeUrl={view.customSchemeUrl}
githubUrl={view.githubUrl}
+ installCommand={SPLASH_INSTALL_COMMAND}
+ cloneCommand={buildCloneCommand({
+ owner: view.owner,
+ repo: view.repo,
+ branch: view.branch,
+ })}
/>
</div>
</section>
@@ -174,9 +186,55 @@ function SplashFallback({ heading }: { heading: string }) {
</Link>
</div>
- <p className="mt-8 text-sm text-slide-muted">Share URLs are only opened on macOS.</p>
+ <p className="mt-8 text-sm text-slide-muted">
+ The desktop app runs on macOS. The CLI is cross-platform on macOS and Linux.
+ </p>
+
+ <SplashFallbackCli />
</div>
</section>
</main>
);
}
+
+function SplashFallbackCli() {
+ return (
+ <details className="group mt-6" data-testid="splash-fallback-cli-disclosure">
+ <summary
+ className={cn(
+ 'inline-flex cursor-pointer list-none items-center gap-2 rounded-full border border-azure-blue px-5 py-[13px]',
+ 'bg-transparent font-mono text-sm font-medium uppercase leading-[115%] tracking-[-0.64px] text-azure-blue sm:text-base',
+ 'transition duration-200 ease-in-out outline-none',
+ 'hover:bg-azure-blue hover:text-white',
+ 'focus-visible:ring-2 focus-visible:ring-slide-accent focus-visible:ring-offset-2',
+ '[&::-webkit-details-marker]:hidden',
+ )}
+ data-testid="splash-fallback-cli-summary"
+ >
+ <span>Install the CLI</span>
+ <ChevronDown
+ className="size-4 shrink-0 transition-transform duration-200 group-open:rotate-180 motion-reduce:transition-none"
+ aria-hidden="true"
+ />
+ </summary>
+ <div
+ className="not-prose mt-3 rounded-lg border border-slide-border bg-slide-bg-elevated p-4"
+ data-testid="splash-fallback-cli-body"
+ >
+ <pre className="overflow-x-auto whitespace-pre rounded bg-black/5 p-3 font-mono text-sm leading-relaxed text-slide-text dark:bg-white/10">
+ <code className="block">{SPLASH_INSTALL_COMMAND}</code>
+ </pre>
+ <p className="mt-3 text-sm text-slide-muted">
+ See the{' '}
+ <Link
+ href="/docs/reference/cli"
+ className="font-medium text-slide-text underline underline-offset-4 transition-colors hover:text-slide-accent-strong focus-visible:rounded focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-slide-accent"
+ >
+ CLI reference
+ </Link>{' '}
+ for `ok clone &lt;owner/repo&gt;` and other commands.
+ </p>
+ </div>
+ </details>
+ );
+}
diff --git a/docs/src/app/d/[encoded]/splash-buttons.tsx b/docs/src/app/d/[encoded]/splash-buttons.tsx
index bfbdb8a06..a65c511d1 100644
--- a/docs/src/app/d/[encoded]/splash-buttons.tsx
+++ b/docs/src/app/d/[encoded]/splash-buttons.tsx
@@ -5,7 +5,7 @@ export const splashPrimaryButton = cn(
'inline-flex items-center gap-2 rounded-full h-12 px-[18px] py-[14px] pr-2.5',
'bg-azure-blue text-white text-sm sm:text-base font-medium uppercase leading-[115%] tracking-[-0.64px]',
'transition duration-200 ease-in-out outline-none cursor-pointer',
- 'hover:bg-blue-dark hover:shadow-lg hover:-translate-y-0.5 active:scale-[0.98]',
+ 'hover:bg-blue-dark hover:shadow-lg hover:-translate-y-0.5 active:scale-[0.98] motion-reduce:transform-none motion-reduce:transition-none',
'focus-visible:ring-2 focus-visible:ring-slide-accent focus-visible:ring-offset-2',
);
diff --git a/docs/src/app/d/[encoded]/splash-cli-block.tsx b/docs/src/app/d/[encoded]/splash-cli-block.tsx
new file mode 100644
index 000000000..53a1c337a
--- /dev/null
+++ b/docs/src/app/d/[encoded]/splash-cli-block.tsx
@@ -0,0 +1,149 @@
+'use client';
+
+import { Check, ChevronDown, Copy } from 'lucide-react';
+import { useEffect, useRef, useState } from 'react';
+import { clipboardCopyOutcome } from '@/lib/share-splash';
+import { cn } from '@/lib/utils';
+
+interface SplashCliBlockProps {
+ installCommand: string;
+ cloneCommand: string;
+ disclosureSummary?: { lead: string; action: string };
+ initialOpen?: boolean;
+}
+
+const COPY_RESET_MS = 2000;
+const FAILED_RESET_MS = 5000;
+
+type CopyStatus = 'idle' | 'copied' | 'failed';
+
+export function SplashCliBlock({
+ installCommand,
+ cloneCommand,
+ disclosureSummary,
+ initialOpen,
+}: SplashCliBlockProps) {
+ const [status, setStatus] = useState<CopyStatus>('idle');
+ const [failureSelected, setFailureSelected] = useState(false);
+ const codeRef = useRef<HTMLPreElement>(null);
+ const resetTimerRef = useRef<number | null>(null);
+
+ useEffect(
+ () => () => {
+ if (resetTimerRef.current !== null) window.clearTimeout(resetTimerRef.current);
+ },
+ [],
+ );
+
+ function scheduleStatusReset(ms: number) {
+ if (resetTimerRef.current !== null) window.clearTimeout(resetTimerRef.current);
+ resetTimerRef.current = window.setTimeout(() => {
+ setStatus('idle');
+ resetTimerRef.current = null;
+ }, ms);
+ }
+
+ const payload = `${installCommand}\n${cloneCommand}`;
+
+ const handleCopy = async () => {
+ let succeeded = true;
+ try {
+ await navigator.clipboard.writeText(payload);
+ } catch {
+ succeeded = false;
+ }
+ const outcome = clipboardCopyOutcome(succeeded);
+ if (outcome.kind === 'copied') {
+ setStatus('copied');
+ scheduleStatusReset(COPY_RESET_MS);
+ return;
+ }
+ let selected = false;
+ if (codeRef.current) {
+ const range = document.createRange();
+ range.selectNodeContents(codeRef.current);
+ const sel = window.getSelection();
+ sel?.removeAllRanges();
+ sel?.addRange(range);
+ selected = true;
+ }
+ setFailureSelected(selected);
+ setStatus('failed');
+ scheduleStatusReset(FAILED_RESET_MS);
+ };
+
+ const statusLabel =
+ status === 'copied'
+ ? 'Copied'
+ : status === 'failed'
+ ? failureSelected
+ ? "Couldn't copy — text is selected"
+ : "Couldn't copy"
+ : 'Copy';
+
+ const body = (
+ <div className="not-prose relative" data-testid="splash-cli-body">
+ <pre
+ ref={codeRef}
+ className="overflow-x-auto whitespace-pre rounded-lg border border-slide-border bg-slide-bg-elevated py-3.5 pr-12 pl-4 font-mono text-sm leading-relaxed text-slide-text"
+ >
+ <code className="block">{installCommand}</code>
+ <code className="block">{cloneCommand}</code>
+ </pre>
+ <button
+ type="button"
+ onClick={handleCopy}
+ data-testid="splash-cli-copy"
+ aria-label="Copy install and clone commands to clipboard"
+ title={statusLabel}
+ data-copy-status={status}
+ className={cn(
+ 'absolute top-2.5 right-2.5 inline-flex size-7 items-center justify-center rounded-md text-slide-muted transition',
+ 'hover:bg-black/5 hover:text-slide-text dark:hover:bg-white/10',
+ 'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-slide-accent',
+ status === 'copied' && 'text-slide-accent-strong',
+ )}
+ >
+ {status === 'copied' ? (
+ <Check className="size-4" aria-hidden="true" />
+ ) : (
+ <Copy className="size-4" aria-hidden="true" />
+ )}
+ {/* Status stays announced to assistive tech (the clipboard-failure
+ recovery) while the visible affordance is icon-only. */}
+ <span className="sr-only" aria-live="polite">
+ {statusLabel}
+ </span>
+ </button>
+ </div>
+ );
+
+ if (!disclosureSummary) {
+ return <div className="mt-12">{body}</div>;
+ }
+
+ return (
+ <details className="group mt-6" data-testid="splash-cli-disclosure" open={initialOpen ?? false}>
+ <summary
+ className={cn(
+ 'group/cli inline-flex w-fit cursor-pointer list-none items-center gap-1.5 text-sm text-slide-muted',
+ 'focus-visible:rounded focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-slide-accent',
+ '[&::-webkit-details-marker]:hidden',
+ )}
+ data-testid="splash-cli-disclosure-summary"
+ >
+ <span>
+ {disclosureSummary.lead}{' '}
+ <span className="font-medium text-slide-text underline underline-offset-4 transition-colors group-hover/cli:text-slide-accent-strong">
+ {disclosureSummary.action}
+ </span>
+ </span>
+ <ChevronDown
+ className="size-3.5 shrink-0 text-slide-muted transition-transform duration-200 group-open:rotate-180 motion-reduce:transition-none"
+ aria-hidden="true"
+ />
+ </summary>
+ <div className="mt-3">{body}</div>
+ </details>
+ );
+}
diff --git a/docs/src/app/d/[encoded]/splash-cta-cluster.tsx b/docs/src/app/d/[encoded]/splash-cta-cluster.tsx
index f6f00e902..5e767497b 100644
--- a/docs/src/app/d/[encoded]/splash-cta-cluster.tsx
+++ b/docs/src/app/d/[encoded]/splash-cta-cluster.tsx
@@ -160,7 +160,7 @@ export function SplashCtaCluster({
href={downloadUrl}
onClick={handleDownloadClick}
data-testid="splash-download-cta"
- className="touch-manipulation font-medium text-slide-text underline underline-offset-4 transition-colors hover:text-slide-accent focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-slide-accent focus-visible:rounded"
+ className="touch-manipulation font-medium text-slide-text underline underline-offset-4 transition-colors hover:text-slide-accent-strong focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-slide-accent focus-visible:rounded"
>
Download for macOS
</a>
diff --git a/docs/src/app/d/[encoded]/splash-cta-panel.tsx b/docs/src/app/d/[encoded]/splash-cta-panel.tsx
new file mode 100644
index 000000000..a1e2f8fa6
--- /dev/null
+++ b/docs/src/app/d/[encoded]/splash-cta-panel.tsx
@@ -0,0 +1,102 @@
+'use client';
+
+import { ArrowUpRight } from 'lucide-react';
+import { useEffect, useState } from 'react';
+import { classifySplashOs, type SplashOs, splashCtaLayout } from '@/lib/share-splash';
+import { SplashCliBlock } from './splash-cli-block';
+import { SplashCtaCluster } from './splash-cta-cluster';
+
+interface SplashCtaPanelProps {
+ downloadUrl: string;
+ customSchemeUrl: string;
+ githubUrl: string;
+ installCommand: string;
+ cloneCommand: string;
+}
+
+export function SplashCtaPanel({
+ downloadUrl,
+ customSchemeUrl,
+ githubUrl,
+ installCommand,
+ cloneCommand,
+}: SplashCtaPanelProps) {
+ const [os, setOs] = useState<SplashOs>('unknown');
+
+ useEffect(() => {
+ setOs(classifySplashOs(readPlatformInput()));
+ }, []);
+
+ const layout = splashCtaLayout(os);
+
+ if (layout.showWindowsNotice) {
+ return <SplashWindowsNotice githubUrl={githubUrl} />;
+ }
+
+ return (
+ <>
+ {layout.showCluster && (
+ <SplashCtaCluster
+ downloadUrl={downloadUrl}
+ customSchemeUrl={customSchemeUrl}
+ githubUrl={githubUrl}
+ />
+ )}
+
+ <SplashCliBlock
+ installCommand={installCommand}
+ cloneCommand={cloneCommand}
+ disclosureSummary={
+ layout.cliInline ? undefined : { lead: 'Have an Intel Mac?', action: 'Open with the CLI' }
+ }
+ />
+
+ {/* Linux drops the cluster (no desktop binary, no deep link) but keeps a
+ standalone GitHub fallback so a recipient who can't run the CLI still
+ reaches the content. splashCtaLayout encodes the invariant that every
+ OS keeps a GitHub path (cluster / standalone / Windows notice). */}
+ {layout.showStandaloneGithub && (
+ <div className="mt-6">
+ <SplashGithubLink githubUrl={githubUrl} />
+ </div>
+ )}
+ </>
+ );
+}
+
+function readPlatformInput(): string | null {
+ if (typeof navigator === 'undefined') return null;
+ const withUaData = navigator as Navigator & {
+ userAgentData?: { platform?: string };
+ };
+ return withUaData.userAgentData?.platform ?? navigator.userAgent ?? null;
+}
+
+function SplashWindowsNotice({ githubUrl }: { githubUrl: string }) {
+ return (
+ <div className="mt-12 flex flex-col gap-4" role="status" data-testid="splash-windows-notice">
+ <p
+ className="text-base leading-relaxed text-slide-text"
+ data-testid="splash-windows-notice-text"
+ >
+ Open Knowledge isn&rsquo;t supported on Windows yet.
+ </p>
+ <SplashGithubLink githubUrl={githubUrl} />
+ </div>
+ );
+}
+
+function SplashGithubLink({ githubUrl }: { githubUrl: string }) {
+ return (
+ <a
+ href={githubUrl}
+ data-testid="splash-github-cta"
+ rel="noopener noreferrer"
+ target="_blank"
+ className="inline-flex w-fit touch-manipulation items-center gap-1.5 font-mono text-sm uppercase tracking-wide text-slide-muted transition-colors hover:text-slide-text focus-visible:rounded focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-slide-accent"
+ >
+ View on GitHub
+ <ArrowUpRight className="size-3.5" aria-hidden="true" />
+ </a>
+ );
+}
diff --git a/docs/src/lib/share-splash.test.ts b/docs/src/lib/share-splash.test.ts
index 20589987d..783a75302 100644
--- a/docs/src/lib/share-splash.test.ts
+++ b/docs/src/lib/share-splash.test.ts
@@ -1,6 +1,15 @@
import { describe, expect, test } from 'bun:test';
import { encodeShareUrl } from '@inkeep/open-knowledge-core';
-import { buildCustomSchemeUrl, buildSplashViewModel, SPLASH_DOWNLOAD_URL } from './share-splash.ts';
+import {
+ buildCloneCommand,
+ buildCustomSchemeUrl,
+ buildSplashViewModel,
+ classifySplashOs,
+ clipboardCopyOutcome,
+ SPLASH_DOWNLOAD_URL,
+ SPLASH_INSTALL_COMMAND,
+ splashCtaLayout,
+} from './share-splash.ts';
function encodeV1(sharedUrl: string): string {
return encodeShareUrl(sharedUrl);
@@ -57,6 +66,24 @@ describe('buildSplashViewModel', () => {
});
});
+ test('uses the path basename as the filename on a nested doc share', () => {
+ const blobUrl = 'https://github.com/inkeep/playbooks/blob/main/docs/architecture/auth.md';
+ const view = buildSplashViewModel(encodeV1(blobUrl));
+ expect(view.kind).toBe('ok');
+ if (view.kind === 'ok') {
+ expect(view.filename).toBe('auth.md');
+ }
+ });
+
+ test('falls back to the repo name as filename for a root-folder (repo/branch root) share', () => {
+ const treeUrl = 'https://github.com/inkeep/playbooks/tree/main';
+ const view = buildSplashViewModel(encodeV1(treeUrl));
+ expect(view.kind).toBe('ok');
+ if (view.kind === 'ok') {
+ expect(view.filename).toBe('playbooks');
+ }
+ });
+
test('decodes a repo/branch-root folder (empty tree path) and falls back to the repo name', () => {
const treeUrl = 'https://github.com/inkeep/playbooks/tree/main';
const view = buildSplashViewModel(encodeV1(treeUrl));
@@ -227,6 +254,83 @@ describe('buildSplashViewModel', () => {
});
});
+describe('buildSplashViewModel — shell-injection guard', () => {
+ test('rejects a branch carrying a shell command separator', () => {
+ const url = 'https://github.com/inkeep/playbooks/blob/main%3Bcurl%20evil.sh%7Csh/readme.md';
+ expect(buildSplashViewModel(encodeV1(url)).kind).toBe('invalid');
+ });
+
+ test('rejects a branch carrying a command substitution', () => {
+ const url = 'https://github.com/inkeep/playbooks/blob/%24(rm%20-rf%20~)/readme.md';
+ expect(buildSplashViewModel(encodeV1(url)).kind).toBe('invalid');
+ });
+
+ test('rejects a branch carrying a newline', () => {
+ const url = 'https://github.com/inkeep/playbooks/blob/a%0Acurl%20evil/readme.md';
+ expect(buildSplashViewModel(encodeV1(url)).kind).toBe('invalid');
+ });
+
+ test('rejects an owner carrying a shell metacharacter', () => {
+ const url = 'https://github.com/o%3Bevil/playbooks/blob/main/readme.md';
+ expect(buildSplashViewModel(encodeV1(url)).kind).toBe('invalid');
+ });
+
+ test('rejects a repo carrying a backtick', () => {
+ const url = 'https://github.com/inkeep/re%60id%60po/blob/main/readme.md';
+ expect(buildSplashViewModel(encodeV1(url)).kind).toBe('invalid');
+ });
+
+ test('rejects a leading-dash branch (option injection into ok clone)', () => {
+ const url = 'https://github.com/inkeep/playbooks/blob/-rf/readme.md';
+ expect(buildSplashViewModel(encodeV1(url)).kind).toBe('invalid');
+ });
+
+ test('rejects the same injection on a tree (folder) share', () => {
+ const url = 'https://github.com/inkeep/playbooks/tree/main%3Bcurl%20evil';
+ expect(buildSplashViewModel(encodeV1(url)).kind).toBe('invalid');
+ });
+
+ test('still accepts a legitimate slash-bearing branch (not over-rejecting)', () => {
+ const url = 'https://github.com/inkeep/playbooks/blob/release%2F1.2.3/readme.md';
+ const view = buildSplashViewModel(encodeV1(url));
+ expect(view.kind).toBe('ok');
+ if (view.kind === 'ok') {
+ expect(view.branch).toBe('release/1.2.3');
+ expect(buildCloneCommand(view)).toBe('ok clone inkeep/playbooks -b release/1.2.3');
+ }
+ });
+
+ test('accepts a valid ref outside the old allowlist (release+candidate) — no over-rejection', () => {
+ const url = 'https://github.com/inkeep/playbooks/blob/release%2Bcandidate/readme.md';
+ const view = buildSplashViewModel(encodeV1(url));
+ expect(view.kind).toBe('ok');
+ if (view.kind === 'ok') {
+ expect(view.branch).toBe('release+candidate');
+ expect(buildCloneCommand(view)).toBe('ok clone inkeep/playbooks -b release+candidate');
+ }
+ });
+
+ test('accepts a shell-unsafe but valid ref and quotes it at render', () => {
+ const url = 'https://github.com/inkeep/playbooks/blob/feat%3Bx/readme.md';
+ const view = buildSplashViewModel(encodeV1(url));
+ expect(view.kind).toBe('ok');
+ if (view.kind === 'ok') {
+ expect(view.branch).toBe('feat;x');
+ expect(buildCloneCommand(view)).toBe("ok clone inkeep/playbooks -b 'feat;x'");
+ }
+ });
+
+ test('still rejects a `:` refspec-injection branch (would rewrite local refs)', () => {
+ const url = 'https://github.com/inkeep/playbooks/blob/HEAD%3Arefs%2Fheads%2Fevil/readme.md';
+ expect(buildSplashViewModel(encodeV1(url)).kind).toBe('invalid');
+ });
+
+ test('rejects `..` owner/repo segments (encoded) — no `ok clone ../..` rendering', () => {
+ const url = 'https://github.com/%2E%2E/%2E%2E/blob/main/readme.md';
+ expect(buildSplashViewModel(encodeV1(url)).kind).toBe('invalid');
+ });
+});
+
describe('buildCustomSchemeUrl', () => {
test('produces the openknowledge://share?url=... custom-scheme handoff URL', () => {
const blobUrl = 'https://github.com/o/r/blob/main/file with space.md';
@@ -243,3 +347,196 @@ describe('SPLASH_DOWNLOAD_URL', () => {
);
});
});
+
+describe('SPLASH_INSTALL_COMMAND', () => {
+ test('is the published CLI install command (global npm install)', () => {
+ expect(SPLASH_INSTALL_COMMAND).toBe('npm install -g @inkeep/open-knowledge');
+ });
+});
+
+describe('buildCloneCommand', () => {
+ test('emits `ok clone <owner>/<repo> -b <branch>` using owner/repo shorthand', () => {
+ expect(buildCloneCommand({ owner: 'inkeep', repo: 'playbooks', branch: 'main' })).toBe(
+ 'ok clone inkeep/playbooks -b main',
+ );
+ });
+
+ test('always emits -b on a default branch (main) — CLI default-fallback covers a deleted ref', () => {
+ expect(buildCloneCommand({ owner: 'o', repo: 'r', branch: 'main' })).toBe(
+ 'ok clone o/r -b main',
+ );
+ });
+
+ test('always emits -b on master', () => {
+ expect(buildCloneCommand({ owner: 'o', repo: 'r', branch: 'master' })).toBe(
+ 'ok clone o/r -b master',
+ );
+ });
+
+ test('always emits -b on a feature branch', () => {
+ expect(buildCloneCommand({ owner: 'inkeep', repo: 'playbooks', branch: 'feat-x' })).toBe(
+ 'ok clone inkeep/playbooks -b feat-x',
+ );
+ });
+
+ test('preserves a slash-bearing branch name verbatim (off-argv, not a URL)', () => {
+ expect(buildCloneCommand({ owner: 'o', repo: 'r', branch: 'feat/share' })).toBe(
+ 'ok clone o/r -b feat/share',
+ );
+ });
+
+ test('contains no `ok auth login` line — auth surfaces at clone-failure time', () => {
+ const cmd = buildCloneCommand({ owner: 'o', repo: 'r', branch: 'main' });
+ expect(cmd).not.toContain('ok auth login');
+ });
+
+ test('POSIX-single-quotes a shell-unsafe but valid ref so the pasted command is inert', () => {
+ expect(buildCloneCommand({ owner: 'o', repo: 'r', branch: 'feat;x' })).toBe(
+ "ok clone o/r -b 'feat;x'",
+ );
+ });
+
+ test('renders a `+`-bearing ref unquoted (release+candidate)', () => {
+ expect(buildCloneCommand({ owner: 'o', repo: 'r', branch: 'release+candidate' })).toBe(
+ 'ok clone o/r -b release+candidate',
+ );
+ });
+
+ test('POSIX-single-quotes a branch containing a literal single quote', () => {
+ expect(buildCloneCommand({ owner: 'o', repo: 'r', branch: "feat'x" })).toBe(
+ "ok clone o/r -b 'feat'\\''x'",
+ );
+ });
+});
+
+describe('classifySplashOs', () => {
+ test('returns `unknown` for null / undefined / empty', () => {
+ expect(classifySplashOs(null)).toBe('unknown');
+ expect(classifySplashOs(undefined)).toBe('unknown');
+ expect(classifySplashOs('')).toBe('unknown');
+ });
+
+ test('classifies userAgentData.platform values', () => {
+ expect(classifySplashOs('macOS')).toBe('macos');
+ expect(classifySplashOs('Linux')).toBe('linux');
+ expect(classifySplashOs('Windows')).toBe('windows');
+ expect(classifySplashOs('Chrome OS')).toBe('linux');
+ expect(classifySplashOs('iOS')).toBe('unknown');
+ expect(classifySplashOs('Android')).toBe('unknown');
+ expect(classifySplashOs('Unknown')).toBe('unknown');
+ });
+
+ test('classifies macOS desktop UA strings', () => {
+ expect(
+ classifySplashOs(
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15',
+ ),
+ ).toBe('macos');
+ expect(
+ classifySplashOs(
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
+ ),
+ ).toBe('macos');
+ });
+
+ test('classifies Linux X11 UA strings', () => {
+ expect(
+ classifySplashOs(
+ 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
+ ),
+ ).toBe('linux');
+ expect(
+ classifySplashOs(
+ 'Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0',
+ ),
+ ).toBe('linux');
+ });
+
+ test('classifies Windows UA strings', () => {
+ expect(
+ classifySplashOs(
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
+ ),
+ ).toBe('windows');
+ expect(
+ classifySplashOs('Mozilla/5.0 (Windows NT 10.0; rv:120.0) Gecko/20100101 Firefox/120.0'),
+ ).toBe('windows');
+ });
+
+ test('classifies iPhone / iPad UAs as unknown (the trailing "Mac OS X" is a decoy)', () => {
+ expect(
+ classifySplashOs(
+ 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1',
+ ),
+ ).toBe('unknown');
+ expect(
+ classifySplashOs(
+ 'Mozilla/5.0 (iPad; CPU OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1',
+ ),
+ ).toBe('unknown');
+ });
+
+ test('classifies Android UAs as unknown (the leading "Linux" is a decoy)', () => {
+ expect(
+ classifySplashOs(
+ 'Mozilla/5.0 (Linux; Android 13; SM-A536B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36',
+ ),
+ ).toBe('unknown');
+ });
+
+ test('never reports architecture — frozen Intel-vs-AS UA still classifies as macos', () => {
+ expect(
+ classifySplashOs(
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 Safari/605.1.15',
+ ),
+ ).toBe('macos');
+ });
+});
+
+describe('splashCtaLayout', () => {
+ test('macOS and unknown render the cluster floor with the CLI in a disclosure', () => {
+ for (const os of ['macos', 'unknown'] as const) {
+ expect(splashCtaLayout(os)).toEqual({
+ showWindowsNotice: false,
+ showCluster: true,
+ cliInline: false,
+ showStandaloneGithub: false,
+ });
+ }
+ });
+
+ test('Linux promotes the CLI inline, drops the cluster, and keeps a standalone GitHub link', () => {
+ expect(splashCtaLayout('linux')).toEqual({
+ showWindowsNotice: false,
+ showCluster: false,
+ cliInline: true,
+ showStandaloneGithub: true,
+ });
+ });
+
+ test('Windows shows the not-supported notice only', () => {
+ expect(splashCtaLayout('windows')).toEqual({
+ showWindowsNotice: true,
+ showCluster: false,
+ cliInline: false,
+ showStandaloneGithub: false,
+ });
+ });
+
+ test('every OS keeps a path to GitHub (regression guard for the Linux-drop bug)', () => {
+ for (const os of ['macos', 'linux', 'windows', 'unknown'] as const) {
+ const l = splashCtaLayout(os);
+ expect(l.showWindowsNotice || l.showCluster || l.showStandaloneGithub).toBe(true);
+ }
+ });
+});
+
+describe('clipboardCopyOutcome', () => {
+ test('maps success to the `copied` branch', () => {
+ expect(clipboardCopyOutcome(true)).toEqual({ kind: 'copied' });
+ });
+
+ test('maps failure to the `fallback-select` branch (never a silent no-op)', () => {
+ expect(clipboardCopyOutcome(false)).toEqual({ kind: 'fallback-select' });
+ });
+});
diff --git a/docs/src/lib/share-splash.ts b/docs/src/lib/share-splash.ts
index e364b801f..698d027f8 100644
--- a/docs/src/lib/share-splash.ts
+++ b/docs/src/lib/share-splash.ts
@@ -86,6 +86,25 @@ export type ParsedGitHubShareTarget =
| { kind: 'doc'; owner: string; repo: string; branch: string; path: string }
| { kind: 'folder'; owner: string; repo: string; branch: string; path: string };
+const SHARE_OWNER_REPO_PATTERN = /^[A-Za-z0-9._-]+$/;
+
+function isValidShareBranch(branch: string): boolean {
+ if (branch.length === 0) return false;
+ if (branch.startsWith('-')) return false;
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: rejecting control chars is the intent
+ if (/[\x00-\x1F\x7F]/.test(branch)) return false;
+ if (/\s/.test(branch)) return false;
+ if (branch.includes(':')) return false;
+ if (branch.split('/').includes('..')) return false;
+ return true;
+}
+
+function isShareSegmentSafe(owner: string, repo: string, branch: string): boolean {
+ const nameSafe = (s: string) =>
+ SHARE_OWNER_REPO_PATTERN.test(s) && !s.startsWith('-') && s !== '.' && s !== '..';
+ return nameSafe(owner) && nameSafe(repo) && isValidShareBranch(branch);
+}
+
function parseGitHubBlobUrl(input: string): ParsedGitHubBlobUrl | null {
let url: URL;
try {
@@ -118,6 +137,7 @@ function parseGitHubBlobUrl(input: string): ParsedGitHubBlobUrl | null {
if (!owner || !repo || !branch || pathParts.length === 0) return null;
if (pathParts.some((p) => p.length === 0)) return null;
+ if (!isShareSegmentSafe(owner, repo, branch)) return null;
return { owner, repo, branch, path: pathParts.join('/') };
}
@@ -158,6 +178,7 @@ function parseGitHubTreeUrl(input: string): ParsedGitHubTreeUrl | null {
if (!owner || !repo || !branch) return null;
if (pathParts.some((p) => p.length === 0)) return null;
+ if (!isShareSegmentSafe(owner, repo, branch)) return null;
return { owner, repo, branch, path: pathParts.join('/') };
}
@@ -178,6 +199,94 @@ export function buildCustomSchemeUrl(sharedUrl: string): string {
return `openknowledge://share?url=${encodeURIComponent(sharedUrl)}`;
}
+export const SPLASH_INSTALL_COMMAND = 'npm install -g @inkeep/open-knowledge';
+
+function shellSingleQuoteShareArg(s: string): string {
+ return `'${s.replace(/'/g, "'\\''")}'`;
+}
+
+const SHARE_SHELL_SAFE_TOKEN = /^[A-Za-z0-9._/@+-]+$/;
+
+function quoteShareArg(s: string): string {
+ return SHARE_SHELL_SAFE_TOKEN.test(s) ? s : shellSingleQuoteShareArg(s);
+}
+
+export function buildCloneCommand({
+ owner,
+ repo,
+ branch,
+}: {
+ owner: string;
+ repo: string;
+ branch: string;
+}): string {
+ return `ok clone ${quoteShareArg(owner)}/${quoteShareArg(repo)} -b ${quoteShareArg(branch)}`;
+}
+
+export type SplashOs = 'macos' | 'linux' | 'windows' | 'unknown';
+
+export function classifySplashOs(input: string | null | undefined): SplashOs {
+ if (!input) return 'unknown';
+ const lower = input.toLowerCase();
+ if (
+ lower.includes('iphone') ||
+ lower.includes('ipad') ||
+ lower.includes('android') ||
+ lower === 'ios'
+ ) {
+ return 'unknown';
+ }
+ if (lower.includes('mac') || lower === 'darwin') return 'macos';
+ if (lower.includes('win')) return 'windows';
+ if (
+ lower.includes('linux') ||
+ lower.includes('x11') ||
+ lower.includes('cros') ||
+ lower.includes('chrome os')
+ ) {
+ return 'linux';
+ }
+ return 'unknown';
+}
+
+export interface SplashCtaLayout {
+ showWindowsNotice: boolean;
+ showCluster: boolean;
+ cliInline: boolean;
+ showStandaloneGithub: boolean;
+}
+
+export function splashCtaLayout(os: SplashOs): SplashCtaLayout {
+ if (os === 'windows') {
+ return {
+ showWindowsNotice: true,
+ showCluster: false,
+ cliInline: false,
+ showStandaloneGithub: false,
+ };
+ }
+ if (os === 'linux') {
+ return {
+ showWindowsNotice: false,
+ showCluster: false,
+ cliInline: true,
+ showStandaloneGithub: true,
+ };
+ }
+ return {
+ showWindowsNotice: false,
+ showCluster: true,
+ cliInline: false,
+ showStandaloneGithub: false,
+ };
+}
+
+export type ClipboardCopyOutcome = { kind: 'copied' } | { kind: 'fallback-select' };
+
+export function clipboardCopyOutcome(succeeded: boolean): ClipboardCopyOutcome {
+ return succeeded ? { kind: 'copied' } : { kind: 'fallback-select' };
+}
+
function isCommonDefaultBranch(branch: string): boolean {
return branch === 'main' || branch === 'master';
}
diff --git a/packages/cli/src/commands/clone.test.ts b/packages/cli/src/commands/clone.test.ts
index 93fbae87f..f6cc06717 100644
--- a/packages/cli/src/commands/clone.test.ts
+++ b/packages/cli/src/commands/clone.test.ts
@@ -3,16 +3,149 @@ import { execFileSync } from 'node:child_process';
import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
+import type { TokenStore } from '../auth/token-store.ts';
import { OK_DIR } from '../constants.ts';
import {
buildCloneArgs,
buildCloneEnv,
+ buildCloneGitOptions,
cloneWithBranchFallback,
+ emitCloneFailure,
ensureOkExcludedFromGit,
+ formatCloneAuthFailure,
+ handleCloneFailure,
isBranchNotFoundError,
+ resolveClonePrincipal,
+ resolveCloneUrl,
shouldSkipAuthForPublicRepo,
} from './clone.ts';
+describe('resolveClonePrincipal', () => {
+ const storeReturning = (entry: { login: string; token: string } | null): TokenStore =>
+ ({ get: async () => entry }) as unknown as TokenStore;
+
+ test('returns the stored login when present', async () => {
+ const store = storeReturning({ login: 'alice', token: 't' });
+ expect(await resolveClonePrincipal(store, 'github.com')).toBe('alice');
+ });
+
+ test('returns null when no entry is stored (hint omitted, no placeholder)', async () => {
+ expect(await resolveClonePrincipal(storeReturning(null), 'github.com')).toBeNull();
+ });
+
+ test('treats the "unknown" sentinel login as not-known', async () => {
+ const store = storeReturning({ login: 'unknown', token: 't' });
+ expect(await resolveClonePrincipal(store, 'github.com')).toBeNull();
+ });
+});
+
+describe('resolveCloneUrl', () => {
+ const parsed = (owner: string, name: string, hostname = 'github.com') => ({
+ hostname,
+ owner,
+ name,
+ });
+
+ test('reconstructs a canonical https URL for owner/repo shorthand', () => {
+ expect(resolveCloneUrl('inkeep/playbooks', parsed('inkeep', 'playbooks'))).toBe(
+ 'https://github.com/inkeep/playbooks',
+ );
+ });
+
+ test('passes a full https URL through unchanged', () => {
+ const url = 'https://github.com/inkeep/playbooks.git';
+ expect(resolveCloneUrl(url, parsed('inkeep', 'playbooks'))).toBe(url);
+ });
+
+ test('passes an SSH/SCP URL through unchanged', () => {
+ const url = '[email protected]:inkeep/playbooks.git';
+ expect(resolveCloneUrl(url, parsed('inkeep', 'playbooks'))).toBe(url);
+ });
+
+ test('passes an @-less SCP/GHES SSH URL through unchanged (not rewritten to https)', () => {
+ const url = 'host.ghe.com:inkeep/playbooks.git';
+ expect(resolveCloneUrl(url, parsed('inkeep', 'playbooks', 'host.ghe.com'))).toBe(url);
+ });
+
+ test('reconstructs shorthand with a trailing .git suffix', () => {
+ expect(resolveCloneUrl('inkeep/playbooks.git', parsed('inkeep', 'playbooks'))).toBe(
+ 'https://github.com/inkeep/playbooks',
+ );
+ });
+});
+
+describe('handleCloneFailure', () => {
+ const collectors = () => {
+ const emitted: Record<string, unknown>[] = [];
+ const stderr: string[] = [];
+ return {
+ emitted,
+ stderr,
+ emit: (e: Record<string, unknown>) => emitted.push(e),
+ printStderr: (t: string) => stderr.push(t),
+ };
+ };
+
+ test('403 resolves the principal and threads it into the access-denied hint', async () => {
+ const c = collectors();
+ let resolvedHost: string | null = null;
+ await handleCloneFailure({
+ error: new Error('remote: HTTP 403 Forbidden'),
+ url: 'https://github.com/owner/repo',
+ branch: 'main',
+ json: false,
+ emit: c.emit,
+ printStderr: c.printStderr,
+ resolvePrincipal: async (host) => {
+ resolvedHost = host;
+ return 'alice';
+ },
+ });
+ expect(resolvedHost).toBe('github.com');
+ expect(c.stderr.join('')).toContain('@alice');
+ expect(c.stderr.join('')).not.toContain('ok auth login');
+ });
+
+ test('non-403 auth failure does not resolve the principal (skips keyring init)', async () => {
+ const c = collectors();
+ let called = false;
+ await handleCloneFailure({
+ error: new Error('fatal: could not read Username for https://github.com'),
+ url: 'https://github.com/owner/repo',
+ branch: 'main',
+ json: false,
+ emit: c.emit,
+ printStderr: c.printStderr,
+ resolvePrincipal: async () => {
+ called = true;
+ return 'alice';
+ },
+ });
+ expect(called).toBe(false);
+ expect(c.stderr.join('')).toContain('ok auth login');
+ });
+
+ test('--json keeps the raw {type:error,message} wire shape and skips principal resolution', async () => {
+ const c = collectors();
+ let called = false;
+ await handleCloneFailure({
+ error: new Error('remote: HTTP 403 Forbidden'),
+ url: 'https://github.com/owner/repo',
+ branch: null,
+ json: true,
+ emit: c.emit,
+ printStderr: c.printStderr,
+ resolvePrincipal: async () => {
+ called = true;
+ return 'alice';
+ },
+ });
+ expect(called).toBe(false);
+ expect(c.emitted).toEqual([{ type: 'error', message: 'remote: HTTP 403 Forbidden' }]);
+ expect(c.stderr).toEqual([]);
+ });
+});
+
describe('buildCloneEnv', () => {
test('inherits PATH and HOME from the source env', () => {
const env = buildCloneEnv({ PATH: '/opt/homebrew/bin:/usr/bin', HOME: '/Users/me' });
@@ -33,6 +166,26 @@ describe('buildCloneEnv', () => {
});
});
+describe('buildCloneGitOptions', () => {
+ test('opts into the env-based unsafe flags so the user PAGER/SSH/askpass env is honored', () => {
+ const o = buildCloneGitOptions('/work/dir', ['credential.helper=!gh auth git-credential']);
+ expect(o.baseDir).toBe('/work/dir');
+ expect(o.config).toEqual(['credential.helper=!gh auth git-credential']);
+ expect(o.unsafe).toEqual({
+ allowUnsafeCredentialHelper: true,
+ allowUnsafePager: true,
+ allowUnsafeSshCommand: true,
+ allowUnsafeAskPass: true,
+ });
+ });
+
+ test('passes an empty config through unchanged (no credential helper injected)', () => {
+ const o = buildCloneGitOptions('/work/dir', []);
+ expect(o.config).toEqual([]);
+ expect(o.unsafe?.allowUnsafePager).toBe(true);
+ });
+});
+
describe('shouldSkipAuthForPublicRepo', () => {
test('https + github.com + isPublic=true → true (anonymous clone path)', () => {
expect(shouldSkipAuthForPublicRepo('https', 'github.com', true)).toBe(true);
@@ -380,3 +533,219 @@ describe('isBranchNotFoundError', () => {
expect(isBranchNotFoundError(undefined)).toBe(false);
});
});
+
+describe('formatCloneAuthFailure', () => {
+ test('returns null for non-auth errors so the caller falls through to the raw git error', () => {
+ expect(
+ formatCloneAuthFailure({
+ error: new Error("fatal: couldn't find remote ref refs/heads/foo"),
+ url: 'https://github.com/o/r',
+ branch: 'foo',
+ }),
+ ).toBeNull();
+ expect(
+ formatCloneAuthFailure({
+ error: new Error('connection timed out'),
+ url: 'https://github.com/o/r',
+ }),
+ ).toBeNull();
+ });
+
+ test('login-fixable (no-credential) → 2-step instruction with reconstructed -b command', () => {
+ const out = formatCloneAuthFailure({
+ error: new Error('fatal: could not read Username for https://github.com'),
+ url: 'https://github.com/inkeep/playbooks',
+ branch: 'feat-x',
+ });
+ expect(out).not.toBeNull();
+ expect(out).toContain("Couldn't clone https://github.com/inkeep/playbooks");
+ expect(out).toContain('authentication is required');
+ expect(out).toContain('1. Run: ok auth login');
+ expect(out).toContain('2. Then re-run: ok clone https://github.com/inkeep/playbooks -b feat-x');
+ });
+
+ test('login-fixable reconstruction omits -b when no branch was supplied', () => {
+ const out = formatCloneAuthFailure({
+ error: new Error('fatal: terminal prompts disabled'),
+ url: 'inkeep/playbooks',
+ branch: null,
+ });
+ expect(out).toMatch(/ok clone inkeep\/playbooks$/);
+ expect(out).not.toContain('-b');
+ });
+
+ test('login-fixable (401 expired token) → same 2-step recovery shape', () => {
+ const out = formatCloneAuthFailure({
+ error: new Error('remote: HTTP 401 Unauthorized'),
+ url: 'inkeep/playbooks',
+ branch: 'main',
+ });
+ expect(out).toContain('1. Run: ok auth login');
+ expect(out).toContain('2. Then re-run: ok clone inkeep/playbooks -b main');
+ });
+
+ test('login-fixable (unknown-auth) → 2-step recovery', () => {
+ const out = formatCloneAuthFailure({
+ error: new Error('remote: Authentication failed'),
+ url: 'inkeep/playbooks',
+ branch: 'main',
+ });
+ expect(out).toContain('1. Run: ok auth login');
+ });
+
+ test('403 → access-denied hint without the login instruction', () => {
+ const out = formatCloneAuthFailure({
+ error: new Error('remote: HTTP 403 Forbidden'),
+ url: 'https://github.com/o/private',
+ branch: 'main',
+ });
+ expect(out).toContain('Access denied when cloning https://github.com/o/private');
+ expect(out).toContain('Check that your account has access');
+ expect(out).not.toContain('ok auth login');
+ });
+
+ test('403 + known principal → "signed in as @user" hint', () => {
+ const out = formatCloneAuthFailure({
+ error: new Error('remote: HTTP 403 Forbidden'),
+ url: 'https://github.com/o/private',
+ principal: 'miles',
+ });
+ expect(out).toContain('signed in as @miles');
+ expect(out).toContain('may lack access');
+ });
+
+ test('scope-mismatch → actionable PAT recovery (ok auth pat + re-run), not ok auth login', () => {
+ const out = formatCloneAuthFailure({
+ error: new Error('insufficient scopes'),
+ url: 'inkeep/private-repo',
+ branch: 'main',
+ });
+ expect(out).toContain('missing required OAuth scopes');
+ expect(out).toContain('repo');
+ expect(out).not.toContain('ok auth login');
+ expect(out).toContain('ok auth pat');
+ expect(out).toContain('https://github.com/settings/tokens');
+ expect(out).toContain('re-run: ok clone inkeep/private-repo -b main');
+ });
+
+ test('ssh-auth → SSH transport hint, never the ok auth login recovery', () => {
+ for (const message of ['Permission denied (publickey).', 'Host key verification failed.']) {
+ const out = formatCloneAuthFailure({
+ error: new Error(message),
+ url: '[email protected]:inkeep/playbooks.git',
+ branch: 'main',
+ });
+ expect(out).not.toBeNull();
+ expect(out).toContain('SSH');
+ expect(out).not.toContain('ok auth login');
+ }
+ });
+
+ test('shell-quotes a branch with spaces in the reconstructed re-run command', () => {
+ const out = formatCloneAuthFailure({
+ error: new Error('fatal: could not read Username'),
+ url: 'inkeep/playbooks',
+ branch: 'feat my idea',
+ });
+ expect(out).toContain("-b 'feat my idea'");
+ });
+});
+
+describe('emitCloneFailure', () => {
+ function makeCollectors() {
+ const emitted: Record<string, unknown>[] = [];
+ const stderr: string[] = [];
+ return {
+ emit: (event: Record<string, unknown>) => emitted.push(event),
+ printStderr: (text: string) => stderr.push(text),
+ emitted,
+ stderr,
+ };
+ }
+
+ test('--json: emits {type:"error", message} with the raw error message — wire shape unchanged', () => {
+ const c = makeCollectors();
+ emitCloneFailure({
+ error: new Error('fatal: could not read Username'),
+ url: 'inkeep/playbooks',
+ branch: 'main',
+ json: true,
+ emit: c.emit,
+ printStderr: c.printStderr,
+ });
+ expect(c.emitted).toHaveLength(1);
+ expect(c.emitted[0]).toEqual({
+ type: 'error',
+ message: 'fatal: could not read Username',
+ });
+ expect(c.stderr).toHaveLength(0);
+ });
+
+ test('--json: shape unchanged for non-auth failures too', () => {
+ const c = makeCollectors();
+ emitCloneFailure({
+ error: new Error('connection timed out'),
+ url: 'inkeep/playbooks',
+ json: true,
+ emit: c.emit,
+ printStderr: c.printStderr,
+ });
+ expect(c.emitted[0]).toEqual({ type: 'error', message: 'connection timed out' });
+ });
+
+ test('interactive + login-fixable: prints the 2-step instruction; does not emit JSON', () => {
+ const c = makeCollectors();
+ emitCloneFailure({
+ error: new Error('fatal: could not read Username'),
+ url: 'inkeep/playbooks',
+ branch: 'main',
+ json: false,
+ emit: c.emit,
+ printStderr: c.printStderr,
+ });
+ expect(c.emitted).toHaveLength(0);
+ expect(c.stderr.join('')).toContain('1. Run: ok auth login');
+ expect(c.stderr.join('')).toContain('2. Then re-run: ok clone inkeep/playbooks -b main');
+ });
+
+ test('interactive + 403: prints the hint, no login instruction', () => {
+ const c = makeCollectors();
+ emitCloneFailure({
+ error: new Error('HTTP 403 Forbidden'),
+ url: 'inkeep/private',
+ json: false,
+ emit: c.emit,
+ printStderr: c.printStderr,
+ });
+ const out = c.stderr.join('');
+ expect(out).toContain('Access denied when cloning inkeep/private');
+ expect(out).not.toContain('ok auth login');
+ });
+
+ test("interactive + non-auth: falls through to today's ✗ <message> line", () => {
+ const c = makeCollectors();
+ emitCloneFailure({
+ error: new Error("fatal: couldn't find remote ref refs/heads/foo"),
+ url: 'inkeep/playbooks',
+ branch: 'foo',
+ json: false,
+ emit: c.emit,
+ printStderr: c.printStderr,
+ });
+ expect(c.stderr.join('')).toBe("✗ fatal: couldn't find remote ref refs/heads/foo\n");
+ });
+
+ test('same actionable message regardless of TTY — no isTTY branch in the helper', () => {
+ const c1 = makeCollectors();
+ const c2 = makeCollectors();
+ const args = {
+ error: new Error('fatal: terminal prompts disabled'),
+ url: 'inkeep/playbooks',
+ branch: 'main',
+ json: false,
+ };
+ emitCloneFailure({ ...args, emit: c1.emit, printStderr: c1.printStderr });
+ emitCloneFailure({ ...args, emit: c2.emit, printStderr: c2.printStderr });
+ expect(c1.stderr.join('')).toBe(c2.stderr.join(''));
+ });
+});
diff --git a/packages/cli/src/commands/clone.ts b/packages/cli/src/commands/clone.ts
index e0364bfb4..c88e7e9e1 100644
--- a/packages/cli/src/commands/clone.ts
+++ b/packages/cli/src/commands/clone.ts
@@ -1,11 +1,17 @@
import { existsSync, readdirSync } from 'node:fs';
import { resolve } from 'node:path';
-import { isBranchNotFoundGitError } from '@inkeep/open-knowledge-core';
+import {
+ type ClassifiedGitAuthError,
+ classifyGitAuthError,
+ isBranchNotFoundGitError,
+ isLoginFixableGitAuthError,
+ shellSingleQuote,
+} from '@inkeep/open-knowledge-core';
import type { Config } from '@inkeep/open-knowledge-server';
import { Command } from 'commander';
import simpleGit, { type SimpleGitOptions } from 'simple-git';
import { resolveAuth } from '../auth/resolve-auth.ts';
-import { makeLazyTokenStore } from '../auth/token-store.ts';
+import { makeLazyTokenStore, type TokenStore } from '../auth/token-store.ts';
import { OK_DIR } from '../constants.ts';
import { parseGitUrl } from '../github/url.ts';
import { isGitHubRepoPublic } from '../github/visibility.ts';
@@ -80,9 +86,28 @@ interface CloneOptions {
type CredentialHelperUnsafeGitOptions = SimpleGitOptions & {
unsafe?: NonNullable<SimpleGitOptions['unsafe']> & {
allowUnsafeCredentialHelper?: boolean;
+ allowUnsafePager?: boolean;
+ allowUnsafeSshCommand?: boolean;
+ allowUnsafeAskPass?: boolean;
};
};
+export function buildCloneGitOptions(
+ cwd: string,
+ gitConfig: string[],
+): Partial<CredentialHelperUnsafeGitOptions> {
+ return {
+ baseDir: cwd,
+ config: gitConfig,
+ unsafe: {
+ allowUnsafeCredentialHelper: true,
+ allowUnsafePager: true,
+ allowUnsafeSshCommand: true,
+ allowUnsafeAskPass: true,
+ },
+ };
+}
+
export function shouldSkipAuthForPublicRepo(
protocol: string,
hostname: string,
@@ -91,6 +116,15 @@ export function shouldSkipAuthForPublicRepo(
return protocol === 'https' && hostname === 'github.com' && isPublic;
}
+export function resolveCloneUrl(
+ rawUrl: string,
+ parsed: { hostname: string; owner: string; name: string },
+): string {
+ const ownerRepo = `${parsed.owner}/${parsed.name}`;
+ const isShorthand = rawUrl === ownerRepo || rawUrl === `${ownerRepo}.git`;
+ return isShorthand ? `https://${parsed.hostname}/${ownerRepo}` : rawUrl;
+}
+
async function runClone(
url: string,
opts: CloneOptions,
@@ -101,6 +135,7 @@ async function runClone(
if (!parsed) {
throw new Error(`Invalid git URL: ${url}`);
}
+ const cloneUrl = resolveCloneUrl(url, parsed);
const targetDir = opts.dir ? resolve(cwd, opts.dir) : resolve(cwd, parsed.name);
@@ -123,12 +158,7 @@ async function runClone(
const gitConfig = resolved.credentialArgs.length >= 2 ? [resolved.credentialArgs[1]] : [];
- const gitOptions: Partial<CredentialHelperUnsafeGitOptions> = {
- baseDir: cwd,
- config: gitConfig,
- unsafe: { allowUnsafeCredentialHelper: true },
- };
-
+ const gitOptions = buildCloneGitOptions(cwd, gitConfig);
const git = simpleGit(gitOptions as Partial<SimpleGitOptions>).env(env);
let lastPct = -1;
@@ -153,7 +183,7 @@ async function runClone(
typeof opts.branch === 'string' && opts.branch.length > 0 ? opts.branch : null;
await cloneWithBranchFallback({
branch: requestedBranch,
- clone: (args) => git.clone(url, targetDir, args),
+ clone: (args) => git.clone(cloneUrl, targetDir, args),
onFallback: (branch) => {
emit(opts.json, { type: 'branch-fallback', branch });
if (!opts.json) {
@@ -201,6 +231,122 @@ export function ensureOkExcludedFromGit(
return 'already-present';
}
+const SHELL_SAFE_TOKEN = /^[A-Za-z0-9._/:@-]+$/;
+
+function quoteIfNeeded(s: string): string {
+ return SHELL_SAFE_TOKEN.test(s) ? s : shellSingleQuote(s);
+}
+
+function reconstructCloneCommand(url: string, branch: string | null | undefined): string {
+ const branchSuffix =
+ typeof branch === 'string' && branch.length > 0 ? ` -b ${quoteIfNeeded(branch)}` : '';
+ return `ok clone ${quoteIfNeeded(url)}${branchSuffix}`;
+}
+
+export function formatCloneAuthFailure(opts: {
+ error: unknown;
+ url: string;
+ branch?: string | null;
+ principal?: string | null;
+}): string | null {
+ const classified: ClassifiedGitAuthError = classifyGitAuthError(opts.error);
+ if (classified.kind !== 'auth') return null;
+
+ if (isLoginFixableGitAuthError(classified)) {
+ const reRun = reconstructCloneCommand(opts.url, opts.branch);
+ return [
+ `✗ Couldn't clone ${opts.url} — authentication is required.`,
+ '',
+ ' To fix:',
+ ' 1. Run: ok auth login',
+ ` 2. Then re-run: ${reRun}`,
+ ].join('\n');
+ }
+
+ if (classified.subclass === '403') {
+ const principalHint =
+ typeof opts.principal === 'string' && opts.principal.length > 0
+ ? ` (signed in as @${opts.principal} — may lack access)`
+ : '';
+ return `✗ Access denied when cloning ${opts.url}${principalHint}. Check that your account has access to the repository.`;
+ }
+
+ if (classified.subclass === 'ssh-auth') {
+ return `✗ Couldn't clone ${opts.url} over SSH — authentication failed. Check that your SSH key is added to your GitHub account and the host key is trusted, or clone the HTTPS URL instead.`;
+ }
+
+ return [
+ '✗ Your GitHub token is missing required OAuth scopes — likely the `repo` scope.',
+ '',
+ ' To fix:',
+ ' 1. Create a token with `repo` scope at https://github.com/settings/tokens',
+ ' 2. Run: ok auth pat',
+ ` 3. Then re-run: ${reconstructCloneCommand(opts.url, opts.branch)}`,
+ ].join('\n');
+}
+
+export function emitCloneFailure(opts: {
+ error: unknown;
+ url: string;
+ branch?: string | null;
+ json: boolean;
+ emit: (event: Record<string, unknown>) => void;
+ printStderr: (text: string) => void;
+ principal?: string | null;
+}): void {
+ const rawMessage = opts.error instanceof Error ? opts.error.message : String(opts.error);
+ if (opts.json) {
+ opts.emit({ type: 'error', message: rawMessage });
+ return;
+ }
+ const actionable = formatCloneAuthFailure({
+ error: opts.error,
+ url: opts.url,
+ branch: opts.branch,
+ principal: opts.principal,
+ });
+ opts.printStderr(`${actionable ?? `✗ ${rawMessage}`}\n`);
+}
+
+export async function resolveClonePrincipal(
+ tokenStore: TokenStore,
+ host: string,
+): Promise<string | null> {
+ const entry = await tokenStore.get(host);
+ const login = entry?.login;
+ return login && login !== 'unknown' ? login : null;
+}
+
+export async function handleCloneFailure(opts: {
+ error: unknown;
+ url: string;
+ branch: string | null;
+ json: boolean;
+ emit: (event: Record<string, unknown>) => void;
+ printStderr: (text: string) => void;
+ resolvePrincipal?: (host: string) => Promise<string | null>;
+}): Promise<void> {
+ const classified = classifyGitAuthError(opts.error);
+ let principal: string | null = null;
+ if (!opts.json && classified.kind === 'auth' && classified.subclass === '403') {
+ const target = parseGitUrl(opts.url);
+ if (target) {
+ const resolve =
+ opts.resolvePrincipal ?? ((host) => resolveClonePrincipal(makeLazyTokenStore(), host));
+ principal = await resolve(target.hostname);
+ }
+ }
+ emitCloneFailure({
+ error: opts.error,
+ url: opts.url,
+ branch: opts.branch,
+ json: opts.json,
+ principal,
+ emit: opts.emit,
+ printStderr: opts.printStderr,
+ });
+}
+
export function cloneCommand(getConfig: () => Config): Command {
return new Command('clone')
.description('Clone a git repository and open it')
@@ -227,12 +373,14 @@ export function cloneCommand(getConfig: () => Config): Command {
await startCmd.parseAsync([], { from: 'user' });
}
} catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- if (opts.json) {
- emit(true, { type: 'error', message: msg });
- } else {
- process.stderr.write(`✗ ${msg}\n`);
- }
+ await handleCloneFailure({
+ error: err,
+ url,
+ branch: opts.branch ?? null,
+ json: opts.json,
+ emit: (event) => emit(true, event),
+ printStderr: (text) => process.stderr.write(text),
+ });
process.exitCode = 1;
}
},
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 196a81979..9862e8c0d 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -513,6 +513,7 @@ export {
CheckoutRequestSchema,
type CheckoutResponse,
CheckoutResponseSchema,
+ type ClassifiedGitAuthError,
type ClientLogEntry,
ClientLogEntrySchema,
type ClientLogsRequest,
@@ -533,6 +534,7 @@ export {
CreatePageRequestSchema,
type CreatePageSuccess,
CreatePageSuccessSchema,
+ classifyGitAuthError,
type DeadLinkEntry,
DeadLinkEntrySchema,
type DeadLinkSource,
@@ -581,6 +583,7 @@ export {
FrontmatterPatchRequestSchema,
type FrontmatterPatchSuccess,
FrontmatterPatchSuccessSchema,
+ type GitAuthFailureSubclass,
type HeadingEntry as PageHeadingEntry,
HeadingEntrySchema as PageHeadingEntrySchema,
type HistoryEntry,
@@ -602,6 +605,7 @@ export {
type InstallSkillSuccess,
InstallSkillSuccessSchema,
isBranchNotFoundGitError,
+ isLoginFixableGitAuthError,
isValidBranchName,
type LifecycleStatus,
LifecycleStatusSchema,
diff --git a/packages/core/src/schemas/api/share.test.ts b/packages/core/src/schemas/api/share.test.ts
new file mode 100644
index 000000000..319d1a74a
--- /dev/null
+++ b/packages/core/src/schemas/api/share.test.ts
@@ -0,0 +1,235 @@
+import { describe, expect, test } from 'bun:test';
+import {
+ type ClassifiedGitAuthError,
+ classifyGitAuthError,
+ isBranchNotFoundGitError,
+ isLoginFixableGitAuthError,
+ isValidBranchName,
+} from './share.ts';
+
+function withGitStderr(message: string, stderr: string): Error & { git: string } {
+ const err = new Error(message) as Error & { git: string };
+ err.git = stderr;
+ return err;
+}
+
+describe('classifyGitAuthError', () => {
+ test('returns non-auth for null / undefined', () => {
+ expect(classifyGitAuthError(null)).toEqual({ kind: 'non-auth' });
+ expect(classifyGitAuthError(undefined)).toEqual({ kind: 'non-auth' });
+ });
+
+ test('returns non-auth for branch-not-found', () => {
+ expect(
+ classifyGitAuthError(new Error("fatal: couldn't find remote ref refs/heads/feat-x")),
+ ).toEqual({ kind: 'non-auth' });
+ });
+
+ test('returns non-auth for network errors', () => {
+ expect(classifyGitAuthError(new Error('could not resolve host github.com'))).toEqual({
+ kind: 'non-auth',
+ });
+ expect(classifyGitAuthError(new Error('connection timed out'))).toEqual({ kind: 'non-auth' });
+ });
+
+ test('classifies "could not read Username" as no-credential (GIT_TERMINAL_PROMPT=0 case)', () => {
+ expect(
+ classifyGitAuthError(new Error('fatal: could not read Username for https://github.com')),
+ ).toEqual({ kind: 'auth', subclass: 'no-credential' });
+ });
+
+ test('classifies "could not read Password" as no-credential', () => {
+ expect(
+ classifyGitAuthError(new Error('fatal: could not read Password for https://github.com')),
+ ).toEqual({ kind: 'auth', subclass: 'no-credential' });
+ });
+
+ test('classifies "terminal prompts disabled" as no-credential', () => {
+ expect(classifyGitAuthError(new Error('fatal: terminal prompts disabled'))).toEqual({
+ kind: 'auth',
+ subclass: 'no-credential',
+ });
+ });
+
+ test('classifies HTTP 401 as 401', () => {
+ expect(classifyGitAuthError(new Error('remote: HTTP 401 Unauthorized'))).toEqual({
+ kind: 'auth',
+ subclass: '401',
+ });
+ });
+
+ test('classifies forward "token ... expired" as 401 (expired-token folds into 401)', () => {
+ expect(classifyGitAuthError(new Error('GitHub token has expired'))).toEqual({
+ kind: 'auth',
+ subclass: '401',
+ });
+ });
+
+ test('classifies reversed "expired token" as unknown-auth, not 401', () => {
+ expect(classifyGitAuthError(new Error('expired token'))).toEqual({
+ kind: 'auth',
+ subclass: 'unknown-auth',
+ });
+ });
+
+ test('classifies HTTP 403 as 403', () => {
+ expect(classifyGitAuthError(new Error('remote: HTTP 403 Forbidden'))).toEqual({
+ kind: 'auth',
+ subclass: '403',
+ });
+ });
+
+ test('classifies "insufficient scopes" as scope-mismatch', () => {
+ expect(classifyGitAuthError(new Error('insufficient scopes — required: repo'))).toEqual({
+ kind: 'auth',
+ subclass: 'scope-mismatch',
+ });
+ });
+
+ test('classifies "missing scope" as scope-mismatch', () => {
+ expect(classifyGitAuthError(new Error('GitHub token missing required scope: repo'))).toEqual({
+ kind: 'auth',
+ subclass: 'scope-mismatch',
+ });
+ });
+
+ test('classifies "Authentication failed" as unknown-auth (no 401/403)', () => {
+ expect(classifyGitAuthError(new Error('remote: Authentication failed'))).toEqual({
+ kind: 'auth',
+ subclass: 'unknown-auth',
+ });
+ });
+
+ test('classifies "Bad credentials" as unknown-auth (no 401/403)', () => {
+ expect(classifyGitAuthError(new Error('remote: Bad credentials'))).toEqual({
+ kind: 'auth',
+ subclass: 'unknown-auth',
+ });
+ });
+
+ test('classifies SSH publickey denied as ssh-auth (not login-fixable)', () => {
+ expect(classifyGitAuthError(new Error('Permission denied (publickey).'))).toEqual({
+ kind: 'auth',
+ subclass: 'ssh-auth',
+ });
+ });
+
+ test('classifies host key verification failed as ssh-auth (not login-fixable)', () => {
+ expect(classifyGitAuthError(new Error('Host key verification failed.'))).toEqual({
+ kind: 'auth',
+ subclass: 'ssh-auth',
+ });
+ });
+
+ test('classifies "fatal: repository not found" as unknown-auth (private-repo masquerade)', () => {
+ expect(
+ classifyGitAuthError(new Error("fatal: repository 'https://github.com/o/r.git' not found")),
+ ).toEqual({ kind: 'auth', subclass: 'unknown-auth' });
+ });
+
+ test('reads stderr from simple-git-style { message, git } shape', () => {
+ expect(
+ classifyGitAuthError(
+ withGitStderr('Clone failed', 'fatal: could not read Username for https://github.com'),
+ ),
+ ).toEqual({ kind: 'auth', subclass: 'no-credential' });
+ });
+
+ test('accepts plain string inputs', () => {
+ expect(classifyGitAuthError('HTTP 403 Forbidden')).toEqual({
+ kind: 'auth',
+ subclass: '403',
+ });
+ expect(classifyGitAuthError('happy path output')).toEqual({ kind: 'non-auth' });
+ });
+
+ test('no-credential takes priority over an incidental 401 substring', () => {
+ expect(
+ classifyGitAuthError(
+ new Error(
+ 'fatal: could not read Username for https://github.com\nremote: HTTP 401 Unauthorized',
+ ),
+ ),
+ ).toEqual({ kind: 'auth', subclass: 'no-credential' });
+ });
+
+ test('scope-mismatch takes priority over an incidental 403', () => {
+ expect(classifyGitAuthError(new Error('insufficient scopes\nHTTP 403 Forbidden'))).toEqual({
+ kind: 'auth',
+ subclass: 'scope-mismatch',
+ });
+ });
+});
+
+describe('isLoginFixableGitAuthError', () => {
+ const cases: ReadonlyArray<{ input: ClassifiedGitAuthError; expected: boolean }> = [
+ { input: { kind: 'auth', subclass: 'no-credential' }, expected: true },
+ { input: { kind: 'auth', subclass: '401' }, expected: true },
+ { input: { kind: 'auth', subclass: 'unknown-auth' }, expected: true },
+ { input: { kind: 'auth', subclass: '403' }, expected: false },
+ { input: { kind: 'auth', subclass: 'scope-mismatch' }, expected: false },
+ { input: { kind: 'auth', subclass: 'ssh-auth' }, expected: false },
+ { input: { kind: 'non-auth' }, expected: false },
+ ];
+
+ for (const { input, expected } of cases) {
+ const label = input.kind === 'auth' ? `auth/${input.subclass}` : 'non-auth';
+ test(`${label} → ${expected}`, () => {
+ expect(isLoginFixableGitAuthError(input)).toBe(expected);
+ });
+ }
+});
+
+describe('isValidBranchName', () => {
+ test('accepts a plain branch', () => expect(isValidBranchName('main')).toBe(true));
+ test('accepts a slashed namespaced branch', () =>
+ expect(isValidBranchName('feat/foo')).toBe(true));
+ test('accepts dots within a segment (not a `..` segment)', () =>
+ expect(isValidBranchName('feat..ure')).toBe(true));
+
+ test('rejects a non-string', () => {
+ expect(isValidBranchName(null)).toBe(false);
+ expect(isValidBranchName(undefined)).toBe(false);
+ expect(isValidBranchName(42)).toBe(false);
+ });
+ test('rejects an empty string', () => expect(isValidBranchName('')).toBe(false));
+ test('rejects a leading dash (git flag injection)', () => {
+ expect(isValidBranchName('-rf')).toBe(false);
+ expect(isValidBranchName('--upload-pack=evil')).toBe(false);
+ });
+ test('rejects control characters', () => {
+ expect(isValidBranchName(`main${String.fromCharCode(0)}evil`)).toBe(false);
+ expect(isValidBranchName(`main${String.fromCharCode(7)}bell`)).toBe(false);
+ });
+ test('rejects whitespace', () => {
+ expect(isValidBranchName('feat ure')).toBe(false);
+ expect(isValidBranchName('feat\ture')).toBe(false);
+ });
+ test('rejects a colon (refspec-separator injection)', () =>
+ expect(isValidBranchName('HEAD:refs/heads/evil')).toBe(false));
+ test('rejects a `..` path-traversal segment', () => {
+ expect(isValidBranchName('feat/../evil')).toBe(false);
+ expect(isValidBranchName('../evil')).toBe(false);
+ });
+});
+
+describe('isBranchNotFoundGitError', () => {
+ test('matches the "couldn\'t find remote ref" variants (case-insensitive)', () => {
+ expect(
+ isBranchNotFoundGitError(new Error("fatal: couldn't find remote ref refs/heads/x")),
+ ).toBe(true);
+ expect(
+ isBranchNotFoundGitError(new Error("fatal: Couldn't find remote ref refs/heads/x")),
+ ).toBe(true);
+ });
+ test('matches the older "Remote branch ... not found" format', () =>
+ expect(
+ isBranchNotFoundGitError(new Error('Remote branch feat-x not found in upstream origin')),
+ ).toBe(true));
+ test('does not match other git failures (auth / network / nullish)', () => {
+ expect(isBranchNotFoundGitError(new Error('remote: HTTP 403 Forbidden'))).toBe(false);
+ expect(isBranchNotFoundGitError(new Error('could not resolve host github.com'))).toBe(false);
+ expect(isBranchNotFoundGitError(null)).toBe(false);
+ expect(isBranchNotFoundGitError(undefined)).toBe(false);
+ });
+});
diff --git a/packages/core/src/schemas/api/share.ts b/packages/core/src/schemas/api/share.ts
index a9ebdd5d1..e53cd7dac 100644
--- a/packages/core/src/schemas/api/share.ts
+++ b/packages/core/src/schemas/api/share.ts
@@ -162,6 +162,87 @@ export function isBranchNotFoundGitError(error: unknown): boolean {
return /couldn'?t find remote ref|Remote branch .+ not found/i.test(message);
}
+export type GitAuthFailureSubclass =
+ | 'no-credential'
+ | '401'
+ | '403'
+ | 'scope-mismatch'
+ | 'ssh-auth'
+ | 'unknown-auth';
+
+export type ClassifiedGitAuthError =
+ | { kind: 'auth'; subclass: GitAuthFailureSubclass }
+ | { kind: 'non-auth' };
+
+const GIT_AUTH_NO_CREDENTIAL_PATTERNS: RegExp[] = [
+ /could not read (username|password)/i,
+ /terminal prompts disabled/i,
+];
+
+const GIT_AUTH_SCOPE_MISMATCH_PATTERNS: RegExp[] = [
+ /insufficient scopes/i,
+ /missing.*scope/i,
+ /required scope/i,
+];
+
+const GIT_AUTH_SSH_PATTERNS: RegExp[] = [
+ /permission denied.*\(publickey\)/i,
+ /host key verification failed/i,
+];
+
+const GIT_AUTH_GENERAL_PATTERNS: RegExp[] = [
+ /\b(401|403)\b/,
+ /authentication failed/i,
+ /authorization failed/i,
+ /invalid credentials/i,
+ /credential helper/i,
+ /bad credentials/i,
+ /token.*expired/i,
+ /expired.*token/i,
+ /fatal:.*repository.*not found/i,
+];
+
+function gitAuthExtractStderr(error: unknown): string {
+ if (error === null || typeof error !== 'object') return '';
+ const git = (error as { git?: unknown }).git;
+ return git == null ? '' : String(git);
+}
+
+export function classifyGitAuthError(error: unknown): ClassifiedGitAuthError {
+ if (error === null || error === undefined) return { kind: 'non-auth' };
+ const message = error instanceof Error ? error.message : String(error);
+ const combined = `${message}\n${gitAuthExtractStderr(error)}`;
+
+ if (GIT_AUTH_NO_CREDENTIAL_PATTERNS.some((re) => re.test(combined))) {
+ return { kind: 'auth', subclass: 'no-credential' };
+ }
+ if (GIT_AUTH_SCOPE_MISMATCH_PATTERNS.some((re) => re.test(combined))) {
+ return { kind: 'auth', subclass: 'scope-mismatch' };
+ }
+ if (GIT_AUTH_SSH_PATTERNS.some((re) => re.test(combined))) {
+ return { kind: 'auth', subclass: 'ssh-auth' };
+ }
+ if (GIT_AUTH_GENERAL_PATTERNS.some((re) => re.test(combined))) {
+ if (/\b401\b/.test(combined) || /token.*expired/i.test(combined)) {
+ return { kind: 'auth', subclass: '401' };
+ }
+ if (/\b403\b/.test(combined)) {
+ return { kind: 'auth', subclass: '403' };
+ }
+ return { kind: 'auth', subclass: 'unknown-auth' };
+ }
+ return { kind: 'non-auth' };
+}
+
+export function isLoginFixableGitAuthError(classified: ClassifiedGitAuthError): boolean {
+ if (classified.kind !== 'auth') return false;
+ return (
+ classified.subclass === 'no-credential' ||
+ classified.subclass === '401' ||
+ classified.subclass === 'unknown-auth'
+ );
+}
+
const BranchInfoSharedFields = {
shareTargetExists: z.boolean(),
dirtyConflicts: z
diff --git a/packages/server/src/error-classification.test.ts b/packages/server/src/error-classification.test.ts
index 6368385cf..207094e60 100644
--- a/packages/server/src/error-classification.test.ts
+++ b/packages/server/src/error-classification.test.ts
@@ -97,6 +97,13 @@ describe('classifyGitError', () => {
expect(r.retryable).toBe(false);
});
+ test('reversed "expired token" wording → unknown-auth, not 401 (delegation preserves output)', () => {
+ const r = classifyGitError(mkErr('expired token'));
+ expect(r.class).toBe('auth');
+ expect(r.subclass).toBe('unknown-auth');
+ expect(r.retryable).toBe(false);
+ });
+
test('permission denied (publickey)', () => {
const r = classifyGitError(mkErr('Permission denied (publickey).'));
expect(r.class).toBe('auth');
@@ -150,6 +157,34 @@ describe('classifyGitError', () => {
test('deriveUserFacingCode maps auth/no-credential', () => {
expect(deriveUserFacingCode('auth', 'no-credential')).toBe('auth-no-credential');
});
+
+ test('unknown-auth subclass — "Authentication failed" without 401/403 signal', () => {
+ const r = classifyGitError(mkErr('Authentication failed for remote'));
+ expect(r.class).toBe('auth');
+ expect(r.subclass).toBe('unknown-auth');
+ expect(r.retryable).toBe(false);
+ expect(r.message).toBe('Authentication failed');
+ });
+
+ test('unknown-auth subclass — bad credentials without 401/403 signal', () => {
+ const r = classifyGitError(mkErr('remote: Bad credentials'));
+ expect(r.class).toBe('auth');
+ expect(r.subclass).toBe('unknown-auth');
+ });
+
+ test('ssh-auth subclass — SSH publickey denied (delegation preserves output)', () => {
+ const r = classifyGitError(mkErr('Permission denied (publickey).'));
+ expect(r.class).toBe('auth');
+ expect(r.subclass).toBe('ssh-auth');
+ expect(r.retryable).toBe(false);
+ expect(r.message).toBe('SSH authentication failed — check your SSH key or host-key trust');
+ });
+
+ test('ssh-auth subclass — host key verification failed', () => {
+ const r = classifyGitError(mkErr('Host key verification failed.'));
+ expect(r.class).toBe('auth');
+ expect(r.subclass).toBe('ssh-auth');
+ });
});
describe('Class 3 — Semantic (non-retryable)', () => {
@@ -317,8 +352,8 @@ describe('classifyGitError', () => {
expect(r.retryable).toBe(true);
});
- test('ENOSPC', () => {
- const r = classifyGitError(mkErr('ENOSPC: no space left on device'));
+ test('bare ENOSPC (case-insensitive, no "no space left" text to fall back on)', () => {
+ const r = classifyGitError(mkErr('fatal: write error: ENOSPC'));
expect(r.class).toBe('local');
expect(r.subclass).toBe('disk-full');
expect(r.retryable).toBe(true);
diff --git a/packages/server/src/error-classification.ts b/packages/server/src/error-classification.ts
index a41fe19de..11b3f5d31 100644
--- a/packages/server/src/error-classification.ts
+++ b/packages/server/src/error-classification.ts
@@ -1,4 +1,8 @@
-import type { SyncErrorCode } from '@inkeep/open-knowledge-core';
+import {
+ classifyGitAuthError,
+ type GitAuthFailureSubclass,
+ type SyncErrorCode,
+} from '@inkeep/open-knowledge-core';
type NetworkSubclass = 'dns' | 'timeout' | '5xx' | '429' | 'connection-refused' | 'unknown-network';
type AuthSubclass =
@@ -7,6 +11,7 @@ type AuthSubclass =
| 'expired-token'
| 'scope-mismatch'
| 'no-credential'
+ | 'ssh-auth'
| 'unknown-auth';
type SemanticSubclass =
| 'non-fast-forward'
@@ -86,30 +91,14 @@ function matchesAny(haystack: string, patterns: RegExp[]): boolean {
return patterns.some((re) => re.test(haystack));
}
-const AUTH_PATTERNS: RegExp[] = [
- /\b(401|403)\b/,
- /authentication failed/i,
- /authorization failed/i,
- /invalid credentials/i,
- /credential helper/i,
- /bad credentials/i,
- /token.*expired/i,
- /expired.*token/i,
- /permission denied.*\(publickey\)/i,
- /host key verification failed/i,
- /fatal:.*repository.*not found/i, // often auth-related on private repos
-];
-
-const NO_CREDENTIAL_PATTERNS: RegExp[] = [
- /could not read (username|password)/i,
- /terminal prompts disabled/i,
-];
-
-const SCOPE_MISMATCH_PATTERNS: RegExp[] = [
- /insufficient scopes/i,
- /missing.*scope/i,
- /required scope/i,
-];
+const AUTH_SUBCLASS_MESSAGES: Record<GitAuthFailureSubclass, string> = {
+ 'no-credential': 'No GitHub credential available — reconnect to resume syncing',
+ '401': 'Authentication failed — token may be expired',
+ '403': 'Access denied (403)',
+ 'scope-mismatch': 'GitHub token missing required scopes',
+ 'ssh-auth': 'SSH authentication failed — check your SSH key or host-key trust',
+ 'unknown-auth': 'Authentication failed',
+};
const NON_FAST_FORWARD_PATTERNS: RegExp[] = [
/non-fast-forward/i,
@@ -182,7 +171,11 @@ const DIRTY_TREE_PATTERNS: RegExp[] = [
/commit your changes or stash/i,
];
-const DISK_FULL_PATTERNS: RegExp[] = [/no space left on device/i, /disk quota exceeded/i, /ENOSPC/];
+const DISK_FULL_PATTERNS: RegExp[] = [
+ /no space left on device/i,
+ /disk quota exceeded/i,
+ /ENOSPC/i,
+];
const NETWORK_PATTERNS: RegExp[] = [
/could not resolve host/i,
@@ -257,57 +250,22 @@ function classifyGitErrorBase(error: Error | unknown): ClassifiedErrorBase {
};
}
- if (matchesAny(combined, NO_CREDENTIAL_PATTERNS)) {
- return {
- class: 'auth',
- subclass: 'no-credential',
- retryable: false,
- message: 'No GitHub credential available — reconnect to resume syncing',
- rawStderr: raw,
- };
- }
- if (matchesAny(combined, SCOPE_MISMATCH_PATTERNS)) {
- return {
- class: 'auth',
- subclass: 'scope-mismatch',
- retryable: false,
- message: 'GitHub token missing required scopes',
- rawStderr: raw,
- };
- }
- if (matchesAny(combined, AUTH_PATTERNS)) {
- if (/\b401\b/.test(combined) || /token.*expired/i.test(combined)) {
- return {
- class: 'auth',
- subclass: '401',
- retryable: false,
- message: 'Authentication failed — token may be expired',
- rawStderr: raw,
- };
- }
- if (/\b403\b/.test(combined)) {
- if (matchesAny(combined, PROTECTED_BRANCH_PATTERNS)) {
- return {
- class: 'semantic',
- subclass: 'protected-branch',
- retryable: false,
- message: 'Push rejected — branch is protected',
- rawStderr: raw,
- };
- }
+ const authResult = classifyGitAuthError(err);
+ if (authResult.kind === 'auth') {
+ if (authResult.subclass === '403' && matchesAny(combined, PROTECTED_BRANCH_PATTERNS)) {
return {
- class: 'auth',
- subclass: '403',
+ class: 'semantic',
+ subclass: 'protected-branch',
retryable: false,
- message: 'Access denied (403)',
+ message: 'Push rejected — branch is protected',
rawStderr: raw,
};
}
return {
class: 'auth',
- subclass: 'unknown-auth',
+ subclass: authResult.subclass,
retryable: false,
- message: 'Authentication failed',
+ message: AUTH_SUBCLASS_MESSAGES[authResult.subclass],
rawStderr: raw,
};
}