Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ Top-level `defineCommand` in `src/index.ts` wires fourteen 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 `<frontend>/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 <name|id>` 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`.

Expand Down
123 changes: 68 additions & 55 deletions src/gateways/cli-auth-gateway.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -53,63 +49,80 @@ 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<string, string> = {},
): Promise<RefreshedSession> {
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) {
let s: Partial<RefreshedSession>;
try {
s = (await res.json()) as Partial<RefreshedSession>;
} 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);
}
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,
);
},
};
6 changes: 1 addition & 5 deletions src/utils/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
Expand Down
162 changes: 162 additions & 0 deletions test/unit/cli-auth-gateway.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
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<string, string>; url: string }>;

function stubFetch(respond: () => Response | Promise<Response>): void {
calls = [];
globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
calls.push({
body: JSON.parse(String(init?.body)),
headers: init?.headers as Record<string, string>,
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<SessionRefreshError> {
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('<html>bad gateway</html>', { status: 502 })],
['a 200 that is not JSON', () => new Response('<html>ok</html>', { status: 200 })],
] as Array<[string, () => Promise<Response> | 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');
});
}
});
Loading
Loading