diff --git a/packages/cli/README.md b/packages/cli/README.md index 9545291e..7a0c2d7a 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -895,11 +895,18 @@ Show stored auth for the selected target beeper auth status ``` +Flags: + +| Flag | Type | Description | +| --- | --- | --- | +| `--check` | boolean | Validate the selected bearer token against the live target | + Examples: ```sh beeper auth status -beeper auth status --json +beeper auth status --check +beeper auth status --check --json ``` Global flags: `--base-url`, `--target`, `--debug`, `--events`, `--full`, `--json`, `--quiet`, `--read-only`, `--timeout`, `--yes`. diff --git a/packages/cli/docs/auth.md b/packages/cli/docs/auth.md index 7ca3a99b..85a76b47 100644 --- a/packages/cli/docs/auth.md +++ b/packages/cli/docs/auth.md @@ -10,7 +10,7 @@ target file under `~/.beeper/targets/`; `BEEPER_ACCESS_TOKEN` overrides it. ## Commands ```sh -beeper auth status +beeper auth status [--check] beeper auth logout beeper auth email start --email # headless sign-in, step 1 beeper auth email response --setup-request-id --code # step 2 @@ -30,7 +30,7 @@ beeper verify cancel ## Notes -- `auth status` reports the token source (env vs. target file) and metadata; it does not call the network. +- `auth status` reports the token source (env vs. target file) and metadata without a network call by default. Add `--check` to ask the selected target whether that bearer is still accepted; the result is `valid`, `invalid`, `unknown`, or `missing`, and the token itself is never printed. - `auth logout` revokes the token at the Desktop OAuth endpoint and clears the local copy. - `auth email start` + `auth email response` sign in with an emailed code, no browser and no prompts. `response` also takes `--username --yes` when the email has no Beeper account yet. Walkthrough: [Headless server setup](setup.md#headless-server-setup). - `verify` (no subcommand) walks the most common SAS/emoji verification flow interactively. @@ -41,7 +41,7 @@ beeper verify cancel ## Examples ```sh -beeper auth status --json +beeper auth status --check --json beeper auth email start --email you@example.com -t server --json beeper auth email response --setup-request-id --code 123456 -t server --json beeper verify diff --git a/packages/cli/src/commands/auth/status.ts b/packages/cli/src/commands/auth/status.ts index 0d0f94e1..e02c7043 100644 --- a/packages/cli/src/commands/auth/status.ts +++ b/packages/cli/src/commands/auth/status.ts @@ -1,14 +1,20 @@ +import { Flags } from '@oclif/core' import { BeeperCommand } from '../../lib/command.js' +import { checkAccessToken, parseTimeoutMs } from '../../lib/auth-health.js' import { resolveTarget } from '../../lib/targets.js' import { printData } from '../../lib/output.js' export default class AuthStatus extends BeeperCommand { static override summary = 'Show stored auth for the selected target' + static override flags = { + check: Flags.boolean({ default: false, description: 'Validate the selected bearer token against the live target' }), + } async run(): Promise { const { flags } = await this.parse(AuthStatus) const target = await resolveTarget({ target: flags.target, baseURL: flags['base-url'] }) - const authenticated = Boolean(process.env.BEEPER_ACCESS_TOKEN || target.auth?.accessToken) + const token = process.env.BEEPER_ACCESS_TOKEN || target.auth?.accessToken + const authenticated = Boolean(token) const data = { authenticated, target: target.id, @@ -17,6 +23,7 @@ export default class AuthStatus extends BeeperCommand { clientID: target.auth?.clientID, expiresAt: target.auth?.expiresAt, scope: target.auth?.scope, + ...(flags.check ? { check: await checkAccessToken(target.baseURL, token, { timeoutMs: parseTimeoutMs(flags.timeout) }) } : {}), } await printData(data, flags.json ? 'json' : 'human') } diff --git a/packages/cli/src/lib/auth-health.ts b/packages/cli/src/lib/auth-health.ts new file mode 100644 index 00000000..1867a3f5 --- /dev/null +++ b/packages/cli/src/lib/auth-health.ts @@ -0,0 +1,56 @@ +export type AccessTokenCheck = { + state: 'valid' | 'invalid' | 'unknown' | 'missing' + status?: number + error?: string +} + +/** Translate the CLI's documented --timeout syntax into a safe timer duration. */ +export function parseTimeoutMs(value: string | undefined): number { + if (value === undefined) return 2_000 + const match = value.trim().match(/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/i) + if (!match) throw new Error('Invalid --timeout. Use a positive duration such as 500ms, 30s, 2m, or 1h.') + const unit = (match[2] ?? 'ms').toLowerCase() + const multiplier = { ms: 1, s: 1_000, m: 60_000, h: 3_600_000 }[unit as 'ms' | 's' | 'm' | 'h'] + const milliseconds = Math.round(Number(match[1]) * multiplier) + if (!Number.isSafeInteger(milliseconds) || milliseconds < 1 || milliseconds > 2_147_483_647) { + throw new Error('Invalid --timeout. Duration must be between 1ms and 2147483647ms.') + } + return milliseconds +} + +export async function checkAccessToken( + baseURL: string, + token: string | undefined, + options: { + timeoutMs?: number + fetcher?: typeof fetch + } = {}, +): Promise { + if (!token) return { state: 'missing' } + + const fetcher = options.fetcher ?? fetch + const controller = new AbortController() + const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? 2_000) + + try { + // /v1/app/setup is public and may return 200 during needs-login; accounts is bearer-protected. + // We only inspect the status code, never log or retain the response body. + const response = await fetcher(new URL('/v1/accounts', baseURL), { + headers: { authorization: `Bearer ${token}` }, + signal: controller.signal, + }) + + if (response.status === 401 || response.status === 403) { + return { state: 'invalid', status: response.status } + } + if (response.ok) return { state: 'valid', status: response.status } + + return { state: 'unknown', status: response.status } + } catch { + // Fetch implementations can echo the Authorization header (including the bearer) in errors. + // Never return a raw exception from a request that included a credential. + return { state: 'unknown', error: 'Token check failed; verify target connectivity and token configuration.' } + } finally { + clearTimeout(timeout) + } +} diff --git a/packages/cli/src/lib/ink/components.tsx b/packages/cli/src/lib/ink/components.tsx index de288d11..954dc200 100644 --- a/packages/cli/src/lib/ink/components.tsx +++ b/packages/cli/src/lib/ink/components.tsx @@ -636,31 +636,45 @@ export const DoctorCard: React.FC<{ checks: Array<{ ok: boolean; name: string; d } export const AuthStatusCard: React.FC<{ auth: RecordValue }> = ({ auth }) => { - const ok = Boolean(auth.authenticated) + const check = auth.check && typeof auth.check === 'object' ? auth.check as RecordValue : undefined + const checkState = check ? stringValue(check.state) : undefined + const stored = Boolean(auth.authenticated) + const ok = checkState ? checkState === 'valid' : stored const expires = auth.expiresAt ? formatTime(auth.expiresAt) ?? String(auth.expiresAt) : undefined + const status = checkState === 'valid' + ? { color: theme.mine, glyph: glyphs.check, label: 'token valid' } + : checkState === 'invalid' + ? { color: theme.danger, glyph: glyphs.cross, label: 'token invalid' } + : checkState === 'unknown' + ? { color: theme.warn, glyph: glyphs.ring, label: 'check unknown' } + : checkState === 'missing' + ? { color: theme.warn, glyph: glyphs.ring, label: 'no token' } + : stored + ? { color: theme.mine, glyph: glyphs.check, label: 'signed in' } + : { color: theme.warn, glyph: glyphs.ring, label: 'signed out' } + return ( - + Authentication - {ok ? ( - {glyphs.check} signed in - ) : ( - {glyphs.ring} signed out - )} + {status.glyph} {status.label} {String(auth.baseURL)} } /> + {checkState ? : null} + {typeof check?.status === 'number' ? : null} + {check?.error ? : null} {auth.clientID ? : null} {auth.scope ? : null} {expires ? : null} {!ok && ( )} diff --git a/packages/cli/src/lib/manifest.ts b/packages/cli/src/lib/manifest.ts index 5b7dfe63..484b07bb 100644 --- a/packages/cli/src/lib/manifest.ts +++ b/packages/cli/src/lib/manifest.ts @@ -118,7 +118,7 @@ export const commandManifest: ManifestCommand[] = [ { command: 'auth status', description: 'Show stored auth for the selected target', - examples: ['beeper auth status', 'beeper auth status --json'], + examples: ['beeper auth status', 'beeper auth status --check', 'beeper auth status --check --json'], }, { command: 'auth logout', diff --git a/packages/cli/test/auth-health.test.ts b/packages/cli/test/auth-health.test.ts new file mode 100644 index 00000000..f5a53752 --- /dev/null +++ b/packages/cli/test/auth-health.test.ts @@ -0,0 +1,105 @@ +import { describe, expect, it } from 'bun:test' +import { checkAccessToken, parseTimeoutMs } from '../src/lib/auth-health.js' + +describe('checkAccessToken', () => { + + it('checks a bearer-protected endpoint, not the public setup endpoint', async () => { + let requestedPath = '' + const result = await checkAccessToken('http://127.0.0.1:23373', 'stale-bearer', { + fetcher: async input => { + requestedPath = new URL(String(input)).pathname + return new Response('{}', { status: requestedPath === '/v1/app/setup' ? 200 : 401 }) + }, + }) + expect(requestedPath).toBe('/v1/accounts') + expect(result).toEqual({ state: 'invalid', status: 401 }) + expect(JSON.stringify(result)).not.toContain('stale-bearer') + }) + + it('reports missing without making a request', async () => { + let calls = 0 + const result = await checkAccessToken('http://127.0.0.1:23373', undefined, { + fetcher: async () => { + calls += 1 + return new Response(null, { status: 200 }) + }, + }) + + expect(result).toEqual({ state: 'missing' }) + expect(calls).toBe(0) + }) + + it('reports valid when the target accepts the bearer', async () => { + let authHeader: string | null = null + const result = await checkAccessToken('http://127.0.0.1:23373', 'secret-token', { + fetcher: async (_input, init) => { + authHeader = new Headers(init?.headers).get('authorization') + return new Response('{}', { status: 200 }) + }, + }) + + expect(result).toEqual({ state: 'valid', status: 200 }) + expect(authHeader).toBe('Bearer secret-token') + }) + + it('reports invalid on authentication rejection without exposing the token', async () => { + const result = await checkAccessToken('http://127.0.0.1:23373', 'secret-token', { + fetcher: async () => new Response('Invalid token', { status: 401 }), + }) + + expect(result).toEqual({ state: 'invalid', status: 401 }) + expect(JSON.stringify(result)).not.toContain('secret-token') + }) + + it('reports unknown for non-auth failures', async () => { + const statusResult = await checkAccessToken('http://127.0.0.1:23373', 'token', { + fetcher: async () => new Response('server error', { status: 500 }), + }) + expect(statusResult).toEqual({ state: 'unknown', status: 500 }) + + const networkResult = await checkAccessToken('http://127.0.0.1:23373', 'token', { + fetcher: async () => { + throw new Error('connection refused') + }, + }) + expect(networkResult).toEqual({ state: 'unknown', error: 'Token check failed; verify target connectivity and token configuration.' }) + }) +}) + +describe('auth status credential/timeout regression', () => { + it('never returns malformed bearer data from fetch errors', async () => { + const token = 'line-one\nline-two-secret' + const result = await checkAccessToken('http://127.0.0.1:23373', token, { + fetcher: async () => { + throw new TypeError(`Header authorization has invalid value: 'Bearer ${token}'`) + }, + }) + expect(result.state).toBe('unknown') + expect(JSON.stringify(result)).not.toContain(token) + expect(JSON.stringify(result)).not.toContain('line-two-secret') + expect(JSON.stringify(result)).not.toContain('Bearer') + }) + + it('parses the global timeout flag, including documented minute/hour units', () => { + expect(parseTimeoutMs(undefined)).toBe(2_000) + expect(parseTimeoutMs('500ms')).toBe(500) + expect(parseTimeoutMs('30s')).toBe(30_000) + expect(parseTimeoutMs('2m')).toBe(120_000) + expect(parseTimeoutMs('1h')).toBe(3_600_000) + expect(() => parseTimeoutMs('0ms')).toThrow() + expect(() => parseTimeoutMs('abc')).toThrow() + expect(() => parseTimeoutMs('999999999h')).toThrow() + }) + + it('honors the supplied small timeout rather than the default two seconds', async () => { + const result = await checkAccessToken('http://127.0.0.1:23373', 'secret-token', { + timeoutMs: 5, + fetcher: async (_url, init) => new Promise((_resolve, reject) => { + if (init?.signal?.aborted) return reject(new Error('aborted')) + init?.signal?.addEventListener('abort', () => reject(new Error('aborted')), { once: true }) + }), + }) + expect(result.state).toBe('unknown') + expect(JSON.stringify(result)).not.toContain('secret-token') + }) +})