feat(models): persist explicitly saved credentials with user-scoped DPAPI

This commit is contained in:
Agent Workbench Dev
2026-10-31 09:30:38 +08:00
parent 249f191ebc
commit 72a496adfa
27 changed files with 857 additions and 21 deletions
+28
View File
@@ -0,0 +1,28 @@
import path from 'node:path';
import { execFileSync } from 'node:child_process';
import { projectEnvironment } from '../process-environment.mjs';
export const credentialError = (message, code = 'CREDENTIAL_UNAVAILABLE', status = 409) => Object.assign(new Error(message), { code, status });
// The command and environment contain no credential. Both directions travel
// over private pipes as ASCII frames; raw child output is never logged.
function transform(action, bytes, entropy) {
if (process.platform !== 'win32') throw credentialError('本机加密凭据仅支持Windows用户级DPAPI。', 'CREDENTIAL_PLATFORM_UNSUPPORTED');
if (!Buffer.isBuffer(bytes) || bytes.length > 128000 || !Buffer.isBuffer(entropy) || entropy.length !== 32) throw credentialError('加密凭据输入无效。');
const script = "$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue';Add-Type -AssemblyName System.Security;"
+ '$awbInput=[Console]::In.ReadToEnd()|ConvertFrom-Json;'
+ '$awbBytes=[Convert]::FromBase64String($awbInput.bytes);$awbEntropy=[Convert]::FromBase64String($awbInput.entropy);'
+ 'try{$awbOutput=[Security.Cryptography.ProtectedData]::' + action + '($awbBytes,$awbEntropy,[Security.Cryptography.DataProtectionScope]::CurrentUser);'
+ '[Console]::Out.Write([Convert]::ToBase64String($awbOutput))}'
+ 'finally{[Array]::Clear($awbBytes,0,$awbBytes.Length);[Array]::Clear($awbEntropy,0,$awbEntropy.Length);if($awbOutput){[Array]::Clear($awbOutput,0,$awbOutput.Length)}}';
try {
const output = execFileSync(path.join(process.env.SystemRoot || 'C:\\Windows', 'System32/WindowsPowerShell/v1.0/powershell.exe'),
['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')],
{ input: JSON.stringify({ bytes: bytes.toString('base64'), entropy: entropy.toString('base64') }), encoding: 'utf8',
windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'], timeout: 15000, maxBuffer: 256000, env: projectEnvironment() }).trim();
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(output) || output.length > 200000) throw new Error('Invalid response');
return Buffer.from(output, 'base64');
} catch { throw credentialError('本机加密凭据无法处理,请核对Windows用户、数据目录或保存块。'); }
}
export const protectCredential = (bytes, entropy) => transform('Protect', bytes, entropy);
export const unprotectCredential = (bytes, entropy) => transform('Unprotect', bytes, entropy);
+2 -1
View File
@@ -67,7 +67,7 @@ export class ConfigImporter {
this.previews.set(id, { source, path: path.resolve(filename), created: Date.now(), ...contents });
return { id, entries: contents.entries.map(({ apiKey, sourceId, origin, ...value }, index) => ({ ...value, id: String(index), hasKey: !!apiKey })), notices: contents.notices, expiresInMs: 300000 };
}
apply(id, autoSync) {
apply(id, autoSync, persistCredentials = false) {
const preview = this.previews.get(id);
if (!preview || Date.now() - preview.created > 300000) throw new Error('导入预览已过期,请重新预览。');
const current = this.read(preview.source, preview.path);
@@ -79,6 +79,7 @@ export class ConfigImporter {
const previous = this.hub.state.connections.find(value => value.importOrigin === item.origin);
if (previous && previous.importRevision !== previous.revision) { conflicts.push(previous.name); continue; }
const value = this.hub.upsert({ ...(previous ?? {}), ...item, id: previous?.id, revision: previous?.revision, enabled: previous ? previous.enabled : true,
persistKey: persistCredentials === true && !!item.apiKey,
...(item.apiKey ? { apiKey: item.apiKey } : { apiKey: '' }) });
const stored = this.hub.connection(value.id); stored.source = preview.source; stored.importOrigin = item.origin; stored.importRevision = stored.revision;
imported.push(value.id);
+78
View File
@@ -0,0 +1,78 @@
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); }
}
}
}
+40 -2
View File
@@ -1,6 +1,7 @@
import { randomUUID, createHash } from 'node:crypto';
import { setTimeout as delay } from 'node:timers/promises';
import { ModelRequestError } from '../../server/diagnostics.mjs';
import { CredentialVault } from './credential-vault.mjs';
const legacyId = 'legacy-default';
const stamp = () => new Date().toISOString();
@@ -25,6 +26,7 @@ export class ModelHub {
for (const attempt of this.attempts) if (attempt.status === 'running') { attempt.status = 'unknown'; attempt.finishedAt = stamp(); attempt.reason = '宿主重启,请求结果与用量待核对。'; recovered = true; }
if (recovered) this.saveAttempts();
provider.credentials ??= new Map();
if (store.storage.meta('modelCredentials', null)) this.vault().restore(this);
}
save(config = null) {
this.state.revision++;
@@ -46,6 +48,8 @@ export class ModelHub {
editRegistry(action) {
if (this.editingRegistry) return action();
const before = structuredClone(this.state), credentials = new Map(this.provider.credentials);
const originalKey = this.provider.apiKey, legacyRevision = this.provider.legacyCredentialRevision;
const vaultIssues = this.credentialVault ? new Map(this.credentialVault.issues) : null;
this.editingRegistry = true;
try {
return this.store.storage.transaction(() => {
@@ -57,6 +61,9 @@ export class ModelHub {
this.state = before;
this.provider.credentials.clear();
for (const [id, value] of credentials) this.provider.credentials.set(id, value);
this.provider.apiKey = originalKey; this.provider.legacyCredentialRevision = legacyRevision;
this.credentialVault?.reload();
if (vaultIssues) this.credentialVault.issues = vaultIssues;
throw cause;
} finally { this.editingRegistry = false; }
}
@@ -66,21 +73,48 @@ export class ModelHub {
model: this.store.config.model, enabled: true, requiresKey: false, revision: this.store.config.configRevision ?? 1,
contextLimit: this.store.config.contextLimit, maxOutputTokens: this.store.config.maxOutputTokens, concurrency: 1, source: 'legacy' }, ...this.state.connections];
}
credential(connection) { return connection.id === legacyId ? { key: this.provider.apiKey, revision: 1 } : this.provider.credentials.get(connection.id); }
credential(connection) { return connection.id === legacyId ? { key: this.provider.apiKey, revision: this.provider.legacyCredentialRevision ?? 1 } : this.provider.credentials.get(connection.id); }
vault() { return this.credentialVault ??= new CredentialVault(this.store, this.provider); }
manageCredential(input) {
const connection = this.connection(input.id);
if (input.revision !== connection.revision) throw error('模型连接已修改,请刷新凭据保存页面。', 409);
return this.editRegistry(() => {
const vault = this.vault(), previous = vault.state.entries[connection.id];
if (input.action === 'save') {
const revision = (this.credential(connection)?.revision ?? 0) + 1, record = vault.prepare(connection, input.apiKey, revision);
if (connection.id === legacyId) { this.provider.setKey(input.apiKey); this.provider.legacyCredentialRevision = revision; }
else this.provider.credentials.set(connection.id, { key: input.apiKey.trim(), revision });
vault.stage(connection.id, record);
} else if (input.action === 'delete' || input.action === 'forget') {
vault.stage(connection.id, null);
if (input.action === 'forget') {
if (connection.id === legacyId) { this.provider.setKey(''); this.provider.legacyCredentialRevision = (this.provider.legacyCredentialRevision ?? 1) + 1; }
else this.provider.credentials.set(connection.id, { key: '', revision: (this.credential(connection)?.revision ?? 0) + 1 });
}
} else if (input.action === 'disable' || input.action === 'enable') {
if (!previous) throw error('该连接没有本机保存块。');
vault.stage(connection.id, { ...previous, enabled: input.action === 'enable' });
if (input.action === 'enable') vault.restore(this);
} else throw error('凭据保存操作无效。');
this.save(); return { credential: vault.status(connection), center: this.view(), config: { ...this.store.config, hasKey: this.provider.hasKey() } };
});
}
identity(connection) { return connection.id + ':' + connection.revision + ':' + (this.credential(connection)?.revision ?? 0); }
status(connection) {
const credential = this.credential(connection), health = this.health.get(this.identity(connection));
const ready = connection.enabled && (!connection.requiresKey || !!credential?.key);
return { ...connection, hasKey: !!credential?.key, credentialRevision: credential?.revision ?? 0, credentialStorage: 'memory',
...(this.credentialVault ? { savedCredential: this.credentialVault.status(connection) } : {}),
status: !connection.enabled ? 'disabled' : !ready ? 'needs_key' : health?.blocked ? 'needs_attention' : health?.cooldownUntil > Date.now() ? 'cooling' : 'configured',
activeRequests: this.leases.get(connection.id) ?? 0, health: health ?? { state: 'unverified' },
capabilities: { tools: 'protocol_declared', vision: 'unknown', audio: 'unknown' } };
}
view() { return { revision: this.state.revision, selected: this.state.selected, connections: this.connections().map(value => this.status(value)), pools: this.state.pools,
imports: Object.entries(this.state.imports).map(([id, value]) => ({ id, ...value })), attempts: this.attempts.slice(-100).reverse(), waiting: this.waiting,
storage: { credentials: 'memory', restart: '临时凭据在宿主退出后需要重新填写。', attemptsRetained: 1000 } }; }
storage: { credentials: this.credentialVault ? 'memory-or-windows-user-dpapi' : 'memory', restart: '临时凭据在宿主退出后需要重新填写;已明确本机加密保存的连接按用户与原配置加载。', attemptsRetained: 1000 } }; }
connection(id) { const value = this.connections().find(item => item.id === id); if (!value) throw error('模型连接不存在。', 404); return value; }
upsert(input) {
if (!this.editingRegistry) return this.editRegistry(() => this.upsert(input));
if (input.id === legacyId) throw error('原连接请通过模型连接设置修改。');
const previous = input.id ? this.connection(input.id) : null;
if (this.state.connections.length >= 100 && !previous) throw error('最多保存100个模型连接。');
@@ -100,6 +134,10 @@ export class ModelHub {
this.state.connections = [...this.state.connections.filter(item => item.id !== connection.id), connection];
this.save();
if (Object.hasOwn(input, 'apiKey')) this.provider.credentials.set(connection.id, { key: input.apiKey.trim(), revision: (this.provider.credentials.get(connection.id)?.revision ?? 0) + 1 });
if (input.persistKey === true) {
const vault = this.vault(), record = vault.prepare(connection, input.apiKey, this.credential(connection)?.revision ?? 1);
vault.stage(connection.id, record);
}
return this.status(connection);
}
toggle(id, enabled) {