import fs from 'node:fs'; import { createHash } from 'node:crypto'; import { canonicalHost } from '../../shared/contracts/desktop-host.mjs'; import { observeWindowsProcess } from '../desktop/process-identity.mjs'; import { assertLocalTree } from '../desktop/file-state.mjs'; import { protectCredential, unprotectCredential, credentialError } from '../desktop/windows-dpapi.mjs'; const metadata = 'modelCredentials'; const sha = value => createHash('sha256').update(value).digest('hex'); const empty = () => ({ schema: 1, revision: 0, entries: {} }); export class CredentialVault { constructor(store, provider, { protect = protectCredential, unprotect = unprotectCredential } = {}) { this.store = store; this.provider = provider; this.protect = protect; this.unprotect = unprotect; this.issues = new Map(); assertLocalTree(store.directory); this.dataIdentity = sha(fs.realpathSync.native(store.directory).toLowerCase()); this.userSid = process.platform === 'win32' ? observeWindowsProcess(process.pid).userSid : null; this.reload(); } reload() { const state = this.store.storage.meta(metadata, empty()); this.blocked = !state || state.schema !== 1 || !Number.isSafeInteger(state.revision) || !state.entries || typeof state.entries !== 'object' || Array.isArray(state.entries) || Object.keys(state.entries).length > 101; this.state = this.blocked ? empty() : state; } binding(connection) { return sha(JSON.stringify(canonicalHost({ app: 'agent-workbench', scope: 'Windows.CurrentUser', userSid: this.userSid, dataIdentity: this.dataIdentity, connectionId: connection.id, connectionRevision: connection.revision, protocol: connection.protocol, baseUrl: connection.baseUrl, model: connection.model, requiresKey: connection.requiresKey }))); } status(connection) { if (this.blocked) return { status: 'unavailable', storage: 'windows-user-dpapi', message: '本机保存登记格式损坏或来自新版本,未覆盖原记录。' }; const value = this.state.entries[connection.id]; if (!value) return { status: 'not_saved', storage: 'memory', message: '当前凭据只在宿主内存中。' }; const issue = value.userSid !== this.userSid ? 'user_mismatch' : value.dataIdentity !== this.dataIdentity ? 'directory_mismatch' : value.connectionRevision !== connection.revision || value.bindingSha256 !== this.binding(connection) ? 'source_changed' : this.issues.get(connection.id); return { storage: 'windows-user-dpapi', status: issue ?? (value.enabled ? 'saved' : 'disabled'), enabled: value.enabled === true, connectionRevision: value.connectionRevision, credentialRevision: value.credentialRevision, savedAt: value.savedAt, message: issue ? '原保存块无法用于当前连接;重新填写后保存,或删除原保存。' : value.enabled ? '当前Windows用户可在宿主重启后加载。' : '已关闭自动加载;本次内存连接保留。' }; } view(hub) { return { supported: process.platform === 'win32', storage: 'windows-user-dpapi', revision: this.state.revision, unavailable: this.blocked, connections: hub.connections().map(connection => ({ id: connection.id, name: connection.name, revision: connection.revision, ...this.status(connection) })), scope: '仅处理用户明确新填或确认导入的凭据;不会提取原内存连接。密文与连接登记在同一SQLite事务提交。' }; } prepare(connection, explicitKey, credentialRevision) { if (this.blocked) throw credentialError('原保存登记无法核对;请保留原数据并修复登记后保存。'); if (typeof explicitKey !== 'string' || !explicitKey.trim() || explicitKey.length > 16000) throw credentialError('加密保存需要重新填写API Key。', 'CREDENTIAL_INPUT_REQUIRED', 400); const bindingSha256 = this.binding(connection), plain = Buffer.from(JSON.stringify({ schema: 1, bindingSha256, credentialRevision, key: explicitKey.trim() }), 'utf8'); let protectedBytes; try { protectedBytes = this.protect(plain, Buffer.from(bindingSha256, 'hex')); } finally { plain.fill(0); } try { return { schema: 1, connectionId: connection.id, connectionRevision: connection.revision, credentialRevision, userSid: this.userSid, dataIdentity: this.dataIdentity, bindingSha256, enabled: true, savedAt: new Date().toISOString(), ciphertext: protectedBytes.toString('base64') }; } finally { protectedBytes.fill(0); } } stage(id, record) { if (this.blocked) throw credentialError('本机保存登记无法核对。'); this.state = structuredClone(this.state); this.state.revision++; if (record) this.state.entries[id] = record; else delete this.state.entries[id]; this.store.storage.setMeta(metadata, this.state); this.issues.delete(id); } restore(hub) { for (const connection of hub.connections()) { const record = this.state.entries[connection.id]; if (!record || this.status(connection).status !== 'saved') continue; // Never overwrite or persist credentials already resident in this host. if (connection.id === 'legacy-default' ? this.provider.hasKey() : this.provider.credentials.has(connection.id)) continue; let plain; try { if (record.schema !== 1 || record.connectionId !== connection.id || !Number.isSafeInteger(record.credentialRevision) || record.credentialRevision < 1 || typeof record.ciphertext !== 'string' || record.ciphertext.length > 200000 || !/^[A-Za-z0-9+/]+={0,2}$/.test(record.ciphertext)) throw new Error('Invalid saved block'); plain = this.unprotect(Buffer.from(record.ciphertext, 'base64'), Buffer.from(record.bindingSha256, 'hex')); const payload = JSON.parse(plain.toString('utf8')); if (payload.schema !== 1 || payload.bindingSha256 !== this.binding(connection) || payload.credentialRevision !== record.credentialRevision || typeof payload.key !== 'string' || !payload.key || payload.key.length > 16000) throw new Error('Invalid decrypted binding'); if (connection.id === 'legacy-default') { this.provider.setKey(payload.key); this.provider.legacyCredentialRevision = record.credentialRevision; } else this.provider.credentials.set(connection.id, { key: payload.key, revision: record.credentialRevision }); } catch { this.issues.set(connection.id, 'decrypt_failed'); } finally { plain?.fill(0); } } } }