diff --git a/doc/connections/AI-CONNECTIONS.md b/doc/connections/AI-CONNECTIONS.md index a2ac0701191..35c4dd470eb 100644 --- a/doc/connections/AI-CONNECTIONS.md +++ b/doc/connections/AI-CONNECTIONS.md @@ -164,11 +164,22 @@ denying profile access; in that case the screen explains that Anthropic did not permit reading the account email. A profile denial does not mark a connected credential as disconnected. +OpenAI subscription connections also show the selected **ChatGPT workspace**. +The lookup uses OpenAI's Codex accounts endpoint and matches the workspace ID +saved with that connection. It does not select the first or default workspace, +or infer a workspace from an email or Paperclip access. A personal workspace +without a provider name shows **Personal workspace** only when OpenAI reports +its type. Missing names, ambiguous matches, and denied lookups show an unavailable +state while keeping the saved email and connection controls. API keys and routed +connections do not use this lookup. +The endpoint and response formats follow OpenAI's [Codex backend client](https://github.com/openai/codex/blob/58627e6feac9f69cbbb405d85f4f7343eca75a35/codex-rs/backend-client/src/client.rs#L525) +and [account response types](https://github.com/openai/codex/blob/58627e6feac9f69cbbb405d85f4f7343eca75a35/codex-rs/backend-client/src/types.rs#L130). + `GET /api/companies/:companyId/ai-connections/:connectionId/identity?grantId=...` checks company membership, connection-management authority, and the selected credential's human audience before opening the credential. The response contains -only safe account labels and bounded status messages. The Anthropic profile read -has a 15-second headers/body deadline and no redirects. It runs separately from +only safe account labels and bounded status messages. The provider profile reads +have a 15-second headers/body deadline and no redirects. Each runs separately from the account/grants reads, so profile loading or failure cannot block account maintenance. The UI reuses an observation for five minutes, scoped to the company, connection, grant, and grant update time. Reconnect requires a new observation. diff --git a/server/src/__tests__/ai-connections.test.ts b/server/src/__tests__/ai-connections.test.ts index 3bb34223966..b914c4b75ac 100644 --- a/server/src/__tests__/ai-connections.test.ts +++ b/server/src/__tests__/ai-connections.test.ts @@ -1556,11 +1556,14 @@ console.log(JSON.stringify({ type: "result", subtype: "success", result: "hello" } finally { fetchSpy.mockRestore(); } }); - it("reads provider identity only for an authorized credential and preserves connected state when profile access is denied", async () => { - const owner = "identity-owner"; + it.each(["anthropic", "openai"] as const)("reads %s identity only for an authorized credential and preserves connected state when profile access is denied", async provider => { + const owner = `identity-owner-${provider}`; await db.insert(companyMemberships).values({ companyId, principalId: owner, principalType: "user", status: "active", membershipRole: "member" }); - const account = await service.save(companyId, owner, { provider: "anthropic", method: "subscription", ownership: "personal", name: "Identity account", loginSessionId: "fixture", agentIds: [], allAgents: true }, "identity-selected-secret"); - const fetchSpy = vi.spyOn(globalThis, "fetch").mockResolvedValue(Response.json({ account: { email: "avery@example.test", uuid: "private-account-id" }, organization: { name: "Example team", uuid: "private-org-id" } })); + const credential = provider === "openai" ? JSON.stringify({ tokens: { access_token: "identity-selected-secret", account_id: "private-account-id" } }) : "identity-selected-secret"; + const account = await service.save(companyId, owner, { provider, method: "subscription", ownership: "personal", name: "Identity account", loginSessionId: "fixture", agentIds: [], allAgents: true }, credential); + const profile = provider === "openai" ? { accounts: [{ id: "private-account-id", name: "Example team", structure: "workspace" }] } + : { account: { email: "avery@example.test", uuid: "private-account-id" }, organization: { name: "Example team", uuid: "private-org-id" } }; + const fetchSpy = vi.spyOn(globalThis, "fetch").mockResolvedValue(Response.json(profile)); const app = express(); app.use((req, _res, next) => { req.actor = req.header("x-test-anonymous") ? { type: "none" } @@ -1575,8 +1578,8 @@ console.log(JSON.stringify({ type: "result", subtype: "success", result: "hello" const result = await request(app).get(url); expect(result.status).toBe(200); expect(result.headers["cache-control"]).toBe("no-store"); - expect(result.body).toMatchObject({ ...account, status: "available", accountLabel: "avery@example.test", organizationLabel: "Example team" }); - expect(fetchSpy).toHaveBeenCalledWith("https://api.anthropic.com/api/oauth/profile", expect.objectContaining({ headers: expect.objectContaining({ Authorization: "Bearer identity-selected-secret" }) })); + expect(result.body).toMatchObject({ ...account, status: "available", accountLabel: provider === "openai" ? null : "avery@example.test", organizationLabel: "Example team" }); + expect(fetchSpy).toHaveBeenCalledWith(provider === "openai" ? "https://chatgpt.com/backend-api/wham/accounts/check" : "https://api.anthropic.com/api/oauth/profile", expect.objectContaining({ headers: expect.objectContaining({ Authorization: "Bearer identity-selected-secret" }) })); for (const value of ["identity-selected-secret", "private-account-id", "private-org-id"]) expect(JSON.stringify(result.body)).not.toContain(value); fetchSpy.mockReset(); expect((await request(app).get(url).set("x-test-user", "bob")).status).toBe(404); diff --git a/server/src/services/ai-account-identity.test.ts b/server/src/services/ai-account-identity.test.ts index eb8e67edd2a..0485988eb91 100644 --- a/server/src/services/ai-account-identity.test.ts +++ b/server/src/services/ai-account-identity.test.ts @@ -40,11 +40,71 @@ describe("AI account identity", () => { it("does not call a provider for API keys or other sign-in methods", async () => { const request = fixture({}); expect((await probeAiAccountIdentity({ provider: "anthropic", method: "api_key" }, "", request)).errorCode).toBe("unsupported"); - expect((await probeAiAccountIdentity({ provider: "openai", method: "subscription" }, "", request)).errorCode).toBe("unsupported"); + expect((await probeAiAccountIdentity({ provider: "google", method: "subscription" }, "", request)).errorCode).toBe("unsupported"); expect(request).not.toHaveBeenCalled(); }); - it("aborts a stalled real response body while unrelated requests remain responsive", async () => { + const openai = { provider: "openai", method: "subscription" } as const; + const openaiCredential = JSON.stringify({ tokens: { access_token: "selected-openai-bearer", account_id: "selected-workspace" } }); + + it("reads the selected OpenAI workspace rather than the default or first workspace", async () => { + const request = fixture({ default_account_id: "other-workspace", accounts: { + "other-workspace": { account: { account_id: "other-workspace", name: "Other team", structure: "workspace" } }, + "selected-workspace": { account: { account_id: "selected-workspace", name: "Example business", structure: "workspace", private_field: "private-provider-data" } }, + } }); + const result = await probeAiAccountIdentity(openai, openaiCredential, request); + expect(result).toMatchObject({ status: "available", organizationLabel: "Example business" }); + expect(request).toHaveBeenCalledWith("https://chatgpt.com/backend-api/wham/accounts/check", expect.objectContaining({ + redirect: "error", signal: expect.any(AbortSignal), + headers: { Authorization: "Bearer selected-openai-bearer", "ChatGPT-Account-Id": "selected-workspace" }, + })); + for (const value of ["selected-openai-bearer", "selected-workspace", "private-provider-data", "Other team"]) { + expect(JSON.stringify(result)).not.toContain(value); + } + }); + + it("supports the provider's list response and legacy saved credentials", async () => { + const result = await probeAiAccountIdentity(openai, JSON.stringify({ accessToken: "selected-openai-bearer", accountId: "selected-workspace" }), + fixture({ accounts: [{ id: "selected-workspace", name: "Example business", structure: "workspace" }] })); + expect(result).toMatchObject({ status: "available", organizationLabel: "Example business" }); + }); + + it("identifies a personal workspace when OpenAI supplies its type without a name", async () => { + expect(await probeAiAccountIdentity(openai, openaiCredential, fixture({ accounts: { + "selected-workspace": { account: { account_id: "selected-workspace", structure: "personal" } }, + } }))).toMatchObject({ status: "available", organizationLabel: "Personal workspace" }); + }); + + it.each([ + {}, + { accounts: [{ id: "other-workspace", name: "Other team" }] }, + { accounts: [{ id: "selected-workspace", name: "First" }, { id: "selected-workspace", name: "Second" }] }, + { accounts: { "selected-workspace": { account: { account_id: "other-workspace", name: "Wrong team" } } } }, + { accounts: [{ id: "selected-workspace", name: "Deactivated team", is_deactivated: true }] }, + { accounts: [{ id: "selected-workspace", name: "Unsafe\nname" }] }, + { accounts: [{ id: "selected-workspace", name: "x".repeat(255) }] }, + { accounts: [{ id: "selected-workspace", structure: "workspace" }] }, + ])("does not guess the OpenAI workspace from an incomplete or ambiguous response %j", async profile => { + expect(await probeAiAccountIdentity(openai, openaiCredential, fixture(profile))).toMatchObject({ + status: "unavailable", errorCode: "invalid_response", organizationLabel: null, + }); + }); + + it.each(["", "not-json", "{}", JSON.stringify({ tokens: { access_token: "bearer" } })])("does not make an unscoped OpenAI request for %s", async credential => { + const request = fixture({}); + expect(await probeAiAccountIdentity(openai, credential, request)).toMatchObject({ status: "unavailable", errorCode: "authentication_required" }); + expect(request).not.toHaveBeenCalled(); + }); + + it.each([401, 403, 429, 500])("reports OpenAI HTTP %s without leaking details or naming another provider", async status => { + const result = await probeAiAccountIdentity(openai, openaiCredential, fixture({ error: "private-provider-error" }, status)); + expect(result.status).toBe(status === 401 || status === 403 ? "unavailable" : "error"); + expect(result.organizationLabel).toBeNull(); + expect(result.message).not.toContain("Anthropic"); + expect(JSON.stringify(result)).not.toContain("private-provider-error"); + }); + + it.each([metadata, openai])("aborts a stalled $provider response body while unrelated requests remain responsive", async provider => { const server = createServer((req, res) => { if (req.url === "/profile") { res.writeHead(200, { "Content-Type": "application/json" }); res.flushHeaders(); } else res.end("responsive"); @@ -57,7 +117,7 @@ describe("AI account identity", () => { const timeout = AbortSignal.timeout.bind(AbortSignal); const deadline = vi.spyOn(AbortSignal, "timeout").mockImplementation(() => timeout(100)); try { - const pending = probeAiAccountIdentity(metadata, "selected-credential", (_url, init) => fetch(`${origin}/profile`, init)); + const pending = probeAiAccountIdentity(provider, provider.provider === "openai" ? openaiCredential : "selected-credential", (_url, init) => fetch(`${origin}/profile`, init)); expect(await (await fetch(`${origin}/unrelated`)).text()).toBe("responsive"); const result = await pending; expect(result.status).toBe("error"); diff --git a/server/src/services/ai-account-identity.ts b/server/src/services/ai-account-identity.ts index b93fb6da02c..36ddd45f41a 100644 --- a/server/src/services/ai-account-identity.ts +++ b/server/src/services/ai-account-identity.ts @@ -1,5 +1,6 @@ import type { AiConnectionAccountIdentity, AiConnectionMetadata } from "@paperclipai/shared"; import { readUsage } from "./ai-connection-usage.js"; +import { readOpenAiAccountIdentity } from "./openai-account-identity.js"; type Observation = Omit; type FailureCode = NonNullable; @@ -23,10 +24,13 @@ export async function probeAiAccountIdentity( request: typeof fetch = fetch, ): Promise { const base = { checkedAt: new Date().toISOString(), accountLabel: null, organizationLabel: null }; - if (metadata.provider !== "anthropic" || metadata.method !== "subscription" || metadata.routing) { + if (!["anthropic", "openai"].includes(metadata.provider) || metadata.method !== "subscription" || metadata.routing) { return { ...base, status: "unavailable", errorCode: "unsupported", message: messages.unsupported }; } try { + if (metadata.provider === "openai") { + return { ...base, ...await readOpenAiAccountIdentity(credential, request) }; + } const profile = await readUsage("https://api.anthropic.com/api/oauth/profile", { Authorization: `Bearer ${credential}`, "anthropic-beta": "oauth-2025-04-20", }, request); @@ -38,6 +42,11 @@ export async function probeAiAccountIdentity( } catch (error) { const code = object(error).code; const errorCode: FailureCode = typeof code === "string" && Object.hasOwn(messages, code) ? code as FailureCode : "provider_unavailable"; - return { ...base, status: errorCode === "authentication_required" || errorCode === "permission_denied" ? "unavailable" : "error", errorCode, message: messages[errorCode] }; + const message = metadata.provider === "openai" + ? errorCode === "invalid_response" ? "OpenAI did not return the selected workspace name." + : errorCode === "permission_denied" ? "OpenAI did not permit this connection to read the workspace name." + : messages[errorCode].replace("Anthropic", "OpenAI") + : messages[errorCode]; + return { ...base, status: errorCode === "authentication_required" || errorCode === "permission_denied" ? "unavailable" : "error", errorCode, message }; } } diff --git a/server/src/services/ai-connections.ts b/server/src/services/ai-connections.ts index 5805ea231c4..04964272014 100644 --- a/server/src/services/ai-connections.ts +++ b/server/src/services/ai-connections.ts @@ -263,7 +263,7 @@ export function aiConnectionService(db: Db) { errorCode: "connection_unavailable", message: "Reconnect or enable this connection to check its account details." }; } // Unsupported methods must not open their credentials just to report this limit. - const value = metadata.provider === "anthropic" && metadata.method === "subscription" && !metadata.routing + const value = ["anthropic", "openai"].includes(metadata.provider) && metadata.method === "subscription" && !metadata.routing ? await credential(row, 0, { actorType: "user", actorId: userId, ...audit, responsibleUserId: userId }) : ""; return { ...identity, ...await probeAiAccountIdentity(metadata, value) }; } diff --git a/server/src/services/openai-account-identity.ts b/server/src/services/openai-account-identity.ts new file mode 100644 index 00000000000..2f1e0fe0eaa --- /dev/null +++ b/server/src/services/openai-account-identity.ts @@ -0,0 +1,41 @@ +import type { AiConnectionAccountIdentity } from "@paperclipai/shared"; +import { readUsage } from "./ai-connection-usage.js"; + +const object = (value: unknown): Record => value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; +const label = (value: unknown): string | null => typeof value === "string" && value.trim().length > 0 + && value.length <= 254 && !/[\u0000-\u001f\u007f]/.test(value) ? value.trim() : null; +class AuthenticationRequired extends Error { + readonly code = "authentication_required"; + constructor() { super("authentication_required"); } +} + +export async function readOpenAiAccountIdentity( + credential: string, + request: typeof fetch, +): Promise> { + let auth: Record; + try { auth = object(JSON.parse(credential)); } + catch { throw new AuthenticationRequired(); } + const tokens = object(auth.tokens); + const accessToken = tokens.access_token ?? auth.accessToken; + const accountId = label(tokens.account_id ?? auth.accountId); + if (typeof accessToken !== "string" || !accessToken.trim() || accessToken.length > 32768 + || /[\u0000-\u0020\u007f]/.test(accessToken) || !accountId) throw new AuthenticationRequired(); + + const profile = await readUsage("https://chatgpt.com/backend-api/wham/accounts/check", { + Authorization: `Bearer ${accessToken}`, "ChatGPT-Account-Id": accountId, + }, request); + const accounts: Record[] = Array.isArray(profile.accounts) ? profile.accounts.map(object) + : Object.values(object(profile.accounts)).map(value => { + const account = object(object(value).account); + return { ...account, id: account.account_id }; + }); + const matches = accounts.filter(account => account.id === accountId); + const selected = matches.length === 1 ? matches[0] : undefined; + const organizationLabel = selected && selected.is_deactivated !== true + ? label(selected.name) ?? (selected.name == null && selected.structure === "personal" ? "Personal workspace" : null) + : null; + if (!organizationLabel) return { status: "unavailable", accountLabel: null, organizationLabel: null, + errorCode: "invalid_response", message: "OpenAI did not return the selected workspace name." }; + return { status: "available", accountLabel: null, organizationLabel }; +} diff --git a/ui/src/components/ai-connections/AiConnectionAccountDetails.test.tsx b/ui/src/components/ai-connections/AiConnectionAccountDetails.test.tsx index 72f4ba38d9f..b69086cea3d 100644 --- a/ui/src/components/ai-connections/AiConnectionAccountDetails.test.tsx +++ b/ui/src/components/ai-connections/AiConnectionAccountDetails.test.tsx @@ -78,6 +78,25 @@ it("shows the provider email and organization separately from the Paperclip owne expect(identityCalls()[0][0]).toBe("/api/companies/company/ai-connections/connection/identity?grantId=grant"); }); +it.each(["Example business", "Personal workspace"])("shows the selected OpenAI workspace %s with the saved email", async workspace => { + observation = { ...known, accountLabel: null, organizationLabel: workspace }; + await render({ ...account, provider: "openai", accountLabel: "avery@example.test" }); + expect(host.textContent).toContain("avery@example.test"); + expect(host.textContent).toContain(workspace); + expect(host.textContent).toContain("ChatGPT workspace"); + expect(host.textContent).toContain("Personal · Sam"); + expect(identityCalls()).toHaveLength(1); +}); + +it("explains an unavailable OpenAI workspace without guessing from the email or Paperclip access", async () => { + observation = { ...known, status: "unavailable", accountLabel: null, organizationLabel: null, + errorCode: "invalid_response", message: "OpenAI did not return the selected workspace name." }; + await render({ ...account, provider: "openai", accountLabel: "avery@example.test" }); + expect(host.textContent).toContain("avery@example.test"); + expect(host.textContent).toContain("ChatGPT workspaceNot available"); + expect(host.textContent).toContain("OpenAI did not return the selected workspace name."); +}); + it("explains profile permission denial while preserving connected account controls", async () => { observation = { ...known, status: "unavailable", accountLabel: null, organizationLabel: null, errorCode: "permission_denied", message: "Anthropic did not permit this connection to read the account email." }; await render(account, grant, true); @@ -110,17 +129,17 @@ it("keeps maintenance controls visible during a stalled lookup and recovers only expect(fetchMock.mock.calls.length - identityCalls().length).toBe(ordinaryCalls); }); -it("does not show the previous credential's identity after the selected grant changes", async () => { - await render(); +it.each(["anthropic", "openai"] as const)("does not show the previous %s credential's identity after the selected grant changes", async provider => { + await render({ ...account, provider }); expect(host.textContent).toContain("avery@example.test"); blocked = true; - await render({ ...account, grantId: "other-grant" }, { ...grant, id: "other-grant" }); + await render({ ...account, provider, grantId: "other-grant" }, { ...grant, id: "other-grant" }); expect(host.textContent).not.toContain("avery@example.test"); expect(host.textContent).toContain("Checking account details…"); }); -it("uses saved labels for unsupported methods without opening an identity request", async () => { - await render({ ...account, method: "api_key", accountLabel: "billing@example.test", ownership: "shared" }); +it.each(["anthropic", "openai"] as const)("uses saved labels for %s API keys without opening an identity request", async provider => { + await render({ ...account, provider, method: "api_key", accountLabel: "billing@example.test", ownership: "shared" }); expect(host.textContent).toContain("billing@example.test"); expect(host.textContent).toContain("Company shared"); expect(identityCalls()).toHaveLength(0); diff --git a/ui/src/components/ai-connections/AiConnectionAccountDetails.tsx b/ui/src/components/ai-connections/AiConnectionAccountDetails.tsx index 9b2b84305e0..75bf0c94a81 100644 --- a/ui/src/components/ai-connections/AiConnectionAccountDetails.tsx +++ b/ui/src/components/ai-connections/AiConnectionAccountDetails.tsx @@ -11,7 +11,8 @@ export function AiConnectionAccountDetails({ account, grant }: { account: AiManagedConnectionSummary; grant: ConnectionGrant; }) { - const canLookUp = account.provider === "anthropic" && account.method === "subscription" && account.status === "connected"; + const isChatGpt = account.provider === "openai" && account.method === "subscription" && !account.routing; + const canLookUp = !account.routing && (account.provider === "anthropic" || isChatGpt) && account.method === "subscription" && account.status === "connected"; const identity = useQuery({ queryKey: ["ai-account-identity", account.companyId, account.id, grant.id, grant.updatedAt], queryFn: ({ signal }) => aiConnectionsApi.accountIdentity(account.companyId, account.id, grant.id, { signal }), @@ -28,9 +29,9 @@ export function AiConnectionAccountDetails({ account, grant }: {
{AI_PROVIDERS[account.provider].name} account
{accountLabel ?? "Not available"}
- {identity.data?.organizationLabel && <> -
Organization
-
{identity.data.organizationLabel}
+ {(isChatGpt || identity.data?.organizationLabel) && <> +
{isChatGpt ? "ChatGPT workspace" : "Organization"}
+
{identity.data?.organizationLabel ?? (identity.isPending && canLookUp ? "Checking…" : "Not available")}
}
Sign-in method
{aiMethodLabel(account.provider, account.method)}