@moxxy/plugin-provider-claude-code 0.30.0 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/login.test.ts CHANGED
@@ -1,444 +1,135 @@
1
- import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
2
- import { promises as fs } from 'node:fs';
3
- import * as os from 'node:os';
4
- import * as path from 'node:path';
5
- import { storeTokenSet, type OAuthVault } from '@moxxy/plugin-oauth';
1
+ import { afterAll, beforeEach, describe, expect, it } from 'vitest';
6
2
  import type { ProviderAuthContext } from '@moxxy/sdk';
7
- import { assertDefined } from '@moxxy/sdk';
8
- import { CLAUDE_CLIENT_ID, CLAUDE_TOKEN_URL } from './constants.js';
9
3
  import {
4
+ __setClaudeCommandRunner,
5
+ checkClaudeCliAuth,
10
6
  claudeLogin,
11
7
  claudeLogout,
12
8
  claudeStatus,
13
- ensureFreshClaudeTokens,
14
- refreshClaudeAccessToken,
15
- __setClaudeFetch,
16
- __setClaudeOpenBrowser,
17
- __setClaudeSleep,
18
- __setClaudeTimeoutMs,
9
+ resolveClaudeExecutable,
19
10
  } from './login.js';
20
11
 
21
- interface FakeVault extends OAuthVault {
22
- readonly store: Map<string, string>;
23
- }
24
-
25
- function makeVault(): FakeVault {
12
+ function ctx(providerConfig?: Readonly<Record<string, unknown>>): ProviderAuthContext {
26
13
  const store = new Map<string, string>();
27
14
  return {
28
- store,
29
- get: async (k) => store.get(k) ?? null,
30
- set: async (k, v) => {
31
- store.set(k, v);
32
- },
33
- delete: async (k) => store.delete(k),
34
- };
35
- }
36
-
37
- function makeCtx(vault: OAuthVault, answers: string[]): ProviderAuthContext {
38
- const queue = [...answers];
39
- return {
40
- vault,
41
15
  headless: false,
16
+ ...(providerConfig ? { providerConfig } : {}),
42
17
  write: () => {},
43
- prompt: async () => queue.shift() ?? '',
18
+ vault: {
19
+ get: async (key) => store.get(key) ?? null,
20
+ set: async (key, value) => { store.set(key, value); },
21
+ delete: async (key) => store.delete(key),
22
+ },
44
23
  };
45
24
  }
46
25
 
47
- function jsonResponse(obj: unknown, status = 200): Response {
48
- return {
49
- ok: status >= 200 && status < 300,
50
- status,
51
- json: async () => obj,
52
- text: async () => JSON.stringify(obj),
53
- } as unknown as Response;
54
- }
55
-
56
- const META = { clientId: CLAUDE_CLIENT_ID, tokenUrl: CLAUDE_TOKEN_URL };
57
-
58
- // The refresh path takes a cross-process lockfile under `<moxxy home>/locks`;
59
- // point MOXXY_HOME at a temp dir so tests never touch the real ~/.moxxy.
60
- let moxxyHomeTmp: string;
61
- const priorMoxxyHome = process.env.MOXXY_HOME;
62
- beforeAll(async () => {
63
- moxxyHomeTmp = await fs.mkdtemp(path.join(os.tmpdir(), 'mox-claude-login-'));
64
- process.env.MOXXY_HOME = moxxyHomeTmp;
65
- });
66
- afterAll(async () => {
67
- if (priorMoxxyHome === undefined) delete process.env.MOXXY_HOME;
68
- else process.env.MOXXY_HOME = priorMoxxyHome;
69
- await fs.rm(moxxyHomeTmp, { recursive: true, force: true });
70
- });
26
+ const ok = (stdout = '', code = 0) => Promise.resolve({ code, stdout, stderr: '' });
71
27
 
72
28
  beforeEach(() => {
73
- __setClaudeOpenBrowser(async () => {});
74
- __setClaudeSleep(async () => {}); // don't actually back off under test
75
- __setClaudeTimeoutMs(50); // bound the hung-connection tests; default is 30s
76
- __setClaudeFetch(async () => {
77
- throw new Error('unexpected fetch — a test forgot to stub __setClaudeFetch');
78
- });
29
+ delete process.env.CLAUDE_CODE_EXECUTABLE;
79
30
  });
80
31
 
81
- /**
82
- * A fetch that respects the `AbortSignal` exactly like the real one: it never
83
- * resolves on its own, so it only settles when the per-attempt deadline aborts
84
- * it (mirroring a half-open socket / black-holing proxy).
85
- */
86
- function hangingFetch(): typeof fetch {
87
- return ((_url, init) =>
88
- new Promise((_resolve, reject) => {
89
- const signal = (init as { signal?: AbortSignal } | undefined)?.signal;
90
- if (signal?.aborted) {
91
- reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
92
- return;
93
- }
94
- signal?.addEventListener('abort', () => {
95
- reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
96
- });
97
- })) as typeof fetch;
98
- }
99
-
100
32
  afterAll(() => {
101
- __setClaudeFetch(fetch);
102
- __setClaudeTimeoutMs(30_000);
33
+ __setClaudeCommandRunner(async () => ({ code: 1, stdout: '', stderr: 'not configured' }));
103
34
  });
104
35
 
105
- describe('claudeLogin', () => {
106
- it('stores a pasted `setup-token` verbatim, with no refresh token', async () => {
107
- const vault = makeVault();
108
- const res = await claudeLogin(makeCtx(vault, ['sk-ant-oat-PASTED']));
109
- expect(vault.store.get('oauth/claude-code/access_token')).toBe('sk-ant-oat-PASTED');
110
- expect(vault.store.has('oauth/claude-code/refresh_token')).toBe(false);
111
- expect(res).toEqual({});
112
- });
113
-
114
- it('runs the out-of-band flow and exchanges the pasted code for tokens', async () => {
115
- const vault = makeVault();
116
- const calls: Array<{ url: string; body: Record<string, unknown> }> = [];
117
- __setClaudeFetch(async (url, init) => {
118
- calls.push({ url: String(url), body: JSON.parse(String(init?.body ?? '{}')) });
119
- return jsonResponse({
120
- access_token: 'access-1',
121
- refresh_token: 'refresh-1',
122
- expires_in: 3600,
123
- token_type: 'Bearer',
124
- account: { email_address: 'me@example.com' },
125
- });
126
- });
127
-
128
- // First prompt empty => browser flow; second prompt => the auth code.
129
- const res = await claudeLogin(makeCtx(vault, ['', 'AUTHCODE']));
130
-
131
- expect(calls).toHaveLength(1);
132
- const call0 = calls[0];
133
- assertDefined(call0, 'one call asserted above');
134
- expect(call0.url).toBe(CLAUDE_TOKEN_URL);
135
- expect(call0.body).toMatchObject({
136
- grant_type: 'authorization_code',
137
- code: 'AUTHCODE',
138
- client_id: CLAUDE_CLIENT_ID,
139
- redirect_uri: 'https://console.anthropic.com/oauth/code/callback',
36
+ describe('Claude CLI authentication', () => {
37
+ it('accepts an already authenticated CLI without invoking login', async () => {
38
+ const calls: string[][] = [];
39
+ __setClaudeCommandRunner(async (_exe, args) => {
40
+ calls.push([...args]);
41
+ return ok(JSON.stringify({ loggedIn: true, email: 'me@example.com' }));
140
42
  });
141
- expect(typeof call0.body.code_verifier).toBe('string');
142
- expect(vault.store.get('oauth/claude-code/access_token')).toBe('access-1');
143
- expect(vault.store.get('oauth/claude-code/refresh_token')).toBe('refresh-1');
144
- expect(vault.store.get('oauth/claude-code/extras')).toContain('me@example.com');
145
- expect(res.accountId).toBe('me@example.com');
43
+ await expect(claudeLogin(ctx())).resolves.toEqual({ accountId: 'me@example.com' });
44
+ expect(calls).toEqual([['auth', 'status']]);
146
45
  });
147
46
 
148
- it('retries a transient 5xx from the token endpoint and then succeeds', async () => {
149
- const vault = makeVault();
150
- let calls = 0;
151
- __setClaudeFetch(async () => {
152
- calls++;
153
- if (calls < 3) return jsonResponse({ error: { type: 'api_error', message: 'Internal server error' } }, 500);
154
- return jsonResponse({ access_token: 'access-after-retry', token_type: 'Bearer', expires_in: 3600 });
47
+ it('invokes the CLI login flow when signed out and verifies the result', async () => {
48
+ const calls: string[][] = [];
49
+ __setClaudeCommandRunner(async (_exe, args) => {
50
+ calls.push([...args]);
51
+ if (args[1] === 'login') return ok();
52
+ return ok(JSON.stringify({ loggedIn: calls.length > 2, account: 'subscriber@example.com' }));
155
53
  });
156
-
157
- const res = await claudeLogin(makeCtx(vault, ['', 'AUTHCODE']));
158
-
159
- expect(calls).toBe(3); // two 500s, third attempt wins
160
- expect(vault.store.get('oauth/claude-code/access_token')).toBe('access-after-retry');
161
- expect(res.expiresAt).toBeGreaterThan(0);
54
+ await expect(claudeLogin(ctx())).resolves.toEqual({ accountId: 'subscriber@example.com' });
55
+ expect(calls).toEqual([
56
+ ['auth', 'status'],
57
+ ['auth', 'login'],
58
+ ['auth', 'status'],
59
+ ]);
162
60
  });
163
61
 
164
- it('does NOT retry a deterministic 4xx — surfaces it immediately', async () => {
165
- const vault = makeVault();
166
- let calls = 0;
167
- __setClaudeFetch(async () => {
168
- calls++;
169
- return jsonResponse({ error: { type: 'invalid_request', message: 'invalid_grant' } }, 400);
62
+ it('uses a configured executable path containing spaces in every auth surface', async () => {
63
+ process.env.CLAUDE_CODE_EXECUTABLE = '/wrong/path/claude';
64
+ const executable = '/Applications/Claude Code/bin/claude';
65
+ const calls: Array<{ executable: string; args: readonly string[] }> = [];
66
+ __setClaudeCommandRunner(async (seenExecutable, args) => {
67
+ calls.push({ executable: seenExecutable, args });
68
+ return args[1] === 'logout' ? ok() : ok('{"loggedIn":true}');
170
69
  });
171
-
172
- await expect(claudeLogin(makeCtx(vault, ['', 'AUTHCODE']))).rejects.toThrow(/HTTP 400/);
173
- expect(calls).toBe(1);
174
- });
175
-
176
- it('gives a transient-retry hint after exhausting attempts on persistent 5xx', async () => {
177
- const vault = makeVault();
178
- let calls = 0;
179
- __setClaudeFetch(async () => {
180
- calls++;
181
- return jsonResponse({ error: { type: 'api_error', message: 'Internal server error' } }, 500);
182
- });
183
-
184
- await expect(claudeLogin(makeCtx(vault, ['', 'AUTHCODE']))).rejects.toThrow(/after 3 attempts/);
185
- expect(calls).toBe(3);
70
+ await claudeLogin(ctx({ executable }));
71
+ await claudeStatus(ctx({ executable }));
72
+ await claudeLogout(ctx({ executable }));
73
+ expect(calls.map((call) => call.executable)).toEqual([executable, executable, executable, executable]);
74
+ expect(calls.map((call) => call.args)).toEqual([
75
+ ['auth', 'status'],
76
+ ['auth', 'status'],
77
+ ['auth', 'status'],
78
+ ['auth', 'logout'],
79
+ ]);
80
+ expect(resolveClaudeExecutable({ executable: '/a path/claude' })).toBe('/a path/claude');
186
81
  });
187
82
 
188
- it('splits a pasted `code#state` and rejects a mismatched state', async () => {
189
- const vault = makeVault();
190
- // The internally-generated state will never equal "WRONG", so this must throw.
191
- await expect(claudeLogin(makeCtx(vault, ['', 'THECODE#WRONGSTATE']))).rejects.toThrow(/state/i);
83
+ it('does not accept signed-in JSON from a failed status command', async () => {
84
+ __setClaudeCommandRunner(async () => ({ code: 2, stdout: '{"loggedIn":true}', stderr: 'status failed' }));
85
+ await expect(checkClaudeCliAuth()).resolves.toMatchObject({ state: 'error' });
192
86
  });
193
87
 
194
- it('omits expiresAt entirely for a pasted setup-token (no false "expired")', async () => {
195
- const vault = makeVault();
196
- const res = await claudeLogin(makeCtx(vault, ['sk-ant-oat-PASTED']));
197
- // Absent expiry must be omitted, not collapsed to 0 (which reads as expired).
198
- expect('expiresAt' in res).toBe(false);
88
+ it('preserves signed-out JSON from a non-zero status command', async () => {
89
+ __setClaudeCommandRunner(async () => ({ code: 1, stdout: '{"loggedIn":false}', stderr: '' }));
90
+ await expect(checkClaudeCliAuth()).resolves.toMatchObject({ state: 'signed-out' });
199
91
  });
200
92
 
201
- it('omits expiresAt when the token response has no expires_in', async () => {
202
- const vault = makeVault();
203
- __setClaudeFetch(async () =>
204
- jsonResponse({ access_token: 'access-noexp', refresh_token: 'r', token_type: 'Bearer' }),
205
- );
206
- const res = await claudeLogin(makeCtx(vault, ['', 'AUTHCODE']));
207
- expect(res.accountId).toBeUndefined();
208
- expect('expiresAt' in res).toBe(false);
93
+ it('distinguishes a missing executable', async () => {
94
+ __setClaudeCommandRunner(async () => ({
95
+ code: 1, stdout: '', stderr: '', error: Object.assign(new Error('spawn ENOENT'), { code: 'ENOENT' }),
96
+ }));
97
+ const status = await checkClaudeCliAuth('/missing/claude');
98
+ expect(status.state).toBe('missing');
99
+ expect(status.message).toMatch(/Install Claude Code/);
209
100
  });
210
101
 
211
- it('treats a 200 with a non-JSON body as transient and retries', async () => {
212
- const vault = makeVault();
213
- let calls = 0;
214
- __setClaudeFetch(async () => {
215
- calls++;
216
- if (calls < 2) {
217
- return {
218
- ok: true,
219
- status: 200,
220
- json: async () => {
221
- throw new SyntaxError('Unexpected token < in JSON');
222
- },
223
- text: async () => '<html>captive portal</html>',
224
- } as unknown as Response;
225
- }
226
- return jsonResponse({ access_token: 'recovered', token_type: 'Bearer', expires_in: 3600 });
227
- });
228
-
229
- const res = await claudeLogin(makeCtx(vault, ['', 'AUTHCODE']));
230
- expect(calls).toBe(2); // bad 200 retried, second attempt wins
231
- expect(vault.store.get('oauth/claude-code/access_token')).toBe('recovered');
232
- expect(res.expiresAt).toBeGreaterThan(0);
102
+ it('distinguishes signed-out and signed-in states', async () => {
103
+ __setClaudeCommandRunner(async () => ok('{"loggedIn":false}'));
104
+ await expect(claudeStatus(ctx())).resolves.toMatchObject({ authState: 'signed-out' });
105
+ __setClaudeCommandRunner(async () => ok('{"loggedIn":true,"email":"x@y.test"}'));
106
+ await expect(claudeStatus(ctx())).resolves.toMatchObject({ authState: 'signed-in', accountId: 'x@y.test' });
233
107
  });
234
108
 
235
- it('surfaces a transient-retry hint when every 200 body is non-JSON', async () => {
236
- const vault = makeVault();
237
- let calls = 0;
238
- __setClaudeFetch(async () => {
239
- calls++;
240
- return {
241
- ok: true,
242
- status: 200,
243
- json: async () => {
244
- throw new SyntaxError('Unexpected token < in JSON');
245
- },
246
- text: async () => '',
247
- } as unknown as Response;
248
- });
249
- await expect(claudeLogin(makeCtx(vault, ['', 'AUTHCODE']))).rejects.toThrow(/after 3 attempts/);
250
- expect(calls).toBe(3);
109
+ it('reports unsupported CLI versions actionably', async () => {
110
+ __setClaudeCommandRunner(async () => ({ code: 1, stdout: '', stderr: 'unknown command auth' }));
111
+ const status = await checkClaudeCliAuth();
112
+ expect(status.state).toBe('unsupported');
113
+ expect(status.message).toMatch(/Update Claude Code/);
251
114
  });
252
115
 
253
- it('treats a 200 JSON primitive/array body as transient and retries', async () => {
254
- const vault = makeVault();
255
- let calls = 0;
256
- __setClaudeFetch(async () => {
257
- calls++;
258
- if (calls < 2) return jsonResponse([] as unknown, 200); // array, not an object
259
- return jsonResponse({ access_token: 'after-array', token_type: 'Bearer', expires_in: 3600 });
260
- });
261
- const res = await claudeLogin(makeCtx(vault, ['', 'AUTHCODE']));
262
- expect(calls).toBe(2);
263
- expect(res.expiresAt).toBeGreaterThan(0);
116
+ it('surfaces command failures without treating them as signed-out', async () => {
117
+ __setClaudeCommandRunner(async () => ({ code: 2, stdout: '', stderr: 'config is corrupt' }));
118
+ const status = await checkClaudeCliAuth();
119
+ expect(status.state).toBe('error');
120
+ await expect(claudeLogin(ctx())).rejects.toThrow(/config is corrupt/);
264
121
  });
265
122
 
266
- it('aborts a hung connection on the per-attempt deadline and retries', async () => {
267
- const vault = makeVault();
268
- const hang = hangingFetch();
123
+ it('logs out through the CLI without touching legacy vault entries', async () => {
124
+ const context = ctx();
125
+ await context.vault.set('oauth/claude-code/access_token', 'legacy-secret');
269
126
  let calls = 0;
270
- __setClaudeFetch(async (url, init) => {
127
+ __setClaudeCommandRunner(async (_exe, args) => {
271
128
  calls++;
272
- // First attempt: a half-open socket that never responds — must be aborted
273
- // by the deadline (not hang forever), reclassified as a transient, retried.
274
- if (calls < 2) return hang(url, init);
275
- return jsonResponse({ access_token: 'after-timeout', token_type: 'Bearer', expires_in: 3600 });
129
+ return args[1] === 'logout' ? ok() : ok('{"loggedIn":true}');
276
130
  });
277
-
278
- const res = await claudeLogin(makeCtx(vault, ['', 'AUTHCODE']));
131
+ await expect(claudeLogout(context)).resolves.toBe(true);
132
+ expect(await context.vault.get('oauth/claude-code/access_token')).toBe('legacy-secret');
279
133
  expect(calls).toBe(2);
280
- expect(vault.store.get('oauth/claude-code/access_token')).toBe('after-timeout');
281
- expect(res.expiresAt).toBeGreaterThan(0);
282
- });
283
-
284
- it('surfaces the transient-retry hint when every attempt hangs past the deadline', async () => {
285
- const vault = makeVault();
286
- const hang = hangingFetch();
287
- let calls = 0;
288
- __setClaudeFetch((url, init) => {
289
- calls++;
290
- return hang(url, init);
291
- });
292
- await expect(claudeLogin(makeCtx(vault, ['', 'AUTHCODE']))).rejects.toThrow(/after 3 attempts/);
293
- expect(calls).toBe(3);
294
- });
295
-
296
- it('refuses without a TTY prompt', async () => {
297
- const vault = makeVault();
298
- const ctx: ProviderAuthContext = { vault, headless: true, write: () => {} };
299
- await expect(claudeLogin(ctx)).rejects.toThrow(/interactive terminal/i);
300
- });
301
- });
302
-
303
- describe('token lifecycle', () => {
304
- it('ensureFreshClaudeTokens returns null when nothing is stored', async () => {
305
- expect(await ensureFreshClaudeTokens(makeVault())).toBeNull();
306
- });
307
-
308
- it('ensureFreshClaudeTokens returns a non-expired token without refreshing', async () => {
309
- const vault = makeVault();
310
- await storeTokenSet(
311
- vault,
312
- 'claude-code',
313
- { accessToken: 'a', refreshToken: 'r', expiresAt: Date.now() + 3_600_000, tokenType: 'Bearer' },
314
- META,
315
- );
316
- // __setClaudeFetch is the throwing default — proving no refresh happens.
317
- const fresh = await ensureFreshClaudeTokens(vault);
318
- expect(fresh).toMatchObject({ accessToken: 'a', canRefresh: true });
319
- });
320
-
321
- it('ensureFreshClaudeTokens refreshes + persists when expired', async () => {
322
- const vault = makeVault();
323
- await storeTokenSet(
324
- vault,
325
- 'claude-code',
326
- { accessToken: 'old', refreshToken: 'r-old', expiresAt: Date.now() - 1000, tokenType: 'Bearer' },
327
- META,
328
- );
329
- __setClaudeFetch(async (_url, init) => {
330
- expect(JSON.parse(String(init?.body ?? '{}'))).toMatchObject({
331
- grant_type: 'refresh_token',
332
- refresh_token: 'r-old',
333
- });
334
- return jsonResponse({ access_token: 'new', refresh_token: 'r-new', expires_in: 3600, token_type: 'Bearer' });
335
- });
336
- const fresh = await ensureFreshClaudeTokens(vault);
337
- expect(fresh?.accessToken).toBe('new');
338
- // Rotated refresh token persisted before returning.
339
- expect(vault.store.get('oauth/claude-code/refresh_token')).toBe('r-new');
340
- });
341
-
342
- it('coalesces concurrent refreshes — one IdP call, both consumers get the rotated token', async () => {
343
- const vault = makeVault();
344
- await storeTokenSet(
345
- vault,
346
- 'claude-code',
347
- { accessToken: 'old', refreshToken: 'r-old', expiresAt: Date.now() - 1000, tokenType: 'Bearer' },
348
- META,
349
- );
350
- let refreshCalls = 0;
351
- __setClaudeFetch(async () => {
352
- refreshCalls++;
353
- return jsonResponse({ access_token: 'new', refresh_token: 'r-new', expires_in: 3600, token_type: 'Bearer' });
354
- });
355
-
356
- const [a, b] = await Promise.all([
357
- ensureFreshClaudeTokens(vault),
358
- ensureFreshClaudeTokens(vault),
359
- ]);
360
-
361
- // The single-use refresh_token must be burned exactly once; the loser of
362
- // the race re-reads the winner's rotated bundle under the lock.
363
- expect(refreshCalls).toBe(1);
364
- expect(a?.accessToken).toBe('new');
365
- expect(b?.accessToken).toBe('new');
366
- expect(vault.store.get('oauth/claude-code/refresh_token')).toBe('r-new');
367
- });
368
-
369
- it('recovers from invalid_grant by retrying once with the refresh_token another process rotated in', async () => {
370
- const vault = makeVault();
371
- await storeTokenSet(
372
- vault,
373
- 'claude-code',
374
- { accessToken: 'old', refreshToken: 'r-dead', expiresAt: Date.now() - 1000, tokenType: 'Bearer' },
375
- META,
376
- );
377
- const attempted: string[] = [];
378
- __setClaudeFetch(async (_url, init) => {
379
- const body = JSON.parse(String(init?.body ?? '{}')) as { refresh_token?: string };
380
- attempted.push(body.refresh_token ?? '');
381
- if (body.refresh_token === 'r-dead') {
382
- // Simulate the cross-process race: another moxxy already rotated the
383
- // stored bundle, so OUR copy of the refresh token is single-use-spent.
384
- vault.store.set('oauth/claude-code/refresh_token', 'r-fresh');
385
- return jsonResponse({ error: 'invalid_grant' }, 400);
386
- }
387
- return jsonResponse({ access_token: 'new-2', refresh_token: 'r-next', expires_in: 3600, token_type: 'Bearer' });
388
- });
389
-
390
- const res = await refreshClaudeAccessToken(vault);
391
-
392
- expect(attempted).toEqual(['r-dead', 'r-fresh']);
393
- expect(res.token).toBe('new-2');
394
- expect(vault.store.get('oauth/claude-code/refresh_token')).toBe('r-next');
395
- });
396
-
397
- it('does NOT retry an invalid_grant when the stored refresh_token is unchanged (true re-auth case)', async () => {
398
- const vault = makeVault();
399
- await storeTokenSet(
400
- vault,
401
- 'claude-code',
402
- { accessToken: 'old', refreshToken: 'r-revoked', expiresAt: Date.now() - 1000, tokenType: 'Bearer' },
403
- META,
404
- );
405
- let calls = 0;
406
- __setClaudeFetch(async () => {
407
- calls++;
408
- return jsonResponse({ error: 'invalid_grant' }, 400);
409
- });
410
- await expect(refreshClaudeAccessToken(vault)).rejects.toThrow(/HTTP 400/);
411
- expect(calls).toBe(1);
412
- });
413
-
414
- it('refreshClaudeAccessToken throws when no refresh_token is stored', async () => {
415
- const vault = makeVault();
416
- await storeTokenSet(vault, 'claude-code', { accessToken: 'a', tokenType: 'Bearer' }, META);
417
- await expect(refreshClaudeAccessToken(vault)).rejects.toThrow(/refresh/i);
418
- });
419
-
420
- it('claudeStatus / claudeLogout report and clear stored creds', async () => {
421
- const vault = makeVault();
422
- const ctx = makeCtx(vault, []);
423
- await storeTokenSet(
424
- vault,
425
- 'claude-code',
426
- { accessToken: 'a', expiresAt: Date.now() + 1000, tokenType: 'Bearer' },
427
- { ...META, extras: { account_email: 'me@example.com' } },
428
- );
429
- const status = await claudeStatus(ctx);
430
- expect(status).toMatchObject({ accountId: 'me@example.com' });
431
- expect(await claudeLogout(ctx)).toBe(true);
432
- expect(await claudeStatus(ctx)).toBeNull();
433
- });
434
-
435
- it('claudeStatus omits expiresAt for a stored setup-token (no false "expired")', async () => {
436
- const vault = makeVault();
437
- const ctx = makeCtx(vault, []);
438
- // A pasted setup-token has no expiry — status must not surface 0/epoch.
439
- await storeTokenSet(vault, 'claude-code', { accessToken: 'a', tokenType: 'Bearer' }, META);
440
- const status = await claudeStatus(ctx);
441
- expect(status).not.toBeNull();
442
- expect('expiresAt' in (status as object)).toBe(false);
443
134
  });
444
135
  });