Skip to content
Open
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
9 changes: 8 additions & 1 deletion packages/cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
6 changes: 3 additions & 3 deletions packages/cli/docs/auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <addr> # headless sign-in, step 1
beeper auth email response --setup-request-id <id> --code <code> # step 2
Expand All @@ -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 <name> --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.
Expand All @@ -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 <id> --code 123456 -t server --json
beeper verify
Expand Down
9 changes: 8 additions & 1 deletion packages/cli/src/commands/auth/status.ts
Original file line number Diff line number Diff line change
@@ -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<void> {
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,
Expand All @@ -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')
}
Expand Down
56 changes: 56 additions & 0 deletions packages/cli/src/lib/auth-health.ts
Original file line number Diff line number Diff line change
@@ -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<AccessTokenCheck> {
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 }
Comment thread
b-pm marked this conversation as resolved.
Resolved

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)
}
}
30 changes: 22 additions & 8 deletions packages/cli/src/lib/ink/components.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
<Box flexDirection="column">
<Box>
<Rail color={ok ? theme.mine : theme.warn} />
<Rail color={status.color} />
<Text> </Text>
<Text bold color={theme.text}>Authentication</Text>
<Text> </Text>
{ok ? (
<Text color={theme.mine}>{glyphs.check} signed in</Text>
) : (
<Text color={theme.warn}>{glyphs.ring} signed out</Text>
)}
<Text color={status.color}>{status.glyph} {status.label}</Text>
</Box>
<KV label="endpoint" value={
<Hyperlink url={String(auth.baseURL)}><Text color={theme.link}>{String(auth.baseURL)}</Text></Hyperlink>
} />
<KV label="source" value={String(auth.source ?? 'none')} tone="muted" />
{checkState ? <KV label="check" value={checkState} tone={checkState === 'valid' ? 'muted' : 'normal'} /> : null}
{typeof check?.status === 'number' ? <KV label="http" value={String(check.status)} tone="dim" /> : null}
{check?.error ? <KV label="error" value={String(check.error)} tone="muted" /> : null}
{auth.clientID ? <KV label="client" value={String(auth.clientID)} tone="dim" /> : null}
{auth.scope ? <KV label="scope" value={String(auth.scope)} tone="muted" /> : null}
{expires ? <KV label="expires" value={expires} tone="muted" /> : null}
{!ok && (
<Suggestions suggestions={[
{ command: 'beeper setup', hint: 'continue target setup' },
{ command: 'beeper setup', hint: checkState === 'invalid' ? 'refresh authentication' : 'continue target setup' },
]} />
)}
</Box>
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/lib/manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
105 changes: 105 additions & 0 deletions packages/cli/test/auth-health.test.ts
Original file line number Diff line number Diff line change
@@ -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<Response>((_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')
})
})