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
39 changes: 37 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.

Expand All @@ -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.

Expand Down
59 changes: 58 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
4 changes: 4 additions & 0 deletions src/exe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`;
}
Expand Down
29 changes: 29 additions & 0 deletions src/flow-schemas.ts
Original file line number Diff line number Diff line change
@@ -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<typeof flowInputSchema>;
62 changes: 62 additions & 0 deletions src/flow-service.ts
Original file line number Diff line number Diff line change
@@ -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<void> {
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<unknown> {
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" }); }
}
6 changes: 4 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> { const body = b64(JSON.stringify(session)); return `${body}.${await hmac(body, secret)}`; }
async function readSession(value: string | undefined, secret: string): Promise<Session | null> {
export async function readSession(value: string | undefined, secret: string): Promise<Session | null> {
if (!value) return null;
const [body, signature] = value.split(".");
if (!body || !signature || signature !== await hmac(body, secret)) return null;
Expand Down Expand Up @@ -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");
});

Expand Down
Loading