mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-09-30 12:39:42 +02:00
Adds an Add Case -> "Clone Repo" tab plus two endpoints, implementing @DodgyBadger's proposal in #236: clone a public repository straight into codeman-cases/<name> and register it as a normal local case. POST /api/cases/clone is synchronous by design (request held open, bounded by GIT_CLONE_TIMEOUT_MS): no job store, no polling, no cancellation surface. Success broadcasts the usual case:created event, so the case still appears when a proxy idle-timeout kills the request mid-clone. POST /api/cases/clone-preflight runs `git ls-remote --symref` so the UI can say, while the user is still typing, whether the URL is cloneable without credentials, what its default branch is, and which branches/tags exist. Core lives in src/git-clone.ts, split into a pure half (URL parse, argv/env, ls-remote parse, stderr classification) and a thin IO half, so every security decision is unit-testable without spawning anything: - `<name>::<payload>` transports are refused as a family, not by name: ext:: is the famous one, but any of them dispatches to git-remote-<name> and turns a clone into arbitrary command execution. - A leading `-` is refused AND every spawn puts `--` before the operands. Either alone is one edit away from being a hole. - argv arrays, never a shell. URLs carrying user:password@ are refused. - gitNonInteractiveEnv() closes all four ways git can block on a prompt with no terminal attached (terminal prompt, askpass/GUI, ssh, GCM). HOME/PATH stay inherited, so a user's own credential helper or ssh agent keeps working; Codeman itself collects and stores nothing. - The timeout signals the process GROUP, since clone fans out into git-remote-https/index-pack children that outlive a signal to the parent. - Bounded output (redacted stderr tail, capped ls-remote stdout, 500 refs each) and a global 2-op pool, so N large clones cannot exhaust the host. Repository contents beat scaffolding: an existing CLAUDE.md is kept, hooks are merged into whatever .claude/settings.local.json the repo shipped, and a repo that ships its own Claude settings is reported back as a warning (those hooks run locally as soon as a session starts there). A failed clone removes only the directory the attempt created, and refuses a pre-existing destination outright, so it can never squat on a case name. Not admin-gated in multi-user mode, unlike /api/cases/link: it writes only inside the caller's own case space. Local-path/file:// sources are the exception and stay admin-only there. UI: live verdict under the URL field, case name filled from the parsed repo until the user types their own, branch/tag as a datalist of the remote's real refs, optional shallow clone, and a Brain picker (installed CLIs only) that points the Run button at the chosen agent. Starting a session stays opt-in. The tab hides itself when the server reports no git. Tests: the pure half exhaustively (every refusal has a case), plus real git against a real local bare repo for clone/ref/timeout/cleanup, and a route-level suite with unmocked fs that clones through the endpoint. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
188 lines
8.0 KiB
TypeScript
188 lines
8.0 KiB
TypeScript
/**
|
|
* WebServer.renderIndexHtml — server-side gating of the index shell:
|
|
* - multi-monitor button reveal (stable class-marker, not brittle copy match)
|
|
* - solo (/session/:id) global injection + escaping, and settings skipped
|
|
* - gesture overlay availability vs. enablement (CODEMAN_GESTURE + setting)
|
|
* - settings read FRESH so a post-save reload doesn't render stale state
|
|
*
|
|
* WebServer's constructor only assigns fields (no port bind), so we construct it
|
|
* directly, swap in a tiny indexHtmlTemplate, and stub readSettings to avoid disk.
|
|
*
|
|
* Port: N/A (no server start).
|
|
*/
|
|
import { describe, it, expect, afterEach, vi } from 'vitest';
|
|
import { WebServer } from '../src/web/server.js';
|
|
import { isClaudeAvailable } from '../src/utils/claude-cli-resolver.js';
|
|
import { isOpenCodeAvailable } from '../src/utils/opencode-cli-resolver.js';
|
|
import { isCodexAvailable } from '../src/utils/codex-cli-resolver.js';
|
|
import { isGeminiAvailable } from '../src/utils/gemini-cli-resolver.js';
|
|
import { isAntigravityAvailable } from '../src/utils/antigravity-cli-resolver.js';
|
|
import { isCloudflaredAvailable } from '../src/utils/cloudflared-resolver.js';
|
|
import { isGitAvailable } from '../src/git-clone.js';
|
|
|
|
// renderIndexHtml probes the real PATH for every CLI, which would make the
|
|
// assertions below depend on whatever happens to be installed on the machine
|
|
// running the suite. Default them all to "not installed" and opt in per test.
|
|
vi.mock('../src/utils/claude-cli-resolver.js', () => ({
|
|
isClaudeAvailable: vi.fn(() => false),
|
|
findClaudeDir: vi.fn(() => null),
|
|
}));
|
|
vi.mock('../src/utils/opencode-cli-resolver.js', () => ({
|
|
isOpenCodeAvailable: vi.fn(() => false),
|
|
resolveOpenCodeDir: vi.fn(() => null),
|
|
}));
|
|
vi.mock('../src/utils/codex-cli-resolver.js', () => ({
|
|
isCodexAvailable: vi.fn(() => false),
|
|
resolveCodexDir: vi.fn(() => null),
|
|
}));
|
|
vi.mock('../src/utils/gemini-cli-resolver.js', () => ({
|
|
isGeminiAvailable: vi.fn(() => false),
|
|
resolveGeminiDir: vi.fn(() => null),
|
|
}));
|
|
vi.mock('../src/utils/antigravity-cli-resolver.js', () => ({
|
|
isAntigravityAvailable: vi.fn(() => false),
|
|
resolveAntigravityDir: vi.fn(() => null),
|
|
}));
|
|
vi.mock('../src/utils/cloudflared-resolver.js', () => ({
|
|
isCloudflaredAvailable: vi.fn(() => false),
|
|
resolveCloudflaredPath: vi.fn(() => null),
|
|
}));
|
|
// git gates the Add Case -> Clone Repo tab (#236), so it rides in the same object.
|
|
vi.mock('../src/git-clone.js', () => ({
|
|
isGitAvailable: vi.fn(() => false),
|
|
}));
|
|
|
|
const TEMPLATE = [
|
|
'<head>',
|
|
'<title>Codeman</title>',
|
|
'</head>',
|
|
'<body>',
|
|
'<button class="btn-icon-header btn-multimonitor btn-multimonitor--hidden" aria-label="Open Codeman across all displays"></button>',
|
|
'</body>',
|
|
].join('\n');
|
|
|
|
function makeServer(settings: Record<string, unknown> = {}) {
|
|
const server = new WebServer(0, false, true);
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
(server as any).indexHtmlTemplate = TEMPLATE;
|
|
const readSettings = vi.fn(async () => settings);
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
(server as any).readSettings = readSettings;
|
|
return { server, readSettings };
|
|
}
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const render = (server: WebServer, solo?: string): Promise<string> => (server as any).renderIndexHtml(solo);
|
|
|
|
const ORIG_GESTURE = process.env.CODEMAN_GESTURE;
|
|
afterEach(() => {
|
|
if (ORIG_GESTURE === undefined) delete process.env.CODEMAN_GESTURE;
|
|
else process.env.CODEMAN_GESTURE = ORIG_GESTURE;
|
|
});
|
|
|
|
describe('WebServer.renderIndexHtml', () => {
|
|
it('keeps the multi-monitor button hidden by default and reads settings FRESH', async () => {
|
|
const { server, readSettings } = makeServer({});
|
|
const html = await render(server);
|
|
expect(html).toContain('btn-multimonitor--hidden');
|
|
// forceFresh=true — fixes the post-save reload race against the 2s cache.
|
|
expect(readSettings).toHaveBeenCalledWith(true);
|
|
});
|
|
|
|
it('reveals the multi-monitor button when showMultiMonitorButton is set', async () => {
|
|
const { server } = makeServer({ showMultiMonitorButton: true });
|
|
const html = await render(server);
|
|
expect(html).not.toContain('btn-multimonitor--hidden');
|
|
expect(html).toContain('btn-multimonitor"'); // class list still present, only the marker stripped
|
|
});
|
|
|
|
it('injects the solo global and skips settings for a /session/:id window', async () => {
|
|
const { server, readSettings } = makeServer({ showMultiMonitorButton: true });
|
|
const html = await render(server, 'sess-123');
|
|
expect(html).toContain('window.__CODEMAN_SOLO__="sess-123"');
|
|
expect(readSettings).not.toHaveBeenCalled();
|
|
// Solo skips settings, so the button is NOT revealed even though the setting is on.
|
|
expect(html).toContain('btn-multimonitor--hidden');
|
|
});
|
|
|
|
it('escapes the solo id so it cannot break out of the inline <script>', async () => {
|
|
const { server } = makeServer({});
|
|
const html = await render(server, 'a</script><b>');
|
|
expect(html).not.toContain('</script><b>');
|
|
expect(html).toContain('\\u003c');
|
|
});
|
|
|
|
it('exposes gesture availability but injects the bundle only when enabled', async () => {
|
|
process.env.CODEMAN_GESTURE = '1';
|
|
let { server } = makeServer({ gestureControlEnabled: false });
|
|
let html = await render(server);
|
|
expect(html).toContain('window.__codemanGestureAvailable=true');
|
|
expect(html).not.toContain('gesture-codeman.js');
|
|
|
|
({ server } = makeServer({ gestureControlEnabled: true }));
|
|
html = await render(server);
|
|
expect(html).toContain('window.__codemanGestureAvailable=true');
|
|
expect(html).toContain('gesture-codeman.js');
|
|
});
|
|
|
|
it('reports every tool the welcome buttons, run menu and Codex tab gate on', async () => {
|
|
vi.mocked(isClaudeAvailable).mockReturnValue(true);
|
|
vi.mocked(isOpenCodeAvailable).mockReturnValue(false);
|
|
vi.mocked(isCodexAvailable).mockReturnValue(true);
|
|
vi.mocked(isGeminiAvailable).mockReturnValue(false);
|
|
vi.mocked(isAntigravityAvailable).mockReturnValue(false);
|
|
vi.mocked(isCloudflaredAvailable).mockReturnValue(true);
|
|
vi.mocked(isGitAvailable).mockReturnValue(true);
|
|
const { server } = makeServer({});
|
|
const html = await render(server);
|
|
const flags = JSON.parse(html.match(/window\.__codemanCliAvailable=(\{.*?\});/)![1]);
|
|
// Every key must be PRESENT, not merely truthy where installed: the client
|
|
// treats a missing key as available, so a dropped key silently un-gates.
|
|
expect(flags).toEqual({
|
|
claude: true,
|
|
opencode: false,
|
|
codex: true,
|
|
gemini: false,
|
|
antigravity: false,
|
|
cloudflared: true,
|
|
git: true,
|
|
});
|
|
});
|
|
|
|
it('still emits the object when nothing at all is installed', async () => {
|
|
// The all-false case is the one that matters most and the easiest to get
|
|
// wrong by only injecting when something resolves.
|
|
for (const probe of [
|
|
isClaudeAvailable,
|
|
isOpenCodeAvailable,
|
|
isCodexAvailable,
|
|
isGeminiAvailable,
|
|
isAntigravityAvailable,
|
|
isCloudflaredAvailable,
|
|
isGitAvailable,
|
|
]) {
|
|
vi.mocked(probe).mockReturnValue(false);
|
|
}
|
|
const { server } = makeServer({});
|
|
const html = await render(server);
|
|
expect(html).toContain('window.__codemanCliAvailable=');
|
|
const flags = JSON.parse(html.match(/window\.__codemanCliAvailable=(\{.*?\});/)![1]);
|
|
expect(Object.values(flags).every((v) => v === false)).toBe(true);
|
|
});
|
|
|
|
it('skips the probe for a solo window, which has no welcome screen or run menu', async () => {
|
|
vi.mocked(isCodexAvailable).mockReturnValue(true);
|
|
const { server } = makeServer({});
|
|
const html = await render(server, 'sess-123');
|
|
expect(html).not.toContain('__codemanCliAvailable');
|
|
});
|
|
|
|
it('does not expose gesture at all when CODEMAN_GESTURE is unset', async () => {
|
|
delete process.env.CODEMAN_GESTURE;
|
|
const { server } = makeServer({ gestureControlEnabled: true });
|
|
const html = await render(server);
|
|
expect(html).not.toContain('__codemanGestureAvailable');
|
|
expect(html).not.toContain('gesture-codeman.js');
|
|
});
|
|
});
|