diff --git a/packages/sim-cli/src/auth/oauth-flow.ts b/packages/sim-cli/src/auth/oauth-flow.ts
index fe6a26e9d64..c9cf7aafc5e 100644
--- a/packages/sim-cli/src/auth/oauth-flow.ts
+++ b/packages/sim-cli/src/auth/oauth-flow.ts
@@ -264,10 +264,12 @@ async function readTokens(
try {
body = JSON.parse(raw) as TokenResponse
} catch {
- throw new SimApiError(
+ const error = new SimApiError(
`The authorization server answered HTTP ${response.status} with a non-JSON body.`,
response.status
)
+ error.nonJsonBody = true
+ throw error
}
if (!response.ok || typeof body.error === 'string') {
throw new OAuthTokenError(
diff --git a/packages/sim-cli/src/commands/auth.ts b/packages/sim-cli/src/commands/auth.ts
index 2734ebfd383..9eb273d679a 100644
--- a/packages/sim-cli/src/commands/auth.ts
+++ b/packages/sim-cli/src/commands/auth.ts
@@ -949,6 +949,24 @@ function credentialFactsFrom(response: unknown): CredentialFacts | null {
/** Definitive profile refusals, including a workspace the credential cannot access. */
const PROFILE_REJECTION_STATUSES = new Set([401, 403, 404])
+/**
+ * A failure whose body was not JSON most likely came from a proxy, VPN, or WAF in front of Sim,
+ * so it neither accepts nor rejects the credential.
+ */
+function blockedBeforeSim(
+ error: SimApiError,
+ authenticated: boolean | null,
+ facts: CredentialFacts
+): Verification {
+ return {
+ status: 'unreachable',
+ authenticated,
+ workspace: null,
+ ...facts,
+ detail: `blocked before reaching Sim; check your network or VPN (${error.message})`,
+ }
+}
+
/**
* Exit 1 reports a definitive refusal or missing credential. Exit 2 means the
* profile check could not finish: retrying or configuring a workspace may help.
@@ -1001,6 +1019,7 @@ async function verifyProfile(
} catch (error) {
if (!(error instanceof SimApiError)) throw error
if (error.status === 401 || error.status === 403) {
+ if (error.nonJsonBody) return blockedBeforeSim(error, authenticated, facts)
return {
status: 'rejected',
authenticated: false,
@@ -1037,6 +1056,9 @@ async function verifyProfile(
}
} catch (error) {
if (!(error instanceof SimApiError)) throw error
+ if (error.nonJsonBody && PROFILE_REJECTION_STATUSES.has(error.status)) {
+ return blockedBeforeSim(error, authenticated, facts)
+ }
return {
status: PROFILE_REJECTION_STATUSES.has(error.status) ? 'rejected' : 'unreachable',
authenticated: error.status === 401 ? false : authenticated,
diff --git a/packages/sim-cli/src/commands/whoami-edge-refusal.test.ts b/packages/sim-cli/src/commands/whoami-edge-refusal.test.ts
new file mode 100644
index 00000000000..36ae8a12be9
--- /dev/null
+++ b/packages/sim-cli/src/commands/whoami-edge-refusal.test.ts
@@ -0,0 +1,140 @@
+import { spawn } from 'node:child_process'
+import { mkdtempSync, rmSync } from 'node:fs'
+import { createServer, type Server } from 'node:http'
+import type { AddressInfo } from 'node:net'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+import { writeConfigProfile, writeCredentialsProfile } from '../config/profile'
+
+/** The page an AWS load balancer's WAF serves when it blocks a request before it reaches Sim. */
+function edgeRefusal(status: number): string {
+ return `
+
${status}
+
+${status}
+
awselb/2.0
+
+`
+}
+
+interface WhoamiRun {
+ exitCode: number | null
+ stdout: string
+}
+
+describe('whoami behind an edge that answers HTML', () => {
+ let server: Server
+ let endpoint: string
+ let dir: string
+ /** When set, Sim answers the credential metadata read and the edge blocks only the rest. */
+ let metaPassesEdge = false
+ let edgeStatus = 403
+
+ beforeAll(async () => {
+ server = createServer((request, response) => {
+ if (metaPassesEdge && request.url === '/api/v2/meta') {
+ response.writeHead(200, { 'content-type': 'application/json' })
+ response.end(JSON.stringify({ data: { keyType: 'personal', expiresAt: null } }))
+ return
+ }
+ response.writeHead(edgeStatus, { 'content-type': 'text/html', server: 'awselb/2.0' })
+ response.end(edgeRefusal(edgeStatus))
+ })
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
+ endpoint = `http://127.0.0.1:${(server.address() as AddressInfo).port}`
+ })
+
+ afterAll(async () => {
+ server.closeAllConnections()
+ await new Promise((resolve) => server.close(() => resolve()))
+ })
+
+ beforeEach(() => {
+ metaPassesEdge = false
+ edgeStatus = 403
+ dir = mkdtempSync(join(tmpdir(), 'sim-cli-whoami-edge-'))
+ vi.stubEnv('SIM_CONFIG_DIR', dir)
+ })
+
+ afterEach(() => {
+ rmSync(dir, { recursive: true, force: true })
+ })
+
+ /** Runs `whoami --output json` against the edge; without `apiKey` it uses the stored login. */
+ function whoami(apiKey?: string): Promise {
+ const env: NodeJS.ProcessEnv = {
+ ...process.env,
+ SIM_CONFIG_DIR: dir,
+ SIM_ENDPOINT: endpoint,
+ SIM_WORKSPACE: 'ws_1',
+ SIM_NO_UPDATE_CHECK: '1',
+ SIM_CLI_TELEMETRY_DISABLED: '1',
+ NO_PROXY: '127.0.0.1',
+ }
+ Reflect.deleteProperty(env, 'SIM_PROFILE')
+ if (apiKey) env.SIM_API_KEY = apiKey
+ else Reflect.deleteProperty(env, 'SIM_API_KEY')
+ const entrypoint = join(import.meta.dirname, '..', 'index.ts')
+ const child = spawn('bun', [entrypoint, '--output', 'json', 'whoami'], {
+ env,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ })
+ let stdout = ''
+ child.stdout.setEncoding('utf8').on('data', (chunk: string) => {
+ stdout += chunk
+ })
+ return new Promise((resolve, reject) => {
+ child.on('error', reject)
+ child.on('close', (exitCode) => resolve({ exitCode, stdout }))
+ })
+ }
+
+ function expectUnreachable(run: WhoamiRun, authenticated: boolean | null = null): void {
+ const result = JSON.parse(run.stdout)
+ expect(result.authenticated).toBe(authenticated)
+ expect(result.verification.status).toBe('unreachable')
+ expect(result.verification.detail).toContain('blocked before reaching Sim')
+ expect(run.exitCode).toBe(2)
+ }
+
+ it('reports an API key the edge blocked as unreachable, not rejected', async () => {
+ expectUnreachable(await whoami('sk-test'))
+ }, 60_000)
+
+ it('reports an API key the edge answered HTML 401 as unreachable, not rejected', async () => {
+ edgeStatus = 401
+ expectUnreachable(await whoami('sk-test'))
+ }, 60_000)
+
+ it('keeps a credential Sim accepted when the edge blocks the workspace read', async () => {
+ metaPassesEdge = true
+ expectUnreachable(await whoami('sk-test'), true)
+ }, 60_000)
+
+ it('does not blame the network when the workspace read answers an HTML 5xx', async () => {
+ metaPassesEdge = true
+ edgeStatus = 502
+ const run = await whoami('sk-test')
+ const result = JSON.parse(run.stdout)
+ expect(result.verification.status).toBe('unreachable')
+ expect(result.verification.detail).not.toContain('blocked before reaching Sim')
+ expect(run.exitCode).toBe(2)
+ }, 60_000)
+
+ it('reports an OAuth refresh the edge blocked as unreachable, not rejected', async () => {
+ writeConfigProfile('default', { endpoint })
+ writeCredentialsProfile('default', {
+ kind: 'oauth',
+ oauth: {
+ accessToken: 'expired-access',
+ refreshToken: 'stored-refresh',
+ expiresAt: 1,
+ issuer: `${endpoint}/api/auth`,
+ loginId: 'edge-test',
+ scope: 'offline_access api:read',
+ },
+ })
+ expectUnreachable(await whoami())
+ }, 60_000)
+})
diff --git a/packages/sim-cli/src/http/client.ts b/packages/sim-cli/src/http/client.ts
index b1eaba7034e..939f51b2b57 100644
--- a/packages/sim-cli/src/http/client.ts
+++ b/packages/sim-cli/src/http/client.ts
@@ -21,6 +21,12 @@ import { warnIfCredentialOverCleartext, warnIfProxyIgnored } from './environment
*/
export class SimApiError extends Error {
retryAfterMs: number | null = null
+ /**
+ * The failed response's body was not JSON. Sim answers every API call in JSON, so a proxy,
+ * VPN, or WAF in front of it most likely answered instead, and its status says nothing about
+ * the credential.
+ */
+ nonJsonBody = false
constructor(
message: string,
readonly status: number,
@@ -179,7 +185,7 @@ function toNonJsonError(
const text = raw.trim()
const keepSnippet = !isMarkup && text.length > 0 && text.length <= 200
- return new SimApiError(
+ const error = new SimApiError(
`${url} returned ${kind}, not JSON (HTTP ${status}) — check your endpoint.${
keepSnippet ? ` Response: ${truncate(text, 200, '…')}` : ''
}`,
@@ -189,6 +195,8 @@ function toNonJsonError(
1,
requestId
)
+ error.nonJsonBody = true
+ return error
}
/**
@@ -419,6 +427,7 @@ function rateLimitedError(error: SimApiError, resends: number): SimApiError {
error.requestId
)
refusal.retryAfterMs = error.retryAfterMs
+ refusal.nonJsonBody = error.nonJsonBody
return refusal
}
@@ -809,17 +818,18 @@ export class SimClient {
if (!response.ok) {
const raw = await readResponseText(response)
const refused = toApiError(url, response, raw)
- const error =
- response.status === 401
- ? new SimApiError(
- `${refused.message} — ${this.credentialRemedy()}`,
- refused.status,
- refused.code ?? AUTH_REQUIRED_CODE,
- refused.details,
- AUTH_REQUIRED_EXIT_CODE,
- refused.requestId
- )
- : refused
+ let error = refused
+ if (response.status === 401) {
+ error = new SimApiError(
+ `${refused.message} — ${this.credentialRemedy()}`,
+ refused.status,
+ refused.code ?? AUTH_REQUIRED_CODE,
+ refused.details,
+ AUTH_REQUIRED_EXIT_CODE,
+ refused.requestId
+ )
+ error.nonJsonBody = refused.nonJsonBody
+ }
error.retryAfterMs = parseRetryAfter(response.headers.get('retry-after'), 300_000)
if (namesKeyScopeRefusal(error)) {
error.message = `${error.message} — this operation does not support workspace API keys; use an OAuth login or personal API key: ${this.credentialRemedy()}`