From 20d2ef3325e0dd21def4562300a122fc23967085 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 12:25:01 -0800 Subject: [PATCH 01/32] feat: run organization and org-domain commands with an API key Environment-scoped resource commands now take an API-key path when --api-key or WORKOS_API_KEY is given, or the active profile is an unclaimed environment. Signed-in users without an explicit key keep the dashboard session path unchanged. The path is chosen in one seam (resolveEnvScopedAuth in dashboard-operation.ts). On it, each catalog operation runs through a REST adapter that returns the dashboard operation's data shape, so the commands' existing shapers produce the --json output. Operations with no REST equivalent exit with a structured api_key_unsupported error. This commit adds the seam, the --api-key flag on the resource command groups, the organization/org-domain adapters, and rewords the API-key-set auth copy, which no longer says these commands reject API keys. --- src/bin.ts | 60 ++++-- src/commands/invitation.ts | 29 +-- src/commands/membership.ts | 9 +- src/commands/permission.ts | 35 ++-- src/commands/role.ts | 52 ++---- src/lib/api-key-operations/context.ts | 121 ++++++++++++ src/lib/api-key-operations/index.ts | 95 ++++++++++ src/lib/api-key-operations/organizations.ts | 194 ++++++++++++++++++++ src/lib/command-auth.spec.ts | 101 +++++++++- src/lib/command-auth.ts | 24 ++- src/lib/dashboard-operation.ts | 91 ++++++++- src/lib/resource-auth.ts | 82 +++++++++ src/utils/help-json.ts | 38 ++-- 13 files changed, 802 insertions(+), 129 deletions(-) create mode 100644 src/lib/api-key-operations/context.ts create mode 100644 src/lib/api-key-operations/index.ts create mode 100644 src/lib/api-key-operations/organizations.ts create mode 100644 src/lib/resource-auth.ts diff --git a/src/bin.ts b/src/bin.ts index c5e95920..d631974e 100644 --- a/src/bin.ts +++ b/src/bin.ts @@ -12,6 +12,7 @@ if (process.argv.includes('--local') || process.env.WORKOS_DEV) { import { getVersion } from './lib/settings.js'; import yargs from 'yargs'; +import type { Argv } from 'yargs'; import { ensureAuthenticated } from './lib/ensure-auth.js'; import { InstallDeclinedError } from './lib/installer-errors.js'; import { checkForUpdates } from './lib/version-check.js'; @@ -144,6 +145,27 @@ async function maybeWarnUnclaimed(): Promise { import { resolveInstallCredentials } from './lib/resolve-install-credentials.js'; +/** + * `--api-key` on the environment-scoped resource commands (organization, user, + * role, …): with it, or with WORKOS_API_KEY, the command runs on the WorkOS + * REST API with that key instead of the dashboard login. Same flag `workos api` + * and the still-REST commands take; see lib/resource-auth.ts for precedence. + */ +const resourceApiKeyOption = { + 'api-key': { + type: 'string' as const, + describe: 'WorkOS API key (runs the command with this key instead of your dashboard login)', + }, +} as const; + +/** Add `--api-key` to a resource command group and hand it to the auth selector. */ +function withResourceApiKey(yargs: Argv): Argv { + return yargs.options(resourceApiKeyOption).middleware(async (argv) => { + const { setResourceApiKeyFlag } = await import('./lib/resource-auth.js'); + setResourceApiKeyFlag(argv.apiKey as string | undefined); + }); +} + /** Shared insecure-storage option for commands that access credentials */ const insecureStorageOption = { 'insecure-storage': { @@ -579,7 +601,7 @@ async function runCli(): Promise { 'authkit', 'Manage AuthKit app config (redirect URIs, CORS, logout URIs, branding) on the dashboard account plane', (yargs) => { - yargs.options(insecureStorageOption); + withResourceApiKey(yargs.options(insecureStorageOption)); yargs.command('redirect-uris', 'Manage AuthKit redirect URIs', (yargs) => { registerSubcommand( @@ -713,7 +735,7 @@ async function runCli(): Promise { }, ) .command('branding', 'Manage branding images (logo, icon, favicon) for an environment', (yargs) => { - yargs.options(insecureStorageOption); + withResourceApiKey(yargs.options(insecureStorageOption)); registerSubcommand( yargs, 'get', @@ -1301,7 +1323,7 @@ async function runCli(): Promise { }, ) .command(['organization', 'org'], 'Manage WorkOS organizations (create, update, get, list, delete)', (yargs) => { - yargs.options(insecureStorageOption); + withResourceApiKey(yargs.options(insecureStorageOption)); registerSubcommand( yargs, 'create [domains..]', @@ -1406,7 +1428,7 @@ async function runCli(): Promise { return yargs.demandCommand(1, 'Please specify an organization subcommand').strict(); }) .command('user', 'Manage AuthKit users (get, list, update, delete)', (yargs) => { - yargs.options(insecureStorageOption); + withResourceApiKey(yargs.options(insecureStorageOption)); registerSubcommand( yargs, 'get ', @@ -1496,10 +1518,12 @@ async function runCli(): Promise { }) // --- Resource Management Commands --- .command('role', 'Manage WorkOS roles (environment and organization-scoped)', (yargs) => { - yargs.options({ - ...insecureStorageOption, - org: { type: 'string' as const, describe: 'Organization ID (for organization roles)' }, - }); + withResourceApiKey( + yargs.options({ + ...insecureStorageOption, + org: { type: 'string' as const, describe: 'Organization ID (for organization roles)' }, + }), + ); registerSubcommand( yargs, 'list', @@ -1692,7 +1716,7 @@ async function runCli(): Promise { return yargs.demandCommand(1, 'Please specify a role subcommand').strict(); }) .command('permission', 'Manage WorkOS permissions', (yargs) => { - yargs.options(insecureStorageOption); + withResourceApiKey(yargs.options(insecureStorageOption)); registerSubcommand( yargs, 'list', @@ -1796,7 +1820,7 @@ async function runCli(): Promise { return yargs.demandCommand(1, 'Please specify a permission subcommand').strict(); }) .command('membership', 'Manage organization memberships', (yargs) => { - yargs.options(insecureStorageOption); + withResourceApiKey(yargs.options(insecureStorageOption)); registerSubcommand( yargs, 'list', @@ -1947,7 +1971,7 @@ async function runCli(): Promise { return yargs.demandCommand(1, 'Please specify a membership subcommand').strict(); }) .command('invitation', 'Manage user invitations', (yargs) => { - yargs.options(insecureStorageOption); + withResourceApiKey(yargs.options(insecureStorageOption)); registerSubcommand( yargs, 'list', @@ -2048,7 +2072,7 @@ async function runCli(): Promise { return yargs.demandCommand(1, 'Please specify an invitation subcommand').strict(); }) .command('session', 'Manage user sessions', (yargs) => { - yargs.options(insecureStorageOption); + withResourceApiKey(yargs.options(insecureStorageOption)); registerSubcommand( yargs, 'list ', @@ -2335,7 +2359,7 @@ async function runCli(): Promise { return yargs.demandCommand(1, 'Please specify a directory subcommand').strict(); }) .command('event', 'Query WorkOS events', (yargs) => { - yargs.options(insecureStorageOption); + withResourceApiKey(yargs.options(insecureStorageOption)); registerSubcommand( yargs, 'list', @@ -2502,7 +2526,7 @@ async function runCli(): Promise { return yargs.demandCommand(1, 'Please specify an audit-log subcommand').strict(); }) .command('feature-flag', 'Manage feature flags', (yargs) => { - yargs.options(insecureStorageOption); + withResourceApiKey(yargs.options(insecureStorageOption)); registerSubcommand( yargs, 'list', @@ -2600,7 +2624,7 @@ async function runCli(): Promise { return yargs.demandCommand(1, 'Please specify a feature-flag subcommand').strict(); }) .command('webhook', 'Manage webhooks', (yargs) => { - yargs.options(insecureStorageOption); + withResourceApiKey(yargs.options(insecureStorageOption)); registerSubcommand( yargs, 'list', @@ -2654,7 +2678,7 @@ async function runCli(): Promise { return yargs.demandCommand(1, 'Please specify a webhook subcommand').strict(); }) .command('config', 'Manage AuthKit app configuration (redirect URIs, CORS, homepage)', (yargs) => { - yargs.options(insecureStorageOption); + withResourceApiKey(yargs.options(insecureStorageOption)); yargs.command('redirect', 'Manage redirect URIs', (yargs) => { registerSubcommand( yargs, @@ -2709,7 +2733,7 @@ async function runCli(): Promise { return yargs.demandCommand(1, 'Please specify a config subcommand').strict(); }) .command('portal', 'Manage Admin Portal', (yargs) => { - yargs.options(insecureStorageOption); + withResourceApiKey(yargs.options(insecureStorageOption)); registerSubcommand( yargs, 'generate-link', @@ -2988,7 +3012,7 @@ async function runCli(): Promise { return yargs.demandCommand(1, 'Please specify an api-key subcommand').strict(); }) .command('org-domain', 'Manage organization domains', (yargs) => { - yargs.options(insecureStorageOption); + withResourceApiKey(yargs.options(insecureStorageOption)); registerSubcommand( yargs, 'get ', diff --git a/src/commands/invitation.ts b/src/commands/invitation.ts index 5bccc024..ff09573c 100644 --- a/src/commands/invitation.ts +++ b/src/commands/invitation.ts @@ -24,10 +24,9 @@ */ import chalk from 'chalk'; -import { requireCommandToken } from '../lib/command-auth.js'; -import { resolveEnvironmentTarget } from '../lib/environment-target.js'; +import type { OperationAuth } from '../lib/resource-auth.js'; import { getOperation } from '../catalog/operation.js'; -import { runEnvScopedOperation, executeDashboardOperation } from '../lib/dashboard-operation.js'; +import { runEnvScopedOperation, executeDashboardOperation, resolveEnvScopedAuth } from '../lib/dashboard-operation.js'; import { confirmDestructive } from '../catalog/confirm.js'; import { isJsonMode, outputJson, outputSuccess, exitWithError } from '../utils/output.js'; import { enumOut } from '../utils/output-conventions.js'; @@ -90,7 +89,7 @@ interface InvitationPage { /** Fetch one page of env-wide invitations (also backs `invitation get`). */ async function fetchEnvironmentInvitations( - token: string, + token: OperationAuth, environmentId: string, variables: { search?: string; limit?: number; before?: string; after?: string }, ): Promise { @@ -122,7 +121,11 @@ export interface InvitationListOptions { } export async function runInvitationList(options: InvitationListOptions = {}): Promise { - const token = await requireCommandToken(); + const op = getOperation(options.org ? 'userlandUserInvitesByOrg' : 'userlandUserInvites'); + const { token, environmentId } = await resolveEnvScopedAuth({ + environmentId: options.environmentId, + forMutation: op.kind === 'mutation', + }); const pageVariables = { ...(options.email ? { search: options.email } : {}), ...(options.limit !== undefined ? { limit: options.limit } : {}), @@ -132,12 +135,6 @@ export async function runInvitationList(options: InvitationListOptions = {}): Pr let page: InvitationPage; if (options.org) { - const op = getOperation('userlandUserInvitesByOrg'); - const { environmentId } = await resolveEnvironmentTarget(token, { - flagValue: options.environmentId, - forMutation: op.kind === 'mutation', - }); - const data = await executeDashboardOperation<{ organization: { userlandUserInvites: { @@ -166,11 +163,6 @@ export async function runInvitationList(options: InvitationListOptions = {}): Pr }, }; } else { - const op = getOperation('userlandUserInvites'); - const { environmentId } = await resolveEnvironmentTarget(token, { - flagValue: options.environmentId, - forMutation: op.kind === 'mutation', - }); page = await fetchEnvironmentInvitations(token, environmentId, pageVariables); } @@ -193,11 +185,10 @@ export interface InvitationGetOptions { } export async function runInvitationGet(id: string, options: InvitationGetOptions = {}): Promise { - const token = await requireCommandToken(); const op = getOperation('userlandUserInvites'); - const { environmentId } = await resolveEnvironmentTarget(token, { - flagValue: options.environmentId, + const { token, environmentId } = await resolveEnvScopedAuth({ + environmentId: options.environmentId, forMutation: op.kind === 'mutation', }); diff --git a/src/commands/membership.ts b/src/commands/membership.ts index fe721ff7..39214082 100644 --- a/src/commands/membership.ts +++ b/src/commands/membership.ts @@ -24,10 +24,8 @@ */ import chalk from 'chalk'; -import { requireCommandToken } from '../lib/command-auth.js'; -import { resolveEnvironmentTarget } from '../lib/environment-target.js'; import { getOperation } from '../catalog/operation.js'; -import { runEnvScopedOperation, executeDashboardOperation } from '../lib/dashboard-operation.js'; +import { runEnvScopedOperation, executeDashboardOperation, resolveEnvScopedAuth } from '../lib/dashboard-operation.js'; import { confirmDestructive, requireConfirmationFlag } from '../catalog/confirm.js'; import { isJsonMode, outputJson, outputSuccess, exitWithError } from '../utils/output.js'; import { formatTable } from '../utils/table.js'; @@ -399,12 +397,11 @@ export async function runMembershipDelete(id: string, options: MembershipDeleteO action: `delete membership ${id} — this removes the user from the organization`, }); - const token = await requireCommandToken(); const removeOp = getOperation('removeMemberFromOrganization'); // Environment-scoped mutation: pre-validated resolved target as header. - const { environmentId } = await resolveEnvironmentTarget(token, { - flagValue: options.environmentId, + const { token, environmentId } = await resolveEnvScopedAuth({ + environmentId: options.environmentId, forMutation: removeOp.kind === 'mutation', }); diff --git a/src/commands/permission.ts b/src/commands/permission.ts index 8438c320..41ee4a54 100644 --- a/src/commands/permission.ts +++ b/src/commands/permission.ts @@ -25,9 +25,8 @@ */ import chalk from 'chalk'; -import { requireCommandToken } from '../lib/command-auth.js'; -import { resolveEnvironmentTarget } from '../lib/environment-target.js'; -import { runEnvScopedOperation, executeDashboardOperation } from '../lib/dashboard-operation.js'; +import type { OperationAuth } from '../lib/resource-auth.js'; +import { runEnvScopedOperation, executeDashboardOperation, resolveEnvScopedAuth } from '../lib/dashboard-operation.js'; import { getOperation } from '../catalog/operation.js'; import { confirmDestructive, requireConfirmationFlag } from '../catalog/confirm.js'; import { isJsonMode, outputJson, outputSuccess, exitWithError } from '../utils/output.js'; @@ -62,7 +61,7 @@ function shapePermission(permission: PermissionNode) { } /** Fetch the environment's full permission set (the op is unpaginated). */ -async function fetchPermissions(token: string, environmentId: string): Promise { +async function fetchPermissions(token: OperationAuth, environmentId: string): Promise { const op = getOperation('permissions'); const data = await executeDashboardOperation<{ permissionsForEnvironment: { permissions: PermissionNode[] } | null; @@ -71,7 +70,11 @@ async function fetchPermissions(token: string, environmentId: string): Promise

{ +async function requirePermissionBySlug( + token: OperationAuth, + environmentId: string, + slug: string, +): Promise { const permissions = await fetchPermissions(token, environmentId); const permission = permissions.find((candidate) => candidate.slug === slug); if (!permission) { @@ -96,12 +99,10 @@ export interface PermissionEnvironmentOptions { } export async function runPermissionList(options: PermissionEnvironmentOptions = {}): Promise { - const token = await requireCommandToken(); - // Environment-scoped read: the op takes the resolved ID as a variable and it // rides as the environment header. - const { environmentId } = await resolveEnvironmentTarget(token, { - flagValue: options.environmentId, + const { token, environmentId } = await resolveEnvScopedAuth({ + environmentId: options.environmentId, forMutation: false, }); @@ -128,10 +129,8 @@ export async function runPermissionList(options: PermissionEnvironmentOptions = } export async function runPermissionGet(slug: string, options: PermissionEnvironmentOptions = {}): Promise { - const token = await requireCommandToken(); - - const { environmentId } = await resolveEnvironmentTarget(token, { - flagValue: options.environmentId, + const { token, environmentId } = await resolveEnvScopedAuth({ + environmentId: options.environmentId, forMutation: false, }); @@ -217,12 +216,11 @@ export async function runPermissionUpdate(slug: string, options: PermissionUpdat // require-flag: a privilege-surface change; non-interactive callers must pass --yes. await requireConfirmationFlag(options, { action: `update permission ${slug}` }); - const token = await requireCommandToken(); const op = getOperation('updatePermission'); // Environment-scoped mutation: pre-validated resolved target as header. - const { environmentId } = await resolveEnvironmentTarget(token, { - flagValue: options.environmentId, + const { token, environmentId } = await resolveEnvScopedAuth({ + environmentId: options.environmentId, forMutation: op.kind === 'mutation', }); @@ -275,12 +273,11 @@ export async function runPermissionDelete(slug: string, options: PermissionDelet action: `delete permission ${slug} — this permanently removes it from every role that uses it`, }); - const token = await requireCommandToken(); const op = getOperation('deletePermission'); // Environment-scoped mutation: pre-validated resolved target as header. - const { environmentId } = await resolveEnvironmentTarget(token, { - flagValue: options.environmentId, + const { token, environmentId } = await resolveEnvScopedAuth({ + environmentId: options.environmentId, forMutation: op.kind === 'mutation', }); diff --git a/src/commands/role.ts b/src/commands/role.ts index 61ed800a..d172fbce 100644 --- a/src/commands/role.ts +++ b/src/commands/role.ts @@ -29,9 +29,8 @@ */ import chalk from 'chalk'; -import { requireCommandToken } from '../lib/command-auth.js'; -import { resolveEnvironmentTarget } from '../lib/environment-target.js'; -import { runEnvScopedOperation, executeDashboardOperation } from '../lib/dashboard-operation.js'; +import type { OperationAuth } from '../lib/resource-auth.js'; +import { runEnvScopedOperation, executeDashboardOperation, resolveEnvScopedAuth } from '../lib/dashboard-operation.js'; import { getOperation } from '../catalog/operation.js'; import { confirmDestructive, requireConfirmationFlag } from '../catalog/confirm.js'; import { isJsonMode, outputJson, outputSuccess, exitWithError } from '../utils/output.js'; @@ -77,7 +76,7 @@ type ShapedRole = ReturnType; * includes environment roles the organization inherits — org-scoped mutations * must therefore check `type` before acting (see {@link requireOrgScopedRole}). */ -async function fetchRoles(token: string, environmentId: string, orgId: string | undefined): Promise { +async function fetchRoles(token: OperationAuth, environmentId: string, orgId: string | undefined): Promise { if (orgId) { const op = getOperation('rolesForOrganization'); const data = await executeDashboardOperation<{ rolesForOrganization: { roles: RoleNode[] } | null }>(op, { @@ -99,7 +98,7 @@ async function fetchRoles(token: string, environmentId: string, orgId: string | /** Resolve a slug within the scope's role list, or exit not_found. */ async function requireRoleBySlug( - token: string, + token: OperationAuth, environmentId: string, orgId: string | undefined, slug: string, @@ -170,12 +169,10 @@ export interface RoleScopeOptions { } export async function runRoleList(options: RoleScopeOptions = {}): Promise { - const token = await requireCommandToken(); - // Environment-scoped read: both list ops take the resolved ID as a variable // and it rides as the environment header. - const { environmentId } = await resolveEnvironmentTarget(token, { - flagValue: options.environmentId, + const { token, environmentId } = await resolveEnvScopedAuth({ + environmentId: options.environmentId, forMutation: false, }); @@ -193,10 +190,8 @@ export async function runRoleList(options: RoleScopeOptions = {}): Promise } export async function runRoleGet(slug: string, options: RoleScopeOptions = {}): Promise { - const token = await requireCommandToken(); - - const { environmentId } = await resolveEnvironmentTarget(token, { - flagValue: options.environmentId, + const { token, environmentId } = await resolveEnvScopedAuth({ + environmentId: options.environmentId, forMutation: false, }); @@ -266,7 +261,7 @@ export async function runRoleCreate(options: RoleCreateOptions): Promise { * mutation (the list that was sent, or the pre-mutation list when none was). */ async function executeRoleUpdate( - token: string, + token: OperationAuth, environmentId: string, input: { roleId: string; name: string; description?: string; permissions?: string[] }, slug: string, @@ -321,11 +316,9 @@ export async function runRoleUpdate(slug: string, options: RoleUpdateOptions = { // require-flag: a privilege change; non-interactive callers must pass --yes. await requireConfirmationFlag(options, { action: `update role ${slug}` }); - const token = await requireCommandToken(); - // Environment-scoped mutation: pre-validated resolved target as header. - const { environmentId } = await resolveEnvironmentTarget(token, { - flagValue: options.environmentId, + const { token, environmentId } = await resolveEnvScopedAuth({ + environmentId: options.environmentId, forMutation: true, }); @@ -364,12 +357,11 @@ export async function runRoleDelete(slug: string, options: RoleDeleteOptions): P action: `delete role ${slug} — this permanently removes the role and unassigns its members`, }); - const token = await requireCommandToken(); const op = getOperation('deleteRole'); // Environment-scoped mutation: pre-validated resolved target as header. - const { environmentId } = await resolveEnvironmentTarget(token, { - flagValue: options.environmentId, + const { token, environmentId } = await resolveEnvScopedAuth({ + environmentId: options.environmentId, forMutation: op.kind === 'mutation', }); @@ -411,10 +403,8 @@ export async function runRoleSetPermissions( // require-flag: a privilege change; non-interactive callers must pass --yes. await requireConfirmationFlag(options, { action: `replace the permissions on role ${slug}` }); - const token = await requireCommandToken(); - - const { environmentId } = await resolveEnvironmentTarget(token, { - flagValue: options.environmentId, + const { token, environmentId } = await resolveEnvScopedAuth({ + environmentId: options.environmentId, forMutation: true, }); @@ -448,10 +438,8 @@ export async function runRoleAddPermission( // require-flag: a privilege change; non-interactive callers must pass --yes. await requireConfirmationFlag(options, { action: `add permission ${permissionSlug} to role ${slug}` }); - const token = await requireCommandToken(); - - const { environmentId } = await resolveEnvironmentTarget(token, { - flagValue: options.environmentId, + const { token, environmentId } = await resolveEnvScopedAuth({ + environmentId: options.environmentId, forMutation: true, }); @@ -493,10 +481,8 @@ export async function runRoleRemovePermission( // require-flag: a privilege change; non-interactive callers must pass --yes. await requireConfirmationFlag(options, { action: `remove permission ${permissionSlug} from role ${slug}` }); - const token = await requireCommandToken(); - - const { environmentId } = await resolveEnvironmentTarget(token, { - flagValue: options.environmentId, + const { token, environmentId } = await resolveEnvScopedAuth({ + environmentId: options.environmentId, forMutation: true, }); diff --git a/src/lib/api-key-operations/context.ts b/src/lib/api-key-operations/context.ts new file mode 100644 index 00000000..8167bb8b --- /dev/null +++ b/src/lib/api-key-operations/context.ts @@ -0,0 +1,121 @@ +/** + * Shared plumbing for the API-key adapters: an authenticated REST request + * helper and the paging/not-found helpers every resource file uses. + * + * Adapters translate one catalog operation into WorkOS REST calls and return + * the data in the SAME shape the dashboard operation returns, selecting only + * the fields that operation's document selects. The command's existing shaper + * then produces the `--json` output, so both paths emit identical keys and + * casing by construction. Fields the REST API has no source for come back + * `null` (never invented); they are listed in the parity ACCEPTED map. + */ + +import { workosRequest, WorkOSApiError, type WorkOSRequestOptions, type WorkOSListResponse } from '../workos-api.js'; +import type { ApiKeyAuth } from '../resource-auth.js'; +import { exitWithError } from '../../utils/output.js'; +import { formatWorkOSCommand } from '../../utils/command-invocation.js'; + +export type Variables = Record; + +export type RequestOptions = Omit; + +export interface ApiKeyContext { + auth: ApiKeyAuth; + request(options: RequestOptions): Promise; +} + +/** Adapter: catalog-operation variables in, dashboard-shaped data out. */ +export type ApiKeyOperation = (variables: Variables, ctx: ApiKeyContext) => Promise; + +export function createContext(auth: ApiKeyAuth): ApiKeyContext { + return { + auth, + request: (options: RequestOptions) => + workosRequest({ ...options, apiKey: auth.apiKey, baseUrl: auth.baseUrl }), + }; +} + +export function isNotFound(error: unknown): boolean { + return error instanceof WorkOSApiError && error.statusCode === 404; +} + +/** Run a read; a REST 404 resolves to `null` so the command's own not-found branch runs. */ +export async function orNull(read: Promise): Promise { + try { + return await read; + } catch (error) { + if (isNotFound(error)) return null; + throw error; + } +} + +/** The dashboard list envelope: `{ data, listMetadata }`. */ +export function listEnvelope(data: T[], listMetadata?: { before: string | null; after: string | null }) { + return { + data, + listMetadata: { before: listMetadata?.before ?? null, after: listMetadata?.after ?? null }, + }; +} + +/** REST page size used when an operation must return a complete list. */ +const FULL_LIST_PAGE_SIZE = 100; +/** Hard stop for full-list reads, so a bad cursor can never loop forever. */ +const FULL_LIST_MAX_PAGES = 50; + +/** + * Read every page of a REST list. Used where the dashboard operation returns a + * complete, unpaginated list (permissions, an organization's memberships). + */ +export async function listAll( + ctx: ApiKeyContext, + path: string, + params: Record = {}, +): Promise { + const items: T[] = []; + let after: string | undefined; + for (let page = 0; page < FULL_LIST_MAX_PAGES; page++) { + const result = await ctx.request | { data: T[]; list_metadata?: undefined }>({ + method: 'GET', + path, + params: { ...params, limit: FULL_LIST_PAGE_SIZE, ...(after ? { after } : {}) }, + }); + items.push(...(result?.data ?? [])); + after = result?.list_metadata?.after ?? undefined; + if (!after) break; + } + return items; +} + +/** `Asc`/`Desc` (the dashboard pagination enum) → REST `asc`/`desc`. */ +export function restOrder(order: unknown): string | undefined { + return typeof order === 'string' && order !== '' ? order.toLowerCase() : undefined; +} + +export function str(value: unknown): string | undefined { + return typeof value === 'string' && value !== '' ? value : undefined; +} + +export function num(value: unknown): number | undefined { + return typeof value === 'number' && Number.isFinite(value) ? value : undefined; +} + +export function encode(segment: string): string { + return encodeURIComponent(segment); +} + +/** + * Copy for something the API key can't do, naming what's missing. Exported so + * the leak gate can check it; never name internal backends here. + */ +export function apiKeyUnsupportedMessage(missing: string): string { + return ( + `This isn't available with an API key: ${missing}. ` + + `Sign in with \`${formatWorkOSCommand('auth login')}\` and run it without --api-key or WORKOS_API_KEY. ` + + `An unclaimed environment must be claimed first (\`${formatWorkOSCommand('profile claim')}\`).` + ); +} + +/** Exit with a structured `api_key_unsupported` error. Never returns. */ +export function exitApiKeyUnsupported(missing: string): never { + exitWithError({ code: 'api_key_unsupported', message: apiKeyUnsupportedMessage(missing) }); +} diff --git a/src/lib/api-key-operations/index.ts b/src/lib/api-key-operations/index.ts new file mode 100644 index 00000000..79d1e934 --- /dev/null +++ b/src/lib/api-key-operations/index.ts @@ -0,0 +1,95 @@ +/** + * API-key execution for environment-scoped resource commands. + * + * `executeDashboardOperation()` routes here when the invocation runs with an + * API key (see `resource-auth.ts`). Each catalog operation that has a WorkOS + * REST equivalent has an adapter that returns the dashboard operation's data + * shape, so command handlers and their `--json` shapers don't change. An + * operation with no REST equivalent exits with a structured + * `api_key_unsupported` error naming what's missing; nothing is faked. + * + * User-facing copy here follows the no-internal-terms rule enforced by + * `no-graphql-leak.spec.ts`. + */ + +import type { ApiKeyAuth } from '../resource-auth.js'; +import { createApiErrorHandler } from '../api-error-handler.js'; +import { CliExit } from '../../utils/cli-exit.js'; +import { exitWithError } from '../../utils/output.js'; +import { WorkOSApiError } from '../workos-api.js'; +import { + type ApiKeyContext, + type ApiKeyOperation, + type Variables, + createContext, + exitApiKeyUnsupported, +} from './context.js'; +import { organizationOperations } from './organizations.js'; + +const OPERATIONS: Record = { + ...organizationOperations, +}; + +/** + * Operations the WorkOS REST API can't serve, keyed by catalog operation name, + * with what's missing in user-facing terms. + */ +export const API_KEY_UNSUPPORTED: Record = { + logoutUris: 'AuthKit sign-out redirect URIs have no WorkOS API endpoint', + setLogoutUris: 'AuthKit sign-out redirect URIs have no WorkOS API endpoint', + environmentAppBranding: 'AuthKit branding images have no WorkOS API endpoint', + updateAppBranding: 'AuthKit branding images have no WorkOS API endpoint', +}; + +export function hasApiKeyOperation(opName: string): boolean { + return opName in OPERATIONS; +} + +/** What's missing for an operation the API key can't run, in user-facing terms. */ +export function apiKeyUnsupportedReason(opName: string): string { + return API_KEY_UNSUPPORTED[opName] ?? 'this action has no WorkOS API endpoint'; +} + +const handleApiError = createApiErrorHandler('WorkOS API'); + +/** + * Run one catalog operation against the REST API with an API key, returning + * the dashboard operation's data shape. Exits with a structured error on any + * failure; never returns on error. + */ +export async function executeApiKeyOperation( + opName: string, + variables: Variables | undefined, + auth: ApiKeyAuth, +): Promise { + const operation = OPERATIONS[opName]; + if (!operation) exitApiKeyUnsupported(apiKeyUnsupportedReason(opName)); + return withApiKey(auth, (ctx) => operation(variables ?? {}, ctx) as Promise); +} + +/** + * Run REST calls with an API key under the same structured-error contract as + * {@link executeApiKeyOperation}. For the few commands whose REST semantics + * differ enough that they call REST directly (flag targets, homepage URL). + */ +export async function withApiKey(auth: ApiKeyAuth, run: (ctx: ApiKeyContext) => Promise): Promise { + try { + return await run(createContext(auth)); + } catch (error) { + // An adapter's own structured exit is already reported. + if (error instanceof CliExit) throw error; + // Adapters turn the 404s a command reports itself into its not-found + // result; any other 404 keeps the API's own message ("Organization not + // found: 'org_…'"), which names the missing thing. + if (error instanceof WorkOSApiError && error.statusCode === 404) { + exitWithError({ + code: 'not_found', + message: error.message || 'Not found.', + apiContext: { status: 404, code: error.code ?? 'not_found' }, + }); + } + handleApiError(error); + } +} + +export { exitApiKeyUnsupported, apiKeyUnsupportedMessage } from './context.js'; diff --git a/src/lib/api-key-operations/organizations.ts b/src/lib/api-key-operations/organizations.ts new file mode 100644 index 00000000..851be400 --- /dev/null +++ b/src/lib/api-key-operations/organizations.ts @@ -0,0 +1,194 @@ +/** + * API-key adapters for `workos organization` and `workos org-domain`, backed by + * the WorkOS REST API (`/organizations`, `/organization_domains`). + * + * Fields the REST API has no source for (`usersCount`, a domain's + * `subdomain`/`verificationContent`/`domainCaptureEnabled`) are returned + * `null` rather than invented. + */ + +import type { WorkOSListResponse } from '../workos-api.js'; +import { type ApiKeyOperation, encode, listEnvelope, num, orNull, restOrder, str } from './context.js'; + +export interface RestOrganizationDomain { + object?: 'organization_domain'; + id: string; + organization_id?: string; + domain: string; + state?: string | null; + verification_strategy?: string | null; + verification_token?: string | null; + verification_prefix?: string | null; + created_at?: string; + updated_at?: string; +} + +export interface RestOrganization { + object?: 'organization'; + id: string; + name: string; + domains?: RestOrganizationDomain[]; + metadata?: Record | null; + external_id?: string | null; + allow_profiles_outside_organization?: boolean; + stripe_customer_id?: string; + created_at?: string; + updated_at?: string; +} + +/** Object map → the `[{ key, value }]` pairs the dashboard operation returns. */ +export function metadataPairs(metadata: Record | null | undefined) { + return Object.entries(metadata ?? {}).map(([key, value]) => ({ key, value })); +} + +/** A REST organization domain in the dashboard `OrganizationDomain` selection. */ +export function domainNode(domain: RestOrganizationDomain) { + return { + id: domain.id, + domain: domain.domain, + state: domain.state ?? null, + subdomain: null, + verificationContent: null, + verificationStrategy: domain.verification_strategy ?? null, + }; +} + +/** A REST organization in the dashboard `Organization` fragment's selection. */ +function organizationNode(org: RestOrganization) { + return { + id: org.id, + name: org.name ?? null, + createdAt: org.created_at ?? null, + allowProfilesOutsideOrganization: org.allow_profiles_outside_organization ?? null, + usersCount: null, + externalId: org.external_id ?? null, + metadata: metadataPairs(org.metadata), + domains: (org.domains ?? []).map((domain) => ({ ...domainNode(domain), domainCaptureEnabled: null })), + }; +} + +/** `domain[]` + one shared verified flag (the dashboard input) → REST `domain_data`. */ +function domainData(variables: { domains?: unknown; domainsDeveloperVerified?: unknown }) { + if (!Array.isArray(variables.domains)) return undefined; + const state = variables.domainsDeveloperVerified === false ? 'pending' : 'verified'; + return variables.domains.map((domain) => ({ domain: String(domain), state })); +} + +export const organizationOperations: Record = { + async organizations(variables, ctx) { + // The CLI's only search input is `--domain`, so it maps onto REST's + // domain filter (an exact domain match). + const domain = str(variables.search); + const page = await ctx.request>({ + method: 'GET', + path: '/organizations', + params: { + limit: num(variables.limit), + before: str(variables.before), + after: str(variables.after), + order: restOrder(variables.order), + domains: domain, + }, + }); + return { organizations: listEnvelope((page?.data ?? []).map(organizationNode), page?.list_metadata) }; + }, + + async organization(variables, ctx) { + const org = await orNull( + ctx.request({ method: 'GET', path: `/organizations/${encode(String(variables.id))}` }), + ); + return { organization: org ? organizationNode(org) : null }; + }, + + async createOrganization(variables, ctx) { + const input = (variables.input ?? {}) as { name?: unknown; domains?: unknown; domainsDeveloperVerified?: unknown }; + const domains = domainData(input); + const org = await ctx.request({ + method: 'POST', + path: '/organizations', + body: { name: input.name, ...(domains ? { domain_data: domains } : {}) }, + }); + // The create operation selects only id, name and domains. + return { + createOrganization: { + __typename: 'OrganizationCreated', + organization: { id: org.id, name: org.name ?? null, domains: (org.domains ?? []).map(domainNode) }, + }, + }; + }, + + async updateOrganization(variables, ctx) { + const domains = domainData(variables); + const org = await ctx.request({ + method: 'PUT', + path: `/organizations/${encode(String(variables.id))}`, + body: { + ...(variables.name !== undefined ? { name: variables.name } : {}), + ...(domains ? { domain_data: domains } : {}), + }, + }); + // The update operation selects only id, name and each domain's id/domain/state. + return { + updateOrganization: { + __typename: 'UpdateOrganizationPayload', + organization: { + id: org.id, + name: org.name ?? null, + domains: (org.domains ?? []).map((d) => ({ id: d.id, domain: d.domain, state: d.state ?? null })), + }, + }, + }; + }, + + async deleteOrganization(variables, ctx) { + const { organizationId } = (variables.input ?? {}) as { organizationId?: unknown }; + await ctx.request({ method: 'DELETE', path: `/organizations/${encode(String(organizationId))}` }); + return { deleteOrganization: { organization: { id: organizationId } } }; + }, + + // --- org-domain --------------------------------------------------------------- + + async addDomains(variables, ctx) { + const input = (variables.input ?? {}) as { organizationId?: unknown; domains?: unknown }; + const domains = Array.isArray(input.domains) ? input.domains.map(String) : []; + const created: RestOrganizationDomain[] = []; + for (const domain of domains) { + created.push( + await ctx.request({ + method: 'POST', + path: '/organization_domains', + body: { organization_id: input.organizationId, domain }, + }), + ); + } + // The add operation selects id, state, domain and verificationStrategy. + return { + addDomains: { + __typename: 'DomainsAdded', + domains: created.map((d) => ({ + id: d.id, + state: d.state ?? null, + domain: d.domain, + verificationStrategy: d.verification_strategy ?? null, + })), + }, + }; + }, + + async restartOrganizationDomainVerification(variables, ctx) { + const domain = await ctx.request({ + method: 'POST', + path: `/organization_domains/${encode(String(variables.id))}/verify`, + }); + return { + restartOrganizationDomainVerification: domain + ? { ...domainNode(domain), domainCaptureEnabled: null } + : { id: variables.id }, + }; + }, + + async deleteOrganizationDomain(variables, ctx) { + await ctx.request({ method: 'DELETE', path: `/organization_domains/${encode(String(variables.id))}` }); + return { deleteOrganizationDomain: { id: variables.id } }; + }, +}; diff --git a/src/lib/command-auth.spec.ts b/src/lib/command-auth.spec.ts index 4834955d..0985d598 100644 --- a/src/lib/command-auth.spec.ts +++ b/src/lib/command-auth.spec.ts @@ -67,6 +67,8 @@ const { getCliAuthClientId } = await import('./settings.js'); const { formatWorkOSCommand } = await import('../utils/command-invocation.js'); const { CliExit } = await import('../utils/cli-exit.js'); const { refreshIfExpired, requireCommandToken, DASHBOARD_ERROR_MESSAGES } = await import('./command-auth.js'); +const { saveConfig, clearConfig, setInsecureConfigStorage } = await import('./config-store.js'); +const { resolveResourceApiKey, setResourceApiKeyFlag } = await import('./resource-auth.js'); async function expectAuthExit(promise: Promise): Promise { try { @@ -278,7 +280,7 @@ describe('command-auth', () => { expect(err).toContain(`\`${formatWorkOSCommand('api')}\``); }); - it('adds the API-key caveat to the transient-failure copy when WORKOS_API_KEY is set', async () => { + it('says resource commands run with an API key in the transient-failure copy when WORKOS_API_KEY is set', async () => { vi.stubEnv('WORKOS_API_KEY', 'sk_test_x'); saveCredentials(expiredCreds); mockRefreshAccessToken.mockResolvedValue({ success: false, errorType: 'network', error: 'Network error' }); @@ -289,7 +291,10 @@ describe('command-auth', () => { const err = consoleErrors.join('\n'); expect(err).toContain(DASHBOARD_ERROR_MESSAGES.refreshFailedApiKeySet); expect(err).toContain('WORKOS_API_KEY'); - expect(err).toContain('does not accept API keys'); + // Resource commands now accept the key; the copy must not claim otherwise. + expect(err).not.toContain('does not accept API keys'); + expect(err).toContain(`\`${formatWorkOSCommand('organization')}\``); + expect(err).toContain('needs a dashboard login'); expect(err).not.toContain('Not logged in'); }); @@ -304,7 +309,7 @@ describe('command-auth', () => { expect(mockRefreshAccessToken).not.toHaveBeenCalled(); }); - it('explains that API keys do not work here when WORKOS_API_KEY is set', async () => { + it('explains which commands run with an API key when WORKOS_API_KEY is set', async () => { vi.stubEnv('WORKOS_API_KEY', 'sk_test_x'); await expectAuthExit(requireCommandToken()); @@ -312,12 +317,91 @@ describe('command-auth', () => { const err = consoleErrors.join('\n'); expect(err).toContain(DASHBOARD_ERROR_MESSAGES.authRequiredApiKeySet); expect(err).toContain('WORKOS_API_KEY'); - expect(err).toContain('does not accept API keys'); + // Resource commands now accept the key; the copy must not claim otherwise. + expect(err).not.toContain('does not accept API keys'); + expect(err).toContain(`\`${formatWorkOSCommand('organization')}\``); + expect(err).toContain(`\`${formatWorkOSCommand('user')}\``); + expect(err).toContain('needs a dashboard login'); expect(err).toContain(`\`${formatWorkOSCommand('auth login')}\``); expect(err).toContain(`\`${formatWorkOSCommand('api')}\``); }); }); + describe('resolveResourceApiKey', () => { + const unclaimedProfile = { + name: 'unclaimed', + type: 'unclaimed' as const, + apiKey: 'sk_test_unclaimed', + clientId: 'client_unclaimed', + claimToken: 'claim_token', + }; + const claimedProfile = { name: 'sandbox', type: 'sandbox' as const, apiKey: 'sk_test_claimed' }; + + function activate(profile: typeof unclaimedProfile | typeof claimedProfile): void { + saveConfig({ activeEnvironment: profile.name, environments: { [profile.name]: profile } }); + } + + beforeEach(() => { + setInsecureConfigStorage(true); + setResourceApiKeyFlag(undefined); + vi.stubEnv('WORKOS_API_URL', ''); + vi.stubEnv('WORKOS_API_BASE_URL', ''); + }); + + afterEach(() => { + setResourceApiKeyFlag(undefined); + clearConfig(); + }); + + it('stays on the dashboard session with no key and a claimed profile, even one with an API key stored', () => { + activate(claimedProfile); + saveCredentials(validCreds); + + expect(resolveResourceApiKey()).toBeNull(); + }); + + it('uses the unclaimed profile key with an API key stored on an unclaimed active profile', () => { + activate(unclaimedProfile); + + expect(resolveResourceApiKey()).toEqual({ + kind: 'api-key', + apiKey: 'sk_test_unclaimed', + baseUrl: 'https://api.workos.com', + source: 'unclaimed-profile', + }); + }); + + it('prefers an explicit WORKOS_API_KEY over the session with an API key in the environment', () => { + activate(claimedProfile); + saveCredentials(validCreds); + vi.stubEnv('WORKOS_API_KEY', 'sk_test_env'); + + expect(resolveResourceApiKey()).toMatchObject({ apiKey: 'sk_test_env', source: 'env' }); + }); + + it('prefers WORKOS_API_KEY over an unclaimed profile key with an API key in the environment', () => { + activate(unclaimedProfile); + vi.stubEnv('WORKOS_API_KEY', 'sk_test_env'); + + expect(resolveResourceApiKey()).toMatchObject({ apiKey: 'sk_test_env', source: 'env' }); + }); + + it('lets the --api-key flag win over everything with an API key passed explicitly', () => { + activate(unclaimedProfile); + vi.stubEnv('WORKOS_API_KEY', 'sk_test_env'); + setResourceApiKeyFlag('sk_test_flag'); + + expect(resolveResourceApiKey()).toMatchObject({ apiKey: 'sk_test_flag', source: 'flag' }); + }); + + it('returns null with an API key flag that is blank', () => { + activate(claimedProfile); + setResourceApiKeyFlag(' '); + + expect(resolveResourceApiKey()).toBeNull(); + }); + }); + describe('DASHBOARD_ERROR_MESSAGES', () => { it('exposes plain strings through Object.entries (leak-gate contract)', () => { const entries = Object.entries(DASHBOARD_ERROR_MESSAGES); @@ -328,6 +412,15 @@ describe('command-auth', () => { } }); + it('no API-key-set variant says the resource commands reject keys, now that they run with an API key', () => { + for (const key of ['authRequiredApiKeySet', 'refreshFailedApiKeySet'] as const) { + const message = DASHBOARD_ERROR_MESSAGES[key]; + expect(message, key).not.toMatch(/does not accept API keys|reject/i); + expect(message, key).toContain(`\`${formatWorkOSCommand('organization')}\``); + expect(message, key).toContain('run with the API key'); + } + }); + it('every auth-required variant names both escape hatches', () => { const login = `\`${formatWorkOSCommand('auth login')}\``; const api = `\`${formatWorkOSCommand('api')}\``; diff --git a/src/lib/command-auth.ts b/src/lib/command-auth.ts index 41cde4e6..7a0e70db 100644 --- a/src/lib/command-auth.ts +++ b/src/lib/command-auth.ts @@ -10,6 +10,13 @@ * login flow (or exit 4 when prompting isn't allowed). * - Resource commands (`requireCommandToken()` here) always exit 4 with a * structured error — they never open a browser. + * + * Environment-scoped resource commands (`organization`, `user`, `role`, …) + * only reach `requireCommandToken()` when no API key applies: with + * `--api-key`, `WORKOS_API_KEY` or an unclaimed active profile they run on the + * REST API instead (see `resource-auth.ts`). So the `*ApiKeySet` copy below is + * in practice shown by the account-plane commands (`team`, `project`, + * `environment`, `whoami`), which have no API-key equivalent. */ import { @@ -53,14 +60,16 @@ export const DASHBOARD_ERROR_MESSAGES: Record< ); }, /** - * Same as `authRequired`, but WORKOS_API_KEY is set — the one failure mode - * that must be self-explanatory: these commands act as the logged-in - * dashboard user and do not accept API keys. + * Same as `authRequired`, but WORKOS_API_KEY is set. Resource commands use + * the key, so this is reached by the account-plane commands, which manage + * the dashboard account itself and need a login: say which is which. */ get authRequiredApiKeySet() { return ( - 'Not logged in. WORKOS_API_KEY is set, but this command uses your WorkOS dashboard session ' + - `and does not accept API keys. Run \`${formatWorkOSCommand('auth login')}\` to authenticate, ` + + 'Not logged in. WORKOS_API_KEY is set, but this command manages your WorkOS dashboard account ' + + '(team, projects, environments) and needs a dashboard login. ' + + `Resource commands such as \`${formatWorkOSCommand('organization')}\` and \`${formatWorkOSCommand('user')}\` run with the API key. ` + + `Run \`${formatWorkOSCommand('auth login')}\` to authenticate, ` + `or use \`${formatWorkOSCommand('api')}\` for API-key requests.` ); }, @@ -72,11 +81,12 @@ export const DASHBOARD_ERROR_MESSAGES: Record< `or use \`${formatWorkOSCommand('api')}\` for API-key requests.` ); }, - /** Transient refresh failure while WORKOS_API_KEY is set: same, plus the API-key caveat. */ + /** Transient refresh failure while WORKOS_API_KEY is set: same, plus which commands the key covers. */ get refreshFailedApiKeySet() { return ( 'Could not refresh your session (network or server error). Your saved login was kept. ' + - 'WORKOS_API_KEY is set, but this command uses your WorkOS dashboard session and does not accept API keys. ' + + 'WORKOS_API_KEY is set, but this command manages your WorkOS dashboard account and needs a dashboard login. ' + + `Resource commands such as \`${formatWorkOSCommand('organization')}\` and \`${formatWorkOSCommand('user')}\` run with the API key. ` + `Try again, run \`${formatWorkOSCommand('auth login')}\` to re-authenticate, ` + `or use \`${formatWorkOSCommand('api')}\` for API-key requests.` ); diff --git a/src/lib/dashboard-operation.ts b/src/lib/dashboard-operation.ts index 390e3518..0e737835 100644 --- a/src/lib/dashboard-operation.ts +++ b/src/lib/dashboard-operation.ts @@ -15,6 +15,12 @@ * - {@link executeDashboardOperation} — request + structured-error exit only, * for flows that resolve their token/environment once and run several * operations against it (read-then-mutate helpers). + * + * Environment-scoped operations can also run with an API key (see + * `resource-auth.ts` for when): {@link resolveEnvScopedAuth} returns the key + * instead of a bearer, and {@link executeDashboardOperation} routes the + * operation to its REST adapter (`api-key-operations/`), which returns the same + * data shape. Team-scoped operations stay session-only. */ import { requireCommandToken } from './command-auth.js'; @@ -22,9 +28,26 @@ import { dashboardGraphqlRequest, dashboardGraphqlUpload, type DashboardUploadFi import { resolveEnvironmentTarget } from './environment-target.js'; import { getOperation, resolveExecutableDocument, reportDashboardError } from '../catalog/operation.js'; import type { CatalogOperation } from '../catalog/catalog-types.js'; +import { + API_KEY_ENVIRONMENT_ID, + isApiKeyAuth, + resolveResourceApiKey, + type ApiKeyAuth, + type OperationAuth, +} from './resource-auth.js'; +import { apiKeyUnsupportedReason, executeApiKeyOperation, exitApiKeyUnsupported } from './api-key-operations/index.js'; +import { exitWithError } from '../utils/output.js'; +import { formatWorkOSCommand } from '../utils/command-invocation.js'; type Variables = Record; +/** + * Environment-scoped operations behind account-plane commands (`environment + * create|rename`). Like the team-scoped ones, they act on the dashboard + * account and stay session-only even when an API key is present. + */ +const SESSION_ONLY_OPERATIONS = new Set(['createEnvironment', 'renameEnvironment']); + export interface EnvScopedOptions { /** `--environment-id` override; defaults from the active profile. */ environmentId?: string; @@ -36,21 +59,68 @@ export interface EnvScopedResult { data: T; /** The resolved target — for operations that also take it as a variable. */ environmentId: string; - /** For follow-up requests within the same invocation. */ - token: string; + /** For follow-up requests within the same invocation (a bearer, or the API key). */ + token: OperationAuth; op: CatalogOperation; } +/** Why `--environment-id` can't be combined with an API key, per key source. */ +function environmentFlagConflict(auth: ApiKeyAuth): string { + if (auth.source === 'unclaimed-profile') { + return ( + '--environment-id cannot be used while the active profile is an unclaimed environment: ' + + `its API key already decides the environment. Run \`${formatWorkOSCommand('profile switch')}\` to use another profile.` + ); + } + return ( + '--environment-id cannot be combined with an API key: the key already decides the environment. ' + + 'Drop --environment-id, or remove --api-key / WORKOS_API_KEY to use your dashboard login.' + ); +} + +/** + * Resolve the credential and target for an environment-scoped operation. + * + * API-key path: the key IS the environment, so there is nothing to resolve; + * an explicit `--environment-id` is refused rather than silently ignored. + * Session path: unchanged — a usable bearer plus the validated target. + */ +export async function resolveEnvScopedAuth(options: { + environmentId?: string; + forMutation: boolean; + /** Skip the API-key path (account-plane operations). */ + sessionOnly?: boolean; +}): Promise<{ token: OperationAuth; environmentId: string }> { + const apiKey = options.sessionOnly ? null : resolveResourceApiKey(); + if (apiKey) { + if (options.environmentId?.trim()) { + exitWithError({ code: 'invalid_argument', message: environmentFlagConflict(apiKey) }); + } + return { token: apiKey, environmentId: API_KEY_ENVIRONMENT_ID }; + } + + const token = await requireCommandToken(); + const { environmentId } = await resolveEnvironmentTarget(token, { + flagValue: options.environmentId, + forMutation: options.forMutation, + }); + return { token, environmentId }; +} + /** * Execute one operation with an already-resolved token/environment, translating * any transport/server failure into a structured exit. */ export async function executeDashboardOperation( op: CatalogOperation, - options: { token: string; variables?: Variables; environmentId?: string }, + options: { token: OperationAuth; variables?: Variables; environmentId?: string }, ): Promise { + const { token } = options; + if (isApiKeyAuth(token)) { + return executeApiKeyOperation(op.name, options.variables, token); + } try { - return await dashboardGraphqlRequest(resolveExecutableDocument(op), options); + return await dashboardGraphqlRequest(resolveExecutableDocument(op), { ...options, token }); } catch (error) { reportDashboardError(error); } @@ -63,10 +133,13 @@ export async function executeDashboardOperation( */ export async function executeDashboardUpload( op: CatalogOperation, - options: { token: string; variables?: Variables; environmentId?: string; files: DashboardUploadFile[] }, + options: { token: OperationAuth; variables?: Variables; environmentId?: string; files: DashboardUploadFile[] }, ): Promise { + const { token } = options; + // File uploads exist only for dashboard-managed assets (branding images). + if (isApiKeyAuth(token)) exitApiKeyUnsupported(apiKeyUnsupportedReason(op.name)); try { - return await dashboardGraphqlUpload(resolveExecutableDocument(op), options); + return await dashboardGraphqlUpload(resolveExecutableDocument(op), { ...options, token }); } catch (error) { reportDashboardError(error); } @@ -84,11 +157,11 @@ export async function runEnvScopedOperation( options: EnvScopedOptions, variables?: Variables | ((environmentId: string) => Variables), ): Promise> { - const token = await requireCommandToken(); const op = getOperation(opName); - const { environmentId } = await resolveEnvironmentTarget(token, { - flagValue: options.environmentId, + const { token, environmentId } = await resolveEnvScopedAuth({ + environmentId: options.environmentId, forMutation: options.forMutation ?? op.kind === 'mutation', + sessionOnly: SESSION_ONLY_OPERATIONS.has(opName), }); const data = await executeDashboardOperation(op, { token, diff --git a/src/lib/resource-auth.ts b/src/lib/resource-auth.ts new file mode 100644 index 00000000..b385c5a8 --- /dev/null +++ b/src/lib/resource-auth.ts @@ -0,0 +1,82 @@ +/** + * Which credential an environment-scoped resource command (`organization`, + * `user`, `role`, …) runs with: the dashboard session, or an API key. + * + * Precedence (first match wins): + * 1. `--api-key` flag + * 2. `WORKOS_API_KEY` + * 3. the active profile's stored key, but ONLY when that profile is an + * unclaimed environment (a dashboard session can't reach an unclaimed + * environment, so its key is the only credential that works there) + * 4. otherwise the existing dashboard-session path, unchanged + * + * A claimed profile's stored key never switches the path: signed-in users keep + * today's behavior unless they pass a key explicitly. Resolution reuses + * `resolveOptionalApiKey()` so these commands accept exactly the flag and env + * var `workos api` and the still-REST commands do. + * + * Team-scoped account-plane commands (`team`, `project`, `environment`, + * `whoami`) don't consult this module: they have no API-key equivalent. + */ + +import { getActiveEnvironment, isUnclaimedEnvironment } from './config-store.js'; +import { resolveApiBaseUrl, resolveOptionalApiKey } from './api-key.js'; + +export type ApiKeySource = 'flag' | 'env' | 'unclaimed-profile'; + +/** + * Stand-in target for the API-key path, where the key itself selects the + * environment and no dashboard environment ID is known. Internal only: it + * keys per-environment state inside one invocation (feature-flag state) and + * is never sent anywhere. + */ +export const API_KEY_ENVIRONMENT_ID = 'environment_of_api_key'; + +export interface ApiKeyAuth { + kind: 'api-key'; + apiKey: string; + baseUrl: string; + source: ApiKeySource; +} + +/** + * The credential an operation runs with: a dashboard bearer token (string, the + * long-standing shape every call site already passes) or an API key. + */ +export type OperationAuth = string | ApiKeyAuth; + +export function isApiKeyAuth(auth: OperationAuth): auth is ApiKeyAuth { + return typeof auth !== 'string'; +} + +let apiKeyFlag: string | undefined; + +/** + * Record the `--api-key` flag for this invocation. Set from a command-group + * middleware in bin.ts, so every subcommand handler picks it up without + * threading the value through each options object. + */ +export function setResourceApiKeyFlag(value: string | undefined): void { + apiKeyFlag = typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined; +} + +/** + * The API key this invocation should use, or `null` to stay on the dashboard + * session path. See the module comment for the precedence rule. + */ +export function resolveResourceApiKey(): ApiKeyAuth | null { + let source: ApiKeySource | undefined; + if (apiKeyFlag) { + source = 'flag'; + } else if (process.env.WORKOS_API_KEY) { + source = 'env'; + } else { + const active = getActiveEnvironment(); + if (active && isUnclaimedEnvironment(active) && active.apiKey) source = 'unclaimed-profile'; + } + if (!source) return null; + + const apiKey = resolveOptionalApiKey({ apiKey: apiKeyFlag }); + if (!apiKey) return null; + return { kind: 'api-key', apiKey, baseUrl: resolveApiBaseUrl(), source }; +} diff --git a/src/utils/help-json.ts b/src/utils/help-json.ts index e1995086..0d54db6b 100644 --- a/src/utils/help-json.ts +++ b/src/utils/help-json.ts @@ -66,6 +66,15 @@ const apiKeyOpt: OptionSchema = { hidden: false, }; +/** `--api-key` on the dashboard-plane resource commands (mirrors bin.ts `resourceApiKeyOption`). */ +const resourceApiKeyOpt: OptionSchema = { + name: 'api-key', + type: 'string', + description: 'WorkOS API key (runs the command with this key instead of your dashboard login)', + required: false, + hidden: false, +}; + const environmentIdOpt: OptionSchema = { name: 'environment-id', type: 'string', @@ -258,7 +267,7 @@ const commands: CommandSchema[] = [ name: 'authkit', description: 'Manage AuthKit app config (redirect URIs, CORS, logout URIs, branding) on the dashboard account plane', - options: [insecureStorageOpt], + options: [insecureStorageOpt, resourceApiKeyOpt], commands: [ { name: 'redirect-uris', @@ -416,7 +425,7 @@ const commands: CommandSchema[] = [ { name: 'branding', description: 'Manage branding images (logo, icon, favicon) for an environment', - options: [insecureStorageOpt], + options: [insecureStorageOpt, resourceApiKeyOpt], commands: [ { name: 'get', @@ -924,7 +933,7 @@ const commands: CommandSchema[] = [ { name: 'organization', description: 'Manage WorkOS organizations (create, update, get, list, delete) in the active environment', - options: [insecureStorageOpt], + options: [insecureStorageOpt, resourceApiKeyOpt], commands: [ { name: 'create', @@ -983,7 +992,7 @@ const commands: CommandSchema[] = [ { name: 'user', description: 'Manage AuthKit users (get, list, update, delete) in the active environment', - options: [insecureStorageOpt], + options: [insecureStorageOpt, resourceApiKeyOpt], commands: [ { name: 'get', @@ -1039,6 +1048,7 @@ const commands: CommandSchema[] = [ description: 'Manage roles in the active environment (environment and organization-scoped)', options: [ insecureStorageOpt, + resourceApiKeyOpt, { name: 'org', type: 'string', @@ -1122,7 +1132,7 @@ const commands: CommandSchema[] = [ { name: 'permission', description: 'Manage permissions in the active environment', - options: [insecureStorageOpt], + options: [insecureStorageOpt, resourceApiKeyOpt], commands: [ { name: 'list', description: 'List permissions', options: [environmentIdOpt] }, { @@ -1170,7 +1180,7 @@ const commands: CommandSchema[] = [ { name: 'membership', description: 'Manage organization memberships in the active environment', - options: [insecureStorageOpt], + options: [insecureStorageOpt, resourceApiKeyOpt], commands: [ { name: 'list', @@ -1271,7 +1281,7 @@ const commands: CommandSchema[] = [ { name: 'invitation', description: 'Manage user invitations in the active environment', - options: [insecureStorageOpt], + options: [insecureStorageOpt, resourceApiKeyOpt], commands: [ { name: 'list', @@ -1349,7 +1359,7 @@ const commands: CommandSchema[] = [ { name: 'session', description: 'Manage user sessions in the active environment', - options: [insecureStorageOpt], + options: [insecureStorageOpt, resourceApiKeyOpt], commands: [ { name: 'list', @@ -1539,7 +1549,7 @@ const commands: CommandSchema[] = [ { name: 'event', description: 'Query WorkOS events', - options: [insecureStorageOpt], + options: [insecureStorageOpt, resourceApiKeyOpt], commands: [ { name: 'list', @@ -1628,7 +1638,7 @@ const commands: CommandSchema[] = [ { name: 'feature-flag', description: 'Manage feature flags in the active environment', - options: [insecureStorageOpt], + options: [insecureStorageOpt, resourceApiKeyOpt], commands: [ { name: 'list', description: 'List feature flags', options: [...paginationOpts, environmentIdOpt] }, { @@ -1672,7 +1682,7 @@ const commands: CommandSchema[] = [ { name: 'webhook', description: 'Manage webhooks', - options: [insecureStorageOpt], + options: [insecureStorageOpt, resourceApiKeyOpt], commands: [ { name: 'list', description: 'List webhook endpoints', options: [environmentIdOpt] }, { @@ -1695,7 +1705,7 @@ const commands: CommandSchema[] = [ { name: 'config', description: 'Manage AuthKit app configuration (redirect URIs, CORS, homepage)', - options: [insecureStorageOpt], + options: [insecureStorageOpt, resourceApiKeyOpt], commands: [ { name: 'redirect', @@ -1740,7 +1750,7 @@ const commands: CommandSchema[] = [ { name: 'portal', description: 'Manage Admin Portal', - options: [insecureStorageOpt], + options: [insecureStorageOpt, resourceApiKeyOpt], commands: [ { name: 'generate-link', @@ -1914,7 +1924,7 @@ const commands: CommandSchema[] = [ { name: 'org-domain', description: 'Manage organization domains', - options: [insecureStorageOpt], + options: [insecureStorageOpt, resourceApiKeyOpt], commands: [ { name: 'get', From 62d618f1ec1d53ff9a678aea64d85fc5d306f027 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 12:25:02 -0800 Subject: [PATCH 02/32] feat: run user and session commands with an API key REST adapters for user list/get/update/delete and session list/revoke. Identities come from the user's organization memberships, with role IDs and names resolved from their slugs; user get adds auth factors. Fields REST has no source for (sessionCount, hasPassword, emailVerifiedAt, a factor's lastVerifiedAt) are null rather than invented; the human view still reports verification from REST's email_verified flag. --- src/commands/user.ts | 6 +- src/lib/api-key-operations/index.ts | 2 + src/lib/api-key-operations/lookups.ts | 122 ++++++++++++ src/lib/api-key-operations/users.ts | 258 ++++++++++++++++++++++++++ 4 files changed, 386 insertions(+), 2 deletions(-) create mode 100644 src/lib/api-key-operations/lookups.ts create mode 100644 src/lib/api-key-operations/users.ts diff --git a/src/commands/user.ts b/src/commands/user.ts index 17b558f6..a6f0915b 100644 --- a/src/commands/user.ts +++ b/src/commands/user.ts @@ -40,6 +40,8 @@ interface UserNode { lastName?: string | null; createdAt?: string | null; emailVerifiedAt?: string | null; + /** API-key path only: REST reports verification as a boolean, with no timestamp. Not in `--json`. */ + emailVerified?: boolean | null; lastSignedInAt?: string | null; sessionCount?: number | null; hasPassword?: boolean | null; @@ -113,7 +115,7 @@ export async function runUserGet(userId: string, options: UserGetOptions = {}): ['ID', user.id], ['Email', user.email], ['Name', [user.firstName, user.lastName].filter(Boolean).join(' ') || null], - ['Verified', user.emailVerifiedAt ? 'Yes' : 'No'], + ['Verified', user.emailVerifiedAt || data.userlandUser.emailVerified ? 'Yes' : 'No'], ['Created', user.createdAt], ['Last sign-in', user.lastSignedInAt], ['External ID', user.externalId], @@ -169,7 +171,7 @@ export async function runUserList(options: UserListOptions = {}): Promise user.email ?? chalk.dim('—'), user.firstName || chalk.dim('-'), user.lastName || chalk.dim('-'), - user.emailVerifiedAt ? 'Yes' : 'No', + user.emailVerifiedAt || user.emailVerified ? 'Yes' : 'No', ]); console.log( formatTable( diff --git a/src/lib/api-key-operations/index.ts b/src/lib/api-key-operations/index.ts index 79d1e934..880e66b8 100644 --- a/src/lib/api-key-operations/index.ts +++ b/src/lib/api-key-operations/index.ts @@ -25,9 +25,11 @@ import { exitApiKeyUnsupported, } from './context.js'; import { organizationOperations } from './organizations.js'; +import { userOperations } from './users.js'; const OPERATIONS: Record = { ...organizationOperations, + ...userOperations, }; /** diff --git a/src/lib/api-key-operations/lookups.ts b/src/lib/api-key-operations/lookups.ts new file mode 100644 index 00000000..4c571324 --- /dev/null +++ b/src/lib/api-key-operations/lookups.ts @@ -0,0 +1,122 @@ +/** + * Extra REST reads that fill fields the dashboard returns inline but REST + * returns only as IDs or slugs: role IDs/names behind membership role slugs, + * and organization names behind `organization_id`. Memoized per adapter call + * (one context), so a page of results costs one read per distinct key. + */ + +import type { WorkOSListResponse } from '../workos-api.js'; +import { type ApiKeyContext, encode, listAll, orNull } from './context.js'; + +export interface RestRole { + object?: 'role'; + id: string; + name: string; + slug: string; + description?: string | null; + type?: string; + resource_type_slug?: string; + permissions?: string[]; + created_at?: string; + updated_at?: string; +} + +interface Memo { + environmentRoles?: Promise; + organizationRoles: Map>; + organizationNames: Map>; +} + +const memos = new WeakMap(); + +function memoFor(ctx: ApiKeyContext): Memo { + let memo = memos.get(ctx); + if (!memo) { + memo = { organizationRoles: new Map(), organizationNames: new Map() }; + memos.set(ctx, memo); + } + return memo; +} + +export function environmentRoles(ctx: ApiKeyContext): Promise { + const memo = memoFor(ctx); + memo.environmentRoles ??= ctx + .request<{ data: RestRole[] }>({ method: 'GET', path: '/authorization/roles' }) + .then((result) => result?.data ?? []); + return memo.environmentRoles; +} + +/** Roles assignable in an organization (its own roles plus the environment roles it inherits). */ +export function organizationRoles(ctx: ApiKeyContext, organizationId: string): Promise { + const memo = memoFor(ctx); + let roles = memo.organizationRoles.get(organizationId); + if (!roles) { + roles = ctx + .request<{ data: RestRole[] }>({ + method: 'GET', + path: `/authorization/organizations/${encode(organizationId)}/roles`, + }) + .then((result) => result?.data ?? []); + memo.organizationRoles.set(organizationId, roles); + } + return roles; +} + +/** Find a role by ID (or slug) among the environment roles, then the organization's. */ +export async function findRole( + ctx: ApiKeyContext, + match: { id?: string; slug?: string }, + organizationId?: string | null, +): Promise { + const matches = (role: RestRole) => (match.id ? role.id === match.id : role.slug === match.slug); + const fromEnvironment = (await environmentRoles(ctx)).find(matches); + if (fromEnvironment || !organizationId) return fromEnvironment; + return (await organizationRoles(ctx, organizationId)).find(matches); +} + +/** An organization's name, or `null` when it can't be read. */ +export function organizationName(ctx: ApiKeyContext, organizationId: string): Promise { + const memo = memoFor(ctx); + let name = memo.organizationNames.get(organizationId); + if (!name) { + name = orNull( + ctx.request<{ name?: string }>({ method: 'GET', path: `/organizations/${encode(organizationId)}` }), + ).then((org) => org?.name ?? null); + memo.organizationNames.set(organizationId, name); + } + return name; +} + +/** Map with bounded concurrency, preserving order. */ +export async function mapLimit(items: T[], limit: number, fn: (item: T) => Promise): Promise { + const results: R[] = new Array(items.length); + let next = 0; + const workers = Array.from({ length: Math.min(limit, items.length) }, async () => { + while (next < items.length) { + const index = next++; + results[index] = await fn(items[index]); + } + }); + await Promise.all(workers); + return results; +} + +export interface RestMembership { + object?: 'organization_membership'; + id: string; + user_id: string; + organization_id: string; + organization_name?: string | null; + status?: string | null; + role?: { slug: string } | null; + roles?: Array<{ slug: string }> | null; + directory_managed?: boolean; + created_at?: string; + updated_at?: string; +} + +export function membershipsForUser(ctx: ApiKeyContext, userId: string): Promise { + return listAll(ctx, '/user_management/organization_memberships', { user_id: userId }); +} + +export type { WorkOSListResponse }; diff --git a/src/lib/api-key-operations/users.ts b/src/lib/api-key-operations/users.ts new file mode 100644 index 00000000..1d3a4a98 --- /dev/null +++ b/src/lib/api-key-operations/users.ts @@ -0,0 +1,258 @@ +/** + * API-key adapters for `workos user` and `workos session`, backed by + * `/user_management/users` and its sessions/memberships/auth-factor endpoints. + * + * Filled with extra reads: `identities` (the user's organization memberships, + * with role IDs/names resolved from their slugs), `authenticationFactors` + * (user get), and session organization names. No REST source, returned + * `null`: `sessionCount`, `hasPassword`, `emailVerifiedAt` (REST has only a + * verified boolean, kept internally for the human view), a factor's + * `lastVerifiedAt`, and a session impersonator's id/name. + */ + +import type { WorkOSListResponse } from '../workos-api.js'; +import { + type ApiKeyContext, + type ApiKeyOperation, + encode, + listEnvelope, + num, + orNull, + restOrder, + str, +} from './context.js'; +import { metadataPairs } from './organizations.js'; +import { findRole, mapLimit, membershipsForUser, organizationName, type RestMembership } from './lookups.js'; + +export interface RestUser { + object?: 'user'; + id: string; + email: string; + first_name?: string | null; + last_name?: string | null; + email_verified?: boolean; + profile_picture_url?: string | null; + last_sign_in_at?: string | null; + locale?: string | null; + external_id?: string | null; + metadata?: Record | null; + created_at?: string; + updated_at?: string; +} + +interface RestSession { + object?: 'session'; + id: string; + impersonator?: { email: string; reason: string | null } | null; + ip_address?: string | null; + organization_id?: string | null; + user_agent?: string | null; + user_id?: string; + auth_method?: string | null; + status?: string | null; + expires_at?: string | null; + ended_at?: string | null; + created_at?: string; + updated_at?: string; +} + +/** Concurrent per-user reads on a list page. */ +const PER_USER_CONCURRENCY = 5; + +function userNode(user: RestUser) { + return { + id: user.id, + email: user.email ?? null, + firstName: user.first_name ?? null, + lastName: user.last_name ?? null, + createdAt: user.created_at ?? null, + emailVerifiedAt: null, + // Not part of the `--json` shape: lets the human view say "Verified" + // without inventing a verification timestamp. + emailVerified: user.email_verified ?? null, + lastSignedInAt: user.last_sign_in_at ?? null, + sessionCount: null, + hasPassword: null, + locale: user.locale ?? null, + externalId: user.external_id ?? null, + profilePictureUrl: user.profile_picture_url ?? null, + metadata: metadataPairs(user.metadata), + }; +} + +/** A membership as a dashboard identity, role slugs resolved to `{ id, name }`. */ +async function identityNode(ctx: ApiKeyContext, membership: RestMembership) { + const slugs = (membership.roles?.length ? membership.roles : membership.role ? [membership.role] : []).map( + (role) => role.slug, + ); + const roles = await Promise.all( + slugs.map(async (slug) => { + const role = await findRole(ctx, { slug }, membership.organization_id); + return { id: role?.id ?? null, name: role?.name ?? null }; + }), + ); + return { + id: membership.id, + status: membership.status ?? null, + organization: { + id: membership.organization_id, + name: membership.organization_name ?? (await organizationName(ctx, membership.organization_id)), + }, + roles, + }; +} + +async function identitiesFor(ctx: ApiKeyContext, userId: string) { + const memberships = await membershipsForUser(ctx, userId); + return { data: await Promise.all(memberships.map((membership) => identityNode(ctx, membership))) }; +} + +const SESSION_STATE: Record Record> = { + active: (s) => ({ __typename: 'UserlandSessionIssued', expiresAt: s.expires_at ?? null }), + expired: (s) => ({ __typename: 'UserlandSessionExpired', endedAt: s.ended_at ?? null }), + revoked: (s) => ({ + __typename: 'UserlandSessionRevoked', + expiresAt: s.expires_at ?? null, + endedAt: s.ended_at ?? null, + }), +}; + +/** + * REST auth methods are snake_case (`password`, `magic_code`); the dashboard + * reports the same values in PascalCase (`Password`), which the session shape + * passes through as-is. + */ +function sessionProvider(method: string | null | undefined): string | null { + if (!method) return null; + return method + .split('_') + .map((part) => part.charAt(0).toUpperCase() + part.slice(1)) + .join(''); +} + +async function sessionNode(ctx: ApiKeyContext, session: RestSession) { + return { + id: session.id, + createdAt: session.created_at ?? null, + updatedAt: session.updated_at ?? null, + ipAddress: session.ip_address ?? null, + userAgent: session.user_agent ?? null, + provider: sessionProvider(session.auth_method), + impersonator: session.impersonator + ? { id: null, email: session.impersonator.email ?? null, firstName: null, lastName: null } + : null, + impersonationReason: session.impersonator?.reason ?? null, + organization: session.organization_id + ? { id: session.organization_id, name: await organizationName(ctx, session.organization_id) } + : null, + application: null, + state: session.status ? (SESSION_STATE[session.status]?.(session) ?? null) : null, + }; +} + +export const userOperations: Record = { + async userlandUsers(variables, ctx) { + // `--email` is the CLI's only search input; REST filters by exact email. + const page = await ctx.request>({ + method: 'GET', + path: '/user_management/users', + params: { + limit: num(variables.limit), + before: str(variables.before), + after: str(variables.after), + order: restOrder(variables.order), + email: str(variables.search), + }, + }); + const users = await mapLimit(page?.data ?? [], PER_USER_CONCURRENCY, async (user) => ({ + ...userNode(user), + identities: await identitiesFor(ctx, user.id), + })); + return { userlandUsers: listEnvelope(users, page?.list_metadata) }; + }, + + async userlandUser(variables, ctx) { + const id = String(variables.id); + const user = await orNull(ctx.request({ method: 'GET', path: `/user_management/users/${encode(id)}` })); + if (!user) return { userlandUser: null }; + const [identities, factors] = await Promise.all([ + identitiesFor(ctx, id), + ctx.request<{ data: Array<{ id: string }> }>({ + method: 'GET', + path: `/user_management/users/${encode(id)}/auth_factors`, + }), + ]); + return { + userlandUser: { + ...userNode(user), + identities, + authenticationFactors: (factors?.data ?? []).map((factor) => ({ id: factor.id, lastVerifiedAt: null })), + }, + }; + }, + + async updateUserlandUser(variables, ctx) { + const input = (variables.input ?? {}) as Record; + const body: Record = {}; + if (input.firstName !== undefined) body.first_name = input.firstName; + if (input.lastName !== undefined) body.last_name = input.lastName; + if (input.email !== undefined) body.email = input.email; + if (input.locale !== undefined) body.locale = input.locale; + if (input.externalId !== undefined) body.external_id = input.externalId; + const user = await orNull( + ctx.request({ + method: 'PUT', + path: `/user_management/users/${encode(String(input.userlandUserId))}`, + body, + }), + ); + if (!user) return { updateUserlandUser: { __typename: 'UserlandUserNotFound' } }; + return { + updateUserlandUser: { + __typename: 'UserlandUserUpdated', + userlandUser: { + id: user.id, + email: user.email ?? null, + firstName: user.first_name ?? null, + lastName: user.last_name ?? null, + }, + }, + }; + }, + + async deleteUserlandUser(variables, ctx) { + const { userlandUserId } = (variables.input ?? {}) as { userlandUserId?: unknown }; + const deleted = await orNull( + ctx + .request({ method: 'DELETE', path: `/user_management/users/${encode(String(userlandUserId))}` }) + .then(() => true), + ); + return { deleteUserlandUser: { __typename: deleted ? 'UserlandUserDeleted' : 'UserlandUserNotFound' } }; + }, + + // --- session ------------------------------------------------------------------ + + async userlandSessions(variables, ctx) { + const userId = String(variables.userId); + const page = await orNull( + ctx.request>({ + method: 'GET', + path: `/user_management/users/${encode(userId)}/sessions`, + params: { limit: num(variables.limit), before: str(variables.before), after: str(variables.after) }, + }), + ); + if (!page) return { userlandUser: null }; + const sessions = await Promise.all((page.data ?? []).map((session) => sessionNode(ctx, session))); + return { userlandUser: { id: userId, sessions: listEnvelope(sessions, page.list_metadata) } }; + }, + + async revokeUserlandSession(variables, ctx) { + const { sessionId } = (variables.input ?? {}) as { sessionId?: unknown }; + const revoked = await orNull( + ctx + .request({ method: 'POST', path: '/user_management/sessions/revoke', body: { session_id: sessionId } }) + .then(() => true), + ); + return { revokeUserlandSession: revoked ? { sessionId } : null }; + }, +}; From f7f32176b8a9616411476380ac42a7edbc42f60b Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 12:25:02 -0800 Subject: [PATCH 03/32] feat: run membership and invitation commands with an API key REST adapters for membership list/get/create/update/delete/deactivate/ reactivate and invitation list/get/send/revoke/resend. The CLI's --role takes a role ID; REST takes a slug, so the ID is resolved through the roles endpoints first. Organization names on invitations come from one extra read per organization. --- src/lib/api-key-operations/index.ts | 2 + src/lib/api-key-operations/memberships.ts | 318 ++++++++++++++++++++++ 2 files changed, 320 insertions(+) create mode 100644 src/lib/api-key-operations/memberships.ts diff --git a/src/lib/api-key-operations/index.ts b/src/lib/api-key-operations/index.ts index 880e66b8..20962bab 100644 --- a/src/lib/api-key-operations/index.ts +++ b/src/lib/api-key-operations/index.ts @@ -26,10 +26,12 @@ import { } from './context.js'; import { organizationOperations } from './organizations.js'; import { userOperations } from './users.js'; +import { membershipOperations } from './memberships.js'; const OPERATIONS: Record = { ...organizationOperations, ...userOperations, + ...membershipOperations, }; /** diff --git a/src/lib/api-key-operations/memberships.ts b/src/lib/api-key-operations/memberships.ts new file mode 100644 index 00000000..06776547 --- /dev/null +++ b/src/lib/api-key-operations/memberships.ts @@ -0,0 +1,318 @@ +/** + * API-key adapters for `workos membership` and `workos invitation`, backed by + * `/user_management/organization_memberships` and `/user_management/invitations`. + * + * The CLI takes role IDs (`role_*`) for `--role`; REST takes role slugs, so the + * ID is resolved through the roles endpoints first. A membership's `type` and + * `directoryUserId` have no REST source and come back `null`. + */ + +import type { WorkOSListResponse } from '../workos-api.js'; +import { + type ApiKeyContext, + type ApiKeyOperation, + encode, + listEnvelope, + num, + orNull, + restOrder, + str, +} from './context.js'; +import { findRole, membershipsForUser, organizationName, type RestMembership } from './lookups.js'; +import { exitWithError } from '../../utils/output.js'; + +interface RestInvitation { + object?: 'invitation'; + id: string; + email: string; + state?: string | null; + organization_id?: string | null; + created_at?: string; +} + +function membershipNode(membership: RestMembership) { + return { + id: membership.id, + type: null, + status: membership.status ?? null, + organizationId: membership.organization_id ?? null, + userlandUserId: membership.user_id ?? null, + directoryUserId: null, + role: membership.role ?? null, + roles: membership.roles ?? [], + createdAt: membership.created_at ?? null, + updatedAt: membership.updated_at ?? null, + }; +} + +function readMembership(ctx: ApiKeyContext, id: string): Promise { + return orNull( + ctx.request({ method: 'GET', path: `/user_management/organization_memberships/${encode(id)}` }), + ); +} + +async function organizationExists(ctx: ApiKeyContext, organizationId: string): Promise { + const org = await orNull(ctx.request({ method: 'GET', path: `/organizations/${encode(organizationId)}` })); + return org !== null; +} + +/** A role ID → its slug, searching the environment roles, then the organization's. */ +async function roleSlug(ctx: ApiKeyContext, roleId: string, organizationId?: string | null) { + return (await findRole(ctx, { id: roleId }, organizationId))?.slug; +} + +async function invitationNode(ctx: ApiKeyContext, invitation: RestInvitation) { + return { + __typename: 'UserlandUserInvite', + id: invitation.id, + createdAt: invitation.created_at ?? null, + inviteeEmail: invitation.email ?? null, + state: invitation.state ?? null, + organization: invitation.organization_id + ? { id: invitation.organization_id, name: await organizationName(ctx, invitation.organization_id) } + : null, + }; +} + +function listInvitations(ctx: ApiKeyContext, variables: Record, organizationId?: string) { + return ctx.request>({ + method: 'GET', + path: '/user_management/invitations', + params: { + limit: num(variables.limit), + before: str(variables.before), + after: str(variables.after), + // `--email` is the CLI's only search input; REST filters by exact email. + email: str(variables.search), + organization_id: organizationId, + }, + }); +} + +/** Membership state change endpoints share one not-found contract. */ +async function setMembershipState(ctx: ApiKeyContext, id: unknown, action: 'deactivate' | 'reactivate') { + const result = await orNull( + ctx + .request({ method: 'PUT', path: `/user_management/organization_memberships/${encode(String(id))}/${action}` }) + .then(() => true), + ); + return result + ? `UserlandUserOrganizationMembership${action === 'deactivate' ? 'Deactivated' : 'Reactivated'}` + : 'UserlandUserOrganizationMembershipNotFound'; +} + +export const membershipOperations: Record = { + async userlandUserOrganizationMemberships(variables, ctx) { + const memberships = await membershipsForUser(ctx, String(variables.userlandUserId)); + return { userlandUserOrganizationMemberships: { organizationMemberships: memberships.map(membershipNode) } }; + }, + + async userlandUsersByOrg(variables, ctx) { + const organizationId = String(variables.organizationId); + if (!(await organizationExists(ctx, organizationId))) return { organization: null }; + // REST pages the organization's memberships directly (cursors are + // membership IDs); each becomes a user entry carrying that one identity. + const page = await ctx.request>({ + method: 'GET', + path: '/user_management/organization_memberships', + params: { + organization_id: organizationId, + limit: num(variables.limit), + before: str(variables.before), + after: str(variables.after), + order: restOrder(variables.order), + }, + }); + const users = (page?.data ?? []).map((membership) => ({ + id: membership.user_id, + identities: { + data: [ + { + id: membership.id, + status: membership.status ?? null, + directoryUserId: null, + role: membership.role ?? null, + roles: membership.roles ?? [], + organization: { id: organizationId, name: membership.organization_name ?? null }, + createdAt: membership.created_at ?? null, + updatedAt: membership.updated_at ?? null, + }, + ], + }, + })); + return { organization: { userlandUsers: listEnvelope(users, page?.list_metadata) } }; + }, + + async userlandUserOrganizationMembership(variables, ctx) { + const membership = await readMembership(ctx, String(variables.id)); + return { userlandUserOrganizationMembership: membership ? membershipNode(membership) : null }; + }, + + async addUserlandUserToOrg(variables, ctx) { + const input = (variables.input ?? {}) as { organizationId?: string; userlandUserId?: string; roleId?: string }; + let slug: string | undefined; + if (input.roleId) { + slug = await roleSlug(ctx, input.roleId, input.organizationId); + if (!slug) return roleNotFound(input.roleId); + } + await ctx.request({ + method: 'POST', + path: '/user_management/organization_memberships', + body: { + organization_id: input.organizationId, + user_id: input.userlandUserId, + ...(slug ? { role_slug: slug } : {}), + }, + }); + return { addUserlandUserToOrganization: { __typename: 'UserlandUserAddedToOrganization' } }; + }, + + async updateRoleOnOrganizationMembership(variables, ctx) { + const input = (variables.input ?? {}) as { organizationMembershipId?: string; roleId?: string }; + const notFound = { + updateRoleOnOrganizationMembership: { __typename: 'UserlandUserOrganizationMembershipNotFound', message: '' }, + }; + const current = await readMembership(ctx, String(input.organizationMembershipId)); + if (!current) return notFound; + const slug = await roleSlug(ctx, String(input.roleId), current.organization_id); + if (!slug) { + return { updateRoleOnOrganizationMembership: { __typename: 'RoleNotFound', roleId: input.roleId } }; + } + const updated = await orNull( + ctx.request({ + method: 'PUT', + path: `/user_management/organization_memberships/${encode(current.id)}`, + body: { role_slug: slug }, + }), + ); + if (!updated) return notFound; + return { + updateRoleOnOrganizationMembership: { + __typename: 'RoleOnOrganizationMembershipUpdated', + organizationMembership: membershipNode(updated), + }, + }; + }, + + async removeMemberFromOrganization(variables, ctx) { + const input = (variables.input ?? {}) as { organizationId?: string; userlandUserId?: string }; + // REST deletes by membership ID; find the pair's membership first. + const page = await ctx.request>({ + method: 'GET', + path: '/user_management/organization_memberships', + params: { organization_id: input.organizationId, user_id: input.userlandUserId, limit: 1 }, + }); + const membership = page?.data?.[0]; + const removed = + membership && + (await orNull( + ctx + .request({ method: 'DELETE', path: `/user_management/organization_memberships/${encode(membership.id)}` }) + .then(() => true), + )); + return { + removeUserlandUserFromOrganization: { + __typename: removed ? 'UserlandUserRemovedFromOrganization' : 'UserlandUserOrganizationMembershipNotFound', + }, + }; + }, + + async deactivateOrganizationMembership(variables, ctx) { + const { userlandUserOrganizationMembershipId: id } = (variables.input ?? {}) as Record; + return { + deactivateUserlandUserOrganizationMembership: { __typename: await setMembershipState(ctx, id, 'deactivate') }, + }; + }, + + async reactivateOrganizationMembership(variables, ctx) { + const { userlandUserOrganizationMembershipId: id } = (variables.input ?? {}) as Record; + return { + reactivateUserlandUserOrganizationMembership: { __typename: await setMembershipState(ctx, id, 'reactivate') }, + }; + }, + + // --- invitation --------------------------------------------------------------- + + async userlandUserInvites(variables, ctx) { + const page = await listInvitations(ctx, variables); + const invitations = await Promise.all((page?.data ?? []).map((invitation) => invitationNode(ctx, invitation))); + return { userlandUserInvites: listEnvelope(invitations, page?.list_metadata) }; + }, + + async userlandUserInvitesByOrg(variables, ctx) { + const organizationId = String(variables.organizationId); + if (!(await organizationExists(ctx, organizationId))) return { organization: null }; + const page = await listInvitations(ctx, variables, organizationId); + // The by-org selection carries no per-invite organization. + const invitations = (page?.data ?? []).map((invitation) => ({ + __typename: 'UserlandUserInvite', + id: invitation.id, + createdAt: invitation.created_at ?? null, + inviteeEmail: invitation.email ?? null, + state: invitation.state ?? null, + })); + return { organization: { userlandUserInvites: listEnvelope(invitations, page?.list_metadata) } }; + }, + + async createUserlandUserInvite(variables, ctx) { + const input = (variables.input ?? {}) as { + inviteeEmail?: string; + expiresInDays?: number; + organizationId?: string; + roleId?: string; + }; + let slug: string | undefined; + if (input.roleId) { + slug = await roleSlug(ctx, input.roleId, input.organizationId); + if (!slug) return { createUserlandUserInvite: { __typename: 'CreateUserlandUserInviteInvalidRole' } }; + } + const invitation = await ctx.request({ + method: 'POST', + path: '/user_management/invitations', + body: { + email: input.inviteeEmail, + ...(input.expiresInDays !== undefined ? { expires_in_days: input.expiresInDays } : {}), + ...(input.organizationId ? { organization_id: input.organizationId } : {}), + ...(slug ? { role_slug: slug } : {}), + }, + }); + return { + createUserlandUserInvite: { __typename: 'UserlandUserInviteCreated', userlandUserInvite: { id: invitation.id } }, + }; + }, + + async revokeUserlandUserInvite(variables, ctx) { + const { userlandUserInviteId: id } = (variables.input ?? {}) as { userlandUserInviteId?: string }; + const invitation = await orNull( + ctx.request({ + method: 'POST', + path: `/user_management/invitations/${encode(String(id))}/revoke`, + }), + ); + return { + revokeUserlandUserInvite: invitation + ? { __typename: 'UserlandUserInviteRevoked', userlandUserInvite: { id: invitation.id ?? id } } + : { __typename: 'UserlandUserInviteNotFound' }, + }; + }, + + async resendUserlandUserInvite(variables, ctx) { + const { userlandUserInviteId: id } = (variables.input ?? {}) as { userlandUserInviteId?: string }; + const invitation = await orNull( + ctx.request({ + method: 'POST', + path: `/user_management/invitations/${encode(String(id))}/resend`, + }), + ); + return { + resendUserlandUserInvite: invitation + ? { __typename: 'UserlandUserInviteResent', userlandUserInvite: { id: invitation.id ?? id } } + : { __typename: 'UserlandUserInviteNotFound' }, + }; + }, +}; + +/** The add operation has no role-not-found result, so report it directly. */ +function roleNotFound(roleId: string): never { + exitWithError({ code: 'not_found', message: `Role "${roleId}" was not found in this environment.` }); +} From 6d5b201b41f78b9827248ec944a74a5319873f9d Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 12:25:03 -0800 Subject: [PATCH 04/32] feat: run role and permission commands with an API key REST adapters for environment and organization roles and for permissions. REST is slug-keyed while the commands' mutations are ID-keyed, so the list adapters remember each slug and scope by ID for the mutation that follows. Role types map EnvironmentRole/OrganizationRole to the same environment/organization values the session path emits. --- src/lib/api-key-operations/index.ts | 2 + src/lib/api-key-operations/rbac.ts | 246 ++++++++++++++++++++++++++++ 2 files changed, 248 insertions(+) create mode 100644 src/lib/api-key-operations/rbac.ts diff --git a/src/lib/api-key-operations/index.ts b/src/lib/api-key-operations/index.ts index 20962bab..09a2d569 100644 --- a/src/lib/api-key-operations/index.ts +++ b/src/lib/api-key-operations/index.ts @@ -27,11 +27,13 @@ import { import { organizationOperations } from './organizations.js'; import { userOperations } from './users.js'; import { membershipOperations } from './memberships.js'; +import { rbacOperations } from './rbac.js'; const OPERATIONS: Record = { ...organizationOperations, ...userOperations, ...membershipOperations, + ...rbacOperations, }; /** diff --git a/src/lib/api-key-operations/rbac.ts b/src/lib/api-key-operations/rbac.ts new file mode 100644 index 00000000..f437f0de --- /dev/null +++ b/src/lib/api-key-operations/rbac.ts @@ -0,0 +1,246 @@ +/** + * API-key adapters for `workos role` and `workos permission`, backed by + * `/authorization/roles`, `/authorization/organizations/{id}/roles` and + * `/authorization/permissions`. + * + * The dashboard mutations are ID-keyed; REST is slug-keyed. The commands always + * list the scope before mutating (to resolve the slug), so the list adapters + * remember each role/permission's slug and scope by ID for the mutation that + * follows in the same invocation. + */ + +import { WorkOSApiError } from '../workos-api.js'; +import { type ApiKeyContext, type ApiKeyOperation, encode, listAll, orNull } from './context.js'; +import type { RestRole } from './lookups.js'; + +interface RestPermission { + object?: 'permission'; + id: string; + slug: string; + name: string; + description?: string | null; + system?: boolean; + resource_type_slug?: string; + created_at?: string; + updated_at?: string; +} + +interface RoleRef { + slug: string; + /** Set for organization (custom) roles. */ + organizationId?: string; +} + +const roleRefs = new Map(); +const permissionSlugs = new Map(); + +/** REST `EnvironmentRole`/`OrganizationRole` → the dashboard's `Environment`/`Organization`. */ +function roleType(type: string | undefined): string | null { + if (!type) return null; + return type.endsWith('Role') ? type.slice(0, -'Role'.length) : type; +} + +function roleNode(role: RestRole) { + return { + id: role.id, + name: role.name, + slug: role.slug, + description: role.description ?? null, + state: null, + type: roleType(role.type), + permissions: (role.permissions ?? []).map((slug) => ({ id: null, slug })), + createdAt: role.created_at ?? null, + updatedAt: role.updated_at ?? null, + }; +} + +function rememberRoles(roles: RestRole[], organizationId?: string): RestRole[] { + for (const role of roles) { + const custom = organizationId !== undefined && roleType(role.type) === 'Organization'; + roleRefs.set(role.id, { slug: role.slug, ...(custom ? { organizationId } : {}) }); + } + return roles; +} + +function permissionNode(permission: RestPermission) { + permissionSlugs.set(permission.id, permission.slug); + return { + id: permission.id, + name: permission.name, + slug: permission.slug, + description: permission.description ?? null, + system: permission.system ?? false, + createdAt: permission.created_at ?? null, + updatedAt: permission.updated_at ?? null, + }; +} + +function rolePath(ref: RoleRef): string { + return ref.organizationId + ? `/authorization/organizations/${encode(ref.organizationId)}/roles/${encode(ref.slug)}` + : `/authorization/roles/${encode(ref.slug)}`; +} + +function isConflict(error: unknown): boolean { + return ( + error instanceof WorkOSApiError && + (error.statusCode === 409 || (typeof error.code === 'string' && error.code.includes('already_exists'))) + ); +} + +async function readRole(ctx: ApiKeyContext, ref: RoleRef): Promise { + return orNull(ctx.request({ method: 'GET', path: rolePath(ref) })); +} + +export const rbacOperations: Record = { + async roles(_variables, ctx) { + const result = await ctx.request<{ data: RestRole[] }>({ method: 'GET', path: '/authorization/roles' }); + return { rolesForEnvironment: { roles: rememberRoles(result?.data ?? []).map(roleNode) } }; + }, + + async rolesForOrganization(variables, ctx) { + const organizationId = String(variables.organizationId); + const result = await orNull( + ctx.request<{ data: RestRole[] }>({ + method: 'GET', + path: `/authorization/organizations/${encode(organizationId)}/roles`, + }), + ); + if (!result) return { rolesForOrganization: null }; + return { rolesForOrganization: { roles: rememberRoles(result.data ?? [], organizationId).map(roleNode) } }; + }, + + async createRole(variables, ctx) { + const input = (variables.input ?? {}) as { + slug?: string; + name?: string; + description?: string; + organizationId?: string; + }; + const path = input.organizationId + ? `/authorization/organizations/${encode(input.organizationId)}/roles` + : '/authorization/roles'; + try { + const role = await ctx.request({ + method: 'POST', + path, + body: { + slug: input.slug, + name: input.name, + ...(input.description !== undefined ? { description: input.description } : {}), + }, + }); + return { createRole: { __typename: 'RoleCreated', role: roleNode(role) } }; + } catch (error) { + if (isConflict(error)) return { createRole: { __typename: 'RoleAlreadyExists', slug: input.slug } }; + throw error; + } + }, + + async updateRole(variables, ctx) { + const input = (variables.input ?? {}) as { + roleId?: string; + name?: string; + description?: string; + permissions?: string[]; + }; + const ref = input.roleId ? roleRefs.get(input.roleId) : undefined; + const notFound = { updateRole: { __typename: 'RoleNotFound', roleId: input.roleId } }; + if (!ref) return notFound; + + let role = await orNull( + ctx.request({ + method: 'PATCH', + path: rolePath(ref), + body: { + ...(input.name !== undefined ? { name: input.name } : {}), + ...(input.description !== undefined ? { description: input.description } : {}), + }, + }), + ); + if (!role) return notFound; + if (input.permissions) { + role = + (await orNull( + ctx.request({ + method: 'PUT', + path: `${rolePath(ref)}/permissions`, + body: { permissions: input.permissions }, + }), + )) ?? (await readRole(ctx, ref)); + if (!role) return notFound; + } + return { updateRole: { __typename: 'RoleUpdated', role: roleNode(role) } }; + }, + + async deleteRole(variables, ctx) { + const { roleId } = (variables.input ?? {}) as { roleId?: string }; + const ref = roleId ? roleRefs.get(roleId) : undefined; + const deleted = ref && (await orNull(ctx.request({ method: 'DELETE', path: rolePath(ref) }).then(() => true))); + return { deleteRole: deleted ? { __typename: 'RoleDeleted' } : { __typename: 'RoleNotFound', roleId } }; + }, + + // --- permission --------------------------------------------------------------- + + async permissions(_variables, ctx) { + // The dashboard returns the environment's whole permission set; REST pages it. + const permissions = await listAll(ctx, '/authorization/permissions'); + return { permissionsForEnvironment: { permissions: permissions.map(permissionNode) } }; + }, + + async createPermission(variables, ctx) { + const input = (variables.input ?? {}) as { slug?: string; name?: string; description?: string }; + try { + const permission = await ctx.request({ + method: 'POST', + path: '/authorization/permissions', + body: { + slug: input.slug, + name: input.name, + ...(input.description !== undefined ? { description: input.description } : {}), + }, + }); + return { createPermission: { __typename: 'PermissionCreated', permission: permissionNode(permission) } }; + } catch (error) { + if (isConflict(error)) return { createPermission: { __typename: 'PermissionAlreadyExists', slug: input.slug } }; + throw error; + } + }, + + async updatePermission(variables, ctx) { + const input = (variables.input ?? {}) as { permissionId?: string; name?: string; description?: string }; + const slug = input.permissionId ? permissionSlugs.get(input.permissionId) : undefined; + const permission = + slug && + (await orNull( + ctx.request({ + method: 'PATCH', + path: `/authorization/permissions/${encode(slug)}`, + body: { + ...(input.name !== undefined ? { name: input.name } : {}), + ...(input.description !== undefined ? { description: input.description } : {}), + }, + }), + )); + return { + updatePermission: permission + ? { __typename: 'PermissionUpdated', permission: permissionNode(permission) } + : { __typename: 'PermissionNotFound', permissionId: input.permissionId }, + }; + }, + + async deletePermission(variables, ctx) { + const { permissionId } = (variables.input ?? {}) as { permissionId?: string }; + const slug = permissionId ? permissionSlugs.get(permissionId) : undefined; + const deleted = + slug && + (await orNull( + ctx.request({ method: 'DELETE', path: `/authorization/permissions/${encode(slug)}` }).then(() => true), + )); + return { + deletePermission: deleted + ? { __typename: 'PermissionDeleted', permissionId } + : { __typename: 'PermissionNotFound', permissionId }, + }; + }, +}; From f19101684a6c05ec392f2d6ab67323b456b7aafb Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 12:25:03 -0800 Subject: [PATCH 05/32] feat: run webhook, event, portal and feature-flag commands with an API key REST adapters for webhook list/create/delete, event list (newest first, same cursor contract), portal generate-link and feature-flag list/get/enable/disable. REST can't list a flag's targets, so add-target/remove-target call the target endpoints directly and flag get reports accessType and targets as null on this path. --- src/commands/feature-flag.ts | 122 ++++++++---- src/lib/api-key-operations/index.ts | 3 + src/lib/api-key-operations/platform.ts | 266 +++++++++++++++++++++++++ 3 files changed, 356 insertions(+), 35 deletions(-) create mode 100644 src/lib/api-key-operations/platform.ts diff --git a/src/commands/feature-flag.ts b/src/commands/feature-flag.ts index 8a5aa76e..669aeceb 100644 --- a/src/commands/feature-flag.ts +++ b/src/commands/feature-flag.ts @@ -26,9 +26,9 @@ */ import chalk from 'chalk'; -import { requireCommandToken } from '../lib/command-auth.js'; -import { resolveEnvironmentTarget } from '../lib/environment-target.js'; -import { executeDashboardOperation } from '../lib/dashboard-operation.js'; +import { isApiKeyAuth, type ApiKeyAuth, type OperationAuth } from '../lib/resource-auth.js'; +import { changeFlagTarget, withApiKey } from '../lib/api-key-operations/index.js'; +import { executeDashboardOperation, resolveEnvScopedAuth } from '../lib/dashboard-operation.js'; import { getOperation } from '../catalog/operation.js'; import { isJsonMode, outputJson, outputSuccess, exitWithError } from '../utils/output.js'; import { enumOut } from '../utils/output-conventions.js'; @@ -44,6 +44,8 @@ interface FlagEnvironmentNode { accessType?: string | null; organizations?: Array<{ id: string; name?: string | null }> | null; users?: Array<{ id: string; email?: string | null }> | null; + /** Set on the API-key path, where the REST API can't list a flag's targets. */ + targetsUnknown?: boolean; } interface FlagNode { @@ -85,8 +87,12 @@ function shapeFlagDetail(flag: FlagNode, environmentId: string) { ...shapeFlag(flag, environmentId), defaultEnabled: state?.defaultEnabled ?? false, accessType: enumOut(state?.accessType), - organizationTargets: (state?.organizations ?? []).map((org) => ({ id: org.id, name: org.name ?? null })), - userTargets: (state?.users ?? []).map((user) => ({ id: user.id, email: user.email ?? null })), + organizationTargets: state?.targetsUnknown + ? null + : (state?.organizations ?? []).map((org) => ({ id: org.id, name: org.name ?? null })), + userTargets: state?.targetsUnknown + ? null + : (state?.users ?? []).map((user) => ({ id: user.id, email: user.email ?? null })), tags: (flag.tags ?? []).map((tag) => tag.name ?? tag.id), }; } @@ -103,7 +109,10 @@ interface TeamProjectsData { * that joins no project means the stored ID went stale — same remedy as the * environment resolver's staleness error. */ -async function resolveProjectId(token: string, environmentId: string): Promise { +async function resolveProjectId(token: OperationAuth, environmentId: string): Promise { + // With an API key the key is the environment and the REST flag endpoints + // aren't project-scoped, so there is no project to derive. + if (isApiKeyAuth(token)) return ''; const op = getOperation('teamProjectsV2'); // Team-scoped read: deliberately no environment header. const data = await executeDashboardOperation(op, { token }); @@ -134,11 +143,10 @@ export interface FeatureFlagListOptions { export async function runFeatureFlagList(options: FeatureFlagListOptions = {}): Promise { const order = normalizeOrder(options.order); - const token = await requireCommandToken(); const op = getOperation('flags'); - const { environmentId } = await resolveEnvironmentTarget(token, { - flagValue: options.environmentId, + const { token, environmentId } = await resolveEnvScopedAuth({ + environmentId: options.environmentId, forMutation: op.kind === 'mutation', }); const projectId = await resolveProjectId(token, environmentId); @@ -195,7 +203,7 @@ export interface FeatureFlagEnvironmentOptions { /** Fetch a flag by slug within the resolved environment's project, or exit not_found. */ async function requireFlagBySlug( - token: string, + token: OperationAuth, environmentId: string, projectId: string, slug: string, @@ -213,10 +221,8 @@ async function requireFlagBySlug( } export async function runFeatureFlagGet(slug: string, options: FeatureFlagEnvironmentOptions = {}): Promise { - const token = await requireCommandToken(); - - const { environmentId } = await resolveEnvironmentTarget(token, { - flagValue: options.environmentId, + const { token, environmentId } = await resolveEnvScopedAuth({ + environmentId: options.environmentId, forMutation: false, }); const projectId = await resolveProjectId(token, environmentId); @@ -264,7 +270,7 @@ function requireEnvironmentState(flag: FlagNode, slug: string, environmentId: st * their change into the freshly fetched state and pass everything back. */ async function executeFlagEnvironmentUpdate( - token: string, + token: OperationAuth, environmentId: string, slug: string, state: FlagEnvironmentNode, @@ -301,11 +307,9 @@ async function executeFlagEnvironmentUpdate( } async function setFlagEnabled(slug: string, enabled: boolean, options: FeatureFlagEnvironmentOptions): Promise { - const token = await requireCommandToken(); - // Environment-scoped mutation: pre-validated resolved target as header. - const { environmentId } = await resolveEnvironmentTarget(token, { - flagValue: options.environmentId, + const { token, environmentId } = await resolveEnvScopedAuth({ + environmentId: options.environmentId, forMutation: true, }); const projectId = await resolveProjectId(token, environmentId); @@ -345,12 +349,31 @@ export async function runFeatureFlagAddTarget( options: FeatureFlagEnvironmentOptions = {}, ): Promise { const key = targetListKey(targetId); - const token = await requireCommandToken(); - const { environmentId } = await resolveEnvironmentTarget(token, { - flagValue: options.environmentId, + const { token, environmentId } = await resolveEnvScopedAuth({ + environmentId: options.environmentId, forMutation: true, }); + if (isApiKeyAuth(token)) { + await changeTargetWithApiKey(token, slug, targetId, 'add'); + } else { + await addTargetWithSession(token, environmentId, slug, targetId, key); + } + + if (isJsonMode()) { + outputJson({ added: { flag: slug, targetId } }); + return; + } + outputSuccess(`Added target ${chalk.bold(targetId)} to feature flag ${chalk.bold(slug)}`); +} + +async function addTargetWithSession( + token: OperationAuth, + environmentId: string, + slug: string, + targetId: string, + key: 'organizationIds' | 'userIds', +): Promise { const projectId = await resolveProjectId(token, environmentId); const flag = await requireFlagBySlug(token, environmentId, projectId, slug); const state = requireEnvironmentState(flag, slug, environmentId); @@ -361,12 +384,28 @@ export async function runFeatureFlagAddTarget( const merged = [...new Set([...current, targetId])]; await executeFlagEnvironmentUpdate(token, environmentId, slug, state, { [key]: merged }); +} - if (isJsonMode()) { - outputJson({ added: { flag: slug, targetId } }); - return; +/** + * API-key path for add/remove-target: REST can't list a flag's targets, so + * call the target endpoint directly instead of read-merge-write. + */ +async function changeTargetWithApiKey( + token: ApiKeyAuth, + slug: string, + targetId: string, + action: 'add' | 'remove', +): Promise { + const changed = await withApiKey(token, (ctx) => changeFlagTarget(ctx, slug, targetId, action)); + if (!changed) { + exitWithError({ + code: 'not_found', + message: + action === 'add' + ? `Feature flag "${slug}" was not found.` + : `Feature flag "${slug}" has no target "${targetId}" in this environment.`, + }); } - outputSuccess(`Added target ${chalk.bold(targetId)} to feature flag ${chalk.bold(slug)}`); } export async function runFeatureFlagRemoveTarget( @@ -375,12 +414,31 @@ export async function runFeatureFlagRemoveTarget( options: FeatureFlagEnvironmentOptions = {}, ): Promise { const key = targetListKey(targetId); - const token = await requireCommandToken(); - const { environmentId } = await resolveEnvironmentTarget(token, { - flagValue: options.environmentId, + const { token, environmentId } = await resolveEnvScopedAuth({ + environmentId: options.environmentId, forMutation: true, }); + if (isApiKeyAuth(token)) { + await changeTargetWithApiKey(token, slug, targetId, 'remove'); + } else { + await removeTargetWithSession(token, environmentId, slug, targetId, key); + } + + if (isJsonMode()) { + outputJson({ removed: { flag: slug, targetId } }); + return; + } + outputSuccess(`Removed target ${chalk.bold(targetId)} from feature flag ${chalk.bold(slug)}`); +} + +async function removeTargetWithSession( + token: OperationAuth, + environmentId: string, + slug: string, + targetId: string, + key: 'organizationIds' | 'userIds', +): Promise { const projectId = await resolveProjectId(token, environmentId); const flag = await requireFlagBySlug(token, environmentId, projectId, slug); const state = requireEnvironmentState(flag, slug, environmentId); @@ -396,10 +454,4 @@ export async function runFeatureFlagRemoveTarget( const remaining = current.filter((candidate) => candidate !== targetId); await executeFlagEnvironmentUpdate(token, environmentId, slug, state, { [key]: remaining }); - - if (isJsonMode()) { - outputJson({ removed: { flag: slug, targetId } }); - return; - } - outputSuccess(`Removed target ${chalk.bold(targetId)} from feature flag ${chalk.bold(slug)}`); } diff --git a/src/lib/api-key-operations/index.ts b/src/lib/api-key-operations/index.ts index 09a2d569..ec3e67c9 100644 --- a/src/lib/api-key-operations/index.ts +++ b/src/lib/api-key-operations/index.ts @@ -28,12 +28,14 @@ import { organizationOperations } from './organizations.js'; import { userOperations } from './users.js'; import { membershipOperations } from './memberships.js'; import { rbacOperations } from './rbac.js'; +import { platformOperations } from './platform.js'; const OPERATIONS: Record = { ...organizationOperations, ...userOperations, ...membershipOperations, ...rbacOperations, + ...platformOperations, }; /** @@ -99,3 +101,4 @@ export async function withApiKey(auth: ApiKeyAuth, run: (ctx: ApiKeyContext) } export { exitApiKeyUnsupported, apiKeyUnsupportedMessage } from './context.js'; +export { changeFlagTarget } from './platform.js'; diff --git a/src/lib/api-key-operations/platform.ts b/src/lib/api-key-operations/platform.ts new file mode 100644 index 00000000..835f5e4b --- /dev/null +++ b/src/lib/api-key-operations/platform.ts @@ -0,0 +1,266 @@ +/** + * API-key adapters for `workos webhook`, `workos event`, `workos portal` and + * `workos feature-flag`, backed by `/webhook_endpoints`, `/events`, + * `/portal/generate_link` and `/feature-flags`. + * + * No REST source, returned `null`: an event's `updatedAt`, a portal link's + * `id`/`state`/`expiresAt`, and a flag's `accessType` and target lists (the + * REST flag endpoints expose neither). + */ + +import type { WorkOSListResponse } from '../workos-api.js'; +import { API_KEY_ENVIRONMENT_ID } from '../resource-auth.js'; +import { enumOut } from '../../utils/output-conventions.js'; +import { + type ApiKeyContext, + type ApiKeyOperation, + encode, + listEnvelope, + num, + orNull, + restOrder, + str, +} from './context.js'; + +interface RestWebhookEndpoint { + object?: 'webhook_endpoint'; + id: string; + endpoint_url: string; + events?: string[]; + status?: string | null; + created_at?: string; +} + +interface RestEvent { + object?: 'event'; + id: string; + event: string; + data?: unknown; + created_at?: string; +} + +interface RestFlag { + object?: 'feature_flag'; + id: string; + slug: string; + name?: string | null; + description?: string | null; + tags?: string[]; + enabled?: boolean; + default_value?: boolean; + created_at?: string; + updated_at?: string; +} + +/** REST `enabled` → the dashboard's `Active`; other states pass through. */ +function webhookState(status: string | null | undefined): string | null { + if (!status) return null; + return status === 'enabled' ? 'Active' : status; +} + +/** Flag environment IDs handed out by the flag reads → slug, for the update that follows. */ +const flagSlugs = new Map(); + +function flagNode(flag: RestFlag, detail: boolean) { + // The key is the environment, so the one environment state is the flag's own. + flagSlugs.set(flag.id, flag.slug); + const state = { + id: flag.id, + environmentId: API_KEY_ENVIRONMENT_ID, + flagId: flag.id, + flagEnabled: flag.enabled ?? false, + ...(detail + ? { + defaultEnabled: flag.default_value ?? false, + accessType: null, + organizations: null, + users: null, + // REST can't list a flag's targets; the shape reports them as unknown. + targetsUnknown: true, + } + : {}), + }; + return { + id: flag.id, + name: flag.name ?? null, + slug: flag.slug, + description: flag.description ?? null, + flagEnvironments: [state], + createdAt: flag.created_at ?? null, + updatedAt: flag.updated_at ?? null, + tags: (flag.tags ?? []).map((tag) => ({ id: null, name: tag })), + }; +} + +export const platformOperations: Record = { + // --- webhook ------------------------------------------------------------------ + + async webhookEndpoints(variables, ctx) { + const page = await ctx.request>({ + method: 'GET', + path: '/webhook_endpoints', + params: { limit: num(variables.limit), before: str(variables.before), after: str(variables.after) }, + }); + const endpoints = (page?.data ?? []).map((endpoint) => ({ + id: endpoint.id, + endpointUrl: endpoint.endpoint_url ?? null, + events: endpoint.events ?? [], + state: webhookState(endpoint.status), + createdAt: endpoint.created_at ?? null, + })); + return { webhookEndpoints: listEnvelope(endpoints, page?.list_metadata) }; + }, + + async createWebhookEndpoint(variables, ctx) { + const endpoint = await ctx.request({ + method: 'POST', + path: '/webhook_endpoints', + body: { endpoint_url: variables.endpointUrl, events: variables.events }, + }); + return { createWebhookEndpoint: { id: endpoint.id } }; + }, + + async deleteWebhookEndpoint(variables, ctx) { + await ctx.request({ method: 'DELETE', path: `/webhook_endpoints/${encode(String(variables.id))}` }); + return { deleteWebhookEndpoint: true }; + }, + + // --- event -------------------------------------------------------------------- + + async environmentEvents(variables, ctx) { + // Newest-first like the dashboard feed. The command passes its `--after` + // as `before` and swaps the returned cursors, so the next-page (older) + // cursor goes back as `before`. + const page = await ctx.request>({ + method: 'GET', + path: '/events', + params: { + events: Array.isArray(variables.names) ? variables.names.join(',') : undefined, + range_start: str(variables.rangeStart), + range_end: str(variables.rangeEnd), + limit: num(variables.limit), + after: str(variables.before), + order: 'desc', + }, + }); + const events = (page?.data ?? []).map((event) => ({ + id: event.id, + name: event.event ?? null, + data: event.data ?? null, + createdAt: event.created_at ?? null, + updatedAt: null, + })); + return { + environment: { + events: listEnvelope(events, { + before: page?.list_metadata?.after ?? null, + after: page?.list_metadata?.before ?? null, + }), + }, + }; + }, + + // --- portal ------------------------------------------------------------------- + + async generatePortalSetupLink(variables, ctx) { + const input = (variables.input ?? {}) as { organizationId?: string; intents?: string[] }; + const intent = input.intents?.[0]; + const result = await orNull( + ctx.request<{ link: string }>({ + method: 'POST', + path: '/portal/generate_link', + body: { organization: input.organizationId, intent: enumOut(intent) }, + }), + ); + if (!result) { + return { generatePortalSetupLink: { __typename: 'OrganizationNotFound', organizationId: input.organizationId } }; + } + return { + generatePortalSetupLink: { + __typename: 'PortalSetupLinkGenerated', + // The link is for exactly the intent requested. + portalSetupLink: { id: null, url: result.link, intents: intent ? [intent] : [], state: null, expiresAt: null }, + }, + }; + }, + + // --- feature-flag ------------------------------------------------------------- + + async flags(variables, ctx) { + const page = await ctx.request>({ + method: 'GET', + path: '/feature-flags', + params: { + limit: num(variables.limit), + before: str(variables.before), + after: str(variables.after), + order: restOrder(variables.order), + }, + }); + return { + flagsForProject: listEnvelope( + (page?.data ?? []).map((flag) => flagNode(flag, false)), + page?.list_metadata, + ), + }; + }, + + async flagBySlug(variables, ctx) { + const flag = await orNull( + ctx.request({ method: 'GET', path: `/feature-flags/${encode(String(variables.slug))}` }), + ); + return { flagBySlug: flag ? flagNode(flag, true) : null }; + }, + + async updateFlagEnvironment(variables, ctx) { + // Only enable/disable reach here on the API-key path; targets use the + // REST target endpoints directly (see `changeFlagTarget`). + const input = (variables.input ?? {}) as { flagEnvironmentId?: string; flagEnabled?: boolean }; + const slug = input.flagEnvironmentId ? flagSlugs.get(input.flagEnvironmentId) : undefined; + if (!slug) { + return { + updateFlagEnvironment: { __typename: 'FlagEnvironmentNotFound', flagEnvironmentId: input.flagEnvironmentId }, + }; + } + const flag = await orNull( + ctx.request({ + method: 'PUT', + path: `/feature-flags/${encode(slug)}/${input.flagEnabled ? 'enable' : 'disable'}`, + }), + ); + if (flag === null) { + return { + updateFlagEnvironment: { __typename: 'FlagEnvironmentNotFound', flagEnvironmentId: input.flagEnvironmentId }, + }; + } + return { + updateFlagEnvironment: { + __typename: 'FlagEnvironmentUpdated', + flagEnvironment: { id: input.flagEnvironmentId, flagEnabled: input.flagEnabled ?? false }, + }, + }; + }, +}; + +/** + * Add or remove one feature-flag target with an API key. REST can't list a + * flag's targets, so this skips the dashboard path's read-merge-write and + * calls the target endpoint directly. Returns `false` when REST reports the + * flag (or, on removal, the target) as not found. + */ +export async function changeFlagTarget( + ctx: ApiKeyContext, + slug: string, + targetId: string, + action: 'add' | 'remove', +): Promise { + const result = await orNull( + ctx + .request({ + method: action === 'add' ? 'POST' : 'DELETE', + path: `/feature-flags/${encode(slug)}/targets/${encode(targetId)}`, + }) + .then(() => true), + ); + return result === true; +} From 8b13b0c428ee0b3ef7035b811e137a86ccfd7619 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 12:25:04 -0800 Subject: [PATCH 06/32] feat: run config and authkit URI/CORS commands with an API key REST adapters for redirect URIs and CORS origins (list, and set as a create/delete diff) back config redirect add / cors add and authkit redirect-uris / cors. Where REST lacks a piece the command fails before any write: no CORS delete, no way to choose the default redirect URI, no --dry-run. config homepage-url set uses REST's homepage endpoint and reports applicationId as null. AuthKit logout URIs and branding stay session-only and fail with api_key_unsupported. --- src/commands/config.ts | 33 +++--- src/lib/api-key-operations/app-config.ts | 124 +++++++++++++++++++++++ src/lib/api-key-operations/index.ts | 3 + 3 files changed, 148 insertions(+), 12 deletions(-) create mode 100644 src/lib/api-key-operations/app-config.ts diff --git a/src/commands/config.ts b/src/commands/config.ts index dc439956..670abbbe 100644 --- a/src/commands/config.ts +++ b/src/commands/config.ts @@ -27,10 +27,10 @@ */ import chalk from 'chalk'; -import { requireCommandToken } from '../lib/command-auth.js'; -import { resolveEnvironmentTarget } from '../lib/environment-target.js'; import { getOperation } from '../catalog/operation.js'; -import { executeDashboardOperation } from '../lib/dashboard-operation.js'; +import { executeDashboardOperation, resolveEnvScopedAuth } from '../lib/dashboard-operation.js'; +import { isApiKeyAuth } from '../lib/resource-auth.js'; +import { setHomepageUrl, withApiKey } from '../lib/api-key-operations/index.js'; import { isJsonMode, outputJson, outputSuccess, exitWithError } from '../utils/output.js'; import { rejectWildcardOrigins } from './authkit.js'; @@ -53,13 +53,12 @@ export interface ConfigRedirectAddOptions { } export async function runConfigRedirectAdd(uri: string, options: ConfigRedirectAddOptions = {}): Promise { - const token = await requireCommandToken(); const readOp = getOperation('redirectUris'); const writeOp = getOperation('setRedirectUris'); // The subcommand as a whole mutates: pre-validate the resolved target. - const { environmentId } = await resolveEnvironmentTarget(token, { - flagValue: options.environmentId, + const { token, environmentId } = await resolveEnvScopedAuth({ + environmentId: options.environmentId, forMutation: writeOp.kind === 'mutation', }); @@ -130,13 +129,12 @@ export interface ConfigCorsAddOptions { export async function runConfigCorsAdd(origin: string, options: ConfigCorsAddOptions = {}): Promise { rejectWildcardOrigins([origin]); - const token = await requireCommandToken(); const readOp = getOperation('corsConfig'); const writeOp = getOperation('updateCorsConfig'); // The subcommand as a whole mutates: pre-validate the resolved target. - const { environmentId } = await resolveEnvironmentTarget(token, { - flagValue: options.environmentId, + const { token, environmentId } = await resolveEnvScopedAuth({ + environmentId: options.environmentId, forMutation: writeOp.kind === 'mutation', }); @@ -185,16 +183,27 @@ export interface ConfigHomepageUrlSetOptions { } export async function runConfigHomepageUrlSet(url: string, options: ConfigHomepageUrlSetOptions = {}): Promise { - const token = await requireCommandToken(); const lookupOp = getOperation('defaultAuthkitApplication'); const writeOp = getOperation('updateAuthkitApplication'); // The subcommand as a whole mutates: pre-validate the resolved target. - const { environmentId } = await resolveEnvironmentTarget(token, { - flagValue: options.environmentId, + const { token, environmentId } = await resolveEnvScopedAuth({ + environmentId: options.environmentId, forMutation: writeOp.kind === 'mutation', }); + // API-key path: REST sets the key environment's AuthKit homepage directly + // and never exposes the application's ID, so `applicationId` is null. + if (isApiKeyAuth(token)) { + await withApiKey(token, (ctx) => setHomepageUrl(ctx, url)); + if (isJsonMode()) { + outputJson({ homepageUrl: url, applicationId: null }); + return; + } + outputSuccess(`Set homepage URL to ${chalk.bold(url)}`); + return; + } + // Step 1: resolve the environment's AuthKit application — the update is // keyed by application ID, and this is the application the REST endpoint // wrote to. diff --git a/src/lib/api-key-operations/app-config.ts b/src/lib/api-key-operations/app-config.ts new file mode 100644 index 00000000..856d4cb8 --- /dev/null +++ b/src/lib/api-key-operations/app-config.ts @@ -0,0 +1,124 @@ +/** + * API-key adapters for AuthKit app configuration (`workos config`, `workos + * authkit redirect-uris|cors`), backed by `/user_management/redirect_uris`, + * `/user_management/cors_origins` and `/user_management/app_homepage_url`. + * + * The dashboard setters replace whole lists; REST has per-item endpoints. A + * list "set" becomes a diff: create what's missing and delete what's dropped. + * Where REST lacks a piece, the request fails before any write: there is no + * delete for CORS origins, no way to choose the default redirect URI, and no + * validate-only (`--dry-run`) mode. + */ + +import { + type ApiKeyContext, + type ApiKeyOperation, + encode, + exitApiKeyUnsupported, + listAll, + listEnvelope, + num, + str, +} from './context.js'; +import type { WorkOSListResponse } from '../workos-api.js'; + +interface RestRedirectUri { + object?: 'redirect_uri'; + id: string; + uri: string; + default?: boolean; +} + +interface RestCorsOrigin { + object?: 'cors_origin'; + id: string; + origin: string; +} + +function redirectUriNode(uri: RestRedirectUri) { + return { id: uri.id, uri: uri.uri, isDefault: uri.default ?? false }; +} + +function refuseDryRun(dryRun: unknown): void { + if (dryRun) exitApiKeyUnsupported('--dry-run has no validate-only equivalent in the WorkOS API'); +} + +function corsOrigins(ctx: ApiKeyContext): Promise { + return listAll(ctx, '/user_management/cors_origins'); +} + +export const appConfigOperations: Record = { + async redirectUris(variables, ctx) { + const page = await ctx.request>({ + method: 'GET', + path: '/user_management/redirect_uris', + params: { limit: num(variables.limit), before: str(variables.before), after: str(variables.after) }, + }); + return { redirectUris: listEnvelope((page?.data ?? []).map(redirectUriNode), page?.list_metadata) }; + }, + + async setRedirectUris(variables, ctx) { + const input = (variables.input ?? {}) as { + redirectUris?: Array<{ uri: string; isDefault?: boolean }>; + dryRun?: boolean; + }; + refuseDryRun(input.dryRun); + const desired = input.redirectUris ?? []; + const current = await listAll(ctx, '/user_management/redirect_uris'); + + // REST can't choose the default: only an already-default URI may be marked default. + const wantsNewDefault = desired.some( + (entry) => entry.isDefault && !current.some((existing) => existing.uri === entry.uri && existing.default), + ); + if (wantsNewDefault) { + exitApiKeyUnsupported('choosing the default redirect URI has no WorkOS API endpoint'); + } + + const desiredUris = new Set(desired.map((entry) => entry.uri)); + for (const existing of current) { + if (!desiredUris.has(existing.uri)) { + await ctx.request({ method: 'DELETE', path: `/user_management/redirect_uris/${encode(existing.id)}` }); + } + } + for (const entry of desired) { + if (!current.some((existing) => existing.uri === entry.uri)) { + await ctx.request({ method: 'POST', path: '/user_management/redirect_uris', body: { uri: entry.uri } }); + } + } + + const saved = await listAll(ctx, '/user_management/redirect_uris'); + return { setRedirectUris: { __typename: 'RedirectUrisSet', redirectUris: saved.map(redirectUriNode) } }; + }, + + async corsConfig(_variables, ctx) { + const origins = await corsOrigins(ctx); + return { webOrigins: { webOrigins: { origins: origins.map((origin) => origin.origin) } } }; + }, + + async updateCorsConfig(variables, ctx) { + refuseDryRun(variables.dryRun); + const desired = Array.isArray(variables.origins) ? variables.origins.map(String) : []; + const current = (await corsOrigins(ctx)).map((origin) => origin.origin); + + const removed = current.filter((origin) => !desired.includes(origin)); + if (removed.length > 0) { + exitApiKeyUnsupported(`removing CORS origins (${removed.join(', ')}) has no WorkOS API endpoint`); + } + for (const origin of desired) { + if (!current.includes(origin)) { + await ctx.request({ method: 'POST', path: '/user_management/cors_origins', body: { origin } }); + } + } + + const saved = (await corsOrigins(ctx)).map((origin) => origin.origin); + return { setWebOrigins: { __typename: 'WebOriginsSet', origins: saved } }; + }, +}; + +/** + * Set the AuthKit homepage URL with an API key. The key's environment has one + * AuthKit application, which REST updates without exposing its ID. + */ +export async function setHomepageUrl(ctx: ApiKeyContext, url: string): Promise { + await ctx.request({ method: 'PUT', path: '/user_management/app_homepage_url', body: { url } }); +} diff --git a/src/lib/api-key-operations/index.ts b/src/lib/api-key-operations/index.ts index ec3e67c9..edb923c8 100644 --- a/src/lib/api-key-operations/index.ts +++ b/src/lib/api-key-operations/index.ts @@ -29,6 +29,7 @@ import { userOperations } from './users.js'; import { membershipOperations } from './memberships.js'; import { rbacOperations } from './rbac.js'; import { platformOperations } from './platform.js'; +import { appConfigOperations } from './app-config.js'; const OPERATIONS: Record = { ...organizationOperations, @@ -36,6 +37,7 @@ const OPERATIONS: Record = { ...membershipOperations, ...rbacOperations, ...platformOperations, + ...appConfigOperations, }; /** @@ -102,3 +104,4 @@ export async function withApiKey(auth: ApiKeyAuth, run: (ctx: ApiKeyContext) export { exitApiKeyUnsupported, apiKeyUnsupportedMessage } from './context.js'; export { changeFlagTarget } from './platform.js'; +export { setHomepageUrl } from './app-config.js'; From 9ce531cfb5edd98a4df694936e2a1f760d8a88b6 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 12:25:04 -0800 Subject: [PATCH 07/32] test: cover resource commands with an API key, including session parity api-key-auth.spec.ts covers when the API-key path is chosen (unclaimed profile, WORKOS_API_KEY, --api-key), that signed-in users keep the session otherwise, the unsupported errors, and each command's REST requests. api-key-parity.spec.ts runs every list/get command on both paths against the same entity, feeding real dashboard and REST casing, and requires identical --json apart from the documented null fields in API_KEY_NULL_FIELDS. --- src/commands/api-key-auth.spec.ts | 701 +++++++++++++++++++ src/commands/api-key-parity.spec.ts | 831 +++++++++++++++++++++++ src/lib/__test-helpers__/rest-mock.ts | 80 +++ src/lib/api-key-operations/known-gaps.ts | 31 + 4 files changed, 1643 insertions(+) create mode 100644 src/commands/api-key-auth.spec.ts create mode 100644 src/commands/api-key-parity.spec.ts create mode 100644 src/lib/__test-helpers__/rest-mock.ts create mode 100644 src/lib/api-key-operations/known-gaps.ts diff --git a/src/commands/api-key-auth.spec.ts b/src/commands/api-key-auth.spec.ts new file mode 100644 index 00000000..b6057d2c --- /dev/null +++ b/src/commands/api-key-auth.spec.ts @@ -0,0 +1,701 @@ +/** + * The API-key path for environment-scoped resource commands: when it is + * chosen (unclaimed profile, WORKOS_API_KEY, --api-key), that signed-in users + * keep the dashboard session otherwise, and that each command's mutations hit + * the right REST endpoints with the key. Output parity lives in + * api-key-parity.spec.ts. + */ + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { createRestMock, restList } from '../lib/__test-helpers__/rest-mock.js'; + +const mockRequireCommandToken = vi.fn(); +const mockGraphqlRequest = vi.fn(); +const mockGetActiveEnvironment = vi.fn(); +const mockGetConfig = vi.fn(); + +vi.mock('../lib/command-auth.js', async (importActual) => { + const actual = await importActual(); + return { ...actual, requireCommandToken: () => mockRequireCommandToken() }; +}); + +vi.mock('../lib/dashboard-graphql.js', async (importActual) => { + const actual = await importActual(); + return { ...actual, dashboardGraphqlRequest: (...args: unknown[]) => mockGraphqlRequest(...args) }; +}); + +vi.mock('../utils/ui.js', () => ({ + default: { confirm: vi.fn(), isCancel: vi.fn(() => false), select: vi.fn() }, +})); + +vi.mock('../lib/config-store.js', async (importActual) => { + const actual = await importActual(); + return { + ...actual, + getActiveEnvironment: () => mockGetActiveEnvironment(), + getConfig: () => mockGetConfig(), + setProfileEnvironmentId: vi.fn(), + }; +}); + +const { setOutputMode } = await import('../utils/output.js'); +const { resetInteractionModeForTests } = await import('../utils/interaction-mode.js'); +const { CliExit } = await import('../utils/cli-exit.js'); +const { formatWorkOSCommand } = await import('../utils/command-invocation.js'); +const { setResourceApiKeyFlag } = await import('../lib/resource-auth.js'); +const { API_KEY_UNSUPPORTED, apiKeyUnsupportedMessage } = await import('../lib/api-key-operations/index.js'); +const { LEAK_PATTERN } = await import('../catalog/curation.js'); +const { runOrgList, runOrgGet, runOrgCreate, runOrgUpdate, runOrgDelete } = await import('./organization.js'); +const { runUserUpdate, runUserDelete } = await import('./user.js'); +const { runRoleCreate, runRoleUpdate, runRoleSetPermissions, runRoleDelete } = await import('./role.js'); +const { runPermissionCreate, runPermissionUpdate, runPermissionDelete } = await import('./permission.js'); +const { runMembershipCreate, runMembershipUpdate, runMembershipDelete, runMembershipDeactivate } = + await import('./membership.js'); +const { runInvitationSend, runInvitationRevoke } = await import('./invitation.js'); +const { runSessionRevoke } = await import('./session.js'); +const { runWebhookCreate, runWebhookDelete } = await import('./webhook.js'); +const { runFeatureFlagEnable, runFeatureFlagAddTarget, runFeatureFlagRemoveTarget } = await import('./feature-flag.js'); +const { runOrgDomainCreate, runOrgDomainVerify, runOrgDomainDelete } = await import('./org-domain.js'); +const { runConfigRedirectAdd, runConfigCorsAdd, runConfigHomepageUrlSet } = await import('./config.js'); +const { runAuthkitCorsSet, runAuthkitRedirectUrisSet, runAuthkitLogoutUrisList } = await import('./authkit.js'); +const { runBrandingGet } = await import('./branding.js'); +const { runEnvironmentRename } = await import('./environment.js'); +const { runTeamMembers } = await import('./team.js'); + +const rest = createRestMock(); + +const T0 = '2026-01-01T00:00:00.000Z'; +const REST_ORG = { + object: 'organization', + id: 'org_1', + name: 'FooCorp', + domains: [ + { + object: 'organization_domain', + id: 'dom_1', + organization_id: 'org_1', + domain: 'foo.com', + state: 'verified', + verification_strategy: 'dns', + created_at: T0, + updated_at: T0, + }, + ], + metadata: {}, + external_id: null, + created_at: T0, + updated_at: T0, +}; +const REST_ROLE = (overrides: Record = {}) => ({ + object: 'role', + id: 'role_admin', + name: 'Admin', + slug: 'admin', + description: 'Administrator', + type: 'EnvironmentRole', + resource_type_slug: 'organization', + permissions: ['users:read'], + created_at: T0, + updated_at: T0, + ...overrides, +}); +const REST_PERMISSION = { + object: 'permission', + id: 'perm_1', + slug: 'users:read', + name: 'Read users', + description: 'Read user records', + system: false, + resource_type_slug: 'organization', + created_at: T0, + updated_at: T0, +}; +const REST_MEMBERSHIP = { + object: 'organization_membership', + id: 'om_1', + user_id: 'user_1', + organization_id: 'org_1', + organization_name: 'FooCorp', + status: 'active', + role: { slug: 'member' }, + roles: [{ slug: 'member' }], + created_at: T0, + updated_at: T0, +}; + +const UNCLAIMED_PROFILE = { + name: 'unclaimed', + type: 'unclaimed', + apiKey: 'sk_test_unclaimed', + clientId: 'client_1', + claimToken: 'claim_1', +}; +const CLAIMED_PROFILE = { name: 'sandbox', type: 'sandbox', apiKey: 'sk_stored', environmentId: 'env_profile' }; + +const TEAM_PROJECTS_PAYLOAD = { + currentTeam: { + projectsV2: [{ id: 'proj_1', environments: [{ id: 'env_profile', name: 'Sandbox', sandbox: true }] }], + }, +}; + +let stdout: string[]; +let stderr: string[]; + +function useProfile(profile: Record): void { + mockGetActiveEnvironment.mockReturnValue(profile); + mockGetConfig.mockReturnValue({ + activeEnvironment: profile.name, + environments: { [profile.name as string]: profile }, + }); +} + +async function json(run: () => Promise): Promise> { + stdout = []; + await run(); + return JSON.parse(stdout[stdout.length - 1]); +} + +async function expectExit(run: () => Promise): Promise<{ code: string; message: string; exitCode: number }> { + stderr = []; + try { + await run(); + } catch (err) { + if (err instanceof CliExit) { + const payload = JSON.parse(stderr[stderr.length - 1]) as { error: { code: string; message: string } }; + return { ...payload.error, exitCode: err.exitCode }; + } + throw err; + } + throw new Error('Expected CliExit but the command resolved'); +} + +describe('resource commands with an API key', () => { + beforeEach(() => { + vi.clearAllMocks(); + resetInteractionModeForTests(); + setOutputMode('json'); + setResourceApiKeyFlag(undefined); + vi.stubGlobal('fetch', rest.fetchMock); + vi.stubEnv('WORKOS_API_KEY', ''); + vi.stubEnv('WORKOS_API_URL', ''); + vi.stubEnv('WORKOS_API_BASE_URL', ''); + rest.respond({}); + mockRequireCommandToken.mockResolvedValue('tok_session'); + mockGraphqlRequest.mockImplementation(async (doc: unknown) => { + if (String(doc).includes('teamProjectsV2')) return TEAM_PROJECTS_PAYLOAD; + return { organizations: { data: [], listMetadata: { before: null, after: null } } }; + }); + useProfile(CLAIMED_PROFILE); + stdout = []; + stderr = []; + vi.spyOn(console, 'log').mockImplementation((...args: unknown[]) => { + stdout.push(args.map(String).join(' ')); + }); + vi.spyOn(console, 'error').mockImplementation((...args: unknown[]) => { + stderr.push(args.map(String).join(' ')); + }); + }); + + afterEach(() => { + setResourceApiKeyFlag(undefined); + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + resetInteractionModeForTests(); + setOutputMode('human'); + }); + + describe('choosing the path', () => { + it('runs on REST with an API key from an unclaimed active profile, without a session', async () => { + useProfile(UNCLAIMED_PROFILE); + mockRequireCommandToken.mockRejectedValue(new Error('no session')); + rest.respond({ 'GET /organizations': restList([REST_ORG]) }); + + const out = await json(() => runOrgList({})); + + expect(out).toMatchObject({ organizations: [{ id: 'org_1', name: 'FooCorp' }] }); + expect(rest.callsTo('GET /organizations')[0].authorization).toBe('Bearer sk_test_unclaimed'); + expect(mockRequireCommandToken).not.toHaveBeenCalled(); + expect(mockGraphqlRequest).not.toHaveBeenCalled(); + }); + + it('runs on REST with an API key in WORKOS_API_KEY even when signed in', async () => { + vi.stubEnv('WORKOS_API_KEY', 'sk_test_env'); + rest.respond({ 'GET /organizations': restList([REST_ORG]) }); + + await json(() => runOrgList({})); + + expect(rest.callsTo('GET /organizations')[0].authorization).toBe('Bearer sk_test_env'); + expect(mockRequireCommandToken).not.toHaveBeenCalled(); + expect(mockGraphqlRequest).not.toHaveBeenCalled(); + }); + + it('lets an API key from --api-key win over WORKOS_API_KEY and the unclaimed profile', async () => { + useProfile(UNCLAIMED_PROFILE); + vi.stubEnv('WORKOS_API_KEY', 'sk_test_env'); + setResourceApiKeyFlag('sk_test_flag'); + rest.respond({ 'GET /organizations/org_1': REST_ORG }); + + await json(() => runOrgGet('org_1')); + + expect(rest.callsTo('GET /organizations/org_1')[0].authorization).toBe('Bearer sk_test_flag'); + }); + + it('keeps signed-in users on the dashboard session without an API key, ignoring a claimed profile’s stored key', async () => { + await json(() => runOrgList({})); + + expect(mockRequireCommandToken).toHaveBeenCalledOnce(); + expect(mockGraphqlRequest).toHaveBeenCalled(); + expect(rest.calls).toHaveLength(0); + }); + + it('refuses --environment-id with an API key, since the key picks the environment', async () => { + vi.stubEnv('WORKOS_API_KEY', 'sk_test_env'); + + const error = await expectExit(() => runOrgList({ environmentId: 'env_profile' })); + + expect(error).toMatchObject({ code: 'invalid_argument', exitCode: 1 }); + expect(error.message).toContain('--environment-id cannot be combined with an API key'); + expect(rest.calls).toHaveLength(0); + }); + + it('explains the unclaimed profile when --environment-id is passed with an API key from it', async () => { + useProfile(UNCLAIMED_PROFILE); + + const error = await expectExit(() => runOrgList({ environmentId: 'env_profile' })); + + expect(error.code).toBe('invalid_argument'); + expect(error.message).toContain('unclaimed environment'); + expect(error.message).toContain(formatWorkOSCommand('profile switch')); + }); + + it('keeps account-plane commands on the dashboard session with an API key set', async () => { + vi.stubEnv('WORKOS_API_KEY', 'sk_test_env'); + mockGraphqlRequest.mockImplementation(async (doc: unknown) => { + const text = String(doc); + if (text.includes('teamProjectsV2')) return TEAM_PROJECTS_PAYLOAD; + if (text.includes('renameEnvironment')) + return { renameEnvironment: { environment: { id: 'env_profile', name: 'Renamed' } } }; + return { currentTeam: { memberships: [] } }; + }); + + await json(() => runEnvironmentRename({ environmentId: 'env_profile', name: 'Renamed' })); + await json(() => runTeamMembers()); + + expect(mockRequireCommandToken).toHaveBeenCalledTimes(2); + expect(rest.calls).toHaveLength(0); + }); + }); + + describe('unsupported with an API key', () => { + beforeEach(() => { + vi.stubEnv('WORKOS_API_KEY', 'sk_test_env'); + }); + + it('fails branding get with a structured error naming what is missing with an API key', async () => { + const error = await expectExit(() => runBrandingGet({})); + + expect(error.code).toBe('api_key_unsupported'); + expect(error.message).toContain('branding images have no WorkOS API endpoint'); + expect(error.message).toContain(formatWorkOSCommand('auth login')); + expect(rest.calls).toHaveLength(0); + }); + + it('fails authkit logout-uris with a structured error with an API key', async () => { + const error = await expectExit(() => runAuthkitLogoutUrisList({})); + + expect(error.code).toBe('api_key_unsupported'); + expect(error.message).toContain('sign-out redirect URIs'); + }); + + it('keeps every unsupported-with-an-API-key message free of internal terms', async () => { + const messages = Object.values(API_KEY_UNSUPPORTED).map(apiKeyUnsupportedMessage); + messages.push((await expectExit(() => runBrandingGet({}))).message); + vi.stubEnv('WORKOS_API_KEY', 'sk_test_env'); + messages.push((await expectExit(() => runOrgList({ environmentId: 'env_x' }))).message); + for (const message of messages) expect(LEAK_PATTERN.test(message), message).toBe(false); + }); + + it('refuses --dry-run before any write with an API key', async () => { + const error = await expectExit(() => + runAuthkitRedirectUrisSet({ uris: ['https://a.example.com/cb'], dryRun: true }), + ); + + expect(error.code).toBe('api_key_unsupported'); + expect(error.message).toContain('--dry-run'); + expect(rest.calls).toHaveLength(0); + }); + + it('refuses to drop CORS origins (no REST delete) before any write with an API key', async () => { + rest.respond({ + 'GET /user_management/cors_origins': restList([ + { object: 'cors_origin', id: 'cors_1', origin: 'https://old.example.com' }, + ]), + }); + + const error = await expectExit(() => runAuthkitCorsSet({ origins: ['https://new.example.com'] })); + + expect(error.code).toBe('api_key_unsupported'); + expect(error.message).toContain('https://old.example.com'); + expect(rest.callsTo('POST /user_management/cors_origins')).toHaveLength(0); + }); + }); + + describe('REST requests with an API key', () => { + beforeEach(() => { + vi.stubEnv('WORKOS_API_KEY', 'sk_test_env'); + }); + + it('maps a REST 404 to the command’s not_found error with an API key', async () => { + const error = await expectExit(() => runOrgGet('org_missing')); + + expect(error.code).toBe('not_found'); + expect(error.message).toContain('org_missing'); + }); + + it('keeps the API’s own not-found message for other 404s with an API key', async () => { + rest.respond({ + 'PUT /organizations/org_missing': { status: 404, body: { message: "Organization not found: 'org_missing'." } }, + }); + + const error = await expectExit(() => runOrgUpdate('org_missing', 'Name')); + + expect(error).toMatchObject({ code: 'not_found', message: "Organization not found: 'org_missing'." }); + }); + + it('reports a rejected key as a structured error with an API key', async () => { + rest.respond({ 'GET /organizations': { status: 401, body: { message: 'Unauthorized' } } }); + + const error = await expectExit(() => runOrgList({})); + + expect(error.code).toBe('http_401'); + expect(error.message).toContain('Invalid API key'); + }); + + it('creates, updates and deletes organizations with an API key', async () => { + rest.respond({ + 'POST /organizations': REST_ORG, + 'PUT /organizations/org_1': { ...REST_ORG, name: 'Renamed' }, + 'DELETE /organizations/org_1': { status: 204 }, + }); + + const created = await json(() => runOrgCreate('FooCorp', ['foo.com:pending'])); + const updated = await json(() => runOrgUpdate('org_1', 'Renamed')); + const deleted = await json(() => runOrgDelete('org_1', { yes: true })); + + expect(rest.callsTo('POST /organizations')[0].body).toEqual({ + name: 'FooCorp', + domain_data: [{ domain: 'foo.com', state: 'pending' }], + }); + expect(rest.callsTo('PUT /organizations/org_1')[0].body).toEqual({ name: 'Renamed' }); + expect(created).toMatchObject({ organization: { id: 'org_1', domains: [{ id: 'dom_1', state: 'verified' }] } }); + expect(updated).toMatchObject({ organization: { name: 'Renamed' } }); + expect(deleted).toEqual({ deleted: 'org_1' }); + }); + + it('updates and deletes users with snake_case bodies with an API key', async () => { + rest.respond({ + 'PUT /user_management/users/user_1': { + object: 'user', + id: 'user_1', + email: 'j@example.com', + first_name: 'Jo', + last_name: 'Doe', + }, + 'DELETE /user_management/users/user_1': { status: 204 }, + }); + + const updated = await json(() => runUserUpdate('user_1', { firstName: 'Jo', externalId: 'ext_9' })); + const deleted = await json(() => runUserDelete('user_1', { yes: true })); + + expect(rest.callsTo('PUT /user_management/users/user_1')[0].body).toEqual({ + first_name: 'Jo', + external_id: 'ext_9', + }); + expect(updated).toEqual({ user: { id: 'user_1', email: 'j@example.com', firstName: 'Jo', lastName: 'Doe' } }); + expect(deleted).toEqual({ deleted: 'user_1' }); + }); + + it('reports a missing user as not_found on delete with an API key', async () => { + const error = await expectExit(() => runUserDelete('user_missing', { yes: true })); + expect(error.code).toBe('not_found'); + }); + + it('creates and updates roles by slug, replacing permissions, with an API key', async () => { + rest.respond({ + 'POST /authorization/roles': REST_ROLE({ id: 'role_new', slug: 'auditor', name: 'Auditor', permissions: [] }), + 'GET /authorization/roles': { object: 'list', data: [REST_ROLE()] }, + 'PATCH /authorization/roles/admin': REST_ROLE({ name: 'Administrators' }), + 'PUT /authorization/roles/admin/permissions': REST_ROLE({ permissions: ['users:read', 'users:write'] }), + }); + + const created = await json(() => runRoleCreate({ slug: 'auditor', name: 'Auditor', yes: true })); + const updated = await json(() => runRoleUpdate('admin', { name: 'Administrators', yes: true })); + const set = await json(() => runRoleSetPermissions('admin', ['users:read', 'users:write'], { yes: true })); + + expect(rest.callsTo('POST /authorization/roles')[0].body).toEqual({ slug: 'auditor', name: 'Auditor' }); + expect(created).toMatchObject({ role: { slug: 'auditor', type: 'environment' } }); + expect(rest.callsTo('PATCH /authorization/roles/admin')[0].body).toEqual({ + name: 'Administrators', + description: 'Administrator', + }); + expect(updated).toMatchObject({ role: { name: 'Administrators', permissions: ['users:read'] } }); + expect(rest.callsTo('PUT /authorization/roles/admin/permissions')[0].body).toEqual({ + permissions: ['users:read', 'users:write'], + }); + expect(set).toMatchObject({ role: { permissions: ['users:read', 'users:write'] } }); + }); + + it('reports an existing slug as already_exists on role create with an API key', async () => { + rest.respond({ + 'POST /authorization/roles': { status: 409, body: { message: 'exists', code: 'role_slug_already_exists' } }, + }); + + const error = await expectExit(() => runRoleCreate({ slug: 'admin', name: 'Admin', yes: true })); + expect(error.code).toBe('already_exists'); + }); + + it('deletes an organization role through the organization scope with an API key', async () => { + rest.respond({ + 'GET /authorization/organizations/org_1/roles': { + object: 'list', + data: [REST_ROLE(), REST_ROLE({ id: 'role_org', slug: 'billing', type: 'OrganizationRole' })], + }, + 'DELETE /authorization/organizations/org_1/roles/billing': { status: 204 }, + }); + + const out = await json(() => runRoleDelete('billing', { org: 'org_1', yes: true })); + + expect(out).toEqual({ deleted: 'billing' }); + expect(rest.callsTo('DELETE /authorization/organizations/org_1/roles/billing')).toHaveLength(1); + }); + + it('creates, updates and deletes permissions by slug with an API key', async () => { + rest.respond({ + 'POST /authorization/permissions': REST_PERMISSION, + 'GET /authorization/permissions': restList([REST_PERMISSION]), + 'PATCH /authorization/permissions/users:read': { ...REST_PERMISSION, name: 'View users' }, + 'DELETE /authorization/permissions/users:read': { status: 204 }, + }); + + await json(() => runPermissionCreate({ slug: 'users:read', name: 'Read users', yes: true })); + const updated = await json(() => runPermissionUpdate('users:read', { name: 'View users', yes: true })); + const deleted = await json(() => runPermissionDelete('users:read', { yes: true })); + + expect(updated).toMatchObject({ permission: { slug: 'users:read', name: 'View users' } }); + expect(deleted).toEqual({ deleted: 'users:read' }); + }); + + it('resolves role IDs to slugs for memberships and invitations with an API key', async () => { + rest.respond({ + 'GET /authorization/roles': { + object: 'list', + data: [REST_ROLE({ id: 'role_member', slug: 'member', name: 'Member' })], + }, + 'POST /user_management/organization_memberships': REST_MEMBERSHIP, + 'GET /user_management/organization_memberships/om_1': REST_MEMBERSHIP, + 'PUT /user_management/organization_memberships/om_1': REST_MEMBERSHIP, + 'POST /user_management/invitations': { + object: 'invitation', + id: 'invitation_1', + email: 'n@example.com', + state: 'pending', + }, + }); + + const added = await json(() => runMembershipCreate({ org: 'org_1', user: 'user_1', role: 'role_member' })); + const updated = await json(() => runMembershipUpdate('om_1', { role: 'role_member', yes: true })); + const invited = await json(() => + runInvitationSend({ email: 'n@example.com', org: 'org_1', role: 'role_member' }), + ); + + expect(rest.callsTo('POST /user_management/organization_memberships')[0].body).toEqual({ + organization_id: 'org_1', + user_id: 'user_1', + role_slug: 'member', + }); + expect(added).toEqual({ added: { organizationId: 'org_1', userId: 'user_1' } }); + expect(rest.callsTo('PUT /user_management/organization_memberships/om_1')[0].body).toEqual({ + role_slug: 'member', + }); + expect(updated).toMatchObject({ membership: { id: 'om_1', role: 'member', state: 'active' } }); + expect(rest.callsTo('POST /user_management/invitations')[0].body).toEqual({ + email: 'n@example.com', + expires_in_days: 7, + organization_id: 'org_1', + role_slug: 'member', + }); + expect(invited).toEqual({ invitation: { id: 'invitation_1' } }); + }); + + it('reports an unknown role ID as not_found on membership update with an API key', async () => { + rest.respond({ + 'GET /authorization/roles': { object: 'list', data: [] }, + 'GET /authorization/organizations/org_1/roles': { object: 'list', data: [] }, + 'GET /user_management/organization_memberships/om_1': REST_MEMBERSHIP, + }); + + const error = await expectExit(() => runMembershipUpdate('om_1', { role: 'role_nope', yes: true })); + expect(error).toMatchObject({ code: 'not_found' }); + expect(error.message).toContain('role_nope'); + }); + + it('deletes and deactivates memberships by ID with an API key', async () => { + rest.respond({ + 'GET /user_management/organization_memberships/om_1': REST_MEMBERSHIP, + 'GET /user_management/organization_memberships': restList([REST_MEMBERSHIP]), + 'DELETE /user_management/organization_memberships/om_1': { status: 204 }, + 'PUT /user_management/organization_memberships/om_1/deactivate': REST_MEMBERSHIP, + }); + + const deleted = await json(() => runMembershipDelete('om_1', { yes: true })); + const deactivated = await json(() => runMembershipDeactivate('om_1', { yes: true })); + + expect(rest.callsTo('GET /user_management/organization_memberships')[0].query).toMatchObject({ + organization_id: 'org_1', + user_id: 'user_1', + }); + expect(deleted).toEqual({ deleted: 'om_1' }); + expect(deactivated).toEqual({ deactivated: 'om_1' }); + }); + + it('revokes invitations and sessions with an API key', async () => { + rest.respond({ + 'POST /user_management/invitations/invitation_1/revoke': { + object: 'invitation', + id: 'invitation_1', + state: 'revoked', + }, + 'POST /user_management/sessions/revoke': { status: 204 }, + }); + + expect(await json(() => runInvitationRevoke('invitation_1', { yes: true }))).toEqual({ revoked: 'invitation_1' }); + expect(await json(() => runSessionRevoke('session_1', { yes: true }))).toEqual({ revoked: 'session_1' }); + expect(rest.callsTo('POST /user_management/sessions/revoke')[0].body).toEqual({ session_id: 'session_1' }); + }); + + it('creates and deletes webhook endpoints with an API key', async () => { + rest.respond({ + 'POST /webhook_endpoints': { + object: 'webhook_endpoint', + id: 'we_1', + endpoint_url: 'https://e.example.com', + status: 'enabled', + }, + 'DELETE /webhook_endpoints/we_1': { status: 204 }, + }); + + const created = await json(() => runWebhookCreate({ url: 'https://e.example.com', events: ['user.created'] })); + const deleted = await json(() => runWebhookDelete('we_1', { yes: true })); + + expect(rest.callsTo('POST /webhook_endpoints')[0].body).toEqual({ + endpoint_url: 'https://e.example.com', + events: ['user.created'], + }); + expect(created).toEqual({ + webhookEndpoint: { id: 'we_1', url: 'https://e.example.com', events: ['user.created'] }, + }); + expect(deleted).toEqual({ deleted: 'we_1' }); + }); + + it('enables flags and changes targets through the REST endpoints with an API key', async () => { + const flag = { + object: 'feature_flag', + id: 'flag_1', + slug: 'beta', + name: 'Beta', + enabled: false, + default_value: false, + tags: [], + }; + rest.respond({ + 'GET /feature-flags/beta': flag, + 'PUT /feature-flags/beta/enable': { ...flag, enabled: true }, + 'POST /feature-flags/beta/targets/org_1': { status: 204 }, + 'DELETE /feature-flags/beta/targets/user_1': { status: 204 }, + }); + + expect(await json(() => runFeatureFlagEnable('beta'))).toEqual({ enabled: 'beta' }); + expect(await json(() => runFeatureFlagAddTarget('beta', 'org_1'))).toEqual({ + added: { flag: 'beta', targetId: 'org_1' }, + }); + expect(await json(() => runFeatureFlagRemoveTarget('beta', 'user_1'))).toEqual({ + removed: { flag: 'beta', targetId: 'user_1' }, + }); + expect(rest.callsTo('PUT /feature-flags/beta/enable')).toHaveLength(1); + // No project lookup on the key path: the key is the environment. + expect(mockGraphqlRequest).not.toHaveBeenCalled(); + }); + + it('adds, verifies and deletes organization domains with an API key', async () => { + const domain = { + object: 'organization_domain', + id: 'dom_2', + organization_id: 'org_1', + domain: 'bar.com', + state: 'pending', + verification_strategy: 'dns', + }; + rest.respond({ + 'POST /organization_domains': domain, + 'POST /organization_domains/dom_2/verify': domain, + 'DELETE /organization_domains/dom_2': { status: 204 }, + }); + + const created = await json(() => runOrgDomainCreate('bar.com', { org: 'org_1' })); + const verified = await json(() => runOrgDomainVerify('dom_2')); + const deleted = await json(() => runOrgDomainDelete('dom_2', { yes: true })); + + expect(rest.callsTo('POST /organization_domains')[0].body).toEqual({ + organization_id: 'org_1', + domain: 'bar.com', + }); + expect(created).toMatchObject({ + domain: { id: 'dom_2', state: 'pending', verificationStrategy: 'dns', organizationId: 'org_1' }, + }); + expect(verified).toMatchObject({ domain: { id: 'dom_2', domain: 'bar.com' } }); + expect(deleted).toEqual({ deleted: 'dom_2' }); + }); + + it('adds redirect URIs and CORS origins without rewriting the rest with an API key', async () => { + const existing = { object: 'redirect_uri', id: 'ru_1', uri: 'https://a.example.com/cb', default: true }; + let created = false; + rest.respond({ + 'GET /user_management/redirect_uris': () => + restList( + created + ? [existing, { object: 'redirect_uri', id: 'ru_2', uri: 'https://b.example.com/cb', default: false }] + : [existing], + ), + 'POST /user_management/redirect_uris': () => { + created = true; + return { object: 'redirect_uri', id: 'ru_2', uri: 'https://b.example.com/cb', default: false }; + }, + 'GET /user_management/cors_origins': restList([]), + 'POST /user_management/cors_origins': { object: 'cors_origin', id: 'cors_1', origin: 'https://b.example.com' }, + }); + + expect(await json(() => runConfigRedirectAdd('https://b.example.com/cb'))).toEqual({ + uri: 'https://b.example.com/cb', + alreadyExists: false, + }); + expect(await json(() => runConfigCorsAdd('https://b.example.com'))).toEqual({ + origin: 'https://b.example.com', + alreadyExists: false, + }); + expect(rest.callsTo('POST /user_management/redirect_uris').map((c) => c.body)).toEqual([ + { uri: 'https://b.example.com/cb' }, + ]); + expect(rest.callsTo('DELETE /user_management/redirect_uris/ru_1')).toHaveLength(0); + }); + + it('sets the homepage URL with a null applicationId with an API key', async () => { + rest.respond({ 'PUT /user_management/app_homepage_url': { status: 204 } }); + + const out = await json(() => runConfigHomepageUrlSet('https://app.example.com')); + + expect(rest.callsTo('PUT /user_management/app_homepage_url')[0].body).toEqual({ url: 'https://app.example.com' }); + expect(out).toEqual({ homepageUrl: 'https://app.example.com', applicationId: null }); + }); + }); +}); diff --git a/src/commands/api-key-parity.spec.ts b/src/commands/api-key-parity.spec.ts new file mode 100644 index 00000000..7495f4f2 --- /dev/null +++ b/src/commands/api-key-parity.spec.ts @@ -0,0 +1,831 @@ +/** + * Offline parity: every resource command's `--json` output must be the same on + * the dashboard-session path and the API-key (REST) path. + * + * Each case runs the real handler twice against the same entity: once with the + * dashboard wire mocked (real dashboard casing: `Verified`, `Active`, metadata + * as `{key,value}` pairs) and once with `fetch` mocked to return real WorkOS + * REST responses (snake_case keys, REST casing: `verified`, `EnvironmentRole`, + * `enabled`, metadata as an object). The outputs must be deep-equal, except the + * fields in `API_KEY_NULL_FIELDS`, which must be `null` on the key path (REST + * has no source for them). A casing-only difference fails here. + */ + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { createRestMock, restList } from '../lib/__test-helpers__/rest-mock.js'; + +const mockRequireCommandToken = vi.fn(); +const mockGraphqlRequest = vi.fn(); +const mockGetActiveEnvironment = vi.fn(); +const mockGetConfig = vi.fn(); + +vi.mock('../lib/command-auth.js', async (importActual) => { + const actual = await importActual(); + return { ...actual, requireCommandToken: () => mockRequireCommandToken() }; +}); + +vi.mock('../lib/dashboard-graphql.js', async (importActual) => { + const actual = await importActual(); + return { ...actual, dashboardGraphqlRequest: (...args: unknown[]) => mockGraphqlRequest(...args) }; +}); + +vi.mock('../utils/ui.js', () => ({ + default: { confirm: vi.fn(), isCancel: vi.fn(() => false), select: vi.fn() }, +})); + +vi.mock('../lib/config-store.js', async (importActual) => { + const actual = await importActual(); + return { + ...actual, + getActiveEnvironment: () => mockGetActiveEnvironment(), + getConfig: () => mockGetConfig(), + setProfileEnvironmentId: vi.fn(), + }; +}); + +const { setOutputMode } = await import('../utils/output.js'); +const { resetInteractionModeForTests } = await import('../utils/interaction-mode.js'); +const { setResourceApiKeyFlag } = await import('../lib/resource-auth.js'); +const { API_KEY_NULL_FIELDS } = await import('../lib/api-key-operations/known-gaps.js'); +const { runOrgList, runOrgGet } = await import('./organization.js'); +const { runUserList, runUserGet } = await import('./user.js'); +const { runRoleList, runRoleGet } = await import('./role.js'); +const { runPermissionList, runPermissionGet } = await import('./permission.js'); +const { runInvitationList, runInvitationGet } = await import('./invitation.js'); +const { runMembershipList, runMembershipGet } = await import('./membership.js'); +const { runSessionList } = await import('./session.js'); +const { runWebhookList } = await import('./webhook.js'); +const { runEventList } = await import('./event.js'); +const { runFeatureFlagList, runFeatureFlagGet } = await import('./feature-flag.js'); +const { runOrgDomainGet } = await import('./org-domain.js'); +const { runPortalGenerateLink } = await import('./portal.js'); + +const rest = createRestMock(); + +const TEAM_PROJECTS_PAYLOAD = { + currentTeam: { + projectsV2: [ + { id: 'proj_1', environments: [{ id: 'env_profile', name: 'Sandbox', sandbox: true, clientId: null }] }, + ], + }, +}; + +const T0 = '2026-01-01T00:00:00.000Z'; +const T1 = '2026-02-01T00:00:00.000Z'; + +// --------------------------------------------------------------------------- +// Dashboard fixtures (real dashboard casing and transport shapes) +// --------------------------------------------------------------------------- + +const GQL_ORG = { + id: 'org_1', + name: 'FooCorp', + createdAt: T0, + usersCount: 3, + allowProfilesOutsideOrganization: false, + externalId: 'ext_1', + metadata: [{ key: 'team', value: 'blue' }], + domains: [{ id: 'dom_1', domain: 'foo.com', state: 'Verified', verificationStrategy: 'Dns' }], + seeded: false, +}; + +const GQL_IDENTITY = { + id: 'om_1', + status: 'Active', + directoryUserId: null, + role: { id: 'role_member', name: 'Member' }, + roles: [{ id: 'role_member', name: 'Member' }], + organization: { id: 'org_1', name: 'FooCorp' }, + createdAt: T0, + updatedAt: T1, +}; + +const GQL_USER = { + id: 'user_1', + email: 'jane@example.com', + firstName: 'Jane', + lastName: 'Doe', + createdAt: T0, + emailVerifiedAt: '2026-01-02T00:00:00.000Z', + lastSignedInAt: T1, + sessionCount: 4, + hasPassword: true, + locale: 'en-US', + externalId: null, + profilePictureUrl: 'https://example.com/jane.png', + metadata: [{ key: 'team', value: 'blue' }], + identities: { data: [GQL_IDENTITY] }, +}; + +const GQL_ROLE = { + id: 'role_admin', + name: 'Admin', + slug: 'admin', + description: 'Administrator', + state: 'Active', + type: 'Environment', + permissions: [{ id: 'perm_1', slug: 'users:read' }], + createdAt: T0, + updatedAt: T1, +}; + +const GQL_PERMISSION = { + id: 'perm_1', + name: 'Read users', + slug: 'users:read', + description: 'Read user records', + system: false, + createdAt: T0, + updatedAt: T1, +}; + +const GQL_INVITE = { + __typename: 'UserlandUserInvite', + id: 'invitation_1', + createdAt: T0, + inviteeEmail: 'new@example.com', + state: 'Pending', + organization: { id: 'org_1', name: 'FooCorp' }, +}; + +const GQL_MEMBERSHIP = { + id: 'om_1', + type: 'Standard', + status: 'Active', + organizationId: 'org_1', + userlandUserId: 'user_1', + directoryUserId: null, + role: { slug: 'member' }, + roles: [{ slug: 'member' }], + createdAt: T0, + updatedAt: T1, +}; + +const GQL_SESSION = { + __typename: 'UserlandSession', + id: 'session_1', + createdAt: T0, + updatedAt: T1, + ipAddress: '203.0.113.7', + userAgent: 'Mozilla/5.0', + provider: 'Password', + impersonator: null, + impersonationReason: null, + organization: { id: 'org_1', name: 'FooCorp' }, + application: { id: 'app_1', name: 'Web' }, + state: { __typename: 'UserlandSessionIssued', expiresAt: '2026-03-01T00:00:00.000Z' }, +}; + +const GQL_ENDPOINT = { + id: 'we_1', + endpointUrl: 'https://example.com/hook', + events: ['user.created'], + state: 'Active', + createdAt: T0, +}; + +const GQL_EVENT = { + id: 'event_1', + name: 'user.created', + data: { id: 'user_1' }, + context: {}, + createdAt: T0, + updatedAt: T0, + metadata: {}, +}; + +const GQL_FLAG = { + id: 'flag_1', + name: 'Beta', + slug: 'beta', + description: 'Beta feature', + projectId: 'proj_1', + flagEnvironments: [ + { + id: 'fe_1', + environmentId: 'env_profile', + flagId: 'flag_1', + flagEnabled: true, + defaultEnabled: false, + accessType: 'SOME', + organizations: [{ id: 'org_1', name: 'FooCorp' }], + users: [], + }, + ], + createdAt: T0, + updatedAt: T1, + tags: [{ id: 'tag_1', name: 'beta-wave' }], +}; + +const GQL_DOMAIN = { + id: 'dom_1', + domain: 'foo.com', + state: 'Verified', + subdomain: null, + verificationContent: 'workos-verify=abc123', + verificationStrategy: 'Dns', + domainCaptureEnabled: false, +}; + +// --------------------------------------------------------------------------- +// REST fixtures (real WorkOS REST response shapes and casing) +// --------------------------------------------------------------------------- + +const REST_ORG = { + object: 'organization', + id: 'org_1', + name: 'FooCorp', + domains: [ + { + object: 'organization_domain', + id: 'dom_1', + organization_id: 'org_1', + domain: 'foo.com', + state: 'verified', + verification_strategy: 'dns', + verification_token: 'abc123', + verification_prefix: 'workos-verify', + created_at: T0, + updated_at: T0, + }, + ], + metadata: { team: 'blue' }, + external_id: 'ext_1', + stripe_customer_id: 'cus_internal', + allow_profiles_outside_organization: false, + created_at: T0, + updated_at: T1, +}; + +const REST_USER = { + object: 'user', + id: 'user_1', + email: 'jane@example.com', + first_name: 'Jane', + last_name: 'Doe', + email_verified: true, + profile_picture_url: 'https://example.com/jane.png', + last_sign_in_at: T1, + locale: 'en-US', + external_id: null, + metadata: { team: 'blue' }, + created_at: T0, + updated_at: T1, +}; + +const REST_MEMBERSHIP = { + object: 'organization_membership', + id: 'om_1', + user_id: 'user_1', + organization_id: 'org_1', + organization_name: 'FooCorp', + status: 'active', + directory_managed: false, + role: { slug: 'member' }, + roles: [{ slug: 'member' }], + custom_attributes: {}, + created_at: T0, + updated_at: T1, +}; + +const REST_ROLE_MEMBER = { + object: 'role', + id: 'role_member', + name: 'Member', + slug: 'member', + description: null, + type: 'EnvironmentRole', + resource_type_slug: 'organization', + permissions: [], + created_at: T0, + updated_at: T0, +}; + +const REST_ROLE_ADMIN = { + object: 'role', + id: 'role_admin', + name: 'Admin', + slug: 'admin', + description: 'Administrator', + type: 'EnvironmentRole', + resource_type_slug: 'organization', + permissions: ['users:read'], + created_at: T0, + updated_at: T1, +}; + +const REST_PERMISSION = { + object: 'permission', + id: 'perm_1', + slug: 'users:read', + name: 'Read users', + description: 'Read user records', + system: false, + resource_type_slug: 'organization', + created_at: T0, + updated_at: T1, +}; + +const REST_INVITE = { + object: 'invitation', + id: 'invitation_1', + email: 'new@example.com', + state: 'pending', + accepted_at: null, + revoked_at: null, + expires_at: '2026-01-08T00:00:00.000Z', + organization_id: 'org_1', + inviter_user_id: null, + accepted_user_id: null, + token: 'tok_secret', + accept_invitation_url: 'https://example.com/invite', + created_at: T0, + updated_at: T0, +}; + +const REST_SESSION = { + object: 'session', + id: 'session_1', + impersonator: null, + ip_address: '203.0.113.7', + organization_id: 'org_1', + user_agent: 'Mozilla/5.0', + user_id: 'user_1', + auth_method: 'password', + status: 'active', + expires_at: '2026-03-01T00:00:00.000Z', + ended_at: null, + created_at: T0, + updated_at: T1, +}; + +const REST_ENDPOINT = { + object: 'webhook_endpoint', + id: 'we_1', + endpoint_url: 'https://example.com/hook', + secret: 'whsec_internal', + status: 'enabled', + events: ['user.created'], + created_at: T0, + updated_at: T0, +}; + +const REST_EVENT = { + object: 'event', + id: 'event_1', + event: 'user.created', + data: { id: 'user_1' }, + created_at: T0, + context: {}, +}; + +const REST_FLAG = { + object: 'feature_flag', + id: 'flag_1', + slug: 'beta', + name: 'Beta', + description: 'Beta feature', + owner: null, + tags: ['beta-wave'], + enabled: true, + default_value: false, + created_at: T0, + updated_at: T1, +}; + +// --------------------------------------------------------------------------- +// Harness +// --------------------------------------------------------------------------- + +let consoleOutput: string[]; + +async function render(run: () => Promise): Promise> { + consoleOutput = []; + await run(); + return JSON.parse(consoleOutput[0]); +} + +/** Run on the dashboard path: no key, signed in, dashboard wire mocked. */ +async function viaSession(router: (doc: string) => unknown, run: () => Promise) { + vi.stubEnv('WORKOS_API_KEY', ''); + mockGraphqlRequest.mockImplementation(async (doc: unknown) => { + const text = String(doc); + if (text.includes('teamProjectsV2')) return TEAM_PROJECTS_PAYLOAD; + return router(text); + }); + rest.respond({}); + const output = await render(run); + expect(rest.calls).toHaveLength(0); + return output; +} + +/** Run on the API-key path: WORKOS_API_KEY set, REST mocked. */ +async function viaApiKey(routes: Parameters[0], run: () => Promise) { + vi.stubEnv('WORKOS_API_KEY', 'sk_test_parity'); + mockGraphqlRequest.mockReset(); + mockRequireCommandToken.mockClear(); + rest.respond(routes); + const output = await render(run); + expect(mockGraphqlRequest).not.toHaveBeenCalled(); + expect(mockRequireCommandToken).not.toHaveBeenCalled(); + for (const call of rest.calls) expect(call.authorization).toBe('Bearer sk_test_parity'); + return output; +} + +type Json = Record | unknown[]; + +function at(value: Json, path: string[]): { parent: Record; key: string } { + let node: unknown = value; + for (const segment of path.slice(0, -1)) node = (node as Record)[segment]; + return { parent: node as Record, key: path[path.length - 1] }; +} + +/** + * Assert the two outputs are identical except `nullOnKeyPath` (dot paths into + * the output), which must be null on the key path and must each be a listed + * known gap (`command.field`). + */ +function expectParity( + command: string, + session: Json, + apiKey: Json, + nullOnKeyPath: Array<{ path: string; field: string }> = [], +): void { + const s = structuredClone(session); + const k = structuredClone(apiKey); + for (const { path, field } of nullOnKeyPath) { + expect(API_KEY_NULL_FIELDS, `${command}.${field} must be a documented gap`).toHaveProperty([`${command}.${field}`]); + const keyed = at(k, path.split('.')); + expect(keyed.parent[keyed.key], `${path} on the key path`).toBeNull(); + const sessioned = at(s, path.split('.')); + sessioned.parent[sessioned.key] = null; + } + expect(k).toEqual(s); +} + +describe('resource command --json parity, session vs API key', () => { + beforeEach(() => { + vi.clearAllMocks(); + resetInteractionModeForTests(); + setOutputMode('json'); + setResourceApiKeyFlag(undefined); + vi.stubGlobal('fetch', rest.fetchMock); + vi.stubEnv('WORKOS_API_URL', ''); + vi.stubEnv('WORKOS_API_BASE_URL', ''); + mockRequireCommandToken.mockResolvedValue('tok_123'); + // A claimed profile with a stored key: the session path must still win without an explicit key. + mockGetActiveEnvironment.mockReturnValue({ + name: 'sandbox', + type: 'sandbox', + apiKey: 'sk_stored', + environmentId: 'env_profile', + }); + mockGetConfig.mockReturnValue({ + activeEnvironment: 'sandbox', + environments: { + sandbox: { name: 'sandbox', type: 'sandbox', apiKey: 'sk_stored', environmentId: 'env_profile' }, + }, + }); + consoleOutput = []; + vi.spyOn(console, 'log').mockImplementation((...args: unknown[]) => { + consoleOutput.push(args.map(String).join(' ')); + }); + vi.spyOn(console, 'error').mockImplementation(() => {}); + }); + + afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + resetInteractionModeForTests(); + setOutputMode('human'); + }); + + it('organization list matches with an API key', async () => { + const session = await viaSession( + () => ({ organizations: { data: [GQL_ORG], listMetadata: { before: null, after: 'org_1' } } }), + () => runOrgList({}), + ); + const apiKey = await viaApiKey({ 'GET /organizations': restList([REST_ORG], 'org_1') }, () => runOrgList({})); + + expectParity('organization', session, apiKey, [{ path: 'organizations.0.usersCount', field: 'usersCount' }]); + expect(apiKey).toMatchObject({ organizations: [{ domains: [{ state: 'verified' }], metadata: { team: 'blue' } }] }); + }); + + it('organization get matches with an API key', async () => { + const session = await viaSession( + () => ({ organization: GQL_ORG }), + () => runOrgGet('org_1'), + ); + const apiKey = await viaApiKey({ 'GET /organizations/org_1': REST_ORG }, () => runOrgGet('org_1')); + + expectParity('organization', session, apiKey, [{ path: 'organization.usersCount', field: 'usersCount' }]); + }); + + const userRestRoutes = { + 'GET /user_management/users': restList([REST_USER], 'user_1'), + 'GET /user_management/users/user_1': REST_USER, + 'GET /user_management/organization_memberships': restList([REST_MEMBERSHIP]), + 'GET /user_management/users/user_1/auth_factors': restList([ + { + object: 'authentication_factor', + id: 'auth_factor_1', + type: 'totp', + user_id: 'user_1', + created_at: T0, + updated_at: T0, + }, + ]), + 'GET /authorization/roles': { object: 'list', data: [REST_ROLE_MEMBER, REST_ROLE_ADMIN] }, + }; + + it('user list matches with an API key', async () => { + const session = await viaSession( + () => ({ userlandUsers: { data: [GQL_USER], listMetadata: { before: null, after: 'user_1' } } }), + () => runUserList({}), + ); + const apiKey = await viaApiKey(userRestRoutes, () => runUserList({})); + + expectParity('user', session, apiKey, [ + { path: 'users.0.sessionCount', field: 'sessionCount' }, + { path: 'users.0.hasPassword', field: 'hasPassword' }, + { path: 'users.0.emailVerifiedAt', field: 'emailVerifiedAt' }, + ]); + // Identities are filled from memberships, with role IDs/names resolved from slugs. + expect(apiKey).toMatchObject({ + users: [ + { + identities: [ + { + id: 'om_1', + state: 'active', + organization: { id: 'org_1', name: 'FooCorp' }, + roles: [{ id: 'role_member', name: 'Member' }], + }, + ], + }, + ], + }); + expect(rest.callsTo('GET /user_management/organization_memberships')[0].query).toMatchObject({ user_id: 'user_1' }); + }); + + it('user get matches with an API key', async () => { + const session = await viaSession( + () => ({ + userlandUser: { ...GQL_USER, authenticationFactors: [{ id: 'auth_factor_1', lastVerifiedAt: T1 }] }, + }), + () => runUserGet('user_1'), + ); + const apiKey = await viaApiKey(userRestRoutes, () => runUserGet('user_1')); + + expectParity('user', session, apiKey, [ + { path: 'user.sessionCount', field: 'sessionCount' }, + { path: 'user.hasPassword', field: 'hasPassword' }, + { path: 'user.emailVerifiedAt', field: 'emailVerifiedAt' }, + { path: 'user.authenticationFactors.0.lastVerifiedAt', field: 'authenticationFactors' }, + ]); + }); + + it('role list and get match with an API key', async () => { + const router = () => ({ rolesForEnvironment: { roles: [GQL_ROLE] } }); + const routes = { 'GET /authorization/roles': { object: 'list', data: [REST_ROLE_ADMIN] } }; + + expectParity( + 'role', + await viaSession(router, () => runRoleList({})), + await viaApiKey(routes, () => runRoleList({})), + ); + expectParity( + 'role', + await viaSession(router, () => runRoleGet('admin')), + await viaApiKey(routes, () => runRoleGet('admin')), + ); + }); + + it('organization role list matches with an API key', async () => { + const orgRole = { ...GQL_ROLE, id: 'role_org', slug: 'billing', type: 'Organization' }; + const restOrgRole = { ...REST_ROLE_ADMIN, id: 'role_org', slug: 'billing', type: 'OrganizationRole' }; + const session = await viaSession( + () => ({ rolesForOrganization: { roles: [GQL_ROLE, orgRole] } }), + () => runRoleList({ org: 'org_1' }), + ); + const apiKey = await viaApiKey( + { 'GET /authorization/organizations/org_1/roles': { object: 'list', data: [REST_ROLE_ADMIN, restOrgRole] } }, + () => runRoleList({ org: 'org_1' }), + ); + expectParity('role', session, apiKey); + expect(apiKey).toMatchObject({ roles: [{ type: 'environment' }, { type: 'organization' }] }); + }); + + it('permission list and get match with an API key', async () => { + const router = () => ({ permissionsForEnvironment: { permissions: [GQL_PERMISSION] } }); + const routes = { 'GET /authorization/permissions': restList([REST_PERMISSION]) }; + + expectParity( + 'permission', + await viaSession(router, () => runPermissionList({})), + await viaApiKey(routes, () => runPermissionList({})), + ); + expectParity( + 'permission', + await viaSession(router, () => runPermissionGet('users:read')), + await viaApiKey(routes, () => runPermissionGet('users:read')), + ); + }); + + it('invitation list and get match with an API key', async () => { + const router = () => ({ userlandUserInvites: { data: [GQL_INVITE], listMetadata: { before: null, after: null } } }); + const routes = { + 'GET /user_management/invitations': restList([REST_INVITE]), + 'GET /organizations/org_1': REST_ORG, + }; + + expectParity( + 'invitation', + await viaSession(router, () => runInvitationList({})), + await viaApiKey(routes, () => runInvitationList({})), + ); + expectParity( + 'invitation', + await viaSession(router, () => runInvitationGet('invitation_1')), + await viaApiKey(routes, () => runInvitationGet('invitation_1')), + ); + }); + + it('invitation list by organization matches with an API key', async () => { + const { organization: _organization, ...byOrgInvite } = GQL_INVITE; + const session = await viaSession( + () => ({ + organization: { userlandUserInvites: { data: [byOrgInvite], listMetadata: { before: null, after: null } } }, + }), + () => runInvitationList({ org: 'org_1' }), + ); + const apiKey = await viaApiKey( + { 'GET /organizations/org_1': REST_ORG, 'GET /user_management/invitations': restList([REST_INVITE]) }, + () => runInvitationList({ org: 'org_1' }), + ); + expectParity('invitation', session, apiKey); + expect(rest.callsTo('GET /user_management/invitations')[0].query).toMatchObject({ organization_id: 'org_1' }); + }); + + it('membership list (by user) and get match with an API key', async () => { + const membershipNull = (path: string) => [{ path, field: 'type' }]; + expectParity( + 'membership', + await viaSession( + () => ({ userlandUserOrganizationMemberships: { organizationMemberships: [GQL_MEMBERSHIP] } }), + () => runMembershipList({ user: 'user_1' }), + ), + await viaApiKey({ 'GET /user_management/organization_memberships': restList([REST_MEMBERSHIP]) }, () => + runMembershipList({ user: 'user_1' }), + ), + membershipNull('memberships.0.type'), + ); + expectParity( + 'membership', + await viaSession( + () => ({ userlandUserOrganizationMembership: GQL_MEMBERSHIP }), + () => runMembershipGet('om_1'), + ), + await viaApiKey({ 'GET /user_management/organization_memberships/om_1': REST_MEMBERSHIP }, () => + runMembershipGet('om_1'), + ), + membershipNull('membership.type'), + ); + }); + + it('membership list (by organization) matches with an API key', async () => { + const session = await viaSession( + () => ({ + organization: { + userlandUsers: { + data: [ + { + id: 'user_1', + identities: { data: [{ ...GQL_IDENTITY, role: { slug: 'member' }, roles: [{ slug: 'member' }] }] }, + }, + ], + listMetadata: { before: null, after: 'om_1' }, + }, + }, + }), + () => runMembershipList({ org: 'org_1' }), + ); + const apiKey = await viaApiKey( + { + 'GET /organizations/org_1': REST_ORG, + 'GET /user_management/organization_memberships': restList([REST_MEMBERSHIP], 'om_1'), + }, + () => runMembershipList({ org: 'org_1' }), + ); + expectParity('membership', session, apiKey); + }); + + it('session list matches with an API key', async () => { + const session = await viaSession( + () => ({ + userlandUser: { + id: 'user_1', + sessions: { data: [GQL_SESSION], listMetadata: { before: null, after: 'session_1' } }, + }, + }), + () => runSessionList('user_1', {}), + ); + const apiKey = await viaApiKey( + { + 'GET /user_management/users/user_1/sessions': restList([REST_SESSION], 'session_1'), + 'GET /organizations/org_1': REST_ORG, + }, + () => runSessionList('user_1', {}), + ); + expectParity('session', session, apiKey); + expect(apiKey).toMatchObject({ sessions: [{ state: 'active', provider: 'Password' }] }); + }); + + it('webhook list matches with an API key', async () => { + const session = await viaSession( + () => ({ webhookEndpoints: { data: [GQL_ENDPOINT], listMetadata: { before: null, after: null } } }), + () => runWebhookList({}), + ); + const apiKey = await viaApiKey({ 'GET /webhook_endpoints': restList([REST_ENDPOINT]) }, () => runWebhookList({})); + expectParity('webhook', session, apiKey); + expect(apiKey).toMatchObject({ webhookEndpoints: [{ state: 'active' }] }); + }); + + it('event list matches with an API key, newest first with the same cursor contract', async () => { + const session = await viaSession( + () => ({ environment: { events: { data: [GQL_EVENT], listMetadata: { before: 'event_0', after: null } } } }), + () => runEventList({ events: ['user.created'] }), + ); + const apiKey = await viaApiKey({ 'GET /events': restList([REST_EVENT], 'event_0') }, () => + runEventList({ events: ['user.created'] }), + ); + expectParity('event', session, apiKey, [{ path: 'events.0.updatedAt', field: 'updatedAt' }]); + expect(rest.callsTo('GET /events')[0].query).toMatchObject({ events: 'user.created', order: 'desc' }); + }); + + it('feature-flag list and get match with an API key', async () => { + const router = (doc: string) => + doc.includes('flagsForProject') + ? { flagsForProject: { data: [GQL_FLAG], listMetadata: { before: null, after: null } } } + : { flagBySlug: GQL_FLAG }; + const routes = { 'GET /feature-flags': restList([REST_FLAG]), 'GET /feature-flags/beta': REST_FLAG }; + + expectParity( + 'feature-flag', + await viaSession(router, () => runFeatureFlagList({})), + await viaApiKey(routes, () => runFeatureFlagList({})), + ); + expectParity( + 'feature-flag', + await viaSession(router, () => runFeatureFlagGet('beta')), + await viaApiKey(routes, () => runFeatureFlagGet('beta')), + [ + { path: 'flag.accessType', field: 'accessType' }, + { path: 'flag.organizationTargets', field: 'organizationTargets' }, + { path: 'flag.userTargets', field: 'userTargets' }, + ], + ); + }); + + it('org-domain get matches with an API key', async () => { + const session = await viaSession( + () => ({ + organizations: { data: [{ id: 'org_1', domains: [GQL_DOMAIN] }], listMetadata: { before: null, after: null } }, + }), + () => runOrgDomainGet('dom_1', {}), + ); + const apiKey = await viaApiKey({ 'GET /organizations': restList([REST_ORG]) }, () => runOrgDomainGet('dom_1', {})); + expectParity('org-domain', session, apiKey, [ + { path: 'domain.verificationContent', field: 'verificationContent' }, + { path: 'domain.domainCaptureEnabled', field: 'domainCaptureEnabled' }, + ]); + }); + + it('portal generate-link matches with an API key', async () => { + const session = await viaSession( + () => ({ + generatePortalSetupLink: { + __typename: 'PortalSetupLinkGenerated', + portalSetupLink: { + id: 'psl_1', + url: 'https://setup.workos.com/x', + intents: ['Sso'], + state: 'Active', + expiresAt: T1, + }, + }, + }), + () => runPortalGenerateLink({ intent: 'sso', organization: 'org_1' }), + ); + const apiKey = await viaApiKey({ 'POST /portal/generate_link': { link: 'https://setup.workos.com/x' } }, () => + runPortalGenerateLink({ intent: 'sso', organization: 'org_1' }), + ); + expectParity('portal', session, apiKey, [ + { path: 'portalSetupLink.id', field: 'id' }, + { path: 'portalSetupLink.state', field: 'state' }, + { path: 'portalSetupLink.expiresAt', field: 'expiresAt' }, + ]); + expect(rest.callsTo('POST /portal/generate_link')[0].body).toEqual({ organization: 'org_1', intent: 'sso' }); + }); +}); diff --git a/src/lib/__test-helpers__/rest-mock.ts b/src/lib/__test-helpers__/rest-mock.ts new file mode 100644 index 00000000..a8705480 --- /dev/null +++ b/src/lib/__test-helpers__/rest-mock.ts @@ -0,0 +1,80 @@ +/** + * A `fetch` stub for the WorkOS REST API, for specs that exercise the API-key + * path end to end (real `workosRequest`, real adapters). + * + * Routes are keyed `METHOD /path` (no query string). A route value is the + * JSON body to return with 200, a `{ status, body }` pair, or a function of + * the request. Unrouted requests get a REST-style 404 so not-found handling is + * exercised, and every call is recorded for assertions. + */ + +import { vi } from 'vitest'; + +export interface RestCall { + method: string; + path: string; + query: Record; + body: unknown; + authorization: string | undefined; +} + +export interface RestReply { + status: number; + body?: unknown; +} + +export type RestRoute = unknown | RestReply | ((call: RestCall) => unknown | RestReply); + +function isReply(value: unknown): value is RestReply { + return typeof value === 'object' && value !== null && 'status' in value && typeof value.status === 'number'; +} + +export function createRestMock() { + let routes: Record = {}; + const calls: RestCall[] = []; + + const fetchMock = vi.fn(async (input: unknown, init: RequestInit = {}) => { + const url = new URL(String(input)); + const method = (init.method ?? 'GET').toUpperCase(); + const headers = (init.headers ?? {}) as Record; + // Routes are written decoded (`/authorization/permissions/users:read`). + const path = decodeURIComponent(url.pathname); + const call: RestCall = { + method, + path, + query: Object.fromEntries(url.searchParams.entries()), + body: typeof init.body === 'string' ? JSON.parse(init.body) : undefined, + authorization: headers.Authorization, + }; + calls.push(call); + + const key = `${method} ${path}`; + if (!(key in routes)) { + return new Response(JSON.stringify({ message: `Not found: ${key}` }), { status: 404 }); + } + const route = routes[key]; + const resolved = typeof route === 'function' ? (route as (call: RestCall) => unknown)(call) : route; + const reply = isReply(resolved) ? resolved : { status: 200, body: resolved }; + if (reply.status === 204) return new Response(null, { status: 204 }); + return new Response(JSON.stringify(reply.body ?? {}), { status: reply.status }); + }); + + return { + fetchMock, + calls, + /** Replace the route table (and clear recorded calls). */ + respond(next: Record): void { + routes = next; + calls.length = 0; + }, + /** Calls matching `METHOD /path`. */ + callsTo(key: string): RestCall[] { + return calls.filter((call) => `${call.method} ${call.path}` === key); + }, + }; +} + +/** A REST list envelope, as the WorkOS API returns it. */ +export function restList(data: T[], after: string | null = null, before: string | null = null) { + return { object: 'list', data, list_metadata: { before, after } }; +} diff --git a/src/lib/api-key-operations/known-gaps.ts b/src/lib/api-key-operations/known-gaps.ts new file mode 100644 index 00000000..b9c4dba9 --- /dev/null +++ b/src/lib/api-key-operations/known-gaps.ts @@ -0,0 +1,31 @@ +/** + * Output fields the API-key path returns as `null` because the WorkOS REST API + * has no source for them, keyed `command.field` (the curated `--json` key). + * Keys, casing and shapes match the dashboard path; only these values differ. + * + * Shared by the offline parity spec (`src/commands/api-key-parity.spec.ts`) + * and the live comparison in `scripts/parity-smoke.ts --api-key`. Every entry + * is a missing REST field, never a casing difference: enum casing is + * normalized on both paths, so a casing-only divergence is a bug. + */ +export const API_KEY_NULL_FIELDS: Record = { + 'organization.usersCount': 'REST organizations carry no member count.', + 'user.sessionCount': 'REST users carry no session count.', + 'user.hasPassword': 'REST users do not say whether a password is set.', + 'user.emailVerifiedAt': 'REST users have an email_verified boolean but no verification timestamp.', + 'user.authenticationFactors': + 'REST auth factors carry no last-verified time, so each factor has lastVerifiedAt: null.', + 'membership.type': 'REST memberships carry no membership type.', + 'event.updatedAt': 'REST events carry only a creation time.', + 'feature-flag.accessType': 'The REST flag endpoints expose no access type.', + 'feature-flag.organizationTargets': 'The REST flag endpoints cannot list a flag’s targets.', + 'feature-flag.userTargets': 'The REST flag endpoints cannot list a flag’s targets.', + 'org-domain.verificationContent': + 'REST returns verification_prefix and verification_token separately, not the combined record.', + 'org-domain.domainCaptureEnabled': 'REST domains carry no domain-capture flag.', + 'portal.id': 'REST generate_link returns only the link URL.', + 'portal.state': 'REST generate_link returns only the link URL.', + 'portal.expiresAt': 'REST generate_link returns only the link URL.', + 'session.impersonator': 'REST names an impersonator by email only; id, firstName and lastName are null.', + 'config.applicationId': 'REST sets the AuthKit homepage URL without exposing the application ID.', +}; From a02ff2a4e6148b775f37bc4ba394568edeca8656 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 12:25:04 -0800 Subject: [PATCH 08/32] test: compare session and API-key output live in parity-smoke --api-key Runs each resource command's list/get on this branch twice, with the dashboard session and with WORKOS_API_KEY, and requires identical keys and values. The only allowed differences are the fields in API_KEY_ACCEPTED (shared with the offline spec via known-gaps.ts), where the key side must be null. --- scripts/parity-smoke.ts | 310 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 307 insertions(+), 3 deletions(-) diff --git a/scripts/parity-smoke.ts b/scripts/parity-smoke.ts index 7f85bab6..caec6ae1 100644 --- a/scripts/parity-smoke.ts +++ b/scripts/parity-smoke.ts @@ -45,12 +45,23 @@ * Env: PARITY_BRANCH_BIN, PARITY_MAIN_BIN (default: bun

/src/bin.ts), * PARITY_ENV_ID (pins --environment-id on branch commands). * + * API-key mode (`--api-key`): compares THIS branch against itself, dashboard + * session vs API key, for every resource command's list/get. No ../main + * needed. Same prereqs as above (a login, and a WORKOS_API_KEY for the same + * environment the session targets). Unlike the branch-vs-main buckets, the two + * sides must have IDENTICAL keys and values; the only allowed difference is a + * field in API_KEY_ACCEPTED (REST has no source for it, so the key side is + * null). The offline equivalent is src/commands/api-key-parity.spec.ts. + * + * bun run scripts/parity-smoke.ts --api-key + * * Exit: 0 if every executed check passed, 1 otherwise. */ import { spawn } from 'node:child_process'; import { existsSync, mkdtempSync, readFileSync } from 'node:fs'; import os from 'node:os'; import path from 'node:path'; +import { API_KEY_NULL_FIELDS } from '../src/lib/api-key-operations/known-gaps.ts'; const BRANCH_DIR = path.resolve(import.meta.dirname, '..'); const MAIN_DIR = path.resolve(BRANCH_DIR, '../main'); @@ -62,6 +73,7 @@ const STRICT = process.argv.includes('--strict'); // delivery. The address used is @example.com (RFC 2606 reserved, black-holed), // and the invitation is revoked during cleanup, but it stays opt-in. const INVITE = process.argv.includes('--invite'); +const API_KEY_MODE = process.argv.includes('--api-key'); if (STRICT) { const missing = [!SEED && '--seed', !INVITE && '--invite', !MUTATE && '--mutate'].filter(Boolean); @@ -71,11 +83,11 @@ if (STRICT) { } } -if (!existsSync(path.join(MAIN_DIR, 'src/bin.ts'))) { +if (!API_KEY_MODE && !existsSync(path.join(MAIN_DIR, 'src/bin.ts'))) { console.error(`main checkout not found: ${MAIN_DIR}/src/bin.ts`); process.exit(2); } -for (const dir of [BRANCH_DIR, MAIN_DIR]) { +for (const dir of API_KEY_MODE ? [BRANCH_DIR] : [BRANCH_DIR, MAIN_DIR]) { const pkg = JSON.parse(readFileSync(path.join(dir, 'package.json'), 'utf8')); if (pkg.name !== 'workos') { console.error(`${dir} is not the workos CLI (package.json name="${pkg.name}")`); @@ -118,11 +130,13 @@ interface RunResult { stderr: string; } const COMMAND_TIMEOUT_MS = 60_000; -function run(dir: string, cliArgs: string[]): Promise { +/** `withoutApiKey` runs the child with WORKOS_API_KEY unset (the dashboard-session side in --api-key mode). */ +function run(dir: string, cliArgs: string[], opts: { withoutApiKey?: boolean } = {}): Promise { const { cmd, args } = binFor(dir); return new Promise((resolve) => { const childEnv: NodeJS.ProcessEnv = { ...process.env }; if (API_KEY) childEnv.WORKOS_API_KEY = API_KEY; + if (opts.withoutApiKey) delete childEnv.WORKOS_API_KEY; const p = spawn(cmd, [...args, ...cliArgs], { cwd: NEUTRAL_CWD, env: childEnv, stdio: ['ignore', 'pipe', 'pipe'] }); let stdout = ''; let stderr = ''; @@ -949,6 +963,296 @@ async function checkNew(c: { label: string; args: string[] }): Promise { push('NEW', c.label, 'PASS', 'valid JSON'); } +// --- API-key mode: dashboard session vs API key, same branch ------------------------ +/** + * Deliberate session-vs-key divergences, keyed `command.field`. Shared with the + * offline spec via known-gaps.ts. Each is a field REST has no source for, so + * the key side must be null; a casing-only difference is never listed here (it + * is a bug and must fail). + */ +const API_KEY_ACCEPTED: Record = { ...API_KEY_NULL_FIELDS }; + +/** Cursors are opaque and plane-specific; everything else must match exactly. */ +const CURSOR_KEYS = new Set(['before', 'after', 'listMetadata', 'list_metadata', 'pagination']); + +function exact(v: unknown): unknown { + if (v === null || v === undefined) return null; + if (Array.isArray(v)) return v.map(exact).sort(cmp); + if (typeof v === 'object') { + const o: Record = {}; + for (const k of Object.keys(v as Record).sort()) { + if (!CURSOR_KEYS.has(k)) o[k] = exact((v as Record)[k]); + } + return o; + } + return v; +} + +/** + * True when `k` is `s` with some values replaced by null (and nothing else + * changed): the key side lacks data REST can't supply but invents nothing. + */ +function isNulledCopy(s: unknown, k: unknown): boolean { + if (k === null || k === undefined) return true; + if (Array.isArray(s) && Array.isArray(k)) { + return s.length === k.length && k.every((item, index) => isNulledCopy(s[index], item)); + } + if (isPlainObject(s) && isPlainObject(k)) { + return Object.keys(k).every((key) => isNulledCopy(s[key], k[key])); + } + return JSON.stringify(s) === JSON.stringify(k); +} + +/** Compare one entity: identical key sets, identical values, except accepted nulls. */ +function compareSessionVsKey(cmd: string, s: any, k: any): { diffs: string[]; accepted: string[] } { + const diffs: string[] = []; + const accepted: string[] = []; + const keys = new Set([...Object.keys(s ?? {}), ...Object.keys(k ?? {})]); + for (const key of keys) { + if (CURSOR_KEYS.has(key)) continue; + if (!(key in (s ?? {})) || !(key in (k ?? {}))) { + diffs.push(`${key}: present only on the ${key in (s ?? {}) ? 'session' : 'API-key'} side`); + continue; + } + if (JSON.stringify(exact(s[key])) === JSON.stringify(exact(k[key]))) continue; + const reason = API_KEY_ACCEPTED[`${cmd}.${key}`]; + if (reason && isNulledCopy(s[key], k[key])) { + accepted.push(`${key} (${reason})`); + } else { + diffs.push(`${key}: session=${JSON.stringify(s[key])} key=${JSON.stringify(k[key])}`); + } + } + return { diffs, accepted }; +} + +interface ApiKeyCheck { + cmd: string; + label: string; + args: string[]; + /** Envelope key holding the list, or the single entity for a get. */ + key: string; + idKey?: string; +} + +async function runBoth(args: string[]): Promise<[RunResult, RunResult]> { + return Promise.all([ + run(BRANCH_DIR, [...args, ...envArgs()], { withoutApiKey: true }), + // The key decides the environment; --environment-id is refused with a key. + run(BRANCH_DIR, args), + ]); +} + +async function checkSessionVsKey(c: ApiKeyCheck): Promise { + const [s, k] = await runBoth(c.args); + if (s.rc === 4) { + push('API-KEY', c.label, 'AUTH', 'session side needs `workos auth login`'); + return undefined; + } + if (s.rc !== 0 || k.rc !== 0) { + push('API-KEY', c.label, 'FAIL', `exit session=${s.rc} key=${k.rc} ${shortErr(s.stderr)}${shortErr(k.stderr)}`); + return undefined; + } + const js = parseJson(s.stdout); + const jk = parseJson(k.stdout); + if (js === undefined || jk === undefined) { + push('API-KEY', c.label, 'FAIL', 'invalid JSON on one side'); + return undefined; + } + const sv = js[c.key]; + const kv = jk[c.key]; + let diffs: string[] = []; + let accepted: string[] = []; + let rows = 1; + if (Array.isArray(sv) && Array.isArray(kv) && c.idKey) { + const sIds = sv.map((row: any) => row?.[c.idKey!]).sort(); + const kIds = kv.map((row: any) => row?.[c.idKey!]).sort(); + if (JSON.stringify(sIds) !== JSON.stringify(kIds)) { + push('API-KEY', c.label, 'FAIL', `row sets differ (session ${sv.length}, key ${kv.length}); same environment?`); + return js; + } + rows = sv.length; + for (const row of sv) { + const other = kv.find((candidate: any) => candidate?.[c.idKey!] === row?.[c.idKey!]); + const r = compareSessionVsKey(c.cmd, row, other); + diffs.push(...r.diffs.map((d) => `${row?.[c.idKey!]}: ${d}`)); + accepted.push(...r.accepted); + } + } else { + const r = compareSessionVsKey(c.cmd, sv, kv); + diffs = r.diffs; + accepted = r.accepted; + } + for (const d of diffs) notes.push(`${C.red}FAIL${C.reset} ${c.label} ${d}`); + for (const a of new Set(accepted)) notes.push(`${C.cyan}INFO${C.reset} ${c.label} accepted: ${a}`); + const empty = Array.isArray(sv) && sv.length === 0; + push( + 'API-KEY', + c.label, + diffs.length ? 'FAIL' : empty ? 'SKIP' : 'PASS', + diffs.length + ? `${diffs.length} UNEXPECTED diff(s)` + : empty + ? 'both sides empty — proves the call works, proves nothing about data' + : `${rows} row(s), identical keys and values${accepted.length ? `; ${new Set(accepted).size} accepted null field(s)` : ''}`, + ); + return js; +} + +async function runApiKeyMode(): Promise { + console.log(`parity-smoke --api-key branch=${BRANCH_DIR}${ENV_ID ? ` env=${ENV_ID}` : ''}`); + console.log(` api key source: ${API_KEY_SOURCE}\n`); + if (API_KEY_SOURCE === 'NONE') { + console.error('--api-key mode needs WORKOS_API_KEY (or the branch .env.local) for the session’s environment'); + process.exit(2); + } + + const lists: ApiKeyCheck[] = [ + { + cmd: 'organization', + label: 'organization list', + args: ['organization', 'list', '--json'], + key: 'organizations', + idKey: 'id', + }, + { cmd: 'user', label: 'user list', args: ['user', 'list', '--json'], key: 'users', idKey: 'id' }, + { cmd: 'role', label: 'role list', args: ['role', 'list', '--json'], key: 'roles', idKey: 'slug' }, + { + cmd: 'permission', + label: 'permission list', + args: ['permission', 'list', '--json'], + key: 'permissions', + idKey: 'slug', + }, + { + cmd: 'invitation', + label: 'invitation list', + args: ['invitation', 'list', '--json'], + key: 'invitations', + idKey: 'id', + }, + { + cmd: 'feature-flag', + label: 'feature-flag list', + args: ['feature-flag', 'list', '--json'], + key: 'flags', + idKey: 'slug', + }, + { + cmd: 'webhook', + label: 'webhook list', + args: ['webhook', 'list', '--json'], + key: 'webhookEndpoints', + idKey: 'id', + }, + { + cmd: 'event', + label: 'event list', + args: ['event', 'list', '--events', 'organization.created,user.created', '--limit', '20', '--json'], + key: 'events', + idKey: 'id', + }, + ]; + const results = new Map(); + await Promise.all(lists.map(async (c) => results.set(c.cmd, await checkSessionVsKey(c)))); + + // Session-side preflight: if the organization sets differ the key targets a + // different environment and every row below is meaningless. + const orgRow = rows.find((row) => row.label === 'organization list'); + if (orgRow?.status === 'FAIL' && orgRow.detail.startsWith('row sets differ')) { + console.log(`${C.red}aborting: the API key and the session target different environments${C.reset}`); + } else { + const first = (cmd: string, key: string) => results.get(cmd)?.[key]?.[0]; + const org = first('organization', 'organizations'); + const user = first('user', 'users'); + const gets: ApiKeyCheck[] = []; + if (org) + gets.push({ + cmd: 'organization', + label: 'organization get', + args: ['organization', 'get', org.id, '--json'], + key: 'organization', + }); + if (user) { + gets.push({ cmd: 'user', label: 'user get', args: ['user', 'get', user.id, '--json'], key: 'user' }); + gets.push({ + cmd: 'membership', + label: 'membership list --user', + args: ['membership', 'list', '--user', user.id, '--json'], + key: 'memberships', + idKey: 'id', + }); + gets.push({ + cmd: 'session', + label: 'session list', + args: ['session', 'list', user.id, '--json'], + key: 'sessions', + idKey: 'id', + }); + } + if (org) + gets.push({ + cmd: 'membership', + label: 'membership list --org', + args: ['membership', 'list', '--org', org.id, '--json'], + key: 'memberships', + idKey: 'id', + }); + const role = first('role', 'roles'); + if (role) gets.push({ cmd: 'role', label: 'role get', args: ['role', 'get', role.slug, '--json'], key: 'role' }); + const permission = first('permission', 'permissions'); + if (permission) + gets.push({ + cmd: 'permission', + label: 'permission get', + args: ['permission', 'get', permission.slug, '--json'], + key: 'permission', + }); + const invitation = first('invitation', 'invitations'); + if (invitation) + gets.push({ + cmd: 'invitation', + label: 'invitation get', + args: ['invitation', 'get', invitation.id, '--json'], + key: 'invitation', + }); + const flag = first('feature-flag', 'flags'); + if (flag) + gets.push({ + cmd: 'feature-flag', + label: 'feature-flag get', + args: ['feature-flag', 'get', flag.slug, '--json'], + key: 'flag', + }); + const domain = org?.domains?.[0]; + if (domain?.id) + gets.push({ + cmd: 'org-domain', + label: 'org-domain get', + args: ['org-domain', 'get', domain.id, '--json'], + key: 'domain', + }); + await Promise.all(gets.map(checkSessionVsKey)); + } + + const w = Math.max(...rows.map((r) => r.label.length), 20); + for (const r of rows) { + const color = r.status === 'PASS' ? C.green : r.status === 'FAIL' ? C.red : r.status === 'AUTH' ? C.yellow : C.dim; + console.log(` ${color}${r.status.padEnd(4)}${C.reset} ${r.label.padEnd(w)} ${C.dim}${r.detail}${C.reset}`); + } + if (notes.length) { + console.log(`\n${C.dim}field-level detail${C.reset}`); + for (const n of notes) console.log(` ${n}`); + } + const failed = rows.filter((r) => r.status === 'FAIL').length; + const auth = rows.filter((r) => r.status === 'AUTH').length; + console.log( + `\n${failed ? C.red : C.green}${rows.filter((r) => r.status === 'PASS').length} pass, ${failed} fail, ${auth} auth${C.reset}`, + ); + process.exit(failed || auth ? 1 : 0); +} + +if (API_KEY_MODE) await runApiKeyMode(); + // --- run ------------------------------------------------------------------------- console.log(`parity-smoke branch=${BRANCH_DIR}`); console.log( From da5d05812b62ab3afe3325a3fbc2db29d89556c1 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 12:25:05 -0800 Subject: [PATCH 09/32] fix: type-check the API-key path and drop unused exports Narrow flag targets in the human flag view (null on the API-key path), return the never-typed REST error handler, and type the --api-key middleware helper without re-returning the yargs instance. --- src/bin.ts | 4 ++-- src/commands/feature-flag.ts | 4 ++-- src/lib/api-key-operations/index.ts | 6 +----- src/lib/api-key-operations/lookups.ts | 5 +---- 4 files changed, 6 insertions(+), 13 deletions(-) diff --git a/src/bin.ts b/src/bin.ts index d631974e..abdfdafb 100644 --- a/src/bin.ts +++ b/src/bin.ts @@ -159,8 +159,8 @@ const resourceApiKeyOption = { } as const; /** Add `--api-key` to a resource command group and hand it to the auth selector. */ -function withResourceApiKey(yargs: Argv): Argv { - return yargs.options(resourceApiKeyOption).middleware(async (argv) => { +function withResourceApiKey(yargs: Argv): void { + yargs.options(resourceApiKeyOption).middleware(async (argv) => { const { setResourceApiKeyFlag } = await import('./lib/resource-auth.js'); setResourceApiKeyFlag(argv.apiKey as string | undefined); }); diff --git a/src/commands/feature-flag.ts b/src/commands/feature-flag.ts index 669aeceb..376e456a 100644 --- a/src/commands/feature-flag.ts +++ b/src/commands/feature-flag.ts @@ -241,9 +241,9 @@ export async function runFeatureFlagGet(slug: string, options: FeatureFlagEnviro ['Access type', flag.accessType], [ 'Organization targets', - flag.organizationTargets.length > 0 ? flag.organizationTargets.map((t) => t.id).join(', ') : null, + flag.organizationTargets?.length ? flag.organizationTargets.map((t) => t.id).join(', ') : null, ], - ['User targets', flag.userTargets.length > 0 ? flag.userTargets.map((t) => t.id).join(', ') : null], + ['User targets', flag.userTargets?.length ? flag.userTargets.map((t) => t.id).join(', ') : null], ['Created', flag.createdAt], ]; printDetailFields(fields); diff --git a/src/lib/api-key-operations/index.ts b/src/lib/api-key-operations/index.ts index edb923c8..4778218f 100644 --- a/src/lib/api-key-operations/index.ts +++ b/src/lib/api-key-operations/index.ts @@ -51,10 +51,6 @@ export const API_KEY_UNSUPPORTED: Record = { updateAppBranding: 'AuthKit branding images have no WorkOS API endpoint', }; -export function hasApiKeyOperation(opName: string): boolean { - return opName in OPERATIONS; -} - /** What's missing for an operation the API key can't run, in user-facing terms. */ export function apiKeyUnsupportedReason(opName: string): string { return API_KEY_UNSUPPORTED[opName] ?? 'this action has no WorkOS API endpoint'; @@ -98,7 +94,7 @@ export async function withApiKey(auth: ApiKeyAuth, run: (ctx: ApiKeyContext) apiContext: { status: 404, code: error.code ?? 'not_found' }, }); } - handleApiError(error); + return handleApiError(error); } } diff --git a/src/lib/api-key-operations/lookups.ts b/src/lib/api-key-operations/lookups.ts index 4c571324..4e59e801 100644 --- a/src/lib/api-key-operations/lookups.ts +++ b/src/lib/api-key-operations/lookups.ts @@ -5,7 +5,6 @@ * (one context), so a page of results costs one read per distinct key. */ -import type { WorkOSListResponse } from '../workos-api.js'; import { type ApiKeyContext, encode, listAll, orNull } from './context.js'; export interface RestRole { @@ -89,7 +88,7 @@ export function organizationName(ctx: ApiKeyContext, organizationId: string): Pr /** Map with bounded concurrency, preserving order. */ export async function mapLimit(items: T[], limit: number, fn: (item: T) => Promise): Promise { - const results: R[] = new Array(items.length); + const results: R[] = []; let next = 0; const workers = Array.from({ length: Math.min(limit, items.length) }, async () => { while (next < items.length) { @@ -118,5 +117,3 @@ export interface RestMembership { export function membershipsForUser(ctx: ApiKeyContext, userId: string): Promise { return listAll(ctx, '/user_management/organization_memberships', { user_id: userId }); } - -export type { WorkOSListResponse }; From 713b9faaf4299e509f104b4cf4fe570fff60d131 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 12:25:05 -0800 Subject: [PATCH 10/32] docs: say resource commands accept an API key README and CLAUDE.md said the resource commands use only the dashboard session and that WORKOS_API_KEY applies only to workos api and the still-REST commands. Describe the new precedence (--api-key, then WORKOS_API_KEY, then an unclaimed active profile's key, else the session), the refused --environment-id, the two api_key_unsupported commands, and the session-only account commands. --- CLAUDE.md | 2 +- README.md | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index a2f99c46..0016be01 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -13,7 +13,7 @@ WorkOS CLI for installing AuthKit integrations and managing WorkOS resources (or ## Non-TTY Behavior - **Output**: Auto-switches to JSON when piped or `--json` flag. `WORKOS_FORCE_TTY=1` overrides. -- **Auth**: Exits code 4 instead of opening browser. Resource commands (organization, user, role, permission, membership, invitation, session, event, feature-flag, org-domain, portal, webhook, config) use the dashboard session from a prior `workos auth login`; expired access tokens refresh silently while the stored refresh token is valid, so only a truly dead session exits 4. `WORKOS_API_KEY` applies only to `workos api` and the still-REST commands (`connection`, `directory`, `audit-log`, `api-key`, `vault`, plus the workflow/debug commands `seed`, `setup-org`, `onboard-user`, `verify-login`, `debug-sso`, `debug-sync`, `migrations`). +- **Auth**: Exits code 4 instead of opening browser. Resource commands (organization, user, role, permission, membership, invitation, session, event, feature-flag, org-domain, portal, webhook, config, authkit, branding) use the dashboard session from a prior `workos auth login`; expired access tokens refresh silently while the stored refresh token is valid, so only a truly dead session exits 4. They switch to an API key on the WorkOS REST API when one applies (first match: `--api-key`, `WORKOS_API_KEY`, the active profile's key if it is unclaimed); `src/lib/resource-auth.ts` decides, and `src/lib/api-key-operations/` maps each operation to REST with the same `--json` shape. With a key, `--environment-id` is refused, and AuthKit logout URIs and branding fail with `api_key_unsupported`. The account commands (`team`, `project`, `environment`, `whoami`) are session-only. `WORKOS_API_KEY` also applies to `workos api` and the still-REST commands (`connection`, `directory`, `audit-log`, `api-key`, `vault`, plus the workflow/debug commands `seed`, `setup-org`, `onboard-user`, `verify-login`, `debug-sso`, `debug-sync`, `migrations`). - **Errors**: Structured JSON to stderr: `{ "error": { "code": "...", "message": "..." } }` - **Exit codes**: 0=success, 1=error, 2=canceled, 4=auth required (follows `gh` CLI convention) - **Headless flags**: `--no-branch`, `--no-git-check`. CI mode (`WORKOS_MODE=ci`) auto-continues past a dirty tree without `--no-git-check`; agent mode requires the flag. diff --git a/README.md b/README.md index 803158c9..a4650af0 100644 --- a/README.md +++ b/README.md @@ -146,7 +146,7 @@ Workflows: debug-sync Diagnose directory sync issues ``` -All management commands support `--json` for structured output (auto-enabled in non-TTY). Still-REST commands (`connection`, `directory`, `audit-log`, `api-key`, `vault`, `workos api`, and the workflow/debug commands) also accept `--api-key` to override the active environment's key; the other resource commands authenticate with your `workos auth login` session (see [Resource Management](#resource-management)). +All management commands support `--json` for structured output (auto-enabled in non-TTY). They also accept `--api-key`: the still-REST commands (`connection`, `directory`, `audit-log`, `api-key`, `vault`, `workos api`, and the workflow/debug commands) use it to override the active environment's key, and the other resource commands use it instead of your `workos auth login` session (see [Resource Management](#resource-management)). ### Unclaimed Environments @@ -309,6 +309,8 @@ All resource commands follow the same pattern: `workos [args Most resource commands — organization, user, role, permission, membership, invitation, session, event, feature-flag, org-domain, portal, webhook, config, authkit, branding — authenticate with your WorkOS dashboard session from `workos auth login` and target the active environment (see `workos profile`). Pass `--environment-id ` on any of them to target a different environment for a single invocation. Access tokens refresh automatically while the session is valid, so a logged-in machine keeps working headlessly; a dead session exits with code 4. +They can also run with an API key instead, against the WorkOS API. The first match wins: the `--api-key` flag, then `WORKOS_API_KEY`, then the active profile's key when that profile is an unclaimed environment (from `workos env provision` or the installer). Otherwise the dashboard session is used, so a signed-in user is unaffected unless they pass a key. With a key, the key decides the environment, so `--environment-id` is refused. AuthKit logout URIs (`authkit logout-uris`) and branding (`branding`) have no API equivalent and fail with `api_key_unsupported`. The account commands (`team`, `project`, `environment`, `whoami`) always need the dashboard session. + The remaining commands (`connection`, `directory`, `audit-log`, `api-key`, `vault`) still use the REST plane, as does the raw escape hatch `workos api`. Those resolve an API key via: `--api-key` flag → `WORKOS_API_KEY` env var → active environment's stored key. #### organization @@ -685,7 +687,7 @@ workos install --api-key sk_test_xxx --client-id client_xxx 2>/dev/null | Variable | Effect | | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `WORKOS_API_KEY` | API key for `workos api`, the still-REST commands (connection, directory, audit-log, api-key, vault), and workflow/debug commands. Resource commands use the `workos auth login` session instead | +| `WORKOS_API_KEY` | API key for `workos api`, the still-REST and workflow/debug commands, and the resource commands (instead of the `workos auth login` session; `team`/`project`/`environment`/`whoami` require it) | | `WORKOS_API_URL` | Override the API base URL for all CLI commands (e.g. a local API) | | `WORKOS_API_BASE_URL` | Accepted alias for `WORKOS_API_URL` (what `workos dev` sets) | | `WORKOS_MODE` | Interaction mode: `human`, `agent`, or `ci` | From c25c9e0a1833e83ccaa9d742e6ab9c5c4900cb5a Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 12:25:06 -0800 Subject: [PATCH 11/32] riker: uncommitted changes from job 320 --- .scratch/job-320/pr-body.md | 209 ++++++++++++++++++++++++++++++++++++ 1 file changed, 209 insertions(+) create mode 100644 .scratch/job-320/pr-body.md diff --git a/.scratch/job-320/pr-body.md b/.scratch/job-320/pr-body.md new file mode 100644 index 00000000..c89cf899 --- /dev/null +++ b/.scratch/job-320/pr-body.md @@ -0,0 +1,209 @@ +# feat: run resource commands with an API key + +> Draft. Suggested title: `feat: run resource commands with an API key (unclaimed environments, WORKOS_API_KEY, --api-key)` + +## Why + +An agent holding a one-shot environment from `workos env provision` (or the installer) could only use `workos api`. Every resource command (`workos organization`, `workos user`, `workos role`, …) failed with "uses your WorkOS dashboard session and does not accept API keys", because none of them can authenticate before an environment is claimed. Clerk's equivalent commands work before claiming. This PR makes them work with an API key. + +## What changed + +- **One seam picks the credential.** `resolveEnvScopedAuth()` in `src/lib/dashboard-operation.ts` asks `src/lib/resource-auth.ts` whether an API key applies. If none does, the existing session path runs unchanged: `requireCommandToken()` plus `resolveEnvironmentTarget()`. +- **REST adapters return the dashboard data shape.** On the API-key path, `executeDashboardOperation()` sends each catalog operation to a REST adapter in `src/lib/api-key-operations/`. The adapter calls the WorkOS REST API with the key and returns the same data shape the dashboard operation returns, using only the fields that operation's document selects. Each command's existing `--json` shaper then runs as before, so keys, casing and shapes match by construction. Enum casing goes through the same `enumOut()` on both paths. +- **No REST source means `null`.** A field REST has no source for comes back `null` and is never invented. Each one is listed in `src/lib/api-key-operations/known-gaps.ts`. +- **Missing REST endpoints fail with a structured error.** A command or input with no REST equivalent exits with `{"error":{"code":"api_key_unsupported","message":"…what's missing…"}}` before any write. +- **`--api-key` is now accepted** on the resource command groups. It's the same flag name and the same `resolveOptionalApiKey()` resolution that `workos api` and the still-REST commands use. It's registered in `help-json.ts` too. +- **The copy no longer says resource commands reject API keys.** `authRequiredApiKeySet` and `refreshFailedApiKeySet` are now in practice shown only by the account commands. They say the command manages your dashboard account and needs a login, and that resource commands such as `workos organization` and `workos user` run with the API key. No internal terms appear in the copy (checked against `LEAK_PATTERN`). +- **Docs** (README, CLAUDE.md) describe the new rule. + +### Commands gated on the dashboard session, and what each does now + +Every command below reached `requireCommandToken()`, either directly or through `runEnvScopedOperation` / `runTeamScopedOperation`. + +**Environment-scoped resource commands now run on REST with a key:** + +| Command | Subcommands on the API-key path | +| --- | --- | +| `organization` | create, update, get, list, delete | +| `user` | get, list, update, delete | +| `role` | list, get, create, update, delete, set-permissions, add-permission, remove-permission (with or without `--org`) | +| `permission` | list, get, create, update, delete | +| `membership` | list (`--user` / `--org`), get, create, update, delete, deactivate, reactivate | +| `invitation` | list (incl. `--org`), get, send, revoke, resend | +| `session` | list, revoke | +| `event` | list | +| `feature-flag` | list, get, enable, disable, add-target, remove-target | +| `org-domain` | get, create, verify, delete | +| `portal` | generate-link | +| `webhook` | list, create, delete | +| `config` | redirect add, cors add, homepage-url set | +| `authkit` | redirect-uris list/set, cors get/set | + +**No REST equivalent, so they fail with `api_key_unsupported` on the key path:** +- `authkit logout-uris list|set`: sign-out redirect URIs have no WorkOS API endpoint. +- `branding get|set`: branding images have no WorkOS API endpoint. + +**Account commands, session-only (no REST equivalent; they ignore the key):** `team` (members, invite, change-role, remove, resend-invite, update, set-mfa), `project` (create, rename, list), `environment` (list, use, create, rename), `whoami`. + +## Precedence rule + +The first match wins: + +1. `--api-key ` +2. `WORKOS_API_KEY` +3. The active profile's stored key, **only if that profile is an unclaimed environment.** A dashboard session can't reach an unclaimed environment, so its key is the only credential that works there. +4. Otherwise, the existing dashboard-session path, unchanged. + +Consequences: +- A **claimed** profile's stored key never switches the path. A signed-in user keeps today's behavior unless they pass a key explicitly. A signed-out user with a claimed profile still gets exit 4, as before. +- With a key, **`--environment-id` is refused** (`invalid_argument`). The key decides the environment, and silently ignoring the flag could act on the wrong one. +- `environment create|rename` are environment-scoped dashboard operations behind an account command, so they stay session-only even with a key set. + +## Known differences on the API-key path + +Keys and shapes are identical on both paths. These values differ because REST has no source for them (all are `null` on the key path, and all are in `API_KEY_ACCEPTED` / `API_KEY_NULL_FIELDS`): + +| Field | Reason | +| --- | --- | +| `organization.usersCount` | REST organizations carry no member count | +| `user.sessionCount`, `user.hasPassword` | not in REST users | +| `user.emailVerifiedAt` | REST has only an `email_verified` boolean. The human view still shows Verified: Yes from it. | +| `user.authenticationFactors[].lastVerifiedAt` | REST auth factors carry no last-verified time | +| `membership.type` | REST memberships carry no type | +| `event.updatedAt` | REST events carry only a creation time | +| `feature-flag` get: `accessType`, `organizationTargets`, `userTargets` | the REST flag endpoints expose neither | +| `org-domain`: `verificationContent`, `domainCaptureEnabled` | REST returns the verification prefix/token separately, and has no capture flag | +| `portal`: `id`, `state`, `expiresAt` | REST `generate_link` returns only the URL | +| `session.impersonator` id/firstName/lastName | REST names an impersonator by email only | +| `config homepage-url set`: `applicationId` | REST never exposes the AuthKit application ID | + +Some fields are filled with extra REST reads rather than nulled. They are bounded per page and memoized per call: +- user `identities`: the user's memberships, with role IDs and names resolved from slugs; +- user get `authenticationFactors`; +- organization names on invitations and sessions. + +Behavioral differences (not output fields): +- **Search filters are exact matches.** `organization list --domain`, `user list --email` and `invitation list --email` use REST's exact-match filters (domain, email). The dashboard does a search. +- **New domains start pending.** `org-domain create` on REST creates the domain `pending` (it needs DNS verification). The dashboard adds it verified. The output reports the real state. +- **`membership list --org` pages over memberships.** Its cursors are membership IDs on the key path and user IDs on the session path. They're opaque either way, and each path accepts its own cursors. +- **`feature-flag add-target|remove-target` call REST's target endpoints directly.** REST can't list a flag's targets, so there's no read-merge-write, and remove-target can't pre-check that the target exists. +- **Redirect URIs and CORS have limits on REST.** + - `authkit redirect-uris set` diffs the list: it creates what's missing and deletes what's dropped. + - `--default` is accepted only for a URI that is already the default, because REST can't choose one. + - `authkit cors set` can't remove origins, because REST has no delete. + - `--dry-run` is refused, because REST has no validate-only mode. + - All of these fail before any write. +- **`session list` `provider`.** The session path emits the dashboard value raw (`Password`, not normalized; this is pre-existing and pinned in the json-contract snapshot). The key path PascalCases REST's `auth_method` to match: `password` becomes `Password`. Multi-word methods (`magic_code` becomes `MagicCode`) are a best guess at the dashboard spelling. Fixing it properly means running `enumOut` on both paths, which changes signed-in output, so it's left for a follow-up. +- **`webhook` `state`.** REST `enabled` maps to `active`, like the dashboard. REST `disabled` passes through as `disabled`; I haven't verified the dashboard's spelling for inactive endpoints. + +## Parity results + +**Offline (`src/commands/api-key-parity.spec.ts`, 17 tests, all pass).** +- Every list and get command runs the real handler on both paths against the same entity: + - organization, user, role (env and `--org`), permission, invitation (env and `--org`), membership (`--user`, `--org`, get), session, webhook, event, feature-flag, org-domain; + - plus portal generate-link. +- The dashboard side is fed real dashboard casing (`Verified`, `Active`, `Environment`, metadata as `{key,value}` pairs). +- The REST side is fed real REST responses: snake_case keys, `verified`, `EnvironmentRole`, `enabled`, `password`, metadata as an object, plus the internal fields the shapers must drop (`stripe_customer_id`, `secret`, invitation `token`). +- Outputs must be deep-equal. The only exception is the documented null fields, which must be `null` on the key side and listed in `API_KEY_NULL_FIELDS`. A casing-only difference fails. + +**Live (`scripts/parity-smoke.ts --api-key`, new mode).** It runs each command's list/get on this branch twice, with the session and with `WORKOS_API_KEY`, and requires identical keys and values. The only allowed differences are the `API_KEY_ACCEPTED` fields (shared with the spec through `known-gaps.ts`), where the key side must be a nulled copy. It needs no `../main`. **Not run for this PR:** the session side needs a real `workos auth login`, and this work was kept away from the real `~/.workos` and Keychain. Running it is a good pre-merge check: + +``` +workos auth login +export WORKOS_API_KEY=sk_test_… # same environment the session targets +bun run scripts/parity-smoke.ts --api-key +``` + +## Real-command proof (from source, fresh unclaimed environment) + +Setup: +- Run from the worktree with `HOME=$PWD/.scratch/home`, `--insecure-storage`, and `bun --preload ./src/test/force-insecure-storage.ts src/bin.ts …`. That's the preload the integration specs use, so startup never touches the Keychain. +- `WORKOS_TELEMETRY=false`, no `WORKOS_API_KEY`, and each command wrapped in `timeout 120`. +- The scratch home was deleted afterwards. Secrets are redacted. + +``` +$ workos env provision --insecure-storage --json +{"status":"ok","message":"Environment provisioned","data":{"name":"unclaimed","type":"unclaimed","active":true,"apiKey":"sk_…REDACTED","clientId":"client_01M6SH09VVW8FK83WABDPS1YF8","claimToken":"…REDACTED","authkitDomain":"vast-sonnet-18-sandbox.authkit.app"}} +exit=0 + +$ workos organization list --json --insecure-storage +{"organizations":[{"id":"org_01M6SH09P7HB581EQQQKQYME31","name":"Test Organization","createdAt":"2026-11-06T22:52:22.375Z","usersCount":null,"allowProfilesOutsideOrganization":false,"externalId":null,"domains":[{"id":"org_domain_01M6SH09Q1BJCH2T5GEF90HRT2","domain":"example.com","state":"verified"}],"metadata":{}}],"pagination":{"before":null,"after":null}} +exit=0 + +$ workos user list --json --insecure-storage +{"users":[],"pagination":{"before":null,"after":null}} +exit=0 +``` + +Both list commands ran with no login, using the unclaimed profile's key. Before this change, both would exit 4 with "does not accept API keys". `usersCount: null` is the documented gap. The user list is empty because the environment is brand new. + +I also checked against a local fake API (`WORKOS_API_URL=http://127.0.0.1:`, no external network): +- `--api-key` reaches the request as the bearer. +- `--api-key` with `--environment-id` exits 1 with `invalid_argument`. +- `branding get` with a key exits 1 with `api_key_unsupported`. +- `team members` with a key and no login still exits 4, with the reworded copy. +- `organization list --help` lists `--api-key`. + +## Overlap with #269 and #270 + +- **#269 (`nicknisi/ax-agent-copy`, open).** + - Overlapping files: `src/lib/command-auth.ts`, `src/utils/recovery-hints.ts`, `src/bin.ts` and `README.md`. This PR doesn't touch `recovery-hints.ts`. + - `git merge-tree` shows one textual conflict, in `src/lib/command-auth.spec.ts`: #269 adds a test next to one this PR renames. It's easy to resolve. + - Semantic follow-up: #269 adds `dashboardSessionRecovery`. Its second hint ("make the same request with an API key … through the API command") and its test asserting no "set WORKOS_API_KEY" hint were written when resource commands rejected keys. Once both land: + - resource commands reach that hint only when no key is set, and setting `WORKOS_API_KEY` or passing `--api-key` now fixes them; + - the account commands still need the session. + - So the hint should be reworded for whichever PR merges second. +- **#270 (`fix/account-plane-forbidden-and-slim-team-query`).** It touches `command-auth.ts` (the `forbidden` copy only). It merges cleanly with this branch. +- Neither branch was touched. + +## Security read: key scope + +**The keys are full-scope.** The one-shot keys from `workos env provision` and the installer are full-scope secret keys for that (sandbox) environment. `WORKOS_API_KEY` / `--api-key` can be any key, including a production `sk_live_…`. + +**What an agent holding one can now do through these commands:** +- **Organizations:** create, update, and delete. Delete cascades to the org's connections, directories and users. +- **Org domains:** add, verify and delete. Domain-based sign-in and capture stop working for a deleted domain. +- **Users:** read, including email, name, metadata and memberships. Update them, including changing a user's email. Delete them. +- **Sessions:** list and revoke. +- **RBAC:** + - create, update and delete organization roles; + - change any role's permissions, including environment roles; + - create, update and delete permissions. +- **Memberships:** add a user to an organization with a role, change roles, deactivate, reactivate, delete. +- **Invitations:** send (real email), revoke, resend. +- **Webhooks:** create and delete endpoints. Creating one aimed at an outside URL streams future events there. +- **Events:** read the event feed, which includes user payloads. +- **Feature flags:** enable, disable, add and remove targets. +- **Admin Portal:** generate setup links, which grant SSO/Directory Sync setup access for an organization. +- **AuthKit config:** add redirect URIs and CORS origins, replace the redirect-URI list (deleting unlisted URIs), set the homepage URL. Adding a redirect URI for an attacker's domain is a classic way to steal sign-ins in a real app. + +**What it could already do with `workos api`:** all of the above. `workos api` makes any authenticated REST request with the same key, so this PR adds no new capability. It adds convenience and discoverability. The real difference is confirmation: +- `workos api` requires `--yes` for **every** mutating request in agent, CI and JSON mode. +- The resource commands keep their own per-command posture: + - destructive commands (deletes, revokes) need `--yes` non-interactively; + - privilege changes (role/permission create and update, membership update and deactivate) need `--yes` non-interactively; + - other writes need no `--yes`: org create/update, user update, invitation send/resend, webhook create, org-domain create/verify, portal links, flag enable/disable/targets, and the redirect/CORS/homepage config. +- That posture was already there for signed-in agents. What's new is that a key alone now reaches it. + +**Recommendations** (not implemented; each needs a product call): +1. **On the API-key path in agent/CI mode, require `--yes` for every mutation,** matching `workos api`. At minimum, require it for the security-sensitive non-destructive writes: redirect URI / CORS / homepage changes, webhook create, portal link generation, invitation send. This is cheap to add in `resolveEnvScopedAuth()` / the adapters' write paths. +2. **Don't refuse destructive commands on an unclaimed key.** An unclaimed environment is a disposable sandbox the agent created itself. Blocking deletes there removes legitimate cleanup without stopping anything `workos api --yes` can already do. +3. **Treat live keys more strictly.** An `sk_live_` key passed via `WORKOS_API_KEY` or `--api-key` is the risky case. Consider always requiring `--yes` (or an extra confirmation) for mutations with a live key. +4. **Tell signed-in users when an exported key takes over.** A signed-in developer who has `WORKOS_API_KEY` exported for app work (common) now runs resource commands against that key's environment instead of their profile's. That follows the brief's rule (an explicit key wins), but it can surprise people. A one-line human-mode stderr notice would help, something like "Using WORKOS_API_KEY; unset it to use your dashboard login". Note that the shipped binary doesn't auto-load `.env` files (`--no-compile-autoload-dotenv`); running from source with Bun does. +5. **Prefer `WORKOS_API_KEY` over `--api-key` in docs for agents.** A flag value shows up in shell history and process lists. This is the same caveat as for the existing REST commands. + +## Tests + +- `src/commands/api-key-auth.spec.ts` covers: + - path choice: unclaimed profile, `WORKOS_API_KEY` over a session, `--api-key` over both, a signed-in user with a claimed profile's stored key staying on the session, the `--environment-id` refusal, account commands staying on the session; + - the unsupported errors and their leak check; + - the REST requests and outputs for every command's mutations; + - not-found and 401 handling. +- `src/commands/api-key-parity.spec.ts` covers JSON parity, described above. +- `src/lib/command-auth.spec.ts` covers: + - the `resolveResourceApiKey()` precedence, against the real file-backed config store; + - the updated copy. Two existing tests were renamed and updated, because their assertion that the copy says "does not accept API keys" is now the bug. +- Every new or changed test name contains "with an API key". +- `bunx vitest run src/lib/command-auth.spec.ts src/commands -t "with an API key"`: 57 passed. +- Existing suites for every touched command, plus `help-json`, `catalog` (incl. `no-graphql-leak`), `environment-target` and the bin integration specs: 1,323 passed. +- `bun run typecheck`: clean. From 5311a06254f321181b798e0f2f832cc952db23af Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 12:25:06 -0800 Subject: [PATCH 12/32] fix: make API-key writes fail safe and map states like the dashboard - authkit redirect-uris set adds new URIs before deleting dropped ones, so a rejected URI or failed request never leaves fewer working URIs. - Role permission changes tell a 404 from an empty success, never fall back to the unchanged role, and confirm the server holds exactly the requested permissions before the command reports them. - Role lookups for memberships search the organization's roles first, so an organization role that reuses an environment role's slug wins, as on the dashboard. - REST webhook status maps to the dashboard's Active/InActive and session auth methods to its SessionProvider values (from the vendored catalog), so enumOut yields the same output on both paths. An OAuth session's provider, which REST doesn't name, is null. --- src/commands/api-key-auth.spec.ts | 92 ++++++++++++++++++++++++ src/lib/api-key-operations/app-config.ts | 16 +++-- src/lib/api-key-operations/context.ts | 13 ++++ src/lib/api-key-operations/lookups.ts | 35 ++++++--- src/lib/api-key-operations/platform.ts | 10 ++- src/lib/api-key-operations/rbac.ts | 47 ++++++++---- src/lib/api-key-operations/users.ts | 27 ++++--- 7 files changed, 200 insertions(+), 40 deletions(-) diff --git a/src/commands/api-key-auth.spec.ts b/src/commands/api-key-auth.spec.ts index b6057d2c..8dbaef04 100644 --- a/src/commands/api-key-auth.spec.ts +++ b/src/commands/api-key-auth.spec.ts @@ -446,6 +446,54 @@ describe('resource commands with an API key', () => { expect(set).toMatchObject({ role: { permissions: ['users:read', 'users:write'] } }); }); + it('never reports permissions it failed to set when the replace returns 404 with an API key', async () => { + rest.respond({ + 'GET /authorization/roles': { object: 'list', data: [REST_ROLE()] }, + 'PATCH /authorization/roles/admin': REST_ROLE(), + // The replace fails; the old role (still holding users:read) must not be reported as updated. + 'PUT /authorization/roles/admin/permissions': { status: 404, body: { message: 'Role not found' } }, + 'GET /authorization/roles/admin': REST_ROLE(), + }); + + const error = await expectExit(() => runRoleSetPermissions('admin', [], { yes: true })); + + expect(error.code).toBe('not_found'); + expect(stdout).toHaveLength(0); + expect(rest.callsTo('GET /authorization/roles/admin')).toHaveLength(0); + }); + + it('refuses to report success when the server holds other permissions afterwards with an API key', async () => { + rest.respond({ + 'GET /authorization/roles': { object: 'list', data: [REST_ROLE()] }, + 'PATCH /authorization/roles/admin': REST_ROLE(), + 'PUT /authorization/roles/admin/permissions': REST_ROLE({ permissions: ['users:read'] }), + }); + + const error = await expectExit(() => runRoleSetPermissions('admin', ['users:write'], { yes: true })); + + expect(error.code).toBe('unexpected_result'); + expect(error.message).toContain('did not change as requested'); + expect(stdout).toHaveLength(0); + }); + + it('reads the role back after an empty-bodied permissions replace with an API key', async () => { + let replaced = false; + rest.respond({ + 'GET /authorization/roles': { object: 'list', data: [REST_ROLE()] }, + 'PATCH /authorization/roles/admin': REST_ROLE(), + 'PUT /authorization/roles/admin/permissions': () => { + replaced = true; + return { status: 204 }; + }, + 'GET /authorization/roles/admin': () => REST_ROLE({ permissions: replaced ? ['users:write'] : ['users:read'] }), + }); + + const out = await json(() => runRoleSetPermissions('admin', ['users:write'], { yes: true })); + + expect(out).toMatchObject({ role: { slug: 'admin', permissions: ['users:write'] } }); + expect(rest.callsTo('GET /authorization/roles/admin')).toHaveLength(1); + }); + it('reports an existing slug as already_exists on role create with an API key', async () => { rest.respond({ 'POST /authorization/roles': { status: 409, body: { message: 'exists', code: 'role_slug_already_exists' } }, @@ -657,6 +705,50 @@ describe('resource commands with an API key', () => { expect(deleted).toEqual({ deleted: 'dom_2' }); }); + it('adds replacement redirect URIs before deleting old ones, so a rejected URI deletes nothing, with an API key', async () => { + const existing = { object: 'redirect_uri', id: 'ru_1', uri: 'https://a.example.com/cb', default: true }; + rest.respond({ + 'GET /user_management/redirect_uris': restList([existing]), + 'POST /user_management/redirect_uris': { + status: 422, + body: { message: 'Invalid redirect URI', code: 'invalid_uri' }, + }, + 'DELETE /user_management/redirect_uris/ru_1': { status: 204 }, + }); + + const error = await expectExit(() => runAuthkitRedirectUrisSet({ uris: ['not-a-url'] })); + + expect(error.code).toBe('invalid_uri'); + expect(rest.callsTo('POST /user_management/redirect_uris')).toHaveLength(1); + expect(rest.callsTo('DELETE /user_management/redirect_uris/ru_1')).toHaveLength(0); + }); + + it('replaces redirect URIs by adding first and deleting second with an API key', async () => { + const oldUri = { object: 'redirect_uri', id: 'ru_1', uri: 'https://a.example.com/cb', default: false }; + const newUri = { object: 'redirect_uri', id: 'ru_2', uri: 'https://b.example.com/cb', default: false }; + let state = [oldUri]; + rest.respond({ + 'GET /user_management/redirect_uris': () => restList(state), + 'POST /user_management/redirect_uris': () => { + state = [...state, newUri]; + return newUri; + }, + 'DELETE /user_management/redirect_uris/ru_1': () => { + state = state.filter((uri) => uri.id !== 'ru_1'); + return { status: 204 }; + }, + }); + + const out = await json(() => runAuthkitRedirectUrisSet({ uris: ['https://b.example.com/cb'] })); + + const writes = rest.calls.filter((call) => call.method !== 'GET').map((call) => `${call.method} ${call.path}`); + expect(writes).toEqual(['POST /user_management/redirect_uris', 'DELETE /user_management/redirect_uris/ru_1']); + expect(out).toEqual({ + redirectUris: [{ id: 'ru_2', uri: 'https://b.example.com/cb', isDefault: false }], + dryRun: false, + }); + }); + it('adds redirect URIs and CORS origins without rewriting the rest with an API key', async () => { const existing = { object: 'redirect_uri', id: 'ru_1', uri: 'https://a.example.com/cb', default: true }; let created = false; diff --git a/src/lib/api-key-operations/app-config.ts b/src/lib/api-key-operations/app-config.ts index 856d4cb8..12f883dd 100644 --- a/src/lib/api-key-operations/app-config.ts +++ b/src/lib/api-key-operations/app-config.ts @@ -4,7 +4,8 @@ * `/user_management/cors_origins` and `/user_management/app_homepage_url`. * * The dashboard setters replace whole lists; REST has per-item endpoints. A - * list "set" becomes a diff: create what's missing and delete what's dropped. + * list "set" becomes a diff: create what's missing first, then delete what's + * dropped, so a failure part-way never leaves fewer working URIs than before. * Where REST lacks a piece, the request fails before any write: there is no * delete for CORS origins, no way to choose the default redirect URI, and no * validate-only (`--dry-run`) mode. @@ -74,17 +75,20 @@ export const appConfigOperations: Record = { exitApiKeyUnsupported('choosing the default redirect URI has no WorkOS API endpoint'); } + // Add before removing: if a new URI is rejected or a request fails, the + // working URIs are all still in place (at worst an extra one remains), + // so a failed replace can't break sign-in. + for (const entry of desired) { + if (!current.some((existing) => existing.uri === entry.uri)) { + await ctx.request({ method: 'POST', path: '/user_management/redirect_uris', body: { uri: entry.uri } }); + } + } const desiredUris = new Set(desired.map((entry) => entry.uri)); for (const existing of current) { if (!desiredUris.has(existing.uri)) { await ctx.request({ method: 'DELETE', path: `/user_management/redirect_uris/${encode(existing.id)}` }); } } - for (const entry of desired) { - if (!current.some((existing) => existing.uri === entry.uri)) { - await ctx.request({ method: 'POST', path: '/user_management/redirect_uris', body: { uri: entry.uri } }); - } - } const saved = await listAll(ctx, '/user_management/redirect_uris'); return { setRedirectUris: { __typename: 'RedirectUrisSet', redirectUris: saved.map(redirectUriNode) } }; diff --git a/src/lib/api-key-operations/context.ts b/src/lib/api-key-operations/context.ts index 8167bb8b..702cd8e2 100644 --- a/src/lib/api-key-operations/context.ts +++ b/src/lib/api-key-operations/context.ts @@ -49,6 +49,19 @@ export async function orNull(read: Promise): Promise { } } +/** Marks a REST 404, distinct from a 2xx with an empty body (which `workosRequest` returns as `null`). */ +export const NOT_FOUND = Symbol('not_found'); + +/** Run a request; a REST 404 resolves to {@link NOT_FOUND}, so an empty success can't pass for "missing". */ +export async function orNotFound(request: Promise): Promise { + try { + return await request; + } catch (error) { + if (isNotFound(error)) return NOT_FOUND; + throw error; + } +} + /** The dashboard list envelope: `{ data, listMetadata }`. */ export function listEnvelope(data: T[], listMetadata?: { before: string | null; after: string | null }) { return { diff --git a/src/lib/api-key-operations/lookups.ts b/src/lib/api-key-operations/lookups.ts index 4e59e801..404ffbea 100644 --- a/src/lib/api-key-operations/lookups.ts +++ b/src/lib/api-key-operations/lookups.ts @@ -22,7 +22,7 @@ export interface RestRole { interface Memo { environmentRoles?: Promise; - organizationRoles: Map>; + organizationRoles: Map>; organizationNames: Map>; } @@ -45,32 +45,45 @@ export function environmentRoles(ctx: ApiKeyContext): Promise { return memo.environmentRoles; } -/** Roles assignable in an organization (its own roles plus the environment roles it inherits). */ -export function organizationRoles(ctx: ApiKeyContext, organizationId: string): Promise { +/** + * Roles assignable in an organization: its own custom roles plus the + * environment roles it inherits. `null` when REST can't list them (e.g. the + * organization is gone). + */ +export function organizationRoles(ctx: ApiKeyContext, organizationId: string): Promise { const memo = memoFor(ctx); let roles = memo.organizationRoles.get(organizationId); if (!roles) { - roles = ctx - .request<{ data: RestRole[] }>({ + roles = orNull( + ctx.request<{ data: RestRole[] }>({ method: 'GET', path: `/authorization/organizations/${encode(organizationId)}/roles`, - }) - .then((result) => result?.data ?? []); + }), + ).then((result) => (result ? (result.data ?? []) : null)); memo.organizationRoles.set(organizationId, roles); } return roles; } -/** Find a role by ID (or slug) among the environment roles, then the organization's. */ +/** + * Find a role by ID or slug as the organization sees it. An organization's + * custom role can reuse an environment role's slug and then wins inside that + * organization (as on the dashboard), so with an `organizationId` the + * organization's roles are searched first, preferring its custom role; the + * environment roles are the fallback. + */ export async function findRole( ctx: ApiKeyContext, match: { id?: string; slug?: string }, organizationId?: string | null, ): Promise { const matches = (role: RestRole) => (match.id ? role.id === match.id : role.slug === match.slug); - const fromEnvironment = (await environmentRoles(ctx)).find(matches); - if (fromEnvironment || !organizationId) return fromEnvironment; - return (await organizationRoles(ctx, organizationId)).find(matches); + if (organizationId) { + const candidates = ((await organizationRoles(ctx, organizationId)) ?? []).filter(matches); + const found = candidates.find((role) => role.type === 'OrganizationRole') ?? candidates[0]; + if (found) return found; + } + return (await environmentRoles(ctx)).find(matches); } /** An organization's name, or `null` when it can't be read. */ diff --git a/src/lib/api-key-operations/platform.ts b/src/lib/api-key-operations/platform.ts index 835f5e4b..777b3259 100644 --- a/src/lib/api-key-operations/platform.ts +++ b/src/lib/api-key-operations/platform.ts @@ -52,10 +52,16 @@ interface RestFlag { updated_at?: string; } -/** REST `enabled` → the dashboard's `Active`; other states pass through. */ +/** + * REST endpoint status → the dashboard's `WebhookEndpointState` (`Active` / + * `InActive`, per the vendored catalog), so `enumOut` yields the same + * `active` / `in_active` on both paths. + */ +const WEBHOOK_STATE: Record = { enabled: 'Active', disabled: 'InActive' }; + function webhookState(status: string | null | undefined): string | null { if (!status) return null; - return status === 'enabled' ? 'Active' : status; + return WEBHOOK_STATE[status] ?? status; } /** Flag environment IDs handed out by the flag reads → slug, for the update that follows. */ diff --git a/src/lib/api-key-operations/rbac.ts b/src/lib/api-key-operations/rbac.ts index f437f0de..33401158 100644 --- a/src/lib/api-key-operations/rbac.ts +++ b/src/lib/api-key-operations/rbac.ts @@ -10,7 +10,9 @@ */ import { WorkOSApiError } from '../workos-api.js'; -import { type ApiKeyContext, type ApiKeyOperation, encode, listAll, orNull } from './context.js'; +import { type ApiKeyContext, type ApiKeyOperation, encode, listAll, NOT_FOUND, orNotFound, orNull } from './context.js'; +import { exitWithError } from '../../utils/output.js'; +import { formatWorkOSCommand } from '../../utils/command-invocation.js'; import type { RestRole } from './lookups.js'; interface RestPermission { @@ -75,6 +77,11 @@ function permissionNode(permission: RestPermission) { }; } +function sameSlugs(actual: string[], expected: string[]): boolean { + const want = new Set(expected); + return actual.length === want.size && actual.every((slug) => want.has(slug)); +} + function rolePath(ref: RoleRef): string { return ref.organizationId ? `/authorization/organizations/${encode(ref.organizationId)}/roles/${encode(ref.slug)}` @@ -148,7 +155,7 @@ export const rbacOperations: Record = { const notFound = { updateRole: { __typename: 'RoleNotFound', roleId: input.roleId } }; if (!ref) return notFound; - let role = await orNull( + const patched = await orNotFound( ctx.request({ method: 'PATCH', path: rolePath(ref), @@ -158,17 +165,33 @@ export const rbacOperations: Record = { }, }), ); - if (!role) return notFound; + if (patched === NOT_FOUND) return notFound; + let role: RestRole | null = patched; if (input.permissions) { - role = - (await orNull( - ctx.request({ - method: 'PUT', - path: `${rolePath(ref)}/permissions`, - body: { permissions: input.permissions }, - }), - )) ?? (await readRole(ctx, ref)); - if (!role) return notFound; + const replaced = await orNotFound( + ctx.request({ + method: 'PUT', + path: `${rolePath(ref)}/permissions`, + body: { permissions: input.permissions }, + }), + ); + // A 404 here means nothing changed: never fall back to the old role. + if (replaced === NOT_FOUND) return notFound; + role = replaced; + } + // An empty 2xx body: read back what the server now holds. + role ??= await readRole(ctx, ref); + if (!role) return notFound; + // The command reports the requested permissions as the result, so confirm + // the server actually holds exactly those before letting it. + if (input.permissions && !sameSlugs(role.permissions ?? [], input.permissions)) { + exitWithError({ + code: 'unexpected_result', + message: + `The permissions on role "${ref.slug}" did not change as requested. ` + + `Run \`${formatWorkOSCommand(`role get ${ref.slug}${ref.organizationId ? ` --org ${ref.organizationId}` : ''}`)}\` ` + + 'to see what it holds now.', + }); } return { updateRole: { __typename: 'RoleUpdated', role: roleNode(role) } }; }, diff --git a/src/lib/api-key-operations/users.ts b/src/lib/api-key-operations/users.ts index 1d3a4a98..7c458522 100644 --- a/src/lib/api-key-operations/users.ts +++ b/src/lib/api-key-operations/users.ts @@ -7,7 +7,8 @@ * (user get), and session organization names. No REST source, returned * `null`: `sessionCount`, `hasPassword`, `emailVerifiedAt` (REST has only a * verified boolean, kept internally for the human view), a factor's - * `lastVerifiedAt`, and a session impersonator's id/name. + * `lastVerifiedAt`, a session impersonator's id/name, and an OAuth session's + * provider. */ import type { WorkOSListResponse } from '../workos-api.js'; @@ -118,16 +119,24 @@ const SESSION_STATE: Record Record = { + cross_app_auth: 'CrossAppAuth', + external_auth: 'ExternalAuth', + impersonation: 'Impersonation', + magic_code: 'MagicAuth', + migrated_session: 'MigratedSession', + passkey: 'Passkey', + password: 'Password', + sso: 'SingleSignOn', +}; + function sessionProvider(method: string | null | undefined): string | null { - if (!method) return null; - return method - .split('_') - .map((part) => part.charAt(0).toUpperCase() + part.slice(1)) - .join(''); + return method ? (SESSION_PROVIDER[method] ?? null) : null; } async function sessionNode(ctx: ApiKeyContext, session: RestSession) { From 98e841094f19d227f8338662e4ed97d87fedb62f Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 12:25:07 -0800 Subject: [PATCH 13/32] test: tighten the session-vs-key parity gate offline and live Null gaps are now exact leaf paths (user.authenticationFactors[].lastVerifiedAt, session.impersonator.id, ...) judged by one shared apiKeyParityDiffs(): every object needs the same keys on both sides, arrays the same length, and every other leaf the same value, so an emptied element or an object going null fails. The offline spec and parity-smoke --api-key both use it. parity-smoke --api-key now proves the session side: whoami must succeed without a key, and every session-side command is pinned to its environment with --environment-id, which the CLI refuses whenever any API key applies (including an unclaimed profile's), so the session side can never quietly run on REST. --- scripts/parity-smoke.ts | 120 ++++++------- src/commands/api-key-parity.spec.ts | 219 +++++++++++++++++------ src/lib/api-key-operations/known-gaps.ts | 87 ++++++++- 3 files changed, 299 insertions(+), 127 deletions(-) diff --git a/scripts/parity-smoke.ts b/scripts/parity-smoke.ts index caec6ae1..6789b135 100644 --- a/scripts/parity-smoke.ts +++ b/scripts/parity-smoke.ts @@ -48,10 +48,14 @@ * API-key mode (`--api-key`): compares THIS branch against itself, dashboard * session vs API key, for every resource command's list/get. No ../main * needed. Same prereqs as above (a login, and a WORKOS_API_KEY for the same - * environment the session targets). Unlike the branch-vs-main buckets, the two - * sides must have IDENTICAL keys and values; the only allowed difference is a - * field in API_KEY_ACCEPTED (REST has no source for it, so the key side is - * null). The offline equivalent is src/commands/api-key-parity.spec.ts. + * environment the session targets). `whoami` first proves the login and finds + * its environment; every session-side command is pinned to it with + * --environment-id, which the CLI refuses whenever any API key applies, so the + * session side can't silently run on REST. Unlike the branch-vs-main buckets, + * the two sides must have IDENTICAL keys and values; the only allowed + * difference is a leaf in API_KEY_ACCEPTED (REST has no source for it), which + * may be null on the key side. The offline equivalent is + * src/commands/api-key-parity.spec.ts. * * bun run scripts/parity-smoke.ts --api-key * @@ -61,7 +65,7 @@ import { spawn } from 'node:child_process'; import { existsSync, mkdtempSync, readFileSync } from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -import { API_KEY_NULL_FIELDS } from '../src/lib/api-key-operations/known-gaps.ts'; +import { API_KEY_NULL_FIELDS, apiKeyParityDiffs } from '../src/lib/api-key-operations/known-gaps.ts'; const BRANCH_DIR = path.resolve(import.meta.dirname, '..'); const MAIN_DIR = path.resolve(BRANCH_DIR, '../main'); @@ -965,65 +969,26 @@ async function checkNew(c: { label: string; args: string[] }): Promise { // --- API-key mode: dashboard session vs API key, same branch ------------------------ /** - * Deliberate session-vs-key divergences, keyed `command.field`. Shared with the - * offline spec via known-gaps.ts. Each is a field REST has no source for, so - * the key side must be null; a casing-only difference is never listed here (it - * is a bug and must fail). + * Deliberate session-vs-key divergences, keyed `command.path` (one leaf of the + * curated entity; `[]` steps into array elements). Shared with the offline + * spec via known-gaps.ts, and enforced by the same `apiKeyParityDiffs()`: a + * listed leaf may be null on the key side, and nothing else may differ (no + * missing keys, no emptied objects, no casing-only differences). */ const API_KEY_ACCEPTED: Record = { ...API_KEY_NULL_FIELDS }; /** Cursors are opaque and plane-specific; everything else must match exactly. */ const CURSOR_KEYS = new Set(['before', 'after', 'listMetadata', 'list_metadata', 'pagination']); -function exact(v: unknown): unknown { - if (v === null || v === undefined) return null; - if (Array.isArray(v)) return v.map(exact).sort(cmp); - if (typeof v === 'object') { - const o: Record = {}; - for (const k of Object.keys(v as Record).sort()) { - if (!CURSOR_KEYS.has(k)) o[k] = exact((v as Record)[k]); - } - return o; - } - return v; -} - /** - * True when `k` is `s` with some values replaced by null (and nothing else - * changed): the key side lacks data REST can't supply but invents nothing. + * The environment the session side is pinned to. Every session-side command + * passes it as `--environment-id`, which the CLI refuses whenever ANY API key + * applies (WORKOS_API_KEY, --api-key, or an unclaimed active profile's stored + * key). So a session-side run either really goes through the dashboard login + * or fails loudly; it can never quietly fall back to REST and compare REST + * with itself. */ -function isNulledCopy(s: unknown, k: unknown): boolean { - if (k === null || k === undefined) return true; - if (Array.isArray(s) && Array.isArray(k)) { - return s.length === k.length && k.every((item, index) => isNulledCopy(s[index], item)); - } - if (isPlainObject(s) && isPlainObject(k)) { - return Object.keys(k).every((key) => isNulledCopy(s[key], k[key])); - } - return JSON.stringify(s) === JSON.stringify(k); -} - -/** Compare one entity: identical key sets, identical values, except accepted nulls. */ -function compareSessionVsKey(cmd: string, s: any, k: any): { diffs: string[]; accepted: string[] } { - const diffs: string[] = []; - const accepted: string[] = []; - const keys = new Set([...Object.keys(s ?? {}), ...Object.keys(k ?? {})]); - for (const key of keys) { - if (CURSOR_KEYS.has(key)) continue; - if (!(key in (s ?? {})) || !(key in (k ?? {}))) { - diffs.push(`${key}: present only on the ${key in (s ?? {}) ? 'session' : 'API-key'} side`); - continue; - } - if (JSON.stringify(exact(s[key])) === JSON.stringify(exact(k[key]))) continue; - const reason = API_KEY_ACCEPTED[`${cmd}.${key}`]; - if (reason && isNulledCopy(s[key], k[key])) { - accepted.push(`${key} (${reason})`); - } else { - diffs.push(`${key}: session=${JSON.stringify(s[key])} key=${JSON.stringify(k[key])}`); - } - } - return { diffs, accepted }; -} +let sessionEnvironmentId = ''; interface ApiKeyCheck { cmd: string; @@ -1036,12 +1001,34 @@ interface ApiKeyCheck { async function runBoth(args: string[]): Promise<[RunResult, RunResult]> { return Promise.all([ - run(BRANCH_DIR, [...args, ...envArgs()], { withoutApiKey: true }), + run(BRANCH_DIR, [...args, '--environment-id', sessionEnvironmentId], { withoutApiKey: true }), // The key decides the environment; --environment-id is refused with a key. run(BRANCH_DIR, args), ]); } +/** + * Prove a dashboard login exists and find the environment it targets, using + * `whoami` (session-only: it never uses a key). Pinning that environment on + * every session-side command is what keeps the session side honest. + */ +async function pinSessionEnvironment(): Promise { + const r = await run(BRANCH_DIR, ['whoami', '--json', ...envArgs()], { withoutApiKey: true }); + if (r.rc === 4) { + console.error('--api-key mode needs a dashboard login for the session side: run `workos auth login` first.'); + process.exit(2); + } + const environmentId = parseJson(r.stdout)?.environment?.id; + if (r.rc !== 0 || typeof environmentId !== 'string' || !environmentId) { + console.error( + `could not resolve the session's environment (whoami rc=${r.rc} ${shortErr(r.stderr)}). ` + + 'Set PARITY_ENV_ID, or switch to a claimed profile that targets the API key’s environment.', + ); + process.exit(2); + } + sessionEnvironmentId = environmentId; +} + async function checkSessionVsKey(c: ApiKeyCheck): Promise { const [s, k] = await runBoth(c.args); if (s.rc === 4) { @@ -1060,8 +1047,7 @@ async function checkSessionVsKey(c: ApiKeyCheck): Promise { } const sv = js[c.key]; const kv = jk[c.key]; - let diffs: string[] = []; - let accepted: string[] = []; + const diffs: string[] = []; let rows = 1; if (Array.isArray(sv) && Array.isArray(kv) && c.idKey) { const sIds = sv.map((row: any) => row?.[c.idKey!]).sort(); @@ -1073,17 +1059,12 @@ async function checkSessionVsKey(c: ApiKeyCheck): Promise { rows = sv.length; for (const row of sv) { const other = kv.find((candidate: any) => candidate?.[c.idKey!] === row?.[c.idKey!]); - const r = compareSessionVsKey(c.cmd, row, other); - diffs.push(...r.diffs.map((d) => `${row?.[c.idKey!]}: ${d}`)); - accepted.push(...r.accepted); + diffs.push(...apiKeyParityDiffs(c.cmd, row, other, CURSOR_KEYS).map((d) => `${row?.[c.idKey!]}: ${d}`)); } } else { - const r = compareSessionVsKey(c.cmd, sv, kv); - diffs = r.diffs; - accepted = r.accepted; + diffs.push(...apiKeyParityDiffs(c.cmd, sv, kv, CURSOR_KEYS)); } for (const d of diffs) notes.push(`${C.red}FAIL${C.reset} ${c.label} ${d}`); - for (const a of new Set(accepted)) notes.push(`${C.cyan}INFO${C.reset} ${c.label} accepted: ${a}`); const empty = Array.isArray(sv) && sv.length === 0; push( 'API-KEY', @@ -1093,7 +1074,7 @@ async function checkSessionVsKey(c: ApiKeyCheck): Promise { ? `${diffs.length} UNEXPECTED diff(s)` : empty ? 'both sides empty — proves the call works, proves nothing about data' - : `${rows} row(s), identical keys and values${accepted.length ? `; ${new Set(accepted).size} accepted null field(s)` : ''}`, + : `${rows} row(s), identical keys and values apart from documented null gaps`, ); return js; } @@ -1105,6 +1086,8 @@ async function runApiKeyMode(): Promise { console.error('--api-key mode needs WORKOS_API_KEY (or the branch .env.local) for the session’s environment'); process.exit(2); } + await pinSessionEnvironment(); + console.log(` session pinned to environment ${sessionEnvironmentId}\n`); const lists: ApiKeyCheck[] = [ { @@ -1243,6 +1226,9 @@ async function runApiKeyMode(): Promise { console.log(`\n${C.dim}field-level detail${C.reset}`); for (const n of notes) console.log(` ${n}`); } + console.log(`\n${C.dim}documented null gaps (may be null on the API-key side)${C.reset}`); + for (const [field, reason] of Object.entries(API_KEY_ACCEPTED)) + console.log(` ${C.cyan}${field}${C.reset} ${reason}`); const failed = rows.filter((r) => r.status === 'FAIL').length; const auth = rows.filter((r) => r.status === 'AUTH').length; console.log( diff --git a/src/commands/api-key-parity.spec.ts b/src/commands/api-key-parity.spec.ts index 7495f4f2..059191da 100644 --- a/src/commands/api-key-parity.spec.ts +++ b/src/commands/api-key-parity.spec.ts @@ -46,7 +46,7 @@ vi.mock('../lib/config-store.js', async (importActual) => { const { setOutputMode } = await import('../utils/output.js'); const { resetInteractionModeForTests } = await import('../utils/interaction-mode.js'); const { setResourceApiKeyFlag } = await import('../lib/resource-auth.js'); -const { API_KEY_NULL_FIELDS } = await import('../lib/api-key-operations/known-gaps.js'); +const { API_KEY_NULL_FIELDS, apiKeyParityDiffs } = await import('../lib/api-key-operations/known-gaps.js'); const { runOrgList, runOrgGet } = await import('./organization.js'); const { runUserList, runUserGet } = await import('./user.js'); const { runRoleList, runRoleGet } = await import('./role.js'); @@ -432,35 +432,37 @@ async function viaApiKey(routes: Parameters[0], run: () => return output; } -type Json = Record | unknown[]; +type Json = Record; -function at(value: Json, path: string[]): { parent: Record; key: string } { - let node: unknown = value; - for (const segment of path.slice(0, -1)) node = (node as Record)[segment]; - return { parent: node as Record, key: path[path.length - 1] }; +/** First value at a gap path (`[]` steps into the first element), for checking a fixture exercises the gap. */ +function firstAt(value: unknown, path: string): unknown { + let node: unknown = Array.isArray(value) ? value[0] : value; + for (const segment of path.split('.')) { + const key = segment.replace(/\[\]$/, ''); + node = (node as Record | null)?.[key]; + if (segment.endsWith('[]')) node = Array.isArray(node) ? node[0] : undefined; + } + return node; } /** - * Assert the two outputs are identical except `nullOnKeyPath` (dot paths into - * the output), which must be null on the key path and must each be a listed - * known gap (`command.field`). + * Assert the two outputs are identical: same envelope and pagination, and the + * entity (or rows) judged by the shared `apiKeyParityDiffs`, which allows only + * documented null leaves. `expectedGaps` names the gaps this fixture exercises + * (the session side has a value there), so a test can't pass vacuously. */ -function expectParity( - command: string, - session: Json, - apiKey: Json, - nullOnKeyPath: Array<{ path: string; field: string }> = [], -): void { - const s = structuredClone(session); - const k = structuredClone(apiKey); - for (const { path, field } of nullOnKeyPath) { - expect(API_KEY_NULL_FIELDS, `${command}.${field} must be a documented gap`).toHaveProperty([`${command}.${field}`]); - const keyed = at(k, path.split('.')); - expect(keyed.parent[keyed.key], `${path} on the key path`).toBeNull(); - const sessioned = at(s, path.split('.')); - sessioned.parent[sessioned.key] = null; +function expectParity(command: string, session: Json, apiKey: Json, expectedGaps: string[] = []): void { + expect(Object.keys(apiKey).sort()).toEqual(Object.keys(session).sort()); + const entityKey = Object.keys(session).find((key) => key !== 'pagination') as string; + const { [entityKey]: sessionEntity, ...sessionEnvelope } = session; + const { [entityKey]: apiKeyEntity, ...apiKeyEnvelope } = apiKey; + expect(apiKeyEnvelope).toEqual(sessionEnvelope); + expect(apiKeyParityDiffs(command, sessionEntity, apiKeyEntity)).toEqual([]); + for (const gap of expectedGaps) { + expect(API_KEY_NULL_FIELDS, `${command}.${gap} must be a documented gap`).toHaveProperty([`${command}.${gap}`]); + expect(firstAt(sessionEntity, gap), `${gap} has a value on the session side`).not.toBeNull(); + expect(firstAt(apiKeyEntity, gap), `${gap} on the API-key side`).toBeNull(); } - expect(k).toEqual(s); } describe('resource command --json parity, session vs API key', () => { @@ -508,7 +510,7 @@ describe('resource command --json parity, session vs API key', () => { ); const apiKey = await viaApiKey({ 'GET /organizations': restList([REST_ORG], 'org_1') }, () => runOrgList({})); - expectParity('organization', session, apiKey, [{ path: 'organizations.0.usersCount', field: 'usersCount' }]); + expectParity('organization', session, apiKey, ['usersCount']); expect(apiKey).toMatchObject({ organizations: [{ domains: [{ state: 'verified' }], metadata: { team: 'blue' } }] }); }); @@ -519,7 +521,7 @@ describe('resource command --json parity, session vs API key', () => { ); const apiKey = await viaApiKey({ 'GET /organizations/org_1': REST_ORG }, () => runOrgGet('org_1')); - expectParity('organization', session, apiKey, [{ path: 'organization.usersCount', field: 'usersCount' }]); + expectParity('organization', session, apiKey, ['usersCount']); }); const userRestRoutes = { @@ -546,11 +548,7 @@ describe('resource command --json parity, session vs API key', () => { ); const apiKey = await viaApiKey(userRestRoutes, () => runUserList({})); - expectParity('user', session, apiKey, [ - { path: 'users.0.sessionCount', field: 'sessionCount' }, - { path: 'users.0.hasPassword', field: 'hasPassword' }, - { path: 'users.0.emailVerifiedAt', field: 'emailVerifiedAt' }, - ]); + expectParity('user', session, apiKey, ['sessionCount', 'hasPassword', 'emailVerifiedAt']); // Identities are filled from memberships, with role IDs/names resolved from slugs. expect(apiKey).toMatchObject({ users: [ @@ -579,13 +577,40 @@ describe('resource command --json parity, session vs API key', () => { const apiKey = await viaApiKey(userRestRoutes, () => runUserGet('user_1')); expectParity('user', session, apiKey, [ - { path: 'user.sessionCount', field: 'sessionCount' }, - { path: 'user.hasPassword', field: 'hasPassword' }, - { path: 'user.emailVerifiedAt', field: 'emailVerifiedAt' }, - { path: 'user.authenticationFactors.0.lastVerifiedAt', field: 'authenticationFactors' }, + 'sessionCount', + 'hasPassword', + 'emailVerifiedAt', + 'authenticationFactors[].lastVerifiedAt', ]); }); + it('user get shows an organization role that shadows an environment slug, matching the dashboard, with an API key', async () => { + const orgMember = { ...REST_ROLE_MEMBER, id: 'role_org_member', name: 'Org Member', type: 'OrganizationRole' }; + const session = await viaSession( + () => ({ + userlandUser: { + ...GQL_USER, + identities: { data: [{ ...GQL_IDENTITY, roles: [{ id: 'role_org_member', name: 'Org Member' }] }] }, + authenticationFactors: [], + }, + }), + () => runUserGet('user_1'), + ); + const apiKey = await viaApiKey( + { + ...userRestRoutes, + 'GET /user_management/users/user_1/auth_factors': restList([]), + // The organization's list carries both the inherited environment role and its own role of the same slug. + 'GET /authorization/organizations/org_1/roles': { object: 'list', data: [REST_ROLE_MEMBER, orgMember] }, + }, + () => runUserGet('user_1'), + ); + expectParity('user', session, apiKey, ['sessionCount', 'hasPassword', 'emailVerifiedAt']); + expect(apiKey).toMatchObject({ + user: { identities: [{ roles: [{ id: 'role_org_member', name: 'Org Member' }] }] }, + }); + }); + it('role list and get match with an API key', async () => { const router = () => ({ rolesForEnvironment: { roles: [GQL_ROLE] } }); const routes = { 'GET /authorization/roles': { object: 'list', data: [REST_ROLE_ADMIN] } }; @@ -669,7 +694,6 @@ describe('resource command --json parity, session vs API key', () => { }); it('membership list (by user) and get match with an API key', async () => { - const membershipNull = (path: string) => [{ path, field: 'type' }]; expectParity( 'membership', await viaSession( @@ -679,7 +703,7 @@ describe('resource command --json parity, session vs API key', () => { await viaApiKey({ 'GET /user_management/organization_memberships': restList([REST_MEMBERSHIP]) }, () => runMembershipList({ user: 'user_1' }), ), - membershipNull('memberships.0.type'), + ['type'], ); expectParity( 'membership', @@ -690,7 +714,7 @@ describe('resource command --json parity, session vs API key', () => { await viaApiKey({ 'GET /user_management/organization_memberships/om_1': REST_MEMBERSHIP }, () => runMembershipGet('om_1'), ), - membershipNull('membership.type'), + ['type'], ); }); @@ -752,6 +776,54 @@ describe('resource command --json parity, session vs API key', () => { expect(apiKey).toMatchObject({ webhookEndpoints: [{ state: 'active' }] }); }); + it('disabled webhook endpoints match with an API key (dashboard InActive, REST disabled)', async () => { + const session = await viaSession( + () => ({ + webhookEndpoints: { + data: [{ ...GQL_ENDPOINT, state: 'InActive' }], + listMetadata: { before: null, after: null }, + }, + }), + () => runWebhookList({}), + ); + const apiKey = await viaApiKey( + { 'GET /webhook_endpoints': restList([{ ...REST_ENDPOINT, status: 'disabled' }]) }, + () => runWebhookList({}), + ); + expectParity('webhook', session, apiKey); + expect(apiKey).toMatchObject({ webhookEndpoints: [{ state: 'in_active' }] }); + }); + + it('session providers match with an API key, and an unnamed OAuth provider is a documented null', async () => { + const gqlSessions = [ + { ...GQL_SESSION, id: 'session_magic', provider: 'MagicAuth' }, + { ...GQL_SESSION, id: 'session_sso', provider: 'SingleSignOn' }, + { ...GQL_SESSION, id: 'session_oauth', provider: 'GoogleOAuth' }, + ]; + const restSessions = [ + { ...REST_SESSION, id: 'session_magic', auth_method: 'magic_code' }, + { ...REST_SESSION, id: 'session_sso', auth_method: 'sso' }, + { ...REST_SESSION, id: 'session_oauth', auth_method: 'oauth' }, + ]; + const session = await viaSession( + () => ({ + userlandUser: { id: 'user_1', sessions: { data: gqlSessions, listMetadata: { before: null, after: null } } }, + }), + () => runSessionList('user_1', {}), + ); + const apiKey = await viaApiKey( + { + 'GET /user_management/users/user_1/sessions': restList(restSessions), + 'GET /organizations/org_1': REST_ORG, + }, + () => runSessionList('user_1', {}), + ); + expectParity('session', session, apiKey); + expect(apiKey).toMatchObject({ + sessions: [{ provider: 'MagicAuth' }, { provider: 'SingleSignOn' }, { provider: null }], + }); + }); + it('event list matches with an API key, newest first with the same cursor contract', async () => { const session = await viaSession( () => ({ environment: { events: { data: [GQL_EVENT], listMetadata: { before: 'event_0', after: null } } } }), @@ -760,7 +832,7 @@ describe('resource command --json parity, session vs API key', () => { const apiKey = await viaApiKey({ 'GET /events': restList([REST_EVENT], 'event_0') }, () => runEventList({ events: ['user.created'] }), ); - expectParity('event', session, apiKey, [{ path: 'events.0.updatedAt', field: 'updatedAt' }]); + expectParity('event', session, apiKey, ['updatedAt']); expect(rest.callsTo('GET /events')[0].query).toMatchObject({ events: 'user.created', order: 'desc' }); }); @@ -780,11 +852,7 @@ describe('resource command --json parity, session vs API key', () => { 'feature-flag', await viaSession(router, () => runFeatureFlagGet('beta')), await viaApiKey(routes, () => runFeatureFlagGet('beta')), - [ - { path: 'flag.accessType', field: 'accessType' }, - { path: 'flag.organizationTargets', field: 'organizationTargets' }, - { path: 'flag.userTargets', field: 'userTargets' }, - ], + ['accessType', 'organizationTargets', 'userTargets'], ); }); @@ -796,10 +864,7 @@ describe('resource command --json parity, session vs API key', () => { () => runOrgDomainGet('dom_1', {}), ); const apiKey = await viaApiKey({ 'GET /organizations': restList([REST_ORG]) }, () => runOrgDomainGet('dom_1', {})); - expectParity('org-domain', session, apiKey, [ - { path: 'domain.verificationContent', field: 'verificationContent' }, - { path: 'domain.domainCaptureEnabled', field: 'domainCaptureEnabled' }, - ]); + expectParity('org-domain', session, apiKey, ['verificationContent', 'domainCaptureEnabled']); }); it('portal generate-link matches with an API key', async () => { @@ -821,11 +886,59 @@ describe('resource command --json parity, session vs API key', () => { const apiKey = await viaApiKey({ 'POST /portal/generate_link': { link: 'https://setup.workos.com/x' } }, () => runPortalGenerateLink({ intent: 'sso', organization: 'org_1' }), ); - expectParity('portal', session, apiKey, [ - { path: 'portalSetupLink.id', field: 'id' }, - { path: 'portalSetupLink.state', field: 'state' }, - { path: 'portalSetupLink.expiresAt', field: 'expiresAt' }, - ]); + expectParity('portal', session, apiKey, ['id', 'state', 'expiresAt']); expect(rest.callsTo('POST /portal/generate_link')[0].body).toEqual({ organization: 'org_1', intent: 'sso' }); }); }); + +describe('apiKeyParityDiffs, the shared session-vs-key parity gate', () => { + const sessionUser = { + id: 'user_1', + email: 'jane@example.com', + authenticationFactors: [{ id: 'auth_factor_1', lastVerifiedAt: T1 }], + }; + const sessionRow = { + id: 'session_1', + provider: 'Password', + impersonator: { id: 'user_admin', email: 'admin@example.com', firstName: 'Ada', lastName: 'Admin' }, + }; + + it('accepts only documented null leaves with an API key', () => { + expect( + apiKeyParityDiffs('user', sessionUser, { + ...sessionUser, + authenticationFactors: [{ id: 'auth_factor_1', lastVerifiedAt: null }], + }), + ).toEqual([]); + expect( + apiKeyParityDiffs('session', sessionRow, { + ...sessionRow, + impersonator: { id: null, email: 'admin@example.com', firstName: null, lastName: null }, + }), + ).toEqual([]); + }); + + it('rejects an auth factor that lost its keys with an API key', () => { + const diffs = apiKeyParityDiffs('user', sessionUser, { ...sessionUser, authenticationFactors: [{}] }); + expect(diffs.join('\n')).toContain('authenticationFactors[].id: present only on the session side'); + }); + + it('rejects an impersonator that went null as a whole with an API key', () => { + const diffs = apiKeyParityDiffs('session', sessionRow, { ...sessionRow, impersonator: null }); + expect(diffs).toHaveLength(1); + expect(diffs[0]).toContain('impersonator'); + }); + + it('rejects a lost email, a lost ID and a casing-only difference with an API key', () => { + expect( + apiKeyParityDiffs('session', sessionRow, { + ...sessionRow, + impersonator: { id: null, email: null, firstName: null, lastName: null }, + }), + ).toEqual([expect.stringContaining('impersonator.email')]); + expect(apiKeyParityDiffs('user', [sessionUser], [{ ...sessionUser, id: undefined }])).not.toEqual([]); + expect(apiKeyParityDiffs('session', sessionRow, { ...sessionRow, provider: 'password' })).toEqual([ + expect.stringContaining('provider'), + ]); + }); +}); diff --git a/src/lib/api-key-operations/known-gaps.ts b/src/lib/api-key-operations/known-gaps.ts index b9c4dba9..b72312c0 100644 --- a/src/lib/api-key-operations/known-gaps.ts +++ b/src/lib/api-key-operations/known-gaps.ts @@ -1,20 +1,21 @@ /** * Output fields the API-key path returns as `null` because the WorkOS REST API - * has no source for them, keyed `command.field` (the curated `--json` key). + * has no source for them. Keys are `command.path`, where `path` points at one + * leaf of the curated `--json` entity (`[]` steps into every array element). * Keys, casing and shapes match the dashboard path; only these values differ. * * Shared by the offline parity spec (`src/commands/api-key-parity.spec.ts`) - * and the live comparison in `scripts/parity-smoke.ts --api-key`. Every entry - * is a missing REST field, never a casing difference: enum casing is - * normalized on both paths, so a casing-only divergence is a bug. + * and the live comparison in `scripts/parity-smoke.ts --api-key`, which both + * judge parity with {@link apiKeyParityDiffs}. Every entry is a missing REST + * field, never a casing difference: enum casing is normalized on both paths, + * so a casing-only divergence is a bug. */ export const API_KEY_NULL_FIELDS: Record = { 'organization.usersCount': 'REST organizations carry no member count.', 'user.sessionCount': 'REST users carry no session count.', 'user.hasPassword': 'REST users do not say whether a password is set.', 'user.emailVerifiedAt': 'REST users have an email_verified boolean but no verification timestamp.', - 'user.authenticationFactors': - 'REST auth factors carry no last-verified time, so each factor has lastVerifiedAt: null.', + 'user.authenticationFactors[].lastVerifiedAt': 'REST auth factors carry no last-verified time.', 'membership.type': 'REST memberships carry no membership type.', 'event.updatedAt': 'REST events carry only a creation time.', 'feature-flag.accessType': 'The REST flag endpoints expose no access type.', @@ -26,6 +27,78 @@ export const API_KEY_NULL_FIELDS: Record = { 'portal.id': 'REST generate_link returns only the link URL.', 'portal.state': 'REST generate_link returns only the link URL.', 'portal.expiresAt': 'REST generate_link returns only the link URL.', - 'session.impersonator': 'REST names an impersonator by email only; id, firstName and lastName are null.', + 'session.provider': 'REST reports OAuth sign-ins as plain "oauth", without naming the OAuth provider.', + 'session.impersonator.id': 'REST names an impersonator by email only.', + 'session.impersonator.firstName': 'REST names an impersonator by email only.', + 'session.impersonator.lastName': 'REST names an impersonator by email only.', 'config.applicationId': 'REST sets the AuthKit homepage URL without exposing the application ID.', }; + +const isPlainObject = (value: unknown): value is Record => + typeof value === 'object' && value !== null && !Array.isArray(value); + +/** Order-insensitive array pairing: by `id` when every element has one, else by JSON. */ +function sortForPairing(items: unknown[]): unknown[] { + const byId = items.every((item) => isPlainObject(item) && typeof item.id === 'string'); + const key = (item: unknown) => (byId ? String((item as { id: string }).id) : JSON.stringify(item)); + return [...items].sort((a, b) => (key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0)); +} + +/** + * Compare one entity from the dashboard path (`session`) with the same entity + * from the API-key path (`apiKey`). Returns one message per divergence; `[]` + * means parity. + * + * Strict by design: every object must have the same keys on both sides, + * arrays the same length, and every leaf the same value. The only exception + * is a leaf listed in {@link API_KEY_NULL_FIELDS} for `command`, which may be + * `null` on the API-key side whatever the dashboard returned (a non-null value + * there must still match). A whole object going null, an element losing its + * keys, or an ID or email disappearing all fail. `ignoreKeys` drops keys at + * any depth (pagination cursors are opaque and plane-specific). + */ +export function apiKeyParityDiffs( + command: string, + session: unknown, + apiKey: unknown, + ignoreKeys: ReadonlySet = new Set(), +): string[] { + const diffs: string[] = []; + + function walk(path: string, s: unknown, k: unknown): void { + const label = path || '(entity)'; + // A documented gap may be null on the API-key side; any other value there + // must still match the dashboard exactly. + if (path && k === null && `${command}.${path}` in API_KEY_NULL_FIELDS) return; + if (Array.isArray(s) && Array.isArray(k)) { + if (s.length !== k.length) { + diffs.push(`${label}: ${s.length} item(s) on the session side, ${k.length} on the API-key side`); + return; + } + // A top-level array is a list of entities; their fields keep bare paths. + const elementPath = path ? `${path}[]` : ''; + const sorted = [sortForPairing(s), sortForPairing(k)]; + sorted[0].forEach((item, index) => walk(elementPath, item, sorted[1][index])); + return; + } + if (isPlainObject(s) && isPlainObject(k)) { + const keys = new Set([...Object.keys(s), ...Object.keys(k)]); + for (const key of keys) { + if (ignoreKeys.has(key)) continue; + const child = path ? `${path}.${key}` : key; + if (!(key in s) || !(key in k)) { + diffs.push(`${child}: present only on the ${key in s ? 'session' : 'API-key'} side`); + continue; + } + walk(child, s[key], k[key]); + } + return; + } + if (JSON.stringify(s) !== JSON.stringify(k)) { + diffs.push(`${label}: session=${JSON.stringify(s)} apiKey=${JSON.stringify(k)}`); + } + } + + walk('', session, apiKey); + return diffs; +} From 3116b0952ab12b08dc678e52f32bf3bbe8fdc8b8 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 12:25:07 -0800 Subject: [PATCH 14/32] riker: uncommitted changes from job 320 --- .scratch/job-320/pr-body.md | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/.scratch/job-320/pr-body.md b/.scratch/job-320/pr-body.md index c89cf899..a71f1eaa 100644 --- a/.scratch/job-320/pr-body.md +++ b/.scratch/job-320/pr-body.md @@ -75,10 +75,11 @@ Keys and shapes are identical on both paths. These values differ because REST ha | `org-domain`: `verificationContent`, `domainCaptureEnabled` | REST returns the verification prefix/token separately, and has no capture flag | | `portal`: `id`, `state`, `expiresAt` | REST `generate_link` returns only the URL | | `session.impersonator` id/firstName/lastName | REST names an impersonator by email only | +| `session.provider` for OAuth sign-ins | REST reports every OAuth provider as plain `oauth`, so `GoogleOAuth` etc. can't be named | | `config homepage-url set`: `applicationId` | REST never exposes the AuthKit application ID | Some fields are filled with extra REST reads rather than nulled. They are bounded per page and memoized per call: -- user `identities`: the user's memberships, with role IDs and names resolved from slugs; +- user `identities`: the user's memberships, with role IDs and names resolved from slugs. An organization's own role wins over an environment role with the same slug, as on the dashboard; - user get `authenticationFactors`; - organization names on invitations and sessions. @@ -88,25 +89,31 @@ Behavioral differences (not output fields): - **`membership list --org` pages over memberships.** Its cursors are membership IDs on the key path and user IDs on the session path. They're opaque either way, and each path accepts its own cursors. - **`feature-flag add-target|remove-target` call REST's target endpoints directly.** REST can't list a flag's targets, so there's no read-merge-write, and remove-target can't pre-check that the target exists. - **Redirect URIs and CORS have limits on REST.** - - `authkit redirect-uris set` diffs the list: it creates what's missing and deletes what's dropped. + - `authkit redirect-uris set` diffs the list. It creates what's missing **first** and only then deletes what's dropped, so a rejected URI or a failed request never leaves fewer working URIs (at worst an extra one remains). - `--default` is accepted only for a URI that is already the default, because REST can't choose one. - `authkit cors set` can't remove origins, because REST has no delete. - `--dry-run` is refused, because REST has no validate-only mode. - All of these fail before any write. -- **`session list` `provider`.** The session path emits the dashboard value raw (`Password`, not normalized; this is pre-existing and pinned in the json-contract snapshot). The key path PascalCases REST's `auth_method` to match: `password` becomes `Password`. Multi-word methods (`magic_code` becomes `MagicCode`) are a best guess at the dashboard spelling. Fixing it properly means running `enumOut` on both paths, which changes signed-in output, so it's left for a follow-up. -- **`webhook` `state`.** REST `enabled` maps to `active`, like the dashboard. REST `disabled` passes through as `disabled`; I haven't verified the dashboard's spelling for inactive endpoints. +- **Role permission changes are verified.** If the permissions replace returns 404, or the server afterwards holds anything other than the requested permissions, the command fails (`not_found` / `unexpected_result`) instead of reporting the requested list. + +Enum mapping is taken from the vendored catalog's enum types, so both paths print the same value: +- **`session list` `provider`.** The session path emits the dashboard's `SessionProvider` value raw (`Password`, not normalized; this is pre-existing and pinned in the json-contract snapshot). The key path maps REST's `auth_method` to the same values: `password` → `Password`, `magic_code` → `MagicAuth`, `sso` → `SingleSignOn`, `passkey`, `impersonation`, `cross_app_auth`, `external_auth`, `migrated_session` likewise. `oauth` and `unknown` have no single dashboard value and come back `null` (a documented gap). Running `enumOut` on both paths would be the cleaner fix, but it changes signed-in output, so it's left for a follow-up. +- **`webhook` `state`.** REST `enabled`/`disabled` map to the dashboard's `Active`/`InActive`, so both paths print `active` / `in_active`. ## Parity results -**Offline (`src/commands/api-key-parity.spec.ts`, 17 tests, all pass).** +**Offline (`src/commands/api-key-parity.spec.ts`, 24 parity tests plus 4 tests of the gate itself, all pass).** - Every list and get command runs the real handler on both paths against the same entity: - organization, user, role (env and `--org`), permission, invitation (env and `--org`), membership (`--user`, `--org`, get), session, webhook, event, feature-flag, org-domain; - - plus portal generate-link. + - plus portal generate-link; + - plus the edge cases: disabled webhooks (`InActive` vs `disabled`), every mapped session provider and an unnamed OAuth one, and an organization role shadowing an environment role's slug. - The dashboard side is fed real dashboard casing (`Verified`, `Active`, `Environment`, metadata as `{key,value}` pairs). - The REST side is fed real REST responses: snake_case keys, `verified`, `EnvironmentRole`, `enabled`, `password`, metadata as an object, plus the internal fields the shapers must drop (`stripe_customer_id`, `secret`, invitation `token`). -- Outputs must be deep-equal. The only exception is the documented null fields, which must be `null` on the key side and listed in `API_KEY_NULL_FIELDS`. A casing-only difference fails. +- The envelope and pagination must be deep-equal, and each entity must pass the shared gate below. Each test also names the gaps its fixture exercises, so it can't pass vacuously. + +**One gate, offline and live.** Both use `apiKeyParityDiffs()` from `known-gaps.ts`. Every object must have the same keys on both sides, arrays the same length, and every leaf the same value. The only exception is a leaf path listed in `API_KEY_NULL_FIELDS` (for example `user.authenticationFactors[].lastVerifiedAt`, `session.impersonator.id`), which may be `null` on the key side. An element that loses its keys, an object that goes null as a whole, a lost ID or email, or a casing-only difference all fail. -**Live (`scripts/parity-smoke.ts --api-key`, new mode).** It runs each command's list/get on this branch twice, with the session and with `WORKOS_API_KEY`, and requires identical keys and values. The only allowed differences are the `API_KEY_ACCEPTED` fields (shared with the spec through `known-gaps.ts`), where the key side must be a nulled copy. It needs no `../main`. **Not run for this PR:** the session side needs a real `workos auth login`, and this work was kept away from the real `~/.workos` and Keychain. Running it is a good pre-merge check: +**Live (`scripts/parity-smoke.ts --api-key`, new mode).** It runs each command's list/get on this branch twice, with the session and with `WORKOS_API_KEY`, and judges each entity with the same gate. It needs no `../main`. The session side is proven, not assumed: `whoami` (session-only) must succeed without a key, and every session-side command is pinned to that environment with `--environment-id`. The CLI refuses `--environment-id` whenever any API key applies, including an unclaimed profile's stored key, so the session side can't quietly run on REST and compare REST with itself. **Not run for this PR:** the session side needs a real `workos auth login`, and this work was kept away from the real `~/.workos` and Keychain. With no login it exits 2 before comparing anything (checked against a scratch HOME). Running it is a good pre-merge check: ``` workos auth login @@ -153,7 +160,7 @@ I also checked against a local fake API (`WORKOS_API_URL=http://127.0.0.1: - resource commands reach that hint only when no key is set, and setting `WORKOS_API_KEY` or passing `--api-key` now fixes them; - the account commands still need the session. - So the hint should be reworded for whichever PR merges second. -- **#270 (`fix/account-plane-forbidden-and-slim-team-query`).** It touches `command-auth.ts` (the `forbidden` copy only). It merges cleanly with this branch. +- **#270 (`fix/account-plane-forbidden-and-slim-team-query`).** It touches `command-auth.ts` (the `forbidden` copy only). It merges cleanly with this branch. This branch is cut from `origin/main`, not from #270, so #270's own changes (the slim team-environments query, sanitized server error codes, and their tests in `no-graphql-leak.spec.ts`, `dashboard-graphql.spec.ts` and `environment-target.spec.ts`) are not here. They land with #270; this PR deletes none of them. - Neither branch was touched. ## Security read: key scope @@ -204,6 +211,6 @@ I also checked against a local fake API (`WORKOS_API_URL=http://127.0.0.1: - the `resolveResourceApiKey()` precedence, against the real file-backed config store; - the updated copy. Two existing tests were renamed and updated, because their assertion that the copy says "does not accept API keys" is now the bug. - Every new or changed test name contains "with an API key". -- `bunx vitest run src/lib/command-auth.spec.ts src/commands -t "with an API key"`: 57 passed. +- `bunx vitest run src/lib/command-auth.spec.ts src/commands -t "with an API key"`: 69 passed. - Existing suites for every touched command, plus `help-json`, `catalog` (incl. `no-graphql-leak`), `environment-target` and the bin integration specs: 1,323 passed. - `bun run typecheck`: clean. From 67985812ec6871312f1bc13d320b214469889ab1 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 12:25:07 -0800 Subject: [PATCH 15/32] riker: uncommitted changes from job 320 --- .scratch/job-320/pr-body.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.scratch/job-320/pr-body.md b/.scratch/job-320/pr-body.md index a71f1eaa..a4abf435 100644 --- a/.scratch/job-320/pr-body.md +++ b/.scratch/job-320/pr-body.md @@ -160,7 +160,7 @@ I also checked against a local fake API (`WORKOS_API_URL=http://127.0.0.1: - resource commands reach that hint only when no key is set, and setting `WORKOS_API_KEY` or passing `--api-key` now fixes them; - the account commands still need the session. - So the hint should be reworded for whichever PR merges second. -- **#270 (`fix/account-plane-forbidden-and-slim-team-query`).** It touches `command-auth.ts` (the `forbidden` copy only). It merges cleanly with this branch. This branch is cut from `origin/main`, not from #270, so #270's own changes (the slim team-environments query, sanitized server error codes, and their tests in `no-graphql-leak.spec.ts`, `dashboard-graphql.spec.ts` and `environment-target.spec.ts`) are not here. They land with #270; this PR deletes none of them. +- **#270 (`fix/account-plane-forbidden-and-slim-team-query`).** It touches `command-auth.ts` (the `forbidden` copy only). It merges cleanly with this branch. This branch is cut from `origin/main`, not from #270, so #270's own changes (the slim team-environments query, sanitized server error codes, and their tests in `no-graphql-leak.spec.ts`, `dashboard-graphql.spec.ts` and `environment-target.spec.ts`) are not here. They land with #270; this PR deletes none of them. #270 also carries the slim `teamProjectsV2` query used by signed-in environment resolution, so whichever of the two PRs lands second rebases onto the other. - Neither branch was touched. ## Security read: key scope From 94ec2e8f7cd768ccb32a388bac66c777141f6632 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 12:25:08 -0800 Subject: [PATCH 16/32] test: assert each flag command makes exactly its own REST write The flag test checked outputs and the enable call but not the target writes, so a target command that printed success without calling REST would pass. Assert the exact ordered list of writes. --- src/commands/api-key-auth.spec.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/commands/api-key-auth.spec.ts b/src/commands/api-key-auth.spec.ts index 8dbaef04..38e4261d 100644 --- a/src/commands/api-key-auth.spec.ts +++ b/src/commands/api-key-auth.spec.ts @@ -670,7 +670,12 @@ describe('resource commands with an API key', () => { expect(await json(() => runFeatureFlagRemoveTarget('beta', 'user_1'))).toEqual({ removed: { flag: 'beta', targetId: 'user_1' }, }); - expect(rest.callsTo('PUT /feature-flags/beta/enable')).toHaveLength(1); + // Each command makes exactly its own write, in order, and nothing else writes. + expect(rest.calls.filter((call) => call.method !== 'GET').map((call) => `${call.method} ${call.path}`)).toEqual([ + 'PUT /feature-flags/beta/enable', + 'POST /feature-flags/beta/targets/org_1', + 'DELETE /feature-flags/beta/targets/user_1', + ]); // No project lookup on the key path: the key is the environment. expect(mockGraphqlRequest).not.toHaveBeenCalled(); }); From 79bd0ebe826a85bbbd30b98e255d400528388b11 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 12:25:08 -0800 Subject: [PATCH 17/32] test: make parity-smoke --api-key fail when it compared no entity A check now counts only when both sides returned real entities: lists whose rows each carry their ID, or a non-empty entity object. A missing envelope key no longer compares undefined with undefined and passes. A run that compared no entity at all exits 1 and says parity is unproven. --- scripts/parity-smoke.ts | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/scripts/parity-smoke.ts b/scripts/parity-smoke.ts index 6789b135..8a579ddc 100644 --- a/scripts/parity-smoke.ts +++ b/scripts/parity-smoke.ts @@ -990,6 +990,9 @@ const CURSOR_KEYS = new Set(['before', 'after', 'listMetadata', 'list_metadata', */ let sessionEnvironmentId = ''; +/** Entities actually compared field by field; a run that compared none proves nothing and fails. */ +let comparedEntities = 0; + interface ApiKeyCheck { cmd: string; label: string; @@ -1047,6 +1050,24 @@ async function checkSessionVsKey(c: ApiKeyCheck): Promise { } const sv = js[c.key]; const kv = jk[c.key]; + // A check only counts when both sides returned real entities: a list of rows + // that each carry their ID, or a single entity object. A missing envelope + // key on both sides must not compare `undefined` with `undefined` and pass. + const isEntity = (value: unknown) => isPlainObject(value) && Object.keys(value).length > 0; + if (c.idKey) { + if (!Array.isArray(sv) || !Array.isArray(kv)) { + push('API-KEY', c.label, 'FAIL', `no "${c.key}" list on the ${Array.isArray(sv) ? 'API-key' : 'session'} side`); + return js; + } + const missingId = [...sv, ...kv].some((row: any) => !isEntity(row) || row[c.idKey!] == null); + if (missingId) { + push('API-KEY', c.label, 'FAIL', `a "${c.key}" row has no ${c.idKey}, so rows can't be paired`); + return js; + } + } else if (!isEntity(sv) || !isEntity(kv)) { + push('API-KEY', c.label, 'FAIL', `no "${c.key}" entity on the ${isEntity(sv) ? 'API-key' : 'session'} side`); + return js; + } const diffs: string[] = []; let rows = 1; if (Array.isArray(sv) && Array.isArray(kv) && c.idKey) { @@ -1066,6 +1087,7 @@ async function checkSessionVsKey(c: ApiKeyCheck): Promise { } for (const d of diffs) notes.push(`${C.red}FAIL${C.reset} ${c.label} ${d}`); const empty = Array.isArray(sv) && sv.length === 0; + if (!diffs.length && !empty) comparedEntities += rows; push( 'API-KEY', c.label, @@ -1231,10 +1253,16 @@ async function runApiKeyMode(): Promise { console.log(` ${C.cyan}${field}${C.reset} ${reason}`); const failed = rows.filter((r) => r.status === 'FAIL').length; const auth = rows.filter((r) => r.status === 'AUTH').length; + if (comparedEntities === 0) { + console.log( + `\n${C.red}no entity was compared on both paths, so parity is unproven; seed the environment (organizations, users) and re-run${C.reset}`, + ); + } + const blocked = failed > 0 || auth > 0 || comparedEntities === 0; console.log( - `\n${failed ? C.red : C.green}${rows.filter((r) => r.status === 'PASS').length} pass, ${failed} fail, ${auth} auth${C.reset}`, + `\n${blocked ? C.red : C.green}${rows.filter((r) => r.status === 'PASS').length} pass, ${failed} fail, ${auth} auth, ${comparedEntities} entities compared${C.reset}`, ); - process.exit(failed || auth ? 1 : 0); + process.exit(blocked ? 1 : 0); } if (API_KEY_MODE) await runApiKeyMode(); From 21c19a4e1647b0f2049b18e2f28a24e5f0733380 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 12:25:09 -0800 Subject: [PATCH 18/32] riker: uncommitted changes from job 320 --- .scratch/job-320/pr-body.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.scratch/job-320/pr-body.md b/.scratch/job-320/pr-body.md index a4abf435..fb7539fc 100644 --- a/.scratch/job-320/pr-body.md +++ b/.scratch/job-320/pr-body.md @@ -113,7 +113,7 @@ Enum mapping is taken from the vendored catalog's enum types, so both paths prin **One gate, offline and live.** Both use `apiKeyParityDiffs()` from `known-gaps.ts`. Every object must have the same keys on both sides, arrays the same length, and every leaf the same value. The only exception is a leaf path listed in `API_KEY_NULL_FIELDS` (for example `user.authenticationFactors[].lastVerifiedAt`, `session.impersonator.id`), which may be `null` on the key side. An element that loses its keys, an object that goes null as a whole, a lost ID or email, or a casing-only difference all fail. -**Live (`scripts/parity-smoke.ts --api-key`, new mode).** It runs each command's list/get on this branch twice, with the session and with `WORKOS_API_KEY`, and judges each entity with the same gate. It needs no `../main`. The session side is proven, not assumed: `whoami` (session-only) must succeed without a key, and every session-side command is pinned to that environment with `--environment-id`. The CLI refuses `--environment-id` whenever any API key applies, including an unclaimed profile's stored key, so the session side can't quietly run on REST and compare REST with itself. **Not run for this PR:** the session side needs a real `workos auth login`, and this work was kept away from the real `~/.workos` and Keychain. With no login it exits 2 before comparing anything (checked against a scratch HOME). Running it is a good pre-merge check: +**Live (`scripts/parity-smoke.ts --api-key`, new mode).** It runs each command's list/get on this branch twice, with the session and with `WORKOS_API_KEY`, and judges each entity with the same gate. It needs no `../main`. A check counts only when both sides returned real entities (rows that each carry their ID, or a non-empty entity), and a run that compared no entity at all exits 1. The session side is proven, not assumed: `whoami` (session-only) must succeed without a key, and every session-side command is pinned to that environment with `--environment-id`. The CLI refuses `--environment-id` whenever any API key applies, including an unclaimed profile's stored key, so the session side can't quietly run on REST and compare REST with itself. **Not run for this PR:** the session side needs a real `workos auth login`, and this work was kept away from the real `~/.workos` and Keychain. With no login it exits 2 before comparing anything (checked against a scratch HOME). Running it is a good pre-merge check: ``` workos auth login From 9a38951421401720e6be5e645bf2d2824778143b Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 12:25:09 -0800 Subject: [PATCH 19/32] fix: read every page and every membership status on the API-key path - Full-list reads (permissions, a user's memberships, redirect URIs, CORS origins) now request order=desc. Endpoints that default to normal walk toward newer records on after, so past 100 permissions the old loop stopped at the first page and get/update/delete could report not_found. - membership delete removes the membership ID the command just resolved instead of searching again; the fallback search, and membership/identity listings, pass statuses=active,inactive,pending rather than relying on REST's default status filter, so a deactivated membership can be listed and deleted. --- src/commands/api-key-auth.spec.ts | 72 +++++++++++++++++++++-- src/lib/api-key-operations/context.ts | 10 +++- src/lib/api-key-operations/lookups.ts | 12 +++- src/lib/api-key-operations/memberships.ts | 53 +++++++++++++---- 4 files changed, 126 insertions(+), 21 deletions(-) diff --git a/src/commands/api-key-auth.spec.ts b/src/commands/api-key-auth.spec.ts index 38e4261d..c4f4fea9 100644 --- a/src/commands/api-key-auth.spec.ts +++ b/src/commands/api-key-auth.spec.ts @@ -48,8 +48,9 @@ const { LEAK_PATTERN } = await import('../catalog/curation.js'); const { runOrgList, runOrgGet, runOrgCreate, runOrgUpdate, runOrgDelete } = await import('./organization.js'); const { runUserUpdate, runUserDelete } = await import('./user.js'); const { runRoleCreate, runRoleUpdate, runRoleSetPermissions, runRoleDelete } = await import('./role.js'); -const { runPermissionCreate, runPermissionUpdate, runPermissionDelete } = await import('./permission.js'); -const { runMembershipCreate, runMembershipUpdate, runMembershipDelete, runMembershipDeactivate } = +const { runPermissionList, runPermissionGet, runPermissionCreate, runPermissionUpdate, runPermissionDelete } = + await import('./permission.js'); +const { runMembershipList, runMembershipCreate, runMembershipUpdate, runMembershipDelete, runMembershipDeactivate } = await import('./membership.js'); const { runInvitationSend, runInvitationRevoke } = await import('./invitation.js'); const { runSessionRevoke } = await import('./session.js'); @@ -599,14 +600,73 @@ describe('resource commands with an API key', () => { const deleted = await json(() => runMembershipDelete('om_1', { yes: true })); const deactivated = await json(() => runMembershipDeactivate('om_1', { yes: true })); - expect(rest.callsTo('GET /user_management/organization_memberships')[0].query).toMatchObject({ - organization_id: 'org_1', - user_id: 'user_1', - }); + // The removal deletes the membership the command just resolved, by ID. + expect(rest.callsTo('DELETE /user_management/organization_memberships/om_1')).toHaveLength(1); expect(deleted).toEqual({ deleted: 'om_1' }); expect(deactivated).toEqual({ deactivated: 'om_1' }); }); + it('deletes a deactivated membership by the ID it resolved with an API key', async () => { + const inactive = { ...REST_MEMBERSHIP, id: 'om_inactive', user_id: 'user_2', status: 'inactive' }; + rest.respond({ + 'GET /user_management/organization_memberships/om_inactive': inactive, + // Like REST's default status filter, a search without statuses finds no inactive membership. + 'GET /user_management/organization_memberships': (call: { query: Record }) => + restList(call.query.statuses?.includes('inactive') ? [inactive] : []), + 'DELETE /user_management/organization_memberships/om_inactive': { status: 204 }, + }); + + const deleted = await json(() => runMembershipDelete('om_inactive', { yes: true })); + + expect(deleted).toEqual({ deleted: 'om_inactive' }); + expect(rest.callsTo('DELETE /user_management/organization_memberships/om_inactive')).toHaveLength(1); + }); + + it('lists memberships of every status, by user and by organization, with an API key', async () => { + rest.respond({ + 'GET /organizations/org_1': REST_ORG, + 'GET /user_management/organization_memberships': restList([{ ...REST_MEMBERSHIP, status: 'inactive' }]), + }); + + const byUser = await json(() => runMembershipList({ user: 'user_1' })); + const byOrg = await json(() => runMembershipList({ org: 'org_1' })); + + const searches = rest.callsTo('GET /user_management/organization_memberships'); + expect(searches).toHaveLength(2); + for (const search of searches) expect(search.query.statuses).toBe('active,inactive,pending'); + expect(byUser).toMatchObject({ memberships: [{ id: 'om_1', state: 'inactive' }] }); + expect(byOrg).toMatchObject({ memberships: [{ id: 'om_1', state: 'inactive' }] }); + }); + + it('reads every page of permissions in an explicit order with an API key', async () => { + const page = (from: number, count: number) => + Array.from({ length: count }, (_, i) => ({ + ...REST_PERMISSION, + id: `perm_${from + i}`, + slug: `p:${from + i}`, + name: `Permission ${from + i}`, + })); + rest.respond({ + // Only an explicit order makes `after` the next page; without one the second page is never reached. + 'GET /authorization/permissions': (call: { query: Record }) => { + if (call.query.order !== 'desc') return restList(page(0, 100), null); + return call.query.after === 'perm_99' ? restList(page(100, 5)) : restList(page(0, 100), 'perm_99'); + }, + }); + + const listed = (await json(() => runPermissionList({}))) as { permissions: unknown[] }; + const got = await json(() => runPermissionGet('p:104')); + + expect(listed.permissions).toHaveLength(105); + expect(got).toMatchObject({ permission: { slug: 'p:104' } }); + expect(rest.callsTo('GET /authorization/permissions').map((call) => call.query.after ?? null)).toEqual([ + null, + 'perm_99', + null, + 'perm_99', + ]); + }); + it('revokes invitations and sessions with an API key', async () => { rest.respond({ 'POST /user_management/invitations/invitation_1/revoke': { diff --git a/src/lib/api-key-operations/context.ts b/src/lib/api-key-operations/context.ts index 702cd8e2..6cb3c69b 100644 --- a/src/lib/api-key-operations/context.ts +++ b/src/lib/api-key-operations/context.ts @@ -77,7 +77,13 @@ const FULL_LIST_MAX_PAGES = 50; /** * Read every page of a REST list. Used where the dashboard operation returns a - * complete, unpaginated list (permissions, an organization's memberships). + * complete, unpaginated list (permissions, a user's memberships, redirect URIs, + * CORS origins). + * + * The order is always explicit: several endpoints default to `normal`, where + * `after` walks toward NEWER records, so following `after` from the first page + * would stop early and silently drop everything older. Under `desc`, `after` + * is the next (older) page, which is what the loop follows. */ export async function listAll( ctx: ApiKeyContext, @@ -90,7 +96,7 @@ export async function listAll( const result = await ctx.request | { data: T[]; list_metadata?: undefined }>({ method: 'GET', path, - params: { ...params, limit: FULL_LIST_PAGE_SIZE, ...(after ? { after } : {}) }, + params: { order: 'desc', ...params, limit: FULL_LIST_PAGE_SIZE, ...(after ? { after } : {}) }, }); items.push(...(result?.data ?? [])); after = result?.list_metadata?.after ?? undefined; diff --git a/src/lib/api-key-operations/lookups.ts b/src/lib/api-key-operations/lookups.ts index 404ffbea..e98c0a7b 100644 --- a/src/lib/api-key-operations/lookups.ts +++ b/src/lib/api-key-operations/lookups.ts @@ -127,6 +127,16 @@ export interface RestMembership { updated_at?: string; } +/** + * Every membership status. Membership listings pass it explicitly rather than + * relying on REST's default status filter, so inactive and pending + * memberships show up as they do on the dashboard. + */ +export const ALL_MEMBERSHIP_STATUSES = 'active,inactive,pending'; + export function membershipsForUser(ctx: ApiKeyContext, userId: string): Promise { - return listAll(ctx, '/user_management/organization_memberships', { user_id: userId }); + return listAll(ctx, '/user_management/organization_memberships', { + user_id: userId, + statuses: ALL_MEMBERSHIP_STATUSES, + }); } diff --git a/src/lib/api-key-operations/memberships.ts b/src/lib/api-key-operations/memberships.ts index 06776547..7fbd443a 100644 --- a/src/lib/api-key-operations/memberships.ts +++ b/src/lib/api-key-operations/memberships.ts @@ -18,7 +18,13 @@ import { restOrder, str, } from './context.js'; -import { findRole, membershipsForUser, organizationName, type RestMembership } from './lookups.js'; +import { + ALL_MEMBERSHIP_STATUSES, + findRole, + membershipsForUser, + organizationName, + type RestMembership, +} from './lookups.js'; import { exitWithError } from '../../utils/output.js'; interface RestInvitation { @@ -45,10 +51,22 @@ function membershipNode(membership: RestMembership) { }; } -function readMembership(ctx: ApiKeyContext, id: string): Promise { - return orNull( +/** + * Membership IDs this invocation has already resolved, keyed by organization + + * user. `membership delete ` reads the membership first (the dashboard + * removal is keyed by organization + user), so the removal can delete that + * exact ID instead of searching again. + */ +const resolvedMembershipIds = new Map(); +const membershipKey = (organizationId: unknown, userId: unknown) => `${String(organizationId)}\u0000${String(userId)}`; + +async function readMembership(ctx: ApiKeyContext, id: string): Promise { + const membership = await orNull( ctx.request({ method: 'GET', path: `/user_management/organization_memberships/${encode(id)}` }), ); + if (membership) + resolvedMembershipIds.set(membershipKey(membership.organization_id, membership.user_id), membership.id); + return membership; } async function organizationExists(ctx: ApiKeyContext, organizationId: string): Promise { @@ -117,6 +135,7 @@ export const membershipOperations: Record = { path: '/user_management/organization_memberships', params: { organization_id: organizationId, + statuses: ALL_MEMBERSHIP_STATUSES, limit: num(variables.limit), before: str(variables.before), after: str(variables.after), @@ -196,18 +215,28 @@ export const membershipOperations: Record = { async removeMemberFromOrganization(variables, ctx) { const input = (variables.input ?? {}) as { organizationId?: string; userlandUserId?: string }; - // REST deletes by membership ID; find the pair's membership first. - const page = await ctx.request>({ - method: 'GET', - path: '/user_management/organization_memberships', - params: { organization_id: input.organizationId, user_id: input.userlandUserId, limit: 1 }, - }); - const membership = page?.data?.[0]; + // REST deletes by membership ID. Use the one this invocation already + // resolved; otherwise search the pair across every status (an inactive + // membership must still be deletable). + let membershipId = resolvedMembershipIds.get(membershipKey(input.organizationId, input.userlandUserId)); + if (!membershipId) { + const page = await ctx.request>({ + method: 'GET', + path: '/user_management/organization_memberships', + params: { + organization_id: input.organizationId, + user_id: input.userlandUserId, + statuses: ALL_MEMBERSHIP_STATUSES, + limit: 1, + }, + }); + membershipId = page?.data?.[0]?.id; + } const removed = - membership && + membershipId && (await orNull( ctx - .request({ method: 'DELETE', path: `/user_management/organization_memberships/${encode(membership.id)}` }) + .request({ method: 'DELETE', path: `/user_management/organization_memberships/${encode(membershipId)}` }) .then(() => true), )); return { From c81eba79c0ea906bdf171cc9e40494e974b4d146 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 12:25:10 -0800 Subject: [PATCH 20/32] riker: uncommitted changes from job 320 --- .scratch/job-320/pr-body.md | 1 + 1 file changed, 1 insertion(+) diff --git a/.scratch/job-320/pr-body.md b/.scratch/job-320/pr-body.md index fb7539fc..573e611f 100644 --- a/.scratch/job-320/pr-body.md +++ b/.scratch/job-320/pr-body.md @@ -86,6 +86,7 @@ Some fields are filled with extra REST reads rather than nulled. They are bounde Behavioral differences (not output fields): - **Search filters are exact matches.** `organization list --domain`, `user list --email` and `invitation list --email` use REST's exact-match filters (domain, email). The dashboard does a search. - **New domains start pending.** `org-domain create` on REST creates the domain `pending` (it needs DNS verification). The dashboard adds it verified. The output reports the real state. +- **Full lists and statuses are explicit.** Reads that must return a complete list (permissions, a user's memberships, redirect URIs, CORS origins) page with `order=desc`, so following `after` never stops early. Membership listings and `membership delete` include every status (`active,inactive,pending`), so a deactivated membership is listed and can be deleted, as on the dashboard. - **`membership list --org` pages over memberships.** Its cursors are membership IDs on the key path and user IDs on the session path. They're opaque either way, and each path accepts its own cursors. - **`feature-flag add-target|remove-target` call REST's target endpoints directly.** REST can't list a flag's targets, so there's no read-merge-write, and remove-target can't pre-check that the target exists. - **Redirect URIs and CORS have limits on REST.** From 422842ced96b67ddb2c44524ae92b1ab9957cd7a Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 12:25:10 -0800 Subject: [PATCH 21/32] fix: keep `after` as the next page on every API-key list Several REST lists default to the normal order, where the older-page cursor comes back in before and after walks toward newer records. The redirect URI read relied on after to detect more than one page, so config redirect add could merge over a truncated list and the setter would delete the URIs it never saw. Every key-path list now sends an explicit order (the user's --order, else desc: same newest-first rows), and the redirect read defaults to the dashboard's 100. Tests: config redirect add refuses past one page with no writes; every paginated list sends an order; config cors add keeps an existing origin and posts only the new one. --- src/commands/api-key-auth.spec.ts | 87 +++++++++++++++++++++-- src/lib/api-key-operations/app-config.ts | 12 +++- src/lib/api-key-operations/context.ts | 12 +++- src/lib/api-key-operations/memberships.ts | 1 + src/lib/api-key-operations/platform.ts | 7 +- src/lib/api-key-operations/users.ts | 7 +- 6 files changed, 113 insertions(+), 13 deletions(-) diff --git a/src/commands/api-key-auth.spec.ts b/src/commands/api-key-auth.spec.ts index c4f4fea9..21bc1c52 100644 --- a/src/commands/api-key-auth.spec.ts +++ b/src/commands/api-key-auth.spec.ts @@ -52,13 +52,15 @@ const { runPermissionList, runPermissionGet, runPermissionCreate, runPermissionU await import('./permission.js'); const { runMembershipList, runMembershipCreate, runMembershipUpdate, runMembershipDelete, runMembershipDeactivate } = await import('./membership.js'); -const { runInvitationSend, runInvitationRevoke } = await import('./invitation.js'); -const { runSessionRevoke } = await import('./session.js'); -const { runWebhookCreate, runWebhookDelete } = await import('./webhook.js'); -const { runFeatureFlagEnable, runFeatureFlagAddTarget, runFeatureFlagRemoveTarget } = await import('./feature-flag.js'); +const { runInvitationList, runInvitationSend, runInvitationRevoke } = await import('./invitation.js'); +const { runSessionList, runSessionRevoke } = await import('./session.js'); +const { runWebhookList, runWebhookCreate, runWebhookDelete } = await import('./webhook.js'); +const { runFeatureFlagList, runFeatureFlagEnable, runFeatureFlagAddTarget, runFeatureFlagRemoveTarget } = + await import('./feature-flag.js'); const { runOrgDomainCreate, runOrgDomainVerify, runOrgDomainDelete } = await import('./org-domain.js'); const { runConfigRedirectAdd, runConfigCorsAdd, runConfigHomepageUrlSet } = await import('./config.js'); -const { runAuthkitCorsSet, runAuthkitRedirectUrisSet, runAuthkitLogoutUrisList } = await import('./authkit.js'); +const { runAuthkitCorsSet, runAuthkitRedirectUrisSet, runAuthkitRedirectUrisList, runAuthkitLogoutUrisList } = + await import('./authkit.js'); const { runBrandingGet } = await import('./branding.js'); const { runEnvironmentRename } = await import('./environment.js'); const { runTeamMembers } = await import('./team.js'); @@ -817,6 +819,7 @@ describe('resource commands with an API key', () => { it('adds redirect URIs and CORS origins without rewriting the rest with an API key', async () => { const existing = { object: 'redirect_uri', id: 'ru_1', uri: 'https://a.example.com/cb', default: true }; let created = false; + let origins = [{ object: 'cors_origin', id: 'cors_1', origin: 'https://a.example.com' }]; rest.respond({ 'GET /user_management/redirect_uris': () => restList( @@ -828,8 +831,13 @@ describe('resource commands with an API key', () => { created = true; return { object: 'redirect_uri', id: 'ru_2', uri: 'https://b.example.com/cb', default: false }; }, - 'GET /user_management/cors_origins': restList([]), - 'POST /user_management/cors_origins': { object: 'cors_origin', id: 'cors_1', origin: 'https://b.example.com' }, + 'GET /user_management/cors_origins': () => restList(origins), + 'POST /user_management/cors_origins': (call: { body: unknown }) => { + const { origin } = call.body as { origin: string }; + const created = { object: 'cors_origin', id: `cors_${origins.length + 1}`, origin }; + origins = [...origins, created]; + return created; + }, }); expect(await json(() => runConfigRedirectAdd('https://b.example.com/cb'))).toEqual({ @@ -844,6 +852,71 @@ describe('resource commands with an API key', () => { { uri: 'https://b.example.com/cb' }, ]); expect(rest.callsTo('DELETE /user_management/redirect_uris/ru_1')).toHaveLength(0); + // Only the new origin is posted; the existing one is kept, not re-sent or dropped. + expect(rest.callsTo('POST /user_management/cors_origins').map((c) => c.body)).toEqual([ + { origin: 'https://b.example.com' }, + ]); + expect(origins.map((origin) => origin.origin)).toEqual(['https://a.example.com', 'https://b.example.com']); + // Adding an origin that already exists writes nothing. + expect(await json(() => runConfigCorsAdd('https://a.example.com'))).toEqual({ + origin: 'https://a.example.com', + alreadyExists: true, + }); + expect(rest.callsTo('POST /user_management/cors_origins')).toHaveLength(1); + }); + + it('refuses to add a redirect URI over a list longer than one page with an API key', async () => { + const uris = Array.from({ length: 100 }, (_, i) => ({ + object: 'redirect_uri', + id: `ru_${i}`, + uri: `https://app.example.com/cb/${i}`, + default: i === 0, + })); + rest.respond({ + // REST's default `normal` order puts the older-page cursor in `before`; only an + // explicit `desc` puts it in `after`, which is what the merge guard checks. + 'GET /user_management/redirect_uris': (call: { query: Record }) => + call.query.order === 'desc' ? restList(uris, 'ru_99') : restList(uris, null, 'ru_99'), + 'POST /user_management/redirect_uris': { object: 'redirect_uri', id: 'ru_new', uri: 'x', default: false }, + }); + + const error = await expectExit(() => runConfigRedirectAdd('https://app.example.com/cb/new')); + + expect(error.code).toBe('too_many_uris'); + expect(rest.callsTo('GET /user_management/redirect_uris')[0].query).toMatchObject({ + limit: '100', + order: 'desc', + }); + expect(rest.calls.filter((call) => call.method !== 'GET')).toHaveLength(0); + }); + + it('asks every paginated list for an explicit order so after is the next page with an API key', async () => { + rest.respond({ + 'GET /organizations': restList([]), + 'GET /user_management/invitations': restList([]), + 'GET /webhook_endpoints': restList([]), + 'GET /user_management/users/user_1/sessions': restList([]), + 'GET /feature-flags': restList([]), + 'GET /user_management/redirect_uris': restList([]), + }); + + await json(() => runOrgList({})); + await json(() => runInvitationList({})); + await json(() => runWebhookList({})); + await json(() => runSessionList('user_1', {})); + await json(() => runFeatureFlagList({})); + await json(() => runAuthkitRedirectUrisList({})); + await json(() => runOrgList({ order: 'asc' })); + + expect(rest.calls.map((call) => `${call.path} ${call.query.order}`)).toEqual([ + '/organizations desc', + '/user_management/invitations desc', + '/webhook_endpoints desc', + '/user_management/users/user_1/sessions desc', + '/feature-flags desc', + '/user_management/redirect_uris desc', + '/organizations asc', + ]); }); it('sets the homepage URL with a null applicationId with an API key', async () => { diff --git a/src/lib/api-key-operations/app-config.ts b/src/lib/api-key-operations/app-config.ts index 12f883dd..7cede6cf 100644 --- a/src/lib/api-key-operations/app-config.ts +++ b/src/lib/api-key-operations/app-config.ts @@ -19,6 +19,7 @@ import { listAll, listEnvelope, num, + restOrder, str, } from './context.js'; import type { WorkOSListResponse } from '../workos-api.js'; @@ -50,10 +51,19 @@ function corsOrigins(ctx: ApiKeyContext): Promise { export const appConfigOperations: Record = { async redirectUris(variables, ctx) { + // The dashboard read defaults to 100 URIs. The order must be explicit so + // `after` is set whenever more URIs exist: `config redirect add` relies on + // it to refuse a merge over a truncated list, which would otherwise delete + // the URIs it never saw. const page = await ctx.request>({ method: 'GET', path: '/user_management/redirect_uris', - params: { limit: num(variables.limit), before: str(variables.before), after: str(variables.after) }, + params: { + limit: num(variables.limit) ?? 100, + before: str(variables.before), + after: str(variables.after), + order: restOrder(), + }, }); return { redirectUris: listEnvelope((page?.data ?? []).map(redirectUriNode), page?.list_metadata) }; }, diff --git a/src/lib/api-key-operations/context.ts b/src/lib/api-key-operations/context.ts index 6cb3c69b..d21a28e1 100644 --- a/src/lib/api-key-operations/context.ts +++ b/src/lib/api-key-operations/context.ts @@ -105,9 +105,15 @@ export async function listAll( return items; } -/** `Asc`/`Desc` (the dashboard pagination enum) → REST `asc`/`desc`. */ -export function restOrder(order: unknown): string | undefined { - return typeof order === 'string' && order !== '' ? order.toLowerCase() : undefined; +/** + * `Asc`/`Desc` (the dashboard pagination enum) → REST `asc`/`desc`, and `desc` + * when no order was asked for. Always explicit: several REST lists default to + * `normal` (newest first, but `after` walks toward NEWER records), and every + * list on this path must keep the CLI's contract that `after` is the next + * page. `desc` returns the same newest-first rows as `normal`. + */ +export function restOrder(order?: unknown): string { + return typeof order === 'string' && order !== '' ? order.toLowerCase() : 'desc'; } export function str(value: unknown): string | undefined { diff --git a/src/lib/api-key-operations/memberships.ts b/src/lib/api-key-operations/memberships.ts index 7fbd443a..c100f8e8 100644 --- a/src/lib/api-key-operations/memberships.ts +++ b/src/lib/api-key-operations/memberships.ts @@ -103,6 +103,7 @@ function listInvitations(ctx: ApiKeyContext, variables: Record, // `--email` is the CLI's only search input; REST filters by exact email. email: str(variables.search), organization_id: organizationId, + order: restOrder(), }, }); } diff --git a/src/lib/api-key-operations/platform.ts b/src/lib/api-key-operations/platform.ts index 777b3259..817bd1e0 100644 --- a/src/lib/api-key-operations/platform.ts +++ b/src/lib/api-key-operations/platform.ts @@ -105,7 +105,12 @@ export const platformOperations: Record = { const page = await ctx.request>({ method: 'GET', path: '/webhook_endpoints', - params: { limit: num(variables.limit), before: str(variables.before), after: str(variables.after) }, + params: { + limit: num(variables.limit), + before: str(variables.before), + after: str(variables.after), + order: restOrder(), + }, }); const endpoints = (page?.data ?? []).map((endpoint) => ({ id: endpoint.id, diff --git a/src/lib/api-key-operations/users.ts b/src/lib/api-key-operations/users.ts index 7c458522..d328efeb 100644 --- a/src/lib/api-key-operations/users.ts +++ b/src/lib/api-key-operations/users.ts @@ -247,7 +247,12 @@ export const userOperations: Record = { ctx.request>({ method: 'GET', path: `/user_management/users/${encode(userId)}/sessions`, - params: { limit: num(variables.limit), before: str(variables.before), after: str(variables.after) }, + params: { + limit: num(variables.limit), + before: str(variables.before), + after: str(variables.after), + order: restOrder(), + }, }), ); if (!page) return { userlandUser: null }; From 3ce1b1a93d140bcfe45537140120d0144c62ef94 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 12:25:11 -0800 Subject: [PATCH 22/32] riker: uncommitted changes from job 320 --- .scratch/job-320/pr-body.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.scratch/job-320/pr-body.md b/.scratch/job-320/pr-body.md index 573e611f..905bc07b 100644 --- a/.scratch/job-320/pr-body.md +++ b/.scratch/job-320/pr-body.md @@ -86,7 +86,7 @@ Some fields are filled with extra REST reads rather than nulled. They are bounde Behavioral differences (not output fields): - **Search filters are exact matches.** `organization list --domain`, `user list --email` and `invitation list --email` use REST's exact-match filters (domain, email). The dashboard does a search. - **New domains start pending.** `org-domain create` on REST creates the domain `pending` (it needs DNS verification). The dashboard adds it verified. The output reports the real state. -- **Full lists and statuses are explicit.** Reads that must return a complete list (permissions, a user's memberships, redirect URIs, CORS origins) page with `order=desc`, so following `after` never stops early. Membership listings and `membership delete` include every status (`active,inactive,pending`), so a deactivated membership is listed and can be deleted, as on the dashboard. +- **Order, full lists and statuses are explicit.** Every key-path list sends an order (your `--order`, else `desc`, which returns the same newest-first rows as REST's `normal` default), so `after` is always the next page. Reads that must return a complete list (permissions, a user's memberships, redirect URIs, CORS origins) follow it to the end, and `config redirect add` still refuses to merge over more than one page of URIs. Membership listings and `membership delete` include every status (`active,inactive,pending`), so a deactivated membership is listed and can be deleted, as on the dashboard. - **`membership list --org` pages over memberships.** Its cursors are membership IDs on the key path and user IDs on the session path. They're opaque either way, and each path accepts its own cursors. - **`feature-flag add-target|remove-target` call REST's target endpoints directly.** REST can't list a flag's targets, so there's no read-merge-write, and remove-target can't pre-check that the target exists. - **Redirect URIs and CORS have limits on REST.** From 4a5d8a4a12c83c1dcdf3eefbd9e8c9fb9f7c3d5a Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 12:25:11 -0800 Subject: [PATCH 23/32] fix: keep the DNS challenge when domains are added or verified with an API key The key path mapped every REST domain's verificationContent to null, dropping the challenge REST returns as verification_prefix and verification_token. Build it the way the dashboard does (OrganizationDomain.verificationContent: `=`, prefix defaulting to verification_token, null without a token), so org list/get, org-domain get, create and verify carry it in the same field. Create includes it because REST adds domains pending; human create output now prints the record when there is one. verificationContent is no longer a documented gap. subdomain is listed instead: REST doesn't return it and the dashboard derives it with a public-suffix parser this CLI doesn't ship. Tests (fail on the old mapping): org-domain get/verify parity against the dashboard's challenge, the default-prefix case, and create/verify output. --- src/commands/api-key-auth.spec.ts | 15 +++++- src/commands/api-key-parity.spec.ts | 54 ++++++++++++++++++++- src/commands/org-domain.ts | 4 ++ src/lib/api-key-operations/known-gaps.ts | 4 +- src/lib/api-key-operations/organizations.ts | 34 +++++++++++-- 5 files changed, 100 insertions(+), 11 deletions(-) diff --git a/src/commands/api-key-auth.spec.ts b/src/commands/api-key-auth.spec.ts index 21bc1c52..2c0ef3a3 100644 --- a/src/commands/api-key-auth.spec.ts +++ b/src/commands/api-key-auth.spec.ts @@ -750,6 +750,8 @@ describe('resource commands with an API key', () => { domain: 'bar.com', state: 'pending', verification_strategy: 'dns', + verification_prefix: 'workos-verify', + verification_token: 'tok_bar', }; rest.respond({ 'POST /organization_domains': domain, @@ -765,10 +767,19 @@ describe('resource commands with an API key', () => { organization_id: 'org_1', domain: 'bar.com', }); + // REST adds the domain pending, so the DNS challenge needed to verify it must reach the output. expect(created).toMatchObject({ - domain: { id: 'dom_2', state: 'pending', verificationStrategy: 'dns', organizationId: 'org_1' }, + domain: { + id: 'dom_2', + state: 'pending', + verificationStrategy: 'dns', + verificationContent: 'workos-verify=tok_bar', + organizationId: 'org_1', + }, + }); + expect(verified).toMatchObject({ + domain: { id: 'dom_2', domain: 'bar.com', verificationContent: 'workos-verify=tok_bar' }, }); - expect(verified).toMatchObject({ domain: { id: 'dom_2', domain: 'bar.com' } }); expect(deleted).toEqual({ deleted: 'dom_2' }); }); diff --git a/src/commands/api-key-parity.spec.ts b/src/commands/api-key-parity.spec.ts index 059191da..ff1fcd96 100644 --- a/src/commands/api-key-parity.spec.ts +++ b/src/commands/api-key-parity.spec.ts @@ -57,7 +57,7 @@ const { runSessionList } = await import('./session.js'); const { runWebhookList } = await import('./webhook.js'); const { runEventList } = await import('./event.js'); const { runFeatureFlagList, runFeatureFlagGet } = await import('./feature-flag.js'); -const { runOrgDomainGet } = await import('./org-domain.js'); +const { runOrgDomainGet, runOrgDomainVerify } = await import('./org-domain.js'); const { runPortalGenerateLink } = await import('./portal.js'); const rest = createRestMock(); @@ -864,7 +864,57 @@ describe('resource command --json parity, session vs API key', () => { () => runOrgDomainGet('dom_1', {}), ); const apiKey = await viaApiKey({ 'GET /organizations': restList([REST_ORG]) }, () => runOrgDomainGet('dom_1', {})); - expectParity('org-domain', session, apiKey, ['verificationContent', 'domainCaptureEnabled']); + // The DNS challenge (`workos-verify=abc123`) comes through; only the capture flag has no REST source. + expectParity('org-domain', session, apiKey, ['domainCaptureEnabled']); + expect(apiKey).toMatchObject({ + domain: { verificationContent: 'workos-verify=abc123', verificationStrategy: 'dns' }, + }); + }); + + it('org-domain verify returns the dashboard’s DNS challenge with an API key', async () => { + const pendingDomain = { ...GQL_DOMAIN, state: 'Pending' }; + const restPending = { ...REST_ORG.domains[0], state: 'pending' }; + const session = await viaSession( + () => ({ restartOrganizationDomainVerification: pendingDomain }), + () => runOrgDomainVerify('dom_1', {}), + ); + const apiKey = await viaApiKey({ 'POST /organization_domains/dom_1/verify': restPending }, () => + runOrgDomainVerify('dom_1', {}), + ); + expectParity('org-domain', session, apiKey, ['domainCaptureEnabled']); + expect(apiKey).toEqual({ + domain: { + id: 'dom_1', + domain: 'foo.com', + state: 'pending', + organizationId: null, + subdomain: null, + verificationStrategy: 'dns', + verificationContent: 'workos-verify=abc123', + domainCaptureEnabled: null, + }, + }); + }); + + it('org-domain verify uses the dashboard’s default record prefix when REST has none, with an API key', async () => { + const session = await viaSession( + () => ({ + restartOrganizationDomainVerification: { ...GQL_DOMAIN, verificationContent: 'verification_token=tok_9' }, + }), + () => runOrgDomainVerify('dom_1', {}), + ); + const apiKey = await viaApiKey( + { + 'POST /organization_domains/dom_1/verify': { + ...REST_ORG.domains[0], + verification_prefix: null, + verification_token: 'tok_9', + }, + }, + () => runOrgDomainVerify('dom_1', {}), + ); + expectParity('org-domain', session, apiKey, ['domainCaptureEnabled']); + expect(apiKey).toMatchObject({ domain: { verificationContent: 'verification_token=tok_9' } }); }); it('portal generate-link matches with an API key', async () => { diff --git a/src/commands/org-domain.ts b/src/commands/org-domain.ts index ec21b67d..d49f09d3 100644 --- a/src/commands/org-domain.ts +++ b/src/commands/org-domain.ts @@ -166,6 +166,10 @@ export async function runOrgDomainCreate(domain: string, options: OrgDomainCreat outputSuccess( `Added domain ${chalk.bold(domain)} to organization ${chalk.bold(options.org)} (state: ${added.state ?? 'unknown'})`, ); + // Only an API-key add returns a challenge (the domain starts pending there). + if (added.verificationContent) { + console.log(chalk.dim(`Verification record: ${added.verificationContent}`)); + } } export interface OrgDomainVerifyOptions { diff --git a/src/lib/api-key-operations/known-gaps.ts b/src/lib/api-key-operations/known-gaps.ts index b72312c0..e0710f35 100644 --- a/src/lib/api-key-operations/known-gaps.ts +++ b/src/lib/api-key-operations/known-gaps.ts @@ -21,8 +21,8 @@ export const API_KEY_NULL_FIELDS: Record = { 'feature-flag.accessType': 'The REST flag endpoints expose no access type.', 'feature-flag.organizationTargets': 'The REST flag endpoints cannot list a flag’s targets.', 'feature-flag.userTargets': 'The REST flag endpoints cannot list a flag’s targets.', - 'org-domain.verificationContent': - 'REST returns verification_prefix and verification_token separately, not the combined record.', + 'org-domain.subdomain': + 'REST doesn’t return it; the dashboard derives it from the domain with a public-suffix parser.', 'org-domain.domainCaptureEnabled': 'REST domains carry no domain-capture flag.', 'portal.id': 'REST generate_link returns only the link URL.', 'portal.state': 'REST generate_link returns only the link URL.', diff --git a/src/lib/api-key-operations/organizations.ts b/src/lib/api-key-operations/organizations.ts index 851be400..cfdca179 100644 --- a/src/lib/api-key-operations/organizations.ts +++ b/src/lib/api-key-operations/organizations.ts @@ -3,8 +3,10 @@ * the WorkOS REST API (`/organizations`, `/organization_domains`). * * Fields the REST API has no source for (`usersCount`, a domain's - * `subdomain`/`verificationContent`/`domainCaptureEnabled`) are returned - * `null` rather than invented. + * `subdomain` and `domainCaptureEnabled`) are returned `null` rather than + * invented. A domain's DNS challenge is kept: REST returns its prefix and + * token, and `verificationContent` is built from them exactly as the dashboard + * builds it. */ import type { WorkOSListResponse } from '../workos-api.js'; @@ -41,14 +43,32 @@ export function metadataPairs(metadata: Record | null | undefine return Object.entries(metadata ?? {}).map(([key, value]) => ({ key, value })); } -/** A REST organization domain in the dashboard `OrganizationDomain` selection. */ +/** The dashboard's prefix when a domain has none of its own (`DEFAULT_VERIFICATION_PREFIX`). */ +const DEFAULT_VERIFICATION_PREFIX = 'verification_token'; + +/** + * The DNS TXT record value for a domain's verification challenge, as the + * dashboard reports it (`OrganizationDomain.verificationContent`): + * `=`, using the default prefix when the domain has none, and + * null when there is no token (nothing to verify). + */ +export function verificationContent(domain: RestOrganizationDomain): string | null { + if (!domain.verification_token) return null; + return `${domain.verification_prefix ?? DEFAULT_VERIFICATION_PREFIX}=${domain.verification_token}`; +} + +/** + * A REST organization domain in the dashboard `OrganizationDomain` selection. + * `subdomain` stays null: the dashboard derives it with a public-suffix + * parser, and REST doesn't return it. + */ export function domainNode(domain: RestOrganizationDomain) { return { id: domain.id, domain: domain.domain, state: domain.state ?? null, subdomain: null, - verificationContent: null, + verificationContent: verificationContent(domain), verificationStrategy: domain.verification_strategy ?? null, }; } @@ -161,7 +181,10 @@ export const organizationOperations: Record = { }), ); } - // The add operation selects id, state, domain and verificationStrategy. + // The dashboard's add selects id, state, domain and verificationStrategy: + // it adds domains already verified, so there is no challenge to show. + // REST adds them pending, so the DNS challenge needed to verify them rides + // along in the same `verificationContent` field. return { addDomains: { __typename: 'DomainsAdded', @@ -170,6 +193,7 @@ export const organizationOperations: Record = { state: d.state ?? null, domain: d.domain, verificationStrategy: d.verification_strategy ?? null, + verificationContent: verificationContent(d), })), }, }; From d93f7917766449058fbc6b38aa6b74aeaae5e275 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 12:25:12 -0800 Subject: [PATCH 24/32] fix: fail instead of truncating API-key lists past 5,000 records Full-list reads stopped at 50 pages and returned what they had. Callers treat the result as complete (slug lookups, list replaces), so a partial list could report a permission missing or act on the wrong set. Exit with list_too_long instead. --- src/commands/api-key-auth.spec.ts | 19 +++++++++++++++++++ src/lib/api-key-operations/context.ts | 14 +++++++++++--- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/src/commands/api-key-auth.spec.ts b/src/commands/api-key-auth.spec.ts index 2c0ef3a3..9de5ec99 100644 --- a/src/commands/api-key-auth.spec.ts +++ b/src/commands/api-key-auth.spec.ts @@ -640,6 +640,25 @@ describe('resource commands with an API key', () => { expect(byOrg).toMatchObject({ memberships: [{ id: 'om_1', state: 'inactive' }] }); }); + it('stops with an error instead of truncating a list past 5,000 records with an API key', async () => { + let served = 0; + rest.respond({ + // Every page says there is another one. + 'GET /authorization/permissions': () => { + const rows = Array.from({ length: 100 }, (_, i) => ({ ...REST_PERMISSION, id: `perm_${served * 100 + i}` })); + served += 1; + return restList(rows, `perm_${served * 100 - 1}`); + }, + }); + + const error = await expectExit(() => runPermissionList({})); + + expect(error.code).toBe('list_too_long'); + expect(error.message).toContain('5000'); + expect(stdout).toHaveLength(0); + expect(rest.callsTo('GET /authorization/permissions')).toHaveLength(50); + }); + it('reads every page of permissions in an explicit order with an API key', async () => { const page = (from: number, count: number) => Array.from({ length: count }, (_, i) => ({ diff --git a/src/lib/api-key-operations/context.ts b/src/lib/api-key-operations/context.ts index d21a28e1..ea5e4ce4 100644 --- a/src/lib/api-key-operations/context.ts +++ b/src/lib/api-key-operations/context.ts @@ -72,7 +72,7 @@ export function listEnvelope(data: T[], listMetadata?: { before: string | nul /** REST page size used when an operation must return a complete list. */ const FULL_LIST_PAGE_SIZE = 100; -/** Hard stop for full-list reads, so a bad cursor can never loop forever. */ +/** Hard stop for full-list reads, so a bad cursor can never loop forever; hitting it is an error. */ const FULL_LIST_MAX_PAGES = 50; /** @@ -100,9 +100,17 @@ export async function listAll( }); items.push(...(result?.data ?? [])); after = result?.list_metadata?.after ?? undefined; - if (!after) break; + if (!after) return items; } - return items; + // Still more pages after the cap. Callers rely on the list being complete + // (lookups by slug, list replaces), so acting on a partial one could report + // something missing or drop entries: stop instead of truncating silently. + exitWithError({ + code: 'list_too_long', + message: + `More than ${FULL_LIST_PAGE_SIZE * FULL_LIST_MAX_PAGES} records came back from one list, ` + + 'so this command stopped rather than act on a partial list.', + }); } /** From 952a886d92990645040d06d7e0797187c8bb7a08 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 12:25:12 -0800 Subject: [PATCH 25/32] test: check --api-key precedence through the real command line The in-process test set the flag with setResourceApiKeyFlag(), skipping yargs and the resource-group middleware. Drive bin.ts as a subprocess against a local HTTP stub (temp HOME, file-only storage via the insecure-storage preload) and assert the Authorization header: --api-key beats WORKOS_API_KEY and an unclaimed profile, WORKOS_API_KEY beats the profile, the profile's key is used last, and --environment-id with a key is refused before any request. --- src/commands/api-key-flag.integration.spec.ts | 155 ++++++++++++++++++ 1 file changed, 155 insertions(+) create mode 100644 src/commands/api-key-flag.integration.spec.ts diff --git a/src/commands/api-key-flag.integration.spec.ts b/src/commands/api-key-flag.integration.spec.ts new file mode 100644 index 00000000..92a60bf9 --- /dev/null +++ b/src/commands/api-key-flag.integration.spec.ts @@ -0,0 +1,155 @@ +/** + * The API-key precedence through the REAL command line: bin.ts parses + * `--api-key` with yargs, the resource-group middleware hands it to the auth + * selector, and the request goes out with that key. api-key-auth.spec.ts + * covers the selector in-process; this drives the actual CLI as a subprocess + * (bin.ts runs at import and has no seams) against a local HTTP stub of the + * WorkOS API, with a throwaway HOME and file-only credential storage so the + * host keychain and ~/.workos are never touched. + */ + +import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach } from 'vitest'; +import { spawn } from 'node:child_process'; +import { createServer, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const binPath = fileURLToPath(new URL('../bin.ts', import.meta.url)); +const forceInsecureStorageImport = fileURLToPath(new URL('../test/force-insecure-storage.ts', import.meta.url)); + +const ORG = { + object: 'organization', + id: 'org_1', + name: 'FooCorp', + domains: [], + metadata: {}, + external_id: null, + created_at: '2026-01-01T00:00:00.000Z', + updated_at: '2026-01-01T00:00:00.000Z', +}; + +let server: Server; +let baseUrl: string; +/** Requests the stub saw. Unclaimed profiles also trigger an unrelated claim-status check, so assertions filter. */ +const seen: Array<{ method: string; url: string; auth: string }> = []; +/** Authorization headers sent to the organizations API (the resource command's own requests). */ +const orgAuth = () => seen.filter((request) => request.url.startsWith('/organizations')).map((request) => request.auth); +let home: string; + +beforeAll(async () => { + server = createServer((req, res) => { + seen.push({ method: String(req.method), url: String(req.url), auth: String(req.headers.authorization ?? '') }); + if (req.method === 'GET' && req.url === '/organizations/org_1') { + res.writeHead(200, { 'content-type': 'application/json' }); + res.end(JSON.stringify(ORG)); + return; + } + res.writeHead(404, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ message: 'not found' })); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; +}); + +afterAll(async () => { + await new Promise((resolve) => server.close(() => resolve())); +}); + +beforeEach(() => { + seen.length = 0; + home = mkdtempSync(join(tmpdir(), 'wos-cli-api-key-it-')); + // An unclaimed active profile with its own key: the lowest-precedence key. + mkdirSync(join(home, '.workos'), { recursive: true }); + writeFileSync( + join(home, '.workos', 'config.json'), + JSON.stringify({ + activeEnvironment: 'unclaimed', + environments: { + unclaimed: { + name: 'unclaimed', + type: 'unclaimed', + apiKey: 'sk_test_unclaimed', + clientId: 'client_test', + claimToken: 'claim_test', + }, + }, + }), + ); +}); + +afterEach(() => { + rmSync(home, { recursive: true, force: true }); +}); + +function runCli( + args: string[], + env: NodeJS.ProcessEnv = {}, +): Promise<{ code: number | null; stdout: string; stderr: string }> { + return new Promise((resolve) => { + const child = spawn( + 'bun', + ['--preload', forceInsecureStorageImport, binPath, ...args, '--json', '--insecure-storage'], + { + // An empty cwd: nothing for Bun to auto-load from a .env file. + cwd: home, + env: { + PATH: process.env.PATH, + HOME: home, + USERPROFILE: home, + TMPDIR: home, + WORKOS_MODE: 'agent', + WORKOS_TELEMETRY: 'false', + WORKOS_API_URL: baseUrl, + ...env, + }, + stdio: ['ignore', 'pipe', 'pipe'], + }, + ); + let stdout = ''; + let stderr = ''; + child.stdout.on('data', (chunk) => (stdout += chunk)); + child.stderr.on('data', (chunk) => (stderr += chunk)); + child.on('close', (code) => resolve({ code, stdout, stderr })); + }); +} + +describe('--api-key through the real command line', () => { + it('sends the --api-key flag over WORKOS_API_KEY and the unclaimed profile with an API key', async () => { + const result = await runCli(['organization', 'get', 'org_1', '--api-key', 'sk_test_flag'], { + WORKOS_API_KEY: 'sk_test_env', + }); + + expect(result.code, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toMatchObject({ organization: { id: 'org_1', name: 'FooCorp' } }); + expect(orgAuth()).toEqual(['Bearer sk_test_flag']); + }, 30_000); + + it('falls back to WORKOS_API_KEY, then the unclaimed profile’s key, with an API key from each', async () => { + const fromEnv = await runCli(['organization', 'get', 'org_1'], { WORKOS_API_KEY: 'sk_test_env' }); + expect(fromEnv.code, fromEnv.stderr).toBe(0); + + const fromProfile = await runCli(['org', 'get', 'org_1']); + expect(fromProfile.code, fromProfile.stderr).toBe(0); + + expect(orgAuth()).toEqual(['Bearer sk_test_env', 'Bearer sk_test_unclaimed']); + }, 30_000); + + it('refuses --environment-id with an API key passed as a flag, before any request', async () => { + const result = await runCli([ + 'organization', + 'get', + 'org_1', + '--api-key', + 'sk_test_flag', + '--environment-id', + 'env_x', + ]); + + expect(result.code).toBe(1); + expect(JSON.parse(result.stderr.trim().split('\n').pop()!)).toMatchObject({ error: { code: 'invalid_argument' } }); + expect(orgAuth()).toEqual([]); + }, 30_000); +}); From e5c09dc5ca3de70584f468e0f830c4c95c635d72 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 12:25:13 -0800 Subject: [PATCH 26/32] riker: uncommitted changes from job 320 --- .scratch/job-320/pr-body.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.scratch/job-320/pr-body.md b/.scratch/job-320/pr-body.md index 905bc07b..68b627c6 100644 --- a/.scratch/job-320/pr-body.md +++ b/.scratch/job-320/pr-body.md @@ -72,7 +72,7 @@ Keys and shapes are identical on both paths. These values differ because REST ha | `membership.type` | REST memberships carry no type | | `event.updatedAt` | REST events carry only a creation time | | `feature-flag` get: `accessType`, `organizationTargets`, `userTargets` | the REST flag endpoints expose neither | -| `org-domain`: `verificationContent`, `domainCaptureEnabled` | REST returns the verification prefix/token separately, and has no capture flag | +| `org-domain`: `subdomain`, `domainCaptureEnabled` | REST doesn't return either (the dashboard derives `subdomain` with a public-suffix parser this CLI doesn't ship) | | `portal`: `id`, `state`, `expiresAt` | REST `generate_link` returns only the URL | | `session.impersonator` id/firstName/lastName | REST names an impersonator by email only | | `session.provider` for OAuth sign-ins | REST reports every OAuth provider as plain `oauth`, so `GoogleOAuth` etc. can't be named | @@ -85,7 +85,8 @@ Some fields are filled with extra REST reads rather than nulled. They are bounde Behavioral differences (not output fields): - **Search filters are exact matches.** `organization list --domain`, `user list --email` and `invitation list --email` use REST's exact-match filters (domain, email). The dashboard does a search. -- **New domains start pending.** `org-domain create` on REST creates the domain `pending` (it needs DNS verification). The dashboard adds it verified. The output reports the real state. +- **New domains start pending, with their DNS challenge.** `org-domain create` on REST creates the domain `pending` (it needs DNS verification); the dashboard adds it verified. The output reports the real state, and `verificationContent` carries the TXT record value to publish. On every domain read (`organization list/get`, `org-domain get/create/verify`) it's built exactly as the dashboard builds it: `=`, prefix defaulting to `verification_token`, null without a token. +- **Full lists never truncate silently.** A full-list read stops at 5,000 records and fails with `list_too_long` rather than act on a partial list. - **Order, full lists and statuses are explicit.** Every key-path list sends an order (your `--order`, else `desc`, which returns the same newest-first rows as REST's `normal` default), so `after` is always the next page. Reads that must return a complete list (permissions, a user's memberships, redirect URIs, CORS origins) follow it to the end, and `config redirect add` still refuses to merge over more than one page of URIs. Membership listings and `membership delete` include every status (`active,inactive,pending`), so a deactivated membership is listed and can be deleted, as on the dashboard. - **`membership list --org` pages over memberships.** Its cursors are membership IDs on the key path and user IDs on the session path. They're opaque either way, and each path accepts its own cursors. - **`feature-flag add-target|remove-target` call REST's target endpoints directly.** REST can't list a flag's targets, so there's no read-merge-write, and remove-target can't pre-check that the target exists. @@ -208,6 +209,7 @@ I also checked against a local fake API (`WORKOS_API_URL=http://127.0.0.1: - the REST requests and outputs for every command's mutations; - not-found and 401 handling. - `src/commands/api-key-parity.spec.ts` covers JSON parity, described above. +- `src/commands/api-key-flag.integration.spec.ts` drives the real CLI (subprocess, temp HOME, local HTTP stub) to check `--api-key` > `WORKOS_API_KEY` > unclaimed profile through actual yargs parsing, and the `--environment-id` refusal. - `src/lib/command-auth.spec.ts` covers: - the `resolveResourceApiKey()` precedence, against the real file-backed config store; - the updated copy. Two existing tests were renamed and updated, because their assertion that the copy says "does not accept API keys" is now the bug. From 999ca56ac9109b4a81432a49b2ba478d0d141d82 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 12:25:13 -0800 Subject: [PATCH 27/32] test: stop the live parity gate from skipping cursor-named fields parity-smoke --api-key passed the pagination cursor names to apiKeyParityDiffs, which skipped them at every depth, so a changed or missing metadata.before / metadata.after / metadata.pagination still passed. Both callers only ever pass the entity or its rows (the cursors live in the envelope, outside the comparison), so the gate drops the exemption parameter entirely and compares every key inside the entity. A test covers cursor-named metadata keys and fails on the old gate. --- scripts/parity-smoke.ts | 9 ++++----- src/commands/api-key-parity.spec.ts | 23 +++++++++++++++++++++++ src/lib/api-key-operations/known-gaps.ts | 16 +++++++--------- 3 files changed, 34 insertions(+), 14 deletions(-) diff --git a/scripts/parity-smoke.ts b/scripts/parity-smoke.ts index 8a579ddc..bf79c89a 100644 --- a/scripts/parity-smoke.ts +++ b/scripts/parity-smoke.ts @@ -977,9 +977,6 @@ async function checkNew(c: { label: string; args: string[] }): Promise { */ const API_KEY_ACCEPTED: Record = { ...API_KEY_NULL_FIELDS }; -/** Cursors are opaque and plane-specific; everything else must match exactly. */ -const CURSOR_KEYS = new Set(['before', 'after', 'listMetadata', 'list_metadata', 'pagination']); - /** * The environment the session side is pinned to. Every session-side command * passes it as `--environment-id`, which the CLI refuses whenever ANY API key @@ -1080,10 +1077,12 @@ async function checkSessionVsKey(c: ApiKeyCheck): Promise { rows = sv.length; for (const row of sv) { const other = kv.find((candidate: any) => candidate?.[c.idKey!] === row?.[c.idKey!]); - diffs.push(...apiKeyParityDiffs(c.cmd, row, other, CURSOR_KEYS).map((d) => `${row?.[c.idKey!]}: ${d}`)); + diffs.push(...apiKeyParityDiffs(c.cmd, row, other).map((d) => `${row?.[c.idKey!]}: ${d}`)); } } else { - diffs.push(...apiKeyParityDiffs(c.cmd, sv, kv, CURSOR_KEYS)); + // Only the entity is compared; the envelope's pagination cursors are + // opaque and plane-specific, and stay out of it. + diffs.push(...apiKeyParityDiffs(c.cmd, sv, kv)); } for (const d of diffs) notes.push(`${C.red}FAIL${C.reset} ${c.label} ${d}`); const empty = Array.isArray(sv) && sv.length === 0; diff --git a/src/commands/api-key-parity.spec.ts b/src/commands/api-key-parity.spec.ts index ff1fcd96..d8e98038 100644 --- a/src/commands/api-key-parity.spec.ts +++ b/src/commands/api-key-parity.spec.ts @@ -979,6 +979,29 @@ describe('apiKeyParityDiffs, the shared session-vs-key parity gate', () => { expect(diffs[0]).toContain('impersonator'); }); + it('compares metadata keys named like pagination cursors with an API key', () => { + const org = { id: 'org_1', metadata: { before: 'v1', after: 'v2', pagination: 'v3' } }; + + expect(apiKeyParityDiffs('organization', org, org)).toEqual([]); + expect( + apiKeyParityDiffs('organization', org, { id: 'org_1', metadata: { before: 'changed', after: 'v2' } }), + ).toEqual([ + 'metadata.before: session="v1" apiKey="changed"', + 'metadata.pagination: present only on the session side', + ]); + expect(apiKeyParityDiffs('organization', [org], [{ ...org, metadata: { ...org.metadata, after: null } }])).toEqual([ + 'metadata.after: session="v2" apiKey=null', + ]); + // The gate takes no exemption set any more (parity-smoke used to pass the + // cursor names, which skipped them at every depth): an extra argument + // must change nothing. + const gate = apiKeyParityDiffs as unknown as (...args: unknown[]) => string[]; + const changed = { ...org, metadata: { ...org.metadata, before: 'changed' } }; + expect(gate('organization', org, changed, new Set(['before']))).toEqual([ + 'metadata.before: session="v1" apiKey="changed"', + ]); + }); + it('rejects a lost email, a lost ID and a casing-only difference with an API key', () => { expect( apiKeyParityDiffs('session', sessionRow, { diff --git a/src/lib/api-key-operations/known-gaps.ts b/src/lib/api-key-operations/known-gaps.ts index e0710f35..5b24709f 100644 --- a/src/lib/api-key-operations/known-gaps.ts +++ b/src/lib/api-key-operations/known-gaps.ts @@ -54,15 +54,14 @@ function sortForPairing(items: unknown[]): unknown[] { * is a leaf listed in {@link API_KEY_NULL_FIELDS} for `command`, which may be * `null` on the API-key side whatever the dashboard returned (a non-null value * there must still match). A whole object going null, an element losing its - * keys, or an ID or email disappearing all fail. `ignoreKeys` drops keys at - * any depth (pagination cursors are opaque and plane-specific). + * keys, or an ID or email disappearing all fail. + * + * Pass the entity (or the list of rows), never the output envelope: nothing is + * exempt inside it, so a `metadata.before` or `metadata.pagination` key is + * compared like any other field. Pagination cursors live in the envelope, + * outside what this compares. */ -export function apiKeyParityDiffs( - command: string, - session: unknown, - apiKey: unknown, - ignoreKeys: ReadonlySet = new Set(), -): string[] { +export function apiKeyParityDiffs(command: string, session: unknown, apiKey: unknown): string[] { const diffs: string[] = []; function walk(path: string, s: unknown, k: unknown): void { @@ -84,7 +83,6 @@ export function apiKeyParityDiffs( if (isPlainObject(s) && isPlainObject(k)) { const keys = new Set([...Object.keys(s), ...Object.keys(k)]); for (const key of keys) { - if (ignoreKeys.has(key)) continue; const child = path ? `${path}.${key}` : key; if (!(key in s) || !(key in k)) { diffs.push(`${child}: present only on the ${key in s ? 'session' : 'API-key'} side`); From c309c6f845fc3710d14697582b296d5cb553b6eb Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 12:25:13 -0800 Subject: [PATCH 28/32] fix: report membership roles the way the dashboard does on the API-key path REST names a membership's roles by slug. The dashboard reports them by role ID on membership records (UserlandUserOrganizationMembership.role / .roles: membership list --user, get, update) and by display name on an organization's identities (role { name } in membership list --org). The key path passed REST's {slug} through, so it printed "member" where the dashboard prints "role_..." or "Member". Resolve each slug through the organization's roles (then the environment's) and emit the same values. The parity fixtures now use what those dashboard queries actually select (role IDs; role { name }), so the old mapping fails them. A role list that 404s now reads as empty, like an organization's. --- src/commands/api-key-auth.spec.ts | 5 +- src/commands/api-key-parity.spec.ts | 42 +++++++++--- src/lib/api-key-operations/lookups.ts | 7 +- src/lib/api-key-operations/memberships.ts | 78 ++++++++++++++++------- 4 files changed, 97 insertions(+), 35 deletions(-) diff --git a/src/commands/api-key-auth.spec.ts b/src/commands/api-key-auth.spec.ts index 9de5ec99..ebcb0fc9 100644 --- a/src/commands/api-key-auth.spec.ts +++ b/src/commands/api-key-auth.spec.ts @@ -569,7 +569,10 @@ describe('resource commands with an API key', () => { expect(rest.callsTo('PUT /user_management/organization_memberships/om_1')[0].body).toEqual({ role_slug: 'member', }); - expect(updated).toMatchObject({ membership: { id: 'om_1', role: 'member', state: 'active' } }); + // The membership record reports the role by ID, as the dashboard does. + expect(updated).toMatchObject({ + membership: { id: 'om_1', role: 'role_member', roles: ['role_member'], state: 'active' }, + }); expect(rest.callsTo('POST /user_management/invitations')[0].body).toEqual({ email: 'n@example.com', expires_in_days: 7, diff --git a/src/commands/api-key-parity.spec.ts b/src/commands/api-key-parity.spec.ts index d8e98038..d7e7dad8 100644 --- a/src/commands/api-key-parity.spec.ts +++ b/src/commands/api-key-parity.spec.ts @@ -148,15 +148,17 @@ const GQL_INVITE = { organization: { id: 'org_1', name: 'FooCorp' }, }; +// The dashboard's membership record carries role IDs as plain strings +// (`UserlandUserOrganizationMembership.role` / `.roles`). const GQL_MEMBERSHIP = { id: 'om_1', - type: 'Standard', + type: 'Manual', status: 'Active', organizationId: 'org_1', userlandUserId: 'user_1', directoryUserId: null, - role: { slug: 'member' }, - roles: [{ slug: 'member' }], + role: 'role_member', + roles: ['role_member'], createdAt: T0, updatedAt: T1, }; @@ -700,8 +702,12 @@ describe('resource command --json parity, session vs API key', () => { () => ({ userlandUserOrganizationMemberships: { organizationMemberships: [GQL_MEMBERSHIP] } }), () => runMembershipList({ user: 'user_1' }), ), - await viaApiKey({ 'GET /user_management/organization_memberships': restList([REST_MEMBERSHIP]) }, () => - runMembershipList({ user: 'user_1' }), + await viaApiKey( + { + 'GET /user_management/organization_memberships': restList([REST_MEMBERSHIP]), + 'GET /authorization/roles': { object: 'list', data: [REST_ROLE_MEMBER] }, + }, + () => runMembershipList({ user: 'user_1' }), ), ['type'], ); @@ -711,13 +717,31 @@ describe('resource command --json parity, session vs API key', () => { () => ({ userlandUserOrganizationMembership: GQL_MEMBERSHIP }), () => runMembershipGet('om_1'), ), - await viaApiKey({ 'GET /user_management/organization_memberships/om_1': REST_MEMBERSHIP }, () => - runMembershipGet('om_1'), + await viaApiKey( + { + 'GET /user_management/organization_memberships/om_1': REST_MEMBERSHIP, + 'GET /authorization/roles': { object: 'list', data: [REST_ROLE_MEMBER] }, + }, + () => runMembershipGet('om_1'), ), ['type'], ); }); + it('membership roles are role IDs on records and display names by organization, with an API key', async () => { + const routes = { + 'GET /organizations/org_1': REST_ORG, + 'GET /user_management/organization_memberships': restList([REST_MEMBERSHIP]), + 'GET /authorization/roles': { object: 'list', data: [REST_ROLE_MEMBER] }, + }; + const byUser = await viaApiKey(routes, () => runMembershipList({ user: 'user_1' })); + const byOrg = await viaApiKey(routes, () => runMembershipList({ org: 'org_1' })); + + // REST's slug ("member") must not leak: records carry the role ID, identities the name. + expect(byUser).toMatchObject({ memberships: [{ role: 'role_member', roles: ['role_member'] }] }); + expect(byOrg).toMatchObject({ memberships: [{ role: 'Member', roles: ['Member'] }] }); + }); + it('membership list (by organization) matches with an API key', async () => { const session = await viaSession( () => ({ @@ -726,7 +750,8 @@ describe('resource command --json parity, session vs API key', () => { data: [ { id: 'user_1', - identities: { data: [{ ...GQL_IDENTITY, role: { slug: 'member' }, roles: [{ slug: 'member' }] }] }, + // The by-organization query selects only each role's name. + identities: { data: [{ ...GQL_IDENTITY, role: { name: 'Member' }, roles: [{ name: 'Member' }] }] }, }, ], listMetadata: { before: null, after: 'om_1' }, @@ -739,6 +764,7 @@ describe('resource command --json parity, session vs API key', () => { { 'GET /organizations/org_1': REST_ORG, 'GET /user_management/organization_memberships': restList([REST_MEMBERSHIP], 'om_1'), + 'GET /authorization/roles': { object: 'list', data: [REST_ROLE_MEMBER] }, }, () => runMembershipList({ org: 'org_1' }), ); diff --git a/src/lib/api-key-operations/lookups.ts b/src/lib/api-key-operations/lookups.ts index e98c0a7b..0ef3b9e7 100644 --- a/src/lib/api-key-operations/lookups.ts +++ b/src/lib/api-key-operations/lookups.ts @@ -39,9 +39,10 @@ function memoFor(ctx: ApiKeyContext): Memo { export function environmentRoles(ctx: ApiKeyContext): Promise { const memo = memoFor(ctx); - memo.environmentRoles ??= ctx - .request<{ data: RestRole[] }>({ method: 'GET', path: '/authorization/roles' }) - .then((result) => result?.data ?? []); + // A 404 (no roles to list) reads as none, like an organization's roles. + memo.environmentRoles ??= orNull( + ctx.request<{ data: RestRole[] }>({ method: 'GET', path: '/authorization/roles' }), + ).then((result) => result?.data ?? []); return memo.environmentRoles; } diff --git a/src/lib/api-key-operations/memberships.ts b/src/lib/api-key-operations/memberships.ts index c100f8e8..9d2299eb 100644 --- a/src/lib/api-key-operations/memberships.ts +++ b/src/lib/api-key-operations/memberships.ts @@ -3,7 +3,10 @@ * `/user_management/organization_memberships` and `/user_management/invitations`. * * The CLI takes role IDs (`role_*`) for `--role`; REST takes role slugs, so the - * ID is resolved through the roles endpoints first. A membership's `type` and + * ID is resolved through the roles endpoints first. Output goes the other way: + * REST names a membership's roles by slug, while the dashboard reports them by + * ID on membership records and by display name on an organization's + * identities, so slugs are resolved to match. A membership's `type` and * `directoryUserId` have no REST source and come back `null`. */ @@ -24,6 +27,7 @@ import { membershipsForUser, organizationName, type RestMembership, + type RestRole, } from './lookups.js'; import { exitWithError } from '../../utils/output.js'; @@ -36,7 +40,24 @@ interface RestInvitation { created_at?: string; } -function membershipNode(membership: RestMembership) { +/** + * A membership's role slugs resolved to roles as its organization sees them. + * REST names roles by slug; the dashboard reports them by ID on a membership + * record and by display name on an organization's identities. + */ +async function membershipRoles(ctx: ApiKeyContext, membership: RestMembership) { + const lookup = (slug: string) => findRole(ctx, { slug }, membership.organization_id); + const role = membership.role ? ((await lookup(membership.role.slug)) ?? null) : null; + const roles = await Promise.all((membership.roles ?? []).map((entry) => lookup(entry.slug))); + return { role, roles: roles.filter((entry): entry is RestRole => entry !== undefined) }; +} + +/** + * A REST membership as the dashboard's membership record, whose `role` and + * `roles` are role IDs (`UserlandUserOrganizationMembership`), not slugs. + */ +async function membershipNode(ctx: ApiKeyContext, membership: RestMembership) { + const { role, roles } = await membershipRoles(ctx, membership); return { id: membership.id, type: null, @@ -44,8 +65,8 @@ function membershipNode(membership: RestMembership) { organizationId: membership.organization_id ?? null, userlandUserId: membership.user_id ?? null, directoryUserId: null, - role: membership.role ?? null, - roles: membership.roles ?? [], + role: role?.id ?? null, + roles: roles.map((entry) => entry.id), createdAt: membership.created_at ?? null, updatedAt: membership.updated_at ?? null, }; @@ -123,7 +144,11 @@ async function setMembershipState(ctx: ApiKeyContext, id: unknown, action: 'deac export const membershipOperations: Record = { async userlandUserOrganizationMemberships(variables, ctx) { const memberships = await membershipsForUser(ctx, String(variables.userlandUserId)); - return { userlandUserOrganizationMemberships: { organizationMemberships: memberships.map(membershipNode) } }; + return { + userlandUserOrganizationMemberships: { + organizationMemberships: await Promise.all(memberships.map((membership) => membershipNode(ctx, membership))), + }, + }; }, async userlandUsersByOrg(variables, ctx) { @@ -143,29 +168,36 @@ export const membershipOperations: Record = { order: restOrder(variables.order), }, }); - const users = (page?.data ?? []).map((membership) => ({ - id: membership.user_id, - identities: { - data: [ - { - id: membership.id, - status: membership.status ?? null, - directoryUserId: null, - role: membership.role ?? null, - roles: membership.roles ?? [], - organization: { id: organizationId, name: membership.organization_name ?? null }, - createdAt: membership.created_at ?? null, - updatedAt: membership.updated_at ?? null, + // The dashboard's by-organization identities select each role's display + // name only (`role { name }`, `roles { name }`), so that is what they carry. + const users = await Promise.all( + (page?.data ?? []).map(async (membership) => { + const { role, roles } = await membershipRoles(ctx, membership); + return { + id: membership.user_id, + identities: { + data: [ + { + id: membership.id, + status: membership.status ?? null, + directoryUserId: null, + role: role ? { name: role.name } : null, + roles: roles.map((entry) => ({ name: entry.name })), + organization: { id: organizationId, name: membership.organization_name ?? null }, + createdAt: membership.created_at ?? null, + updatedAt: membership.updated_at ?? null, + }, + ], }, - ], - }, - })); + }; + }), + ); return { organization: { userlandUsers: listEnvelope(users, page?.list_metadata) } }; }, async userlandUserOrganizationMembership(variables, ctx) { const membership = await readMembership(ctx, String(variables.id)); - return { userlandUserOrganizationMembership: membership ? membershipNode(membership) : null }; + return { userlandUserOrganizationMembership: membership ? await membershipNode(ctx, membership) : null }; }, async addUserlandUserToOrg(variables, ctx) { @@ -209,7 +241,7 @@ export const membershipOperations: Record = { return { updateRoleOnOrganizationMembership: { __typename: 'RoleOnOrganizationMembershipUpdated', - organizationMembership: membershipNode(updated), + organizationMembership: await membershipNode(ctx, updated), }, }; }, From 38c20761e8d09b683adab0e7194bcf58e9db6329 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 12:25:14 -0800 Subject: [PATCH 29/32] test: keep each parity-smoke side on the plane it claims to test - An empty WORKOS_API_KEY now counts as unset, so the key in use and the reported key source always agree. --api-key mode also proves the key side is on the key before comparing (the CLI must refuse --environment-id there), so it can't compare the session to itself. - The default branch-vs-main mode no longer hands WORKOS_API_KEY to the branch's resource commands, which now take the key path when it is set: they run without it (still-REST commands keep it), and are pinned to the session's environment from whoami, so an unclaimed profile's key is refused instead of silently used. Env-scoped NEW checks get the pinned --environment-id at run time. --- scripts/parity-smoke.ts | 114 ++++++++++++++++++++++++++++++++-------- 1 file changed, 93 insertions(+), 21 deletions(-) diff --git a/scripts/parity-smoke.ts b/scripts/parity-smoke.ts index bf79c89a..7e138c15 100644 --- a/scripts/parity-smoke.ts +++ b/scripts/parity-smoke.ts @@ -115,8 +115,10 @@ function envLocalKey(dir: string): string | undefined { } // Precedence: explicit env var > this branch's .env.local. Never main's, so the -// REST plane is pinned to the same environment the branch targets. -const API_KEY = process.env.WORKOS_API_KEY ?? envLocalKey(BRANCH_DIR); +// REST plane is pinned to the same environment the branch targets. An empty +// WORKOS_API_KEY counts as unset (as the CLI treats it), so the key and the +// reported source always agree. +const API_KEY = process.env.WORKOS_API_KEY || envLocalKey(BRANCH_DIR); const API_KEY_SOURCE = process.env.WORKOS_API_KEY ? 'env' : envLocalKey(BRANCH_DIR) ? 'branch .env.local' : 'NONE'; function binFor(dir: string): { cmd: string; args: string[] } { @@ -134,13 +136,50 @@ interface RunResult { stderr: string; } const COMMAND_TIMEOUT_MS = 60_000; -/** `withoutApiKey` runs the child with WORKOS_API_KEY unset (the dashboard-session side in --api-key mode). */ + +/** + * Branch commands that must run on the dashboard session. These resource + * commands now switch to an API key whenever WORKOS_API_KEY is set, so in the + * default branch-vs-main mode the branch side must not inherit the key that + * main's REST side uses, or it would quietly compare REST with REST. The + * still-REST commands (connection, directory, audit-log, api) keep the key. + */ +const SESSION_PLANE_COMMANDS = new Set([ + 'organization', + 'org', + 'user', + 'role', + 'permission', + 'membership', + 'invitation', + 'session', + 'event', + 'feature-flag', + 'org-domain', + 'portal', + 'webhook', + 'config', + 'authkit', + 'branding', + 'whoami', + 'project', + 'team', + 'environment', +]); + +/** + * `withoutApiKey` runs the child with WORKOS_API_KEY unset (the dashboard + * session side). In the default mode, branch session-plane commands always + * run that way. + */ function run(dir: string, cliArgs: string[], opts: { withoutApiKey?: boolean } = {}): Promise { const { cmd, args } = binFor(dir); + const sessionPlane = + opts.withoutApiKey || (!API_KEY_MODE && dir === BRANCH_DIR && SESSION_PLANE_COMMANDS.has(cliArgs[0])); return new Promise((resolve) => { const childEnv: NodeJS.ProcessEnv = { ...process.env }; if (API_KEY) childEnv.WORKOS_API_KEY = API_KEY; - if (opts.withoutApiKey) delete childEnv.WORKOS_API_KEY; + if (sessionPlane) delete childEnv.WORKOS_API_KEY; const p = spawn(cmd, [...args, ...cliArgs], { cwd: NEUTRAL_CWD, env: childEnv, stdio: ['ignore', 'pipe', 'pipe'] }); let stdout = ''; let stderr = ''; @@ -176,7 +215,18 @@ function parseJson(stdout: string): any { } } -const envArgs = (): string[] => (ENV_ID ? ['--environment-id', ENV_ID] : []); +/** + * The environment the branch's session side is pinned to (see + * pinSessionEnvironment). Every branch session-side command passes it as + * `--environment-id`, which the CLI refuses whenever ANY API key applies + * (WORKOS_API_KEY, --api-key, or an unclaimed active profile's stored key), so + * a session-side run either really uses the dashboard login or fails loudly. + */ +let sessionEnvironmentId = ''; +const envArgs = (): string[] => { + const id = sessionEnvironmentId || ENV_ID; + return id ? ['--environment-id', id] : []; +}; const shortErr = (s: string): string => s.split('\n').filter(Boolean).slice(0, 2).join(' | '); // --- value normalization --------------------------------------------------------- @@ -502,8 +552,9 @@ const NEW_ONLY = [ { label: 'whoami', args: ['whoami', '--json'] }, { label: 'project list', args: ['project', 'list', '--json'] }, { label: 'team members', args: ['team', 'members', '--json'] }, - { label: 'authkit redirect-uris list', args: ['authkit', 'redirect-uris', 'list', '--json', ...envArgs()] }, - { label: 'branding get', args: ['branding', 'get', '--json', ...envArgs()] }, + // Environment-scoped: checkNew appends the pinned --environment-id at run time. + { label: 'authkit redirect-uris list', args: ['authkit', 'redirect-uris', 'list', '--json'], envScoped: true }, + { label: 'branding get', args: ['branding', 'get', '--json'], envScoped: true }, ]; // --- reporting ------------------------------------------------------------------- @@ -959,8 +1010,8 @@ async function checkEventPagination(): Promise { push('PAGINATION', 'event', 'PASS', `${firstRows.length} + ${secondRows.length} distinct rows; page 2 is not newer`); } -async function checkNew(c: { label: string; args: string[] }): Promise { - const r = await run(BRANCH_DIR, c.args); +async function checkNew(c: { label: string; args: string[]; envScoped?: boolean }): Promise { + const r = await run(BRANCH_DIR, c.envScoped ? [...c.args, ...envArgs()] : c.args); if (r.rc === 4) return push('NEW', c.label, 'AUTH', 'auth required'); if (r.rc !== 0) return push('NEW', c.label, 'FAIL', `exit ${r.rc} ${shortErr(r.stderr)}`); if (parseJson(r.stdout) === undefined) return push('NEW', c.label, 'FAIL', 'invalid JSON'); @@ -977,16 +1028,6 @@ async function checkNew(c: { label: string; args: string[] }): Promise { */ const API_KEY_ACCEPTED: Record = { ...API_KEY_NULL_FIELDS }; -/** - * The environment the session side is pinned to. Every session-side command - * passes it as `--environment-id`, which the CLI refuses whenever ANY API key - * applies (WORKOS_API_KEY, --api-key, or an unclaimed active profile's stored - * key). So a session-side run either really goes through the dashboard login - * or fails loudly; it can never quietly fall back to REST and compare REST - * with itself. - */ -let sessionEnvironmentId = ''; - /** Entities actually compared field by field; a run that compared none proves nothing and fails. */ let comparedEntities = 0; @@ -1015,7 +1056,7 @@ async function runBoth(args: string[]): Promise<[RunResult, RunResult]> { async function pinSessionEnvironment(): Promise { const r = await run(BRANCH_DIR, ['whoami', '--json', ...envArgs()], { withoutApiKey: true }); if (r.rc === 4) { - console.error('--api-key mode needs a dashboard login for the session side: run `workos auth login` first.'); + console.error('parity-smoke needs a dashboard login for the branch session side: run `workos auth login` first.'); process.exit(2); } const environmentId = parseJson(r.stdout)?.environment?.id; @@ -1029,6 +1070,30 @@ async function pinSessionEnvironment(): Promise { sessionEnvironmentId = environmentId; } +/** + * Prove the API-key side really runs with the key: the CLI refuses + * `--environment-id` only when an API key applies, so a key-side run that + * accepts it would be on the dashboard session (e.g. an empty key), and the + * comparison would be the session against itself. + */ +async function proveKeySide(): Promise { + const r = await run(BRANCH_DIR, ['organization', 'list', '--json', '--environment-id', sessionEnvironmentId]); + const code = (() => { + try { + return JSON.parse(r.stderr.trim().split('\n').pop() ?? '')?.error?.code; + } catch { + return undefined; + } + })(); + if (r.rc !== 1 || code !== 'invalid_argument') { + console.error( + `the API-key side is not running with the key (expected --environment-id to be refused, got rc=${r.rc} ${shortErr(r.stderr)}); ` + + 'set a non-empty WORKOS_API_KEY for the session’s environment.', + ); + process.exit(2); + } +} + async function checkSessionVsKey(c: ApiKeyCheck): Promise { const [s, k] = await runBoth(c.args); if (s.rc === 4) { @@ -1108,7 +1173,8 @@ async function runApiKeyMode(): Promise { process.exit(2); } await pinSessionEnvironment(); - console.log(` session pinned to environment ${sessionEnvironmentId}\n`); + await proveKeySide(); + console.log(` session pinned to environment ${sessionEnvironmentId}; key side confirmed on the key\n`); const lists: ApiKeyCheck[] = [ { @@ -1280,6 +1346,12 @@ if (API_KEY_SOURCE === 'NONE') { if (STRICT) process.exit(2); } +// The branch's resource commands must run on the dashboard session: pin them +// to the session's environment so any API key that could still apply (an +// unclaimed active profile) is refused instead of silently used. +await pinSessionEnvironment(); +console.log(` branch session pinned to environment ${sessionEnvironmentId}\n`); + await Promise.all(CONTROL.map(checkControl)); // Preflight: prove both planes are looking at the SAME environment before any From fab3c6371140647a5e70cf3ee5dde394204d84d3 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 12:25:14 -0800 Subject: [PATCH 30/32] riker: uncommitted changes from job 320 --- .scratch/job-320/pr-body.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.scratch/job-320/pr-body.md b/.scratch/job-320/pr-body.md index 68b627c6..20e4d26f 100644 --- a/.scratch/job-320/pr-body.md +++ b/.scratch/job-320/pr-body.md @@ -88,6 +88,7 @@ Behavioral differences (not output fields): - **New domains start pending, with their DNS challenge.** `org-domain create` on REST creates the domain `pending` (it needs DNS verification); the dashboard adds it verified. The output reports the real state, and `verificationContent` carries the TXT record value to publish. On every domain read (`organization list/get`, `org-domain get/create/verify`) it's built exactly as the dashboard builds it: `=`, prefix defaulting to `verification_token`, null without a token. - **Full lists never truncate silently.** A full-list read stops at 5,000 records and fails with `list_too_long` rather than act on a partial list. - **Order, full lists and statuses are explicit.** Every key-path list sends an order (your `--order`, else `desc`, which returns the same newest-first rows as REST's `normal` default), so `after` is always the next page. Reads that must return a complete list (permissions, a user's memberships, redirect URIs, CORS origins) follow it to the end, and `config redirect add` still refuses to merge over more than one page of URIs. Membership listings and `membership delete` include every status (`active,inactive,pending`), so a deactivated membership is listed and can be deleted, as on the dashboard. +- **Membership roles match the dashboard's values.** REST names roles by slug; the dashboard reports them by role ID on membership records (`membership list --user`, `get`, `update`) and by display name on `membership list --org`. The key path resolves each slug through the organization's roles (then the environment's) and prints the same value. - **`membership list --org` pages over memberships.** Its cursors are membership IDs on the key path and user IDs on the session path. They're opaque either way, and each path accepts its own cursors. - **`feature-flag add-target|remove-target` call REST's target endpoints directly.** REST can't list a flag's targets, so there's no read-merge-write, and remove-target can't pre-check that the target exists. - **Redirect URIs and CORS have limits on REST.** @@ -115,7 +116,7 @@ Enum mapping is taken from the vendored catalog's enum types, so both paths prin **One gate, offline and live.** Both use `apiKeyParityDiffs()` from `known-gaps.ts`. Every object must have the same keys on both sides, arrays the same length, and every leaf the same value. The only exception is a leaf path listed in `API_KEY_NULL_FIELDS` (for example `user.authenticationFactors[].lastVerifiedAt`, `session.impersonator.id`), which may be `null` on the key side. An element that loses its keys, an object that goes null as a whole, a lost ID or email, or a casing-only difference all fail. -**Live (`scripts/parity-smoke.ts --api-key`, new mode).** It runs each command's list/get on this branch twice, with the session and with `WORKOS_API_KEY`, and judges each entity with the same gate. It needs no `../main`. A check counts only when both sides returned real entities (rows that each carry their ID, or a non-empty entity), and a run that compared no entity at all exits 1. The session side is proven, not assumed: `whoami` (session-only) must succeed without a key, and every session-side command is pinned to that environment with `--environment-id`. The CLI refuses `--environment-id` whenever any API key applies, including an unclaimed profile's stored key, so the session side can't quietly run on REST and compare REST with itself. **Not run for this PR:** the session side needs a real `workos auth login`, and this work was kept away from the real `~/.workos` and Keychain. With no login it exits 2 before comparing anything (checked against a scratch HOME). Running it is a good pre-merge check: +**Live (`scripts/parity-smoke.ts --api-key`, new mode).** It runs each command's list/get on this branch twice, with the session and with `WORKOS_API_KEY`, and judges each entity with the same gate. It needs no `../main`. A check counts only when both sides returned real entities (rows that each carry their ID, or a non-empty entity), and a run that compared no entity at all exits 1. The session side is proven, not assumed: `whoami` (session-only) must succeed without a key, and every session-side command is pinned to that environment with `--environment-id`. The CLI refuses `--environment-id` whenever any API key applies, including an unclaimed profile's stored key, so the session side can't quietly run on REST and compare REST with itself. The default branch-vs-main mode also changed: the branch's resource commands now take the key path whenever `WORKOS_API_KEY` is set, so they run without it and pinned to the session's environment, and an empty `WORKOS_API_KEY` counts as unset in both modes. `--api-key` mode also proves the key side is really on the key (the CLI must refuse `--environment-id` there) before comparing. **Not run for this PR:** the session side needs a real `workos auth login`, and this work was kept away from the real `~/.workos` and Keychain. With no login it exits 2 before comparing anything (checked against a scratch HOME). Running it is a good pre-merge check: ``` workos auth login From ef1431ab4711389df16cc3e2f56967c037e5780a Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Mon, 16 Nov 2026 14:01:49 -0600 Subject: [PATCH 31/32] test: never let a hung CLI child outlive the --api-key integration test Each spawned CLI is killed after 20s (before the 30s test timeout, so the failure names the hang), any child still running is killed in afterEach, and the stub server drops lingering connections before closing. --- src/commands/api-key-flag.integration.spec.ts | 24 +++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/src/commands/api-key-flag.integration.spec.ts b/src/commands/api-key-flag.integration.spec.ts index 92a60bf9..14f40ed1 100644 --- a/src/commands/api-key-flag.integration.spec.ts +++ b/src/commands/api-key-flag.integration.spec.ts @@ -9,7 +9,7 @@ */ import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach } from 'vitest'; -import { spawn } from 'node:child_process'; +import { spawn, type ChildProcess } from 'node:child_process'; import { createServer, type Server } from 'node:http'; import type { AddressInfo } from 'node:net'; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; @@ -55,6 +55,8 @@ beforeAll(async () => { }); afterAll(async () => { + // Drop any connection a stray child still holds, so close() can't hang. + server.closeAllConnections(); await new Promise((resolve) => server.close(() => resolve())); }); @@ -81,9 +83,18 @@ beforeEach(() => { }); afterEach(() => { + // A test that timed out can leave its CLI child running; never let it outlive the test. + for (const child of running) child.kill('SIGKILL'); + running.clear(); rmSync(home, { recursive: true, force: true }); }); +/** CLI children still running; killed in afterEach. */ +const running = new Set(); + +/** Kill a hung CLI well before the 30s test timeout, so the failure names the hang. */ +const CHILD_TIMEOUT_MS = 20_000; + function runCli( args: string[], env: NodeJS.ProcessEnv = {}, @@ -108,11 +119,20 @@ function runCli( stdio: ['ignore', 'pipe', 'pipe'], }, ); + running.add(child); let stdout = ''; let stderr = ''; + const timer = setTimeout(() => { + stderr += `\nkilled after ${CHILD_TIMEOUT_MS / 1000}s`; + child.kill('SIGKILL'); + }, CHILD_TIMEOUT_MS); child.stdout.on('data', (chunk) => (stdout += chunk)); child.stderr.on('data', (chunk) => (stderr += chunk)); - child.on('close', (code) => resolve({ code, stdout, stderr })); + child.on('close', (code) => { + clearTimeout(timer); + running.delete(child); + resolve({ code, stdout, stderr }); + }); }); } From 6abbf18c417f8a1c99758441b83f9cc1365b33a2 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Mon, 16 Nov 2026 14:10:04 -0600 Subject: [PATCH 32/32] chore: drop scratch PR body from the branch .scratch/job-320/pr-body.md was working text for the PR description and was never meant to be committed; it also failed oxfmt --check in Lint. --- .scratch/job-320/pr-body.md | 220 ------------------------------------ 1 file changed, 220 deletions(-) delete mode 100644 .scratch/job-320/pr-body.md diff --git a/.scratch/job-320/pr-body.md b/.scratch/job-320/pr-body.md deleted file mode 100644 index 20e4d26f..00000000 --- a/.scratch/job-320/pr-body.md +++ /dev/null @@ -1,220 +0,0 @@ -# feat: run resource commands with an API key - -> Draft. Suggested title: `feat: run resource commands with an API key (unclaimed environments, WORKOS_API_KEY, --api-key)` - -## Why - -An agent holding a one-shot environment from `workos env provision` (or the installer) could only use `workos api`. Every resource command (`workos organization`, `workos user`, `workos role`, …) failed with "uses your WorkOS dashboard session and does not accept API keys", because none of them can authenticate before an environment is claimed. Clerk's equivalent commands work before claiming. This PR makes them work with an API key. - -## What changed - -- **One seam picks the credential.** `resolveEnvScopedAuth()` in `src/lib/dashboard-operation.ts` asks `src/lib/resource-auth.ts` whether an API key applies. If none does, the existing session path runs unchanged: `requireCommandToken()` plus `resolveEnvironmentTarget()`. -- **REST adapters return the dashboard data shape.** On the API-key path, `executeDashboardOperation()` sends each catalog operation to a REST adapter in `src/lib/api-key-operations/`. The adapter calls the WorkOS REST API with the key and returns the same data shape the dashboard operation returns, using only the fields that operation's document selects. Each command's existing `--json` shaper then runs as before, so keys, casing and shapes match by construction. Enum casing goes through the same `enumOut()` on both paths. -- **No REST source means `null`.** A field REST has no source for comes back `null` and is never invented. Each one is listed in `src/lib/api-key-operations/known-gaps.ts`. -- **Missing REST endpoints fail with a structured error.** A command or input with no REST equivalent exits with `{"error":{"code":"api_key_unsupported","message":"…what's missing…"}}` before any write. -- **`--api-key` is now accepted** on the resource command groups. It's the same flag name and the same `resolveOptionalApiKey()` resolution that `workos api` and the still-REST commands use. It's registered in `help-json.ts` too. -- **The copy no longer says resource commands reject API keys.** `authRequiredApiKeySet` and `refreshFailedApiKeySet` are now in practice shown only by the account commands. They say the command manages your dashboard account and needs a login, and that resource commands such as `workos organization` and `workos user` run with the API key. No internal terms appear in the copy (checked against `LEAK_PATTERN`). -- **Docs** (README, CLAUDE.md) describe the new rule. - -### Commands gated on the dashboard session, and what each does now - -Every command below reached `requireCommandToken()`, either directly or through `runEnvScopedOperation` / `runTeamScopedOperation`. - -**Environment-scoped resource commands now run on REST with a key:** - -| Command | Subcommands on the API-key path | -| --- | --- | -| `organization` | create, update, get, list, delete | -| `user` | get, list, update, delete | -| `role` | list, get, create, update, delete, set-permissions, add-permission, remove-permission (with or without `--org`) | -| `permission` | list, get, create, update, delete | -| `membership` | list (`--user` / `--org`), get, create, update, delete, deactivate, reactivate | -| `invitation` | list (incl. `--org`), get, send, revoke, resend | -| `session` | list, revoke | -| `event` | list | -| `feature-flag` | list, get, enable, disable, add-target, remove-target | -| `org-domain` | get, create, verify, delete | -| `portal` | generate-link | -| `webhook` | list, create, delete | -| `config` | redirect add, cors add, homepage-url set | -| `authkit` | redirect-uris list/set, cors get/set | - -**No REST equivalent, so they fail with `api_key_unsupported` on the key path:** -- `authkit logout-uris list|set`: sign-out redirect URIs have no WorkOS API endpoint. -- `branding get|set`: branding images have no WorkOS API endpoint. - -**Account commands, session-only (no REST equivalent; they ignore the key):** `team` (members, invite, change-role, remove, resend-invite, update, set-mfa), `project` (create, rename, list), `environment` (list, use, create, rename), `whoami`. - -## Precedence rule - -The first match wins: - -1. `--api-key ` -2. `WORKOS_API_KEY` -3. The active profile's stored key, **only if that profile is an unclaimed environment.** A dashboard session can't reach an unclaimed environment, so its key is the only credential that works there. -4. Otherwise, the existing dashboard-session path, unchanged. - -Consequences: -- A **claimed** profile's stored key never switches the path. A signed-in user keeps today's behavior unless they pass a key explicitly. A signed-out user with a claimed profile still gets exit 4, as before. -- With a key, **`--environment-id` is refused** (`invalid_argument`). The key decides the environment, and silently ignoring the flag could act on the wrong one. -- `environment create|rename` are environment-scoped dashboard operations behind an account command, so they stay session-only even with a key set. - -## Known differences on the API-key path - -Keys and shapes are identical on both paths. These values differ because REST has no source for them (all are `null` on the key path, and all are in `API_KEY_ACCEPTED` / `API_KEY_NULL_FIELDS`): - -| Field | Reason | -| --- | --- | -| `organization.usersCount` | REST organizations carry no member count | -| `user.sessionCount`, `user.hasPassword` | not in REST users | -| `user.emailVerifiedAt` | REST has only an `email_verified` boolean. The human view still shows Verified: Yes from it. | -| `user.authenticationFactors[].lastVerifiedAt` | REST auth factors carry no last-verified time | -| `membership.type` | REST memberships carry no type | -| `event.updatedAt` | REST events carry only a creation time | -| `feature-flag` get: `accessType`, `organizationTargets`, `userTargets` | the REST flag endpoints expose neither | -| `org-domain`: `subdomain`, `domainCaptureEnabled` | REST doesn't return either (the dashboard derives `subdomain` with a public-suffix parser this CLI doesn't ship) | -| `portal`: `id`, `state`, `expiresAt` | REST `generate_link` returns only the URL | -| `session.impersonator` id/firstName/lastName | REST names an impersonator by email only | -| `session.provider` for OAuth sign-ins | REST reports every OAuth provider as plain `oauth`, so `GoogleOAuth` etc. can't be named | -| `config homepage-url set`: `applicationId` | REST never exposes the AuthKit application ID | - -Some fields are filled with extra REST reads rather than nulled. They are bounded per page and memoized per call: -- user `identities`: the user's memberships, with role IDs and names resolved from slugs. An organization's own role wins over an environment role with the same slug, as on the dashboard; -- user get `authenticationFactors`; -- organization names on invitations and sessions. - -Behavioral differences (not output fields): -- **Search filters are exact matches.** `organization list --domain`, `user list --email` and `invitation list --email` use REST's exact-match filters (domain, email). The dashboard does a search. -- **New domains start pending, with their DNS challenge.** `org-domain create` on REST creates the domain `pending` (it needs DNS verification); the dashboard adds it verified. The output reports the real state, and `verificationContent` carries the TXT record value to publish. On every domain read (`organization list/get`, `org-domain get/create/verify`) it's built exactly as the dashboard builds it: `=`, prefix defaulting to `verification_token`, null without a token. -- **Full lists never truncate silently.** A full-list read stops at 5,000 records and fails with `list_too_long` rather than act on a partial list. -- **Order, full lists and statuses are explicit.** Every key-path list sends an order (your `--order`, else `desc`, which returns the same newest-first rows as REST's `normal` default), so `after` is always the next page. Reads that must return a complete list (permissions, a user's memberships, redirect URIs, CORS origins) follow it to the end, and `config redirect add` still refuses to merge over more than one page of URIs. Membership listings and `membership delete` include every status (`active,inactive,pending`), so a deactivated membership is listed and can be deleted, as on the dashboard. -- **Membership roles match the dashboard's values.** REST names roles by slug; the dashboard reports them by role ID on membership records (`membership list --user`, `get`, `update`) and by display name on `membership list --org`. The key path resolves each slug through the organization's roles (then the environment's) and prints the same value. -- **`membership list --org` pages over memberships.** Its cursors are membership IDs on the key path and user IDs on the session path. They're opaque either way, and each path accepts its own cursors. -- **`feature-flag add-target|remove-target` call REST's target endpoints directly.** REST can't list a flag's targets, so there's no read-merge-write, and remove-target can't pre-check that the target exists. -- **Redirect URIs and CORS have limits on REST.** - - `authkit redirect-uris set` diffs the list. It creates what's missing **first** and only then deletes what's dropped, so a rejected URI or a failed request never leaves fewer working URIs (at worst an extra one remains). - - `--default` is accepted only for a URI that is already the default, because REST can't choose one. - - `authkit cors set` can't remove origins, because REST has no delete. - - `--dry-run` is refused, because REST has no validate-only mode. - - All of these fail before any write. -- **Role permission changes are verified.** If the permissions replace returns 404, or the server afterwards holds anything other than the requested permissions, the command fails (`not_found` / `unexpected_result`) instead of reporting the requested list. - -Enum mapping is taken from the vendored catalog's enum types, so both paths print the same value: -- **`session list` `provider`.** The session path emits the dashboard's `SessionProvider` value raw (`Password`, not normalized; this is pre-existing and pinned in the json-contract snapshot). The key path maps REST's `auth_method` to the same values: `password` → `Password`, `magic_code` → `MagicAuth`, `sso` → `SingleSignOn`, `passkey`, `impersonation`, `cross_app_auth`, `external_auth`, `migrated_session` likewise. `oauth` and `unknown` have no single dashboard value and come back `null` (a documented gap). Running `enumOut` on both paths would be the cleaner fix, but it changes signed-in output, so it's left for a follow-up. -- **`webhook` `state`.** REST `enabled`/`disabled` map to the dashboard's `Active`/`InActive`, so both paths print `active` / `in_active`. - -## Parity results - -**Offline (`src/commands/api-key-parity.spec.ts`, 24 parity tests plus 4 tests of the gate itself, all pass).** -- Every list and get command runs the real handler on both paths against the same entity: - - organization, user, role (env and `--org`), permission, invitation (env and `--org`), membership (`--user`, `--org`, get), session, webhook, event, feature-flag, org-domain; - - plus portal generate-link; - - plus the edge cases: disabled webhooks (`InActive` vs `disabled`), every mapped session provider and an unnamed OAuth one, and an organization role shadowing an environment role's slug. -- The dashboard side is fed real dashboard casing (`Verified`, `Active`, `Environment`, metadata as `{key,value}` pairs). -- The REST side is fed real REST responses: snake_case keys, `verified`, `EnvironmentRole`, `enabled`, `password`, metadata as an object, plus the internal fields the shapers must drop (`stripe_customer_id`, `secret`, invitation `token`). -- The envelope and pagination must be deep-equal, and each entity must pass the shared gate below. Each test also names the gaps its fixture exercises, so it can't pass vacuously. - -**One gate, offline and live.** Both use `apiKeyParityDiffs()` from `known-gaps.ts`. Every object must have the same keys on both sides, arrays the same length, and every leaf the same value. The only exception is a leaf path listed in `API_KEY_NULL_FIELDS` (for example `user.authenticationFactors[].lastVerifiedAt`, `session.impersonator.id`), which may be `null` on the key side. An element that loses its keys, an object that goes null as a whole, a lost ID or email, or a casing-only difference all fail. - -**Live (`scripts/parity-smoke.ts --api-key`, new mode).** It runs each command's list/get on this branch twice, with the session and with `WORKOS_API_KEY`, and judges each entity with the same gate. It needs no `../main`. A check counts only when both sides returned real entities (rows that each carry their ID, or a non-empty entity), and a run that compared no entity at all exits 1. The session side is proven, not assumed: `whoami` (session-only) must succeed without a key, and every session-side command is pinned to that environment with `--environment-id`. The CLI refuses `--environment-id` whenever any API key applies, including an unclaimed profile's stored key, so the session side can't quietly run on REST and compare REST with itself. The default branch-vs-main mode also changed: the branch's resource commands now take the key path whenever `WORKOS_API_KEY` is set, so they run without it and pinned to the session's environment, and an empty `WORKOS_API_KEY` counts as unset in both modes. `--api-key` mode also proves the key side is really on the key (the CLI must refuse `--environment-id` there) before comparing. **Not run for this PR:** the session side needs a real `workos auth login`, and this work was kept away from the real `~/.workos` and Keychain. With no login it exits 2 before comparing anything (checked against a scratch HOME). Running it is a good pre-merge check: - -``` -workos auth login -export WORKOS_API_KEY=sk_test_… # same environment the session targets -bun run scripts/parity-smoke.ts --api-key -``` - -## Real-command proof (from source, fresh unclaimed environment) - -Setup: -- Run from the worktree with `HOME=$PWD/.scratch/home`, `--insecure-storage`, and `bun --preload ./src/test/force-insecure-storage.ts src/bin.ts …`. That's the preload the integration specs use, so startup never touches the Keychain. -- `WORKOS_TELEMETRY=false`, no `WORKOS_API_KEY`, and each command wrapped in `timeout 120`. -- The scratch home was deleted afterwards. Secrets are redacted. - -``` -$ workos env provision --insecure-storage --json -{"status":"ok","message":"Environment provisioned","data":{"name":"unclaimed","type":"unclaimed","active":true,"apiKey":"sk_…REDACTED","clientId":"client_01M6SH09VVW8FK83WABDPS1YF8","claimToken":"…REDACTED","authkitDomain":"vast-sonnet-18-sandbox.authkit.app"}} -exit=0 - -$ workos organization list --json --insecure-storage -{"organizations":[{"id":"org_01M6SH09P7HB581EQQQKQYME31","name":"Test Organization","createdAt":"2026-11-06T22:52:22.375Z","usersCount":null,"allowProfilesOutsideOrganization":false,"externalId":null,"domains":[{"id":"org_domain_01M6SH09Q1BJCH2T5GEF90HRT2","domain":"example.com","state":"verified"}],"metadata":{}}],"pagination":{"before":null,"after":null}} -exit=0 - -$ workos user list --json --insecure-storage -{"users":[],"pagination":{"before":null,"after":null}} -exit=0 -``` - -Both list commands ran with no login, using the unclaimed profile's key. Before this change, both would exit 4 with "does not accept API keys". `usersCount: null` is the documented gap. The user list is empty because the environment is brand new. - -I also checked against a local fake API (`WORKOS_API_URL=http://127.0.0.1:`, no external network): -- `--api-key` reaches the request as the bearer. -- `--api-key` with `--environment-id` exits 1 with `invalid_argument`. -- `branding get` with a key exits 1 with `api_key_unsupported`. -- `team members` with a key and no login still exits 4, with the reworded copy. -- `organization list --help` lists `--api-key`. - -## Overlap with #269 and #270 - -- **#269 (`nicknisi/ax-agent-copy`, open).** - - Overlapping files: `src/lib/command-auth.ts`, `src/utils/recovery-hints.ts`, `src/bin.ts` and `README.md`. This PR doesn't touch `recovery-hints.ts`. - - `git merge-tree` shows one textual conflict, in `src/lib/command-auth.spec.ts`: #269 adds a test next to one this PR renames. It's easy to resolve. - - Semantic follow-up: #269 adds `dashboardSessionRecovery`. Its second hint ("make the same request with an API key … through the API command") and its test asserting no "set WORKOS_API_KEY" hint were written when resource commands rejected keys. Once both land: - - resource commands reach that hint only when no key is set, and setting `WORKOS_API_KEY` or passing `--api-key` now fixes them; - - the account commands still need the session. - - So the hint should be reworded for whichever PR merges second. -- **#270 (`fix/account-plane-forbidden-and-slim-team-query`).** It touches `command-auth.ts` (the `forbidden` copy only). It merges cleanly with this branch. This branch is cut from `origin/main`, not from #270, so #270's own changes (the slim team-environments query, sanitized server error codes, and their tests in `no-graphql-leak.spec.ts`, `dashboard-graphql.spec.ts` and `environment-target.spec.ts`) are not here. They land with #270; this PR deletes none of them. #270 also carries the slim `teamProjectsV2` query used by signed-in environment resolution, so whichever of the two PRs lands second rebases onto the other. -- Neither branch was touched. - -## Security read: key scope - -**The keys are full-scope.** The one-shot keys from `workos env provision` and the installer are full-scope secret keys for that (sandbox) environment. `WORKOS_API_KEY` / `--api-key` can be any key, including a production `sk_live_…`. - -**What an agent holding one can now do through these commands:** -- **Organizations:** create, update, and delete. Delete cascades to the org's connections, directories and users. -- **Org domains:** add, verify and delete. Domain-based sign-in and capture stop working for a deleted domain. -- **Users:** read, including email, name, metadata and memberships. Update them, including changing a user's email. Delete them. -- **Sessions:** list and revoke. -- **RBAC:** - - create, update and delete organization roles; - - change any role's permissions, including environment roles; - - create, update and delete permissions. -- **Memberships:** add a user to an organization with a role, change roles, deactivate, reactivate, delete. -- **Invitations:** send (real email), revoke, resend. -- **Webhooks:** create and delete endpoints. Creating one aimed at an outside URL streams future events there. -- **Events:** read the event feed, which includes user payloads. -- **Feature flags:** enable, disable, add and remove targets. -- **Admin Portal:** generate setup links, which grant SSO/Directory Sync setup access for an organization. -- **AuthKit config:** add redirect URIs and CORS origins, replace the redirect-URI list (deleting unlisted URIs), set the homepage URL. Adding a redirect URI for an attacker's domain is a classic way to steal sign-ins in a real app. - -**What it could already do with `workos api`:** all of the above. `workos api` makes any authenticated REST request with the same key, so this PR adds no new capability. It adds convenience and discoverability. The real difference is confirmation: -- `workos api` requires `--yes` for **every** mutating request in agent, CI and JSON mode. -- The resource commands keep their own per-command posture: - - destructive commands (deletes, revokes) need `--yes` non-interactively; - - privilege changes (role/permission create and update, membership update and deactivate) need `--yes` non-interactively; - - other writes need no `--yes`: org create/update, user update, invitation send/resend, webhook create, org-domain create/verify, portal links, flag enable/disable/targets, and the redirect/CORS/homepage config. -- That posture was already there for signed-in agents. What's new is that a key alone now reaches it. - -**Recommendations** (not implemented; each needs a product call): -1. **On the API-key path in agent/CI mode, require `--yes` for every mutation,** matching `workos api`. At minimum, require it for the security-sensitive non-destructive writes: redirect URI / CORS / homepage changes, webhook create, portal link generation, invitation send. This is cheap to add in `resolveEnvScopedAuth()` / the adapters' write paths. -2. **Don't refuse destructive commands on an unclaimed key.** An unclaimed environment is a disposable sandbox the agent created itself. Blocking deletes there removes legitimate cleanup without stopping anything `workos api --yes` can already do. -3. **Treat live keys more strictly.** An `sk_live_` key passed via `WORKOS_API_KEY` or `--api-key` is the risky case. Consider always requiring `--yes` (or an extra confirmation) for mutations with a live key. -4. **Tell signed-in users when an exported key takes over.** A signed-in developer who has `WORKOS_API_KEY` exported for app work (common) now runs resource commands against that key's environment instead of their profile's. That follows the brief's rule (an explicit key wins), but it can surprise people. A one-line human-mode stderr notice would help, something like "Using WORKOS_API_KEY; unset it to use your dashboard login". Note that the shipped binary doesn't auto-load `.env` files (`--no-compile-autoload-dotenv`); running from source with Bun does. -5. **Prefer `WORKOS_API_KEY` over `--api-key` in docs for agents.** A flag value shows up in shell history and process lists. This is the same caveat as for the existing REST commands. - -## Tests - -- `src/commands/api-key-auth.spec.ts` covers: - - path choice: unclaimed profile, `WORKOS_API_KEY` over a session, `--api-key` over both, a signed-in user with a claimed profile's stored key staying on the session, the `--environment-id` refusal, account commands staying on the session; - - the unsupported errors and their leak check; - - the REST requests and outputs for every command's mutations; - - not-found and 401 handling. -- `src/commands/api-key-parity.spec.ts` covers JSON parity, described above. -- `src/commands/api-key-flag.integration.spec.ts` drives the real CLI (subprocess, temp HOME, local HTTP stub) to check `--api-key` > `WORKOS_API_KEY` > unclaimed profile through actual yargs parsing, and the `--environment-id` refusal. -- `src/lib/command-auth.spec.ts` covers: - - the `resolveResourceApiKey()` precedence, against the real file-backed config store; - - the updated copy. Two existing tests were renamed and updated, because their assertion that the copy says "does not accept API keys" is now the bug. -- Every new or changed test name contains "with an API key". -- `bunx vitest run src/lib/command-auth.spec.ts src/commands -t "with an API key"`: 69 passed. -- Existing suites for every touched command, plus `help-json`, `catalog` (incl. `no-graphql-leak`), `environment-target` and the bin integration specs: 1,323 passed. -- `bun run typecheck`: clean.