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
90 changes: 69 additions & 21 deletions README.md

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions src/auth/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,5 @@ export type AuthErrorCode =
| 'AUTH_PORT_BIND_FAILED'
| 'AUTH_TOKEN_EXCHANGE_FAILED'
| 'AUTH_STORE_WRITE_FAILED'
| 'NOT_AUTHENTICATED'
| 'TOKEN_FROM_ENV'
6 changes: 6 additions & 0 deletions src/auth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@ export { runOAuthFlow } from './flow.js'
export type { RunOAuthFlowOptions, RunOAuthFlowResult } from './flow.js'
export { attachLoginCommand } from './login.js'
export type { AttachLoginCommandOptions, AttachLoginContext } from './login.js'
export { attachLogoutCommand } from './logout.js'
export type { AttachLogoutCommandOptions, AttachLogoutContext } from './logout.js'
export { attachStatusCommand } from './status.js'
export type { AttachStatusCommandOptions, AttachStatusContext } from './status.js'
export { attachTokenViewCommand } from './token-view.js'
export type { AttachTokenViewCommandOptions } from './token-view.js'
export {
DEFAULT_VERIFIER_ALPHABET,
deriveChallenge,
Expand Down
207 changes: 207 additions & 0 deletions src/auth/logout.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
import { Command } from 'commander'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

import { formatJson } from '../json.js'
import { attachLogoutCommand } from './logout.js'
import type { TokenStore } from './types.js'

type Account = { id: string; label?: string; email: string }

const account: Account = { id: '1', label: 'me', email: 'a@b' }

function buildStore(
initial: { token: string; account: Account } | null = { token: 'tok', account },
): {
store: TokenStore<Account>
activeSpy: ReturnType<typeof vi.fn>
clearSpy: ReturnType<typeof vi.fn>
} {
const activeSpy = vi.fn(async () => initial)
const clearSpy = vi.fn(async () => undefined)
const store: TokenStore<Account> = {
active: activeSpy,
set: vi.fn(),
clear: clearSpy,
}
return { store, activeSpy, clearSpy }
}

function build(
overrides: Partial<Parameters<typeof attachLogoutCommand<Account>>[1]> = {},
storeOverride?: TokenStore<Account>,
): {
program: Command
store: TokenStore<Account>
onCleared: ReturnType<typeof vi.fn>
} {
const { store } = storeOverride ? { store: storeOverride } : buildStore()
const program = new Command()
program.exitOverride()
const auth = program.command('auth')
const onCleared = vi.fn()
attachLogoutCommand<Account>(auth, {
store,
onCleared,
...overrides,
})
return { program, store, onCleared }
}

describe('attachLogoutCommand', () => {
let logSpy: ReturnType<typeof vi.spyOn>

beforeEach(() => {
logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
})

afterEach(() => {
logSpy.mockRestore()
})

it('clears the store and emits the human success line in plain mode', async () => {
const built = buildStore()
const { program, onCleared } = build({}, built.store)

await program.parseAsync(['node', 'cli', 'auth', 'logout'])

expect(built.activeSpy).toHaveBeenCalledTimes(1)
expect(built.clearSpy).toHaveBeenCalledTimes(1)
expect(logSpy).toHaveBeenCalledWith('✓ Logged out')
expect(onCleared).toHaveBeenCalledWith({
account,
view: { json: false, ndjson: false },
flags: {},
})
})

it('emits a JSON success envelope under --json', async () => {
const { program, onCleared } = build()

await program.parseAsync(['node', 'cli', 'auth', 'logout', '--json'])

expect(logSpy).toHaveBeenCalledWith(formatJson({ ok: true }))
expect(onCleared).toHaveBeenCalledWith({
account,
view: { json: true, ndjson: false },
flags: {},
})
})

it('is silent on stdout under --ndjson', async () => {
const { program, onCleared } = build()

await program.parseAsync(['node', 'cli', 'auth', 'logout', '--ndjson'])

expect(logSpy).not.toHaveBeenCalled()
expect(onCleared).toHaveBeenCalledWith({
account,
view: { json: false, ndjson: true },
flags: {},
})
})

it('passes a null account when nothing was stored', async () => {
const built = buildStore(null)
const { program, onCleared } = build({}, built.store)

await program.parseAsync(['node', 'cli', 'auth', 'logout'])

expect(built.clearSpy).toHaveBeenCalledTimes(1)
expect(onCleared).toHaveBeenCalledWith({
account: null,
view: { json: false, ndjson: false },
flags: {},
})
})

it('skips store.active() when no onCleared callback is supplied', async () => {
const program = new Command()
program.exitOverride()
const auth = program.command('auth')
const built = buildStore()
attachLogoutCommand<Account>(auth, { store: built.store })

await program.parseAsync(['node', 'cli', 'auth', 'logout'])

expect(built.activeSpy).not.toHaveBeenCalled()
expect(built.clearSpy).toHaveBeenCalledTimes(1)
})

it('exposes consumer-attached options in flags but strips --json / --ndjson', async () => {
const program = new Command()
program.exitOverride()
const auth = program.command('auth')
const built = buildStore()
const onCleared = vi.fn()
const logout = attachLogoutCommand<Account>(auth, { store: built.store, onCleared })
logout.option('--user <ref>', 'Multi-user selector')

await program.parseAsync([
'node',
'cli',
'auth',
'logout',
'--json',
'--user',
'me@example',
])

expect(onCleared).toHaveBeenCalledWith({
account,
view: { json: true, ndjson: false },
flags: { user: 'me@example' },
})
})

it('snapshots the active account before clear() runs', async () => {
const built = buildStore()
const order: string[] = []
;(built.store.active as ReturnType<typeof vi.fn>).mockImplementationOnce(async () => {
order.push('active')
return { token: 'tok', account }
})
;(built.store.clear as ReturnType<typeof vi.fn>).mockImplementationOnce(async () => {
order.push('clear')
})
const onCleared = vi.fn(() => {
order.push('onCleared')
})
const { program } = build({ onCleared }, built.store)

await program.parseAsync(['node', 'cli', 'auth', 'logout'])

expect(order).toEqual(['active', 'clear', 'onCleared'])
})

it('works without an onCleared callback', async () => {
const program = new Command()
program.exitOverride()
const auth = program.command('auth')
const built = buildStore()
attachLogoutCommand<Account>(auth, { store: built.store })

await expect(program.parseAsync(['node', 'cli', 'auth', 'logout'])).resolves.toBeDefined()
expect(built.clearSpy).toHaveBeenCalledTimes(1)
})

it('returns the new Command so the consumer can chain', () => {
const program = new Command()
const auth = program.command('auth')
const built = buildStore()
const logout = attachLogoutCommand<Account>(auth, { store: built.store })

expect(logout.name()).toBe('logout')
})

it('honours a custom description', () => {
const program = new Command()
const auth = program.command('auth')
const built = buildStore()
const logout = attachLogoutCommand<Account>(auth, {
store: built.store,
description: 'Sign out of Todoist',
})

expect(logout.description()).toBe('Sign out of Todoist')
})
})
62 changes: 62 additions & 0 deletions src/auth/logout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import type { Command } from 'commander'
import { formatJson } from '../json.js'
import type { ViewOptions } from '../options.js'
import type { AuthAccount, TokenStore } from './types.js'

export type AttachLogoutContext<TAccount extends AuthAccount> = {
/** The account that was active immediately before `clear()` ran, or `null` if nothing was stored. */
account: TAccount | null
view: Required<ViewOptions>
/**
* Stripped per-CLI flags — the parsed options object with the standard
* registrar flags (`--json`, `--ndjson`) removed. Any consumer-attached
* `.option(...)` lands here (e.g. `--user <ref>` from a multi-user CLI).
*/
flags: Record<string, unknown>
}

export type AttachLogoutCommandOptions<TAccount extends AuthAccount = AuthAccount> = {
store: TokenStore<TAccount>
/** Override the subcommand description. */
description?: string
/**
* Fires after `store.clear()` resolves. Use to surface keyring-fallback
* warnings or other CLI-specific follow-ups. Consumers in machine-output
* mode should route any extra prose to stderr to keep stdout parseable.
*/
onCleared?(ctx: AttachLogoutContext<TAccount>): void | Promise<void>
}

/**
* Attach `logout` as a subcommand of `parent`. Snapshots the active account,
* calls `store.clear()`, emits a sensible default success line gated on
* `--json` / `--ndjson`, then invokes `onCleared` for follow-ups. Returns the
* new `Command` so the consumer can chain.
*/
export function attachLogoutCommand<TAccount extends AuthAccount = AuthAccount>(
parent: Command,
options: AttachLogoutCommandOptions<TAccount>,
): Command {
return parent
.command('logout')
.description(options.description ?? 'Remove the saved authentication token')
.option('--json', 'Emit machine-readable JSON output')
.option('--ndjson', 'Emit machine-readable NDJSON output')
.action(async (cmd: Record<string, unknown>) => {
const { json, ndjson, ...flags } = cmd
const view: Required<ViewOptions> = {
Comment thread
scottlovegrove marked this conversation as resolved.
json: Boolean(json),
ndjson: Boolean(ndjson),
}
// Skip the keyring/file read when no callback consumes the snapshot.
const snapshot = options.onCleared ? await options.store.active() : null
const account = snapshot?.account ?? null
await options.store.clear()
if (view.json) {
console.log(formatJson({ ok: true }))
} else if (!view.ndjson) {
console.log('✓ Logged out')
}
await options.onCleared?.({ account, view, flags })
})
}
Loading
Loading