Skip to content

An open-source, faster Devin alternative

TypeScript

api-edge: one-hour org keys for an organization's computer (work 067)

Mohamed Habib via Computer9aefe724c816
diff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.ts
index 60d7f0b7..494ee668 100644
--- a/cloudflare-workers/api-edge/src/dashboard.ts
+++ b/cloudflare-workers/api-edge/src/dashboard.ts
@@ -622,10 +622,13 @@ async function handleRevokeInvitation(_req: Request, env: DashboardEnv, caller:
// ── API keys ─────────────────────────────────────────────────────────────
async function handleListAPIKeys(_req: Request, env: DashboardEnv, caller: Caller): Promise<Response> {
+ // Expired one-hour computer keys (/internal/computer-keys) are noise: hidden.
const { results } = await env.OPENCOMPUTER_DB.prepare(
`SELECT id, name, key_prefix, scopes, last_used, expires_at, created_at, created_by
- FROM api_keys WHERE org_id = ?1 ORDER BY created_at DESC`,
- ).bind(caller.orgID).all<{
+ FROM api_keys WHERE org_id = ?1
+ AND NOT (created_by = 'computer' AND expires_at < ?2)
+ ORDER BY created_at DESC`,
+ ).bind(caller.orgID, Math.floor(Date.now() / 1000)).all<{
id: string; name: string; key_prefix: string; scopes: string;
last_used: number | null; expires_at: number | null; created_at: number; created_by: string | null;
}>();
diff --git a/cloudflare-workers/api-edge/src/index.test.ts b/cloudflare-workers/api-edge/src/index.test.ts
index 44ac28d6..774f1091 100644
--- a/cloudflare-workers/api-edge/src/index.test.ts
+++ b/cloudflare-workers/api-edge/src/index.test.ts
@@ -639,3 +639,53 @@ describe("/api/managed-agents/computer/slack — public mounts", () => {
expect(headers.get("x-slack-signature")).toBe("v0=abc");
});
});
+
+describe("/internal/computer-keys", () => {
+ const MANAGED = "managed-secret";
+ const sign = async (secret: string, ts: string, body: string): Promise<string> => {
+ const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
+ const mac = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${ts}.${body}`));
+ return [...new Uint8Array(mac)].map((b) => b.toString(16).padStart(2, "0")).join("");
+ };
+ const post = async (secret: string, orgID: string, authEnv: Env) => {
+ const body = JSON.stringify({ org_id: orgID });
+ const ts = Math.floor(Date.now() / 1000).toString();
+ return worker.fetch(
+ new Request("https://app.opencomputer.dev/internal/computer-keys", {
+ method: "POST",
+ headers: { "content-type": "application/json", "X-Timestamp": ts, "X-Signature": await sign(secret, ts, body) },
+ body,
+ }),
+ authEnv,
+ ctx,
+ );
+ };
+
+ it("refuses any other secret", async () => {
+ const authEnv = { ...env, CF_ADMIN_SECRET: "admin", OC_MANAGED_CRED_HMAC_SECRET: MANAGED } as unknown as Env;
+ expect((await post("admin", "org-x", authEnv)).status).toBe(401);
+ });
+
+ it("mints a one-hour key for an existing org", async () => {
+ const runs: unknown[][] = [];
+ const db = {
+ prepare: (sql: string) => ({
+ bind: (...args: unknown[]) => ({
+ first: async () => (sql.includes("FROM orgs") && args[0] === "org-x" ? { id: "org-x" } : null),
+ run: async () => { runs.push(args); return {}; },
+ }),
+ }),
+ };
+ const authEnv = { ...env, OC_MANAGED_CRED_HMAC_SECRET: MANAGED, OPENCOMPUTER_DB: db } as unknown as Env;
+ expect((await post(MANAGED, "org-missing", authEnv)).status).toBe(404);
+ const res = await post(MANAGED, "org-x", authEnv);
+ expect(res.status).toBe(200);
+ const out = (await res.json()) as { key: string; expiresAt: string };
+ expect(out.key).toMatch(/^osb_/);
+ const ttl = Date.parse(out.expiresAt) - Date.now();
+ expect(ttl).toBeGreaterThan(3500_000);
+ expect(ttl).toBeLessThanOrEqual(3600_000);
+ expect(runs[0][1]).toBe("org-x");
+ expect(runs[0][2]).toBe("computer");
+ });
+});
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index e38b5ccb..bd7a6aa7 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -5418,6 +5418,32 @@ export default {
}
}
+ // /internal/computer-keys — a one-hour org key for an organization's computer
+ // (work 067): managed agents mints one when a session runs `opencomputer`,
+ // instead of a long-lived key living on the VM. HMAC-auth'd with the scoped
+ // OC_MANAGED_CRED_HMAC_SECRET over `${ts}.${body}`. Body: { org_id }.
+ if (path === "/internal/computer-keys" && req.method === "POST") {
+ const ts = req.headers.get("X-Timestamp") ?? "";
+ const sig = req.headers.get("X-Signature") ?? "";
+ const body = await req.text();
+ const ok = env.OC_MANAGED_CRED_HMAC_SECRET
+ ? constantTimeEqual(await hmacHex(env.OC_MANAGED_CRED_HMAC_SECRET, `${ts}.${body}`), sig)
+ : false;
+ if (!ok) return json({ error: "signature mismatch" }, 401);
+ if (Math.abs(Math.floor(Date.now() / 1000) - Number(ts)) > 300) return json({ error: "timestamp out of window" }, 401);
+ const parsed = JSON.parse(body) as { org_id?: string };
+ if (!parsed.org_id) return json({ error: "org_id required" }, 400);
+ const org = await env.OPENCOMPUTER_DB.prepare(`SELECT id FROM orgs WHERE id = ?1`).bind(parsed.org_id).first();
+ if (!org) return json({ error: "org not found" }, 404);
+ const created = await createAPIKey(env, {
+ orgID: parsed.org_id,
+ userID: "computer",
+ name: "Computer session",
+ expiresAt: Math.floor(Date.now() / 1000) + 3600,
+ });
+ return json({ key: created.key, expiresAt: created.expiresAt });
+ }
+
// /internal/secret-stores/:id — HMAC-auth'd, called by CP at sandbox-create
// time to materialize the encrypted entry list. CP decrypts with the
// shared SECRET_ENCRYPTION_KEY before injecting into worker env.