diff --git a/extensions/cli/src/auth/workos.orgScope.test.ts b/extensions/cli/src/auth/workos.orgScope.test.ts new file mode 100644 index 000000000..7367a3024 --- /dev/null +++ b/extensions/cli/src/auth/workos.orgScope.test.ts @@ -0,0 +1,58 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; + +import { ensureOrganization, isEnvironmentAuthConfig } from "./workos.js"; + +describe("ensureOrganization with API key org scope", () => { + const originalEnv = { ...process.env }; + const originalFetch = global.fetch; + + beforeEach(() => { + vi.restoreAllMocks(); + }); + + afterEach(() => { + process.env = { ...originalEnv }; + global.fetch = originalFetch as any; + }); + + it("resolves organizationId via auth/scope for API key auth", async () => { + const mockFetch = vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ organizationId: "org_123" }), + }); + (global as any).fetch = mockFetch; + + const envAuthConfig = { + accessToken: "sk_test_api_key", + organizationId: null as string | null, + } as const; + + const result = await ensureOrganization(envAuthConfig, true); + expect(result).not.toBeNull(); + if (result && isEnvironmentAuthConfig(result)) { + expect(result.organizationId).toBe("org_123"); + } else { + throw new Error("Expected environment auth config result"); + } + expect(mockFetch).toHaveBeenCalledOnce(); + }); + + it("keeps organizationId null if endpoint not available", async () => { + const mockFetch = vi.fn().mockResolvedValue({ ok: false }); + (global as any).fetch = mockFetch; + + const envAuthConfig = { + accessToken: "sk_test_api_key", + organizationId: null as string | null, + } as const; + + const result = await ensureOrganization(envAuthConfig, true); + expect(result).not.toBeNull(); + if (result && isEnvironmentAuthConfig(result)) { + expect(result.organizationId).toBeNull(); + } else { + throw new Error("Expected environment auth config result"); + } + expect(mockFetch).toHaveBeenCalledOnce(); + }); +}); diff --git a/extensions/cli/src/auth/workos.ts b/extensions/cli/src/auth/workos.ts index 8ae14c25f..a775ee670 100644 --- a/extensions/cli/src/auth/workos.ts +++ b/extensions/cli/src/auth/workos.ts @@ -540,8 +540,10 @@ export async function ensureOrganization( ); } } else if (isEnvironmentAuthConfig(authConfig)) { - // No CLI organization slug (or "personal" was specified) - return as-is - return authConfig; + // No CLI organization slug (or "personal" was specified) + // If using API key auth, attempt to resolve its organization scope once + const resolved = await resolveOrgScopeForApiKey(authConfig); + return resolved; } // If not authenticated, return as-is @@ -577,6 +579,59 @@ export async function ensureOrganization( return autoSelectOrganization(authenticatedConfig); } +/** + * Attempts to resolve the organization scope for API key auth (environment-based auth). + * Calls a lightweight backend endpoint to determine if the API key is an org-scoped key. + * If successful, returns a new EnvironmentAuthConfig with organizationId set; otherwise returns the original config. + */ +async function resolveOrgScopeForApiKey( + envConfig: EnvironmentAuthConfig, +): Promise { + // If already set (including explicit null), return as-is + if (envConfig.organizationId !== null) { + return envConfig; + } + + const accessToken = envConfig.accessToken; + if (!accessToken) return envConfig; + + try { + // Prefer a dedicated endpoint for scope discovery. This should return JSON like: + // { organizationId: string | null } (aka orgScopeId) + const url = new URL("auth/scope", env.apiBase); + const resp = await fetch(url, { + method: "GET", + headers: { + Authorization: `Bearer ${accessToken}`, + "Content-Type": "application/json", + }, + }); + + if (!resp.ok) { + // Gracefully ignore if the endpoint isn't available yet (e.g., 404) or other non-2xx errors + return envConfig; + } + + const data: any = await resp.json().catch(() => ({})); + const orgId = + data?.organizationId ?? + data?.orgScopeId ?? + data?.organization?.id ?? + null; + + if (orgId && typeof orgId === "string") { + return { + ...envConfig, + organizationId: orgId, + }; + } + } catch { + // Network or parsing issues: leave config unchanged + } + + return envConfig; +} + /** * Gets the list of available organizations for the user */