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` | diff --git a/scripts/parity-smoke.ts b/scripts/parity-smoke.ts index 7f85bab6..7e138c15 100644 --- a/scripts/parity-smoke.ts +++ b/scripts/parity-smoke.ts @@ -45,12 +45,27 @@ * 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). `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 + * * 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, 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'); @@ -62,6 +77,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 +87,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}")`); @@ -99,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[] } { @@ -118,11 +136,50 @@ interface RunResult { stderr: string; } const COMMAND_TIMEOUT_MS = 60_000; -function run(dir: string, cliArgs: string[]): Promise { + +/** + * 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 (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 = ''; @@ -158,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 --------------------------------------------------------- @@ -484,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 ------------------------------------------------------------------- @@ -941,14 +1010,328 @@ 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'); push('NEW', c.label, 'PASS', 'valid JSON'); } +// --- API-key mode: dashboard session vs API key, same branch ------------------------ +/** + * 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 }; + +/** Entities actually compared field by field; a run that compared none proves nothing and fails. */ +let comparedEntities = 0; + +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, '--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('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; + 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; +} + +/** + * 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) { + 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]; + // 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) { + 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!]); + diffs.push(...apiKeyParityDiffs(c.cmd, row, other).map((d) => `${row?.[c.idKey!]}: ${d}`)); + } + } else { + // 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; + if (!diffs.length && !empty) comparedEntities += rows; + 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 apart from documented null gaps`, + ); + 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); + } + await pinSessionEnvironment(); + await proveKeySide(); + console.log(` session pinned to environment ${sessionEnvironmentId}; key side confirmed on the key\n`); + + 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}`); + } + 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; + 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${blocked ? C.red : C.green}${rows.filter((r) => r.status === 'PASS').length} pass, ${failed} fail, ${auth} auth, ${comparedEntities} entities compared${C.reset}`, + ); + process.exit(blocked ? 1 : 0); +} + +if (API_KEY_MODE) await runApiKeyMode(); + // --- run ------------------------------------------------------------------------- console.log(`parity-smoke branch=${BRANCH_DIR}`); console.log( @@ -963,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 diff --git a/src/bin.ts b/src/bin.ts index c5e95920..abdfdafb 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): void { + 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/api-key-auth.spec.ts b/src/commands/api-key-auth.spec.ts new file mode 100644 index 00000000..ebcb0fc9 --- /dev/null +++ b/src/commands/api-key-auth.spec.ts @@ -0,0 +1,964 @@ +/** + * 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 { runPermissionList, runPermissionGet, runPermissionCreate, runPermissionUpdate, runPermissionDelete } = + await import('./permission.js'); +const { runMembershipList, runMembershipCreate, runMembershipUpdate, runMembershipDelete, runMembershipDeactivate } = + await import('./membership.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, runAuthkitRedirectUrisList, 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('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' } }, + }); + + 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', + }); + // 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, + 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 })); + + // 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('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) => ({ + ...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': { + 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' }, + }); + // 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(); + }); + + 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', + verification_prefix: 'workos-verify', + verification_token: 'tok_bar', + }; + 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', + }); + // 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', + verificationContent: 'workos-verify=tok_bar', + organizationId: 'org_1', + }, + }); + expect(verified).toMatchObject({ + domain: { id: 'dom_2', domain: 'bar.com', verificationContent: 'workos-verify=tok_bar' }, + }); + 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; + let origins = [{ object: 'cors_origin', id: 'cors_1', origin: 'https://a.example.com' }]; + 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(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({ + 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); + // 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 () => { + 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-flag.integration.spec.ts b/src/commands/api-key-flag.integration.spec.ts new file mode 100644 index 00000000..14f40ed1 --- /dev/null +++ b/src/commands/api-key-flag.integration.spec.ts @@ -0,0 +1,175 @@ +/** + * 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, 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'; +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 () => { + // Drop any connection a stray child still holds, so close() can't hang. + server.closeAllConnections(); + 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(() => { + // 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 = {}, +): 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'], + }, + ); + 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) => { + clearTimeout(timer); + running.delete(child); + 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); +}); diff --git a/src/commands/api-key-parity.spec.ts b/src/commands/api-key-parity.spec.ts new file mode 100644 index 00000000..d7e7dad8 --- /dev/null +++ b/src/commands/api-key-parity.spec.ts @@ -0,0 +1,1043 @@ +/** + * 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, 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'); +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, runOrgDomainVerify } = 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' }, +}; + +// The dashboard's membership record carries role IDs as plain strings +// (`UserlandUserOrganizationMembership.role` / `.roles`). +const GQL_MEMBERSHIP = { + id: 'om_1', + type: 'Manual', + status: 'Active', + organizationId: 'org_1', + userlandUserId: 'user_1', + directoryUserId: null, + role: 'role_member', + roles: ['role_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; + +/** 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: 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, 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(); + } +} + +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, ['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, ['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, ['sessionCount', 'hasPassword', '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, [ + '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] } }; + + 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 () => { + expectParity( + 'membership', + await viaSession( + () => ({ userlandUserOrganizationMemberships: { organizationMemberships: [GQL_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'], + ); + expectParity( + 'membership', + await viaSession( + () => ({ userlandUserOrganizationMembership: GQL_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( + () => ({ + organization: { + userlandUsers: { + data: [ + { + id: 'user_1', + // 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' }, + }, + }, + }), + () => runMembershipList({ org: 'org_1' }), + ); + const apiKey = await viaApiKey( + { + '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' }), + ); + 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('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 } } } }), + () => runEventList({ events: ['user.created'] }), + ); + const apiKey = await viaApiKey({ 'GET /events': restList([REST_EVENT], 'event_0') }, () => + runEventList({ events: ['user.created'] }), + ); + expectParity('event', session, apiKey, ['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')), + ['accessType', 'organizationTargets', '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', {})); + // 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 () => { + 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, ['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('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, { + ...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/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/commands/feature-flag.ts b/src/commands/feature-flag.ts index 8a5aa76e..376e456a 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); @@ -235,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); @@ -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/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/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/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/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/__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/app-config.ts b/src/lib/api-key-operations/app-config.ts new file mode 100644 index 00000000..7cede6cf --- /dev/null +++ b/src/lib/api-key-operations/app-config.ts @@ -0,0 +1,138 @@ +/** + * 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 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. + */ + +import { + type ApiKeyContext, + type ApiKeyOperation, + encode, + exitApiKeyUnsupported, + listAll, + listEnvelope, + num, + restOrder, + 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) { + // 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) ?? 100, + before: str(variables.before), + after: str(variables.after), + order: restOrder(), + }, + }); + 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'); + } + + // 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)}` }); + } + } + + 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/context.ts b/src/lib/api-key-operations/context.ts new file mode 100644 index 00000000..ea5e4ce4 --- /dev/null +++ b/src/lib/api-key-operations/context.ts @@ -0,0 +1,154 @@ +/** + * 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; + } +} + +/** 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 { + 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; hitting it is an error. */ +const FULL_LIST_MAX_PAGES = 50; + +/** + * Read every page of a REST list. Used where the dashboard operation returns a + * 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, + 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: { order: 'desc', ...params, limit: FULL_LIST_PAGE_SIZE, ...(after ? { after } : {}) }, + }); + items.push(...(result?.data ?? [])); + after = result?.list_metadata?.after ?? undefined; + if (!after) 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.', + }); +} + +/** + * `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 { + 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..4778218f --- /dev/null +++ b/src/lib/api-key-operations/index.ts @@ -0,0 +1,103 @@ +/** + * 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'; +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, + ...userOperations, + ...membershipOperations, + ...rbacOperations, + ...platformOperations, + ...appConfigOperations, +}; + +/** + * 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', +}; + +/** 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' }, + }); + } + return handleApiError(error); + } +} + +export { exitApiKeyUnsupported, apiKeyUnsupportedMessage } from './context.js'; +export { changeFlagTarget } from './platform.js'; +export { setHomepageUrl } from './app-config.js'; 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..5b24709f --- /dev/null +++ b/src/lib/api-key-operations/known-gaps.ts @@ -0,0 +1,102 @@ +/** + * Output fields the API-key path returns as `null` because the WorkOS REST API + * 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`, 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[].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.', + '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.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.', + 'portal.expiresAt': 'REST generate_link returns only the link URL.', + '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. + * + * 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): 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) { + 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; +} diff --git a/src/lib/api-key-operations/lookups.ts b/src/lib/api-key-operations/lookups.ts new file mode 100644 index 00000000..0ef3b9e7 --- /dev/null +++ b/src/lib/api-key-operations/lookups.ts @@ -0,0 +1,143 @@ +/** + * 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 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); + // 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; +} + +/** + * 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 = orNull( + ctx.request<{ data: RestRole[] }>({ + method: 'GET', + path: `/authorization/organizations/${encode(organizationId)}/roles`, + }), + ).then((result) => (result ? (result.data ?? []) : null)); + memo.organizationRoles.set(organizationId, roles); + } + return roles; +} + +/** + * 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); + 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. */ +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[] = []; + 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; +} + +/** + * 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, + statuses: ALL_MEMBERSHIP_STATUSES, + }); +} diff --git a/src/lib/api-key-operations/memberships.ts b/src/lib/api-key-operations/memberships.ts new file mode 100644 index 00000000..9d2299eb --- /dev/null +++ b/src/lib/api-key-operations/memberships.ts @@ -0,0 +1,380 @@ +/** + * 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. 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`. + */ + +import type { WorkOSListResponse } from '../workos-api.js'; +import { + type ApiKeyContext, + type ApiKeyOperation, + encode, + listEnvelope, + num, + orNull, + restOrder, + str, +} from './context.js'; +import { + ALL_MEMBERSHIP_STATUSES, + findRole, + membershipsForUser, + organizationName, + type RestMembership, + type RestRole, +} 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; +} + +/** + * 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, + status: membership.status ?? null, + organizationId: membership.organization_id ?? null, + userlandUserId: membership.user_id ?? null, + directoryUserId: null, + role: role?.id ?? null, + roles: roles.map((entry) => entry.id), + createdAt: membership.created_at ?? null, + updatedAt: membership.updated_at ?? null, + }; +} + +/** + * 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 { + 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, + order: restOrder(), + }, + }); +} + +/** 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: await Promise.all(memberships.map((membership) => membershipNode(ctx, membership))), + }, + }; + }, + + 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, + statuses: ALL_MEMBERSHIP_STATUSES, + limit: num(variables.limit), + before: str(variables.before), + after: str(variables.after), + order: restOrder(variables.order), + }, + }); + // 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 ? await membershipNode(ctx, 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: await membershipNode(ctx, updated), + }, + }; + }, + + async removeMemberFromOrganization(variables, ctx) { + const input = (variables.input ?? {}) as { organizationId?: string; userlandUserId?: string }; + // 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 = + membershipId && + (await orNull( + ctx + .request({ method: 'DELETE', path: `/user_management/organization_memberships/${encode(membershipId)}` }) + .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.` }); +} diff --git a/src/lib/api-key-operations/organizations.ts b/src/lib/api-key-operations/organizations.ts new file mode 100644 index 00000000..cfdca179 --- /dev/null +++ b/src/lib/api-key-operations/organizations.ts @@ -0,0 +1,218 @@ +/** + * 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` 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'; +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 })); +} + +/** 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: verificationContent(domain), + 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 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', + domains: created.map((d) => ({ + id: d.id, + state: d.state ?? null, + domain: d.domain, + verificationStrategy: d.verification_strategy ?? null, + verificationContent: verificationContent(d), + })), + }, + }; + }, + + 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/api-key-operations/platform.ts b/src/lib/api-key-operations/platform.ts new file mode 100644 index 00000000..817bd1e0 --- /dev/null +++ b/src/lib/api-key-operations/platform.ts @@ -0,0 +1,277 @@ +/** + * 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 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 WEBHOOK_STATE[status] ?? 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), + order: restOrder(), + }, + }); + 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; +} diff --git a/src/lib/api-key-operations/rbac.ts b/src/lib/api-key-operations/rbac.ts new file mode 100644 index 00000000..33401158 --- /dev/null +++ b/src/lib/api-key-operations/rbac.ts @@ -0,0 +1,269 @@ +/** + * 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, 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 { + 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 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)}` + : `/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; + + const patched = await orNotFound( + ctx.request({ + method: 'PATCH', + path: rolePath(ref), + body: { + ...(input.name !== undefined ? { name: input.name } : {}), + ...(input.description !== undefined ? { description: input.description } : {}), + }, + }), + ); + if (patched === NOT_FOUND) return notFound; + let role: RestRole | null = patched; + if (input.permissions) { + 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) } }; + }, + + 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 }, + }; + }, +}; diff --git a/src/lib/api-key-operations/users.ts b/src/lib/api-key-operations/users.ts new file mode 100644 index 00000000..d328efeb --- /dev/null +++ b/src/lib/api-key-operations/users.ts @@ -0,0 +1,272 @@ +/** + * 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`, a session impersonator's id/name, and an OAuth session's + * provider. + */ + +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_method` → the dashboard's `SessionProvider` value (per the + * vendored catalog), which the session shape passes through as-is. REST + * reports every OAuth provider as plain `oauth`, so those (and `unknown`) have + * no dashboard equivalent and come back null. + */ +const SESSION_PROVIDER: 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 { + return method ? (SESSION_PROVIDER[method] ?? null) : null; +} + +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), + order: restOrder(), + }, + }), + ); + 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 }; + }, +}; 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',