From 2177337f70e415a322ec12a7974b36e9273fb53b Mon Sep 17 00:00:00 2001 From: Brendan Date: Sat, 12 Sep 2026 18:33:29 +0000 Subject: [PATCH] Expose OAuth-protected flow REST and MCP APIs --- README.md | 39 +++++++++++++++++- package-lock.json | 59 +++++++++++++++++++++++++++- package.json | 6 ++- src/exe.ts | 4 ++ src/flow-schemas.ts | 29 ++++++++++++++ src/flow-service.ts | 62 +++++++++++++++++++++++++++++ src/index.ts | 6 ++- src/protected-api.ts | 83 +++++++++++++++++++++++++++++++++++++++ src/tenant.ts | 79 ++++++++++++++++++++++++++++++++++++- src/types.ts | 9 +++++ src/worker.ts | 77 ++++++++++++++++++++++++++++++++++++ test/exe.test.ts | 9 ++++- test/flow-service.test.ts | 51 ++++++++++++++++++++++++ wrangler.jsonc | 4 +- 14 files changed, 508 insertions(+), 9 deletions(-) create mode 100644 src/flow-schemas.ts create mode 100644 src/flow-service.ts create mode 100644 src/protected-api.ts create mode 100644 src/worker.ts create mode 100644 test/flow-service.test.ts diff --git a/README.md b/README.md index 076a3f02..7e08a8ba 100644 --- a/README.md +++ b/README.md @@ -29,8 +29,9 @@ Click the **Deploy to Cloudflare** button above to create a copy of this Worker 1. Clone the repository and install dependencies. 2. Set `APP_ORIGIN` in `wrangler.jsonc` to your final HTTPS Worker URL or custom domain. -3. Configure the Linear OAuth callback as `https://your-domain.example/auth/linear/callback`. -4. Build assets, add secrets, and deploy: +3. Create a dedicated OAuth KV namespace with `npx wrangler kv namespace create OAUTH_KV`, then replace `REPLACE_WITH_OAUTH_KV_ID` in `wrangler.jsonc` with its ID. +4. Configure the Linear OAuth callback as `https://your-domain.example/auth/linear/callback`. +5. Build assets, add secrets, and deploy: ```bash npm ci @@ -107,6 +108,7 @@ Matching issue updates queue work up to the flow’s configured concurrency. Whe | `CREDENTIAL_ENCRYPTION_KEY` | Base64-encoded 32-byte key for encrypted credentials | | `SESSION_SIGNING_SECRET` | Independent secret for signed browser sessions | | `APP_ORIGIN` | Public Worker origin, configured in `wrangler.jsonc` | +| `OAUTH_KV` | KV binding containing OAuth clients, grants, refresh tokens, and revocation state | Never commit `.dev.vars` or production secret values. The included `.dev.vars.example` is a safe template. @@ -122,11 +124,44 @@ Never commit `.dev.vars` or production secret values. The included `.dev.vars.ex GitHub Actions runs `npm run check` on every push and pull request. +## REST API and OAuth + +API clients use OAuth 2.1 authorization code flow with PKCE S256. Factorize publishes authorization-server and protected-resource discovery metadata, supports Client ID Metadata Documents, and retains dynamic client registration at `/oauth/register` for older clients. Access tokens last one hour and may be refreshed for up to 30 days; RFC 7009 revocation is advertised by discovery metadata. + +Available scopes are `flows:read`, `flows:write`, `runs:read`, and `runs:write`. The resource owner must sign in through the normal Linear-backed Factorize session and explicitly approve the requested scopes. Factorize rechecks owner membership and session version on every service call. + +The versioned API is rooted at `/api/v1`: + +```bash +curl -H "Authorization: Bearer $FACTORIZE_ACCESS_TOKEN" \ + https://app.factorize.sh/api/v1/flows + +curl -H "Authorization: Bearer $FACTORIZE_ACCESS_TOKEN" \ + 'https://app.factorize.sh/api/v1/runs?flowId=FLOW_ID&state=running&limit=25' + +curl -X POST -H "Authorization: Bearer $FACTORIZE_ACCESS_TOKEN" \ + https://app.factorize.sh/api/v1/runs/RUN_ID/stop +``` + +Flow CRUD is available at `/flows` and `/flows/:id`; supporting collections are `/projects`, `/flow-options`, `/runs`, and `/flow-events`. Run and event collections return `{ "items": [...], "nextCursor": "..." }`; pass `nextCursor` back as the `cursor` query parameter. Errors consistently use `{ "error": { "code": "...", "message": "..." } }`. + +## MCP clients + +Configure a compatible remote MCP client with this single URL: + +```text +https://app.factorize.sh/mcp +``` + +The client discovers OAuth automatically, opens Factorize in a browser, completes Linear sign-in if necessary, requests consent, and returns to the client after PKCE authorization. No Linear or exe.dev credential is copied into the MCP client. The server is stateless Streamable HTTP and exposes flow CRUD, projects/options, run inspection/filtering, webhook activity, and active-run stopping tools. + ## Security - Linear and exe.dev credentials, issue prompts, and agent results are AES-GCM encrypted at rest in the Durable Object. - Linear webhooks require a valid HMAC-SHA256 signature and fresh timestamp before workspace routing. - Session cookies are signed, expire after seven days, and are checked against workspace membership. +- OAuth access is tenant-bound, scope-checked, revocable, and revalidates current owner membership at the shared service boundary. +- Public REST and MCP responses omit connection tokens, credential records, prompts, and internal execution requests/responses. - Agent output is not copied into Linear; completion comments point back to the Herdr session on your VM. - The dashboard uses a restrictive content-security policy and locally built Tailwind CSS. diff --git a/package-lock.json b/package-lock.json index 691436dd..1bfad89c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,8 +8,12 @@ "name": "factorize", "version": "0.1.0", "dependencies": { + "@cloudflare/workers-oauth-provider": "^0.10.3", + "@modelcontextprotocol/hono": "^2.0.0", + "@modelcontextprotocol/server": "^2.0.0", "hono": "^4.11.4", - "mustache": "^4.2.0" + "mustache": "^4.2.0", + "zod": "^4.6.2" }, "devDependencies": { "@cloudflare/workers-types": "^5.20260910.1", @@ -132,6 +136,12 @@ "node": ">=16" } }, + "node_modules/@cloudflare/workers-oauth-provider": { + "version": "0.10.3", + "resolved": "https://registry.npmjs.org/@cloudflare/workers-oauth-provider/-/workers-oauth-provider-0.10.3.tgz", + "integrity": "sha512-25ufMONJir9PllqVpK4GwOOoSFgpYm3+bM6NBedj7ufMCIfNf5jk4OI0LPuTJBaJgLl2lGCLqFqEPJXcSuPopQ==", + "license": "MIT" + }, "node_modules/@cloudflare/workers-types": { "version": "5.20260910.1", "resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-5.20260910.1.tgz", @@ -1252,6 +1262,44 @@ "@jridgewell/sourcemap-codec": "^1.4.10" } }, + "node_modules/@modelcontextprotocol/core": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.0.0.tgz", + "integrity": "sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA==", + "license": "MIT", + "dependencies": { + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@modelcontextprotocol/hono": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/hono/-/hono-2.0.0.tgz", + "integrity": "sha512-lKCSXRusLxpX63G+6og9ewcRkqVbjB2xSxpvU/VJhxcUkpvGgpDrmcgNRQ4dTapGr8AspNFdRBdmJc500Vhl/A==", + "license": "MIT", + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "@modelcontextprotocol/server": "^2.0.0", + "hono": "^4.11.4" + } + }, + "node_modules/@modelcontextprotocol/server": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.0.0.tgz", + "integrity": "sha512-YhHWdHfpFMQfd0prsEnxKeS3Qz3ytIGmsS0sth4KDjnacIT7hxk6hXHkJ9KysxlkvTM+WZAtQbbcUhdoP4Hvtw==", + "license": "MIT", + "dependencies": { + "@modelcontextprotocol/core": "2.0.0", + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/@napi-rs/lzma-linux-x64-gnu": { "version": "1.5.1", "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz", @@ -4357,6 +4405,15 @@ "@poppinss/exception": "^1.2.2", "error-stack-parser-es": "^1.0.5" } + }, + "node_modules/zod": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.2.tgz", + "integrity": "sha512-lh5RCAGFa1Cm2hjtNwLQhSs/AsqdWnTQaBER9fEwN/88pSh7KOtJavtBx/0VlkN/uFd61SwYmljLMDAsHlvzBQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } } } } diff --git a/package.json b/package.json index 8f67cb0a..91f79d7c 100644 --- a/package.json +++ b/package.json @@ -11,8 +11,12 @@ "deploy": "wrangler deploy" }, "dependencies": { + "@cloudflare/workers-oauth-provider": "^0.10.3", + "@modelcontextprotocol/hono": "^2.0.0", + "@modelcontextprotocol/server": "^2.0.0", "hono": "^4.11.4", - "mustache": "^4.2.0" + "mustache": "^4.2.0", + "zod": "^4.6.2" }, "devDependencies": { "@cloudflare/workers-types": "^5.20260910.1", diff --git a/src/exe.ts b/src/exe.ts index d0be066b..1d306d7c 100644 --- a/src/exe.ts +++ b/src/exe.ts @@ -67,6 +67,10 @@ export function agentOutputCommand(connection: ExeConnection, agentName: string) return `${herdrPrefix(connection)} && ${herdrBinary(connection)} agent read ${shellAtom(agentName)} --source recent --format text`; } +export function stopAgentCommand(connection: ExeConnection, agentName: string): string { + return `${herdrPrefix(connection)} && ${herdrBinary(connection)} agent stop ${shellAtom(agentName)}`; +} + export function herdrCheckCommand(connection: ExeConnection): string { return `${herdrPrefix(connection)} && ${herdrBinary(connection)} --version && ${herdrBinary(connection)} workspace list`; } diff --git a/src/flow-schemas.ts b/src/flow-schemas.ts new file mode 100644 index 00000000..ce10d5eb --- /dev/null +++ b/src/flow-schemas.ts @@ -0,0 +1,29 @@ +import { z } from "zod"; + +export const scopeSchema = z.enum(["flows:read", "flows:write", "runs:read", "runs:write"]); +export const runStateSchema = z.enum(["queued", "starting", "running", "done", "blocked", "failed", "ignored"]); +export const matchRuleSchema = z.object({ + type: z.enum(["owner", "creator", "status", "label", "assignee"]), + targetId: z.string().min(1), +}); +export const flowInputSchema = z.object({ + name: z.string().trim().min(1).max(120), + flowId: z.string().trim().regex(/^[a-z0-9][a-z0-9-]*$/).optional(), + projectId: z.string().min(1), + matchRules: z.array(matchRuleSchema).min(1), + maxConcurrency: z.number().int().min(0).max(50).default(3), + workspaceName: z.string().max(120).optional(), + contextTemplate: z.string().max(50_000).optional(), + cwd: z.string().max(1_000).optional(), +}).strict(); +export const flowIdSchema = z.object({ flowId: z.string().min(1) }); +export const listRunsSchema = z.object({ + flowId: z.string().min(1).optional(), state: runStateSchema.optional(), + limit: z.coerce.number().int().min(1).max(100).default(50), cursor: z.string().min(1).optional(), +}); +export const runIdSchema = z.object({ runId: z.string().min(1) }); +export const listEventsSchema = z.object({ + flowId: z.string().min(1), limit: z.coerce.number().int().min(1).max(100).default(50), cursor: z.string().min(1).optional(), +}); + +export type FlowInput = z.infer; diff --git a/src/flow-service.ts b/src/flow-service.ts new file mode 100644 index 00000000..96a06045 --- /dev/null +++ b/src/flow-service.ts @@ -0,0 +1,62 @@ +import type { Env, OAuthProps } from "./types"; +import type { FlowInput } from "./flow-schemas"; + +export class ServiceError extends Error { + constructor(public status: number, public code: string, message: string) { super(message); } +} + +type Scope = "flows:read" | "flows:write" | "runs:read" | "runs:write"; + +export class FlowService { + constructor(private env: Env, private auth: OAuthProps) {} + + private stub() { return this.env.TENANTS.get(this.env.TENANTS.idFromName(`tenant:${this.auth.tenantId}`)); } + + private async authorize(scope: Scope): Promise { + if (!this.auth.scopes.includes(scope)) throw new ServiceError(403, "insufficient_scope", `The ${scope} scope is required.`); + const response = await this.stub().fetch(`https://tenant/members/${encodeURIComponent(this.auth.userId)}`); + if (!response.ok) throw new ServiceError(401, "invalid_token", "The resource owner is no longer a member."); + const member = await response.json() as { role?: string; session_version?: number }; + if (member.role !== "owner" || member.session_version !== this.auth.sessionVersion) throw new ServiceError(401, "invalid_token", "The resource owner's session has been revoked."); + } + + private async call(scope: Scope, path: string, init?: RequestInit): Promise { + await this.authorize(scope); + const response = await this.stub().fetch(`https://tenant${path}`, init); + let body: unknown = null; + const text = await response.text(); + if (text) { try { body = JSON.parse(text); } catch { body = { error: text }; } } + if (!response.ok) throw new ServiceError(response.status, response.status === 404 ? "not_found" : "operation_failed", (body as any)?.error ?? "Operation failed"); + return body; + } + + private publicFlow(row: any) { + let source: any = undefined; + let matchRules: unknown = undefined; + try { source = typeof row.source_config === "string" ? JSON.parse(row.source_config) : undefined; } catch { /* omit malformed internal config */ } + try { matchRules = typeof row.match_rules === "string" ? JSON.parse(row.match_rules) : undefined; } catch { /* omit malformed internal config */ } + if (source?.kind === "custom") source = { kind: "custom", origin: source.origin, handlerName: source.handlerName, deploymentState: source.handlerDeployment?.state }; + return { + id: row.id, name: row.name, projectId: row.project_id, source, + matchRules, + maxConcurrency: row.max_concurrency, workspaceName: row.workspace_name, + agentKind: row.agent_kind, cwd: row.cwd, contextTemplate: row.context_template, + enabled: Boolean(row.enabled), createdAt: row.created_at, + }; + } + + async listFlows() { return (await this.call("flows:read", "/pipes") as any[]).map(row => this.publicFlow(row)); } + async getFlow(flowId: string) { + const value = await this.call("flows:read", `/v1/flows/${encodeURIComponent(flowId)}`) as any; + return this.publicFlow(value); + } + createFlow(input: FlowInput) { return this.call("flows:write", "/pipes", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) }); } + updateFlow(flowId: string, input: FlowInput) { return this.call("flows:write", `/pipes/${encodeURIComponent(flowId)}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) }); } + deleteFlow(flowId: string) { return this.call("flows:write", `/pipes/${encodeURIComponent(flowId)}`, { method: "DELETE" }); } + listProjects() { return this.call("flows:read", "/linear/projects"); } + listFlowOptions() { return this.call("flows:read", "/linear/options"); } + listRuns(query: URLSearchParams) { return this.call("runs:read", `/v1/runs?${query}`); } + getRun(runId: string) { return this.call("runs:read", `/v1/runs/${encodeURIComponent(runId)}`); } + listFlowEvents(query: URLSearchParams) { return this.call("runs:read", `/v1/events?${query}`); } + stopRun(runId: string) { return this.call("runs:write", `/v1/runs/${encodeURIComponent(runId)}/stop`, { method: "POST" }); } +} diff --git a/src/index.ts b/src/index.ts index 1d6b80d3..35be96c1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -29,13 +29,13 @@ app.onError((error, c) => { return c.text("Internal Server Error", 500); }); -type Session = { tenantId: string; userId: string; email: string; exp: number; sessionVersion: number }; +export type Session = { tenantId: string; userId: string; email: string; exp: number; sessionVersion: number }; const textEncoder = new TextEncoder(); function b64(value: string): string { return btoa(String.fromCharCode(...textEncoder.encode(value))).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); } function unb64(value: string): string { const padded = value.replaceAll("-", "+").replaceAll("_", "/") + "===".slice((value.length + 3) % 4); return new TextDecoder().decode(Uint8Array.from(atob(padded), (char) => char.charCodeAt(0))); } export async function signSession(session: Session, secret: string): Promise { const body = b64(JSON.stringify(session)); return `${body}.${await hmac(body, secret)}`; } -async function readSession(value: string | undefined, secret: string): Promise { +export async function readSession(value: string | undefined, secret: string): Promise { if (!value) return null; const [body, signature] = value.split("."); if (!body || !signature || signature !== await hmac(body, secret)) return null; @@ -86,6 +86,8 @@ app.get("/auth/linear/callback", async (c) => { await stub.fetch("https://tenant/connections/linear", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ accessToken: tokens.access_token, refreshToken: tokens.refresh_token, organizationId: organization.id, organizationName: organization.name }) }); const lifetime = 60 * 60 * 24 * 7; setCookie(c, "factorize_session", await signSession({ tenantId: organization.id, userId: viewer.id, email: viewer.email, exp: Math.floor(Date.now() / 1000) + lifetime, sessionVersion: member.session_version }, c.env.SESSION_SIGNING_SECRET), { httpOnly: true, secure: new URL(c.env.APP_ORIGIN).protocol === "https:", sameSite: "Lax", path: "/", maxAge: lifetime }); + const oauthReturn = getCookie(c, "factorize_oauth_return"); + if (oauthReturn?.startsWith("/authorize?")) { deleteCookie(c, "factorize_oauth_return", { path: "/" }); return c.redirect(oauthReturn); } return c.redirect("/flows/new"); }); diff --git a/src/protected-api.ts b/src/protected-api.ts new file mode 100644 index 00000000..636b643b --- /dev/null +++ b/src/protected-api.ts @@ -0,0 +1,83 @@ +import { WorkerEntrypoint } from "cloudflare:workers"; +import { McpServer, WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/server"; +import { createMcpHonoApp } from "@modelcontextprotocol/hono"; +import { z } from "zod"; +import { FlowService, ServiceError } from "./flow-service"; +import { flowIdSchema, flowInputSchema, listEventsSchema, listRunsSchema, runIdSchema } from "./flow-schemas"; +import type { Env, OAuthProps } from "./types"; + +function errorResponse(error: unknown): Response { + if (error instanceof z.ZodError) return Response.json({ error: { code: "invalid_request", message: "Request validation failed", details: error.issues } }, { status: 400 }); + if (error instanceof ServiceError) { + const headers = error.code === "insufficient_scope" ? { "WWW-Authenticate": `Bearer error="insufficient_scope"` } : undefined; + return Response.json({ error: { code: error.code, message: error.message } }, { status: error.status, headers }); + } + console.error("Protected API request failed", error); + return Response.json({ error: { code: "internal_error", message: "Factorize could not complete this request." } }, { status: 500 }); +} + +function queryOf(value: Record): URLSearchParams { + const query = new URLSearchParams(); + for (const [key, item] of Object.entries(value)) if (item !== undefined) query.set(key, String(item)); + return query; +} + +function queryInput(url: URL): Record { + const value: Record = {}; + url.searchParams.forEach((item, key) => { value[key] = item; }); + return value; +} + +function structured(value: unknown) { + const output = Array.isArray(value) ? { items: value } : value && typeof value === "object" ? value as Record : { value }; + return { content: [{ type: "text" as const, text: JSON.stringify(output) }], structuredContent: output }; +} + +export class ProtectedApiHandler extends WorkerEntrypoint { + async fetch(request: Request): Promise { + try { + const url = new URL(request.url), path = url.pathname, service = new FlowService(this.env, this.ctx.props); + if (path === "/mcp") return this.mcp(request, service); + if (!path.startsWith("/api/v1")) return Response.json({ error: { code: "not_found", message: "Not found" } }, { status: 404 }); + if (request.method === "GET" && path === "/api/v1/flows") return Response.json(await service.listFlows()); + if (request.method === "POST" && path === "/api/v1/flows") return Response.json(await service.createFlow(flowInputSchema.parse(await request.json())), { status: 201 }); + const flowMatch = path.match(/^\/api\/v1\/flows\/([^/]+)$/); + if (flowMatch && request.method === "GET") return Response.json(await service.getFlow(decodeURIComponent(flowMatch[1]))); + if (flowMatch && request.method === "PUT") return Response.json(await service.updateFlow(decodeURIComponent(flowMatch[1]), flowInputSchema.parse(await request.json()))); + if (flowMatch && request.method === "DELETE") return Response.json(await service.deleteFlow(decodeURIComponent(flowMatch[1]))); + if (request.method === "GET" && path === "/api/v1/projects") return Response.json(await service.listProjects()); + if (request.method === "GET" && path === "/api/v1/flow-options") return Response.json(await service.listFlowOptions()); + if (request.method === "GET" && path === "/api/v1/runs") { const q = listRunsSchema.parse(queryInput(url)); return Response.json(await service.listRuns(queryOf(q))); } + const runMatch = path.match(/^\/api\/v1\/runs\/([^/]+)$/); + if (runMatch && request.method === "GET") return Response.json(await service.getRun(decodeURIComponent(runMatch[1]))); + const stopMatch = path.match(/^\/api\/v1\/runs\/([^/]+)\/stop$/); + if (stopMatch && request.method === "POST") return Response.json(await service.stopRun(decodeURIComponent(stopMatch[1]))); + if (request.method === "GET" && path === "/api/v1/flow-events") { const q = listEventsSchema.parse(queryInput(url)); return Response.json(await service.listFlowEvents(queryOf(q))); } + return Response.json({ error: { code: "not_found", message: "Not found" } }, { status: 404 }); + } catch (error) { return errorResponse(error); } + } + + private async mcp(request: Request, service: FlowService): Promise { + const server = new McpServer({ name: "factorize", version: "1.0.0" }); + const tool = (name: string, description: string, schema: any, action: (input: T) => Promise) => server.registerTool(name, { description, inputSchema: schema }, async (input: T) => { + try { return structured(await action(input)); } + catch (error) { const response = errorResponse(error), detail = await response.json() as any; throw new Error(`${detail.error?.code ?? "operation_failed"}: ${detail.error?.message ?? "Operation failed"}`); } + }); + tool("list_flows", "List Factorize flows", z.object({}), () => service.listFlows()); + tool("get_flow", "Get a flow", flowIdSchema, ({ flowId }: any) => service.getFlow(flowId)); + tool("create_flow", "Create a flow", flowInputSchema, (input: any) => service.createFlow(input)); + tool("update_flow", "Update a flow", flowInputSchema.extend({ flowId: z.string().min(1) }), ({ flowId, ...input }: any) => service.updateFlow(flowId, input)); + tool("delete_flow", "Delete a flow", flowIdSchema, ({ flowId }: any) => service.deleteFlow(flowId)); + tool("list_projects", "List Linear projects", z.object({}), () => service.listProjects()); + tool("list_flow_options", "List match-rule options", z.object({}), () => service.listFlowOptions()); + tool("list_runs", "List and filter flow runs", listRunsSchema, (input: any) => service.listRuns(queryOf(input))); + tool("get_run", "Get a run and its current output", runIdSchema, ({ runId }: any) => service.getRun(runId)); + tool("list_flow_events", "List webhook activity for a flow", listEventsSchema, (input: any) => service.listFlowEvents(queryOf(input))); + 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(); + 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/tenant.ts b/src/tenant.ts index a377523d..af2e05d0 100644 --- a/src/tenant.ts +++ b/src/tenant.ts @@ -1,7 +1,7 @@ import { DurableObject } from "cloudflare:workers"; import Mustache from "mustache"; import { decrypt, encrypt } from "./crypto"; -import { agentOutputCommand, agentStatusCommand, connectionCheckCommand, defaultAgentCommand, exec, herdrAgentStatus, herdrCheckCommand, startAgentCommand, type ExeConnection } from "./exe"; +import { agentOutputCommand, agentStatusCommand, connectionCheckCommand, defaultAgentCommand, exec, herdrAgentStatus, herdrCheckCommand, startAgentCommand, stopAgentCommand, type ExeConnection } from "./exe"; 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"; @@ -119,6 +119,11 @@ export class Tenant extends DurableObject { if (request.method === "GET" && url.pathname === "/pipes") return json(this.rows("SELECT id, name, project_id, team_id, filter_type, filter_target_id, source_kind, source_config, trigger_kind, trigger_config, max_concurrency, workspace_name, agent_kind, enabled, created_at FROM pipes ORDER BY created_at DESC")); if (request.method === "GET" && url.pathname.startsWith("/pipes/")) return await this.flowDetail(url.pathname.split("/")[2] ?? ""); if (request.method === "GET" && url.pathname === "/runs") return json(this.rows("SELECT id, pipe_id, issue_id, agent_name, state, created_at, updated_at FROM runs ORDER BY created_at DESC LIMIT 100")); + if (request.method === "GET" && url.pathname === "/v1/runs") return this.listRuns(url); + if (request.method === "GET" && /^\/v1\/runs\/[^/]+$/.test(url.pathname)) return await this.getRun(decodeURIComponent(url.pathname.split("/")[3] ?? "")); + if (request.method === "POST" && /^\/v1\/runs\/[^/]+\/stop$/.test(url.pathname)) return await this.stopRun(decodeURIComponent(url.pathname.split("/")[3] ?? "")); + if (request.method === "GET" && url.pathname === "/v1/events") return this.listEvents(url); + if (request.method === "GET" && /^\/v1\/flows\/[^/]+$/.test(url.pathname)) return this.getFlow(decodeURIComponent(url.pathname.split("/")[3] ?? "")); if (request.method === "GET" && url.pathname === "/connections/status") return await this.connectionStatus(); if (request.method === "POST" && url.pathname === "/members") return await this.upsertMember(await request.json()); if (request.method === "GET" && url.pathname.startsWith("/members/")) return this.getMember(url.pathname.split("/")[2] ?? ""); @@ -285,6 +290,78 @@ export class Tenant extends DurableObject { return json({ flow, events, runs }); } + private getFlow(flowId: string): Response { + const flow = this.one("SELECT id, name, project_id, match_rules, source_kind, source_config, max_concurrency, workspace_name, agent_kind, cwd, COALESCE(NULLIF(context_template, ''), ?) AS context_template, enabled, created_at FROM pipes WHERE id = ?", DEFAULT_CONTEXT_TEMPLATE, flowId); + return flow ? json(flow) : new Response("Not found", { status: 404 }); + } + + private pageSize(url: URL): number { + const value = Number(url.searchParams.get("limit") ?? 50); + return Math.max(1, Math.min(100, Number.isFinite(value) ? Math.floor(value) : 50)); + } + + private cursor(url: URL): { at: string; id: string } | null { + const value = url.searchParams.get("cursor"); + if (!value) return null; + try { + const normalized = value.replaceAll("-", "+").replaceAll("_", "/"); + const parsed = JSON.parse(atob(normalized + "===".slice((normalized.length + 3) % 4))) as { at?: unknown; id?: unknown }; + return typeof parsed.at === "string" && typeof parsed.id === "string" ? { at: parsed.at, id: parsed.id } : null; + } catch { throw new Error("Invalid cursor"); } + } + + private nextCursor(row: Row | undefined, atKey: string): string | null { + if (!row) return null; + return btoa(JSON.stringify({ at: String(row[atKey]), id: String(row.id) })).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); + } + + private listRuns(url: URL): Response { + const limit = this.pageSize(url), cursor = this.cursor(url), flowId = url.searchParams.get("flowId"), state = url.searchParams.get("state"); + const clauses: string[] = [], args: unknown[] = []; + if (flowId) { clauses.push("pipe_id = ?"); args.push(flowId); } + if (state) { clauses.push("state = ?"); args.push(state); } + if (cursor) { clauses.push("(created_at < ? OR (created_at = ? AND id < ?))"); args.push(cursor.at, cursor.at, cursor.id); } + const rows = this.rows(`SELECT id, pipe_id AS flow_id, issue_id, issue_url, agent_name, workspace_name, agent_kind, state, provider, created_at, updated_at FROM runs ${clauses.length ? `WHERE ${clauses.join(" AND ")}` : ""} ORDER BY created_at DESC, id DESC LIMIT ?`, ...args, limit + 1); + const hasMore = rows.length > limit, items = rows.slice(0, limit); + return json({ items, nextCursor: hasMore ? this.nextCursor(items.at(-1), "created_at") : null }); + } + + 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); + 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); + return json(run); + } + + private listEvents(url: URL): Response { + const limit = this.pageSize(url), cursor = this.cursor(url), flowId = url.searchParams.get("flowId"); + const clauses: string[] = [], args: unknown[] = []; + if (flowId) { clauses.push("flow_id = ?"); args.push(flowId); } + if (cursor) { clauses.push("(received_at < ? OR (received_at = ? AND id < ?))"); args.push(cursor.at, cursor.at, cursor.id); } + const rows = this.rows(`SELECT id, flow_id, delivery_id, issue_id, issue_url, event_type, event_action, outcome, detail, provider, received_at FROM flow_events ${clauses.length ? `WHERE ${clauses.join(" AND ")}` : ""} ORDER BY received_at DESC, id DESC LIMIT ?`, ...args, limit + 1); + const hasMore = rows.length > limit, items = rows.slice(0, limit); + return json({ items, nextCursor: hasMore ? this.nextCursor(items.at(-1), "received_at") : null }); + } + + private async stopRun(runId: string): Promise { + const run = this.one("SELECT * FROM runs WHERE id = ?", runId); + if (!run) return new Response("Not found", { status: 404 }); + if (!["starting", "running"].includes(String(run.state))) return Response.json({ error: "Run is not starting or running" }, { status: 409 }); + if (["starting", "running"].includes(String(run.state))) { + const pipe = this.one("SELECT * FROM pipes WHERE id = ?", run.pipe_id) as Row | undefined; + if (pipe) { + const connection = await this.exeConnection(String(pipe.exe_connection_id || "default")); + if (connection && run.agent_name) { + const stopped = await exec(connection, stopAgentCommand(connection, String(run.agent_name))); + if (!stopped.ok) return Response.json({ error: "Could not stop the active agent" }, { status: 502 }); + } + } + } + this.ctx.storage.sql.exec("UPDATE runs SET state = 'failed', result = ?, updated_at = ? WHERE id = ?", await encrypt("Stopped by user", this.env.CREDENTIAL_ENCRYPTION_KEY), now(), runId); + this.ctx.storage.sql.exec("DELETE FROM active_claims WHERE run_id = ?", runId); + return json({ id: runId, state: "failed", stopped: true }); + } + private async linearProjects(): Promise { const linear = await this.connection<{ accessToken: string }>("linear"); if (!linear) throw new Error("Connect Linear first"); diff --git a/src/types.ts b/src/types.ts index 2c82cefb..30d02f3f 100644 --- a/src/types.ts +++ b/src/types.ts @@ -20,8 +20,17 @@ export interface Env { GITHUB_INTEGRATION_ENABLED?: string; CUSTOM_SOURCES_ENABLED?: string; CUSTOM_HANDLER_LOADER?: WorkerLoader; + OAUTH_KV?: KVNamespace; + OAUTH_PROVIDER?: import("@cloudflare/workers-oauth-provider").OAuthHelpers; } +export type OAuthProps = { + tenantId: string; + userId: string; + sessionVersion: number; + scopes: string[]; +}; + export type CustomOrigin = "linear" | "github"; export type CustomSource = { kind: "custom"; origin: CustomOrigin; handlerName: string; handlerCode: string; handlerDeployment: { scriptName: string; codeDigest: string; state: "deploying" | "ready" | "failed"; lastError?: string } }; diff --git a/src/worker.ts b/src/worker.ts new file mode 100644 index 00000000..47d4c3c7 --- /dev/null +++ b/src/worker.ts @@ -0,0 +1,77 @@ +import { OAuthProvider, AuthorizationError, type AuthRequest } from "@cloudflare/workers-oauth-provider"; +import app, { readSession } from "./index"; +import { ProtectedApiHandler } from "./protected-api"; +import { hmac } from "./crypto"; +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); + 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)}`); + if (!response.ok) return null; + const member = await response.json() as { role?: string; session_version?: number }; + return member.role === "owner" && member.session_version === session.sessionVersion ? session : null; +} + +function oauthError(error: AuthorizationError): Response { + if (!error.redirectUri) return new Response(error.description, { status: 400 }); + const redirect = new URL(error.redirectUri); + redirect.searchParams.set("error", error.code); + redirect.searchParams.set("error_description", error.description); + if (error.state) redirect.searchParams.set("state", error.state); + if (error.issuer) redirect.searchParams.set("iss", error.issuer); + return Response.redirect(redirect, 302); +} + +const defaultHandler: ExportedHandler = { + async fetch(request, env, ctx) { + const url = new URL(request.url); + if (url.pathname !== "/authorize") return app.fetch(request, env, ctx); + 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; + } + if (request.method === "GET") { + const parsed = await env.OAUTH_PROVIDER!.parseAuthRequest(request); + const client = await env.OAUTH_PROVIDER!.lookupClient(parsed.clientId); + if (!client) return new Response("Unknown OAuth client", { status: 400 }); + const payload = btoa(JSON.stringify(parsed)); + const signature = await hmac(`${payload}.${session.tenantId}.${session.userId}`, env.SESSION_SIGNING_SECRET); + const requested = parsed.scope.filter(scope => scopes.includes(scope)); + return new Response(`Authorize Factorize

Authorize ${escape(client.clientName ?? "this client")}

Signed in as ${escape(session.email)}. This client is requesting:

${requested.map(scope => `
`).join("")}

`, { headers: { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" } }); + } + if (request.method !== "POST") return new Response("Method not allowed", { status: 405 }); + const form = await request.formData(), payload = String(form.get("request") ?? ""), signature = String(form.get("signature") ?? ""); + if (!payload || signature !== await hmac(`${payload}.${session.tenantId}.${session.userId}`, env.SESSION_SIGNING_SECRET)) return new Response("Invalid consent request", { status: 400 }); + const parsed = JSON.parse(atob(payload)) as AuthRequest; + if (form.get("decision") !== "allow") { + const redirect = new URL(parsed.redirectUri); redirect.searchParams.set("error", "access_denied"); redirect.searchParams.set("state", parsed.state); if (parsed.issuer) redirect.searchParams.set("iss", parsed.issuer); + return Response.redirect(redirect, 302); + } + const granted = form.getAll("scope").map(String).filter(scope => parsed.scope.includes(scope) && scopes.includes(scope)); + const props: OAuthProps = { tenantId: session.tenantId, userId: session.userId, sessionVersion: session.sessionVersion, scopes: granted }; + const { redirectTo } = await env.OAUTH_PROVIDER!.completeAuthorization({ request: parsed, userId: session.userId, metadata: { tenantId: session.tenantId }, scope: granted, props }); + return Response.redirect(redirectTo, 302); + } catch (error) { if (error instanceof AuthorizationError) return oauthError(error); throw error; } + }, +}; + +function provider(env: Env) { return new OAuthProvider({ + apiRoute: ["/api/v1", "/mcp"], apiHandler: ProtectedApiHandler, defaultHandler, + authorizeEndpoint: "/authorize", tokenEndpoint: "/oauth/token", clientRegistrationEndpoint: "/oauth/register", + scopesSupported: scopes, allowImplicitFlow: false, allowPlainPKCE: false, + accessTokenTTL: 3600, refreshTokenTTL: 2_592_000, + clientIdMetadataDocumentEnabled: true, + resourceMetadata: { resource: `${env.APP_ORIGIN}/mcp`, authorization_servers: [env.APP_ORIGIN], scopes_supported: scopes, bearer_methods_supported: ["header"], resource_name: "Factorize flows" }, +}); } + +export { Tenant, GitHubInstallationRegistry } from "./index"; +export default { fetch: (request: Request, env: Env, ctx: ExecutionContext) => provider(env).fetch(request, env, ctx) } satisfies ExportedHandler; diff --git a/test/exe.test.ts b/test/exe.test.ts index 406d2655..6641fff9 100644 --- a/test/exe.test.ts +++ b/test/exe.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { agentOutputCommand } from "../src/exe"; +import { agentOutputCommand, stopAgentCommand } from "../src/exe"; describe("agent output command", () => { it("requests the complete available transcript without a line limit", () => { @@ -14,3 +14,10 @@ describe("agent output command", () => { expect(command).not.toContain("--lines"); }); }); + +describe("agent stop command", () => { + it("uses the fixed Herdr agent stop command and quotes the agent name", () => { + const command = stopAgentCommand({ vmName: "vm", apiToken: "secret", agentKind: "codex", cwd: "/workspace" }, "agent; unsafe"); + expect(command).toContain("agent stop 'agent; unsafe'"); + }); +}); diff --git a/test/flow-service.test.ts b/test/flow-service.test.ts new file mode 100644 index 00000000..687fdfea --- /dev/null +++ b/test/flow-service.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from "vitest"; +import { FlowService, ServiceError } from "../src/flow-service"; +import { flowInputSchema, listRunsSchema } from "../src/flow-schemas"; +import type { Env, OAuthProps } from "../src/types"; + +function environment(handler: (request: Request) => Response | Promise): Env { + const stub = { fetch: (input: RequestInfo | URL, init?: RequestInit) => handler(new Request(input, init)) } as DurableObjectStub; + return { TENANTS: { idFromName: (name: string) => name as unknown as DurableObjectId, get: () => stub } as unknown as DurableObjectNamespace } as Env; +} + +const auth: OAuthProps = { tenantId: "tenant-a", userId: "owner-a", sessionVersion: 4, scopes: ["flows:read", "runs:read"] }; + +describe("FlowService", () => { + it("checks current owner membership on every call", async () => { + let membershipChecks = 0; + const service = new FlowService(environment(request => { + const path = new URL(request.url).pathname; + if (path === "/members/owner-a") { membershipChecks++; return Response.json({ role: "owner", session_version: 4 }); } + if (path === "/pipes") return Response.json([{ id: "flow-1", name: "Triage" }]); + return new Response("Not found", { status: 404 }); + }), auth); + await service.listFlows(); await service.listFlows(); + expect(membershipChecks).toBe(2); + }); + + it("rejects missing mutation scopes before touching flow storage", async () => { + let mutated = false; + const service = new FlowService(environment(request => { + if (new URL(request.url).pathname === "/pipes" && request.method === "POST") mutated = true; + return Response.json({ role: "owner", session_version: 4 }); + }), auth); + await expect(service.createFlow({ name: "Triage", projectId: "p", matchRules: [{ type: "label", targetId: "l" }], maxConcurrency: 3 })).rejects.toMatchObject({ status: 403, code: "insufficient_scope" } satisfies Partial); + expect(mutated).toBe(false); + }); + + it("invalidates tokens when the owner session version changes", async () => { + const service = new FlowService(environment(() => Response.json({ role: "owner", session_version: 5 })), auth); + await expect(service.listFlows()).rejects.toMatchObject({ status: 401, code: "invalid_token" }); + }); +}); + +describe("shared API schemas", () => { + it("rejects credential and unknown fields", () => { + expect(() => flowInputSchema.parse({ name: "Triage", projectId: "p", matchRules: [{ type: "label", targetId: "l" }], maxConcurrency: 3, apiToken: "secret" })).toThrow(); + }); + + it("bounds pagination and run states", () => { + expect(listRunsSchema.parse({ limit: "100", state: "running" })).toMatchObject({ limit: 100, state: "running" }); + expect(() => listRunsSchema.parse({ limit: "101" })).toThrow(); + }); +}); diff --git a/wrangler.jsonc b/wrangler.jsonc index 82ed46c7..f7af2336 100644 --- a/wrangler.jsonc +++ b/wrangler.jsonc @@ -1,9 +1,11 @@ { "$schema": "./node_modules/wrangler/config-schema.json", "name": "factorize", - "main": "src/index.ts", + "main": "src/worker.ts", "compatibility_date": "2026-09-10", + "compatibility_flags": ["global_fetch_strictly_public"], "assets": { "directory": "./public", "binding": "ASSETS" }, + "kv_namespaces": [{ "binding": "OAUTH_KV", "id": "REPLACE_WITH_OAUTH_KV_ID" }], "worker_loaders": [{ "binding": "CUSTOM_HANDLER_LOADER" }], "durable_objects": { "bindings": [{ "name": "TENANTS", "class_name": "Tenant" }, { "name": "GITHUB_INSTALLATIONS", "class_name": "GitHubInstallationRegistry" }]