From dc0cb2442db255d2edad51a8047db9902bebe2d4 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Mon, 2 Nov 2026 15:49:44 -0600 Subject: [PATCH 1/5] fix!: surface account-plane FORBIDDEN and slim the team projects query - Map an all-FORBIDDEN errors[] response (HTTP 200) to the `forbidden` error, same as an HTTP 403. It previously read as a generic "could not complete this request". - Append the server's error code to generic account-plane failures, and name the real cause in `environment_unresolved` instead of always blaming the network. - Send `teamProjectsV2` with only the fields the CLI reads. The catalog version pulled the full Environment fragment, so one failing resolver broke environment resolution for every env-scoped command. BREAKING CHANGE: `workos project list --json` environments now contain only id, name, sandbox and clientId instead of every raw backend field. --- src/catalog/no-graphql-leak.spec.ts | 29 +++++++++++++++++++- src/catalog/operation.ts | 41 ++++++++++++++++++++++++++++- src/lib/command-auth.ts | 2 +- src/lib/dashboard-graphql.spec.ts | 21 +++++++++++++++ src/lib/dashboard-graphql.ts | 13 ++++++++- src/lib/environment-target.spec.ts | 16 +++++++++++ src/lib/environment-target.ts | 6 +++-- 7 files changed, 122 insertions(+), 6 deletions(-) diff --git a/src/catalog/no-graphql-leak.spec.ts b/src/catalog/no-graphql-leak.spec.ts index fb54526b..0233c038 100644 --- a/src/catalog/no-graphql-leak.spec.ts +++ b/src/catalog/no-graphql-leak.spec.ts @@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest'; import { loadManagementCatalog } from './loader.js'; import { getManifest } from './manifest.js'; import { OVERRIDES, resolveCommandMeta, findLeaks, LEAK_PATTERN } from './curation.js'; -import { dashboardErrorMessage } from './operation.js'; +import { dashboardErrorMessage, getOperation, resolveExecutableDocument } from './operation.js'; import { DASHBOARD_ERROR_MESSAGES } from '../lib/command-auth.js'; import { DashboardGraphqlError, type DashboardGraphqlErrorCode } from '../lib/dashboard-graphql.js'; import { buildCommandTree, type CommandSchema, type HelpOutput } from '../utils/help-json.js'; @@ -124,6 +124,19 @@ describe('no GraphQL/userland leak in dashboard-plane error copy', () => { } }); + it('appends a clean server error code to graphql_error copy, never the server message', () => { + const msg = (serverCode?: string) => + dashboardErrorMessage(new DashboardGraphqlError('private details', 'graphql_error', undefined, serverCode)); + expect(msg('INTERNAL_SERVER_ERROR')).toBe( + 'The WorkOS account plane could not complete this request (INTERNAL_SERVER_ERROR).', + ); + expect(msg('GRAPHQL_VALIDATION_FAILED')).toContain('(VALIDATION_FAILED)'); + expect(msg(undefined)).toBe('The WorkOS account plane could not complete this request.'); + expect(msg('not a code; private')).toBe('The WorkOS account plane could not complete this request.'); + expect(msg('USERLAND_THING')).toBe('The WorkOS account plane could not complete this request.'); + expect(msg('INTERNAL_SERVER_ERROR')).not.toContain('private details'); + }); + it('forbidden copy no longer claims the capability is staging-gated', () => { expect(DASHBOARD_ERROR_MESSAGES.forbidden).not.toMatch(/staging/i); expect(dashboardErrorMessage(new DashboardGraphqlError('x', 'forbidden', 403))).toBe( @@ -131,3 +144,17 @@ describe('no GraphQL/userland leak in dashboard-plane error copy', () => { ); }); }); + +describe('teamProjectsV2 wire document', () => { + // Every env-scoped command resolves its target through this query, so it must + // select only what the CLI reads: a failing resolver on an unread field + // (e.g. certificate expiry) must not take down every command for the team. + it('selects only the fields the CLI reads', () => { + const doc = resolveExecutableDocument(getOperation('teamProjectsV2')); + expect(doc).toContain('query teamProjectsV2'); + for (const field of ['projectsV2', 'clientId', 'sandbox']) expect(doc).toContain(field); + for (const field of ['...Environment', 'expiredConnectionCertificates', 'customAuthDomain', 'resourceTypeCount']) { + expect(doc).not.toContain(field); + } + }); +}); diff --git a/src/catalog/operation.ts b/src/catalog/operation.ts index 47efb349..afc5a600 100644 --- a/src/catalog/operation.ts +++ b/src/catalog/operation.ts @@ -2,6 +2,7 @@ import { loadManagementCatalog } from './loader.js'; import { DashboardGraphqlError } from '../lib/dashboard-graphql.js'; import { DASHBOARD_ERROR_MESSAGES } from '../lib/command-auth.js'; import { exitWithError } from '../utils/output.js'; +import { LEAK_PATTERN } from './curation.js'; import type { CatalogOperation, ManagementCatalog } from './catalog-types.js'; /** @@ -59,6 +60,32 @@ export function getOperation( return op; } +/** + * Slimmer wire documents for operations whose catalog selection is far wider + * than anything the CLI reads. `teamProjectsV2` backs environment resolution + * for every env-scoped command, and its catalog version pulls the full + * Environment fragment (certificate expiry, custom domains, ...): one of those + * resolvers failing for one environment used to fail the whole team's reads. + * Keep the operation name: specs route on it. + */ +const DOCUMENT_OVERRIDES: Record = { + teamProjectsV2: `query teamProjectsV2 { + currentTeam { + id + projectsV2 { + id + name + environments { + id + name + sandbox + clientId + } + } + } +}`, +}; + /** * Returns the full executable GraphQL document for an operation: its own * `document` text plus the definitions of every fragment it transitively @@ -74,6 +101,8 @@ export function resolveExecutableDocument( op: CatalogOperation, catalog: ManagementCatalog = loadManagementCatalog(undefined, { includeFeatureFlagged: true }), ): string { + const override = DOCUMENT_OVERRIDES[op.name]; + if (override) return override; if (op.fragmentNames.length === 0) return op.document; const fragments = op.fragmentNames.map((fragmentName) => { @@ -111,6 +140,16 @@ export function reportDashboardError(error: unknown): never { throw error; } +/** + * The server's error code (e.g. `INTERNAL_SERVER_ERROR`) is the only server + * detail we echo: messages can carry private data. Codes are uppercase + * identifiers; anything else, or anything naming GraphQL, is dropped. + */ +function serverCodeSuffix(code: string | undefined): string { + const clean = code?.replace(/^GRAPHQL_/, ''); + return clean && /^[A-Z][A-Z0-9_]*$/.test(clean) && !LEAK_PATTERN.test(clean) ? ` (${clean})` : ''; +} + /** * Per-code user-facing copy. Exported so `no-graphql-leak.spec.ts` can run the * leak gate over every branch. `forbidden` (exit 1, not auth-recoverable) is @@ -127,6 +166,6 @@ export function dashboardErrorMessage(error: DashboardGraphqlError): string { return 'Could not reach the WorkOS account plane. Check your connection and try again.'; case 'graphql_error': default: - return 'The WorkOS account plane could not complete this request.'; + return `The WorkOS account plane could not complete this request${serverCodeSuffix(error.serverCode)}.`; } } diff --git a/src/lib/command-auth.ts b/src/lib/command-auth.ts index 7571cd6d..41cde4e6 100644 --- a/src/lib/command-auth.ts +++ b/src/lib/command-auth.ts @@ -84,7 +84,7 @@ export const DASHBOARD_ERROR_MESSAGES: Record< /** 403 from the dashboard plane: capability off for the team, or no team. */ get forbidden() { return ( - 'This account-plane capability is not enabled for this team, ' + + 'This account-plane capability is not enabled for this team, your team role does not allow it, ' + 'or the logged-in account is not backed by a WorkOS dashboard team.' ); }, diff --git a/src/lib/dashboard-graphql.spec.ts b/src/lib/dashboard-graphql.spec.ts index 9507d674..33a40b7c 100644 --- a/src/lib/dashboard-graphql.spec.ts +++ b/src/lib/dashboard-graphql.spec.ts @@ -54,6 +54,27 @@ describe('dashboardGraphqlUpload', () => { }); }); + it('maps an all-FORBIDDEN errors[] payload to forbidden (403)', async () => { + fetchMock.mockResolvedValue( + Response.json({ errors: [{ message: 'private details', extensions: { code: 'FORBIDDEN' } }] }), + ); + await expect(dashboardGraphqlRequest('query {}', { token: 'fake-token' })).rejects.toMatchObject({ + code: 'forbidden', + status: 403, + message: expect.not.stringContaining('private details'), + }); + }); + + it('keeps the server error code on graphql_error', async () => { + fetchMock.mockResolvedValue( + Response.json({ errors: [{ message: 'boom' }, { message: 'x', extensions: { code: 'INTERNAL_SERVER_ERROR' } }] }), + ); + await expect(dashboardGraphqlRequest('query {}', { token: 'fake-token' })).rejects.toMatchObject({ + code: 'graphql_error', + serverCode: 'INTERNAL_SERVER_ERROR', + }); + }); + /** The FormData handed to fetch on the most recent call. */ function sentForm(): FormData { const init = fetchMock.mock.calls[0]?.[1] as RequestInit; diff --git a/src/lib/dashboard-graphql.ts b/src/lib/dashboard-graphql.ts index 673ee953..529fd551 100644 --- a/src/lib/dashboard-graphql.ts +++ b/src/lib/dashboard-graphql.ts @@ -40,6 +40,8 @@ export class DashboardGraphqlError extends Error { message: string, readonly code: DashboardGraphqlErrorCode, readonly status?: number, + /** Server-supplied error code (`errors[].extensions.code`) for `graphql_error`. */ + readonly serverCode?: string, ) { super(message); this.name = 'DashboardGraphqlError'; @@ -154,7 +156,16 @@ async function sendDashboardRequest( if (body.errors.every((error) => error.extensions?.code === 'UNAUTHENTICATED')) { throw new DashboardGraphqlError('The dashboard session was rejected.', 'forbidden', 401); } - throw new DashboardGraphqlError(body.errors.map((e) => e.message).join('; '), 'graphql_error'); + // The capability gate (and role checks) answer HTTP 200 with FORBIDDEN, not a 403. + if (body.errors.every((error) => error.extensions?.code === 'FORBIDDEN')) { + throw new DashboardGraphqlError('The dashboard refused this request.', 'forbidden', 403); + } + throw new DashboardGraphqlError( + body.errors.map((e) => e.message).join('; '), + 'graphql_error', + undefined, + body.errors.find((e) => e.extensions?.code)?.extensions?.code, + ); } if (body.data == null) { diff --git a/src/lib/environment-target.spec.ts b/src/lib/environment-target.spec.ts index 16368ecf..480f0f2a 100644 --- a/src/lib/environment-target.spec.ts +++ b/src/lib/environment-target.spec.ts @@ -288,6 +288,22 @@ describe('resolveEnvironmentTarget', () => { expect(err).not.toMatch(/graphql/i); }); + it('names the server failure instead of blaming the network when the account plane errors', async () => { + seedProfile({ clientId: 'client_abc' }); + mockGraphqlRequest.mockRejectedValue( + new DashboardGraphqlError('private details', 'graphql_error', undefined, 'INTERNAL_SERVER_ERROR'), + ); + await expect(resolveEnvironmentTarget('tok', { forMutation: false })).rejects.toMatchObject({ + name: 'CliExit', + context: { errorCode: 'environment_unresolved' }, + }); + const err = errorSpy.mock.calls.map((c) => c.map(String).join(' ')).join('\n'); + expect(err).toContain('account plane could not complete this request (INTERNAL_SERVER_ERROR)'); + expect(err).not.toMatch(/network or server error/i); + expect(err).not.toContain('private details'); + expect(err).toContain('--environment-id'); + }); + it('surfaces a 403 as forbidden guidance, not a transient retry hint', async () => { seedProfile({ clientId: 'client_abc' }); mockGraphqlRequest.mockRejectedValue(new DashboardGraphqlError('denied', 'forbidden', 403)); diff --git a/src/lib/environment-target.ts b/src/lib/environment-target.ts index 1fb1c827..b8f7a163 100644 --- a/src/lib/environment-target.ts +++ b/src/lib/environment-target.ts @@ -28,7 +28,7 @@ import ui from '../utils/ui.js'; import { getConfig, getActiveEnvironment, setProfileEnvironmentId, type CliConfig } from './config-store.js'; import { dashboardGraphqlRequest, DashboardGraphqlError } from './dashboard-graphql.js'; -import { getOperation, resolveExecutableDocument } from '../catalog/operation.js'; +import { dashboardErrorMessage, getOperation, resolveExecutableDocument } from '../catalog/operation.js'; import { refreshIfExpired, DASHBOARD_ERROR_MESSAGES } from './command-auth.js'; import { exitWithError } from '../utils/output.js'; import { isPromptAllowed } from '../utils/interaction-mode.js'; @@ -163,9 +163,11 @@ export async function resolveEnvironmentTarget( if (error instanceof DashboardGraphqlError && error.code === 'forbidden') { exitWithError({ code: 'forbidden', message: DASHBOARD_ERROR_MESSAGES.forbidden }); } + const cause = + error instanceof DashboardGraphqlError ? `: ${dashboardErrorMessage(error)}` : ' (network or server error).'; exitWithError({ code: 'environment_unresolved', - message: `Could not resolve the target WorkOS environment (network or server error). Try again. ${remedies()}`, + message: `Could not resolve the target WorkOS environment${cause} Try again. ${remedies()}`, }); } From c897a3e68a38a7dfaee6cc9ad3a719b710183ce4 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Mon, 2 Nov 2026 15:56:19 -0600 Subject: [PATCH 2/5] fix: ignore non-string server error codes --- src/lib/dashboard-graphql.spec.ts | 15 +++++++++++++++ src/lib/dashboard-graphql.ts | 3 ++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/lib/dashboard-graphql.spec.ts b/src/lib/dashboard-graphql.spec.ts index 33a40b7c..38ee41c8 100644 --- a/src/lib/dashboard-graphql.spec.ts +++ b/src/lib/dashboard-graphql.spec.ts @@ -75,6 +75,21 @@ describe('dashboardGraphqlUpload', () => { }); }); + it('ignores a non-string server error code', async () => { + fetchMock.mockResolvedValue( + Response.json({ + errors: [ + { message: 'boom', extensions: { code: 500 } }, + { message: 'x', extensions: { code: {} } }, + ], + }), + ); + await expect(dashboardGraphqlRequest('query {}', { token: 'fake-token' })).rejects.toMatchObject({ + code: 'graphql_error', + serverCode: undefined, + }); + }); + /** The FormData handed to fetch on the most recent call. */ function sentForm(): FormData { const init = fetchMock.mock.calls[0]?.[1] as RequestInit; diff --git a/src/lib/dashboard-graphql.ts b/src/lib/dashboard-graphql.ts index 529fd551..b557c5a2 100644 --- a/src/lib/dashboard-graphql.ts +++ b/src/lib/dashboard-graphql.ts @@ -164,7 +164,8 @@ async function sendDashboardRequest( body.errors.map((e) => e.message).join('; '), 'graphql_error', undefined, - body.errors.find((e) => e.extensions?.code)?.extensions?.code, + // Untrusted JSON: keep only a string code. + body.errors.map((e) => e.extensions?.code).find((code): code is string => typeof code === 'string'), ); } From 91bf436b627bf93a4d289f8b978b93b5938f0b5c Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Mon, 23 Nov 2026 10:32:29 -0600 Subject: [PATCH 3/5] test: guard the team projects override against catalog drift Riker-Verification: check --- src/catalog/no-graphql-leak.spec.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/catalog/no-graphql-leak.spec.ts b/src/catalog/no-graphql-leak.spec.ts index 0233c038..fc3faef1 100644 --- a/src/catalog/no-graphql-leak.spec.ts +++ b/src/catalog/no-graphql-leak.spec.ts @@ -157,4 +157,15 @@ describe('teamProjectsV2 wire document', () => { expect(doc).not.toContain(field); } }); + + // The override is a second copy of the selection that `catalog:vendor` never + // refreshes: every name it sends must still exist in the vendored document. + it('selects only fields the vendored catalog also selects', () => { + const op = getOperation('teamProjectsV2'); + const catalog = loadManagementCatalog(undefined, { includeFeatureFlagged: true }); + const vendored = [op.document, ...op.fragmentNames.map((name) => catalog.fragments[name])].join('\n'); + const vendoredNames = new Set(vendored.match(/\w+/g)); + const drift = (resolveExecutableDocument(op).match(/\w+/g) ?? []).filter((name) => !vendoredNames.has(name)); + expect(drift).toEqual([]); + }); }); From 0f1825e6550651d3f97e160c60d248c3c11c9e0a Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Mon, 23 Nov 2026 10:33:04 -0600 Subject: [PATCH 4/5] fix: avoid a duplicate environment lookup retry hint Riker-Verification: check --- src/lib/environment-target.spec.ts | 20 ++++++++++++++++++++ src/lib/environment-target.ts | 3 ++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/lib/environment-target.spec.ts b/src/lib/environment-target.spec.ts index 480f0f2a..51e90661 100644 --- a/src/lib/environment-target.spec.ts +++ b/src/lib/environment-target.spec.ts @@ -288,6 +288,26 @@ describe('resolveEnvironmentTarget', () => { expect(err).not.toMatch(/graphql/i); }); + it('says try again once on a network error', async () => { + mockGraphqlRequest.mockRejectedValueOnce(new DashboardGraphqlError('connection failed', 'network_error')); + await expect(resolveEnvironmentTarget('tok', { forMutation: false })).rejects.toMatchObject({ + name: 'CliExit', + context: { errorCode: 'environment_unresolved' }, + }); + const networkMessage = errorSpy.mock.lastCall?.map(String).join(' '); + expect(networkMessage?.match(/try again/gi)).toHaveLength(1); + + mockGraphqlRequest.mockRejectedValueOnce( + new DashboardGraphqlError('private details', 'graphql_error', undefined, 'INTERNAL_SERVER_ERROR'), + ); + await expect(resolveEnvironmentTarget('tok', { forMutation: false })).rejects.toMatchObject({ + name: 'CliExit', + context: { errorCode: 'environment_unresolved' }, + }); + const serverMessage = errorSpy.mock.lastCall?.map(String).join(' '); + expect(serverMessage).toContain('Try again.'); + }); + it('names the server failure instead of blaming the network when the account plane errors', async () => { seedProfile({ clientId: 'client_abc' }); mockGraphqlRequest.mockRejectedValue( diff --git a/src/lib/environment-target.ts b/src/lib/environment-target.ts index b8f7a163..fcb8fd75 100644 --- a/src/lib/environment-target.ts +++ b/src/lib/environment-target.ts @@ -165,9 +165,10 @@ export async function resolveEnvironmentTarget( } const cause = error instanceof DashboardGraphqlError ? `: ${dashboardErrorMessage(error)}` : ' (network or server error).'; + const retry = cause.toLowerCase().endsWith('try again.') ? '' : ' Try again.'; exitWithError({ code: 'environment_unresolved', - message: `Could not resolve the target WorkOS environment${cause} Try again. ${remedies()}`, + message: `Could not resolve the target WorkOS environment${cause}${retry} ${remedies()}`, }); } From 2496021d99c83c56d06b997a314a75409696fbe9 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Mon, 23 Nov 2026 11:01:26 -0600 Subject: [PATCH 5/5] test: detect team projects catalog drift by field path Riker-Verification: check --- src/catalog/no-graphql-leak.spec.ts | 83 ++++++++++++++++++++++++++--- 1 file changed, 76 insertions(+), 7 deletions(-) diff --git a/src/catalog/no-graphql-leak.spec.ts b/src/catalog/no-graphql-leak.spec.ts index fc3faef1..62d2efca 100644 --- a/src/catalog/no-graphql-leak.spec.ts +++ b/src/catalog/no-graphql-leak.spec.ts @@ -145,6 +145,75 @@ describe('no GraphQL/userland leak in dashboard-plane error copy', () => { }); }); +// Only the selection syntax used by this query and its fragments is needed. +// Reject arguments and directives rather than mistaking their names for fields. +function selectedFieldPaths(document: string, fragments: Record = {}): Set { + const paths = new Set(); + const activeFragments = new Set(); + + function visitDefinition(source: string, prefix: string) { + const tokens = source.replace(/#[^\r\n]*/g, '').match(/\.\.\.|[_A-Za-z][_0-9A-Za-z]*|[^\s,]/g) ?? []; + let index = 0; + + function consume(expected: string) { + const token = tokens[index++]; + if (token !== expected) throw new Error(`Expected "${expected}", got ${token ?? 'end of document'}`); + } + + function readName(): string { + const token = tokens[index++]; + if (!token || !/^[_A-Za-z]/.test(token)) throw new Error(`Expected a name, got ${token ?? 'end of document'}`); + return token; + } + + function visitSelection(parent: string) { + consume('{'); + while (tokens[index] !== '}') { + if (tokens[index] === '...') { + index++; + const name = readName(); + if (name === 'on') { + readName(); // Inline fragment type condition, not a field. + visitSelection(parent); + } else { + const fragment = fragments[name]; + if (typeof fragment !== 'string') throw new Error(`Missing fragment "${name}"`); + if (activeFragments.has(name)) throw new Error(`Cyclic fragment "${name}"`); + activeFragments.add(name); + visitDefinition(fragment, parent); + activeFragments.delete(name); + } + continue; + } + let field = readName(); + if (tokens[index] === ':') { + index++; + field = readName(); // Use the schema field name, not the alias. + } + const path = parent ? `${parent}.${field}` : field; + paths.add(path); + if (tokens[index] === '{') visitSelection(path); + } + consume('}'); + } + + if (tokens[index] === 'fragment') { + consume('fragment'); + readName(); + consume('on'); + readName(); + } else { + consume('query'); + readName(); + } + visitSelection(prefix); + if (index !== tokens.length) throw new Error(`Unexpected token "${tokens[index]}" after selection set`); + } + + visitDefinition(document, ''); + return paths; +} + describe('teamProjectsV2 wire document', () => { // Every env-scoped command resolves its target through this query, so it must // select only what the CLI reads: a failing resolver on an unread field @@ -158,14 +227,14 @@ describe('teamProjectsV2 wire document', () => { } }); - // The override is a second copy of the selection that `catalog:vendor` never - // refreshes: every name it sends must still exist in the vendored document. + // `catalog:vendor` never refreshes the override. Compare paths, not names: + // a project may still select `name` after the environment field is renamed. it('selects only fields the vendored catalog also selects', () => { - const op = getOperation('teamProjectsV2'); - const catalog = loadManagementCatalog(undefined, { includeFeatureFlagged: true }); - const vendored = [op.document, ...op.fragmentNames.map((name) => catalog.fragments[name])].join('\n'); - const vendoredNames = new Set(vendored.match(/\w+/g)); - const drift = (resolveExecutableDocument(op).match(/\w+/g) ?? []).filter((name) => !vendoredNames.has(name)); + const operation = getOperation('teamProjectsV2'); + const fragments = Object.fromEntries(operation.fragmentNames.map((name) => [name, catalog.fragments[name]])); + const vendoredPaths = selectedFieldPaths(operation.document, fragments); + const overridePaths = selectedFieldPaths(resolveExecutableDocument(operation)); + const drift = [...overridePaths].filter((path) => !vendoredPaths.has(path)); expect(drift).toEqual([]); }); });