An open-source, faster Devin alternative
TypeScript
computer: harden the one-command connect after self-review (work 082)
Igor Zalutski via Computerf90ab04181d8
diff --git a/cloudflare-workers/api-edge/src/index.test.ts b/cloudflare-workers/api-edge/src/index.test.tsindex f48667dc..3bd41394 100644--- a/cloudflare-workers/api-edge/src/index.test.ts+++ b/cloudflare-workers/api-edge/src/index.test.ts@@ -770,6 +770,25 @@ describe("/api/managed-agents/computer/agent/connect — public CLI connect", ());expect(resp.status).toBe(502);});++ it("rate-limits per caller IP before reading the body or calling blue", async () => {+ const fetchSpy = vi.fn();+ vi.stubGlobal("fetch", fetchSpy);+ const limit = vi.fn(async () => ({ success: false }));+ const resp = await worker.fetch(+ new Request(url, {+ method: "POST",+ headers: { "content-type": "application/json", "CF-Connecting-IP": "203.0.113.9" },+ body: JSON.stringify({ code, provider: "claude", token: "t" }),+ }),+ { ...target, COMPUTER_CONNECT_RATE_LIMIT: { limit } } as unknown as Env,+ ctx,+ );+ expect(resp.status).toBe(429);+ expect(await resp.json()).toMatchObject({ error: { code: "rate_limited" } });+ expect(limit).toHaveBeenCalledWith({ key: "203.0.113.9" });+ expect(fetchSpy).not.toHaveBeenCalled();+ });});describe("/internal/computer-keys", () => {diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex ca1c4a06..9cc8fe33 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -108,6 +108,8 @@ export interface Env extends DashboardEnv, AgentFeedbackEnv {// several times after a single start request.CLI_AUTH_START_RATE_LIMIT: RateLimit;CLI_AUTH_EXCHANGE_RATE_LIMIT: RateLimit;+ // Public CLI connect (work 082), per caller IP ahead of blue.+ COMPUTER_CONNECT_RATE_LIMIT?: RateLimit;// Dedicated HMAC secret for the Sessions API's minimal Agent Hook exposure// alert. It is intentionally not shared with other internal routes.OC_SECURITY_NOTIFICATION_SECRET?: string;diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.tsindex c28efb08..d866ef3d 100644--- a/cloudflare-workers/api-edge/src/managed_agents.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.ts@@ -12,6 +12,8 @@ export interface ManagedAgentsEnv {OPENCOMPUTER_DB?: D1Database;AUTUMN_SECRET_KEY?: string;AUTUMN_BASE_URL?: string;+ /** Per-IP cap on the public CLI connect route (work 082). */+ COMPUTER_CONNECT_RATE_LIMIT?: RateLimit;}export interface ManagedAgentsCaller {@@ -3232,7 +3234,9 @@ export async function handleComputerSlackWebhook(// Work 082: the backend bounds the body the same way (CODEX_BODY_MAX_BYTES:// twice the 64 KiB auth.json cap, plus room for the code and provider).-export const COMPUTER_AGENT_CONNECT_MAX_BYTES = 2 * 64 * 1024 + 1024;+export // Blue verifies the subscription with its provider before answering.+const COMPUTER_AGENT_CONNECT_TIMEOUT_MS = 30_000;+const COMPUTER_AGENT_CONNECT_MAX_BYTES = 2 * 64 * 1024 + 1024;// `occ_<base64url(accountId)>.<base64url nonce>`; anything else is refused here// so garbage never reaches the backend.const CONNECT_CODE = /^occ_[A-Za-z0-9_-]{1,200}\.[A-Za-z0-9_-]{16,200}$/;@@ -3287,36 +3291,86 @@ export async function handleComputerAgentConnect(request: Request,env: ManagedAgentsEnv,): Promise<Response> {+ const startedAt = Date.now();+ const finish = (response: Response, result: string): Response => {+ // One line per attempt: the funnel from command run to connected, and+ // what the edge refused before blue saw it.+ console.log(+ JSON.stringify({+ event: "computer_agent_connect",+ result,+ http_status: response.status,+ duration_ms: Date.now() - startedAt,+ }),+ );+ return response;+ };if (request.method !== "POST") {- return new Response("Method not allowed", {- status: 405,- headers: { allow: "POST" },- });+ return finish(+ new Response("Method not allowed", {+ status: 405,+ headers: { allow: "POST" },+ }),+ "method",+ );+ }+ // Codes carry 128 bits, so this caps load on blue rather than guessing.+ // Without the binding (tests, a misconfigured env) the route stays open:+ // blue still refuses anything but a live code.+ if (env.COMPUTER_CONNECT_RATE_LIMIT) {+ const ip = request.headers.get("CF-Connecting-IP")?.trim();+ const key = ip && ip.length <= 64 ? ip : "unknown";+ const allowed = await env.COMPUTER_CONNECT_RATE_LIMIT.limit({ key }).then(+ (r) => r.success,+ () => true,+ );+ if (!allowed) {+ return finish(+ connectProblem(+ 429,+ "rate_limited",+ "Too many connect attempts. Wait a minute and try again.",+ ),+ "rate_limited",+ );+ }}const contentType = request.headers.get("content-type") ?? "";if (!/^application\/json\s*(;|$)/i.test(contentType)) {- return connectProblem(- 415,- "invalid_request",- "Send the connect request as application/json.",+ return finish(+ connectProblem(+ 415,+ "invalid_request",+ "Send the connect request as application/json.",+ ),+ "content_type",);}const bytes = await boundedBody(request, COMPUTER_AGENT_CONNECT_MAX_BYTES);if (!bytes) {- return connectProblem(413, "invalid_request", "The request is too large.");+ return finish(+ connectProblem(413, "invalid_request", "The request is too large."),+ "too_large",+ );}let code: unknown;try {code = (JSON.parse(new TextDecoder().decode(bytes)) as { code?: unknown })?.code;} catch {- return connectProblem(400, "invalid_request", "The request is not JSON.");+ return finish(+ connectProblem(400, "invalid_request", "The request is not JSON."),+ "not_json",+ );}if (typeof code !== "string" || !CONNECT_CODE.test(code)) {- return connectProblem(- 401,- "computer_connect_code_invalid",- "That connect code is not valid. Get a new one from the dashboard.",+ return finish(+ connectProblem(+ 401,+ "computer_connect_code_invalid",+ "That connect code is not valid. Get a new one from the dashboard.",+ ),+ "malformed_code",);}const base = (@@ -3324,10 +3378,13 @@ export async function handleComputerAgentConnect().replace(/\/+$/, "");const target = new URL(`${base}/v1/computer/agent/connect`);if (target.protocol !== "https:" && target.hostname !== "localhost") {- return connectProblem(- 503,- "computer_not_configured",- "Connecting a subscription isn't available yet. Try again shortly.",+ return finish(+ connectProblem(+ 503,+ "computer_not_configured",+ "Connecting a subscription isn't available yet. Try again shortly.",+ ),+ "not_configured",);}try {@@ -3336,16 +3393,23 @@ export async function handleComputerAgentConnect(headers: { "content-type": "application/json" },body: bytes,redirect: "manual",+ signal: AbortSignal.timeout(COMPUTER_AGENT_CONNECT_TIMEOUT_MS),});const headers = new Headers({ "cache-control": "no-store" });const upstreamType = upstream.headers.get("content-type");if (upstreamType) headers.set("content-type", upstreamType);- return new Response(upstream.body, { status: upstream.status, headers });+ return finish(+ new Response(upstream.body, { status: upstream.status, headers }),+ upstream.ok ? "connected" : "refused_upstream",+ );} catch {- return connectProblem(- 502,- "computer_unavailable",- "Connecting a subscription isn't available right now. Try again shortly.",+ return finish(+ connectProblem(+ 502,+ "computer_unavailable",+ "Connecting a subscription isn't available right now. Try again shortly.",+ ),+ "upstream_unavailable",);}}diff --git a/cloudflare-workers/api-edge/wrangler.igor-dev.toml b/cloudflare-workers/api-edge/wrangler.igor-dev.tomlindex 38590cf5..aaa99827 100644--- a/cloudflare-workers/api-edge/wrangler.igor-dev.toml+++ b/cloudflare-workers/api-edge/wrangler.igor-dev.toml@@ -61,6 +61,15 @@ namespace_id = "2026072412"limit = 180period = 60+# Public CLI connect (work 082): per IP, ahead of blue.+[[ratelimits]]+name = "COMPUTER_CONNECT_RATE_LIMIT"+namespace_id = "2026102311"++ [ratelimits.simple]+ limit = 20+ period = 60+# CreditAccount DO is self-hosted by this worker (script_name defaults to self).[[durable_objects.bindings]]name = "CREDIT_ACCOUNT"diff --git a/cloudflare-workers/api-edge/wrangler.prod.toml b/cloudflare-workers/api-edge/wrangler.prod.tomlindex 293111ff..a03f227d 100644--- a/cloudflare-workers/api-edge/wrangler.prod.toml+++ b/cloudflare-workers/api-edge/wrangler.prod.toml@@ -59,6 +59,15 @@ namespace_id = "2026072402"limit = 180period = 60+# Public CLI connect (work 082): per IP, ahead of blue.+[[ratelimits]]+name = "COMPUTER_CONNECT_RATE_LIMIT"+namespace_id = "2026102301"++ [ratelimits.simple]+ limit = 20+ period = 60+[[durable_objects.bindings]]name = "CREDIT_ACCOUNT"class_name = "CreditAccount"diff --git a/cloudflare-workers/api-edge/wrangler.toml b/cloudflare-workers/api-edge/wrangler.tomlindex 18348c5a..0d35a5be 100644--- a/cloudflare-workers/api-edge/wrangler.toml+++ b/cloudflare-workers/api-edge/wrangler.toml@@ -81,6 +81,15 @@ namespace_id = "2026072422"limit = 180period = 60+# Public CLI connect (work 082): per IP, ahead of blue.+[[ratelimits]]+name = "COMPUTER_CONNECT_RATE_LIMIT"+namespace_id = "2026102321"++ [ratelimits.simple]+ limit = 20+ period = 60+[[durable_objects.bindings]]name = "CREDIT_ACCOUNT"class_name = "CreditAccount"diff --git a/web/src/managed-agents/AgentStep.test.tsx b/web/src/managed-agents/AgentStep.test.tsxindex 1f274417..43f8556b 100644--- a/web/src/managed-agents/AgentStep.test.tsx+++ b/web/src/managed-agents/AgentStep.test.tsx@@ -121,7 +121,7 @@ describe('choosing the coding agent', () => {code: CODE,expiresAt: inTenMinutes(),})- window.sessionStorage.clear()+ window.localStorage.clear()})afterEach(() => {@@ -450,7 +450,7 @@ describe('choosing the coding agent', () => {via: 'command',})// A used code is never offered again.- expect(window.sessionStorage.length).toBe(0)+ expect(window.localStorage.length).toBe(0)})it('waits quickly for the sign-in while the tab is in view', async () => {@@ -480,6 +480,68 @@ describe('choosing the coding agent', () => {expect(computerApi.getComputer.mock.calls.length).toBeGreaterThan(reads)})+ it('stops renewing and waiting in a tab left open, until asked again', async () => {+ vi.useFakeTimers({+ toFake: [+ 'setTimeout',+ 'clearTimeout',+ 'setInterval',+ 'clearInterval',+ 'Date',+ ],+ })+ let minted = 0+ computerApi.createConnectCode.mockImplementation(() =>+ Promise.resolve({+ code: `${CODE}${minted++}`,+ expiresAt: new Date(Date.now() + 10 * 60_000).toISOString(),+ }),+ )+ computerApi.getComputer.mockResolvedValue({ ...empty, agent: fresh })+ act(() => {+ root.render(+ <QueryClientProvider client={client}>+ <MemoryRouter initialEntries={['/computer']}>+ <Routes>+ <Route path="computer" element={<ComputerPage />} />+ </Routes>+ </MemoryRouter>+ </QueryClientProvider>,+ )+ })+ await act(async () => {+ await vi.advanceTimersByTimeAsync(100)+ })+ expect(command()).toBeDefined()+ // An hour with nobody acting: renewed for half an hour, then left.+ for (let i = 0; i < 60; i++)+ await act(async () => {+ await vi.advanceTimersByTimeAsync(60_000)+ })+ expect(computerApi.createConnectCode.mock.calls.length).toBeLessThanOrEqual(+ 4,+ )+ expect(text()).toContain('This command expired.')+ expect(text()).not.toContain('Waiting for you to sign in')+ const reads = computerApi.getComputer.mock.calls.length+ const mints = computerApi.createConnectCode.mock.calls.length+ await act(async () => {+ await vi.advanceTimersByTimeAsync(30 * 60_000)+ })+ // Only the page's own slow poll (every 30 s) is left.+ expect(+ computerApi.getComputer.mock.calls.length - reads,+ ).toBeLessThanOrEqual(61)+ expect(computerApi.createConnectCode.mock.calls.length).toBe(mints)+ // Asked again: a fresh command, and the wait is back.+ act(() => button('Get a new command')!.click())+ await act(async () => {+ await vi.advanceTimersByTimeAsync(100)+ })+ expect(computerApi.createConnectCode.mock.calls.length).toBe(mints + 1)+ expect(text()).toContain('Waiting for you to sign in')+ })+it('keeps the command across a reload, and gives a new one on request', async () => {await show({ ...empty, agent: fresh }, 'Choose your coding agent')await settle(() => command() !== undefined, 'command')@@ -501,6 +563,29 @@ describe('choosing the coding agent', () => {expect(computerApi.createConnectCode).toHaveBeenCalledTimes(2)})+ it('drops a stored code a sign-in already used while no tab watched', async () => {+ window.localStorage.setItem(+ 'opencomputer.computer.connect-code::',+ JSON.stringify({+ code: 'occ_c3BlbnQ.spent-code-0000000000',+ expiresAt: inTenMinutes(),+ mintedAt: Date.parse('2026-10-22T09:59:00Z'),+ }),+ )+ await show(+ {+ ...empty,+ agent: { ...fresh, choice: 'claude', subscription: subscription('ok') },+ },+ 'Add OpenComputer to Slack',+ )+ act(() => button('Change')!.click())+ await settle(() => command() !== undefined, 'command')+ expect(command()).toContain(CODE)+ expect(command()).not.toContain('spent')+ expect(computerApi.createConnectCode).toHaveBeenCalledTimes(1)+ })+it('mints a new command once the code expires', async () => {computerApi.createConnectCode.mockResolvedValueOnce({diff --git a/web/src/managed-agents/AgentStep.tsx b/web/src/managed-agents/AgentStep.tsxindex 7e53041d..89e28311 100644--- a/web/src/managed-agents/AgentStep.tsx+++ b/web/src/managed-agents/AgentStep.tsx@@ -333,13 +333,17 @@ function AgentOption({}// The command's code works for ten minutes. Re-read the status quickly for a-// while after the command is shown or copied (the person may sign in in a-// window beside this one), then slower, then not at all: a person who comes-// back from the terminal or the browser refocuses the tab, which re-reads it.+// while after the person last acted (the command shown, copied or renewed:+// they may sign in in a window beside this one), then slower, then not at+// all: a person who comes back from the terminal or the browser refocuses+// the tab, which re-reads it. An expired code is replaced on its own for+// half an hour after they last acted; after that the command reads expired+// until they ask for another, so a tab left open mints and polls nothing.const WAIT_FAST_MS = 3_000const WAIT_SLOW_MS = 10_000const WAIT_FAST_FOR_MS = 2 * 60_000const WAIT_FOR_MS = 10 * 60_000+const CODE_AUTO_RENEW_FOR_MS = 30 * 60_000const computerQueryHash = hashKey(computerQueryKey)// A stored code is reused only with this long left to run it.const CODE_REUSE_MIN_MS = 60_000@@ -348,17 +352,32 @@ function connectCodeStorageKey(scope: string) {return `opencomputer.computer.connect-code:${scope}`}-function storedConnectCode(key: string): ComputerConnectCode | null {+/**+ * The stored code, unless it is nearly expired or was likely spent: a+ * subscription set after it was minted (the command ran while no tab was+ * watching, so none forgot it) means it was used.+ */+function storedConnectCode(+ key: string,+ subscriptionSetAt: string | undefined,+): ComputerConnectCode | null {try {- const raw = window.sessionStorage.getItem(key)+ const raw = window.localStorage.getItem(key)if (!raw) return null- const stored = JSON.parse(raw) as Partial<ComputerConnectCode>+ const stored = JSON.parse(raw) as Partial<+ ComputerConnectCode & { mintedAt: number }+ >if (typeof stored.code !== 'string' ||typeof stored.expiresAt !== 'string' ||new Date(stored.expiresAt).getTime() - Date.now() < CODE_REUSE_MIN_MS)return null+ if (+ subscriptionSetAt &&+ new Date(subscriptionSetAt).getTime() >= (stored.mintedAt ?? 0)+ )+ return nullreturn { code: stored.code, expiresAt: stored.expiresAt }} catch {return null@@ -367,14 +386,14 @@ function storedConnectCode(key: string): ComputerConnectCode | null {/*** This person's connect code, one for both cards (the command names the- * provider). Minting replaces the last code, so a reload must not mint a new- * one under a command the person is already running: the code is kept in- * this tab's session storage until it is nearly expired. A code is re-minted- * once it expires, but only while the tab is visible (react-query skips- * background intervals and catches up on focus), so a forgotten tab does- * not mint forever.+ * provider). Minting replaces the last code, so neither a reload nor a+ * second tab may mint a new one under a command the person is already+ * running: the code is kept in local storage until it is nearly expired.+ * A code is re-minted once it expires, only while the tab is visible+ * (react-query skips background intervals and catches up on focus) and+ * only until `renewUntil`.*/-function useConnectCode() {+function useConnectCode(renewUntil: number) {const auth = useContext(AuthContext)const key = connectCodeStorageKey(`${auth?.user?.orgId ?? ''}:${auth?.user?.id ?? ''}`,@@ -383,11 +402,16 @@ function useConnectCode() {const query = useQuery({queryKey: [...computerConnectCodeQueryKey, key],queryFn: async () => {- const stored = storedConnectCode(key)+ const status = queryClient.getQueryData<ComputerStatus>(computerQueryKey)+ const stored = storedConnectCode(key, status?.agent?.subscription?.setAt)if (stored) return stored+ const mintedAt = Date.now()const minted = await createConnectCode()try {- window.sessionStorage.setItem(key, JSON.stringify(minted))+ window.localStorage.setItem(+ key,+ JSON.stringify({ ...minted, mintedAt }),+ )} catch {// Storage off: a reload mints a new code, nothing worse.}@@ -396,7 +420,9 @@ function useConnectCode() {retry: false,staleTime: (q) => msUntil(q.state.data?.expiresAt),refetchInterval: (q) =>- q.state.data ? Math.max(1_000, msUntil(q.state.data.expiresAt)) : false,+ q.state.data && Date.now() < renewUntil+ ? Math.max(1_000, msUntil(q.state.data.expiresAt))+ : false,})const renew = useCallback(() => {forgetStoredCode(key)@@ -419,7 +445,7 @@ function useConnectCode() {function forgetStoredCode(key: string) {try {- window.sessionStorage.removeItem(key)+ window.localStorage.removeItem(key)} catch {// Nothing stored.}@@ -510,7 +536,18 @@ function CommandConnect({replacing: booleanonDone?: () => void}) {- const { query: code, renew, forget } = useConnectCode()+ // The last sign of the person acting: the command shown, copied or+ // renewed. Waiting and renewing are paced from it.+ const [actedAt, setActedAt] = useState(() => Date.now())+ const {+ query: code,+ renew: renewCode,+ forget,+ } = useConnectCode(actedAt + CODE_AUTO_RENEW_FOR_MS)+ const renew = () => {+ setActedAt(Date.now())+ renewCode()+ }const queryClient = useQueryClient()// What was there when the command was shown: only a change counts.const [before] = useState(@@ -518,15 +555,11 @@ function CommandConnect({queryClient.getQueryData<ComputerStatus>(computerQueryKey)?.agent?.subscription?.setAt ?? null,)- // The last sign of the person acting: the command shown (a new code) or- // copied. The wait is quick right after it.- const [copiedAt, setCopiedAt] = useState(() => Date.now())- const since = Math.max(copiedAt, code.dataUpdatedAt)const status = useQuery({queryKey: computerQueryKey,queryFn: getComputer,refetchInterval: () => {- const waited = Date.now() - since+ const waited = Date.now() - actedAtif (waited >= WAIT_FOR_MS) return falsereturn waited < WAIT_FAST_FOR_MS ? WAIT_FAST_MS : WAIT_SLOW_MS},@@ -535,6 +568,19 @@ function CommandConnect({const connected =subscription?.provider === provider && subscription.setAt !== beforeconst codeValue = code.data?.code+ // The code this command shows ran out (no auto-renew any more): say so+ // rather than keep a dead command and a spinner up.+ const [expiredCode, setExpiredCode] = useState<string | null>(null)+ const expiresAt = code.data?.expiresAt+ useEffect(() => {+ if (!codeValue) return+ const timer = window.setTimeout(+ () => setExpiredCode(codeValue),+ msUntil(expiresAt),+ )+ return () => window.clearTimeout(timer)+ }, [codeValue, expiresAt])+ const expired = Boolean(codeValue) && expiredCode === codeValue// Announced from the cache, as the status lands: in setup the step moves// on (and this unmounts) in the very render that brings the subscription.const announced = useRef(false)@@ -582,7 +628,7 @@ function CommandConnect({{codeValue ? (<CopyRowvalue={connectCommand(provider, codeValue)}- onCopy={() => setCopiedAt(Date.now())}+ onCopy={() => setActedAt(Date.now())}/>) : (<div@@ -596,6 +642,8 @@ function CommandConnect({<div className="text-muted-foreground flex flex-wrap items-center gap-x-3 gap-y-1 text-xs">{connected ? (<span>{PROVIDER_NAME[provider]} is connected.</span>+ ) : expired ? (+ <span aria-live="polite">This command expired.</span>) : (<span className="flex items-center gap-1.5" aria-live="polite"><Loader2 className="size-3 animate-spin" aria-hidden />@@ -604,7 +652,7 @@ function CommandConnect({: 'Waiting for you to sign in…'}</span>)}- <span>Works once, for 10 minutes.</span>+ {!expired && <span>Works once, for 10 minutes.</span>}<Buttonvariant="link"size="xs"