From 853a0b15ebf95f0614cfdad30d01c9f0a1913649 Mon Sep 17 00:00:00 2001 From: Tom Riglar Date: Thu, 12 Nov 2026 15:53:27 +0000 Subject: [PATCH 1/2] refactor(auth): refresh `dcd login` sessions through the API, not Supabase The CLI refreshed its session by calling Supabase Auth with a publishable key fetched from the API. It now posts the refresh token to the API's POST /cli-login/refresh, which does the refresh server-side. - 401 (Supabase refused the token) and 400 are final: run `dcd login`. The friendly messages for session_expired / session_not_found / refresh_token_not_found are kept. - Network errors, 404, 429 and 5xx keep the stored session for a retry. - Sends the CLI identity headers, like every other API call. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- src/gateways/cli-auth-gateway.ts | 116 +++++++++++---------- src/utils/auth.ts | 6 +- test/unit/cli-auth-gateway.test.ts | 161 +++++++++++++++++++++++++++++ test/unit/supabase-key.test.ts | 120 --------------------- 5 files changed, 224 insertions(+), 181 deletions(-) create mode 100644 test/unit/cli-auth-gateway.test.ts diff --git a/CLAUDE.md b/CLAUDE.md index 570d0d8..5281dc2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -43,7 +43,7 @@ Top-level `defineCommand` in `src/index.ts` wires thirteen subcommands (`cloud`, **Cloud command workflow** (the canonical shape other commands mirror): upload binary with SHA dedup → extract metadata / validate devices → build execution plan → submit tests → poll results every 10s → download artifacts (reports/videos/logs). `RunFailedError` from the polling service is the signal for a failed test run (distinct from infra errors). -**Auth.** Every command calls `resolveAuth({ apiKeyFlag })` (`src/utils/auth.ts`) once and threads the returned `AuthContext` into gateways/services. `ApiGateway` and `fetchCompatibilityData` spread `auth.headers` into fetch headers — they no longer accept a raw api key. The same headers carry the CLI's identity on every request (`x-dcd-cli-version`, plus `x-dcd-ci-provider` / `x-dcd-ci-wrapper-version` from `detectCiContext`), which the API uses for notice targeting and records on each upload and binary (dcd#1622). Precedence: `--api-key` flag > `DEVICE_CLOUD_API_KEY` env > stored session from `dcd login`. `resolveAuth` refreshes expiring Supabase sessions via `CliAuthGateway.refresh` and rewrites the config atomically. A session's access token lasts about an hour, so code that can outlive it re-checks with `isAuthExpiring` / `refreshAuth`: the `dcd cloud` poll loop and the report downloads after it, the MCP context, and `dcd_run_cloud_test`'s wait loop. `refreshAuth` keeps the org the command started with and leaves API-key contexts untouched. +**Auth.** Every command calls `resolveAuth({ apiKeyFlag })` (`src/utils/auth.ts`) once and threads the returned `AuthContext` into gateways/services. `ApiGateway` and `fetchCompatibilityData` spread `auth.headers` into fetch headers — they no longer accept a raw api key. The same headers carry the CLI's identity on every request (`x-dcd-cli-version`, plus `x-dcd-ci-provider` / `x-dcd-ci-wrapper-version` from `detectCiContext`), which the API uses for notice targeting and records on each upload and binary (dcd#1622). Precedence: `--api-key` flag > `DEVICE_CLOUD_API_KEY` env > stored session from `dcd login`. `resolveAuth` refreshes expiring Supabase sessions via `CliAuthGateway.refresh`, which posts the refresh token to the API's `POST /cli-login/refresh` (no Supabase key needed; a 401 or 400 is final, anything else keeps the stored session for a retry), and rewrites the config atomically. A session's access token lasts about an hour, so code that can outlive it re-checks with `isAuthExpiring` / `refreshAuth`: the `dcd cloud` poll loop and the report downloads after it, the MCP context, and `dcd_run_cloud_test`'s wait loop. `refreshAuth` keeps the org the command started with and leaves API-key contexts untouched. **Config store.** `dcd login` writes `$XDG_CONFIG_HOME/dcd/config.json` (fallback `~/.dcd/config.json`, 0600). Shape: `{ version, env, api_url, supabase_url, session: { access_token, refresh_token, expires_at, user_email, user_id }, current_org_id, current_org_name }`. `DCD_CONFIG_DIR` overrides the directory (used by tests). The login command itself (`src/commands/login.ts`) uses PKCE (S256) with a server rendezvous — no loopback server: it mints `state`, `code_verifier`, and `code_challenge`, opens `/cli-login?state=...&code_challenge=...`, then polls the dcd API's `POST /cli-login/claim` with `{state, code_verifier}` while the frontend POSTs proof of identity (the browser's access token) to `POST /cli-login/handoff`; the API verifies the token, **mints a dedicated Supabase session for the CLI** (its own refresh-token family — sharing the browser's tokens caused "Invalid Refresh Token: Already Used" whenever either client rotated them), stores it keyed by state, then on claim verifies `sha256(verifier) === challenge` and returns it. After claiming, the CLI fetches `/me/orgs` and picks the org with `selectOrg` (`src/utils/orgs.ts`): `--org ` if given, else the only org, else the picker `dcd switch-org` uses, starting on the last login's org. That org only counts when the stored `api_url` matches, because org ids are per environment. Without a TTY (`canPrompt` in `src/utils/ci.ts`) the prompts can't be answered: the "already logged in" confirm takes its default and signs in again, the last login's org is used, and with none the command fails pointing at `--org`. `dcd logout` deletes the whole config, so nothing is remembered after it. The frontend lives in `../dcd/frontend/app/features/cli-login/CliLoginScreen.tsx`. diff --git a/src/gateways/cli-auth-gateway.ts b/src/gateways/cli-auth-gateway.ts index bee282e..1e94c8b 100644 --- a/src/gateways/cli-auth-gateway.ts +++ b/src/gateways/cli-auth-gateway.ts @@ -1,20 +1,16 @@ /** - * Supabase session operations for the CLI: refresh an expired access token - * and sign-out (best-effort revocation on the Supabase side). + * Refreshes a `dcd login` session through the dcd API's + * `POST /cli-login/refresh`, which calls Supabase Auth on the CLI's behalf. + * The CLI holds no Supabase key for this. * - * Does not talk to the dcd API — the dcd-side session exchange lives in the - * login command's PKCE rendezvous flow (see src/commands/login.ts). + * The login itself is the PKCE rendezvous in src/commands/login.ts. */ -import { createClient, isAuthApiError, isAuthSessionMissingError } from '@supabase/supabase-js'; - -import type { DcdEnvName } from '../config/environments.js'; -import { getSupabaseKey } from '../config/supabase-key.js'; import type { StoredSession } from '../utils/config-store.js'; /** - * Thrown when a session refresh fails. `definitive` distinguishes "Supabase - * rejected this refresh token" (revoked, already used, malformed — re-login - * is the only fix) from transient failures (network, GoTrue 5xx) where the + * Thrown when a session refresh fails. `definitive` distinguishes "this + * refresh token was rejected" (revoked, already used, expired — re-login is + * the only fix) from transient failures (network, 5xx, rate limit) where the * stored session may still be good on the next attempt. */ export class SessionRefreshError extends Error { @@ -53,63 +49,73 @@ export interface RefreshedSession { user_id: string; } -function client(supabaseUrl: string, supabaseKey: string) { - return createClient(supabaseUrl, supabaseKey, { - auth: { persistSession: false, autoRefreshToken: false, detectSessionInUrl: false }, - }); +/** The API's error envelope: `{ statusCode, error, message }`. */ +interface ApiErrorBody { + error?: unknown; + message?: unknown; } export const CliAuthGateway = { + /** + * @param apiUrl The API the session was minted by (the stored `api_url`) + * @param session The stored session, whose refresh token is spent on success + * @param headers Extra headers, such as the CLI's identity headers + */ async refresh( - supabaseUrl: string, - env: DcdEnvName, + apiUrl: string, session: StoredSession, + headers: Record = {}, ): Promise { - let supabaseKey: string; + let res: Response; try { - supabaseKey = await getSupabaseKey(env); + res = await fetch(`${apiUrl.replace(/\/$/, '')}/cli-login/refresh`, { + body: JSON.stringify({ refresh_token: session.refresh_token }), + headers: { ...headers, 'content-type': 'application/json' }, + method: 'POST', + }); } catch (error) { - // Never definitive: the refresh token was not even tried, so the stored - // session must survive for the next attempt. + // Never definitive: the token was not even tried. throw new SessionRefreshError( `Failed to refresh session: ${(error as Error).message}`, false, ); } - const sb = client(supabaseUrl, supabaseKey); - const { data, error } = await sb.auth.refreshSession({ - refresh_token: session.refresh_token, - }); - if (error || !data.session || !data.user) { - // 4xx from GoTrue means the token itself was rejected; anything else - // (fetch failure, 5xx) could succeed on retry with the same token. - // supabase-js turns GoTrue's `session_not_found` into an - // AuthSessionMissingError rather than an AuthApiError (it throws the same - // for an empty refresh token); only `dcd login` fixes either. - const apiError = error != null && isAuthApiError(error) ? error : undefined; - const sessionMissing = error != null && isAuthSessionMissingError(error); - const definitive = - sessionMissing || - (apiError !== undefined && apiError.status >= 400 && apiError.status < 500); - const code = apiError?.code ?? (sessionMissing ? 'session_not_found' : undefined); - const known = definitive && code ? REFRESH_REFUSAL_MESSAGES.get(code) : undefined; - throw new SessionRefreshError( - known ?? - `Failed to refresh session: ${error?.message ?? 'no session returned'}. ` + - `Run \`dcd login\` again.`, - definitive, - code, - ); + + if (res.ok) { + const s = (await res.json()) as Partial; + if (!s.access_token || !s.refresh_token || !s.expires_at || !s.user_id) { + throw new SessionRefreshError('Failed to refresh session: incomplete response', false); + } + return { + access_token: s.access_token, + refresh_token: s.refresh_token, + expires_at: s.expires_at, + user_email: s.user_email || session.user_email, + user_id: s.user_id, + }; } - const s = data.session; - const u = data.user; - if (!s.expires_at) throw new Error('Refreshed session is missing expires_at'); - return { - access_token: s.access_token, - refresh_token: s.refresh_token, - expires_at: s.expires_at, - user_email: u.email ?? session.user_email, - user_id: u.id, - }; + + let body: ApiErrorBody = {}; + try { + body = (await res.json()) as ApiErrorBody; + } catch { + // Not JSON (a proxy page, say). The status alone decides. + } + const code = typeof body.error === 'string' ? body.error : undefined; + const reason = + typeof body.message === 'string' && body.message ? body.message : `HTTP ${res.status}`; + + // 401: Supabase Auth refused the token, and `error` is its code. 400: the + // API refused the request itself (an empty token). Only `dcd login` fixes + // either. Anything else (404 from an API without this route, 429, 5xx) + // may work later with the same token, so it must survive. + const definitive = res.status === 401 || res.status === 400; + const known = definitive && code ? REFRESH_REFUSAL_MESSAGES.get(code) : undefined; + throw new SessionRefreshError( + known ?? + `Failed to refresh session: ${reason}.` + (definitive ? ' Run `dcd login` again.' : ''), + definitive, + definitive ? code : undefined, + ); }, }; diff --git a/src/utils/auth.ts b/src/utils/auth.ts index b923ea1..1875c41 100644 --- a/src/utils/auth.ts +++ b/src/utils/auth.ts @@ -221,11 +221,7 @@ async function refreshSessionWithLock( // forced a fresh login when an upgrade alone would have fixed it. The // error tells the user to log in again; only `dcd logout` (or the next // `dcd login`) replaces the stored session. - const refreshed = await CliAuthGateway.refresh( - current.supabase_url, - current.env, - session, - ); + const refreshed = await CliAuthGateway.refresh(current.api_url, session, clientHeaders()); // Re-read again and merge only `session` so a concurrent `switch-org` // write (org fields) isn't reverted by our pre-refresh snapshot. const merged: StoredConfig = { ...(readConfig() ?? current), session: refreshed }; diff --git a/test/unit/cli-auth-gateway.test.ts b/test/unit/cli-auth-gateway.test.ts new file mode 100644 index 0000000..e3c6569 --- /dev/null +++ b/test/unit/cli-auth-gateway.test.ts @@ -0,0 +1,161 @@ +import { expect } from 'chai'; + +import { CliAuthGateway, SessionRefreshError } from '../../src/gateways/cli-auth-gateway.js'; + +/** + * A `dcd login` session is refreshed through the API's POST /cli-login/refresh, + * not Supabase Auth, so the CLI needs no Supabase key for it. A refusal the + * user can only fix with `dcd login` must be `definitive`; anything else must + * leave the stored session alone for the next try. + */ +describe('CliAuthGateway.refresh', () => { + const realFetch = globalThis.fetch; + const stored = { + access_token: 'a', + refresh_token: 'r', + expires_at: 0, + user_email: 'u@example.com', + user_id: 'u1', + }; + let calls: Array<{ body: unknown; headers: Record; url: string }>; + + function stubFetch(respond: () => Response | Promise): void { + calls = []; + globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => { + calls.push({ + body: JSON.parse(String(init?.body)), + headers: init?.headers as Record, + url: String(input), + }); + return respond(); + }) as typeof fetch; + } + + const json = (body: unknown, status = 200) => + new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }); + + async function refreshError(): Promise { + try { + await CliAuthGateway.refresh('https://api.devicecloud.dev', stored); + } catch (error) { + expect(error).to.be.instanceOf(SessionRefreshError); + return error as SessionRefreshError; + } + throw new Error('expected the refresh to fail'); + } + + afterEach(() => { + globalThis.fetch = realFetch; + }); + + it('posts the refresh token to the API and returns the new session', async () => { + stubFetch(() => + json({ + access_token: 'a2', + refresh_token: 'r2', + expires_at: 123, + user_email: 'u@example.com', + user_id: 'u1', + }), + ); + + const session = await CliAuthGateway.refresh('https://api.devicecloud.dev/', stored, { + 'x-dcd-cli-version': '9.9.9', + }); + + expect(session).to.deep.equal({ + access_token: 'a2', + refresh_token: 'r2', + expires_at: 123, + user_email: 'u@example.com', + user_id: 'u1', + }); + expect(calls).to.have.length(1); + expect(calls[0].url).to.equal('https://api.devicecloud.dev/cli-login/refresh'); + expect(calls[0].body).to.deep.equal({ refresh_token: 'r' }); + expect(calls[0].headers).to.include({ + 'content-type': 'application/json', + 'x-dcd-cli-version': '9.9.9', + }); + }); + + it('keeps the stored email when the API sends none', async () => { + stubFetch(() => + json({ access_token: 'a2', refresh_token: 'r2', expires_at: 123, user_email: '', user_id: 'u1' }), + ); + + const session = await CliAuthGateway.refresh('https://api.devicecloud.dev', stored); + + expect(session.user_email).to.equal('u@example.com'); + }); + + it('says the session expired', async () => { + stubFetch(() => json({ statusCode: 401, error: 'session_expired', message: 'Session Expired' }, 401)); + + const error = await refreshError(); + + expect(error.message).to.equal('Your session expired. Run `dcd login` to sign in again.'); + expect(error.code).to.equal('session_expired'); + expect(error.definitive).to.equal(true); + }); + + it('says the session was signed out when it no longer exists', async () => { + for (const code of ['refresh_token_not_found', 'session_not_found']) { + stubFetch(() => json({ statusCode: 401, error: code, message: 'Not Found' }, 401)); + + const error = await refreshError(); + + expect(error.message).to.equal('Your session was signed out. Run `dcd login` to sign in again.'); + expect(error.code).to.equal(code); + expect(error.definitive).to.equal(true); + } + }); + + it("keeps Supabase's message for any other refusal", async () => { + stubFetch(() => + json( + { + statusCode: 401, + error: 'refresh_token_already_used', + message: 'Invalid Refresh Token: Already Used', + }, + 401, + ), + ); + + const error = await refreshError(); + + expect(error.message).to.equal( + 'Failed to refresh session: Invalid Refresh Token: Already Used. Run `dcd login` again.', + ); + expect(error.code).to.equal('refresh_token_already_used'); + expect(error.definitive).to.equal(true); + }); + + it('treats a 400 from the API as final', async () => { + stubFetch(() => json({ statusCode: 400, message: ['refresh_token should not be empty'] }, 400)); + + const error = await refreshError(); + + expect(error.definitive).to.equal(true); + }); + + for (const [label, respond] of [ + ['a network failure', () => Promise.reject(new TypeError('fetch failed'))], + ['a 503', () => json({ statusCode: 503, error: 'refresh_unavailable', message: 'Try again.' }, 503)], + ['a 429', () => json({ statusCode: 429, message: 'ThrottlerException: Too Many Requests' }, 429)], + ['a 404 from an API without the route', () => json({ statusCode: 404, message: 'Cannot POST' }, 404)], + ['a page that is not JSON', () => new Response('bad gateway', { status: 502 })], + ] as Array<[string, () => Promise | Response]>) { + it(`keeps the stored session after ${label}`, async () => { + stubFetch(respond); + + const error = await refreshError(); + + // Not definitive, so callers keep the session and try again later. + expect(error.definitive).to.equal(false); + expect(error.code).to.equal(undefined); + expect(error.message).to.not.contain('dcd login'); + }); + } +}); diff --git a/test/unit/supabase-key.test.ts b/test/unit/supabase-key.test.ts index 32ce7bf..c6da796 100644 --- a/test/unit/supabase-key.test.ts +++ b/test/unit/supabase-key.test.ts @@ -5,7 +5,6 @@ import { resetSupabaseKeyCache, supabaseKeyHeaders, } from '../../src/config/supabase-key.js'; -import { CliAuthGateway, SessionRefreshError } from '../../src/gateways/cli-auth-gateway.js'; /** * The Supabase key is fetched from the API's `GET /cli-config` (dcd#1112) @@ -73,123 +72,4 @@ describe('Supabase key from /cli-config', () => { authorization: 'Bearer eyJhbGciOi.x.y', }); }); - - it('keeps the stored session when the key cannot be fetched during a refresh', async () => { - stubFetch(() => { - throw new TypeError('fetch failed'); - }); - let caught: unknown; - try { - await CliAuthGateway.refresh('https://cloud.devicecloud.dev', 'prod', { - access_token: 'a', - refresh_token: 'r', - expires_at: 0, - user_email: 'u@example.com', - user_id: 'u1', - }); - } catch (error) { - caught = error; - } - expect(caught).to.be.instanceOf(SessionRefreshError); - // Not definitive, so resolveAuth will not delete the user's login. - expect((caught as SessionRefreshError).definitive).to.equal(false); - }); - - /** - * Supabase Auth refuses a refresh with a 4xx and an error code: in `code` - * when the response is versioned (2024-01-01 and later), in `error_code` - * before that. The CLI names the common causes instead of echoing them. - */ - describe('when Supabase refuses the refresh', () => { - const storedSession = { - access_token: 'a', - refresh_token: 'r', - expires_at: 0, - user_email: 'u@example.com', - user_id: 'u1', - }; - - function refuseRefresh(token: () => Response): void { - stubFetch((url) => - url.endsWith('/cli-config') - ? json({ supabase_publishable_key: 'sb_publishable_abc' }) - : token(), - ); - } - - const versioned = (status: number, code: string, message: string) => - new Response(JSON.stringify({ code, message }), { - status, - headers: { - 'content-type': 'application/json', - 'x-supabase-api-version': '2024-01-01', - }, - }); - - async function refreshError(): Promise { - try { - await CliAuthGateway.refresh('https://cloud.devicecloud.dev', 'prod', storedSession); - } catch (error) { - expect(error).to.be.instanceOf(SessionRefreshError); - return error as SessionRefreshError; - } - throw new Error('expected the refresh to fail'); - } - - it('says the session expired', async () => { - refuseRefresh(() => versioned(403, 'session_expired', 'Invalid Refresh Token: Session Expired')); - - const error = await refreshError(); - - expect(error.message).to.equal('Your session expired. Run `dcd login` to sign in again.'); - expect(error.code).to.equal('session_expired'); - expect(error.definitive).to.equal(true); - expect(requested[1]).to.equal( - 'https://cloud.devicecloud.dev/auth/v1/token?grant_type=refresh_token', - ); - }); - - it('reads the code from an unversioned response too', async () => { - refuseRefresh(() => - json( - { code: 403, error_code: 'session_expired', msg: 'Invalid Refresh Token: Session Expired (Inactivity)' }, - 403, - ), - ); - - const error = await refreshError(); - - expect(error.message).to.equal('Your session expired. Run `dcd login` to sign in again.'); - expect(error.code).to.equal('session_expired'); - expect(error.definitive).to.equal(true); - }); - - it('says the session was signed out when it no longer exists', async () => { - for (const code of ['refresh_token_not_found', 'session_not_found']) { - refuseRefresh(() => versioned(400, code, 'Invalid Refresh Token: Refresh Token Not Found')); - - const error = await refreshError(); - - expect(error.message).to.equal( - 'Your session was signed out. Run `dcd login` to sign in again.', - ); - expect(error.code).to.equal(code); - expect(error.definitive).to.equal(true); - } - }); - - it("keeps Supabase's message for any other refusal", async () => { - refuseRefresh(() => - versioned(400, 'refresh_token_already_used', 'Invalid Refresh Token: Already Used'), - ); - - const error = await refreshError(); - - expect(error.message).to.equal( - 'Failed to refresh session: Invalid Refresh Token: Already Used. Run `dcd login` again.', - ); - expect(error.code).to.equal('refresh_token_already_used'); - expect(error.definitive).to.equal(true); - }); - }); }); From 91756a9f812af8359aa94ecb05ad507ddcfbf435 Mon Sep 17 00:00:00 2001 From: Tom Riglar Date: Tue, 17 Nov 2026 11:54:03 +0000 Subject: [PATCH 2/2] fix(auth): treat a non-JSON 200 from the refresh endpoint as retryable A 200 whose body is not JSON (a proxy page, say) made res.json() throw a plain SyntaxError. It now throws a retryable SessionRefreshError, like the other might-work-later cases, so the user sees a clear message. Co-Authored-By: Claude Opus 5.5 --- src/gateways/cli-auth-gateway.ts | 9 ++++++++- test/unit/cli-auth-gateway.test.ts | 1 + 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/gateways/cli-auth-gateway.ts b/src/gateways/cli-auth-gateway.ts index 1e94c8b..efe335d 100644 --- a/src/gateways/cli-auth-gateway.ts +++ b/src/gateways/cli-auth-gateway.ts @@ -82,7 +82,14 @@ export const CliAuthGateway = { } if (res.ok) { - const s = (await res.json()) as Partial; + let s: Partial; + try { + s = (await res.json()) as Partial; + } catch { + // A 200 that is not JSON (a proxy page, say). The token may not have + // been spent, so keep the session and try again next time. + throw new SessionRefreshError('Failed to refresh session: response was not JSON', false); + } if (!s.access_token || !s.refresh_token || !s.expires_at || !s.user_id) { throw new SessionRefreshError('Failed to refresh session: incomplete response', false); } diff --git a/test/unit/cli-auth-gateway.test.ts b/test/unit/cli-auth-gateway.test.ts index e3c6569..fe1ccfe 100644 --- a/test/unit/cli-auth-gateway.test.ts +++ b/test/unit/cli-auth-gateway.test.ts @@ -146,6 +146,7 @@ describe('CliAuthGateway.refresh', () => { ['a 429', () => json({ statusCode: 429, message: 'ThrottlerException: Too Many Requests' }, 429)], ['a 404 from an API without the route', () => json({ statusCode: 404, message: 'Cannot POST' }, 404)], ['a page that is not JSON', () => new Response('bad gateway', { status: 502 })], + ['a 200 that is not JSON', () => new Response('ok', { status: 200 })], ] as Array<[string, () => Promise | Response]>) { it(`keeps the stored session after ${label}`, async () => { stubFetch(respond);