@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/dist/constants.d.ts +10 -38
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +10 -38
- package/dist/constants.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +28 -13
- package/dist/index.js.map +1 -1
- package/dist/login.d.ts +24 -44
- package/dist/login.d.ts.map +1 -1
- package/dist/login.js +122 -314
- package/dist/login.js.map +1 -1
- package/dist/process.d.ts +32 -0
- package/dist/process.d.ts.map +1 -0
- package/dist/process.js +194 -0
- package/dist/process.js.map +1 -0
- package/dist/protocol.d.ts +20 -0
- package/dist/protocol.d.ts.map +1 -0
- package/dist/protocol.js +242 -0
- package/dist/protocol.js.map +1 -0
- package/dist/provider.d.ts +46 -20
- package/dist/provider.d.ts.map +1 -1
- package/dist/provider.js +212 -17
- package/dist/provider.js.map +1 -1
- package/package.json +19 -5
- package/src/constants.ts +10 -40
- package/src/index.ts +50 -16
- package/src/login.test.ts +87 -396
- package/src/login.ts +146 -382
- package/src/process.test.ts +208 -0
- package/src/process.ts +220 -0
- package/src/protocol.ts +248 -0
- package/src/provider.test.ts +544 -30
- package/src/provider.ts +244 -25
package/src/login.ts
CHANGED
|
@@ -1,31 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
* Claude subscription login + token lifecycle.
|
|
3
|
-
*
|
|
4
|
-
* Claude's OAuth is an out-of-band (manual code-paste) authorization-code +
|
|
5
|
-
* PKCE flow whose token endpoint speaks JSON (not the form-encoded dialect
|
|
6
|
-
* the framework's `exchangeCodeForToken` / `refreshAccessToken` assume), so
|
|
7
|
-
* the HTTP exchange + refresh are implemented here. Everything else is reused
|
|
8
|
-
* from `@moxxy/plugin-oauth`: PKCE, the auth-URL builder, the browser opener,
|
|
9
|
-
* vault storage layout, and `parseTokenResponse`.
|
|
10
|
-
*/
|
|
11
|
-
|
|
12
|
-
import {
|
|
13
|
-
buildAuthUrl,
|
|
14
|
-
clearStoredCreds,
|
|
15
|
-
computeCodeChallenge,
|
|
16
|
-
generateCodeVerifier,
|
|
17
|
-
generateState,
|
|
18
|
-
isAuthRejection,
|
|
19
|
-
isExpired,
|
|
20
|
-
openInBrowser,
|
|
21
|
-
parseTokenResponse,
|
|
22
|
-
readStoredCreds,
|
|
23
|
-
storeTokenSet,
|
|
24
|
-
withCredentialLock,
|
|
25
|
-
type OAuthVault,
|
|
26
|
-
type StoredCreds,
|
|
27
|
-
type TokenSet,
|
|
28
|
-
} from '@moxxy/plugin-oauth';
|
|
1
|
+
import { spawn, type SpawnOptions } from 'node:child_process';
|
|
29
2
|
import { MoxxyError } from '@moxxy/sdk';
|
|
30
3
|
import type {
|
|
31
4
|
ProviderAuthContext,
|
|
@@ -33,394 +6,185 @@ import type {
|
|
|
33
6
|
ProviderOAuthStatus,
|
|
34
7
|
} from '@moxxy/sdk';
|
|
35
8
|
import {
|
|
36
|
-
|
|
37
|
-
|
|
9
|
+
CLAUDE_AUTH_LOGIN_ARGS,
|
|
10
|
+
CLAUDE_AUTH_LOGOUT_ARGS,
|
|
11
|
+
CLAUDE_AUTH_STATUS_ARGS,
|
|
12
|
+
CLAUDE_CODE_EXECUTABLE_ENV,
|
|
38
13
|
CLAUDE_CODE_PROVIDER_ID,
|
|
39
|
-
CLAUDE_CODE_SERVICE_NAME,
|
|
40
|
-
CLAUDE_REDIRECT_URI,
|
|
41
|
-
CLAUDE_SCOPES,
|
|
42
|
-
CLAUDE_TOKEN_URL,
|
|
43
14
|
} from './constants.js';
|
|
44
15
|
|
|
45
|
-
|
|
46
|
-
'Paste a token from `claude setup-token` (or press Enter to sign in via browser): ';
|
|
47
|
-
const CODE_PROMPT = 'Paste the authorization code shown after you approve: ';
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
* Drive an interactive Claude sign-in. Two ways in, both through one command:
|
|
51
|
-
* 1. paste an existing `claude setup-token` token (stored verbatim), or
|
|
52
|
-
* 2. press Enter to run the browser out-of-band authorization-code flow.
|
|
53
|
-
* Needs `ctx.prompt` (a TTY); headless callers use `CLAUDE_CODE_OAUTH_TOKEN`.
|
|
54
|
-
*/
|
|
55
|
-
export async function claudeLogin(ctx: ProviderAuthContext): Promise<ProviderOAuthResult> {
|
|
56
|
-
if (!ctx.prompt) {
|
|
57
|
-
throw new MoxxyError({
|
|
58
|
-
code: 'OAUTH_FLOW_NOT_SUPPORTED',
|
|
59
|
-
message: 'Claude sign-in needs an interactive terminal.',
|
|
60
|
-
hint:
|
|
61
|
-
'Run `claude setup-token` and set CLAUDE_CODE_OAUTH_TOKEN, or run ' +
|
|
62
|
-
'`moxxy login claude-code` in a terminal.',
|
|
63
|
-
context: { provider: CLAUDE_CODE_PROVIDER_ID },
|
|
64
|
-
});
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
const pasted = (await ctx.prompt(PASTE_PROMPT, { mask: true })).trim();
|
|
68
|
-
if (pasted) {
|
|
69
|
-
// A `setup-token` is a long-lived bearer with no refresh token; store it
|
|
70
|
-
// as-is. `isExpired` treats a missing expiry as non-expiring.
|
|
71
|
-
await storeTokenSet(
|
|
72
|
-
ctx.vault,
|
|
73
|
-
CLAUDE_CODE_PROVIDER_ID,
|
|
74
|
-
{ accessToken: pasted, tokenType: 'Bearer' },
|
|
75
|
-
{ clientId: CLAUDE_CLIENT_ID, tokenUrl: CLAUDE_TOKEN_URL },
|
|
76
|
-
);
|
|
77
|
-
ctx.write('\nStored your Claude token.\n');
|
|
78
|
-
return {};
|
|
79
|
-
}
|
|
16
|
+
export type ClaudeCliAuthState = 'signed-in' | 'signed-out' | 'missing' | 'unsupported' | 'error';
|
|
80
17
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
redirectUri: CLAUDE_REDIRECT_URI,
|
|
88
|
-
scopes: [...CLAUDE_SCOPES],
|
|
89
|
-
codeChallenge: challenge,
|
|
90
|
-
state,
|
|
91
|
-
extraAuthParams: { code: 'true' },
|
|
92
|
-
});
|
|
18
|
+
export interface ClaudeCliAuthStatus {
|
|
19
|
+
readonly state: ClaudeCliAuthState;
|
|
20
|
+
readonly executable: string;
|
|
21
|
+
readonly accountId?: string;
|
|
22
|
+
readonly message: string;
|
|
23
|
+
}
|
|
93
24
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
);
|
|
101
|
-
try {
|
|
102
|
-
await openBrowserImpl(authUrl);
|
|
103
|
-
} catch {
|
|
104
|
-
// Non-fatal — the user can open the URL surfaced above by hand.
|
|
105
|
-
}
|
|
25
|
+
export interface ClaudeCommandResult {
|
|
26
|
+
readonly code: number;
|
|
27
|
+
readonly stdout: string;
|
|
28
|
+
readonly stderr: string;
|
|
29
|
+
readonly error?: NodeJS.ErrnoException;
|
|
30
|
+
}
|
|
106
31
|
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
code: 'AUTH_DENIED',
|
|
113
|
-
message: 'No authorization code entered — sign-in cancelled.',
|
|
114
|
-
context: { provider: CLAUDE_CODE_PROVIDER_ID },
|
|
115
|
-
});
|
|
116
|
-
}
|
|
117
|
-
// Anthropic returns `code#state`, but often shows just the bare code, so the
|
|
118
|
-
// state check below is best-effort: it only fires when a state was pasted.
|
|
119
|
-
// The real CSRF/code-injection defense is PKCE — the `code_verifier` binds
|
|
120
|
-
// the code to this client session, so a foreign code fails the exchange.
|
|
121
|
-
const hash = entered.indexOf('#');
|
|
122
|
-
const code = hash >= 0 ? entered.slice(0, hash) : entered;
|
|
123
|
-
const returnedState = hash >= 0 ? entered.slice(hash + 1) : '';
|
|
124
|
-
if (returnedState && returnedState !== state) {
|
|
125
|
-
throw new MoxxyError({
|
|
126
|
-
code: 'AUTH_INVALID',
|
|
127
|
-
message: 'Authorization state mismatch — please run sign-in again.',
|
|
128
|
-
context: { provider: CLAUDE_CODE_PROVIDER_ID },
|
|
129
|
-
});
|
|
130
|
-
}
|
|
32
|
+
type CommandRunner = (
|
|
33
|
+
executable: string,
|
|
34
|
+
args: readonly string[],
|
|
35
|
+
options?: { readonly inherit?: boolean },
|
|
36
|
+
) => Promise<ClaudeCommandResult>;
|
|
131
37
|
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
// token response without `expires_in`). Surfacing `0` would read as "epoch =
|
|
137
|
-
// already expired" to the CLI status renderer, which only checks `!== undefined`.
|
|
138
|
-
return {
|
|
139
|
-
...(accountEmail ? { accountId: accountEmail } : {}),
|
|
140
|
-
...(tokenSet.expiresAt !== undefined ? { expiresAt: tokenSet.expiresAt } : {}),
|
|
141
|
-
};
|
|
38
|
+
let runCommandImpl: CommandRunner = runCommand;
|
|
39
|
+
/** Test seam. */
|
|
40
|
+
export function __setClaudeCommandRunner(runner: CommandRunner): void {
|
|
41
|
+
runCommandImpl = runner;
|
|
142
42
|
}
|
|
143
43
|
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
}
|
|
44
|
+
/** Resolve the executable without involving a shell (paths containing spaces are safe). */
|
|
45
|
+
export function resolveClaudeExecutable(config: Record<string, unknown> = {}): string {
|
|
46
|
+
const configured = config.executable;
|
|
47
|
+
if (typeof configured === 'string' && configured.trim()) return configured;
|
|
48
|
+
return process.env[CLAUDE_CODE_EXECUTABLE_ENV]?.trim() || 'claude';
|
|
150
49
|
}
|
|
151
50
|
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
}
|
|
51
|
+
/** Probe the installed CLI's supported, machine-readable authentication command. */
|
|
52
|
+
export async function checkClaudeCliAuth(executable = resolveClaudeExecutable()): Promise<ClaudeCliAuthStatus> {
|
|
53
|
+
const result = await runCommandImpl(executable, CLAUDE_AUTH_STATUS_ARGS);
|
|
54
|
+
if (result.error?.code === 'ENOENT') {
|
|
55
|
+
return {
|
|
56
|
+
state: 'missing', executable,
|
|
57
|
+
message: `Claude CLI executable not found: ${executable}. Install Claude Code or set ${CLAUDE_CODE_EXECUTABLE_ENV}.`,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
if (result.error) {
|
|
61
|
+
return { state: 'error', executable, message: `Could not run Claude CLI: ${result.error.message}` };
|
|
62
|
+
}
|
|
163
63
|
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
64
|
+
const combined = `${result.stdout}\n${result.stderr}`.trim();
|
|
65
|
+
const parsed = parseStatusOutput(result.stdout);
|
|
66
|
+
// Claude uses a machine-readable signed-out response on supported versions.
|
|
67
|
+
// Preserve that state even if a CLI version chooses a non-zero exit for it,
|
|
68
|
+
// but never accept signed-in readiness from a failed command.
|
|
69
|
+
if (parsed && !parsed.loggedIn) {
|
|
70
|
+
return { state: 'signed-out', executable, message: 'Claude CLI is installed but signed out. Run `moxxy login claude-code`.' };
|
|
71
|
+
}
|
|
72
|
+
if (parsed?.loggedIn && result.code === 0) {
|
|
73
|
+
return {
|
|
74
|
+
state: 'signed-in', executable,
|
|
75
|
+
...(parsed.accountId ? { accountId: parsed.accountId } : {}),
|
|
76
|
+
message: `Claude CLI is signed in${parsed.accountId ? ` as ${parsed.accountId}` : ''}.`,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
170
79
|
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
if (tokenSet.refreshToken && isExpired(tokenSet)) {
|
|
183
|
-
const refreshed = await refreshClaudeUnderLock(vault, stored);
|
|
184
|
-
return { accessToken: refreshed.accessToken, ...(refreshed.expiresAt !== undefined ? { expiresAt: refreshed.expiresAt } : {}), canRefresh: true };
|
|
80
|
+
if (looksUnsupported(combined)) {
|
|
81
|
+
return {
|
|
82
|
+
state: 'unsupported', executable,
|
|
83
|
+
message: 'This Claude CLI version does not support `claude auth status`. Update Claude Code and try again.',
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
if (result.code !== 0) {
|
|
87
|
+
return {
|
|
88
|
+
state: 'error', executable,
|
|
89
|
+
message: `Claude CLI auth status failed${combined ? `: ${combined}` : ` with exit code ${result.code}`}.`,
|
|
90
|
+
};
|
|
185
91
|
}
|
|
186
92
|
return {
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
canRefresh: tokenSet.refreshToken !== undefined,
|
|
93
|
+
state: 'unsupported', executable,
|
|
94
|
+
message: 'Claude CLI returned an unrecognized auth-status response. Update Claude Code and try again.',
|
|
190
95
|
};
|
|
191
96
|
}
|
|
192
97
|
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
)
|
|
201
|
-
|
|
202
|
-
if (!stored?.tokenSet.refreshToken) {
|
|
98
|
+
export async function claudeLogin(ctx: ProviderAuthContext): Promise<ProviderOAuthResult> {
|
|
99
|
+
const executable = resolveClaudeExecutable(ctx.providerConfig);
|
|
100
|
+
let status = await checkClaudeCliAuth(executable);
|
|
101
|
+
if (status.state === 'signed-in') return status.accountId ? { accountId: status.accountId } : {};
|
|
102
|
+
if (status.state !== 'signed-out') throw authError(status);
|
|
103
|
+
|
|
104
|
+
const login = await runCommandImpl(executable, CLAUDE_AUTH_LOGIN_ARGS, { inherit: true });
|
|
105
|
+
if (login.error) throw authError({ state: login.error.code === 'ENOENT' ? 'missing' : 'error', executable, message: login.error.message });
|
|
106
|
+
if (login.code !== 0) {
|
|
203
107
|
throw new MoxxyError({
|
|
204
|
-
code: '
|
|
205
|
-
message:
|
|
206
|
-
hint: 'Run `
|
|
108
|
+
code: 'AUTH_DENIED',
|
|
109
|
+
message: `Claude CLI login failed${login.stderr ? `: ${login.stderr.trim()}` : ` with exit code ${login.code}`}.`,
|
|
110
|
+
hint: 'Run `claude auth login` directly for more detail, then retry.',
|
|
207
111
|
context: { provider: CLAUDE_CODE_PROVIDER_ID },
|
|
208
112
|
});
|
|
209
113
|
}
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
/**
|
|
215
|
-
* Refresh + persist under the per-credential lock. Anthropic ROTATES the
|
|
216
|
-
* refresh_token on every refresh and invalidates the previous one, so two
|
|
217
|
-
* concurrent refreshes (a second consumer in this process, or another moxxy
|
|
218
|
-
* process — TUI alongside a desktop runner) must not both burn the same
|
|
219
|
-
* stored token. Under the lock we:
|
|
220
|
-
* 1. re-read the vault — if someone else already rotated and the new access
|
|
221
|
-
* token is still fresh, reuse it (coalesce; no IdP call at all);
|
|
222
|
-
* 2. otherwise refresh with the freshest stored refresh_token;
|
|
223
|
-
* 3. on an invalid_grant-style rejection, re-read once more — if the
|
|
224
|
-
* on-disk refresh_token changed under us (another process won a race we
|
|
225
|
-
* couldn't see), retry ONCE with the fresher token before declaring
|
|
226
|
-
* re-auth necessary.
|
|
227
|
-
*/
|
|
228
|
-
async function refreshClaudeUnderLock(vault: OAuthVault, baseline: StoredCreds): Promise<TokenSet> {
|
|
229
|
-
return withCredentialLock(`oauth-${CLAUDE_CODE_PROVIDER_ID}`, async () => {
|
|
230
|
-
const current = (await readStoredCreds(vault, CLAUDE_CODE_PROVIDER_ID)) ?? baseline;
|
|
231
|
-
if (current.tokenSet.accessToken !== baseline.tokenSet.accessToken && !isExpired(current.tokenSet)) {
|
|
232
|
-
return current.tokenSet;
|
|
233
|
-
}
|
|
234
|
-
const refreshToken = current.tokenSet.refreshToken ?? baseline.tokenSet.refreshToken;
|
|
235
|
-
if (!refreshToken) {
|
|
236
|
-
throw new MoxxyError({
|
|
237
|
-
code: 'AUTH_EXPIRED',
|
|
238
|
-
message: 'Claude token expired and no refresh_token is stored.',
|
|
239
|
-
hint: 'Run `moxxy login claude-code` again, or refresh `CLAUDE_CODE_OAUTH_TOKEN` via `claude setup-token`.',
|
|
240
|
-
context: { provider: CLAUDE_CODE_PROVIDER_ID },
|
|
241
|
-
});
|
|
242
|
-
}
|
|
243
|
-
const email = current.extras.account_email ?? baseline.extras.account_email;
|
|
244
|
-
try {
|
|
245
|
-
return await refreshAndPersist(vault, refreshToken, email);
|
|
246
|
-
} catch (err) {
|
|
247
|
-
if (isAuthRejection(err)) {
|
|
248
|
-
const latest = await readStoredCreds(vault, CLAUDE_CODE_PROVIDER_ID);
|
|
249
|
-
const latestRefresh = latest?.tokenSet.refreshToken;
|
|
250
|
-
if (latestRefresh && latestRefresh !== refreshToken) {
|
|
251
|
-
return refreshAndPersist(vault, latestRefresh, latest.extras.account_email ?? email);
|
|
252
|
-
}
|
|
253
|
-
}
|
|
254
|
-
throw err;
|
|
255
|
-
}
|
|
256
|
-
});
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
// --- internal HTTP (JSON dialect) -----------------------------------------
|
|
260
|
-
|
|
261
|
-
interface ClaudeExchangeResult {
|
|
262
|
-
readonly tokenSet: TokenSet;
|
|
263
|
-
readonly accountEmail?: string;
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
/**
|
|
267
|
-
* Anthropic's OAuth endpoints (both `claude.ai/oauth/authorize` and the token
|
|
268
|
-
* endpoint) intermittently return a transient HTTP 500 — the *same* request
|
|
269
|
-
* then succeeds on retry. So retry 5xx/429/network failures with a short
|
|
270
|
-
* backoff before giving up. 4xx (bad/expired/already-used code, invalid_grant)
|
|
271
|
-
* is deterministic and surfaced immediately, never retried.
|
|
272
|
-
*/
|
|
273
|
-
const TOKEN_POST_MAX_ATTEMPTS = 3;
|
|
274
|
-
const TOKEN_POST_BACKOFF_MS = [600, 1800] as const;
|
|
275
|
-
/**
|
|
276
|
-
* Per-attempt deadline on the token POST. Node's `fetch` has NO default
|
|
277
|
-
* timeout, so a half-open TCP socket (server accepts but never responds — a
|
|
278
|
-
* stalled edge node, a black-holing proxy, a captive portal that keeps the
|
|
279
|
-
* connection alive) would hang the whole login/refresh indefinitely. Bound
|
|
280
|
-
* each attempt; a timeout aborts the request and is classed as a transient
|
|
281
|
-
* network error, so the retry loop tries again and ultimately surfaces the
|
|
282
|
-
* "endpoint kept failing" hint instead of wedging forever.
|
|
283
|
-
*/
|
|
284
|
-
const TOKEN_POST_TIMEOUT_MS = 30_000;
|
|
285
|
-
|
|
286
|
-
/** Test seam so the exchange/refresh can run against a fake fetch. */
|
|
287
|
-
let fetchImpl: typeof fetch = fetch;
|
|
288
|
-
export function __setClaudeFetch(f: typeof fetch): void {
|
|
289
|
-
fetchImpl = f;
|
|
114
|
+
status = await checkClaudeCliAuth(executable);
|
|
115
|
+
if (status.state !== 'signed-in') throw authError(status);
|
|
116
|
+
return status.accountId ? { accountId: status.accountId } : {};
|
|
290
117
|
}
|
|
291
118
|
|
|
292
|
-
/**
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
119
|
+
/** Log out the CLI account. Legacy moxxy vault values are deliberately untouched. */
|
|
120
|
+
export async function claudeLogout(ctx: ProviderAuthContext): Promise<boolean> {
|
|
121
|
+
const executable = resolveClaudeExecutable(ctx.providerConfig);
|
|
122
|
+
const before = await checkClaudeCliAuth(executable);
|
|
123
|
+
if (before.state !== 'signed-in') return false;
|
|
124
|
+
const result = await runCommandImpl(executable, CLAUDE_AUTH_LOGOUT_ARGS, { inherit: true });
|
|
125
|
+
if (result.error || result.code !== 0) {
|
|
126
|
+
throw new MoxxyError({ code: 'AUTH_INVALID', message: `Claude CLI logout failed${result.stderr ? `: ${result.stderr}` : '.'}` });
|
|
127
|
+
}
|
|
128
|
+
return true;
|
|
302
129
|
}
|
|
303
130
|
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
131
|
+
export async function claudeStatus(ctx: ProviderAuthContext): Promise<ProviderOAuthStatus | null> {
|
|
132
|
+
const status = await checkClaudeCliAuth(resolveClaudeExecutable(ctx.providerConfig));
|
|
133
|
+
return {
|
|
134
|
+
accountId: status.accountId ?? null,
|
|
135
|
+
authState: status.state,
|
|
136
|
+
message: status.message,
|
|
137
|
+
};
|
|
308
138
|
}
|
|
309
139
|
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
)
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
140
|
+
function parseStatusOutput(output: string): { loggedIn: boolean; accountId?: string } | null {
|
|
141
|
+
try {
|
|
142
|
+
const value = JSON.parse(output) as Record<string, unknown>;
|
|
143
|
+
const loggedIn = value.loggedIn ?? value.logged_in ?? value.authenticated;
|
|
144
|
+
if (typeof loggedIn !== 'boolean') return null;
|
|
145
|
+
const account = value.email ?? value.account ?? value.accountEmail ?? value.account_email;
|
|
146
|
+
return { loggedIn, ...(typeof account === 'string' && account ? { accountId: account } : {}) };
|
|
147
|
+
} catch {
|
|
148
|
+
const text = output.trim();
|
|
149
|
+
if (/not logged in|signed out|not authenticated/i.test(text)) return { loggedIn: false };
|
|
150
|
+
if (/logged in|authenticated|signed in/i.test(text)) {
|
|
151
|
+
const email = text.match(/[\w.+-]+@[\w.-]+\.[A-Za-z]{2,}/)?.[0];
|
|
152
|
+
return { loggedIn: true, ...(email ? { accountId: email } : {}) };
|
|
153
|
+
}
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
323
156
|
}
|
|
324
157
|
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
refreshToken: string,
|
|
328
|
-
priorEmail: string | undefined,
|
|
329
|
-
): Promise<TokenSet> {
|
|
330
|
-
const { tokenSet, accountEmail } = await postClaudeToken({
|
|
331
|
-
grant_type: 'refresh_token',
|
|
332
|
-
refresh_token: refreshToken,
|
|
333
|
-
client_id: CLAUDE_CLIENT_ID,
|
|
334
|
-
});
|
|
335
|
-
// Claude rotates the refresh_token on every refresh; if a response ever
|
|
336
|
-
// omits one, keep the prior so we don't lock ourselves out.
|
|
337
|
-
const merged: TokenSet = tokenSet.refreshToken
|
|
338
|
-
? tokenSet
|
|
339
|
-
: { ...tokenSet, refreshToken };
|
|
340
|
-
await persistClaudeTokens(vault, merged, accountEmail ?? priorEmail);
|
|
341
|
-
return merged;
|
|
158
|
+
function looksUnsupported(text: string): boolean {
|
|
159
|
+
return /unknown (command|option)|invalid (command|option)|unrecognized (command|option)|not supported/i.test(text);
|
|
342
160
|
}
|
|
343
161
|
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
clientId: CLAUDE_CLIENT_ID,
|
|
351
|
-
tokenUrl: CLAUDE_TOKEN_URL,
|
|
352
|
-
...(accountEmail ? { extras: { account_email: accountEmail } } : {}),
|
|
162
|
+
function authError(status: ClaudeCliAuthStatus): MoxxyError {
|
|
163
|
+
return new MoxxyError({
|
|
164
|
+
code: status.state === 'signed-out' ? 'AUTH_NO_CREDENTIALS' : 'AUTH_INVALID',
|
|
165
|
+
message: status.message,
|
|
166
|
+
hint: status.state === 'signed-out' ? 'Run `moxxy login claude-code`.' : undefined,
|
|
167
|
+
context: { provider: CLAUDE_CODE_PROVIDER_ID, executable: status.executable, state: status.state },
|
|
353
168
|
});
|
|
354
169
|
}
|
|
355
170
|
|
|
356
|
-
async function
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
if (res.ok) {
|
|
377
|
-
// A captive portal / proxy / misbehaving edge can return 200 with an HTML
|
|
378
|
-
// or empty body, or a JSON primitive/array. Treat any of these as a
|
|
379
|
-
// transient and retry rather than letting a raw SyntaxError escape the
|
|
380
|
-
// retry/classify path.
|
|
381
|
-
let parsed: unknown;
|
|
382
|
-
try {
|
|
383
|
-
parsed = await res.json();
|
|
384
|
-
} catch {
|
|
385
|
-
transient = 'HTTP 200 with non-JSON body';
|
|
386
|
-
continue;
|
|
387
|
-
}
|
|
388
|
-
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
389
|
-
transient = 'HTTP 200 with malformed token response';
|
|
390
|
-
continue;
|
|
391
|
-
}
|
|
392
|
-
const json = parsed as Record<string, unknown>;
|
|
393
|
-
return { tokenSet: parseTokenResponse(json), ...extractAccountEmail(json) };
|
|
394
|
-
}
|
|
395
|
-
|
|
396
|
-
const text = await res.text().catch(() => '');
|
|
397
|
-
// Deterministic client errors: surface immediately, don't burn retries.
|
|
398
|
-
if (res.status < 500 && res.status !== 429) {
|
|
399
|
-
throw new MoxxyError({
|
|
400
|
-
code: res.status === 401 || res.status === 403 ? 'AUTH_DENIED' : 'AUTH_INVALID',
|
|
401
|
-
message: `Claude token endpoint returned HTTP ${res.status}: ${text.slice(0, 300)}`,
|
|
402
|
-
context: { provider: CLAUDE_CODE_PROVIDER_ID, status: res.status },
|
|
403
|
-
});
|
|
404
|
-
}
|
|
405
|
-
// 5xx / 429 — Anthropic-side flake; loop and try the same request again.
|
|
406
|
-
transient = `HTTP ${res.status}: ${text.slice(0, 200)}`;
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
throw new MoxxyError({
|
|
410
|
-
code: 'AUTH_INVALID',
|
|
411
|
-
message: `Claude token endpoint kept failing after ${TOKEN_POST_MAX_ATTEMPTS} attempts (last: ${transient}).`,
|
|
412
|
-
hint:
|
|
413
|
-
"Anthropic's OAuth endpoint is returning transient errors right now — " +
|
|
414
|
-
'wait a few seconds and run `moxxy login claude-code` again.',
|
|
415
|
-
context: { provider: CLAUDE_CODE_PROVIDER_ID },
|
|
171
|
+
async function runCommand(
|
|
172
|
+
executable: string,
|
|
173
|
+
args: readonly string[],
|
|
174
|
+
options: { readonly inherit?: boolean } = {},
|
|
175
|
+
): Promise<ClaudeCommandResult> {
|
|
176
|
+
return await new Promise((resolve) => {
|
|
177
|
+
const spawnOptions: SpawnOptions = options.inherit
|
|
178
|
+
? { stdio: 'inherit' }
|
|
179
|
+
: { stdio: ['ignore', 'pipe', 'pipe'] };
|
|
180
|
+
const child = spawn(executable, [...args], spawnOptions);
|
|
181
|
+
let stdout = '';
|
|
182
|
+
let stderr = '';
|
|
183
|
+
child.stdout?.setEncoding('utf8');
|
|
184
|
+
child.stderr?.setEncoding('utf8');
|
|
185
|
+
child.stdout?.on('data', (chunk: string) => { stdout += chunk; });
|
|
186
|
+
child.stderr?.on('data', (chunk: string) => { stderr += chunk; });
|
|
187
|
+
child.once('error', (error: NodeJS.ErrnoException) => resolve({ code: 1, stdout, stderr, error }));
|
|
188
|
+
child.once('close', (code) => resolve({ code: code ?? 1, stdout, stderr }));
|
|
416
189
|
});
|
|
417
190
|
}
|
|
418
|
-
|
|
419
|
-
function extractAccountEmail(json: Record<string, unknown>): { accountEmail?: string } {
|
|
420
|
-
const account = json.account;
|
|
421
|
-
if (account && typeof account === 'object') {
|
|
422
|
-
const email = (account as { email_address?: unknown }).email_address;
|
|
423
|
-
if (typeof email === 'string' && email) return { accountEmail: email };
|
|
424
|
-
}
|
|
425
|
-
return {};
|
|
426
|
-
}
|