An open-source, faster Devin alternative
TypeScript
Add browser-assisted CLI login
Igor Zalutski94fc4d240f2c
diff --git a/.github/workflows/release-cli.yml b/.github/workflows/release-cli.ymlindex 3b67576d..a4a50f79 100644--- a/.github/workflows/release-cli.yml+++ b/.github/workflows/release-cli.yml@@ -58,6 +58,28 @@ jobs:echo "exists=false" >> "$GITHUB_OUTPUT"fi+ # The same main merge can trigger the API-edge and CLI workflows in+ # parallel. Do not publish a CLI that advertises `oc login` until the+ # additive edge contract is observably live.+ - name: Wait for CLI login edge contract+ if: steps.check_tag.outputs.exists == 'false'+ run: |+ for attempt in $(seq 1 120); do+ status=$(curl -sS \+ --output /tmp/cli-login-edge.json \+ --write-out '%{http_code}' \+ https://app.opencomputer.dev/auth/cli/device || true)+ if [ "$status" = "405" ] &&+ jq -e '.error == "method_not_allowed"' /tmp/cli-login-edge.json >/dev/null 2>&1; then+ echo "CLI login edge contract is live."+ exit 0+ fi+ echo "Waiting for API edge (attempt $attempt/120; status ${status:-unavailable})..."+ sleep 5+ done+ echo "CLI login edge contract did not become ready; refusing to publish."+ exit 1+- name: Build CLI binariesif: steps.check_tag.outputs.exists == 'false'run: |diff --git a/README.md b/README.mdindex ab559a76..62d7ef60 100644--- a/README.md+++ b/README.md@@ -29,10 +29,14 @@ Download the latest `oc` binary from [GitHub Releases](https://github.com/diggercurl -fsSL https://github.com/diggerhq/opencomputer/releases/latest/download/oc-darwin-arm64 -o /usr/local/bin/occhmod +x /usr/local/bin/oc-# Configure-oc config set api-key YOUR_API_KEY+# Sign in+oc login+oc whoami```+For CI, servers, and SDK applications, keep using an explicit org API key in+`OPENCOMPUTER_API_KEY`; `oc login` is for the local CLI.+### SDKInstall the SDK:diff --git a/cloudflare-workers/api-edge/src/api_keys.ts b/cloudflare-workers/api-edge/src/api_keys.tsnew file mode 100644index 00000000..68392a2c--- /dev/null+++ b/cloudflare-workers/api-edge/src/api_keys.ts@@ -0,0 +1,52 @@+export interface APIKeyEnv {+ OPENCOMPUTER_DB: D1Database;+}++export interface CreatedAPIKey {+ id: string;+ orgId: string;+ name: string;+ key: string;+ keyPrefix: string;+ scopes: string[];+ createdAt: string;+}++export async function hashAPIKey(key: string): Promise<string> {+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(key));+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");+}++/**+ * Creates an ordinary OpenComputer org key. The caller owns the one-time+ * plaintext response; only its SHA-256 hash is persisted.+ */+export async function createAPIKey(+ env: APIKeyEnv,+ input: { orgID: string; userID: string; name: string },+): Promise<CreatedAPIKey> {+ const bytes = new Uint8Array(32);+ crypto.getRandomValues(bytes);+ const plainKey = "osb_" + [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");+ const hash = await hashAPIKey(plainKey);+ const prefix = plainKey.slice(0, 8);+ const id = crypto.randomUUID();+ const now = Math.floor(Date.now() / 1000);++ await env.OPENCOMPUTER_DB.prepare(+ `INSERT INTO api_keys (id, org_id, created_by, key_hash, key_prefix, name, scopes, created_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'sandbox:*', ?7)`,+ )+ .bind(id, input.orgID, input.userID, hash, prefix, input.name, now)+ .run();++ return {+ id,+ orgId: input.orgID,+ name: input.name,+ key: plainKey,+ keyPrefix: prefix,+ scopes: ["sandbox:*"],+ createdAt: new Date(now * 1000).toISOString(),+ };+}diff --git a/cloudflare-workers/api-edge/src/cli_auth.test.ts b/cloudflare-workers/api-edge/src/cli_auth.test.tsnew file mode 100644index 00000000..c0143a16--- /dev/null+++ b/cloudflare-workers/api-edge/src/cli_auth.test.ts@@ -0,0 +1,497 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import worker, { type Env } from "./index";++const userID = "11111111-1111-4111-8111-111111111111";+const orgID = "22222222-2222-4222-8222-222222222222";++interface CapturedStatement {+ sql: string;+ args: unknown[];+}++interface FakeMembership {+ id: string;+ name: string;+ plan: string;+ is_personal: number;+ workos_org_id: string | null;+ membership_created_at: number;+ org_created_at: number;+}++class FakeStatement {+ private args: unknown[] = [];++ constructor(+ private readonly db: FakeDB,+ private readonly sql: string,+ ) {}++ bind(...args: unknown[]): this {+ this.args = args;+ return this;+ }++ async first<T>(): Promise<T | null> {+ if (this.sql.includes("FROM users WHERE workos_user_id")) {+ if (!this.db.user) return null;+ return this.db.user as T;+ }+ if (this.sql.includes("FROM api_keys WHERE key_hash")) {+ return { org_id: orgID, created_by: userID, expires_at: null } as T;+ }+ if (this.sql.includes("SELECT o.name AS org_name")) {+ return { org_name: "Igor's workspace", email: "[email protected]" } as T;+ }+ if (this.sql.includes("JOIN org_memberships") && this.sql.includes("LIMIT 1")) {+ return (this.db.memberships[0] ?? null) as T | null;+ }+ return null;+ }++ async all<T>(): Promise<{ results: T[] }> {+ if (this.sql.includes("JOIN org_memberships")) {+ return { results: this.db.memberships as T[] };+ }+ if (this.sql.includes("FROM cells") && this.sql.includes("accepts_new_orgs = 1")) {+ return {+ results: [{+ cell_id: "azure-us-east-2-a",+ region: "us-east-2",+ } as T],+ };+ }+ return { results: [] };+ }++ async run(): Promise<Record<string, never>> {+ this.db.executed.push({ sql: this.sql, args: this.args });+ if (this.sql.includes("INSERT INTO users")) {+ this.db.user = {+ id: String(this.args[0]),+ email: String(this.args[1]),+ name: String(this.args[3]),+ };+ }+ return {};+ }+}++class FakeDB {+ executed: CapturedStatement[] = [];+ memberships: FakeMembership[];+ user: { id: string; email: string; name: string } | null;++ constructor(+ memberships?: FakeMembership[],+ user: { id: string; email: string; name: string } | null = {+ id: userID,+ email: "[email protected]",+ name: "Igor",+ },+ ) {+ this.memberships = memberships ?? [{+ id: orgID,+ name: "Igor's workspace",+ plan: "free",+ is_personal: 1,+ workos_org_id: null,+ membership_created_at: 1,+ org_created_at: 1,+ }];+ this.user = user;+ }++ prepare(sql: string): FakeStatement {+ return new FakeStatement(this, sql);+ }+}++function testEnv(db = new FakeDB()): Env {+ return {+ OPENCOMPUTER_DB: db,+ SESSIONS_KV: {},+ CREDIT_ACCOUNT: {},+ SESSION_JWT_SECRET: "test-session-secret",+ WORKOS_API_KEY: "sk_test",+ WORKOS_CLIENT_ID: "client_test",+ STRIPE_API_KEY: "",+ WORKER_ENV: "test",+ CF_ADMIN_SECRET: "",+ STRIPE_WEBHOOK_SECRET: "",+ EVENT_SECRET: "",+ SECRET_ENCRYPTION_KEY: "",+ } as unknown as Env;+}++const ctx = {+ waitUntil: vi.fn(),+ passThroughOnException: vi.fn(),+} as unknown as ExecutionContext;++function request(path: string, init?: RequestInit): Request {+ return new Request(`https://app.opencomputer.dev${path}`, init);+}++afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++describe("CLI device authorization edge contract", () => {+ it("starts authorization with a form request and returns only validated fields", async () => {+ const providerFetch = vi.fn(async (_url: string, _init?: RequestInit) => Response.json({+ device_code: "device-secret",+ user_code: "ABCD-EFGH",+ verification_uri: "https://auth.example.com/device",+ verification_uri_complete: "https://auth.example.com/device?user_code=ABCD-EFGH",+ expires_in: 300,+ interval: 5,+ refresh_token: "must-not-cross-the-edge",+ }));+ vi.stubGlobal("fetch", providerFetch);++ const resp = await worker.fetch(request("/auth/cli/device", {+ method: "POST",+ headers: { "content-type": "application/json" },+ }), testEnv(), ctx);++ expect(resp.status).toBe(200);+ expect(resp.headers.get("cache-control")).toBe("no-store");+ expect(await resp.json()).toEqual({+ device_code: "device-secret",+ user_code: "ABCD-EFGH",+ verification_uri: "https://auth.example.com/device",+ verification_uri_complete: "https://auth.example.com/device?user_code=ABCD-EFGH",+ expires_in: 300,+ interval: 5,+ });+ const [, init] = providerFetch.mock.calls[0];+ expect(init?.headers).toEqual({ "content-type": "application/x-www-form-urlencoded" });+ expect(init?.body).toBe("client_id=client_test");+ expect(init?.redirect).toBe("error");+ });++ it("fails closed without exposing a malformed provider response", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => new Response("upstream-secret", { status: 200 })));+ const resp = await worker.fetch(request("/auth/cli/device", {+ method: "POST",+ headers: { "content-type": "application/json" },+ }), testEnv(), ctx);+ expect(resp.status).toBe(502);+ expect(resp.headers.get("cache-control")).toBe("no-store");+ expect(await resp.json()).toEqual({ error: "auth_provider_invalid_response" });+ });++ it("rejects a provider response that places the opaque device code in a URL", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => Response.json({+ device_code: "private-device-code",+ user_code: "ABCD-EFGH",+ verification_uri: "https://auth.example.com/device",+ verification_uri_complete: "https://auth.example.com/device?device_code=private-device-code",+ expires_in: 300,+ interval: 5,+ })));+ const resp = await worker.fetch(request("/auth/cli/device", {+ method: "POST",+ headers: { "content-type": "application/json" },+ }), testEnv(), ctx);+ expect(resp.status).toBe(502);+ expect(await resp.json()).toEqual({ error: "auth_provider_invalid_response" });+ });++ it("rejects wrong methods, bodies, and missing configuration without calling WorkOS", async () => {+ const providerFetch = vi.fn();+ vi.stubGlobal("fetch", providerFetch);++ const wrongMethod = await worker.fetch(+ request("/auth/cli/device", { method: "GET" }),+ testEnv(),+ ctx,+ );+ expect(wrongMethod.status).toBe(405);+ expect(await wrongMethod.json()).toEqual({ error: "method_not_allowed" });++ const wrongBody = await worker.fetch(request("/auth/cli/device", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: "{}",+ }), testEnv(), ctx);+ expect(wrongBody.status).toBe(400);+ expect(await wrongBody.json()).toEqual({ error: "invalid_request" });++ const unavailableEnv = testEnv() as Env;+ unavailableEnv.WORKOS_CLIENT_ID = "";+ const unavailable = await worker.fetch(request("/auth/cli/device", {+ method: "POST",+ headers: { "content-type": "application/json" },+ }), unavailableEnv, ctx);+ expect(unavailable.status).toBe(503);+ expect(unavailable.headers.get("cache-control")).toBe("no-store");+ expect(await unavailable.json()).toEqual({ error: "cli_login_unavailable" });+ expect(providerFetch).not.toHaveBeenCalled();+ });++ it.each([+ ["authorization_pending", 202, { status: "authorization_pending", retry_after: 5 }],+ ["slow_down", 202, { status: "authorization_pending", retry_after: 10 }],+ ["access_denied", 403, { error: "authorization_denied" }],+ ["expired_token", 410, { error: "authorization_expired" }],+ ])("maps provider %s without forwarding raw details", async (error, status, expected) => {+ vi.stubGlobal("fetch", vi.fn(async () => Response.json({+ error,+ error_description: "provider detail must remain private",+ }, { status: 400 })));+ const resp = await worker.fetch(request("/auth/cli/device/exchange", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ device_code: "opaque", credential_name: "oc CLI on test" }),+ }), testEnv(), ctx);+ expect(resp.status).toBe(status);+ expect(resp.headers.get("cache-control")).toBe("no-store");+ expect(await resp.json()).toEqual(expected);+ });++ it("creates one ordinary key while keeping provider tokens and plaintext out of D1", async () => {+ const db = new FakeDB();+ const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});+ const providerFetch = vi.fn(async (_url: string, _init?: RequestInit) => Response.json({+ user: {+ id: "workos-user",+ email: "[email protected]",+ first_name: "Igor",+ },+ access_token: "workos-access-secret",+ refresh_token: "workos-refresh-secret",+ }));+ vi.stubGlobal("fetch", providerFetch);++ const resp = await worker.fetch(request("/auth/cli/device/exchange", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ device_code: "opaque", credential_name: "oc CLI on test" }),+ }), testEnv(db), ctx);++ expect(resp.status).toBe(200);+ expect(resp.headers.get("cache-control")).toBe("no-store");+ const body = await resp.json<{+ status: string;+ credential: { id: string; key: string; key_prefix: string; name: string };+ user: { id: string; email: string; name: string };+ org: { id: string; name: string };+ }>();+ expect(body.status).toBe("authorized");+ expect(body.credential.key).toMatch(/^osb_[0-9a-f]{64}$/);+ expect(body.user).toEqual({ id: userID, email: "[email protected]", name: "Igor" });+ expect(body.org).toEqual({ id: orgID, name: "Igor's workspace" });+ expect(JSON.stringify(body)).not.toContain("workos-access-secret");+ expect(JSON.stringify(body)).not.toContain("workos-refresh-secret");++ const insert = db.executed.find((entry) => entry.sql.includes("INSERT INTO api_keys"));+ expect(insert).toBeDefined();+ expect(insert?.args[1]).toBe(orgID);+ expect(insert?.args[2]).toBe(userID);+ expect(insert?.args[3]).toMatch(/^[0-9a-f]{64}$/);+ expect(insert?.args).not.toContain(body.credential.key);+ expect(insert?.sql).toContain("'sandbox:*'");+ const [, providerInit] = providerFetch.mock.calls[0];+ const providerForm = new URLSearchParams(String(providerInit?.body));+ expect(providerForm.get("grant_type")).toBe("urn:ietf:params:oauth:grant-type:device_code");+ expect(providerForm.get("device_code")).toBe("opaque");+ expect(providerForm.get("client_id")).toBe("client_test");+ expect(providerForm.has("client_secret")).toBe(false);+ expect(providerInit?.redirect).toBe("error");+ const logs = logSpy.mock.calls.flat().join(" ");+ expect(logs).not.toContain("workos-access-secret");+ expect(logs).not.toContain("workos-refresh-secret");+ expect(logs).not.toContain(body.credential.key);+ expect(logs).not.toContain(body.credential.key_prefix);+ expect(logs).not.toContain("[email protected]");+ });++ it("selects a WorkOS-mapped membership before the personal fallback", async () => {+ const mappedOrgID = "33333333-3333-4333-8333-333333333333";+ const db = new FakeDB([+ {+ id: orgID,+ name: "Personal",+ plan: "free",+ is_personal: 1,+ workos_org_id: null,+ membership_created_at: 1,+ org_created_at: 1,+ },+ {+ id: mappedOrgID,+ name: "Digger",+ plan: "pro",+ is_personal: 0,+ workos_org_id: "workos-org",+ membership_created_at: 2,+ org_created_at: 2,+ },+ ]);+ vi.stubGlobal("fetch", vi.fn(async () => Response.json({+ user: { id: "workos-user", email: "[email protected]", first_name: "Igor" },+ organization_id: "workos-org",+ })));+ const resp = await worker.fetch(request("/auth/cli/device/exchange", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ device_code: "opaque", credential_name: "oc CLI" }),+ }), testEnv(db), ctx);+ expect(resp.status).toBe(200);+ const body = await resp.json<{ org: { id: string; name: string } }>();+ expect(body.org).toEqual({ id: mappedOrgID, name: "Digger" });+ const insert = db.executed.find((entry) => entry.sql.includes("INSERT INTO api_keys"));+ expect(insert?.args[1]).toBe(mappedOrgID);+ });++ it("provisions a first-login user, personal org, owner membership, and key", async () => {+ const db = new FakeDB([], null);+ vi.stubGlobal("fetch", vi.fn(async () => Response.json({+ user: {+ id: "new-workos-user",+ email: "[email protected]",+ first_name: "New",+ last_name: "User",+ },+ })));+ const resp = await worker.fetch(request("/auth/cli/device/exchange", {+ method: "POST",+ headers: {+ "content-type": "application/json",+ "cf-ipcountry": "US",+ },+ body: JSON.stringify({ device_code: "opaque", credential_name: "oc CLI" }),+ }), testEnv(db), ctx);+ expect(resp.status).toBe(200);+ const body = await resp.json<{+ user: { id: string; email: string; name: string };+ org: { id: string; name: string };+ credential: { key: string };+ }>();+ expect(body.user.email).toBe("[email protected]");+ expect(body.user.name).toBe("New User");+ expect(body.org.name).toBe("[email protected]'s workspace");+ expect(body.credential.key).toMatch(/^osb_[0-9a-f]{64}$/);++ const userInsert = db.executed.find((entry) => entry.sql.includes("INSERT INTO users"));+ const orgInsert = db.executed.find((entry) => entry.sql.includes("INSERT INTO orgs"));+ const membershipInsert = db.executed.find((entry) => entry.sql.includes("INSERT INTO org_memberships"));+ const keyInsert = db.executed.find((entry) => entry.sql.includes("INSERT INTO api_keys"));+ expect(userInsert).toBeDefined();+ expect(orgInsert?.args[3]).toBe("azure-us-east-2-a");+ expect(membershipInsert?.args[0]).toBe(body.org.id);+ expect(membershipInsert?.args[1]).toBe(body.user.id);+ expect(keyInsert?.args[1]).toBe(body.org.id);+ expect(keyInsert?.args[2]).toBe(body.user.id);+ });++ it("rejects extra exchange fields before contacting WorkOS", async () => {+ const providerFetch = vi.fn();+ vi.stubGlobal("fetch", providerFetch);+ const resp = await worker.fetch(request("/auth/cli/device/exchange", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ device_code: "opaque",+ credential_name: "oc CLI",+ user: { id: "attacker" },+ }),+ }), testEnv(), ctx);+ expect(resp.status).toBe(400);+ expect(await resp.json()).toEqual({ error: "invalid_request" });+ expect(providerFetch).not.toHaveBeenCalled();+ });+});++describe("CLI identity and credential lifecycle", () => {+ it("returns additive human identity fields from whoami", async () => {+ const resp = await worker.fetch(request("/api/whoami", {+ headers: { "X-API-Key": "osb_test" },+ }), testEnv(), ctx);+ expect(resp.status).toBe(200);+ expect(await resp.json()).toEqual({+ org_id: orgID,+ user_id: userID,+ email: "[email protected]",+ org_name: "Igor's workspace",+ });+ });++ it("revokes exactly the presented key and does not accept query credentials", async () => {+ const db = new FakeDB();+ const env = testEnv(db);+ const unauthorized = await worker.fetch(+ request("/auth/cli/credential?api_key=osb_query", { method: "DELETE" }),+ env,+ ctx,+ );+ expect(unauthorized.status).toBe(401);++ const resp = await worker.fetch(request("/auth/cli/credential", {+ method: "DELETE",+ headers: { "X-API-Key": "osb_presented" },+ }), env, ctx);+ expect(resp.status).toBe(204);+ expect(resp.headers.get("cache-control")).toBe("no-store");+ const deletion = db.executed.find((entry) => entry.sql.includes("DELETE FROM api_keys"));+ expect(deletion?.args[0]).toMatch(/^[0-9a-f]{64}$/);+ expect(deletion?.args[1]).toBe(orgID);+ });++ it("keeps the browser callback on its historical membership-selection query", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => Response.json({+ user: { id: "workos-user", email: "[email protected]", first_name: "Igor" },+ access_token: "header.payload.signature",+ })));+ const resp = await worker.fetch(request("/auth/callback?code=browser-code"), testEnv(), ctx);+ expect(resp.status).toBe(302);+ expect(resp.headers.get("location")).toBe("https://app.opencomputer.dev/dashboard");+ expect(resp.headers.get("set-cookie")).toContain("oc_session=");+ });++ it("keeps dashboard key creation on the existing one-time wire shape", async () => {+ const db = new FakeDB();+ vi.stubGlobal("fetch", vi.fn(async () => Response.json({+ user: { id: "workos-user", email: "[email protected]", first_name: "Igor" },+ })));+ const callback = await worker.fetch(+ request("/auth/callback?code=browser-code"),+ testEnv(db),+ ctx,+ );+ const cookie = callback.headers.get("set-cookie")?.split(";", 1)[0];+ expect(cookie).toMatch(/^oc_session=/);++ const resp = await worker.fetch(request("/api/dashboard/api-keys", {+ method: "POST",+ headers: {+ cookie: cookie ?? "",+ "content-type": "application/json",+ },+ body: JSON.stringify({ name: "Dashboard key" }),+ }), testEnv(db), ctx);+ expect(resp.status).toBe(201);+ const body = await resp.json<Record<string, unknown>>();+ expect(Object.keys(body)).toEqual([+ "id",+ "orgId",+ "name",+ "key",+ "keyPrefix",+ "scopes",+ "createdAt",+ ]);+ expect(body.orgId).toBe(orgID);+ expect(body.name).toBe("Dashboard key");+ expect(body.key).toMatch(/^osb_[0-9a-f]{64}$/);+ expect(body.keyPrefix).toBe(String(body.key).slice(0, 8));+ expect(body.scopes).toEqual(["sandbox:*"]);+ const insert = db.executed.find((entry) =>+ entry.sql.includes("INSERT INTO api_keys") && entry.args[5] === "Dashboard key"+ );+ expect(insert?.args).not.toContain(body.key);+ });+});diff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.tsindex 6be85a8b..554d3be1 100644--- a/cloudflare-workers/api-edge/src/dashboard.ts+++ b/cloudflare-workers/api-edge/src/dashboard.ts@@ -31,6 +31,7 @@ import {acknowledgeAgentSecurityNotification,listAgentSecurityNotifications,} from "./agent_security_notifications";+import { createAPIKey } from "./api_keys";export interface DashboardEnv {OPENCOMPUTER_DB: D1Database;@@ -186,11 +187,6 @@ function json(body: unknown, status = 200, extraHeaders: Record<string, string>});}-async function sha256Hex(s: string): Promise<string> {- const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s));- return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");-}-// D1 stores timestamps as unix seconds (INTEGER). The cell's Go handlers// marshal time.Time as RFC3339 strings, which is what the dashboard frontend// expects (`new Date(value)` then `.toISOString()`). Mirror that.@@ -564,22 +560,11 @@ async function handleListAPIKeys(_req: Request, env: DashboardEnv, caller: Calleasync function handleCreateAPIKey(req: Request, env: DashboardEnv, caller: Caller): Promise<Response> {const body = await req.json<{ name?: string }>().catch(() => ({} as { name?: string }));const name = (body.name ?? "Untitled").trim() || "Untitled";- // Same format as the cell: "osb_" + 64 hex chars (32 random bytes).- const bytes = new Uint8Array(32);- crypto.getRandomValues(bytes);- const plainKey = "osb_" + [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");- const hash = await sha256Hex(plainKey);- const prefix = plainKey.slice(0, 8);- const id = crypto.randomUUID();- const now = Math.floor(Date.now() / 1000);- await env.OPENCOMPUTER_DB.prepare(- `INSERT INTO api_keys (id, org_id, created_by, key_hash, key_prefix, name, scopes, created_at)- VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'sandbox:*', ?7)`,- ).bind(id, caller.orgID, caller.userID, hash, prefix, name, now).run();- return json({- id, orgId: caller.orgID, name, key: plainKey, keyPrefix: prefix,- scopes: ["sandbox:*"], createdAt: new Date(now * 1000).toISOString(),- }, 201);+ return json(await createAPIKey(env, {+ orgID: caller.orgID,+ userID: caller.userID,+ name,+ }), 201);}async function handleDeleteAPIKey(_req: Request, env: DashboardEnv, caller: Caller, keyID: string): Promise<Response> {diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex c04c7eb5..025df5f3 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -13,6 +13,9 @@// GET /auth/callback — WorkOS code exchange → upsert user/org → session JWT cookie// POST /auth/logout — clear session cookie// POST /auth/refresh — rotate session JWT (extends expiry)+// POST /auth/cli/device — begin WorkOS device authorization for `oc login`+// POST /auth/cli/device/exchange — poll device authorization → one ordinary org key+// DELETE /auth/cli/credential — revoke the exact CLI-presented org key// POST /webhooks/stripe — Stripe webhook → DO /mark-pro or /mark-free// GET /health@@ -37,6 +40,7 @@ import * as secretStores from "./secret_stores";import * as snapshots from "./snapshots";import * as templates from "./templates";import * as webhooks from "./webhooks";+import { createAPIKey, hashAPIKey } from "./api_keys";export interface Env extends DashboardEnv {CF_ADMIN_SECRET: string;@@ -100,11 +104,6 @@ const b64url = (buf: ArrayBuffer | Uint8Array): string => {return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");};-async function sha256Hex(s: string): Promise<string> {- const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s));- return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");-}-// Mint the capability token the regional CP expects on /internal/sandboxes/create:// HS256 JWT signed with SESSION_JWT_SECRET, iss="opensandbox-edge", carrying// org_id + cell_id + plan (+ optional user_id). Mirrors auth.CapabilityClaims@@ -203,7 +202,7 @@ async function authenticate(req: Request, env: Env): Promise<Caller | null> {) {return verifyProvisionToken(env.OC_PROVISION_SECRET, apiKey);}- const hash = await sha256Hex(apiKey);+ const hash = await hashAPIKey(apiKey);const row = await env.OPENCOMPUTER_DB.prepare("SELECT org_id, created_by, expires_at FROM api_keys WHERE key_hash = ?1",)@@ -1174,6 +1173,21 @@ interface WorkOSProfile {organization_id?: string;}+interface ProvisionedIdentity {+ user: {+ id: string;+ email: string;+ name: string;+ };+ org: {+ id: string;+ name: string;+ plan: string;+ };+}++type IdentitySelection = "browser" | "cli";+// A post-login destination is only honored if it is a same-origin PATH: it must// start with a single "/", carry no host (no "//" protocol-relative form) and no// backslash tricks. Tampering with the WorkOS `state` can then at most pick a@@ -1212,88 +1226,104 @@ async function authLogin(req: Request, env: Env): Promise<Response> {return Response.redirect(authURL.toString(), 302);}-async function authCallback(req: Request, env: Env): Promise<Response> {- const reqURL = new URL(req.url);- const code = reqURL.searchParams.get("code");- if (!code) return json({ error: "missing code" }, 400);- const redirectURI = `${reqURL.origin}/auth/callback`;-- // Exchange code for user profile.- const tokenResp = await fetch("https://api.workos.com/user_management/authenticate", {- method: "POST",- headers: { "content-type": "application/json" },- body: JSON.stringify({- client_id: env.WORKOS_CLIENT_ID,- client_secret: env.WORKOS_API_KEY,- grant_type: "authorization_code",- code,- redirect_uri: redirectURI,- }),- });- if (tokenResp.status !== 200) {- const errText = await tokenResp.text();- return json({ error: `workos exchange failed: ${tokenResp.status}: ${errText}` }, 401);- }- const tokenBody = await tokenResp.json<{ user: WorkOSProfile; organization_id?: string; access_token?: string }>();- const profile = tokenBody.user;- // WorkOS session id (sid) for the hosted logout flow — carried in our session JWT.- const workosSessionID = workosSessionIdFromAccessToken(tokenBody.access_token);-- // Upsert user + org. We share WorkOS with prod, so workos_user_id is the- // stable identity across both. Org auto-created on first sign-in with- // home_cell picked per the policy below.+/**+ * Upserts the WorkOS user and guarantees at least one local membership.+ * Browser login deliberately preserves its historical "first membership"+ * selection; CLI login uses the deterministic policy in work 031 §3.2.+ */+async function provisionWorkOSIdentity(+ req: Request,+ env: Env,+ profile: WorkOSProfile,+ workosOrgID: string | undefined,+ selection: IdentitySelection,+): Promise<ProvisionedIdentity> {const nowSec = Math.floor(Date.now() / 1000);- const userRow = await env.OPENCOMPUTER_DB.prepare(- `SELECT id FROM users WHERE workos_user_id = ?1`,+ const displayName =+ [profile.first_name, profile.last_name].filter(Boolean).join(" ") || profile.email;++ let userRow = await env.OPENCOMPUTER_DB.prepare(+ `SELECT id, email, name FROM users WHERE workos_user_id = ?1`,).bind(profile.id)- .first<{ id: string }>();- let userID: string;- if (userRow) {- userID = userRow.id;- } else {- userID = crypto.randomUUID();+ .first<{ id: string; email: string; name: string | null }>();++ if (!userRow) {+ const candidateID = crypto.randomUUID();await env.OPENCOMPUTER_DB.prepare(`INSERT INTO users (id, email, workos_user_id, name, created_at)VALUES (?1, ?2, ?3, ?4, ?5)ON CONFLICT(email) DO UPDATE SET workos_user_id = excluded.workos_user_id`,)- .bind(- userID,- profile.email,- profile.id,- [profile.first_name, profile.last_name].filter(Boolean).join(" ") || profile.email,- nowSec,- )+ .bind(candidateID, profile.email, profile.id, displayName, nowSec).run();+ // Re-read after the email-conflict path: the existing row retains its id.+ userRow = await env.OPENCOMPUTER_DB.prepare(+ `SELECT id, email, name FROM users WHERE workos_user_id = ?1`,+ )+ .bind(profile.id)+ .first<{ id: string; email: string; name: string | null }>();+ if (!userRow) throw new Error("workos user upsert did not resolve");}- // Find an org via membership; if none, create a personal one.- const orgRow = await env.OPENCOMPUTER_DB.prepare(- `SELECT o.id, o.plan FROM orgs o- JOIN org_memberships m ON m.org_id = o.id- WHERE m.user_id = ?1 LIMIT 1`,- )- .bind(userID)- .first<{ id: string; plan: string }>();- let orgID: string;- let orgPlan: string;- if (orgRow) {- orgID = orgRow.id;- orgPlan = orgRow.plan;- } else {- orgID = crypto.randomUUID();+ const userID = userRow.id;+ type MembershipRow = {+ id: string;+ name: string;+ plan: string;+ is_personal: number;+ workos_org_id: string | null;+ membership_created_at: number;+ org_created_at: number;+ };++ const selectBrowserMembership = () =>+ env.OPENCOMPUTER_DB.prepare(+ `SELECT o.id, o.name, o.plan, o.is_personal, o.workos_org_id,+ m.created_at AS membership_created_at, o.created_at AS org_created_at+ FROM orgs o+ JOIN org_memberships m ON m.org_id = o.id+ WHERE m.user_id = ?1+ LIMIT 1`,+ )+ .bind(userID)+ .first<MembershipRow>();++ const selectCLIMembership = async (): Promise<MembershipRow | null> => {+ const { results } = await env.OPENCOMPUTER_DB.prepare(+ `SELECT o.id, o.name, o.plan, o.is_personal, o.workos_org_id,+ m.created_at AS membership_created_at, o.created_at AS org_created_at+ FROM orgs o+ JOIN org_memberships m ON m.org_id = o.id+ WHERE m.user_id = ?1+ ORDER BY m.created_at ASC, o.created_at ASC, o.id ASC`,+ )+ .bind(userID)+ .all<MembershipRow>();+ const memberships = results ?? [];+ if (workosOrgID) {+ const mapped = memberships.find((row) => row.workos_org_id === workosOrgID);+ if (mapped) return mapped;+ }+ const personal = memberships.find((row) => row.is_personal === 1);+ if (personal) return personal;+ if (memberships.length === 1) return memberships[0];+ return memberships[0] ?? null;+ };++ let orgRow =+ selection === "browser"+ ? await selectBrowserMembership()+ : await selectCLIMembership();++ if (!orgRow) {+ const orgID = crypto.randomUUID();const homeCell = await pickHomeCell(env, req);- orgPlan = "free";- // Stage 2: new signups go to Autumn when AUTUMN_NEW_ORGS is on. Create the- // Autumn customer first (it grants the $5 signup credit); only flag the org- // 'autumn' if that succeeds, so a transient Autumn failure falls back to the- // legacy trial rather than breaking signup. Existing orgs are untouched —- // they migrate later via cmd/migrate-to-autumn after notification.+ const orgName = `${profile.email}'s workspace`;let provider = "legacy";if (env.AUTUMN_NEW_ORGS === "true" && env.AUTUMN_SECRET_KEY) {try {- await createAutumnCustomer(env, { id: orgID, name: `${profile.email}'s workspace`, email: profile.email });+ await createAutumnCustomer(env, { id: orgID, name: orgName, email: profile.email });provider = "autumn";} catch (e) {console.error(`signup: autumn customer create failed for ${orgID}, falling back to legacy`, e);@@ -1305,7 +1335,7 @@ async function authCallback(req: Request, env: Env): Promise<Response> {).bind(orgID,- `${profile.email}'s workspace`,+ orgName,slugify(profile.email + "-" + orgID.slice(0, 6)),homeCell,userID,@@ -1319,11 +1349,74 @@ async function authCallback(req: Request, env: Env): Promise<Response> {).bind(orgID, userID, nowSec).run();+ orgRow = {+ id: orgID,+ name: orgName,+ plan: "free",+ is_personal: 1,+ workos_org_id: null,+ membership_created_at: nowSec,+ org_created_at: nowSec,+ };+ }++ return {+ user: {+ id: userID,+ email: userRow.email || profile.email,+ name: userRow.name || displayName,+ },+ org: {+ id: orgRow.id,+ name: orgRow.name,+ plan: orgRow.plan,+ },+ };+}++async function authCallback(req: Request, env: Env): Promise<Response> {+ const reqURL = new URL(req.url);+ const code = reqURL.searchParams.get("code");+ if (!code) return json({ error: "missing code" }, 400);+ const redirectURI = `${reqURL.origin}/auth/callback`;++ // Exchange code for user profile.+ const tokenResp = await fetch("https://api.workos.com/user_management/authenticate", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ client_id: env.WORKOS_CLIENT_ID,+ client_secret: env.WORKOS_API_KEY,+ grant_type: "authorization_code",+ code,+ redirect_uri: redirectURI,+ }),+ });+ if (tokenResp.status !== 200) {+ const errText = await tokenResp.text();+ return json({ error: `workos exchange failed: ${tokenResp.status}: ${errText}` }, 401);}+ const tokenBody = await tokenResp.json<{ user: WorkOSProfile; organization_id?: string; access_token?: string }>();+ const profile = tokenBody.user;+ // WorkOS session id (sid) for the hosted logout flow — carried in our session JWT.+ const workosSessionID = workosSessionIdFromAccessToken(tokenBody.access_token);+ const identity = await provisionWorkOSIdentity(+ req,+ env,+ profile,+ tokenBody.organization_id ?? profile.organization_id,+ "browser",+ );// Mint session JWT — same signing secret as cap-token but a different// Issuer so cell middleware can distinguish.- const sessionJWT = await mintSessionJWT(env.SESSION_JWT_SECRET, orgID, userID, orgPlan, workosSessionID);+ const sessionJWT = await mintSessionJWT(+ env.SESSION_JWT_SECRET,+ identity.org.id,+ identity.user.id,+ identity.org.plan,+ workosSessionID,+ );// Land on the deferred deep link if `state` carried a valid one, else the// dashboard. Re-validate here: `state` is attacker-influenceable, so the path@@ -1347,6 +1440,396 @@ async function authCallback(req: Request, env: Env): Promise<Response> {});}+const CLI_AUTH_MAX_BODY_BYTES = 4096;+const CLI_AUTH_MAX_DEVICE_CODE = 2048;+const CLI_AUTH_MAX_CREDENTIAL_NAME = 100;+const CLI_AUTH_DEFAULT_RETRY_SEC = 5;+const CLI_AUTH_MAX_PROVIDER_BODY_BYTES = 64 * 1024;++function cliAuthJSON(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: {+ "content-type": "application/json",+ "cache-control": "no-store",+ },+ });+}++function cliAuthError(error: string, status: number): Response {+ return cliAuthJSON({ error }, status);+}++function recordCLIAuth(+ event: "cli_auth_start" | "cli_auth_exchange" | "cli_auth_revoke",+ requestID: string,+ result: string,+ status: number,+ startedAt: number,+ ids: { user_id?: string; org_id?: string; credential_id?: string } = {},+): void {+ console.log(JSON.stringify({+ event,+ request_id: requestID,+ result,+ http_status: status,+ duration_ms: Date.now() - startedAt,+ ...ids,+ }));+}++function isHTTPSURL(value: unknown): value is string {+ if (typeof value !== "string" || value.length === 0 || value.length > 2048) return false;+ try {+ return new URL(value).protocol === "https:";+ } catch {+ return false;+ }+}++function boundedInteger(value: unknown, min: number, max: number): value is number {+ return typeof value === "number" && Number.isInteger(value) && value >= min && value <= max;+}++function normalizeCLICredentialName(value: unknown): string | null {+ if (typeof value !== "string" || /[\u0000-\u001f\u007f]/.test(value)) return null;+ const normalized = value.trim().replace(/\s+/g, " ");+ if (!normalized || normalized.length > CLI_AUTH_MAX_CREDENTIAL_NAME) return null;+ return normalized;+}++async function readSmallJSONObject(+ req: Request,+): Promise<Record<string, unknown> | null> {+ const contentType = req.headers.get("content-type")?.split(";", 1)[0].trim().toLowerCase();+ if (contentType !== "application/json") return null;+ const contentLength = Number(req.headers.get("content-length") ?? "0");+ if (Number.isFinite(contentLength) && contentLength > CLI_AUTH_MAX_BODY_BYTES) return null;+ if (!req.body) return null;+ const reader = req.body.getReader();+ const chunks: Uint8Array[] = [];+ let total = 0;+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ total += value.byteLength;+ if (total > CLI_AUTH_MAX_BODY_BYTES) {+ await reader.cancel();+ return null;+ }+ chunks.push(value);+ }+ if (total === 0) return null;+ const body = new Uint8Array(total);+ let offset = 0;+ for (const chunk of chunks) {+ body.set(chunk, offset);+ offset += chunk.byteLength;+ }+ try {+ const parsed = JSON.parse(new TextDecoder().decode(body));+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;+ return parsed as Record<string, unknown>;+ } catch {+ return null;+ }+}++async function hasRequestBody(req: Request): Promise<boolean> {+ const contentLength = Number(req.headers.get("content-length") ?? "0");+ if (Number.isFinite(contentLength) && contentLength > 0) return true;+ if (!req.body) return false;+ const reader = req.body.getReader();+ const first = await reader.read();+ await reader.cancel();+ return !first.done && first.value.byteLength > 0;+}++async function parseProviderJSON(resp: Response): Promise<Record<string, unknown> | null> {+ const contentLength = Number(resp.headers.get("content-length") ?? "0");+ if (Number.isFinite(contentLength) && contentLength > CLI_AUTH_MAX_PROVIDER_BODY_BYTES) {+ return null;+ }+ if (!resp.body) return null;+ const reader = resp.body.getReader();+ const chunks: Uint8Array[] = [];+ let total = 0;+ try {+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ total += value.byteLength;+ if (total > CLI_AUTH_MAX_PROVIDER_BODY_BYTES) {+ await reader.cancel();+ return null;+ }+ chunks.push(value);+ }+ const raw = new Uint8Array(total);+ let offset = 0;+ for (const chunk of chunks) {+ raw.set(chunk, offset);+ offset += chunk.byteLength;+ }+ const body = JSON.parse(new TextDecoder().decode(raw)) as unknown;+ if (!body || typeof body !== "object" || Array.isArray(body)) return null;+ return body as Record<string, unknown>;+ } catch {+ return null;+ }+}++function urlContainsOpaqueCode(rawURL: string, code: string): boolean {+ if (rawURL.includes(code)) return true;+ try {+ return decodeURIComponent(rawURL).includes(code);+ } catch {+ return true;+ }+}++async function authCLIStart(req: Request, env: Env): Promise<Response> {+ const requestID = crypto.randomUUID();+ const startedAt = Date.now();+ const finish = (response: Response, result: string): Response => {+ recordCLIAuth("cli_auth_start", requestID, result, response.status, startedAt);+ return response;+ };++ if (req.method !== "POST") {+ return finish(cliAuthError("method_not_allowed", 405), "invalid_request");+ }+ if (!env.WORKOS_CLIENT_ID) {+ return finish(cliAuthError("cli_login_unavailable", 503), "configuration_error");+ }+ if (await hasRequestBody(req)) {+ return finish(cliAuthError("invalid_request", 400), "invalid_request");+ }++ let providerResp: Response;+ try {+ providerResp = await fetch("https://api.workos.com/user_management/authorize/device", {+ method: "POST",+ headers: { "content-type": "application/x-www-form-urlencoded" },+ body: new URLSearchParams({ client_id: env.WORKOS_CLIENT_ID }).toString(),+ redirect: "error",+ });+ } catch {+ return finish(cliAuthError("auth_provider_unavailable", 503), "provider_error");+ }+ if (!providerResp.ok) {+ return finish(cliAuthError("auth_provider_unavailable", 503), "provider_error");+ }++ const bodyJSON = await parseProviderJSON(providerResp);+ if (+ !bodyJSON ||+ typeof bodyJSON.device_code !== "string" ||+ bodyJSON.device_code.length === 0 ||+ bodyJSON.device_code.length > CLI_AUTH_MAX_DEVICE_CODE ||+ typeof bodyJSON.user_code !== "string" ||+ bodyJSON.user_code.length === 0 ||+ bodyJSON.user_code.length > 64 ||+ !isHTTPSURL(bodyJSON.verification_uri) ||+ !isHTTPSURL(bodyJSON.verification_uri_complete) ||+ !boundedInteger(bodyJSON.expires_in, 1, 3600) ||+ !boundedInteger(bodyJSON.interval, 1, 60) ||+ urlContainsOpaqueCode(bodyJSON.verification_uri, bodyJSON.device_code) ||+ urlContainsOpaqueCode(bodyJSON.verification_uri_complete, bodyJSON.device_code)+ ) {+ return finish(cliAuthError("auth_provider_invalid_response", 502), "provider_error");+ }++ return finish(cliAuthJSON({+ device_code: bodyJSON.device_code,+ user_code: bodyJSON.user_code,+ verification_uri: bodyJSON.verification_uri,+ verification_uri_complete: bodyJSON.verification_uri_complete,+ expires_in: bodyJSON.expires_in,+ interval: bodyJSON.interval,+ }), "success");+}++function providerErrorCode(body: Record<string, unknown> | null): string {+ return typeof body?.error === "string" ? body.error : "";+}++async function authCLIExchange(req: Request, env: Env): Promise<Response> {+ const requestID = crypto.randomUUID();+ const startedAt = Date.now();+ const finish = (+ response: Response,+ result: string,+ ids: { user_id?: string; org_id?: string; credential_id?: string } = {},+ ): Response => {+ recordCLIAuth("cli_auth_exchange", requestID, result, response.status, startedAt, ids);+ return response;+ };++ if (req.method !== "POST") {+ return finish(cliAuthError("method_not_allowed", 405), "invalid_request");+ }+ if (!env.WORKOS_CLIENT_ID) {+ return finish(cliAuthError("cli_login_unavailable", 503), "configuration_error");+ }+ const body = await readSmallJSONObject(req);+ if (+ !body ||+ Object.keys(body).length !== 2 ||+ !Object.hasOwn(body, "device_code") ||+ !Object.hasOwn(body, "credential_name") ||+ typeof body.device_code !== "string" ||+ body.device_code.length === 0 ||+ body.device_code.length > CLI_AUTH_MAX_DEVICE_CODE+ ) {+ return finish(cliAuthError("invalid_request", 400), "invalid_request");+ }+ const credentialName = normalizeCLICredentialName(body.credential_name);+ if (!credentialName) {+ return finish(cliAuthError("invalid_request", 400), "invalid_request");+ }++ let providerResp: Response;+ try {+ providerResp = await fetch("https://api.workos.com/user_management/authenticate", {+ method: "POST",+ headers: { "content-type": "application/x-www-form-urlencoded" },+ body: new URLSearchParams({+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",+ device_code: body.device_code,+ client_id: env.WORKOS_CLIENT_ID,+ }).toString(),+ redirect: "error",+ });+ } catch {+ return finish(cliAuthError("auth_provider_unavailable", 503), "provider_error");+ }++ const providerBody = await parseProviderJSON(providerResp);+ if (!providerResp.ok) {+ const code = providerErrorCode(providerBody);+ if (code === "authorization_pending") {+ return finish(+ cliAuthJSON({ status: "authorization_pending", retry_after: CLI_AUTH_DEFAULT_RETRY_SEC }, 202),+ "pending",+ );+ }+ if (code === "slow_down") {+ return finish(+ cliAuthJSON({ status: "authorization_pending", retry_after: CLI_AUTH_DEFAULT_RETRY_SEC + 5 }, 202),+ "pending",+ );+ }+ if (code === "access_denied" || code === "authorization_denied") {+ return finish(cliAuthError("authorization_denied", 403), "denied");+ }+ if (code === "expired_token" || code === "invalid_grant") {+ return finish(cliAuthError("authorization_expired", 410), "expired");+ }+ if (providerResp.status >= 500) {+ return finish(cliAuthError("auth_provider_unavailable", 503), "provider_error");+ }+ return finish(cliAuthError("auth_provider_invalid_response", 502), "provider_error");+ }++ const profile = providerBody?.user;+ if (+ !profile ||+ typeof profile !== "object" ||+ Array.isArray(profile) ||+ typeof (profile as Record<string, unknown>).id !== "string" ||+ typeof (profile as Record<string, unknown>).email !== "string"+ ) {+ return finish(cliAuthError("auth_provider_invalid_response", 502), "provider_error");+ }+ const typedProfile = profile as unknown as WorkOSProfile;+ const workosOrgID =+ typeof providerBody?.organization_id === "string"+ ? providerBody.organization_id+ : typedProfile.organization_id;++ let identity: ProvisionedIdentity;+ try {+ identity = await provisionWorkOSIdentity(req, env, typedProfile, workosOrgID, "cli");+ } catch {+ return finish(cliAuthError("account_provisioning_unavailable", 503), "provisioning_error");+ }++ let credential;+ try {+ credential = await createAPIKey(env, {+ orgID: identity.org.id,+ userID: identity.user.id,+ name: credentialName,+ });+ } catch {+ return finish(+ cliAuthError("credential_creation_failed", 503),+ "credential_error",+ { user_id: identity.user.id, org_id: identity.org.id },+ );+ }++ return finish(cliAuthJSON({+ status: "authorized",+ credential: {+ id: credential.id,+ key: credential.key,+ key_prefix: credential.keyPrefix,+ name: credential.name,+ },+ user: identity.user,+ org: {+ id: identity.org.id,+ name: identity.org.name,+ },+ }), "success", {+ user_id: identity.user.id,+ org_id: identity.org.id,+ credential_id: credential.id,+ });+}++async function authCLIRevoke(req: Request, env: Env): Promise<Response> {+ const requestID = crypto.randomUUID();+ const startedAt = Date.now();+ const finish = (response: Response, result: string): Response => {+ recordCLIAuth("cli_auth_revoke", requestID, result, response.status, startedAt);+ return response;+ };++ if (req.method !== "DELETE") {+ return finish(cliAuthError("method_not_allowed", 405), "invalid_request");+ }+ const plainKey = req.headers.get("X-API-Key");+ if (!plainKey || !plainKey.startsWith("osb_")) {+ return finish(cliAuthError("missing or invalid API key", 401), "unauthorized");+ }+ let caller: Caller | null;+ try {+ caller = await authenticate(req, env);+ } catch {+ return finish(cliAuthError("credential_revocation_unavailable", 503), "storage_error");+ }+ if (!caller || caller.scope) {+ return finish(cliAuthError("missing or invalid API key", 401), "unauthorized");+ }+ try {+ const hash = await hashAPIKey(plainKey);+ await env.OPENCOMPUTER_DB.prepare(+ `DELETE FROM api_keys WHERE key_hash = ?1 AND org_id = ?2`,+ )+ .bind(hash, caller.orgID)+ .run();+ } catch {+ return finish(cliAuthError("credential_revocation_unavailable", 503), "storage_error");+ }+ return finish(new Response(null, {+ status: 204,+ headers: { "cache-control": "no-store" },+ }), "success");+}+// Decode the WorkOS session id (`sid` claim) from a WorkOS access-token JWT// without verifying the signature. The token came straight from WorkOS's token// endpoint at callback; we only need the session id to build the hosted logout@@ -2092,7 +2575,19 @@ export default {return json({ error: "method not allowed" }, 405);}- // Auth flow (browser).+ // Auth flows. CLI device auth is deliberately edge-brokered: WorkOS tokens+ // never cross this boundary and the CLI receives one ordinary OC org key.+ if (path === "/auth/cli/device") {+ return authCLIStart(req, env);+ }+ if (path === "/auth/cli/device/exchange") {+ return authCLIExchange(req, env);+ }+ if (path === "/auth/cli/credential") {+ return authCLIRevoke(req, env);+ }++ // Browser auth flow.if (path === "/auth/login") { if (req.method === "GET") return authLogin(req, env); }if (path === "/auth/callback") { if (req.method === "GET") return authCallback(req, env); }if (path === "/auth/logout") { if (req.method === "POST") return authLogout(req, env); }@@ -2261,7 +2756,20 @@ export default {if (path === "/api/whoami" && req.method === "GET") {const caller = await authenticate(req, env);if (!caller) return json({ error: "missing or invalid API key" }, 401);- return json({ org_id: caller.orgID, user_id: caller.userID });+ const identity = await env.OPENCOMPUTER_DB.prepare(+ `SELECT o.name AS org_name, u.email AS email+ FROM orgs o+ LEFT JOIN users u ON u.id = ?1+ WHERE o.id = ?2`,+ )+ .bind(caller.userID, caller.orgID)+ .first<{ org_name: string; email: string | null }>();+ return json({+ org_id: caller.orgID,+ user_id: caller.userID,+ email: identity?.email ?? null,+ org_name: identity?.org_name ?? null,+ });}// /api/webhooks* — sandbox lifecycle webhook management (Svix-backed,diff --git a/cmd/oc/internal/commands/auth.go b/cmd/oc/internal/commands/auth.gonew file mode 100644index 00000000..f3b75bb6--- /dev/null+++ b/cmd/oc/internal/commands/auth.go@@ -0,0 +1,582 @@+package commands++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "net/url"+ "os"+ "os/exec"+ "runtime"+ "strings"+ "time"++ "github.com/opensandbox/opensandbox/cmd/oc/internal/client"+ "github.com/opensandbox/opensandbox/cmd/oc/internal/config"+ "github.com/spf13/cobra"+)++const maxAuthResponseBytes = 64 << 10++type deviceAuthorization struct {+ DeviceCode string `json:"device_code"`+ UserCode string `json:"user_code"`+ VerificationURI string `json:"verification_uri"`+ VerificationURIComplete string `json:"verification_uri_complete"`+ ExpiresIn int `json:"expires_in"`+ Interval int `json:"interval"`+}++type loginCredential struct {+ ID string `json:"id"`+ Key string `json:"key"`+ KeyPrefix string `json:"key_prefix"`+ Name string `json:"name"`+}++type loginIdentity struct {+ UserID string `json:"user_id"`+ Email string `json:"email"`+ OrgID string `json:"org_id"`+ OrgName string `json:"org_name"`+ APIURL string `json:"api_url"`+}++type deviceExchange struct {+ Status string `json:"status"`+ RetryAfter int `json:"retry_after"`+ Credential loginCredential `json:"credential"`+ User struct {+ ID string `json:"id"`+ Email string `json:"email"`+ Name string `json:"name"`+ } `json:"user"`+ Org struct {+ ID string `json:"id"`+ Name string `json:"name"`+ } `json:"org"`+}++type loginResult struct {+ loginIdentity+ Credential struct {+ ID string `json:"id"`+ KeyPrefix string `json:"key_prefix"`+ Name string `json:"name"`+ } `json:"credential"`+}++type edgeErrorBody struct {+ Error string `json:"error"`+}++type cliAuthAPIError struct {+ Code string+ API *client.APIError+}++func (e *cliAuthAPIError) Error() string {+ return e.API.Error()+}++func (e *cliAuthAPIError) Unwrap() error {+ return e.API+}++type cliAuthHTTP struct {+ baseURL string+ client *http.Client+}++func newCLIAuthHTTP(apiURL string) *cliAuthHTTP {+ base := strings.TrimRight(apiURL, "/")+ base = strings.TrimSuffix(base, "/api")+ return &cliAuthHTTP{+ baseURL: base,+ client: &http.Client{+ Timeout: 30 * time.Second,+ CheckRedirect: func(_ *http.Request, _ []*http.Request) error {+ return http.ErrUseLastResponse+ },+ },+ }+}++func (c *cliAuthHTTP) do(+ ctx context.Context,+ method string,+ path string,+ apiKey string,+ body any,+ out any,+) (int, string, error) {+ var bodyReader io.Reader+ if body != nil {+ encoded, err := json.Marshal(body)+ if err != nil {+ return 0, "", err+ }+ bodyReader = bytes.NewReader(encoded)+ }+ req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, bodyReader)+ if err != nil {+ return 0, "", err+ }+ if body != nil || (method == http.MethodPost && path == "/auth/cli/device") {+ req.Header.Set("Content-Type", "application/json")+ }+ if apiKey != "" {+ req.Header.Set("X-API-Key", apiKey)+ }++ resp, err := c.client.Do(req)+ if err != nil {+ return 0, "", err+ }+ defer resp.Body.Close()+ raw, err := io.ReadAll(io.LimitReader(resp.Body, maxAuthResponseBytes+1))+ if err != nil {+ return resp.StatusCode, "", err+ }+ if len(raw) > maxAuthResponseBytes {+ return resp.StatusCode, "", errors.New("OpenComputer returned an oversized authentication response")+ }+ if resp.StatusCode >= 400 {+ var edgeErr edgeErrorBody+ if json.Unmarshal(raw, &edgeErr) != nil || edgeErr.Error == "" {+ edgeErr.Error = "unexpected_auth_response"+ }+ return resp.StatusCode, edgeErr.Error, nil+ }+ if out != nil && len(raw) > 0 {+ if err := json.Unmarshal(raw, out); err != nil {+ return resp.StatusCode, "", errors.New("OpenComputer returned an invalid authentication response")+ }+ }+ return resp.StatusCode, "", nil+}++func (c *cliAuthHTTP) start(ctx context.Context) (deviceAuthorization, error) {+ var receipt deviceAuthorization+ status, code, err := c.do(ctx, http.MethodPost, "/auth/cli/device", "", nil, &receipt)+ if err != nil {+ return receipt, err+ }+ if status != http.StatusOK {+ return receipt, authAPIError(status, code)+ }+ verification, err := url.Parse(receipt.VerificationURIComplete)+ if err != nil || verification.Scheme != "https" || verification.Host == "" {+ return receipt, errors.New("OpenComputer returned an invalid verification URL")+ }+ if receipt.DeviceCode == "" || receipt.UserCode == "" || receipt.ExpiresIn <= 0 || receipt.Interval <= 0 {+ return receipt, errors.New("OpenComputer returned an incomplete authentication response")+ }+ if strings.Contains(receipt.VerificationURI, receipt.DeviceCode) ||+ strings.Contains(receipt.VerificationURIComplete, receipt.DeviceCode) {+ return receipt, errors.New("OpenComputer returned an unsafe verification URL")+ }+ return receipt, nil+}++func (c *cliAuthHTTP) exchange(+ ctx context.Context,+ deviceCode string,+ credentialName string,+) (deviceExchange, error) {+ var exchange deviceExchange+ status, code, err := c.do(ctx, http.MethodPost, "/auth/cli/device/exchange", "", map[string]string{+ "device_code": deviceCode,+ "credential_name": credentialName,+ }, &exchange)+ if err != nil {+ return exchange, err+ }+ if status == http.StatusAccepted {+ if exchange.Status != "authorization_pending" {+ return exchange, errors.New("OpenComputer returned an invalid pending response")+ }+ return exchange, nil+ }+ if status != http.StatusOK {+ return exchange, authAPIError(status, code)+ }+ if exchange.Status != "authorized" ||+ exchange.Credential.ID == "" ||+ !validOrgKey(exchange.Credential.Key) ||+ exchange.User.ID == "" ||+ exchange.Org.ID == "" {+ return exchange, errors.New("OpenComputer returned an incomplete login credential")+ }+ return exchange, nil+}++func validOrgKey(key string) bool {+ if len(key) != 68 || !strings.HasPrefix(key, "osb_") {+ return false+ }+ for _, r := range key[4:] {+ if (r < '0' || r > '9') && (r < 'a' || r > 'f') {+ return false+ }+ }+ return true+}++func (c *cliAuthHTTP) whoami(ctx context.Context, apiKey string) (loginIdentity, error) {+ var identity loginIdentity+ status, code, err := c.do(ctx, http.MethodGet, "/api/whoami", apiKey, nil, &identity)+ if err != nil {+ return identity, err+ }+ if status != http.StatusOK {+ return identity, authAPIError(status, code)+ }+ identity.APIURL = c.baseURL+ if identity.OrgID == "" {+ return identity, errors.New("OpenComputer returned an incomplete identity response")+ }+ return identity, nil+}++func (c *cliAuthHTTP) revoke(ctx context.Context, apiKey string) error {+ status, code, err := c.do(ctx, http.MethodDelete, "/auth/cli/credential", apiKey, nil, nil)+ if err != nil {+ return err+ }+ switch status {+ case http.StatusNoContent, http.StatusUnauthorized, http.StatusNotFound:+ return nil+ default:+ return authAPIError(status, code)+ }+}++func authAPIError(status int, code string) error {+ action := "Retry in a moment; existing configured credentials were not changed."+ switch code {+ case "authorization_expired":+ action = "The confirmation expired; run `oc login` again."+ case "authorization_denied":+ action = "Authorization was denied; run `oc login` again and approve the displayed code."+ case "cli_login_unavailable":+ action = "CLI login is not configured on this OpenComputer API."+ case "invalid_request":+ action = "The CLI and API disagree on the login request; update `oc` and retry."+ case "account_provisioning_unavailable":+ action = "Authorization completed, but the OpenComputer account could not be prepared; run `oc login` again."+ case "credential_creation_failed":+ action = "Authorization completed, but the CLI credential could not be created; run `oc login` again."+ }+ if code == "" {+ code = "authentication_failed"+ }+ return &cliAuthAPIError{+ Code: code,+ API: &client.APIError{+ StatusCode: status,+ Message: fmt.Sprintf("%s: %s", code, action),+ },+ }+}++var (+ openAuthBrowser = openBrowser+ authSleep = sleepContext+)++func openBrowser(rawURL string) error {+ var command string+ var args []string+ switch runtime.GOOS {+ case "darwin":+ command, args = "open", []string{rawURL}+ case "windows":+ command, args = "rundll32", []string{"url.dll,FileProtocolHandler", rawURL}+ default:+ command, args = "xdg-open", []string{rawURL}+ }+ return exec.Command(command, args...).Start()+}++func sleepContext(ctx context.Context, delay time.Duration) error {+ timer := time.NewTimer(delay)+ defer timer.Stop()+ select {+ case <-ctx.Done():+ return ctx.Err()+ case <-timer.C:+ return nil+ }+}++func credentialName() string {+ hostname, err := os.Hostname()+ if err != nil {+ return "oc CLI"+ }+ hostname = strings.TrimSpace(strings.Map(func(r rune) rune {+ if r < 0x20 || r == 0x7f {+ return -1+ }+ return r+ }, hostname))+ if hostname == "" {+ return "oc CLI"+ }+ name := []rune("oc CLI on " + hostname)+ if len(name) > 100 {+ name = name[:100]+ }+ return string(name)+}++func printLoginResult(cmd *cobra.Command, result loginResult, already bool) error {+ if jsonOutput {+ return json.NewEncoder(cmd.OutOrStdout()).Encode(result)+ }+ prefix := "✓ Logged in as "+ if already {+ prefix = "Already logged in as "+ }+ fmt.Fprintf(cmd.OutOrStdout(), "%s%s\n", prefix, oneLine(result.Email))+ fmt.Fprintf(cmd.OutOrStdout(), " %-11s %s\n", "Workspace", oneLine(result.OrgName))+ fmt.Fprintf(cmd.OutOrStdout(), " %-11s %s\n", "API", oneLine(result.APIURL))+ if !already {+ fmt.Fprintln(cmd.OutOrStdout(), "\nNext: oc agent init")+ }+ return nil+}++func identityAsLoginResult(identity loginIdentity, metadata *config.LoginMetadata) loginResult {+ result := loginResult{loginIdentity: identity}+ if metadata != nil {+ result.Credential.ID = metadata.CredentialID+ result.Credential.KeyPrefix = metadata.KeyPrefix+ result.Credential.Name = metadata.Name+ }+ return result+}++func runLogin(cmd *cobra.Command, force, noBrowser bool) error {+ source := config.EffectiveCredentialSource(cmd)+ if source == config.CredentialSourceEnvironment || source == config.CredentialSourceFlag {+ return fmt.Errorf("%s currently controls authentication; unset it before running `oc login`", source)+ }++ fileCfg := config.LoadFile()+ resolved := config.Load(cmd)+ if resolved.APIURL == "" {+ resolved.APIURL = config.DefaultAPIURL+ }+ authClient := newCLIAuthHTTP(resolved.APIURL)++ var oldManagedKey string+ var oldManagedAPI string+ if fileCfg.APIKey != "" {+ if fileCfg.Login == nil {+ if !force {+ return errors.New("a manually configured API key is already saved; use `oc login --force` to replace it locally")+ }+ } else {+ oldAPI := fileCfg.Login.APIURL+ if oldAPI == "" {+ oldAPI = resolved.APIURL+ }+ identity, err := newCLIAuthHTTP(oldAPI).whoami(cmd.Context(), fileCfg.APIKey)+ if err == nil {+ if !force {+ return printLoginResult(cmd, identityAsLoginResult(identity, fileCfg.Login), true)+ }+ oldManagedKey = fileCfg.APIKey+ oldManagedAPI = oldAPI+ } else {+ var apiErr *client.APIError+ if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusUnauthorized {+ return fmt.Errorf("checking existing login before replacement: %w", err)+ }+ }+ }+ }++ receipt, err := authClient.start(cmd.Context())+ if err != nil {+ return fmt.Errorf("starting login: %w", err)+ }+ errOut := cmd.ErrOrStderr()+ style := deployStyleFor(errOut)+ fmt.Fprintln(errOut, "Open this page to sign in:")+ fmt.Fprintf(errOut, " %s\n\n", terminalLink(receipt.VerificationURIComplete, style))+ fmt.Fprintf(errOut, "Confirm code: %s\n", oneLine(receipt.UserCode))+ fmt.Fprintln(errOut, "Waiting for confirmation…")+ if !noBrowser {+ if err := openAuthBrowser(receipt.VerificationURIComplete); err != nil {+ fmt.Fprintf(errOut, "Could not open a browser automatically: %s\n", oneLine(err.Error()))+ }+ }++ interval := time.Duration(receipt.Interval) * time.Second+ deadline := time.Now().Add(time.Duration(receipt.ExpiresIn) * time.Second)+ var exchange deviceExchange+ consecutiveTransientFailures := 0+ for {+ if time.Now().Add(interval).After(deadline) {+ return authAPIError(http.StatusGone, "authorization_expired")+ }+ if err := authSleep(cmd.Context(), interval); err != nil {+ return err+ }+ exchange, err = authClient.exchange(cmd.Context(), receipt.DeviceCode, credentialName())+ if err != nil {+ var authErr *cliAuthAPIError+ if errors.As(err, &authErr) &&+ authErr.Code == "auth_provider_unavailable" &&+ consecutiveTransientFailures < 2 {+ consecutiveTransientFailures+++ continue+ }+ return fmt.Errorf("confirming login: %w", err)+ }+ consecutiveTransientFailures = 0+ if exchange.Status == "authorized" {+ break+ }+ if exchange.RetryAfter > 0 {+ next := time.Duration(exchange.RetryAfter) * time.Second+ if next > interval {+ interval = next+ }+ }+ }++ nextCfg := fileCfg+ nextCfg.APIURL = resolved.APIURL+ nextCfg.APIKey = exchange.Credential.Key+ nextCfg.Login = &config.LoginMetadata{+ CredentialID: exchange.Credential.ID,+ KeyPrefix: exchange.Credential.KeyPrefix,+ Name: exchange.Credential.Name,+ APIURL: resolved.APIURL,+ }+ if err := config.Save(nextCfg); err != nil {+ return fmt.Errorf(+ "login was authorized but the credential could not be saved; remove %q in the dashboard if needed: %w",+ exchange.Credential.Name,+ err,+ )+ }++ identity, err := authClient.whoami(cmd.Context(), exchange.Credential.Key)+ if err != nil {+ return fmt.Errorf(+ "login credential was saved but verification failed; inspect it in the dashboard before retrying: %w",+ err,+ )+ }++ if oldManagedKey != "" {+ if err := newCLIAuthHTTP(oldManagedAPI).revoke(cmd.Context(), oldManagedKey); err != nil {+ return fmt.Errorf(+ "replacement login is active, but the previous CLI credential could not be revoked; remove it in the dashboard: %w",+ err,+ )+ }+ }++ result := identityAsLoginResult(identity, nextCfg.Login)+ return printLoginResult(cmd, result, false)+}++func runWhoami(cmd *cobra.Command) error {+ cfg := config.Load(cmd)+ if cfg.APIKey == "" {+ return errors.New("not logged in; run `oc login` or set OPENCOMPUTER_API_KEY")+ }+ identity, err := newCLIAuthHTTP(cfg.APIURL).whoami(cmd.Context(), cfg.APIKey)+ if err != nil {+ return err+ }+ if jsonOutput {+ return json.NewEncoder(cmd.OutOrStdout()).Encode(identity)+ }+ fmt.Fprintf(cmd.OutOrStdout(), "User %s\n", oneLine(identity.Email))+ fmt.Fprintf(cmd.OutOrStdout(), "Workspace %s\n", oneLine(identity.OrgName))+ fmt.Fprintf(cmd.OutOrStdout(), "Org ID %s\n", oneLine(identity.OrgID))+ fmt.Fprintf(cmd.OutOrStdout(), "API %s\n", oneLine(identity.APIURL))+ return nil+}++func runLogout(cmd *cobra.Command, localOnly bool) error {+ source := config.EffectiveCredentialSource(cmd)+ if source == config.CredentialSourceEnvironment || source == config.CredentialSourceFlag {+ return fmt.Errorf("%s still controls authentication; unset it before logging out", source)+ }+ fileCfg := config.LoadFile()+ if fileCfg.APIKey == "" || fileCfg.Login == nil {+ return errors.New("there is no CLI-managed login to revoke")+ }++ if !localOnly {+ apiURL := fileCfg.Login.APIURL+ if apiURL == "" {+ apiURL = fileCfg.APIURL+ }+ if apiURL == "" {+ apiURL = config.DefaultAPIURL+ }+ if err := newCLIAuthHTTP(apiURL).revoke(cmd.Context(), fileCfg.APIKey); err != nil {+ return fmt.Errorf("remote logout was not confirmed; local login was retained (retry or use `oc logout --local`): %w", err)+ }+ }++ fileCfg.APIKey = ""+ fileCfg.Login = nil+ if err := config.Save(fileCfg); err != nil {+ return fmt.Errorf("clearing local login: %w", err)+ }+ if jsonOutput {+ return json.NewEncoder(cmd.OutOrStdout()).Encode(map[string]string{"status": "logged_out"})+ }+ fmt.Fprintln(cmd.OutOrStdout(), "Logged out.")+ return nil+}++var loginCmd = &cobra.Command{+ Use: "login",+ Short: "Sign in to OpenComputer",+ Args: cobra.NoArgs,+ RunE: func(cmd *cobra.Command, _ []string) error {+ force, _ := cmd.Flags().GetBool("force")+ noBrowser, _ := cmd.Flags().GetBool("no-browser")+ return runLogin(cmd, force, noBrowser)+ },+}++var whoamiCmd = &cobra.Command{+ Use: "whoami",+ Short: "Show the current OpenComputer identity",+ Args: cobra.NoArgs,+ RunE: func(cmd *cobra.Command, _ []string) error {+ return runWhoami(cmd)+ },+}++var logoutCmd = &cobra.Command{+ Use: "logout",+ Short: "Revoke the CLI login and clear it locally",+ Args: cobra.NoArgs,+ RunE: func(cmd *cobra.Command, _ []string) error {+ localOnly, _ := cmd.Flags().GetBool("local")+ return runLogout(cmd, localOnly)+ },+}++func init() {+ loginCmd.Flags().Bool("no-browser", false, "Print the confirmation URL without opening a browser")+ loginCmd.Flags().Bool("force", false, "Replace an existing saved credential")+ logoutCmd.Flags().Bool("local", false, "Clear local login state without remote revocation")+}diff --git a/cmd/oc/internal/commands/auth_test.go b/cmd/oc/internal/commands/auth_test.gonew file mode 100644index 00000000..63bbd742--- /dev/null+++ b/cmd/oc/internal/commands/auth_test.go@@ -0,0 +1,647 @@+package commands++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "runtime"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/opensandbox/opensandbox/cmd/oc/internal/config"+ "github.com/spf13/cobra"+)++const (+ testDeviceCode = "private-device-code"+ testUserCode = "ABCD-EFGH"+ testKey = "osb_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+ oldTestKey = "osb_bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"+)++func authTestCommand(t *testing.T, apiURL string) (*cobra.Command, *bytes.Buffer, *bytes.Buffer) {+ t.Helper()+ home := t.TempDir()+ t.Setenv("HOME", home)+ if runtime.GOOS == "windows" {+ t.Setenv("USERPROFILE", home)+ }+ t.Setenv("OPENCOMPUTER_API_URL", apiURL)+ t.Setenv("OPENCOMPUTER_API_KEY", "")+ t.Setenv("SESSIONS_API_URL", "")++ cmd := &cobra.Command{}+ cmd.SetContext(context.Background())+ var stdout, stderr bytes.Buffer+ cmd.SetOut(&stdout)+ cmd.SetErr(&stderr)++ oldSleep, oldOpen, oldJSON := authSleep, openAuthBrowser, jsonOutput+ authSleep = func(context.Context, time.Duration) error { return nil }+ openAuthBrowser = func(string) error { return nil }+ jsonOutput = false+ t.Cleanup(func() {+ authSleep = oldSleep+ openAuthBrowser = oldOpen+ jsonOutput = oldJSON+ })+ return cmd, &stdout, &stderr+}++func writeJSONResponse(w http.ResponseWriter, status int, body any) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(status)+ _ = json.NewEncoder(w).Encode(body)+}++func deviceReceipt() map[string]any {+ return map[string]any{+ "device_code": testDeviceCode,+ "user_code": testUserCode,+ "verification_uri": "https://auth.example.test/device",+ "verification_uri_complete": "https://auth.example.test/device?user_code=" + testUserCode,+ "expires_in": 300,+ "interval": 1,+ }+}++func authorizedExchange() map[string]any {+ return map[string]any{+ "status": "authorized",+ "credential": map[string]any{+ "id": "credential-1",+ "key": testKey,+ "key_prefix": "osb_aaaa",+ "name": "oc CLI on test",+ },+ "user": map[string]any{+ "id": "user-1",+ "email": "[email protected]",+ "name": "Igor",+ },+ "org": map[string]any{+ "id": "org-1",+ "name": "Igor's workspace",+ },+ }+}++func whoamiResponse() map[string]any {+ return map[string]any{+ "user_id": "user-1",+ "email": "[email protected]",+ "org_id": "org-1",+ "org_name": "Igor's workspace",+ }+}++func TestLoginPollsSavesVerifiesAndNeverPrintsCredential(t *testing.T) {+ var mu sync.Mutex+ var exchanges int+ var opened string+ var delays []time.Duration+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/auth/cli/device":+ if r.Method != http.MethodPost {+ t.Errorf("start method = %s", r.Method)+ }+ if r.Header.Get("X-API-Key") != "" {+ t.Error("start unexpectedly carried an API key")+ }+ writeJSONResponse(w, 200, deviceReceipt())+ case "/auth/cli/device/exchange":+ var body map[string]string+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Errorf("exchange body: %v", err)+ }+ if body["device_code"] != testDeviceCode {+ t.Errorf("device code = %q", body["device_code"])+ }+ mu.Lock()+ exchanges+++ attempt := exchanges+ mu.Unlock()+ if attempt == 1 {+ writeJSONResponse(w, 202, map[string]any{+ "status": "authorization_pending",+ "retry_after": 2,+ })+ return+ }+ writeJSONResponse(w, 200, authorizedExchange())+ case "/api/whoami":+ if r.Header.Get("X-API-Key") != testKey {+ t.Errorf("whoami key = %q", r.Header.Get("X-API-Key"))+ }+ writeJSONResponse(w, 200, whoamiResponse())+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()++ cmd, stdout, stderr := authTestCommand(t, server.URL)+ authSleep = func(_ context.Context, delay time.Duration) error {+ delays = append(delays, delay)+ return nil+ }+ openAuthBrowser = func(rawURL string) error {+ opened = rawURL+ return nil+ }+ if err := runLogin(cmd, false, false); err != nil {+ t.Fatalf("runLogin: %v", err)+ }++ if exchanges != 2 {+ t.Fatalf("exchange attempts = %d, want 2", exchanges)+ }+ if fmt.Sprint(delays) != "[1s 2s]" {+ t.Fatalf("poll delays = %v, want [1s 2s]", delays)+ }+ if opened != "https://auth.example.test/device?user_code="+testUserCode {+ t.Fatalf("opened URL = %q", opened)+ }+ if !strings.Contains(stderr.String(), testUserCode) ||+ !strings.Contains(stderr.String(), "https://auth.example.test/device") {+ t.Fatalf("missing confirmation instructions:\n%s", stderr.String())+ }+ combined := stdout.String() + stderr.String()+ if strings.Contains(combined, testKey) || strings.Contains(combined, testDeviceCode) {+ t.Fatalf("secret leaked to output: %q", combined)+ }+ if !strings.Contains(stdout.String(), "Logged in as [email protected]") ||+ !strings.Contains(stdout.String(), "Igor's workspace") {+ t.Fatalf("unexpected success output:\n%s", stdout.String())+ }++ saved := config.LoadFile()+ if saved.APIKey != testKey || saved.Login == nil || saved.Login.CredentialID != "credential-1" {+ t.Fatalf("saved config = %#v", saved)+ }+ if runtime.GOOS != "windows" {+ info, err := os.Stat(config.ConfigPath())+ if err != nil {+ t.Fatal(err)+ }+ if info.Mode().Perm() != 0o600 {+ t.Fatalf("config mode = %o", info.Mode().Perm())+ }+ }+}++func TestLoginNoBrowserAndJSONContainNoKeyOrDeviceCode(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/auth/cli/device":+ writeJSONResponse(w, 200, deviceReceipt())+ case "/auth/cli/device/exchange":+ writeJSONResponse(w, 200, authorizedExchange())+ case "/api/whoami":+ writeJSONResponse(w, 200, whoamiResponse())+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()+ cmd, stdout, stderr := authTestCommand(t, server.URL)+ jsonOutput = true+ openAuthBrowser = func(string) error {+ t.Fatal("browser opener called under --no-browser")+ return nil+ }+ if err := runLogin(cmd, false, true); err != nil {+ t.Fatalf("runLogin: %v", err)+ }+ var got map[string]any+ if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {+ t.Fatalf("JSON output: %v\n%s", err, stdout.String())+ }+ combined := stdout.String() + stderr.String()+ if strings.Contains(combined, testKey) || strings.Contains(combined, testDeviceCode) {+ t.Fatalf("secret leaked to output: %q", combined)+ }+ if got["email"] != "[email protected]" || got["org_id"] != "org-1" {+ t.Fatalf("login JSON = %#v", got)+ }+}++func TestLoginRejectsVerificationURLContainingDeviceCodeBeforePrinting(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ receipt := deviceReceipt()+ receipt["verification_uri_complete"] = "https://auth.example.test/device?device_code=" + testDeviceCode+ writeJSONResponse(w, 200, receipt)+ }))+ defer server.Close()+ cmd, stdout, stderr := authTestCommand(t, server.URL)+ err := runLogin(cmd, false, true)+ if err == nil || !strings.Contains(err.Error(), "unsafe verification URL") {+ t.Fatalf("error = %v", err)+ }+ if strings.Contains(stdout.String()+stderr.String(), testDeviceCode) {+ t.Fatalf("device code leaked to output: %q", stdout.String()+stderr.String())+ }+}++func TestLoginRefusesEnvironmentCredentialWithoutCallingAPI(t *testing.T) {+ var calls int+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ calls+++ http.Error(w, "unexpected", 500)+ }))+ defer server.Close()+ cmd, _, _ := authTestCommand(t, server.URL)+ t.Setenv("OPENCOMPUTER_API_KEY", "environment-key")+ err := runLogin(cmd, true, true)+ if err == nil || !strings.Contains(err.Error(), "OPENCOMPUTER_API_KEY") {+ t.Fatalf("error = %v", err)+ }+ if calls != 0 {+ t.Fatalf("API called %d times", calls)+ }+}++func TestLoginForceStoresAndVerifiesReplacementBeforeRevokingOld(t *testing.T) {+ var sequence []string+ var mu sync.Mutex+ record := func(s string) {+ mu.Lock()+ defer mu.Unlock()+ sequence = append(sequence, s)+ }+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/api/whoami":+ key := r.Header.Get("X-API-Key")+ if key == oldTestKey {+ record("old-whoami")+ } else if key == testKey {+ saved := config.LoadFile()+ if saved.APIKey != testKey {+ t.Errorf("new key not saved before verification")+ }+ record("new-whoami")+ }+ writeJSONResponse(w, 200, whoamiResponse())+ case "/auth/cli/device":+ record("start")+ writeJSONResponse(w, 200, deviceReceipt())+ case "/auth/cli/device/exchange":+ record("exchange")+ writeJSONResponse(w, 200, authorizedExchange())+ case "/auth/cli/credential":+ if r.Header.Get("X-API-Key") != oldTestKey {+ t.Errorf("revoked key = %q", r.Header.Get("X-API-Key"))+ }+ if config.LoadFile().APIKey != testKey {+ t.Errorf("replacement not saved before old-key revoke")+ }+ record("old-revoke")+ w.WriteHeader(http.StatusNoContent)+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()+ cmd, _, _ := authTestCommand(t, server.URL)+ if err := config.Save(config.Config{+ APIURL: server.URL,+ APIKey: oldTestKey,+ Login: &config.LoginMetadata{+ CredentialID: "old-id",+ KeyPrefix: "osb_bbbb",+ Name: "oc CLI on old",+ APIURL: server.URL,+ },+ }); err != nil {+ t.Fatal(err)+ }+ if err := runLogin(cmd, true, true); err != nil {+ t.Fatalf("runLogin --force: %v", err)+ }+ got := strings.Join(sequence, ",")+ want := "old-whoami,start,exchange,new-whoami,old-revoke"+ if got != want {+ t.Fatalf("sequence = %q, want %q", got, want)+ }+}++func TestLoginWithValidManagedCredentialExitsWithoutNewAuthorization(t *testing.T) {+ var starts int+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/api/whoami":+ writeJSONResponse(w, 200, whoamiResponse())+ case "/auth/cli/device":+ starts+++ http.Error(w, "unexpected", 500)+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()+ cmd, stdout, _ := authTestCommand(t, server.URL)+ if err := config.Save(config.Config{+ APIURL: server.URL,+ APIKey: testKey,+ Login: &config.LoginMetadata{+ CredentialID: "credential-1",+ KeyPrefix: "osb_aaaa",+ Name: "oc CLI on test",+ APIURL: server.URL,+ },+ }); err != nil {+ t.Fatal(err)+ }+ if err := runLogin(cmd, false, false); err != nil {+ t.Fatalf("runLogin: %v", err)+ }+ if starts != 0 {+ t.Fatalf("started %d new authorizations", starts)+ }+ if !strings.Contains(stdout.String(), "Already logged in as [email protected]") {+ t.Fatalf("stdout = %q", stdout.String())+ }+}++func TestLoginForceNeverRevokesManualFileKey(t *testing.T) {+ var revokes int+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/auth/cli/device":+ writeJSONResponse(w, 200, deviceReceipt())+ case "/auth/cli/device/exchange":+ writeJSONResponse(w, 200, authorizedExchange())+ case "/api/whoami":+ writeJSONResponse(w, 200, whoamiResponse())+ case "/auth/cli/credential":+ revokes+++ w.WriteHeader(http.StatusNoContent)+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()+ cmd, _, _ := authTestCommand(t, server.URL)+ if err := config.Save(config.Config{APIURL: server.URL, APIKey: oldTestKey}); err != nil {+ t.Fatal(err)+ }+ if err := runLogin(cmd, true, true); err != nil {+ t.Fatalf("runLogin --force: %v", err)+ }+ if revokes != 0 {+ t.Fatalf("manual key was remotely revoked %d time(s)", revokes)+ }+}++func TestLogoutAmbiguousFailureRetainsLocalCredential(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ writeJSONResponse(w, 503, map[string]string{"error": "credential_revocation_unavailable"})+ }))+ defer server.Close()+ cmd, _, _ := authTestCommand(t, server.URL)+ if err := config.Save(config.Config{+ APIURL: server.URL,+ APIKey: testKey,+ Login: &config.LoginMetadata{+ CredentialID: "credential-1",+ KeyPrefix: "osb_aaaa",+ Name: "oc CLI on test",+ APIURL: server.URL,+ },+ }); err != nil {+ t.Fatal(err)+ }+ err := runLogout(cmd, false)+ if err == nil || !strings.Contains(err.Error(), "local login was retained") {+ t.Fatalf("error = %v", err)+ }+ if got := config.LoadFile(); got.APIKey != testKey || got.Login == nil {+ t.Fatalf("credential was cleared after ambiguous revoke: %#v", got)+ }+}++func TestLogoutRevokesAndClearsManagedCredential(t *testing.T) {+ var revoked string+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ revoked = r.Header.Get("X-API-Key")+ w.WriteHeader(http.StatusNoContent)+ }))+ defer server.Close()+ cmd, stdout, _ := authTestCommand(t, server.URL)+ if err := config.Save(config.Config{+ APIURL: server.URL,+ APIKey: testKey,+ Login: &config.LoginMetadata{+ CredentialID: "credential-1",+ KeyPrefix: "osb_aaaa",+ Name: "oc CLI on test",+ APIURL: server.URL,+ },+ }); err != nil {+ t.Fatal(err)+ }+ if err := runLogout(cmd, false); err != nil {+ t.Fatalf("runLogout: %v", err)+ }+ if revoked != testKey {+ t.Fatalf("revoked key = %q", revoked)+ }+ if got := config.LoadFile(); got.APIKey != "" || got.Login != nil {+ t.Fatalf("credential remains after logout: %#v", got)+ }+ if strings.TrimSpace(stdout.String()) != "Logged out." {+ t.Fatalf("stdout = %q", stdout.String())+ }+}++func TestLogoutLocalDoesNotCallRemote(t *testing.T) {+ var calls int+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ calls+++ http.Error(w, "unexpected", 500)+ }))+ defer server.Close()+ cmd, _, _ := authTestCommand(t, server.URL)+ if err := config.Save(config.Config{+ APIURL: server.URL,+ APIKey: testKey,+ Login: &config.LoginMetadata{+ CredentialID: "credential-1",+ KeyPrefix: "osb_aaaa",+ Name: "oc CLI on test",+ APIURL: server.URL,+ },+ }); err != nil {+ t.Fatal(err)+ }+ if err := runLogout(cmd, true); err != nil {+ t.Fatalf("runLogout --local: %v", err)+ }+ if calls != 0 {+ t.Fatalf("remote called %d times", calls)+ }+ if got := config.LoadFile(); got.APIKey != "" || got.Login != nil {+ t.Fatalf("local login remains: %#v", got)+ }+}++func TestLoginCancellationDoesNotSaveCredential(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/auth/cli/device" {+ t.Fatalf("unexpected path after cancellation: %s", r.URL.Path)+ }+ writeJSONResponse(w, 200, deviceReceipt())+ }))+ defer server.Close()+ cmd, _, _ := authTestCommand(t, server.URL)+ authSleep = func(context.Context, time.Duration) error { return context.Canceled }+ err := runLogin(cmd, false, true)+ if !errors.Is(err, context.Canceled) {+ t.Fatalf("error = %v, want context.Canceled", err)+ }+ if _, err := os.Stat(filepath.Join(os.Getenv("HOME"), ".oc", "config.json")); !os.IsNotExist(err) {+ t.Fatalf("config unexpectedly created: %v", err)+ }+}++func TestLoginRetriesTransientExchangeTwiceThenLeavesConfigUntouched(t *testing.T) {+ var exchanges int+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/auth/cli/device":+ writeJSONResponse(w, 200, deviceReceipt())+ case "/auth/cli/device/exchange":+ exchanges+++ writeJSONResponse(w, 503, map[string]string{"error": "auth_provider_unavailable"})+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()+ cmd, _, _ := authTestCommand(t, server.URL)+ err := runLogin(cmd, false, true)+ if err == nil || !strings.Contains(err.Error(), "auth_provider_unavailable") {+ t.Fatalf("error = %v", err)+ }+ if exchanges != 3 {+ t.Fatalf("exchange attempts = %d, want 3", exchanges)+ }+ if got := config.LoadFile(); got.APIKey != "" || got.Login != nil {+ t.Fatalf("transient failure mutated config: %#v", got)+ }+}++func TestLoginDoesNotRetryPostAuthorizationCredentialFailure(t *testing.T) {+ var exchanges int+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/auth/cli/device":+ writeJSONResponse(w, 200, deviceReceipt())+ case "/auth/cli/device/exchange":+ exchanges+++ writeJSONResponse(w, 503, map[string]string{"error": "credential_creation_failed"})+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()+ cmd, _, _ := authTestCommand(t, server.URL)+ err := runLogin(cmd, false, true)+ if err == nil || !strings.Contains(err.Error(), "run `oc login` again") {+ t.Fatalf("error = %v", err)+ }+ if exchanges != 1 {+ t.Fatalf("exchange attempts = %d, want 1 for a consumed device grant", exchanges)+ }+ if got := config.LoadFile(); got.APIKey != "" || got.Login != nil {+ t.Fatalf("credential failure mutated config: %#v", got)+ }+}++func TestWhoamiJSONIsStable(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Header.Get("X-API-Key") != testKey {+ t.Errorf("key = %q", r.Header.Get("X-API-Key"))+ }+ writeJSONResponse(w, 200, whoamiResponse())+ }))+ defer server.Close()+ cmd, stdout, _ := authTestCommand(t, server.URL)+ t.Setenv("OPENCOMPUTER_API_KEY", testKey)+ jsonOutput = true+ if err := runWhoami(cmd); err != nil {+ t.Fatalf("runWhoami: %v", err)+ }+ var got map[string]any+ if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {+ t.Fatal(err)+ }+ want := fmt.Sprintf(+ `{"api_url":%q,"email":"[email protected]","org_id":"org-1","org_name":"Igor's workspace","user_id":"user-1"}`,+ server.URL,+ )+ encoded, _ := json.Marshal(got)+ var wantMap map[string]any+ _ = json.Unmarshal([]byte(want), &wantMap)+ wantEncoded, _ := json.Marshal(wantMap)+ if string(encoded) != string(wantEncoded) {+ t.Fatalf("whoami JSON = %s, want %s", encoded, wantEncoded)+ }+}++func TestAuthClientNeverFollowsRedirectsWithCredentials(t *testing.T) {+ var destinationCalls int+ destination := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ destinationCalls+++ if r.Header.Get("X-API-Key") != "" {+ t.Errorf("redirect leaked key %q", r.Header.Get("X-API-Key"))+ }+ writeJSONResponse(w, 200, whoamiResponse())+ }))+ defer destination.Close()+ redirector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ http.Redirect(w, r, destination.URL+r.URL.Path, http.StatusFound)+ }))+ defer redirector.Close()++ _, err := newCLIAuthHTTP(redirector.URL).whoami(context.Background(), testKey)+ if err == nil {+ t.Fatal("redirecting auth endpoint unexpectedly succeeded")+ }+ if destinationCalls != 0 {+ t.Fatalf("redirect destination called %d times", destinationCalls)+ }+}++func TestConfigSetAPIKeyClearsLoginManagementMetadata(t *testing.T) {+ cmd, _, _ := authTestCommand(t, "https://example.test")+ if err := config.Save(config.Config{+ APIURL: "https://example.test",+ APIKey: oldTestKey,+ Login: &config.LoginMetadata{+ CredentialID: "old-id",+ KeyPrefix: "osb_bbbb",+ Name: "oc CLI on old",+ APIURL: "https://example.test",+ },+ }); err != nil {+ t.Fatal(err)+ }+ if err := configSetCmd.RunE(cmd, []string{"api-key", testKey}); err != nil {+ t.Fatalf("config set api-key: %v", err)+ }+ got := config.LoadFile()+ if got.APIKey != testKey || got.Login != nil {+ t.Fatalf("config set left login-managed state: %#v", got)+ }+}diff --git a/cmd/oc/internal/commands/config_cmd.go b/cmd/oc/internal/commands/config_cmd.goindex 6f77d34b..98401845 100644--- a/cmd/oc/internal/commands/config_cmd.go+++ b/cmd/oc/internal/commands/config_cmd.go@@ -21,11 +21,12 @@ var configSetCmd = &cobra.Command{api-url API base URL`,Args: cobra.ExactArgs(2),RunE: func(cmd *cobra.Command, args []string) error {- cfg := config.Load(nil)+ cfg := config.LoadFile()switch args[0] {case "api-key":cfg.APIKey = args[1]+ cfg.Login = nilcase "api-url":cfg.APIURL = args[1]default:diff --git a/cmd/oc/internal/commands/root.go b/cmd/oc/internal/commands/root.goindex 296fe287..1a8db987 100644--- a/cmd/oc/internal/commands/root.go+++ b/cmd/oc/internal/commands/root.go@@ -26,8 +26,8 @@ var rootCmd = &cobra.Command{Version: Version,PersistentPreRunE: func(cmd *cobra.Command, args []string) error {cfg := config.Load(cmd)- if cfg.APIKey == "" && !isOfflineCommand(cmd) && cmd.Name() != "config" && cmd.Name() != "help" && cmd.Name() != "set" && cmd.Name() != "show" {- fmt.Fprintln(os.Stderr, "Warning: no API key configured. Set OPENCOMPUTER_API_KEY or run 'oc config set api-key <key>'")+ if cfg.APIKey == "" && !isOfflineCommand(cmd) && cmd.Name() != "login" && cmd.Name() != "logout" && cmd.Name() != "whoami" && cmd.Name() != "config" && cmd.Name() != "help" && cmd.Name() != "set" && cmd.Name() != "show" {+ fmt.Fprintln(os.Stderr, "Warning: no API key configured. Run 'oc login' or set OPENCOMPUTER_API_KEY")}c := client.New(cfg.APIURL, cfg.APIKey)ctx := client.WithClient(cmd.Context(), c)@@ -49,7 +49,7 @@ var rootCmd = &cobra.Command{// maybePromptUpdate for the full skip list (dev build, non-TTY,// OC_NO_UPDATE_CHECK).switch cmd.Name() {- case "update", "help", "completion", "__complete":+ case "login", "update", "help", "completion", "__complete":return}maybePromptUpdate()@@ -83,6 +83,9 @@ func init() {rootCmd.AddCommand(configCmd)rootCmd.AddCommand(agentCmd)rootCmd.AddCommand(logsCmd)+ rootCmd.AddCommand(loginCmd)+ rootCmd.AddCommand(whoamiCmd)+ rootCmd.AddCommand(logoutCmd)// Top-level shortcutsrootCmd.AddCommand(createShortcut)diff --git a/cmd/oc/internal/config/config.go b/cmd/oc/internal/config/config.goindex 011233b0..e0bf717d 100644--- a/cmd/oc/internal/config/config.go+++ b/cmd/oc/internal/config/config.go@@ -2,6 +2,7 @@ package configimport ("encoding/json"+ "fmt""os""path/filepath"@@ -15,16 +16,33 @@ const (configFile = "config.json")+type LoginMetadata struct {+ CredentialID string `json:"credential_id"`+ KeyPrefix string `json:"key_prefix"`+ Name string `json:"name"`+ APIURL string `json:"api_url"`+}+// Config holds the resolved CLI configuration.type Config struct {- APIURL string `json:"api_url,omitempty"`- APIKey string `json:"api_key,omitempty"`- SessionsAPIURL string `json:"sessions_api_url,omitempty"`+ APIURL string `json:"api_url,omitempty"`+ APIKey string `json:"api_key,omitempty"`+ SessionsAPIURL string `json:"sessions_api_url,omitempty"`+ Login *LoginMetadata `json:"login,omitempty"`}+type CredentialSource string++const (+ CredentialSourceNone CredentialSource = ""+ CredentialSourceFile CredentialSource = "config file"+ CredentialSourceEnvironment CredentialSource = "OPENCOMPUTER_API_KEY"+ CredentialSourceFlag CredentialSource = "--api-key"+)+// Load resolves configuration from flags > env > config file > defaults.func Load(cmd *cobra.Command) Config {- cfg := loadFile()+ cfg := LoadFile()// Apply defaultsif cfg.APIURL == "" {@@ -61,13 +79,33 @@ func Load(cmd *cobra.Command) Config {return cfg}+// EffectiveCredentialSource reports which layer currently controls API-key+// authentication. Login uses it to avoid claiming it replaced an env/flag+// override when the saved file would remain ineffective.+func EffectiveCredentialSource(cmd *cobra.Command) CredentialSource {+ if cmd != nil {+ if v, _ := cmd.Flags().GetString("api-key"); v != "" {+ return CredentialSourceFlag+ }+ }+ if os.Getenv("OPENCOMPUTER_API_KEY") != "" {+ return CredentialSourceEnvironment+ }+ if LoadFile().APIKey != "" {+ return CredentialSourceFile+ }+ return CredentialSourceNone+}+// ConfigPath returns the path to the config file.func ConfigPath() string {home, _ := os.UserHomeDir()return filepath.Join(home, configDir, configFile)}-func loadFile() Config {+// LoadFile reads only the persisted configuration, without defaults, env, or+// flag overrides.+func LoadFile() Config {var cfg Configdata, err := os.ReadFile(ConfigPath())if err != nil {@@ -77,15 +115,44 @@ func loadFile() Config {return cfg}-// Save writes the config to disk.+// Save atomically replaces the config with mode 0600 in a mode-0700 directory.func Save(cfg Config) error {dir := filepath.Dir(ConfigPath())if err := os.MkdirAll(dir, 0700); err != nil {return err}+ if err := os.Chmod(dir, 0700); err != nil {+ return err+ }data, err := json.MarshalIndent(cfg, "", " ")if err != nil {return err}- return os.WriteFile(ConfigPath(), data, 0600)+ data = append(data, '\n')++ tmp, err := os.CreateTemp(dir, ".config-*.tmp")+ if err != nil {+ return err+ }+ tmpPath := tmp.Name()+ defer os.Remove(tmpPath)+ if err := tmp.Chmod(0600); err != nil {+ tmp.Close()+ return err+ }+ if _, err := tmp.Write(data); err != nil {+ tmp.Close()+ return err+ }+ if err := tmp.Sync(); err != nil {+ tmp.Close()+ return err+ }+ if err := tmp.Close(); err != nil {+ return err+ }+ if err := os.Rename(tmpPath, ConfigPath()); err != nil {+ return fmt.Errorf("replace config: %w", err)+ }+ return nil}diff --git a/cmd/oc/internal/config/config_test.go b/cmd/oc/internal/config/config_test.gonew file mode 100644index 00000000..8bf74d77--- /dev/null+++ b/cmd/oc/internal/config/config_test.go@@ -0,0 +1,81 @@+package config++import (+ "os"+ "path/filepath"+ "runtime"+ "testing"+)++func useTemporaryHome(t *testing.T) string {+ t.Helper()+ home := t.TempDir()+ t.Setenv("HOME", home)+ if runtime.GOOS == "windows" {+ t.Setenv("USERPROFILE", home)+ }+ return home+}++func TestSaveIsPrivateAndRoundTripsLoginMetadata(t *testing.T) {+ home := useTemporaryHome(t)+ want := Config{+ APIURL: "https://example.test",+ APIKey: "osb_secret",+ Login: &LoginMetadata{+ CredentialID: "key-1",+ KeyPrefix: "osb_abcd",+ Name: "oc CLI on test",+ APIURL: "https://example.test",+ },+ }+ if err := Save(want); err != nil {+ t.Fatalf("Save: %v", err)+ }+ got := LoadFile()+ if got.APIKey != want.APIKey || got.Login == nil || got.Login.CredentialID != "key-1" {+ t.Fatalf("LoadFile() = %#v, want %#v", got, want)+ }++ if runtime.GOOS != "windows" {+ dirInfo, err := os.Stat(filepath.Join(home, ".oc"))+ if err != nil {+ t.Fatal(err)+ }+ if got := dirInfo.Mode().Perm(); got != 0o700 {+ t.Fatalf("config dir mode = %o, want 700", got)+ }+ fileInfo, err := os.Stat(ConfigPath())+ if err != nil {+ t.Fatal(err)+ }+ if got := fileInfo.Mode().Perm(); got != 0o600 {+ t.Fatalf("config mode = %o, want 600", got)+ }+ }++ matches, err := filepath.Glob(filepath.Join(home, ".oc", ".config-*.tmp"))+ if err != nil {+ t.Fatal(err)+ }+ if len(matches) != 0 {+ t.Fatalf("temporary config files left behind: %v", matches)+ }+}++func TestEffectiveCredentialSourcePrecedence(t *testing.T) {+ useTemporaryHome(t)+ if got := EffectiveCredentialSource(nil); got != CredentialSourceNone {+ t.Fatalf("empty source = %q", got)+ }+ if err := Save(Config{APIKey: "file"}); err != nil {+ t.Fatal(err)+ }+ if got := EffectiveCredentialSource(nil); got != CredentialSourceFile {+ t.Fatalf("file source = %q", got)+ }+ t.Setenv("OPENCOMPUTER_API_KEY", "environment")+ if got := EffectiveCredentialSource(nil); got != CredentialSourceEnvironment {+ t.Fatalf("env source = %q", got)+ }+}diff --git a/docs/cli/overview.mdx b/docs/cli/overview.mdxindex db3439a6..98ba37b1 100644--- a/docs/cli/overview.mdx+++ b/docs/cli/overview.mdx@@ -31,22 +31,44 @@ chmod +x /usr/local/bin/oc</CodeGroup>-## Configuration+## Sign in```bash-oc config set api-key your-api-key-oc config show+oc login+oc whoami+```++`oc login` prints a short confirmation code and opens the hosted sign-in page.+Use `oc login --no-browser` over SSH or when a coding agent is running the+command for you. The CLI stores the resulting credential in+`~/.oc/config.json` with private file permissions; it never prints the key.++```bash+oc logout # revoke the CLI-created key, then clear it locally+oc logout --local # clear local login state without claiming remote revocation```-### Resolution Order+`oc login` authenticates the local CLI. CI, servers, and SDK applications+should continue to receive an explicit org key through their secret manager and+`OPENCOMPUTER_API_KEY`.++### Credential resolution| Priority | Source | Example || --- | --- | --- || 1 (highest) | CLI flags | `--api-key=xxx` || 2 | Environment variables | `OPENCOMPUTER_API_KEY` |-| 3 | Config file | `~/.oc/config.json` |+| 3 | Config file | `oc login` or `oc config set api-key …` || 4 (lowest) | Defaults | `https://app.opencomputer.dev` |+An active `--api-key` or `OPENCOMPUTER_API_KEY` override must be removed before+`oc login` or `oc logout`. Manually setting an API key remains supported:++```bash+oc config set api-key "$OPENCOMPUTER_API_KEY"+oc config show+```+## Global Flags| Flag | Environment Variable | Description |@@ -133,6 +155,7 @@ oc exec $ID2 --wait -- ./test-b.sh| [`oc patch`](/cli/patch) | Checkpoint-attached scripts || [`oc preview`](/cli/preview) | Expose ports to the internet || [`oc agent`](/reference/cli/agent) | Invoke durable agents and manage Hook URLs |+| [`oc login`](/reference/cli/auth) | Sign in, inspect identity, and log out || [`oc config`](/reference/cli#oc-config) | Configure API key and API URL |<Tip>diff --git a/docs/docs.json b/docs/docs.jsonindex b5d902c8..0cd7fb39 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -191,6 +191,7 @@"reference/cli/patch","reference/cli/preview","reference/cli/agent",+ "reference/cli/auth","reference/cli/config"]},diff --git a/docs/guides/agent-skill.mdx b/docs/guides/agent-skill.mdxindex 10fb1cd0..195dda06 100644--- a/docs/guides/agent-skill.mdx+++ b/docs/guides/agent-skill.mdx@@ -19,9 +19,13 @@ The `oc` CLI must be installed and configured:```bashcurl -fsSL https://raw.githubusercontent.com/diggerhq/opencomputer/main/scripts/install.sh | bash-oc config set api-key YOUR_API_KEY+oc login```+If the command prints a browser URL or confirmation code, relay it to the user+and wait for them to approve it. The CLI resumes without asking anyone to paste+an API key into chat.+## UsageThe skill activates automatically when you mention sandboxes or the `oc` CLI. Just ask naturally:diff --git a/docs/reference/cli.mdx b/docs/reference/cli.mdxindex 7269d3b6..a7657ed1 100644--- a/docs/reference/cli.mdx+++ b/docs/reference/cli.mdx@@ -15,6 +15,26 @@ These flags apply to all commands.---+## `oc login`, `oc whoami`, and `oc logout`++```bash+oc login+oc whoami+oc logout+```++`oc login` uses browser-assisted device confirmation and saves a private local+CLI credential without printing it. Use `--no-browser` over SSH, and `--force`+to replace a saved credential. `oc whoami` prints the effective user and+workspace. `oc logout` revokes a CLI-managed key before clearing it locally;+`--local` skips remote revocation explicitly.++An active `--api-key` or `OPENCOMPUTER_API_KEY` override takes precedence and+must be unset before login or logout. CI, servers, and SDK applications should+continue to use explicitly managed org keys.++---+## `oc sandbox`Manage sandbox lifecycle.@@ -238,6 +258,7 @@ Output columns: `PORT`, `HOSTNAME`, `SSL`, `CREATED`## `oc config`Manage CLI configuration. Settings are persisted to a local config file.+For a local interactive setup, prefer `oc login`.### `oc config set <key> <value>`@@ -248,6 +269,9 @@ oc config set api-key sk-1234...oc config set api-url https://app.opencomputer.dev```+Setting `api-key` clears CLI-login management metadata; `oc logout` will not+remotely revoke a manually supplied key.+### `oc config show`Display current configuration. The API key is masked (first 4 and last 4 characters shown).diff --git a/docs/reference/cli/auth.mdx b/docs/reference/cli/auth.mdxnew file mode 100644index 00000000..4a0229d8--- /dev/null+++ b/docs/reference/cli/auth.mdx@@ -0,0 +1,54 @@+---+title: "Login and identity"+description: "Sign the local CLI in to OpenComputer"+---++## `oc login`++```bash+oc login [--no-browser] [--force]+```++The CLI prints a short confirmation code and a complete HTTPS sign-in URL,+then waits for approval. It tries to open the URL on a local machine; browser+failure does not stop the flow.++- `--no-browser` only prints the URL, which is useful over SSH or when a coding+ agent is running the command.+- `--force` replaces an existing saved credential. A prior CLI-created key is+ revoked only after the replacement is saved and verified. A manually+ configured key is replaced locally but never remotely revoked.++The credential is stored in `~/.oc/config.json` with private permissions and is+never printed, including under `--json`. If `--api-key` or+`OPENCOMPUTER_API_KEY` is active, unset that override before logging in.++`oc login` is for a person's local CLI. CI, servers, and SDK applications+should keep using an explicit org API key supplied through their secret+manager.++## `oc whoami`++```bash+oc whoami+oc whoami --json+```++Shows the authenticated user, workspace, org id, and API URL for the effective+credential.++## `oc logout`++```bash+oc logout+oc logout --local+```++For a CLI-managed login, `oc logout` first revokes that exact key and only then+clears it from the config file. If remote revocation is ambiguous, the local+credential is retained and the command fails so it cannot claim a still-live+key was revoked.++`--local` explicitly clears local login state without remote revocation.+Manually configured and environment-provided keys are never remotely revoked+by this command.diff --git a/docs/reference/cli/config.mdx b/docs/reference/cli/config.mdxindex 10127020..6023b877 100644--- a/docs/reference/cli/config.mdx+++ b/docs/reference/cli/config.mdx@@ -5,6 +5,9 @@ description: "CLI configuration"Manage CLI configuration. Settings are persisted to a local config file.+For an interactive local setup, prefer [`oc login`](/reference/cli/auth). Use+`oc config set api-key` for a separately managed key.+## `oc config set <key> <value>`Supported keys: `api-key`, `api-url`.@@ -14,6 +17,9 @@ oc config set api-key sk-1234...oc config set api-url https://app.opencomputer.dev```+Setting `api-key` explicitly clears CLI-login management metadata, so a later+`oc logout` cannot revoke a manually supplied key.+---## `oc config show`diff --git a/docs/reference/cli/overview.mdx b/docs/reference/cli/overview.mdxindex 0e40f6d2..5cbfeb7c 100644--- a/docs/reference/cli/overview.mdx+++ b/docs/reference/cli/overview.mdx@@ -43,6 +43,9 @@ These flags apply to all commands.<Card title="oc agent" icon="robot" href="/reference/cli/agent">Invoke agents and manage Hook URLs</Card>+ <Card title="oc login" icon="right-to-bracket" href="/reference/cli/auth">+ Sign in, inspect identity, and log out+ </Card><Card title="oc config" icon="gear" href="/reference/cli/config">CLI configuration</Card>diff --git a/skills/opencomputer/README.md b/skills/opencomputer/README.mdindex 1a86d96e..1c4510de 100644--- a/skills/opencomputer/README.md+++ b/skills/opencomputer/README.md@@ -43,13 +43,15 @@ curl -fsSL https://github.com/diggerhq/opencomputer/releases/latest/download/oc-chmod +x /usr/local/bin/oc```-Then configure your API key:+Then sign in:```bash-oc config set api-key YOUR_API_KEY+oc login```-Get your API key at [app.opencomputer.dev](https://app.opencomputer.dev).+The command opens a hosted confirmation page and saves the CLI credential+without printing it. CI and services can continue to use+`OPENCOMPUTER_API_KEY`.## Example usagediff --git a/skills/opencomputer/SKILL.md b/skills/opencomputer/SKILL.mdindex 57665b82..3fe2fb79 100644--- a/skills/opencomputer/SKILL.md+++ b/skills/opencomputer/SKILL.md@@ -26,29 +26,28 @@ curl -fsSL https://raw.githubusercontent.com/diggerhq/opencomputer/main/scripts/This installs `oc` to `~/.local/bin/oc`. If `~/.local/bin` is not on the user's PATH, tell them to add `export PATH="$HOME/.local/bin:$PATH"` to their shell rc file, and use the full path `~/.local/bin/oc` for the rest of this session.-### 2. Is the user logged in (API key configured)?+### 2. Is the user logged in?```bash-oc config show+oc whoami```-If `API Key` is shown (even masked) → logged in, you're done.+If it succeeds → logged in, you're done.-If no API key is set, OR a sandbox command fails with an auth error (`401`, "unauthorized", "missing API key"):+If it fails because no credential is configured, OR a sandbox command fails+with an auth error (`401`, "unauthorized", "missing API key"):-1. Open the OpenComputer dashboard in the user's browser so they can create a key:- - macOS: `open https://app.opencomputer.dev`- - Linux: `xdg-open https://app.opencomputer.dev`-2. Tell the user (in chat) to:- - Sign in / sign up at the page that just opened- - Create an API key- - Run this command in their terminal once they have the key:- ```bash- oc config set api-key YOUR_API_KEY- ```-3. Wait for the user to confirm they've set the key before proceeding.+1. Run:+ ```bash+ oc login+ ```+2. Relay the complete browser URL and short confirmation code printed by the+ command to the user.+3. Leave the command running while the user approves it in their browser. It+ resumes automatically after approval.-Do **not** prompt them for the key in the chat — they should paste it into their own terminal so it never leaves their machine.+Do **not** ask for an API key in chat. For CI or service automation, the user+may instead configure `OPENCOMPUTER_API_KEY` themselves.## CLI Reference