fix(credentials): persist configured keys across host restarts
This commit is contained in:
@@ -83,7 +83,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, persistCredentials = false) {
|
||||
apply(id, autoSync, persistCredentials) {
|
||||
const preview = this.previews.get(id);
|
||||
if (!preview || Date.now() - preview.created > 300000) throw new Error('导入预览已过期,请重新预览。');
|
||||
const current = this.read(preview.source, preview.path);
|
||||
@@ -91,18 +91,20 @@ export class ConfigImporter {
|
||||
const result = this.hub.editRegistry(() => {
|
||||
const imported = [], conflicts = [];
|
||||
const sourceId = digest({ source: preview.source, path: preview.path });
|
||||
const previousSource = this.hub.state.imports[sourceId];
|
||||
const persist = this.hub.shouldPersistKey(persistCredentials ?? previousSource?.persistCredentials);
|
||||
for (const item of current.entries) {
|
||||
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,
|
||||
persistKey: persist,
|
||||
...(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);
|
||||
}
|
||||
const previousSource = this.hub.state.imports[sourceId];
|
||||
const checkedAt = new Date().toISOString();
|
||||
this.hub.state.imports[sourceId] = { source: preview.source, path: preview.path, enabled: autoSync === undefined ? previousSource?.enabled === true : autoSync === true,
|
||||
persistCredentials: persist,
|
||||
lastFingerprint: current.fingerprint, lastCheckedAt: checkedAt, lastSyncedAt: imported.length ? checkedAt : previousSource?.lastSyncedAt ?? null,
|
||||
lastResult: { imported: imported.length, conflicts } };
|
||||
this.hub.save();
|
||||
@@ -124,7 +126,7 @@ export class ConfigImporter {
|
||||
source.lastCheckedAt = new Date().toISOString();
|
||||
if (read.fingerprint === source.lastFingerprint) { this.hub.save(); continue; }
|
||||
const preview = this.preview(source.source, source.path);
|
||||
reports.push(this.apply(preview.id, true));
|
||||
reports.push(this.apply(preview.id, true, source.persistCredentials ?? false));
|
||||
} catch (cause) { const current = this.hub.state.imports[id]; current.lastError = '来源暂不可读取或格式变化,请重新预览核对。'; current.lastCheckedAt = new Date().toISOString(); this.hub.save(); reports.push({ id, error: current.lastError }); }
|
||||
}
|
||||
return reports;
|
||||
|
||||
@@ -32,7 +32,7 @@ export class CredentialVault {
|
||||
if (connection.credentialSource) return { status: 'reference', storage: 'source-reference', sourceId: connection.credentialSource.connectionId,
|
||||
message: '共用上游源连接的凭据与加载状态,请在源连接管理;没有复制或额外保存 Key。' };
|
||||
if (this.blocked) return { status: 'unavailable', storage: 'windows-user-dpapi', message: '本机保存登记格式损坏或来自新版本,未覆盖原记录。' };
|
||||
if (!Object.hasOwn(this.state.entries, connection.id)) return { status: 'not_saved', storage: 'memory', message: '当前凭据只在宿主内存中。' };
|
||||
if (!Object.hasOwn(this.state.entries, connection.id)) return { status: 'not_saved', storage: 'memory', message: '尚无本机加密副本;仅本次使用的凭据不会在重启后恢复。' };
|
||||
const value = this.state.entries[connection.id];
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value) || value.schema !== 1 || value.connectionId !== connection.id
|
||||
|| !Number.isSafeInteger(value.connectionRevision) || value.connectionRevision < 1 || !Number.isSafeInteger(value.credentialRevision) || value.credentialRevision < 1
|
||||
|
||||
@@ -122,6 +122,7 @@ export class ModelCatalog {
|
||||
if (!unrestricted(this.hub.store) && (input.routing === 'auto' && input.models.length > 32)) throw fail('单个自动模型池最多32个成员;可减少本次选择或分别建立模型池。');
|
||||
if (input.persistKey === true && !value.explicitKey) throw fail('本机加密保存需要本次新填写的 Key;已有凭据沿用原保存状态。');
|
||||
const hub = this.hub;
|
||||
hub.shouldPersistKey(input.persistKey);
|
||||
const result = hub.editRegistry(() => {
|
||||
let owner = value.binding ? hub.credentialOwner(hub.connection(value.binding.id)) : null;
|
||||
if (value.binding && !owner) throw fail('原凭据来源已变化,请核对源连接。', 409);
|
||||
@@ -147,7 +148,7 @@ export class ModelCatalog {
|
||||
capabilityDeclarationSources: Object.fromEntries(Object.entries(model.capabilityDeclarations).map(([key, state]) => [key, state !== 'unknown' ? 'upstream_catalog' : declarations[key] !== 'unknown' ? 'user' : 'protocol'])),
|
||||
contextLimit: reference.fields.contextLimit?.value ?? model.maxInputTokens ?? value.connection.contextLimit ?? DEFAULT_MODEL_CAPACITY.contextLimit,
|
||||
maxOutputTokens: reference.fields.maxOutputTokens?.value ?? value.connection.maxOutputTokens ?? DEFAULT_MODEL_CAPACITY.maxOutputTokens,
|
||||
...(!owner && value.explicitKey ? { apiKey: value.explicitKey, persistKey: input.persistKey === true } : {}) });
|
||||
...(!owner && value.explicitKey ? { apiKey: value.explicitKey, persistKey: input.persistKey } : {}) });
|
||||
const connection = hub.connection(profile.id); connection.upstreamModel = upstreamModel; connection.source = 'upstream-catalog';
|
||||
if (!owner) owner = connection;
|
||||
else connection.credentialSource = { connectionId: owner.id, scope: credentialScope(owner) };
|
||||
|
||||
@@ -140,6 +140,36 @@ export class ModelHub {
|
||||
return !owner ? undefined : owner.id === legacyId ? { key: this.provider.apiKey, revision: this.provider.legacyCredentialRevision ?? 1 } : this.provider.credentials.get(owner.id);
|
||||
}
|
||||
vault() { return this.credentialVault ??= new CredentialVault(this.store, this.provider); }
|
||||
shouldPersistKey(value) {
|
||||
if (value !== undefined && typeof value !== 'boolean') throw error('凭据保存选项必须为开启或关闭。');
|
||||
return value ?? process.platform === 'win32';
|
||||
}
|
||||
writeCredential(connection, apiKey, persistKey, previousRevision = 0) {
|
||||
if (typeof apiKey !== 'string' || apiKey.length > 16000) throw error('模型凭据格式无效。');
|
||||
const key = apiKey.trim(), persist = this.shouldPersistKey(persistKey);
|
||||
const vault = key && persist ? this.vault() : this.credentialVault;
|
||||
const revision = Math.max(previousRevision, this.credential(connection)?.revision ?? 0, this.provider.credentials.get(connection.id)?.revision ?? 0,
|
||||
vault?.state.entries[connection.id]?.credentialRevision ?? 0) + 1;
|
||||
const record = key && persist ? vault.prepare(connection, key, revision) : null;
|
||||
if (connection.id === legacyId) { this.provider.setKey(key); this.provider.legacyCredentialRevision = revision; }
|
||||
else this.provider.credentials.set(connection.id, { key, revision });
|
||||
if (record || vault?.state.entries[connection.id]) vault.stage(connection.id, record);
|
||||
}
|
||||
configureLegacy(config, input) {
|
||||
this.shouldPersistKey(input.persistKey);
|
||||
const previous = this.connection(legacyId);
|
||||
const connection = { ...previous, name: this.state.legacyConnection?.name || config.model || '未配置模型', baseUrl: config.baseUrl, model: config.model,
|
||||
contextLimit: config.contextLimit, maxOutputTokens: config.maxOutputTokens, revision: (this.store.config.configRevision ?? 0) + 1 };
|
||||
const hasKey = Object.hasOwn(input, 'apiKey');
|
||||
connection.credentialBindingRevision = !hasKey && credentialProfile(previous) === credentialProfile(connection)
|
||||
? previous.credentialBindingRevision ?? previous.revision : connection.revision;
|
||||
return this.editRegistry(() => {
|
||||
this.state.selected = { type: 'legacy', id: legacyId };
|
||||
if (this.state.legacyConnection || hasKey || this.credentialVault?.state.entries[legacyId]) this.state.legacyConnection = connection;
|
||||
if (hasKey) this.writeCredential(connection, input.apiKey, input.persistKey);
|
||||
this.save();
|
||||
}, config);
|
||||
}
|
||||
manageCredential(input) {
|
||||
const connection = this.connection(input.id);
|
||||
if (connection.credentialSource) throw error('该模型共用上游凭据,请在源连接管理凭据。');
|
||||
@@ -181,7 +211,9 @@ export class ModelHub {
|
||||
}
|
||||
view() { const page = this.ledger.page({ limit: 100 }); return { revision: this.state.revision, selected: this.state.selected, waitSettings: modelWaitSettings(this.store.config), connections: this.connections().map(value => this.status(value)), pools: this.state.pools,
|
||||
imports: Object.entries(this.state.imports).map(([id, value]) => ({ id, ...value })), attempts: page.items, attemptCount: page.retainedTotal, attemptsHasMore: page.hasMore, waiting: this.waiting,
|
||||
storage: { credentials: this.credentialVault ? 'memory-or-windows-user-dpapi' : 'memory', restart: '临时凭据在宿主退出后需要重新填写;已明确本机加密保存的连接按用户与原配置加载。', attemptsRetained: null,
|
||||
storage: { credentials: this.credentialVault ? 'memory-or-windows-user-dpapi' : 'memory', credentialPersistenceSupported: process.platform === 'win32', defaultPersistKey: process.platform === 'win32',
|
||||
restart: process.platform === 'win32' ? '新填凭据默认本机加密保存并在重启后恢复;只有明确选择仅本次使用的凭据需要重新填写。'
|
||||
: '当前宿主不支持本机加密保存,凭据仅在本次宿主内存中。', attemptsRetained: null,
|
||||
attemptStorage: 'incremental-sqlite', attemptPreview: 100, originalMetadataPreserved: true } }; }
|
||||
selectionView() {
|
||||
const selected = this.state.selected;
|
||||
@@ -239,6 +271,7 @@ export class ModelHub {
|
||||
} finally { this.probing = false; }
|
||||
}
|
||||
upsert(input) {
|
||||
this.shouldPersistKey(input.persistKey);
|
||||
const previous = input.id ? this.connection(input.id) : null;
|
||||
if (!unrestricted(this.store) && this.state.connections.length >= 100 && !previous) throw error('最多保存100个模型连接。');
|
||||
if (previous && input.revision !== previous.revision) throw error('模型连接已修改,请刷新后重试。', 409);
|
||||
@@ -289,15 +322,8 @@ export class ModelHub {
|
||||
if (legacy) this.state.legacyConnection = connection;
|
||||
else this.state.connections = [...this.state.connections.filter(item => item.id !== connection.id), connection];
|
||||
this.save();
|
||||
if (Object.hasOwn(input, 'apiKey')) {
|
||||
const revision = Math.max(this.credential(previous ?? connection)?.revision ?? 0, this.provider.credentials.get(connection.id)?.revision ?? 0) + 1;
|
||||
if (legacy) { this.provider.setKey(input.apiKey); this.provider.legacyCredentialRevision = revision; }
|
||||
else this.provider.credentials.set(connection.id, { key: input.apiKey.trim(), revision });
|
||||
}
|
||||
if (input.persistKey === true) {
|
||||
const vault = this.vault(), record = vault.prepare(connection, input.apiKey, this.credential(connection)?.revision ?? 1);
|
||||
vault.stage(connection.id, record);
|
||||
}
|
||||
if (Object.hasOwn(input, 'apiKey')) this.writeCredential(connection, input.apiKey, input.persistKey, this.credential(previous ?? connection)?.revision ?? 0);
|
||||
else if (input.persistKey === true) throw error('加密保存需要本次填写 API Key。');
|
||||
return this.status(connection);
|
||||
}
|
||||
setNativeParameters(input) {
|
||||
|
||||
Reference in New Issue
Block a user