Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 10 additions & 8 deletions src/device-oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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("=", "");
Expand Down Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion src/exe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
5 changes: 5 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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")); }
Expand Down
3 changes: 2 additions & 1 deletion src/protected-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,8 @@ export class ProtectedApiHandler extends WorkerEntrypoint<Env, OAuthProps> {
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);
}
Expand Down
27 changes: 25 additions & 2 deletions src/recovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,36 @@ 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<string, any>[] {
const values: Record<string, any>[] = [];
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<HerdrIdentity>, 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<HerdrIdentity>, 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<HerdrIdentity>, live: HerdrIdentity, claimedSessions: Set<string>): boolean { return matchesLineage(saved, live) && (!saved.kind || saved.kind === live.kind) && (!saved.cwd || saved.cwd === live.cwd) && !claimedSessions.has(live.sessionValue); }
/** Native sessions and aliases may rotate; terminal + worktree own the pane. */
export function ownsPane(saved: Partial<HerdrIdentity>, 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<HerdrIdentity>, 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; } }
26 changes: 22 additions & 4 deletions src/tenant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -379,9 +379,10 @@ export class Tenant extends DurableObject<Env> {
}

private async getRun(runId: string): Promise<Response> {
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);
}

Expand Down Expand Up @@ -631,9 +632,11 @@ export class Tenant extends DurableObject<Env> {
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"})`);
}
Expand Down Expand Up @@ -682,7 +685,20 @@ export class Tenant extends DurableObject<Env> {
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<void> {
const started = !run.recovery_started_at;
Expand All @@ -703,11 +719,12 @@ export class Tenant extends DurableObject<Env> {
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);
Expand Down Expand Up @@ -751,6 +768,7 @@ export class Tenant extends DurableObject<Env> {
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);
Expand Down
12 changes: 4 additions & 8 deletions src/worker.ts
Original file line number Diff line number Diff line change
@@ -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("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
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)}`);
Expand All @@ -36,9 +34,7 @@ const defaultHandler: ExportedHandler<Env> = {
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") {
Expand Down
Loading