import { Command } from 'commander'; import { AuthStore } from '../lib/auth.js'; import { isDesktopMode } from '../lib/desktop-mode.js'; import { stopDesktopRuntime } from '../lib/desktop-auth.js'; import { createProfileDirs, getWorkspaceDir } from '../lib/init-command.js'; import { switchActiveAccountSkillLinks } from '../lib/agent-workspace-skills.js'; import { ResponseClassifier } from '../short-command/classifier.js'; import { createProcessCommandIo } from '../short-command/process-io.js'; import { ShortCommandRunner, type CommandIo, type ShortCommandOperationResult } from '../short-command/runner.js'; const DEFAULT_SERVER_URL = 'https://myclaw.163.com/claw'; async function readStdin(): Promise { if (process.stdin.isTTY) throw new Error('Pass the client credentials as JSON on stdin.'); const chunks: Buffer[] = []; let bytes = 0; for await (const chunk of process.stdin) { const buffer = Buffer.from(chunk); bytes += buffer.length; if (bytes > 65_536) throw new Error('Auth input exceeds 64 KiB.'); chunks.push(buffer); } return Buffer.concat(chunks).toString('utf8'); } function failure(code: string, message: string): ShortCommandOperationResult { return { kind: 'local_failure', source: 'local', error: { code, message } }; } function status(store: AuthStore): ShortCommandOperationResult { const profile = store.getActive(); return { kind: 'local_success', source: 'local', value: { success: true, data: { mode: isDesktopMode() ? 'desktop' : 'standalone', logged_in: profile !== null, account: profile ? { id: profile.runtimeAccountId, name: profile.agentName } : null, }, } }; } export function createAuthCommand(options: { io?: CommandIo; readStdin?: () => Promise; stopRuntime?: () => Promise; switchSkillLinks?: typeof switchActiveAccountSkillLinks; } = {}): Command { const auth = new Command('auth').description('Client-managed game login'); const runner = new ShortCommandRunner(); const io = options.io ?? createProcessCommandIo(); auth.command('status').description('Show local login state without credentials') .option('--json', 'Return JSON (the default)') .action(async () => { const secrets: string[] = []; await runner.run({ descriptor: { command: 'ccl auth status', sensitivePolicy: { sensitiveValues: secrets } }, io, operation: () => { const store = new AuthStore(); const profile = store.getActive(); if (profile) secrets.push(profile.apiKey); return status(store); } }); }); auth.command('bind').description('Bind the game account provided by Desktop') .requiredOption('--stdin', 'Read {"clawkey":"...","serverUrl":"..."} JSON from stdin; serverUrl is optional') .action(async () => { const secrets: string[] = []; await runner.run({ descriptor: { command: 'ccl auth bind', sensitivePolicy: { sensitiveValues: secrets } }, io, operation: async () => { if (!isDesktopMode()) return failure('DESKTOP_MODE_REQUIRED', 'auth bind requires CLAWCLAW_IS_DESKTOP=true.'); let input: unknown; try { input = JSON.parse(await (options.readStdin ?? readStdin)()); } catch { return failure('INVALID_AUTH_INPUT', 'Expected a JSON object on stdin containing a non-empty clawkey.'); } if (!input || typeof input !== 'object' || Array.isArray(input)) { return failure('INVALID_AUTH_INPUT', 'Expected a JSON object on stdin containing a non-empty clawkey.'); } const value = input as Record; const apiKey = typeof value.clawkey === 'string' ? value.clawkey.trim() : ''; if (!apiKey) return failure('INVALID_AUTH_INPUT', 'clawkey must be a non-empty string.'); secrets.push(apiKey); if (value.serverUrl !== undefined && typeof value.serverUrl !== 'string') { return failure('INVALID_AUTH_INPUT', 'serverUrl must be an HTTP or HTTPS URL.'); } const serverUrl = (value.serverUrl as string | undefined)?.trim() || process.env.CLAWCLAW_SERVER_URL?.trim() || DEFAULT_SERVER_URL; try { const url = new URL(serverUrl); if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw new Error(); } catch { return failure('INVALID_AUTH_INPUT', 'serverUrl must be an HTTP or HTTPS URL without credentials, query or fragment.'); } const [{ GameClient }, { extractBackendAccountId, extractServerAccountName, LOGIN_CONTRACT }] = await Promise.all([ import('../lib/game-client.js'), import('./account.js'), ]); const client = new GameClient({ lobbyUrl: serverUrl, apiKey: '' }); const response = await client.requestRaw('POST', '/api/v1/agents/login', { api_key: apiKey }); const result = new ResponseClassifier().classify(response, LOGIN_CONTRACT); if (result.kind !== 'success') return { kind: 'backend', response, contract: LOGIN_CONTRACT }; const agentName = extractServerAccountName(result.upstreamRoot); if (typeof agentName !== 'string' || !agentName.trim()) { return failure('INVALID_LOGIN_RESPONSE', 'Login response did not contain an account name.'); } const store = new AuthStore(); const previous = store.getActive(); if (previous) secrets.push(previous.apiKey); if (previous?.apiKey !== apiKey || previous.serverUrl !== serverUrl) { await (options.stopRuntime ?? stopDesktopRuntime)(); } const profile = { agentName, apiKey, serverUrl, backendAccountId: extractBackendAccountId(result.upstreamRoot) }; (options.switchSkillLinks ?? switchActiveAccountSkillLinks)(getWorkspaceDir(), previous, profile); if (previous && previous.serverUrl !== serverUrl) store.updateGameServerUrl(undefined); createProfileDirs(profile); // The client provides one account. Do not keep fallback credentials. store.addProfile(profile, { replaceExisting: true }); return status(store); } }); }); auth.command('unbind').description('Stop the local runtime and clear login; keep account resources and memory') .action(async () => { await runner.run({ descriptor: { command: 'ccl auth unbind' }, io, operation: async () => { if (!isDesktopMode()) return failure('DESKTOP_MODE_REQUIRED', 'auth unbind requires CLAWCLAW_IS_DESKTOP=true.'); const store = new AuthStore(); await (options.stopRuntime ?? stopDesktopRuntime)(); (options.switchSkillLinks ?? switchActiveAccountSkillLinks)(getWorkspaceDir(), store.getActive(), null); store.clear(); return status(store); } }); }); return auth; }