import { chmodSync, existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs'; import { randomUUID } from 'crypto'; import { join, dirname } from 'path'; import { getWorkspaceDir } from './init-command.js'; import { tryAcquireWorkspaceRuntimeLock, type WorkspaceRuntimeLock } from './workspace-runtime-lock.js'; import { ensureUserDataLayout, getRuntimeAuthStateFile, getUserDataAccountHash, getUserDataAuthFile, readRuntimeAuthState, splitAuthData, writeRuntimeAuthState, type RuntimeAuthState, } from './user-data.js'; export interface AuthProfile { agentName: string; apiKey: string; /** Stable, non-secret local identity used by runtime ledgers and IPC scopes. */ runtimeAccountId?: string; /** Stable backend identity when the server exposes it; never returned to Agent output. */ backendAccountId?: string; /** Lobby server URL (e.g. https://myclaw.163.com/claw) */ serverUrl: string; /** Game server URL (e.g. http://{address}:{port}), obtained from /queue/status after match */ gameServerUrl?: string; } export interface AuthData { activeProfile: string; profiles: Record; } const EMPTY_AUTH: AuthData = { activeProfile: '', profiles: {} }; const RUNTIME_ACCOUNT_ID = /^acct_[a-f0-9]{32}$/; function createRuntimeAccountId(): string { return `acct_${randomUUID().replace(/-/g, '')}`; } function profileKeyFor( data: AuthData, profile: Pick, ): string { if (profile.backendAccountId) { for (const [key, savedProfile] of Object.entries(data.profiles ?? {})) { if (savedProfile?.backendAccountId === profile.backendAccountId) return key; } } for (const [key, savedProfile] of Object.entries(data.profiles ?? {})) { if (savedProfile?.apiKey === profile.apiKey) return key; } const baseKey = profile.agentName; if (!data.profiles[baseKey]) return baseKey; const suffix = getUserDataAccountHash(profile.apiKey); let candidate = `${baseKey}#${suffix}`; let index = 2; while (data.profiles[candidate] && data.profiles[candidate]?.apiKey !== profile.apiKey) { candidate = `${baseKey}#${suffix}-${index}`; index += 1; } return candidate; } export class AuthStore { private authFile: string; private runtimeAuthStateFile: string; private workspaceDir?: string; constructor(authFile?: string, runtimeAuthStateFile?: string) { if (authFile) { this.authFile = authFile; this.runtimeAuthStateFile = runtimeAuthStateFile ?? join(dirname(authFile), 'auth-state.json'); return; } const workspaceDir = getWorkspaceDir(); this.workspaceDir = workspaceDir; ensureUserDataLayout(workspaceDir); this.authFile = getUserDataAuthFile(workspaceDir); this.runtimeAuthStateFile = getRuntimeAuthStateFile(workspaceDir); } load(): AuthData { if (!existsSync(this.authFile)) return { ...EMPTY_AUTH, profiles: {} }; try { const data = JSON.parse(readFileSync(this.authFile, 'utf8')) as AuthData; const { auth, runtime, changed } = splitAuthData(data); let identityChanged = false; for (const profile of Object.values(auth.profiles)) { if (!RUNTIME_ACCOUNT_ID.test(profile.runtimeAccountId ?? '')) { profile.runtimeAccountId = createRuntimeAccountId(); identityChanged = true; } } this.mergeRuntimeState(runtime); if (changed || identityChanged) this.writeAuth(auth); return auth; } catch { return { ...EMPTY_AUTH, profiles: {} }; } } save(data: AuthData): void { const { auth, runtime } = splitAuthData(data); this.mergeRuntimeState(runtime); this.writeAuth(auth); } private writeAuth(data: AuthData): void { let guard: WorkspaceRuntimeLock | null = null; if (this.workspaceDir) { let previous: AuthData = EMPTY_AUTH; try { previous = JSON.parse(readFileSync(this.authFile, 'utf8')) as AuthData; } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; } if (previous.profiles[previous.activeProfile]?.apiKey !== data.profiles[data.activeProfile]?.apiKey) { guard = tryAcquireWorkspaceRuntimeLock(this.workspaceDir); if (!guard) throw new Error('A ClawClaw runtime is running in this workspace. Stop it before switching accounts.'); } } try { const dir = dirname(this.authFile); if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 }); writeFileSync(this.authFile, JSON.stringify(data, null, 2), { encoding: 'utf8', mode: 0o600, }); // writeFileSync preserves an existing file's mode, so tighten migrated // installs as well. Windows keeps the enclosing user-profile ACL. try { chmodSync(this.authFile, 0o600); } catch {} } finally { guard?.release(); } } private mergeRuntimeState(incoming: RuntimeAuthState): void { const incomingEntries = Object.entries(incoming.profiles ?? {}).filter(([, profile]) => profile.gameServerUrl); if (incomingEntries.length === 0) return; const current = readRuntimeAuthState(this.runtimeAuthStateFile); let changed = false; for (const [name, profile] of incomingEntries) { if (current.profiles[name]?.gameServerUrl) continue; current.profiles[name] = profile; changed = true; } if (changed) writeRuntimeAuthState(this.runtimeAuthStateFile, current); } addProfile(profile: AuthProfile, options: { replaceExisting?: boolean } = {}): string { const data = this.load(); const key = profileKeyFor(data, profile); const existing = data.profiles[key]; if (options.replaceExisting) data.profiles = {}; data.profiles[key] = { ...profile, runtimeAccountId: RUNTIME_ACCOUNT_ID.test(profile.runtimeAccountId ?? '') ? profile.runtimeAccountId : existing?.runtimeAccountId ?? createRuntimeAccountId(), backendAccountId: profile.backendAccountId ?? existing?.backendAccountId, }; data.activeProfile = key; this.save(data); return key; } /** Forget credentials and routing, without deleting account resources or memory. */ clear(): void { this.save({ activeProfile: '', profiles: {} }); writeRuntimeAuthState(this.runtimeAuthStateFile, { profiles: {} }); } removeProfile(name: string): void { this.removeProfileByKey(name); } removeProfileByKey(key: string): void { const data = this.load(); delete data.profiles[key]; if (data.activeProfile === key) { const remaining = Object.keys(data.profiles); data.activeProfile = remaining[0] ?? ''; } this.save(data); const state = readRuntimeAuthState(this.runtimeAuthStateFile); if (state.profiles[key]) { delete state.profiles[key]; writeRuntimeAuthState(this.runtimeAuthStateFile, state); } } switchProfile(name: string): void { const data = this.load(); if (!data.profiles[name]) { throw new Error(`Profile "${name}" not found. Available: ${Object.keys(data.profiles).join(', ') || 'none'}`); } data.activeProfile = name; this.save(data); } listProfiles(): string[] { return Object.keys(this.load().profiles); } findProfileKeyByApiKey(apiKey: string): string | null { const data = this.load(); return Object.keys(data.profiles).find(key => data.profiles[key]?.apiKey === apiKey) ?? null; } getActiveProfileKey(): string | null { const data = this.load(); if (!data.activeProfile || !data.profiles[data.activeProfile]) return null; return data.activeProfile; } getActive(): AuthProfile | null { const data = this.load(); if (!data.activeProfile || !data.profiles[data.activeProfile]) return null; const profile = data.profiles[data.activeProfile]; const gameServerUrl = this.getGameServerUrl(data.activeProfile); return gameServerUrl ? { ...profile, gameServerUrl } : { ...profile }; } updateGameServerUrl(url: string | undefined, name?: string): void { const data = this.load(); const profileName = name ?? data.activeProfile; const profile = data.profiles[profileName]; if (!profile) return; const state = readRuntimeAuthState(this.runtimeAuthStateFile); if (url) { state.profiles[profileName] = { gameServerUrl: url, updatedAt: new Date().toISOString() }; } else { delete state.profiles[profileName]?.gameServerUrl; delete state.profiles[profileName]?.updatedAt; if (state.profiles[profileName] && Object.keys(state.profiles[profileName]).length === 0) { delete state.profiles[profileName]; } } writeRuntimeAuthState(this.runtimeAuthStateFile, state); } getGameServerUrl(profileName?: string): string | undefined { const data = this.load(); const name = profileName ?? data.activeProfile; if (!name) return undefined; return readRuntimeAuthState(this.runtimeAuthStateFile).profiles[name]?.gameServerUrl; } }