-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.test.ts
More file actions
815 lines (696 loc) · 32.8 KB
/
Copy pathauth.test.ts
File metadata and controls
815 lines (696 loc) · 32.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
import { captureConsole, createTestProgram } from '@doist/cli-core/testing'
import { Command } from 'commander'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
// Mock the auth module (only the read-side shims are stubbed; the
// write-side path now goes through `createCommsTokenStore` from
// auth-provider.js, mocked below).
vi.mock('../../lib/auth.js', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../lib/auth.js')>()
return {
...actual,
getApiTokenSnapshot: vi.fn(),
probeApiToken: vi.fn(),
}
})
// Mock the cli-core-backed token store so token / logout tests can drive
// `set` / `clear` / `getLastStorageResult` / `getLastClearResult` directly.
const storeMocks = vi.hoisted(() => ({
set: vi.fn(),
clear: vi.fn(),
active: vi.fn(),
list: vi.fn(),
setDefault: vi.fn(),
getLastStorageResult: vi.fn(),
getLastClearResult: vi.fn(),
}))
vi.mock('../../lib/auth-provider.js', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../lib/auth-provider.js')>()
return {
...actual,
createCommsTokenStore: () => storeMocks,
}
})
// Mock the api module
vi.mock('../../lib/api.js', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../lib/api.js')>()
return {
...actual,
createWrappedCommsClient: vi.fn(),
}
})
vi.mock('../../lib/config.js', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../lib/config.js')>()
return {
...actual,
getConfig: vi.fn(),
updateConfig: vi.fn(),
}
})
// Mock cli-core's auth subpath so login subcommand wiring doesn't drive a real
// OAuth flow during tests. The provider + token-store units are exercised in
// src/lib/auth-provider.test.ts. attachLogoutCommand + attachStatusCommand
// fall through to the real cli-core implementations so the integration is
// exercised end-to-end.
vi.mock('@doist/cli-core/auth', async (importOriginal) => {
const actual = await importOriginal<typeof import('@doist/cli-core/auth')>()
return {
...actual,
attachLoginCommand: vi.fn((parent, _options) => {
const cmd = parent.command('login')
cmd.action(() => {})
return cmd
}),
}
})
// Mock readline for interactive token input
vi.mock('node:readline', () => ({
createInterface: vi.fn(() => {
const rl = {
question: vi.fn(),
close: vi.fn(),
}
return rl
}),
}))
// Mock chalk to avoid colors in tests
vi.mock('chalk')
import { createInterface, type Interface } from 'node:readline'
import { attachLoginCommand } from '@doist/cli-core/auth'
import { CommsRequestError, type User } from '@doist/comms-sdk'
import { createWrappedCommsClient } from '../../lib/api.js'
import { type CommsAccount, type CommsTokenStore } from '../../lib/auth-provider.js'
import { getApiTokenSnapshot, NoTokenError, TOKEN_ENV_VAR } from '../../lib/auth.js'
import { getConfig, updateConfig } from '../../lib/config.js'
import { resetGlobalArgs } from '../../lib/global-args.js'
import { registerAuthCommand } from './index.js'
import { attachCommsStatusCommand } from './status.js'
const mockCreateInterface = vi.mocked(createInterface)
const mockGetApiTokenSnapshot = vi.mocked(getApiTokenSnapshot)
const mockCreateWrappedCommsClient = vi.mocked(createWrappedCommsClient)
const mockAttachLoginCommand = vi.mocked(attachLoginCommand)
const mockGetConfig = vi.mocked(getConfig)
const mockUpdateConfig = vi.mocked(updateConfig)
const createProgram = () => createTestProgram(registerAuthCommand)
const TEST_USER: User = {
id: 1,
fullName: 'Test User',
shortName: 'test',
timezone: 'UTC',
removed: false,
email: 'test@example.com',
lang: 'en',
}
describe('auth command', () => {
let consoleSpy: ReturnType<typeof vi.spyOn>
let errorSpy: ReturnType<typeof vi.spyOn>
beforeEach(() => {
vi.clearAllMocks()
// Mock console.log to capture output
consoleSpy = captureConsole('log')
errorSpy = captureConsole('error')
})
const STORED_ACCOUNT: CommsAccount = {
id: '1',
label: 'Test User',
authMode: 'read-write',
authScope: 'user:read',
}
const STORED_SNAPSHOT = { token: 'tk_stored_1234567890', account: STORED_ACCOUNT }
const STORED_RECORDS = [{ account: STORED_ACCOUNT, isDefault: true }]
const COMMS_SCOPE =
'user:read comms:content:read comms:content:write comms:messages:read comms:messages:write'
function workspace(id: number, name = `Workspace ${id}`) {
return {
id,
name,
creator: 1,
created: new Date('2026-01-01T00:00:00Z'),
plan: 'business',
}
}
function mockWorkspaceClient(workspaces: ReturnType<typeof workspace>[]) {
const getWorkspaces = vi.fn().mockResolvedValue(workspaces)
mockCreateWrappedCommsClient.mockReturnValue({
workspaces: { getWorkspaces },
// biome-ignore lint/suspicious/noExplicitAny: only the method used by these tests matters
} as any)
return getWorkspaces
}
describe('token subcommand', () => {
let originalIsTTY: boolean | undefined
let writeSpy: ReturnType<typeof vi.spyOn>
function mockPromptAnswer(answer: string): { question: ReturnType<typeof vi.fn> } {
const mockRl = {
question: vi.fn((_prompt: string, cb: (answer: string) => void) => cb(answer)),
close: vi.fn(),
_writeToOutput: vi.fn(),
}
mockCreateInterface.mockReturnValue(mockRl as unknown as Interface)
return { question: mockRl.question }
}
beforeEach(() => {
storeMocks.set.mockReset().mockResolvedValue(undefined)
storeMocks.getLastStorageResult.mockReset().mockReturnValue({ storage: 'secure-store' })
originalIsTTY = process.stdin.isTTY
Object.defineProperty(process.stdin, 'isTTY', { value: true, configurable: true })
writeSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true)
})
afterEach(() => {
writeSpy.mockRestore()
Object.defineProperty(process.stdin, 'isTTY', {
value: originalIsTTY,
configurable: true,
})
})
it('prompts interactively, saves the trimmed token via store.set with an empty-id account, and confirms', async () => {
const { question } = mockPromptAnswer(' some_token_123456789 ')
await createProgram().parseAsync(['node', 'tdc', 'auth', 'token'])
expect(question).toHaveBeenCalled()
expect(storeMocks.set).toHaveBeenCalledWith(
{ id: '', label: '', authMode: 'unknown', authScope: '' },
'some_token_123456789',
)
expect(consoleSpy).toHaveBeenCalledWith('✓', 'API token saved successfully!')
expect(consoleSpy).toHaveBeenCalledWith(
'Token stored securely in the system credential manager',
)
})
it('lets store.set errors propagate unchanged', async () => {
storeMocks.set.mockRejectedValue(new Error('Permission denied'))
mockPromptAnswer('some_token_123456789')
await expect(
createProgram().parseAsync(['node', 'tdc', 'auth', 'token']),
).rejects.toThrow('Permission denied')
})
it('surfaces the keyring-fallback warning from getLastStorageResult on stderr', async () => {
storeMocks.getLastStorageResult.mockReturnValue({
storage: 'config-file',
warning:
'system credential manager unavailable; token saved as plaintext in /home/user/.config/comms-cli/config.json',
})
mockPromptAnswer('some_token_123456789')
await createProgram().parseAsync(['node', 'tdc', 'auth', 'token'])
expect(errorSpy).toHaveBeenCalledWith(
'Warning:',
'system credential manager unavailable; token saved as plaintext in /home/user/.config/comms-cli/config.json',
)
})
it('throws NO_TOKEN without calling store.set when the input is empty (interactive + non-interactive)', async () => {
mockPromptAnswer('')
await expect(
createProgram().parseAsync(['node', 'tdc', 'auth', 'token']),
).rejects.toHaveProperty('code', 'NO_TOKEN')
// non-interactive (no TTY, no arg)
Object.defineProperty(process.stdin, 'isTTY', { value: undefined, configurable: true })
await expect(
createProgram().parseAsync(['node', 'tdc', 'auth', 'token']),
).rejects.toHaveProperty('code', 'NO_TOKEN')
expect(storeMocks.set).not.toHaveBeenCalled()
})
// Regression: positional secrets violate the Doist Secrets Management
// Standard (visible in `ps` / shell history). The command must reject
// unknown positionals rather than treat them as the token.
it('rejects a token passed as a positional argument and never calls store.set', async () => {
mockPromptAnswer('') // ensure no fall-through to the interactive prompt
await expect(
createProgram().parseAsync([
'node',
'tdc',
'auth',
'token',
'positional_secret_should_be_rejected',
]),
).rejects.toThrow()
expect(storeMocks.set).not.toHaveBeenCalled()
})
})
describe('token view subcommand', () => {
let writeSpy: ReturnType<typeof vi.spyOn>
// Capture the full stdout payload so we can assert pipe-safety: any
// extra preamble/trailer added by a future change would change this
// string and fail the test.
function stdoutPayload(): string {
return writeSpy.mock.calls.map((call: unknown[]) => String(call[0])).join('')
}
beforeEach(() => {
writeSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true)
storeMocks.active.mockReset()
storeMocks.list.mockReset()
})
afterEach(() => {
writeSpy.mockRestore()
vi.unstubAllEnvs()
})
it('prints exactly the current token snapshot to stdout with no envelope (pipe-safe)', async () => {
vi.stubEnv(TOKEN_ENV_VAR, '')
mockGetApiTokenSnapshot.mockResolvedValue(STORED_SNAPSHOT)
await createProgram().parseAsync(['node', 'tdc', 'auth', 'token', 'view'])
expect(mockGetApiTokenSnapshot).toHaveBeenCalledWith(undefined)
expect(stdoutPayload()).toBe('tk_stored_1234567890')
expect(consoleSpy).not.toHaveBeenCalled()
})
it('adds a trailing newline only when stdout is a TTY', async () => {
vi.stubEnv(TOKEN_ENV_VAR, '')
mockGetApiTokenSnapshot.mockResolvedValue(STORED_SNAPSHOT)
const originalIsTTY = process.stdout.isTTY
Object.defineProperty(process.stdout, 'isTTY', { value: true, configurable: true })
try {
await createProgram().parseAsync(['node', 'tdc', 'auth', 'token', 'view'])
} finally {
Object.defineProperty(process.stdout, 'isTTY', {
value: originalIsTTY,
configurable: true,
})
}
expect(stdoutPayload()).toBe('tk_stored_1234567890\n')
})
it('refreshes an expired OAuth token before printing', async () => {
vi.stubEnv(TOKEN_ENV_VAR, '')
const oauthAccount: CommsAccount = {
...STORED_ACCOUNT,
oauthClientId: 'tdd_123',
authBaseUrl: 'https://todoist.com',
authResource: 'https://comms.todoist.com',
}
mockGetApiTokenSnapshot.mockResolvedValue({
token: 'tk_refreshed_1234567890',
account: oauthAccount,
})
await createProgram().parseAsync(['node', 'tdc', 'auth', 'token', 'view'])
expect(mockGetApiTokenSnapshot).toHaveBeenCalledWith(undefined)
expect(stdoutPayload()).toBe('tk_refreshed_1234567890')
})
it('prints manual tokens returned by the token snapshot path', async () => {
vi.stubEnv(TOKEN_ENV_VAR, '')
mockGetApiTokenSnapshot.mockResolvedValue({
token: 'manual_token_1234567890',
account: { id: '', label: '', authMode: 'unknown', authScope: '' },
})
await createProgram().parseAsync(['node', 'tdc', 'auth', 'token', 'view'])
expect(mockGetApiTokenSnapshot).toHaveBeenCalledWith(undefined)
expect(stdoutPayload()).toBe('manual_token_1234567890')
})
it('refuses to print when the env var is set so the CLI does not disclose an unmanaged token', async () => {
vi.stubEnv(TOKEN_ENV_VAR, 'env_token_supplied_externally')
await expect(
createProgram().parseAsync(['node', 'tdc', 'auth', 'token', 'view']),
).rejects.toHaveProperty('code', 'TOKEN_FROM_ENV')
expect(mockGetApiTokenSnapshot).not.toHaveBeenCalled()
expect(stdoutPayload()).toBe('')
})
it('throws NOT_AUTHENTICATED when no token is stored', async () => {
vi.stubEnv(TOKEN_ENV_VAR, '')
mockGetApiTokenSnapshot.mockRejectedValue(new NoTokenError())
await expect(
createProgram().parseAsync(['node', 'tdc', 'auth', 'token', 'view']),
).rejects.toHaveProperty('code', 'NOT_AUTHENTICATED')
expect(stdoutPayload()).toBe('')
})
it('passes per-command --user through to the token snapshot path', async () => {
vi.stubEnv(TOKEN_ENV_VAR, '')
mockGetApiTokenSnapshot.mockResolvedValue(STORED_SNAPSHOT)
await createProgram().parseAsync([
'node',
'tdc',
'auth',
'token',
'view',
'--user',
'1',
])
expect(mockGetApiTokenSnapshot).toHaveBeenCalledWith('1')
expect(stdoutPayload()).toBe('tk_stored_1234567890')
})
it('rejects per-command --user with ACCOUNT_NOT_FOUND when the ref does not match', async () => {
vi.stubEnv(TOKEN_ENV_VAR, '')
mockGetApiTokenSnapshot.mockRejectedValue(new NoTokenError())
await expect(
createProgram().parseAsync([
'node',
'tdc',
'auth',
'token',
'view',
'--user',
'999',
]),
).rejects.toHaveProperty('code', 'ACCOUNT_NOT_FOUND')
expect(mockGetApiTokenSnapshot).toHaveBeenCalledWith('999')
expect(stdoutPayload()).toBe('')
})
})
describe('global --user flag', () => {
// Tests simulate `src/index.ts`'s startup: mutate `process.argv` +
// `resetGlobalArgs()` to rebuild the parser cache, then hand
// commander the already-stripped argv (no `--user` token).
let originalArgv: string[]
let writeSpy: ReturnType<typeof vi.spyOn>
beforeEach(() => {
originalArgv = process.argv
writeSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true)
})
afterEach(() => {
process.argv = originalArgv
resetGlobalArgs()
writeSpy.mockRestore()
vi.unstubAllEnvs()
})
it('threads `tdc --user <ref> auth token view` into token refresh', async () => {
vi.stubEnv(TOKEN_ENV_VAR, '')
mockGetApiTokenSnapshot.mockResolvedValue(STORED_SNAPSHOT)
process.argv = ['node', 'tdc', '--user', '1', 'auth', 'token', 'view']
resetGlobalArgs()
await createProgram().parseAsync(['node', 'tdc', 'auth', 'token', 'view'])
expect(mockGetApiTokenSnapshot).toHaveBeenCalledWith('1')
expect(writeSpy.mock.calls.map((c: unknown[]) => String(c[0])).join('')).toBe(
'tk_stored_1234567890',
)
})
it('threads `tdc --user <ref> auth status` into the snapshot used by fetchLive', async () => {
vi.stubEnv(TOKEN_ENV_VAR, '')
storeMocks.list.mockResolvedValue(STORED_RECORDS)
storeMocks.active.mockResolvedValue(STORED_SNAPSHOT)
mockGetApiTokenSnapshot.mockResolvedValue({
token: 'tk_refreshed_1234567890',
account: {
...STORED_ACCOUNT,
authResource: 'https://comms.staging.todoist.com',
},
})
mockCreateWrappedCommsClient.mockReturnValue({
users: { getSessionUser: vi.fn().mockResolvedValue(TEST_USER) },
// biome-ignore lint/suspicious/noExplicitAny: only the methods used in this test matter
} as any)
process.argv = ['node', 'tdc', '--user', '1', 'auth', 'status']
resetGlobalArgs()
await createProgram().parseAsync(['node', 'tdc', 'auth', 'status'])
expect(storeMocks.active).toHaveBeenCalledWith('1')
expect(mockGetApiTokenSnapshot).toHaveBeenCalledWith('1')
expect(mockCreateWrappedCommsClient).toHaveBeenCalledWith('tk_refreshed_1234567890', {
baseUrl: 'https://comms.staging.todoist.com',
})
expect(consoleSpy).toHaveBeenCalledWith('✓ Authenticated')
})
it('blocks `tdc --user <wrong> auth logout` with ACCOUNT_NOT_FOUND before touching storage', async () => {
// `withUserRefAware` validates the global ref against `store.list()`
// before substituting it into the store call, so a non-matching ref
// surfaces as a typed miss instead of cli-core's silent clear no-op.
storeMocks.list.mockResolvedValue([
{
account: {
id: '1',
label: 'Test User',
authMode: 'read-write',
authScope: 'user:read',
},
},
])
process.argv = ['node', 'tdc', '--user', '999', 'auth', 'logout']
resetGlobalArgs()
const program = createProgram()
await expect(
program.parseAsync(['node', 'tdc', 'auth', 'logout']),
).rejects.toHaveProperty('code', 'ACCOUNT_NOT_FOUND')
expect(storeMocks.clear).not.toHaveBeenCalled()
})
})
describe('status subcommand', () => {
// All happy-path tests drive a controllable snapshot store directly
// into `attachCommsStatusCommand` so the `fetchLive` →
// `renderText` / `renderJson` path is covered without relying on
// process state (env vars, secure store) leaking from the host. The
// `onNotAuthenticated` branch is exercised below via `createProgram()`,
// which reaches it because no token resolves in the test environment.
const SNAPSHOT_ACCOUNT: CommsAccount = {
id: String(TEST_USER.id),
label: TEST_USER.fullName,
authMode: 'read-write',
authScope: COMMS_SCOPE,
authResource: 'https://comms.staging.todoist.com',
}
function programWithSnapshot(): Command {
const program = new Command()
program.exitOverride()
const auth = program.command('auth')
const snapshotStore: CommsTokenStore = {
async active() {
return { token: 'snapshot_token', account: SNAPSHOT_ACCOUNT }
},
async set() {},
async clear() {
return null
},
async list() {
return [{ account: SNAPSHOT_ACCOUNT, isDefault: true }]
},
async setDefault() {},
async setBundle() {},
async activeBundle() {
return { account: SNAPSHOT_ACCOUNT, bundle: { accessToken: 'snapshot_token' } }
},
async activeAccount() {
return { account: SNAPSHOT_ACCOUNT, isDefault: true }
},
getLastStorageResult: () => undefined,
getLastClearResult: () => undefined,
}
attachCommsStatusCommand(auth, snapshotStore)
return program
}
beforeEach(() => {
mockGetApiTokenSnapshot.mockResolvedValue({
token: 'snapshot_token',
account: SNAPSHOT_ACCOUNT,
})
mockCreateWrappedCommsClient.mockReturnValue({
users: { getSessionUser: vi.fn().mockResolvedValue(TEST_USER) },
// biome-ignore lint/suspicious/noExplicitAny: only the methods used in this test matter
} as any)
})
it('renders text status from the snapshot', async () => {
await programWithSnapshot().parseAsync(['node', 'tdc', 'auth', 'status'])
expect(mockCreateWrappedCommsClient).toHaveBeenCalledWith('snapshot_token', {
baseUrl: 'https://comms.staging.todoist.com',
})
expect(consoleSpy).toHaveBeenCalledWith('✓ Authenticated')
expect(consoleSpy).toHaveBeenCalledWith(' Email: test@example.com')
expect(consoleSpy).toHaveBeenCalledWith(' Name: Test User')
expect(consoleSpy).toHaveBeenCalledWith(' Mode: read-write')
})
it('emits the JSON envelope from the snapshot path', async () => {
await programWithSnapshot().parseAsync(['node', 'tdc', 'auth', 'status', '--json'])
const printed = consoleSpy.mock.calls[0][0] as string
expect(JSON.parse(printed)).toEqual({
id: 1,
email: 'test@example.com',
name: 'Test User',
authMode: 'read-write',
authScope: COMMS_SCOPE,
source: 'config',
})
})
it('emits a single newline-free NDJSON line from the snapshot path', async () => {
await programWithSnapshot().parseAsync(['node', 'tdc', 'auth', 'status', '--ndjson'])
// NDJSON must be one JSON value per line — assert one console.log
// call whose payload contains no embedded newline (would slip
// through a pretty-printed JSON regression).
expect(consoleSpy).toHaveBeenCalledTimes(1)
const printed = consoleSpy.mock.calls[0][0] as string
expect(printed).not.toContain('\n')
expect(JSON.parse(printed)).toEqual({
id: 1,
email: 'test@example.com',
name: 'Test User',
authMode: 'read-write',
authScope: COMMS_SCOPE,
source: 'config',
})
})
it('translates a 401 from the live API into a NO_TOKEN CliError', async () => {
// Snapshot exists (e.g. a stored token), but the API rejects it
// with 401 — the shared `gatherStatusData` 401 branch must wrap
// it in the standard `NO_TOKEN` envelope so users see the
// "re-authenticate" hint, not a raw `CommsRequestError`.
mockCreateWrappedCommsClient.mockReturnValue({
users: {
getSessionUser: vi
.fn()
.mockRejectedValue(new CommsRequestError('Authentication required', 401)),
},
// biome-ignore lint/suspicious/noExplicitAny: only the methods used in this test matter
} as any)
await expect(
programWithSnapshot().parseAsync(['node', 'tdc', 'auth', 'status']),
).rejects.toHaveProperty('code', 'NO_TOKEN')
})
it('throws NoTokenError when no token is stored at all', async () => {
// Drive a store whose `active()` returns null so the
// `onNotAuthenticated` branch fires regardless of any keyring /
// env state on the host running the tests.
const program = new Command()
program.exitOverride()
const auth = program.command('auth')
const emptyStore: CommsTokenStore = {
async active() {
return null
},
async set() {},
async clear() {
return null
},
async list() {
return []
},
async setDefault() {},
async setBundle() {},
async activeBundle() {
return null
},
async activeAccount() {
return null
},
getLastStorageResult: () => undefined,
getLastClearResult: () => undefined,
}
attachCommsStatusCommand(auth, emptyStore)
await expect(
program.parseAsync(['node', 'tdc', 'auth', 'status']),
).rejects.toHaveProperty('code', 'NO_TOKEN')
})
})
describe('login subcommand wiring', () => {
const OAUTH_ACCOUNT: CommsAccount = {
...STORED_ACCOUNT,
authResource: 'https://comms.todoist.com',
}
beforeEach(() => {
storeMocks.active.mockReset().mockResolvedValue(null)
storeMocks.getLastStorageResult.mockReset().mockReturnValue(undefined)
mockCreateWrappedCommsClient.mockReset()
mockGetConfig.mockReset().mockResolvedValue({})
mockUpdateConfig.mockReset().mockResolvedValue(undefined)
})
it('passes the comms provider, store, port, and renderers to cli-core attachLoginCommand', async () => {
createProgram()
expect(mockAttachLoginCommand).toHaveBeenCalledTimes(1)
const [, options] = mockAttachLoginCommand.mock.calls[0]
expect(options.preferredPort).toBe(8766)
expect(typeof options.provider.prepare).toBe('function')
expect(typeof options.provider.authorize).toBe('function')
expect(typeof options.provider.exchangeCode).toBe('function')
expect(typeof options.provider.validateToken).toBe('function')
expect(typeof options.store.active).toBe('function')
expect(typeof options.store.set).toBe('function')
expect(typeof options.store.clear).toBe('function')
expect(typeof options.renderSuccess).toBe('function')
expect(typeof options.renderError).toBe('function')
expect(options.renderSuccess()).toContain("You're connected")
expect(options.renderError('boom')).toContain('Authentication failed')
})
it('resolveScopes returns standard, read-only, or full-access OAuth scopes', () => {
createProgram()
const [, options] = mockAttachLoginCommand.mock.calls[0]
const writeScopes = options.resolveScopes({ readOnly: false, flags: {} })
const fullScopes = options.resolveScopes({
readOnly: false,
flags: { fullAccess: true },
})
const readScopes = options.resolveScopes({ readOnly: true, flags: {} })
expect(writeScopes).toContain('comms:content:write')
expect(writeScopes).toContain('comms:messages:write')
expect(writeScopes).not.toContain('comms:content:delete')
expect(writeScopes).not.toContain('user:write')
expect(fullScopes).toContain('comms:content:delete')
expect(fullScopes).toContain('user:write')
expect(readScopes).not.toContain('comms:content:write')
expect(readScopes).toContain('comms:content:read')
})
it('registers --full-access and rejects combining it with --read-only', () => {
const program = createProgram()
const authCommand = program.commands.find((command) => command.name() === 'auth')
const loginCommand = authCommand?.commands.find((command) => command.name() === 'login')
expect(loginCommand?.options.some((option) => option.long === '--full-access')).toBe(
true,
)
const [, options] = mockAttachLoginCommand.mock.calls[0]
expect(() =>
options.resolveScopes({ readOnly: true, flags: { fullAccess: true } }),
).toThrow('Choose either --read-only or --full-access, not both.')
})
it('sets the only available workspace as current after successful OAuth login', async () => {
mockGetConfig.mockResolvedValue({ currentWorkspace: 48121 })
storeMocks.active.mockResolvedValue({
token: 'oauth-token',
account: OAUTH_ACCOUNT,
})
mockWorkspaceClient([workspace(69, 'Doist')])
createProgram()
const [, options] = mockAttachLoginCommand.mock.calls[0]
await options.onSuccess({
account: OAUTH_ACCOUNT,
view: { json: true, ndjson: false },
flags: {},
})
expect(mockUpdateConfig).toHaveBeenCalledTimes(1)
expect(mockUpdateConfig).toHaveBeenCalledWith({ currentWorkspace: 69 })
})
it('clears the current workspace when it no longer belongs to the logged-in account', async () => {
mockGetConfig.mockResolvedValue({ currentWorkspace: 48121 })
storeMocks.active.mockResolvedValue({
token: 'oauth-token',
account: OAUTH_ACCOUNT,
})
mockWorkspaceClient([workspace(69, 'Doist'), workspace(70)])
createProgram()
const [, options] = mockAttachLoginCommand.mock.calls[0]
await options.onSuccess({
account: OAUTH_ACCOUNT,
view: { json: true, ndjson: false },
flags: {},
})
expect(mockUpdateConfig).toHaveBeenCalledTimes(1)
expect(mockUpdateConfig).toHaveBeenCalledWith({ currentWorkspace: undefined })
})
})
describe('logout subcommand', () => {
const WARNING_RESULT = {
storage: 'config-file' as const,
warning:
'system credential manager unavailable; local auth state cleared in /home/user/.config/comms-cli/config.json',
}
beforeEach(() => {
storeMocks.clear.mockReset().mockResolvedValue(undefined)
storeMocks.getLastClearResult.mockReset().mockReturnValue({ storage: 'secure-store' })
})
it('clears the API token', async () => {
await createProgram().parseAsync(['node', 'tdc', 'auth', 'logout'])
expect(storeMocks.clear).toHaveBeenCalled()
expect(consoleSpy).toHaveBeenCalledWith('✓ Logged out')
expect(consoleSpy).toHaveBeenCalledWith(
'Stored token removed from the system credential manager',
)
})
it('surfaces keyring-fallback warning to stderr in plain mode', async () => {
storeMocks.getLastClearResult.mockReturnValue(WARNING_RESULT)
await createProgram().parseAsync(['node', 'tdc', 'auth', 'logout'])
expect(consoleSpy).toHaveBeenCalledWith('✓ Logged out')
expect(errorSpy).toHaveBeenCalledWith('Warning:', WARNING_RESULT.warning)
})
it('routes warning to stderr and emits JSON envelope on stdout in --json mode', async () => {
storeMocks.getLastClearResult.mockReturnValue(WARNING_RESULT)
await createProgram().parseAsync(['node', 'tdc', 'auth', 'logout', '--json'])
const stdoutLines = consoleSpy.mock.calls.map((c: unknown[]) => String(c[0]))
expect(stdoutLines).toHaveLength(1)
expect(JSON.parse(stdoutLines[0])).toEqual({ ok: true })
// Plain "Stored token removed" confirmation must be suppressed under --json.
expect(stdoutLines.join('\n')).not.toContain('Stored token removed')
expect(errorSpy).toHaveBeenCalledWith('Warning:', WARNING_RESULT.warning)
})
it('routes warning to stderr and keeps stdout silent in --ndjson mode', async () => {
storeMocks.getLastClearResult.mockReturnValue(WARNING_RESULT)
await createProgram().parseAsync(['node', 'tdc', 'auth', 'logout', '--ndjson'])
expect(consoleSpy).not.toHaveBeenCalled()
expect(errorSpy).toHaveBeenCalledWith('Warning:', WARNING_RESULT.warning)
})
})
})