/** Minimal, opt-in team credential store. Standalone startup never imports or * reads it; only explicit team commands / online-model resolution do. */ import { chmod, mkdir, readFile, rename, writeFile } from 'node:fs/promises'; import { dirname, join } from 'node:path'; import { getConfigFilePath } from '../config/configFile.js'; import type { OnlineModelAvailability } from './onlineToolContract.js'; const TEAM_REQUEST_TIMEOUT_MS = Math.max( 3_000, Math.min( 60_000, Number(process.env.MINIMAL_AGENT_TEAM_REQUEST_TIMEOUT_MS ?? 15_000), ), ); export interface TeamCredentials { serverUrl: string; deviceToken: string; deviceLabel?: string; updatedAt: number; } export interface OnlineModelCatalogItem { id: string; displayName: string; model: string; apiFormat: 'openai' | 'anthropic'; contextWindow: number; maxTokens: number; supportsVision: boolean; capabilities?: { vision: boolean; tools: boolean; structuredOutput: boolean }; isDefault: boolean; maxToolCategories: string[]; defaultToolCategories: string[]; availability?: OnlineModelAvailability; } export interface TeamAccountSubscription { credits?: { grantedMicro: string; usedMicro: string; heldMicro: string; availableMicro: string }; status: string; planName: string; billingInterval: string; requestLimit: number; inputTokenLimit: number; outputTokenLimit: number; requestCount: number; inputTokens: number; outputTokens: number; } function authPath(): string { return join(dirname(getConfigFilePath()), 'team-auth.json'); } export function normalizeTeamServerUrl(value: string): string { const url = new URL(value.trim()); if (url.protocol !== 'https:' && url.protocol !== 'http:') throw new Error('团队服务器必须使用 http(s) 地址'); const hostname = url.hostname.toLowerCase().replace(/^\[|\]$/g, ''); const isLocalDevelopmentHost = hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1'; if ( url.protocol === 'http:' && !isLocalDevelopmentHost && process.env.KAKADEAI_ALLOW_HTTP_TEAM_SERVER !== '1' ) { throw new Error( '团队服务器必须使用 HTTPS(开发环境可使用本机地址或显式允许 HTTP)', ); } url.search = ''; url.hash = ''; return url.toString().replace(/\/$/, ''); } export async function loadTeamCredentials( expectedServerUrl?: string, ): Promise { const rawServerUrl = process.env.KAKADEAI_SOCIAL_SERVER_URL; // The Desktop shell deliberately injects an empty value in standalone mode. // An empty environment value is an explicit opt-out and must not fall back // to a stale team-auth.json left by an earlier team-mode run. if (rawServerUrl !== undefined && !rawServerUrl.trim()) return null; const serverUrl = rawServerUrl?.trim() ?? expectedServerUrl?.trim(); if ( rawServerUrl?.trim() && expectedServerUrl?.trim() && normalizeTeamServerUrl(rawServerUrl) !== normalizeTeamServerUrl(expectedServerUrl) ) return null; const deviceToken = process.env.KAKADEAI_TEAM_DEVICE_TOKEN?.trim(); if (serverUrl && deviceToken) { return { serverUrl: normalizeTeamServerUrl(serverUrl), deviceToken, ...(process.env.KAKADEAI_TEAM_DEVICE_LABEL ? { deviceLabel: process.env.KAKADEAI_TEAM_DEVICE_LABEL } : {}), updatedAt: Date.now(), }; } try { const raw = JSON.parse( await readFile(authPath(), 'utf8'), ) as Partial; if (!raw.serverUrl || !raw.deviceToken) return null; const storedServerUrl = normalizeTeamServerUrl(raw.serverUrl); if (serverUrl && storedServerUrl !== normalizeTeamServerUrl(serverUrl)) return null; return { serverUrl: storedServerUrl, deviceToken: raw.deviceToken, ...(raw.deviceLabel ? { deviceLabel: raw.deviceLabel } : {}), updatedAt: Number(raw.updatedAt) || 0, }; } catch { return null; } } export async function saveTeamCredentials( value: TeamCredentials, ): Promise { const path = authPath(); await mkdir(dirname(path), { recursive: true }); const temporary = `${path}.${process.pid}.tmp`; await writeFile( temporary, `${JSON.stringify({ ...value, serverUrl: normalizeTeamServerUrl(value.serverUrl) }, null, 2)}\n`, { mode: 0o600 }, ); await chmod(temporary, 0o600).catch(() => {}); await rename(temporary, path); await chmod(path, 0o600).catch(() => {}); } export async function clearTeamCredentials(): Promise { const path = authPath(); await writeFile(path, '{}\n', { mode: 0o600 }).catch(() => {}); } /** * Revoke exactly the credentials supplied by the caller, then clear the local * copy. A null value is deliberately local-only: silently discovering an old * team-auth.json here could make standalone logout contact a historical * server. Callers that want remote revocation must first load credentials * against the currently configured server. */ export async function revokeTeamCredentials( credentials: TeamCredentials | null, ): Promise { if (credentials?.serverUrl && credentials.deviceToken) { await fetch(`${credentials.serverUrl}/api/auth/device/logout`, { method: 'POST', headers: { authorization: `Bearer ${credentials.deviceToken}` }, }).catch(() => {}); } await clearTeamCredentials(); } export async function fetchOnlineModels( credentials: TeamCredentials, signal?: AbortSignal, ): Promise { const deadline = AbortSignal.timeout(TEAM_REQUEST_TIMEOUT_MS); const response = await fetch(`${credentials.serverUrl}/api/models`, { headers: { authorization: `Bearer ${credentials.deviceToken}` }, signal: signal ? AbortSignal.any([signal, deadline]) : deadline, }); const body = (await response.json().catch(() => ({}))) as { models?: OnlineModelCatalogItem[]; error?: string; code?: string; }; if (!response.ok) { const code = body.code ?? (response.status === 401 ? 'DEVICE_REVOKED' : response.status === 403 ? 'MODEL_UNAVAILABLE' : `HTTP_${response.status}`); throw new Error( `[${code}] ${body.error ?? `读取在线模型失败(${response.status})`}`, ); } return (body.models ?? []).filter((model) => typeof model.id === 'string'); } export async function fetchTeamSubscription( credentials: TeamCredentials, ): Promise { const response = await fetch( `${credentials.serverUrl}/api/account/subscription`, { headers: { authorization: `Bearer ${credentials.deviceToken}` }, signal: AbortSignal.timeout(TEAM_REQUEST_TIMEOUT_MS), }, ); const body = (await response.json().catch(() => ({}))) as { subscription?: TeamAccountSubscription | null; error?: string; }; if (!response.ok) throw new Error(body.error ?? `读取订阅失败(${response.status})`); return body.subscription ?? null; } export async function fetchTeamUsage( credentials: TeamCredentials, ): Promise { const response = await fetch(`${credentials.serverUrl}/api/account/usage`, { headers: { authorization: `Bearer ${credentials.deviceToken}` }, signal: AbortSignal.timeout(TEAM_REQUEST_TIMEOUT_MS), }); const body = (await response.json().catch(() => ({}))) as { usage?: unknown[]; error?: string; }; if (!response.ok) throw new Error(body.error ?? `读取用量失败(${response.status})`); return body.usage ?? []; } export async function resolveOnlineModel( modelId: string, expectedServerUrl?: string, ): Promise<{ credentials: TeamCredentials; model: OnlineModelCatalogItem; } | null> { const credentials = await loadTeamCredentials(expectedServerUrl); if (!credentials) return null; const models = await fetchOnlineModels(credentials); const model = models.find((item) => item.id === modelId); return model ? { credentials, model } : null; } export async function beginTeamLogin( serverUrl: string, deviceLabel = 'minimal-agent', ): Promise<{ authorizeUrl: string; complete: () => Promise }> { const normalized = normalizeTeamServerUrl(serverUrl); const start = await fetch(`${normalized}/api/auth/device/start`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ clientLabel: deviceLabel }), signal: AbortSignal.timeout(TEAM_REQUEST_TIMEOUT_MS), }); const authorization = (await start.json().catch(() => ({}))) as { requestId?: string; deviceCode?: string; authorizeUrl?: string; error?: string; }; if ( !start.ok || !authorization.requestId || !authorization.deviceCode || !authorization.authorizeUrl ) throw new Error(authorization.error ?? '无法发起团队登录'); return { authorizeUrl: authorization.authorizeUrl, complete: async () => { const deadline = Date.now() + 10 * 60_000; while (Date.now() < deadline) { const poll = await fetch( `${normalized}/api/auth/device/poll?requestId=${encodeURIComponent(authorization.requestId!)}`, { headers: { 'x-kakadeai-device-code': authorization.deviceCode!, }, signal: AbortSignal.timeout(TEAM_REQUEST_TIMEOUT_MS), }, ); const result = (await poll.json().catch(() => ({}))) as { state?: string; deviceToken?: string; error?: string; }; if (result.state === 'approved' && result.deviceToken) { const credentials: TeamCredentials = { serverUrl: normalized, deviceToken: result.deviceToken, deviceLabel, updatedAt: Date.now(), }; await saveTeamCredentials(credentials); return credentials; } if (result.state === 'expired') throw new Error('浏览器授权已过期,请重新登录'); if (!poll.ok && result.error) throw new Error(result.error); await new Promise((resolve) => setTimeout(resolve, 1500)); } throw new Error('等待浏览器授权超时'); }, }; }