diff --git a/src/device-oauth.ts b/src/device-oauth.ts index 5edc7906..6bdca3b0 100644 --- a/src/device-oauth.ts +++ b/src/device-oauth.ts @@ -32,6 +32,16 @@ type DeviceRecord = { const noStoreHeaders = { "Content-Type": "application/json", "Cache-Control": "no-store", Pragma: "no-cache" }; const json = (body: unknown, status = 200) => Response.json(body, { status, headers: noStoreHeaders }); const oauthError = (error: string, description: string, status = 400) => json({ error, error_description: description }, status); +export function deviceLoginRedirect(appOrigin: string, returnTo: string): Response { + return new Response(null, { + status: 302, + headers: { + "Cache-Control": "no-store", + Location: `${appOrigin}/auth/linear`, + "Set-Cookie": `factorize_oauth_return=${encodeURIComponent(returnTo)}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=600`, + }, + }); +} const random = (bytes = 32) => { const value = crypto.getRandomValues(new Uint8Array(bytes)); return btoa(String.fromCharCode(...value)).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); @@ -139,14 +149,6 @@ export async function deviceToken(request: Request, env: Env, oauthProvider: { f if (!await authenticateDeviceClient(request, env, form, { clientId: record.clientId, redirectUris: [record.redirectUri], tokenEndpointAuthMethod: record.tokenEndpointAuthMethod })) return oauthError("invalid_client", "Client authentication failed.", 401); if (record.status === "denied") return oauthError("access_denied", "The resource owner denied the request."); if (record.status === "pending") { - if (record.lastPolledAt && now - record.lastPolledAt < record.interval) { - record.interval += 5; - record.lastPolledAt = now; - await env.OAUTH_KV.put(deviceKey(deviceCode), JSON.stringify(record), { expirationTtl: Math.max(1, record.expiresAt - now) }); - return oauthError("slow_down", "Polling is too frequent."); - } - record.lastPolledAt = now; - await env.OAUTH_KV.put(deviceKey(deviceCode), JSON.stringify(record), { expirationTtl: Math.max(1, record.expiresAt - now) }); return oauthError("authorization_pending", "The resource owner has not completed authorization."); } if (!record.authorizationCode) return oauthError("server_error", "The approved device grant is incomplete.", 500); diff --git a/src/exe.ts b/src/exe.ts index 1def1948..429ba1a4 100644 --- a/src/exe.ts +++ b/src/exe.ts @@ -109,7 +109,7 @@ export function connectionCheckCommand(): string { /** exe.dev executes non-interactive shells, which do not load the user's PATH customizations. */ function herdrPrefix(connection: ExeConnection): string { - return `export PATH="$HOME/.local/bin:$PATH" && command -v ${shellAtom(herdrBinary(connection))}`; + return `export PATH="$HOME/.local/bin:$PATH" && command -v ${shellAtom(herdrBinary(connection))} >/dev/null`; } function herdrBinary(connection: ExeConnection): string { diff --git a/src/index.ts b/src/index.ts index f83dc3f9..6aa6959e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,6 @@ import { Hono } from "hono"; import { deleteCookie, getCookie, setCookie } from "hono/cookie"; +import { parse } from "hono/utils/cookie"; import { equalHmac, hmac } from "./crypto"; import { Tenant } from "./tenant"; import { GitHubInstallationRegistry } from "./github-registry"; @@ -42,6 +43,10 @@ export async function readSession(value: string | undefined, secret: string): Pr if (!body || !signature || signature !== await hmac(body, secret)) return null; try { const session = JSON.parse(unb64(body)) as Session; return session.exp > Math.floor(Date.now() / 1000) ? session : null; } catch { return null; } } +export const requestCookie = (request: Request, name: string) => { + const header = request.headers.get("Cookie"); + return header ? parse(header, name)[name] : undefined; +}; function tenant(c: { env: Env }, tenantId: string) { return c.env.TENANTS.get(c.env.TENANTS.idFromName(`tenant:${tenantId}`)); } function githubRegistry(c: { env: Env }) { if (!c.env.GITHUB_INSTALLATIONS) throw new Error("GitHub registry is not configured"); return c.env.GITHUB_INSTALLATIONS.get(c.env.GITHUB_INSTALLATIONS.idFromName("github-installations")); } diff --git a/src/protected-api.ts b/src/protected-api.ts index 636b643b..4ec528a2 100644 --- a/src/protected-api.ts +++ b/src/protected-api.ts @@ -76,7 +76,8 @@ export class ProtectedApiHandler extends WorkerEntrypoint { tool("stop_run", "Stop an active run", runIdSchema, ({ runId }: any) => service.stopRun(runId)); const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined }); await server.connect(transport); - const mcpApp = createMcpHonoApp(); + const appHostname = new URL(this.env.APP_ORIGIN).hostname; + const mcpApp = createMcpHonoApp({ host: appHostname, allowedHosts: [appHostname], allowedOrigins: [appHostname] }); mcpApp.all("/mcp", c => transport.handleRequest(c.req.raw, { parsedBody: (c as any).get("parsedBody") })); return mcpApp.fetch(request, this.env, this.ctx); } diff --git a/src/recovery.ts b/src/recovery.ts index 0d41b6b9..e419b0a5 100644 --- a/src/recovery.ts +++ b/src/recovery.ts @@ -7,8 +7,28 @@ function identity(value: unknown): HerdrIdentity | null { const result = { name: str(agent.name, agent.agent_name), status: str(agent.agent_status, agent.status, agent.state).toLowerCase(), kind: str(agent.agent_kind, agent.kind), workspaceId: str(agent.workspace_id, obj(agent.workspace).id), paneId: str(agent.pane_id, obj(agent.pane).id), terminalId: str(agent.terminal_id, obj(agent.terminal).id), cwd: str(agent.cwd), sessionSource: typeof session.source === "string" ? session.source : str(agent.session_source), sessionKind: str(session.kind, source.kind, agent.session_kind), sessionValue: str(session.value, session.id, source.value, agent.session_id, agent.session_value) }; return result.name || result.paneId || result.sessionValue ? result : null; } -export function parseAgent(body: string): HerdrIdentity | null { for (const candidate of [body, ...body.trim().split(/\n/).reverse()]) { try { const parsed = obj(JSON.parse(candidate)); const found = identity(obj(parsed.result).agent ?? parsed.agent ?? parsed.result ?? parsed); if (found) return found; } catch {} } return null; } -export function parseAgentList(body: string): HerdrIdentity[] { try { const parsed = obj(JSON.parse(body)), result = obj(parsed.result); const values = Array.isArray(result.agents) ? result.agents : Array.isArray(parsed.agents) ? parsed.agents : Array.isArray(parsed.result) ? parsed.result : []; return values.map(identity).filter((value): value is HerdrIdentity => value !== null); } catch { return []; } } +function jsonObjects(body: string): Record[] { + const values: Record[] = []; + let start = -1, depth = 0, quoted = false, escaped = false; + for (let index = 0; index < body.length; index++) { + const char = body[index]!; + if (quoted) { + if (escaped) escaped = false; + else if (char === "\\") escaped = true; + else if (char === '"') quoted = false; + continue; + } + if (char === '"' && depth > 0) { quoted = true; continue; } + if (char === "{") { if (depth++ === 0) start = index; continue; } + if (char === "}" && depth > 0 && --depth === 0 && start >= 0) { + try { values.push(obj(JSON.parse(body.slice(start, index + 1)))); } catch { /* ignore non-JSON output */ } + start = -1; + } + } + return values; +} +export function parseAgent(body: string): HerdrIdentity | null { for (const parsed of jsonObjects(body).reverse()) { const found = identity(obj(parsed.result).agent ?? parsed.agent ?? parsed.result ?? parsed); if (found) return found; } return null; } +export function parseAgentList(body: string): HerdrIdentity[] { for (const parsed of jsonObjects(body).reverse()) { const result = obj(parsed.result); const values = Array.isArray(result.agents) ? result.agents : Array.isArray(parsed.agents) ? parsed.agents : Array.isArray(parsed.result) ? parsed.result : []; const agents = values.map(identity).filter((value): value is HerdrIdentity => value !== null); if (agents.length || values.length) return agents; } return []; } export function sameStableSession(saved: Partial, live: HerdrIdentity): boolean { return Boolean(saved.sessionValue && live.sessionValue && saved.sessionValue === live.sessionValue && (!saved.sessionKind || !live.sessionKind || saved.sessionKind === live.sessionKind)); } export function matchesLineage(saved: Partial, live: HerdrIdentity): boolean { return Boolean((saved.terminalId && saved.terminalId === live.terminalId) || (saved.paneId && saved.paneId === live.paneId && (!saved.workspaceId || !live.workspaceId || saved.workspaceId === live.workspaceId))); } export function safeToAdopt(saved: Partial, live: HerdrIdentity, claimedSessions: Set): boolean { return matchesLineage(saved, live) && (!saved.kind || saved.kind === live.kind) && (!saved.cwd || saved.cwd === live.cwd) && !claimedSessions.has(live.sessionValue); } @@ -16,4 +36,7 @@ export function safeToAdopt(saved: Partial, live: HerdrIdentity, export function ownsPane(saved: Partial, live: HerdrIdentity, worktreePath: string): boolean { return Boolean(saved.terminalId && saved.terminalId === live.terminalId && worktreePath && live.cwd === worktreePath && (!saved.paneId || saved.paneId === live.paneId)); } +export function findOwnedAgent(saved: Partial, agents: HerdrIdentity[], worktreePath: string, expectedName: string, expectedKind: string): HerdrIdentity | undefined { + return agents.find((agent) => ownsPane(saved, agent, worktreePath)) ?? agents.find((agent) => agent.name === expectedName && agent.cwd === worktreePath && (!expectedKind || agent.kind === expectedKind)); +} export function parsePaneProcess(body: string): PaneProcess | null { try { const parsed = obj(JSON.parse(body)), result = obj(parsed.result), foreground = obj(result.foreground ?? result.process ?? parsed.foreground ?? parsed); const pane = obj(result.pane); const pid = Number(foreground.pid ?? result.pid), processGroup = Number(foreground.process_group ?? foreground.pgid ?? result.process_group ?? result.pgid); if (!Number.isSafeInteger(pid) || pid <= 1 || !Number.isSafeInteger(processGroup) || processGroup <= 1) return null; return { paneId: str(result.pane_id, pane.pane_id, pane.id, parsed.pane_id), pid, processGroup, argv: Array.isArray(foreground.argv) ? foreground.argv.map(String) : [], executable: str(foreground.executable, foreground.exe), cwd: str(foreground.cwd, result.cwd) }; } catch { return null; } } diff --git a/src/tenant.ts b/src/tenant.ts index 95836c36..c70ffcf5 100644 --- a/src/tenant.ts +++ b/src/tenant.ts @@ -2,7 +2,7 @@ import { DurableObject } from "cloudflare:workers"; import Mustache from "mustache"; import { decrypt, encrypt } from "./crypto"; import { agentListCommand, agentOutputCommand, agentStatusCommand, connectionCheckCommand, defaultAgentCommand, exec, garbageCollectPaneCommand, herdrAgentStatus, herdrCheckCommand, paneGetCommand, paneProcessInfoCommand, replaceForegroundCommand, startAgentCommand, startAgentInPaneCommand, stopAgentCommand, validateWorktreeLeaseCommand, type ExeConnection } from "./exe"; -import { ownsPane, parseAgent, parseAgentList, parsePaneProcess, type HerdrIdentity } from "./recovery"; +import { findOwnedAgent, ownsPane, parseAgent, parseAgentList, parsePaneProcess, type HerdrIdentity } from "./recovery"; import { LINEAR_ISSUE_PROJECT_QUERY, LINEAR_OPTION_QUERIES, LINEAR_PROJECTS_QUERY } from "./linear"; import { matchingIssue } from "./matcher"; import type { Env, ExeConnectionInput, FilterType, MatchRule, PipeInput, RunState } from "./types"; @@ -379,9 +379,10 @@ export class Tenant extends DurableObject { } private async getRun(runId: string): Promise { - const run = this.one("SELECT id, pipe_id AS flow_id, issue_id, issue_url, agent_name, workspace_name, agent_kind, state, provider, result, exec_status, exec_exit_code, created_at, updated_at FROM runs WHERE id = ?", runId); + const run = this.one("SELECT id, pipe_id AS flow_id, issue_id, issue_url, agent_name, workspace_name, agent_kind, state, provider, result, exec_status, exec_exit_code, recovery_last_action, created_at, updated_at FROM runs WHERE id = ?", runId); if (!run) return new Response("Not found", { status: 404 }); if (run.state !== "ignored" && typeof run.result === "string" && run.result) run.result = await decrypt(run.result, this.env.CREDENTIAL_ENCRYPTION_KEY); + run.activity = this.rows("SELECT action, detail, created_at FROM run_activity WHERE run_id = ? ORDER BY created_at, id", runId); return json(run); } @@ -631,9 +632,11 @@ export class Tenant extends DurableObject { const execRequest = await encrypt(result.requestBody, this.env.CREDENTIAL_ENCRYPTION_KEY); const execResponse = await encrypt(result.body, this.env.CREDENTIAL_ENCRYPTION_KEY); this.ctx.storage.sql.exec("UPDATE runs SET exec_request = ?, exec_response = ?, exec_status = ?, exec_exit_code = ?, updated_at = ? WHERE id = ?", execRequest, execResponse, result.status, result.exitCode, now(), run.id); + this.commandActivity(run.id, "initial agent start", result); if (!result.ok || (result.exitCode !== null && result.exitCode !== 0)) return this.finishRun(run, "failed", `Unable to start Herdr agent (exe.dev HTTP ${result.status}, VM exit ${result.exitCode ?? "not reported"}): ${result.body.slice(0, 800)}`); this.ctx.storage.sql.exec("UPDATE runs SET prompt_accepted=1,updated_at=? WHERE id=?", now(), run.id); const verification = await exec(connection, agentStatusCommand(connection, String(run.agent_name))); + this.commandActivity(run.id, "initial agent verification", verification); if (!verification.ok || (verification.exitCode !== null && verification.exitCode !== 0) || !herdrAgentStatus(verification.body)) { return this.beginRecovery(run, pipe, connection, `agent start succeeded but verification was ambiguous (exe.dev HTTP ${verification.status}, VM exit ${verification.exitCode ?? "not reported"})`); } @@ -682,7 +685,20 @@ export class Tenant extends DurableObject { this.ctx.storage.sql.exec("INSERT INTO run_activity VALUES (?,?,?,?,?)", id(), runId, action, detail.slice(0, 1000), now()); } - private commandActivity(runId: unknown, command: string, result: { ok: boolean; status: number; exitCode: number | null }): void { this.activity(runId, "herdr_command", `${command}: HTTP ${result.status}, VM exit ${result.exitCode ?? "not reported"}, ${result.ok ? "request succeeded" : "request failed"}`); } + private diagnosticExcerpt(body: string): string { + return body.slice(-700) + .replace(/("(?:authorization|cookie|token|secret|credential|prompt|body)"\s*:\s*")[^"]*/gi, "$1[redacted]") + .replace(/\bBearer\s+[A-Za-z0-9._~+\/-]+/gi, "Bearer [redacted]") + .replace(/\bexe1[A-Za-z0-9_-]+/g, "[redacted exe.dev token]") + .replace(/[A-Za-z0-9+/_-]{80,}={0,2}/g, "[redacted long value]") + .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, " ") + .trim(); + } + + private commandActivity(runId: unknown, command: string, result: { ok: boolean; status: number; exitCode: number | null; body?: string }): void { + const excerpt = result.body ? this.diagnosticExcerpt(result.body) : ""; + this.activity(runId, "herdr_command", `${command}: HTTP ${result.status}, VM exit ${result.exitCode ?? "not reported"}, ${result.ok ? "request succeeded" : "request failed"}${excerpt ? `; response: ${excerpt}` : "; empty response"}`); + } private async beginRecovery(run: Row, pipe: Row, connection: ExeConnection, reason: string): Promise { const started = !run.recovery_started_at; @@ -703,11 +719,12 @@ export class Tenant extends DurableObject { const timeoutMs = Math.max(15_000, Number(this.env.RECOVERY_TIMEOUT_MS) || 5 * 60_000), maxAttempts = Math.max(1, Number(this.env.RECOVERY_MAX_ATTEMPTS) || 8); if (attempt > maxAttempts || Date.now() - Date.parse(String(run.recovery_started_at)) > timeoutMs) return this.finishRecovery(run, "failed", "Automatic recovery exhausted its bounded retry budget."); this.ctx.storage.sql.exec("UPDATE runs SET recovery_attempt=?,recovery_last_action='listing Herdr agents',updated_at=? WHERE id=?", attempt, now(), run.id); + this.activity(run.id, "recovery_attempt", `Attempt ${attempt}/${maxAttempts}; elapsed ${Math.max(0, Date.now() - Date.parse(String(run.recovery_started_at)))}ms of ${timeoutMs}ms budget.`); const listed = await exec(connection, agentListCommand(connection)); this.commandActivity(run.id, "agent list", listed); if (!listed.ok || (listed.exitCode !== null && listed.exitCode !== 0)) { this.scheduleRecovery(run.id, attempt, "transient Herdr agent-list failure"); return; } const agents = parseAgentList(listed.body), saved = this.savedIdentity(run); - const owned = agents.find((agent) => ownsPane(saved, agent, String(run.worktree_path || ""))); + const owned = findOwnedAgent(saved, agents, String(run.worktree_path || ""), String(run.agent_name || ""), connection.agentKind); if (owned) { const rotated = String(run.agent_session_value || "") !== owned.sessionValue; this.persistIdentity(run.id, owned, "running", rotated); @@ -751,6 +768,7 @@ export class Tenant extends DurableObject { const lease = crypto.randomUUID(), worktreePath = `${connection.cwd.replace(/\/$/, "")}/.factorize-worktrees/${String(run.id)}-recovery-${attempt}`; this.ctx.storage.sql.exec("UPDATE runs SET worktree_path=?,ownership_lease=?,ownership_generation=ownership_generation+1 WHERE id=?", worktreePath, lease, run.id); const replacement = await exec(connection, startAgentCommand(String(run.agent_name), connection, recoveryPrompt, String(run.workspace_name), worktreePath, lease)); + this.commandActivity(run.id, "replacement agent start", replacement); if (replacement.ok && (replacement.exitCode === null || replacement.exitCode === 0)) this.ctx.storage.sql.exec("UPDATE runs SET prompt_accepted=1 WHERE id=?", run.id); const live = replacement.ok ? parseAgent(replacement.body) : null; if (live) return this.finishRecovery(run, "running", "Recreated the deleted pane/workspace and started a replacement harness.", live); diff --git a/src/worker.ts b/src/worker.ts index adcbe84a..c105c134 100644 --- a/src/worker.ts +++ b/src/worker.ts @@ -1,16 +1,14 @@ import { OAuthProvider, AuthorizationError, getOAuthApi, type AuthRequest, type OAuthProviderOptions } from "@cloudflare/workers-oauth-provider"; -import app, { readSession } from "./index"; +import app, { readSession, requestCookie } from "./index"; import { ProtectedApiHandler } from "./protected-api"; import { hmac } from "./crypto"; -import { addDeviceMetadata, DEVICE_GRANT, deviceAuthorization, deviceClientRegistration, deviceToken, deviceVerification } from "./device-oauth"; +import { addDeviceMetadata, DEVICE_GRANT, deviceAuthorization, deviceClientRegistration, deviceLoginRedirect, deviceToken, deviceVerification } from "./device-oauth"; import type { Env, OAuthProps } from "./types"; const scopes = ["flows:read", "flows:write", "runs:read", "runs:write"]; const escape = (value: string) => value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """); -const cookie = (request: Request, name: string) => request.headers.get("Cookie")?.split(";").map(v => v.trim()).find(v => v.startsWith(`${name}=`))?.slice(name.length + 1); - async function currentOwner(request: Request, env: Env) { - const session = await readSession(cookie(request, "factorize_session"), env.SESSION_SIGNING_SECRET); + const session = await readSession(requestCookie(request, "factorize_session"), env.SESSION_SIGNING_SECRET); if (!session) return null; const stub = env.TENANTS.get(env.TENANTS.idFromName(`tenant:${session.tenantId}`)); const response = await stub.fetch(`https://tenant/members/${encodeURIComponent(session.userId)}`); @@ -36,9 +34,7 @@ const defaultHandler: ExportedHandler = { try { const session = await currentOwner(request, env); if (!session) { - const response = Response.redirect(`${env.APP_ORIGIN}/auth/linear`, 302); - response.headers.append("Set-Cookie", `factorize_oauth_return=${encodeURIComponent(url.pathname + url.search)}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=600`); - return response; + return deviceLoginRedirect(env.APP_ORIGIN, url.pathname + url.search); } if (url.pathname === "/device") return deviceVerification(request, env, env.OAUTH_PROVIDER!, session); if (request.method === "GET") { diff --git a/test/device-oauth.test.ts b/test/device-oauth.test.ts index 304bd408..55331381 100644 --- a/test/device-oauth.test.ts +++ b/test/device-oauth.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from "vitest"; -import { addDeviceMetadata, DEVICE_GRANT, deviceAuthorization, deviceClientRegistration, deviceToken, deviceVerification } from "../src/device-oauth"; +import { addDeviceMetadata, DEVICE_GRANT, deviceAuthorization, deviceClientRegistration, deviceLoginRedirect, deviceToken, deviceVerification } from "../src/device-oauth"; import type { Env } from "../src/types"; class MemoryKv { @@ -24,6 +24,14 @@ function environment(kv: MemoryKv): Env { const publicClient = { clientId: "client-1", clientName: "Codex", redirectUris: ["http://127.0.0.1/callback"], tokenEndpointAuthMethod: "none" }; describe("OAuth device authorization", () => { + it("redirects unauthenticated device approval through login and preserves the device code", () => { + const response = deviceLoginRedirect("https://factorize.test", "/device?user_code=ABCD-2345"); + expect(response.status).toBe(302); + expect(response.headers.get("cache-control")).toBe("no-store"); + expect(response.headers.get("location")).toBe("https://factorize.test/auth/linear"); + expect(response.headers.get("set-cookie")).toContain("factorize_oauth_return=%2Fdevice%3Fuser_code%3DABCD-2345"); + }); + it("issues RFC 8628 device and user codes", async () => { const kv = new MemoryKv(), env = environment(kv); const response = await deviceAuthorization(new Request("https://factorize.test/oauth/device_authorization", { @@ -48,13 +56,13 @@ describe("OAuth device authorization", () => { await expect(badResource.json()).resolves.toMatchObject({ error: "invalid_target" }); }); - it("returns authorization_pending and slow_down while approval is outstanding", async () => { + it("keeps polling read-only while approval is outstanding", async () => { const kv = new MemoryKv(), env = environment(kv); const issue = await deviceAuthorization(new Request("https://factorize.test/oauth/device_authorization", { method: "POST", body: new URLSearchParams({ client_id: "client-1", scope: "runs:read" }) }), env, { lookupClient: vi.fn().mockResolvedValue(publicClient), completeAuthorization: vi.fn() }, ["flows:read", "runs:read"]); const { device_code } = await issue.json() as any; const poll = () => deviceToken(new Request("https://factorize.test/oauth/token", { method: "POST", body: new URLSearchParams({ grant_type: DEVICE_GRANT, client_id: "client-1", device_code }) }), env, { fetch: vi.fn() }, {} as ExecutionContext); await expect((await poll()).json()).resolves.toMatchObject({ error: "authorization_pending" }); - await expect((await poll()).json()).resolves.toMatchObject({ error: "slow_down" }); + await expect((await poll()).json()).resolves.toMatchObject({ error: "authorization_pending" }); }); it("approves a code and exchanges it through the normal PKCE token endpoint", async () => { diff --git a/test/recovery.test.ts b/test/recovery.test.ts index b073493a..4775f810 100644 --- a/test/recovery.test.ts +++ b/test/recovery.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { matchesLineage, ownsPane, parseAgent, parseAgentList, parsePaneProcess, safeToAdopt, sameStableSession } from "../src/recovery"; +import { findOwnedAgent, matchesLineage, ownsPane, parseAgent, parseAgentList, parsePaneProcess, safeToAdopt, sameStableSession } from "../src/recovery"; const moved = { name: "renamed", status: "working", kind: "codex", workspaceId: "ws-2", paneId: "pane-2", terminalId: "term-1", cwd: "/repo", sessionSource: "codex", sessionKind: "thread", sessionValue: "session-7" }; @@ -26,6 +26,21 @@ describe("Herdr 0.9 recovery identity", () => { expect(agents[0]).toMatchObject({ name: "flow-1", paneId: "pane-1", sessionValue: "abc" }); }); + it("parses pretty JSON after non-JSON command output", () => { + const wireAgent = { name: "renamed", agent_status: "working", agent_kind: "codex", workspace_id: "ws-2", pane_id: "pane-2", terminal_id: "term-1", cwd: "/repo", session_identity: { source: "codex", kind: "thread", value: "session-7" } }; + const body = `/home/exedev/.local/bin/herdr\nAgent started\n${JSON.stringify({ result: { agent: wireAgent } }, null, 2)}`; + expect(parseAgent(body)).toMatchObject({ name: "renamed", paneId: "pane-2" }); + const list = `/home/exedev/.local/bin/herdr\n${JSON.stringify({ result: { agents: [wireAgent] } }, null, 2)}`; + expect(parseAgentList(list)).toHaveLength(1); + }); + + it("recovers pre-persistence agents by exact alias, kind, and unique worktree", () => { + const expected = { ...moved, name: "run-agent", cwd: "/repo/.factorize-worktrees/run-1" }; + const wrongCwd = { ...expected, cwd: "/repo/human" }; + expect(findOwnedAgent({}, [wrongCwd, expected], expected.cwd, "run-agent", "codex")).toBe(expected); + expect(findOwnedAgent({}, [wrongCwd], expected.cwd, "run-agent", "codex")).toBeUndefined(); + }); + it("adopts only matching cwd/kind/lineage and unclaimed sessions", () => { const saved = { terminalId: "term-1", kind: "codex", cwd: "/repo" }; expect(safeToAdopt(saved, moved, new Set())).toBe(true); diff --git a/test/worker.test.ts b/test/worker.test.ts index 392c69e0..c65d56cc 100644 --- a/test/worker.test.ts +++ b/test/worker.test.ts @@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; vi.mock("cloudflare:workers", () => ({ DurableObject: class {} })); -import app, { signSession } from "../src/index"; +import app, { requestCookie, signSession } from "../src/index"; import type { Env } from "../src/types"; type StubHandler = (request: Request) => Response | Promise; @@ -54,6 +54,12 @@ function ownerHandler(routes: Record Response)>): Stub describe("Worker routes", () => { beforeEach(() => vi.restoreAllMocks()); + it("decodes URL-encoded session cookies in OAuth routes", async () => { + const session = await signSession({ tenantId: "workspace-1", userId: "user-1", email: "owner@example.com", exp: Math.floor(Date.now() / 1000) + 60, sessionVersion: 1 }, "session-secret"); + const request = new Request("https://factorize.test/device", { headers: { cookie: `factorize_session=${encodeURIComponent(session)}` } }); + expect(requestCookie(request, "factorize_session")).toBe(session); + }); + it("serves the landing page with nonce-protected scripts", async () => { const response = await app.request("https://factorize.test/", {}, testEnv(() => new Response("Not found", { status: 404 }))); const html = await response.text(); diff --git a/test/workspace.test.ts b/test/workspace.test.ts index 3b4118b9..0ed486ce 100644 --- a/test/workspace.test.ts +++ b/test/workspace.test.ts @@ -56,7 +56,9 @@ describe("flow workspaces", () => { }); it("makes the user-local Herdr binary available to non-interactive VM commands", () => { - expect(agentStatusCommand({ vmName: "vm", apiToken: "token", agentKind: "codex", cwd: "/repo" }, "factorize-1")).toContain('export PATH="$HOME/.local/bin:$PATH"'); + const command = agentStatusCommand({ vmName: "vm", apiToken: "token", agentKind: "codex", cwd: "/repo" }, "factorize-1"); + expect(command).toContain('export PATH="$HOME/.local/bin:$PATH"'); + expect(command).toContain("command -v 'herdr' >/dev/null"); }); it("reads Herdr's current agent_status response field", () => {