@lsamien/yaoyao 0.4.76 → 0.4.78
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -5
- package/THIRD_PARTY_NOTICES.md +8 -0
- package/bin/hermes-yaoyao.mjs +15 -2
- package/build-info.json +35 -3
- package/desktop/main.mjs +12 -4
- package/dist/assets/{AboutDialog-fbm5CG09.js → AboutDialog-jvhTP8-J.js} +2 -2
- package/dist/assets/AboutDialog-jvhTP8-J.js.map +1 -0
- package/dist/assets/BotAutomationsView-ktoci79V.js +2 -0
- package/dist/assets/{BotAutomationsView-DPAAYyuy.js.map → BotAutomationsView-ktoci79V.js.map} +1 -1
- package/dist/assets/{BotPluginsDialog-MwGpwjgu.js → BotPluginsDialog-H85RI-7P.js} +2 -2
- package/dist/assets/{BotPluginsDialog-MwGpwjgu.js.map → BotPluginsDialog-H85RI-7P.js.map} +1 -1
- package/dist/assets/{BotSettingsDialog-DXtsSzi8.js → BotSettingsDialog-Ci_DZL4m.js} +5 -5
- package/dist/assets/{BotSettingsDialog-DXtsSzi8.js.map → BotSettingsDialog-Ci_DZL4m.js.map} +1 -1
- package/dist/assets/ChatView-6cdLMsuy.js +2 -0
- package/dist/assets/ChatView-6cdLMsuy.js.map +1 -0
- package/dist/assets/ChatView-C_7_7olu.css +1 -0
- package/dist/assets/{ComputerPanel-B0QyKQkF.js → ComputerPanel-Dbwgx5n8.js} +2 -2
- package/dist/assets/{ComputerPanel-B0QyKQkF.js.map → ComputerPanel-Dbwgx5n8.js.map} +1 -1
- package/dist/assets/{ComputerViewerView-CaOkTXpc.js → ComputerViewerView-csnhRedK.js} +2 -2
- package/dist/assets/{ComputerViewerView-CaOkTXpc.js.map → ComputerViewerView-csnhRedK.js.map} +1 -1
- package/dist/assets/ConversationsView-CEO2SVGT.js +6 -0
- package/dist/assets/ConversationsView-CEO2SVGT.js.map +1 -0
- package/dist/assets/{ConversationsView-C_VZl5g2.css → ConversationsView-CHLGKsJt.css} +1 -1
- package/dist/assets/FilesView-t5jA-H2-.js +2 -0
- package/dist/assets/{FilesView-CluNyIk8.js.map → FilesView-t5jA-H2-.js.map} +1 -1
- package/dist/assets/FloatingResourceSearch-3GOuDkuO.css +1 -0
- package/dist/assets/FloatingResourceSearch-BAYymuJV.js +9 -0
- package/dist/assets/FloatingResourceSearch-BAYymuJV.js.map +1 -0
- package/dist/assets/HistoryView-BqMSV9iC.js +2 -0
- package/dist/assets/HistoryView-BqMSV9iC.js.map +1 -0
- package/dist/assets/HistoryView-DlVfSP_p.css +1 -0
- package/dist/assets/KanbanView-CWwrwH9S.js +2 -0
- package/dist/assets/{KanbanView-D5AdRwqi.js.map → KanbanView-CWwrwH9S.js.map} +1 -1
- package/dist/assets/{LocalVmSettingsPanel-BILcGHmu.js → LocalVmSettingsPanel-BXvZwFQP.js} +2 -2
- package/dist/assets/{LocalVmSettingsPanel-BILcGHmu.js.map → LocalVmSettingsPanel-BXvZwFQP.js.map} +1 -1
- package/dist/assets/{RunnerSettingsPanel-IHLAFIh8.js → RunnerSettingsPanel-KkpIkkob.js} +2 -2
- package/dist/assets/{RunnerSettingsPanel-IHLAFIh8.js.map → RunnerSettingsPanel-KkpIkkob.js.map} +1 -1
- package/dist/assets/{StandaloneDialog-DdcL_wV2.js → StandaloneDialog-D4BQqjpB.js} +2 -2
- package/dist/assets/{StandaloneDialog-DdcL_wV2.js.map → StandaloneDialog-D4BQqjpB.js.map} +1 -1
- package/dist/assets/{UpdateCheckDialog-CJQezkXo.js → UpdateCheckDialog-Ct0bT6xU.js} +2 -2
- package/dist/assets/{UpdateCheckDialog-CJQezkXo.js.map → UpdateCheckDialog-Ct0bT6xU.js.map} +1 -1
- package/dist/assets/{WorkspaceKnowledgePanel-DS0kOQgg.js → WorkspaceKnowledgePanel-WBcPB49x.js} +2 -2
- package/dist/assets/{WorkspaceKnowledgePanel-DS0kOQgg.js.map → WorkspaceKnowledgePanel-WBcPB49x.js.map} +1 -1
- package/dist/assets/{WorkspaceRoutinesPanel-DpVAtnDX.js → WorkspaceRoutinesPanel-JubUwGsV.js} +2 -2
- package/dist/assets/{WorkspaceRoutinesPanel-DpVAtnDX.js.map → WorkspaceRoutinesPanel-JubUwGsV.js.map} +1 -1
- package/dist/assets/WorkspaceShell-0m4gg6AW.css +1 -0
- package/dist/assets/WorkspaceShell-Do2VAwIz.js +44 -0
- package/dist/assets/WorkspaceShell-Do2VAwIz.js.map +1 -0
- package/dist/assets/{WorkspaceView-Cco3Umfn.js → WorkspaceView-DTanioWW.js} +2 -2
- package/dist/assets/{WorkspaceView-Cco3Umfn.js.map → WorkspaceView-DTanioWW.js.map} +1 -1
- package/dist/assets/{docx-preview-C6qrP-g2.js → docx-preview-B1SjJgD_.js} +2 -2
- package/dist/assets/{docx-preview-C6qrP-g2.js.map → docx-preview-B1SjJgD_.js.map} +1 -1
- package/dist/assets/index-CWamgtSb.js +17 -0
- package/dist/assets/index-CWamgtSb.js.map +1 -0
- package/dist/assets/{pdf-G3DUsfMb.js → pdf-DVDddcFC.js} +2 -2
- package/dist/assets/{pdf-G3DUsfMb.js.map → pdf-DVDddcFC.js.map} +1 -1
- package/dist/assets/sessionOwnership-0hdKcwOs.js +4 -0
- package/dist/assets/sessionOwnership-0hdKcwOs.js.map +1 -0
- package/dist/assets/{sessionOwnership-BTz0Fyp5.css → sessionOwnership-CfO8CfmZ.css} +1 -1
- package/dist/assets/{viewModels-DfaKvI0x.js → viewModels-DKBqaDRg.js} +12 -12
- package/dist/assets/{viewModels-DfaKvI0x.js.map → viewModels-DKBqaDRg.js.map} +1 -1
- package/dist/index.html +1 -1
- package/dist-server/runner/agent.js +15 -4
- package/dist-server/runner/hermes-bots-bridge/README.md +4 -2
- package/dist-server/runner/hermes-bots-bridge/bridge_runtime.py +21 -2
- package/dist-server/runner/hermes-bots-bridge/plugin.yaml +1 -1
- package/dist-server/runner/worker/gateway.js +52 -22
- package/dist-server/runner/worker/profileSession.js +2 -12
- package/dist-server/server/app.js +15 -1
- package/dist-server/server/chatTranscriptApi.js +2 -2
- package/dist-server/server/chatTranscriptStore.js +16 -0
- package/dist-server/server/config.js +3 -0
- package/dist-server/server/credentialVault/broker.js +272 -0
- package/dist-server/server/credentialVault/coordinator.js +297 -0
- package/dist-server/server/credentialVault/executor.js +1 -0
- package/dist-server/server/credentialVault/fixtureWebsiteExecutor.js +51 -0
- package/dist-server/server/credentialVault/index.js +49 -0
- package/dist-server/server/credentialVault/isolation.js +37 -0
- package/dist-server/server/credentialVault/privateFiles.js +17 -0
- package/dist-server/server/credentialVault/protectedExecutor.js +21 -0
- package/dist-server/server/credentialVault/schema.js +45 -0
- package/dist-server/server/credentialVault/sshExecutor.js +135 -0
- package/dist-server/server/credentialVault/store.js +308 -0
- package/dist-server/server/credentialVault/transport.js +127 -0
- package/dist-server/server/credentialVault/websiteExecutor.js +102 -0
- package/dist-server/server/desktopEnvironments.js +2 -2
- package/dist-server/server/hermesRuntimeEnvironment.js +14 -0
- package/dist-server/server/localAuth.js +5 -0
- package/dist-server/server/openVikingMemoryProvider.js +29 -10
- package/dist-server/server/openVikingService.js +44 -14
- package/dist-server/server/openVikingSessionSync.js +148 -37
- package/dist-server/server/pushCoordinator.js +7 -4
- package/dist-server/server/realtimeApi.js +11 -2
- package/dist-server/server/realtimeBroker.js +1 -1
- package/dist-server/server/realtimeReceipts.js +39 -8
- package/dist-server/server/routes.js +18 -0
- package/dist-server/server/runnerHub.js +17 -4
- package/dist-server/server/sessionStop.js +19 -0
- package/dist-server/server/subaccountAccess.js +12 -0
- package/dist-server/server/taskCoordinator.js +3 -1
- package/dist-server/server/unreadCenter.js +61 -0
- package/dist-server/server/uploads.js +4 -1
- package/dist-server/server/workspaceAssets.js +56 -12
- package/dist-server/server/workspaceEnvironment.js +1 -0
- package/dist-server/server/workspaceMemorySynthesis.js +5 -1
- package/dist-server/server/workspacePrompt.js +5 -1
- package/dist-server/server/workspaceRoutes.js +26 -21
- package/dist-server/server/workspaceRuntime.js +89 -8
- package/dist-server/server/workspaceScheduler.js +5 -1
- package/dist-server/server/workspaceStore.js +125 -47
- package/dist-server/server/workspaceSync.js +4 -1
- package/dist-server/shared/botEnvironment.js +3 -3
- package/dist-server/shared/credentialVault.js +2 -0
- package/dist-server/shared/unread.js +6 -0
- package/dist-server/shared/uploadNames.js +14 -0
- package/licenses/libsodium.js/LICENSE +16 -0
- package/licenses/ssh2/LICENSE +19 -0
- package/package.json +8 -5
- package/release.json +3 -3
- package/dist/assets/AboutDialog-fbm5CG09.js.map +0 -1
- package/dist/assets/BotAutomationsView-DPAAYyuy.js +0 -2
- package/dist/assets/ChatView-BNqHa6Ma.js +0 -2
- package/dist/assets/ChatView-BNqHa6Ma.js.map +0 -1
- package/dist/assets/ChatView-Dx8YlcPr.css +0 -1
- package/dist/assets/ConversationsView-CYNc59hv.js +0 -6
- package/dist/assets/ConversationsView-CYNc59hv.js.map +0 -1
- package/dist/assets/FilesView-CluNyIk8.js +0 -2
- package/dist/assets/FloatingResourceSearch-BF2XOLd-.css +0 -1
- package/dist/assets/FloatingResourceSearch-Bg5rUZMy.js +0 -9
- package/dist/assets/FloatingResourceSearch-Bg5rUZMy.js.map +0 -1
- package/dist/assets/HistoryView-DSbSDzsB.js +0 -2
- package/dist/assets/HistoryView-DSbSDzsB.js.map +0 -1
- package/dist/assets/HistoryView-DvuCAjlo.css +0 -1
- package/dist/assets/KanbanView-D5AdRwqi.js +0 -2
- package/dist/assets/WorkspaceShell-7wn8iTne.css +0 -1
- package/dist/assets/WorkspaceShell-Bykfy3AR.js +0 -44
- package/dist/assets/WorkspaceShell-Bykfy3AR.js.map +0 -1
- package/dist/assets/index-CEqMqiJr.js +0 -17
- package/dist/assets/index-CEqMqiJr.js.map +0 -1
- package/dist/assets/sessionOwnership-DMfBRINe.js +0 -6
- package/dist/assets/sessionOwnership-DMfBRINe.js.map +0 -1
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/** Operator-started foreground service. Never started by Web/Runner or the model.
|
|
2
|
+
* No setup of OS users, permissions, service manager or network rules is performed. */
|
|
3
|
+
import { chmodSync } from 'node:fs';
|
|
4
|
+
import { isAbsolute } from 'node:path';
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import { parse } from './schema.js';
|
|
7
|
+
import { CredentialVaultStore } from './store.js';
|
|
8
|
+
import { CredentialVaultBroker } from './broker.js';
|
|
9
|
+
import { serveCredentialVault } from './transport.js';
|
|
10
|
+
import { acquireServiceInstance } from '../serviceInstance.js';
|
|
11
|
+
import { readPrivateUtf8 } from './privateFiles.js';
|
|
12
|
+
import { OperatorIsolationGate } from './isolation.js';
|
|
13
|
+
import { ProtectedCredentialExecutor } from './protectedExecutor.js';
|
|
14
|
+
try {
|
|
15
|
+
const index = process.argv.indexOf('--config'), path = index < 0 ? undefined : process.argv[index + 1];
|
|
16
|
+
if (!path)
|
|
17
|
+
throw new Error('用法:node credentialVault/index.js --config /私有路径/vault.json');
|
|
18
|
+
const config = parse(z.object({ home: z.string().refine(isAbsolute), socket: z.string().refine(isAbsolute), tokenFile: z.string().refine(isAbsolute),
|
|
19
|
+
hermesUid: z.number().int().positive(), execution: z.object({ approvalFile: z.string().refine(isAbsolute), hermesPid: z.number().int().positive(), home: z.string().refine(isAbsolute) }).strict().optional() }).strict(), JSON.parse(readPrivateUtf8(path, 8192)));
|
|
20
|
+
if (!process.getuid || process.getuid() === 0 || process.getuid() === config.hermesUid)
|
|
21
|
+
throw new Error('密码库需要独立非 root OS 身份,不能与 Hermes 同用户运行');
|
|
22
|
+
const controlToken = readPrivateUtf8(config.tokenFile, 4096).trim();
|
|
23
|
+
const store = await CredentialVaultStore.create(config.home);
|
|
24
|
+
process.umask(0o077);
|
|
25
|
+
const instance = acquireServiceInstance(store.root, 'credential-vault-v1');
|
|
26
|
+
const executor = config.execution ? new ProtectedCredentialExecutor(config.execution.home, new OperatorIsolationGate(config.execution.approvalFile, config.hermesUid, config.execution.hermesPid)) : undefined;
|
|
27
|
+
const broker = new CredentialVaultBroker(store, Date.now, executor);
|
|
28
|
+
const server = serveCredentialVault(broker, controlToken);
|
|
29
|
+
process.once('exit', () => { broker.close(); instance.release(); });
|
|
30
|
+
server.listen(config.socket, () => {
|
|
31
|
+
try {
|
|
32
|
+
chmodSync(config.socket, 0o600);
|
|
33
|
+
process.stdout.write('密码库私有服务已启动,默认锁定;执行能力以专用管理界面状态为准\n');
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
broker.close();
|
|
37
|
+
server.close();
|
|
38
|
+
process.exitCode = 1;
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
const stop = () => { broker.close(); server.close(() => { instance.release(); }); server.closeAllConnections(); };
|
|
42
|
+
server.once('error', () => { stop(); process.exitCode = 1; process.stderr.write('密码库私有服务无法监听,请检查路径或已有实例\n'); });
|
|
43
|
+
process.once('SIGTERM', stop);
|
|
44
|
+
process.once('SIGINT', stop);
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
process.stderr.write('密码库启动失败,请检查私有配置和独立 OS 身份;不会自动修改系统设置\n');
|
|
48
|
+
process.exitCode = 1;
|
|
49
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { readPrivateUtf8 } from './privateFiles.js';
|
|
4
|
+
import { parse } from './schema.js';
|
|
5
|
+
import { HttpError } from '../errors.js';
|
|
6
|
+
const controls = ['separate-identity', 'hermes-no-control-access', 'browser-private-no-cdp', 'restricted-egress'];
|
|
7
|
+
const approval = z.object({ version: z.literal(1), approved: z.literal(true), brokerUid: z.number().int().positive(), hermesUid: z.number().int().positive(), hermesPid: z.number().int().positive(),
|
|
8
|
+
approvedAt: z.number().int().positive(), expiresAt: z.number().int().positive(), controls: z.array(z.enum(controls)).length(4) }).strict();
|
|
9
|
+
const processUid = (pid) => Number(execFileSync('/bin/ps', ['-o', 'uid=', '-p', String(pid)], { encoding: 'utf8', timeout: 2000, env: { PATH: '/usr/bin:/bin' } }).trim());
|
|
10
|
+
/** Manual operator approval is a deployment trust contract, NOT proof of OS,
|
|
11
|
+
* IPC/CDP/firewall isolation. Also checks the observable process identity.
|
|
12
|
+
* CLI uses the real probe; tests inject a dummy probe without inspecting users. */
|
|
13
|
+
export class OperatorIsolationGate {
|
|
14
|
+
path;
|
|
15
|
+
hermesUid;
|
|
16
|
+
hermesPid;
|
|
17
|
+
probe;
|
|
18
|
+
now;
|
|
19
|
+
constructor(path, hermesUid, hermesPid, probe = processUid, now = Date.now) {
|
|
20
|
+
this.path = path;
|
|
21
|
+
this.hermesUid = hermesUid;
|
|
22
|
+
this.hermesPid = hermesPid;
|
|
23
|
+
this.probe = probe;
|
|
24
|
+
this.now = now;
|
|
25
|
+
}
|
|
26
|
+
assert() {
|
|
27
|
+
try {
|
|
28
|
+
const a = parse(approval, JSON.parse(readPrivateUtf8(this.path, 8192))), uid = process.getuid?.();
|
|
29
|
+
if (!uid || uid !== a.brokerUid || uid === a.hermesUid || a.hermesUid !== this.hermesUid || a.hermesPid !== this.hermesPid || this.probe(a.hermesPid) !== a.hermesUid
|
|
30
|
+
|| a.approvedAt > this.now() || a.expiresAt <= this.now() || a.expiresAt - a.approvedAt > 31 * 86400000 || new Set(a.controls).size !== controls.length)
|
|
31
|
+
throw new Error();
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
throw new HttpError(503, '执行隔离尚未获得有效人工批准或身份已变化', 'vault_isolation_required');
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { constants, openSync, fstatSync, readFileSync, closeSync } from 'node:fs';
|
|
2
|
+
/** Open first without following a final symlink, then check the actual inode. */
|
|
3
|
+
export function readPrivateUtf8(path, maxBytes) {
|
|
4
|
+
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
5
|
+
try {
|
|
6
|
+
const s = fstatSync(fd);
|
|
7
|
+
if (!s.isFile() || (s.mode & 0o077) || s.uid !== process.getuid?.() || s.size > maxBytes)
|
|
8
|
+
throw new Error('private file required');
|
|
9
|
+
const bytes = readFileSync(fd);
|
|
10
|
+
if (bytes.length > maxBytes)
|
|
11
|
+
throw new Error('private file size limit');
|
|
12
|
+
return bytes.toString('utf8');
|
|
13
|
+
}
|
|
14
|
+
finally {
|
|
15
|
+
closeSync(fd);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { mkdirSync, lstatSync } from 'node:fs';
|
|
2
|
+
import { WebsiteFormExecutor } from './websiteExecutor.js';
|
|
3
|
+
import { SshSftpExecutor } from './sshExecutor.js';
|
|
4
|
+
export class ProtectedCredentialExecutor {
|
|
5
|
+
gate;
|
|
6
|
+
mode = 'protected-adapters';
|
|
7
|
+
website;
|
|
8
|
+
ssh;
|
|
9
|
+
constructor(home, gate, testCA) {
|
|
10
|
+
this.gate = gate;
|
|
11
|
+
gate.assert();
|
|
12
|
+
mkdirSync(home, { recursive: true, mode: 0o700 });
|
|
13
|
+
const stat = lstatSync(home);
|
|
14
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || (stat.mode & 0o077) || stat.uid !== process.getuid?.())
|
|
15
|
+
throw new Error('private executor home required');
|
|
16
|
+
this.website = new WebsiteFormExecutor(home, gate, testCA);
|
|
17
|
+
this.ssh = new SshSftpExecutor(gate);
|
|
18
|
+
}
|
|
19
|
+
assertAvailable() { this.gate.assert(); }
|
|
20
|
+
execute(entry, input, signal) { this.gate.assert(); return entry.target.kind === 'website' ? this.website.execute(entry, input, signal) : this.ssh.execute(entry, input, signal); }
|
|
21
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { HttpError } from '../errors.js';
|
|
3
|
+
export const website = z.object({ kind: z.literal('website'), origin: z.string().max(2000).transform((value, ctx) => {
|
|
4
|
+
try {
|
|
5
|
+
const u = new URL(value);
|
|
6
|
+
if (u.protocol !== 'https:' || u.username || u.password || u.search || u.hash || (u.pathname !== '/' && u.pathname !== ''))
|
|
7
|
+
throw new Error();
|
|
8
|
+
return u.origin;
|
|
9
|
+
}
|
|
10
|
+
catch {
|
|
11
|
+
ctx.addIssue({ code: 'custom', message: '网站需要准确的 HTTPS origin' });
|
|
12
|
+
return z.NEVER;
|
|
13
|
+
}
|
|
14
|
+
}) }).strict();
|
|
15
|
+
export const ssh = z.object({ kind: z.literal('ssh'), host: z.string().min(1).max(253).regex(/^[A-Za-z0-9.:[\]_-]+$/).transform(v => v.toLowerCase()),
|
|
16
|
+
port: z.number().int().min(1).max(65535), hostKey: z.string().regex(/^SHA256:[A-Za-z0-9+/]{43}=?$/) }).strict();
|
|
17
|
+
export const target = z.discriminatedUnion('kind', [website, ssh]);
|
|
18
|
+
const path = z.string().min(2).max(1024).refine(v => v.startsWith('/') && !v.includes('\\') && !/[\u0000-\u001f\u007f?#]/.test(v) && v.split('/').every((s, i) => i === 0 || !!s && s !== '.' && s !== '..'));
|
|
19
|
+
const name = z.string().min(1).max(100).regex(/^[A-Za-z][A-Za-z0-9_.:-]*$/);
|
|
20
|
+
const form = z.object({ kind: z.literal('website.form'), loginPath: path, submitPath: path, successPath: path, logoutPath: path.optional(), formId: name, usernameName: name, passwordName: name,
|
|
21
|
+
successSelector: z.string().min(1).max(256).regex(/^(#[A-Za-z][A-Za-z0-9_-]*|\[data-[a-z0-9-]+(?:="[A-Za-z0-9_-]+")?\])$/) }).strict();
|
|
22
|
+
const command = z.object({ kind: z.literal('ssh.exec'), command: z.string().max(512).regex(/^\/[A-Za-z0-9_/-]+$/).refine(v => !v.includes('//') && !v.endsWith('/')) }).strict();
|
|
23
|
+
const read = z.object({ kind: z.literal('sftp.read'), remotePath: path, maxBytes: z.number().int().min(1).max(1048576).default(65536) }).strict();
|
|
24
|
+
const write = z.object({ kind: z.literal('sftp.write'), remotePath: path, contents: z.string().max(65536) }).strict();
|
|
25
|
+
export const usage = z.discriminatedUnion('kind', [form, command, read, write]);
|
|
26
|
+
const updatedUsage = z.discriminatedUnion('kind', [form, command, read, write.extend({ contents: z.string().max(65536).optional() })]);
|
|
27
|
+
export const leaseInput = z.object({
|
|
28
|
+
credentialRef: z.string().uuid(), agentId: z.string().uuid(), workId: z.string().uuid(),
|
|
29
|
+
runnerId: z.string().uuid(), runnerInstance: z.string().uuid(), runnerEpoch: z.string().min(1).max(128),
|
|
30
|
+
operation: z.enum(['website.login', 'ssh.exec', 'sftp.read', 'sftp.write']), target,
|
|
31
|
+
seconds: z.number().int().min(15).max(120).default(60),
|
|
32
|
+
}).strict();
|
|
33
|
+
export const entryInput = z.object({ name: z.string().trim().min(1).max(120), username: z.string().min(1).max(256),
|
|
34
|
+
target, usage: usage.optional(), secret: z.string().min(1).max(32768), passphrase: z.string().max(4096).optional() }).strict();
|
|
35
|
+
export const updateInput = entryInput.extend({ secret: entryInput.shape.secret.optional(), usage: updatedUsage.optional(), revision: z.number().int().positive() });
|
|
36
|
+
export const storedEntry = entryInput.extend({ id: z.string().uuid(), revision: z.number().int().positive(), updatedAt: z.number().int().nonnegative() });
|
|
37
|
+
export function parse(schema, value) {
|
|
38
|
+
const result = schema.safeParse(value);
|
|
39
|
+
if (!result.success)
|
|
40
|
+
throw new HttpError(400, '密码库请求格式无效', 'vault_invalid_request');
|
|
41
|
+
return result.data;
|
|
42
|
+
}
|
|
43
|
+
export function masterPassword(value) {
|
|
44
|
+
return parse(z.string().min(12).max(1024), value);
|
|
45
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { Client } from 'ssh2';
|
|
2
|
+
import { createHash, timingSafeEqual } from 'node:crypto';
|
|
3
|
+
import { HttpError } from '../errors.js';
|
|
4
|
+
const call = (start) => new Promise((resolve, reject) => start((error, value) => error ? reject(error) : resolve(value)));
|
|
5
|
+
/** Key-only, pinned-host SSH. No shell session, command interpolation, PTY,
|
|
6
|
+
* environment, agent forwarding, ProxyCommand, jump host or TCP forwarding. */
|
|
7
|
+
export class SshSftpExecutor {
|
|
8
|
+
gate;
|
|
9
|
+
constructor(gate) {
|
|
10
|
+
this.gate = gate;
|
|
11
|
+
}
|
|
12
|
+
async execute(entry, input, externalSignal) {
|
|
13
|
+
this.gate.assert();
|
|
14
|
+
externalSignal.throwIfAborted();
|
|
15
|
+
const plan = entry.usage;
|
|
16
|
+
if (entry.target.kind !== 'ssh' || input.target.kind !== 'ssh' || JSON.stringify(entry.target) !== JSON.stringify(input.target) || !plan || plan.kind === 'website.form' || plan.kind !== input.operation)
|
|
17
|
+
return { status: 'manual_takeover_required', reason: 'usage_policy_required', submitted: false };
|
|
18
|
+
const host = entry.target, expected = Buffer.from(host.hostKey.slice(7), 'base64');
|
|
19
|
+
if (expected.length !== 32)
|
|
20
|
+
throw new HttpError(403, 'SSH host key 指纹无效', 'vault_host_key_rejected');
|
|
21
|
+
const signal = AbortSignal.any([externalSignal, AbortSignal.timeout(15000)]), conn = new Client();
|
|
22
|
+
let hostRejected = false, finished = false, fail, ready;
|
|
23
|
+
const failure = new Promise((_r, reject) => { fail = reject; }), connected = new Promise(resolve => { ready = resolve; });
|
|
24
|
+
// connect() can synchronously reject a malformed key before work is created.
|
|
25
|
+
// Keep close/error rejection observed on that path as well.
|
|
26
|
+
void failure.catch(() => { });
|
|
27
|
+
const invoke = (start) => Promise.race([call(start), failure]);
|
|
28
|
+
const abort = () => { fail(new Error('operation cancelled')); conn.destroy(); };
|
|
29
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
30
|
+
conn.on('error', () => fail(hostRejected ? new HttpError(403, 'SSH host key 与人工批准指纹不符', 'vault_host_key_rejected') : new Error('SSH connection unavailable')));
|
|
31
|
+
conn.on('close', () => { if (!finished)
|
|
32
|
+
fail(new Error('SSH receipt unavailable')); });
|
|
33
|
+
conn.once('ready', ready);
|
|
34
|
+
const check = () => { signal.throwIfAborted(); this.gate.assert(); };
|
|
35
|
+
try {
|
|
36
|
+
conn.connect({ host: host.host.replace(/^\[|\]$/g, ''), port: host.port, username: entry.username, privateKey: entry.secret, ...(entry.passphrase ? { passphrase: entry.passphrase } : {}),
|
|
37
|
+
authHandler: ['publickey'], tryKeyboard: false, agentForward: false, readyTimeout: 5000, keepaliveInterval: 0,
|
|
38
|
+
algorithms: { serverHostKey: ['ssh-ed25519', 'rsa-sha2-512', 'rsa-sha2-256', 'ecdsa-sha2-nistp256'] },
|
|
39
|
+
hostVerifier: (key) => { const digest = createHash('sha256').update(key).digest(); const match = timingSafeEqual(digest, expected); hostRejected = !match; return match; } });
|
|
40
|
+
const work = (async () => {
|
|
41
|
+
await Promise.race([connected, failure]);
|
|
42
|
+
check();
|
|
43
|
+
if (plan.kind === 'ssh.exec') {
|
|
44
|
+
// Exactly the user-approved absolute executable; no arguments or
|
|
45
|
+
// strings assembled from model input are ever sent to the server.
|
|
46
|
+
const stream = await invoke(done => conn.exec(plan.command, { pty: false }, done));
|
|
47
|
+
check();
|
|
48
|
+
let output = 0;
|
|
49
|
+
const discard = (data) => { output += data.length; if (output > 65536)
|
|
50
|
+
abort(); };
|
|
51
|
+
stream.on('data', discard);
|
|
52
|
+
stream.stderr.on('data', discard);
|
|
53
|
+
stream.on('error', () => fail(new Error('SSH command interrupted')));
|
|
54
|
+
const code = await new Promise((resolve, reject) => { stream.once('close', (value) => Number.isInteger(value) ? resolve(value) : reject(new Error('SSH exit receipt unavailable'))); stream.end(); });
|
|
55
|
+
check();
|
|
56
|
+
return { status: 'complete', operation: 'ssh.exec', exitCode: code };
|
|
57
|
+
}
|
|
58
|
+
const sftp = await invoke(done => conn.sftp(done));
|
|
59
|
+
sftp.on('error', () => fail(new Error('SFTP interrupted')));
|
|
60
|
+
check();
|
|
61
|
+
if (plan.kind === 'sftp.read') {
|
|
62
|
+
const canonical = await invoke(done => sftp.realpath(plan.remotePath, done));
|
|
63
|
+
check();
|
|
64
|
+
if (canonical !== plan.remotePath)
|
|
65
|
+
throw new HttpError(403, 'SFTP 读取目标不是批准的准确路径', 'vault_usage_forbidden');
|
|
66
|
+
const handle = await invoke(done => sftp.open(plan.remotePath, 'r', done));
|
|
67
|
+
check();
|
|
68
|
+
try {
|
|
69
|
+
const stat = await invoke(done => sftp.fstat(handle, done));
|
|
70
|
+
check();
|
|
71
|
+
if (!stat.isFile() || stat.size > plan.maxBytes)
|
|
72
|
+
throw new HttpError(403, 'SFTP 读取文件超出授权类型或大小', 'vault_usage_forbidden');
|
|
73
|
+
const digest = createHash('sha256'), buffer = Buffer.alloc(16384);
|
|
74
|
+
let bytes = 0;
|
|
75
|
+
try {
|
|
76
|
+
while (true) {
|
|
77
|
+
check();
|
|
78
|
+
const count = await invoke(done => sftp.read(handle, buffer, 0, Math.min(buffer.length, plan.maxBytes + 1 - bytes), bytes, (error, count) => done(error, count)));
|
|
79
|
+
check();
|
|
80
|
+
if (!count)
|
|
81
|
+
break;
|
|
82
|
+
bytes += count;
|
|
83
|
+
if (bytes > plan.maxBytes)
|
|
84
|
+
throw new Error('SFTP size limit');
|
|
85
|
+
digest.update(buffer.subarray(0, count));
|
|
86
|
+
}
|
|
87
|
+
return { status: 'complete', operation: 'sftp.read', bytes, sha256: digest.digest('hex') };
|
|
88
|
+
}
|
|
89
|
+
finally {
|
|
90
|
+
buffer.fill(0);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
finally {
|
|
94
|
+
await invoke(done => sftp.close(handle, error => done(error, undefined))).catch(() => { });
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
const slash = plan.remotePath.lastIndexOf('/'), parent = plan.remotePath.slice(0, slash) || '/';
|
|
98
|
+
const canonical = await invoke(done => sftp.realpath(parent, done));
|
|
99
|
+
check();
|
|
100
|
+
if (canonical !== parent)
|
|
101
|
+
throw new HttpError(403, 'SFTP 写入目录不是批准的准确路径', 'vault_usage_forbidden');
|
|
102
|
+
if (Buffer.byteLength(plan.contents, 'utf8') > 65536)
|
|
103
|
+
throw new HttpError(403, 'SFTP 写入超过授权大小', 'vault_usage_forbidden');
|
|
104
|
+
const data = Buffer.from(plan.contents, 'utf8');
|
|
105
|
+
let handle;
|
|
106
|
+
try {
|
|
107
|
+
// Exclusive creation: never overwrite or follow an existing final link.
|
|
108
|
+
handle = await invoke(done => sftp.open(plan.remotePath, 'wx', { mode: 0o600 }, done));
|
|
109
|
+
check();
|
|
110
|
+
for (let offset = 0; offset < data.length; offset += 16384) {
|
|
111
|
+
check();
|
|
112
|
+
await invoke(done => sftp.write(handle, data, offset, Math.min(16384, data.length - offset), offset, error => done(error, undefined)));
|
|
113
|
+
check();
|
|
114
|
+
}
|
|
115
|
+
await invoke(done => sftp.close(handle, error => done(error, undefined)));
|
|
116
|
+
check();
|
|
117
|
+
handle = undefined;
|
|
118
|
+
return { status: 'complete', operation: 'sftp.write', bytes: data.length, sha256: createHash('sha256').update(data).digest('hex') };
|
|
119
|
+
}
|
|
120
|
+
finally {
|
|
121
|
+
data.fill(0);
|
|
122
|
+
if (handle)
|
|
123
|
+
await invoke(done => sftp.close(handle, error => done(error, undefined))).catch(() => { });
|
|
124
|
+
} // Interrupted writes may leave a partial file: never retry or overwrite automatically.
|
|
125
|
+
})();
|
|
126
|
+
const result = await Promise.race([work, failure]);
|
|
127
|
+
finished = true;
|
|
128
|
+
return result;
|
|
129
|
+
}
|
|
130
|
+
finally {
|
|
131
|
+
signal.removeEventListener('abort', abort);
|
|
132
|
+
conn.destroy();
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
import sodium from 'libsodium-wrappers-sumo';
|
|
2
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
3
|
+
import { mkdirSync, lstatSync, openSync, writeFileSync, fsyncSync, closeSync, renameSync, rmSync } from 'node:fs';
|
|
4
|
+
import { join, resolve } from 'node:path';
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import { HttpError } from '../errors.js';
|
|
7
|
+
import { entryInput, updateInput, storedEntry, parse, masterPassword } from './schema.js';
|
|
8
|
+
import { readPrivateUtf8 } from './privateFiles.js';
|
|
9
|
+
const MAX_BYTES = 2 * 1024 * 1024;
|
|
10
|
+
const bytes = z.string().max(MAX_BYTES).regex(/^[A-Za-z0-9+/]*={0,2}$/);
|
|
11
|
+
const envelopeSchema = z.object({
|
|
12
|
+
format: z.literal('yaoyao-credential-vault'), version: z.literal(1),
|
|
13
|
+
owner: z.string().min(1).max(256), id: z.string().uuid(), revision: z.number().int().positive(),
|
|
14
|
+
kdf: z.object({ algorithm: z.literal('argon2id13'), salt: bytes, ops: z.literal(3), memory: z.literal(67108864) }).strict(),
|
|
15
|
+
wrapping: z.object({ nonce: bytes, ciphertext: bytes }).strict(),
|
|
16
|
+
payload: z.object({ nonce: bytes, ciphertext: bytes }).strict(),
|
|
17
|
+
}).strict();
|
|
18
|
+
const documentSchema = z.object({ entries: z.array(storedEntry).max(256) }).strict();
|
|
19
|
+
const encode = (value) => sodium.to_base64(value, sodium.base64_variants.ORIGINAL);
|
|
20
|
+
const decode = (value, length) => {
|
|
21
|
+
const data = sodium.from_base64(value, sodium.base64_variants.ORIGINAL);
|
|
22
|
+
if (length !== undefined && data.length !== length)
|
|
23
|
+
throw new Error('invalid envelope');
|
|
24
|
+
return data;
|
|
25
|
+
};
|
|
26
|
+
const wipe = (value) => { if (value)
|
|
27
|
+
sodium.memzero(value); };
|
|
28
|
+
function aad(e, part) {
|
|
29
|
+
return JSON.stringify(['yaoyao-credential-vault', e.version, e.owner, e.id, part,
|
|
30
|
+
...(part === 'key' ? [e.kdf] : [e.revision])]);
|
|
31
|
+
}
|
|
32
|
+
function encrypt(value, key, associated) {
|
|
33
|
+
const nonce = sodium.randombytes_buf(24);
|
|
34
|
+
return { nonce: encode(nonce), ciphertext: encode(sodium.crypto_aead_xchacha20poly1305_ietf_encrypt(value, associated, null, nonce, key)) };
|
|
35
|
+
}
|
|
36
|
+
function decrypt(value, key, associated) {
|
|
37
|
+
return sodium.crypto_aead_xchacha20poly1305_ietf_decrypt(null, decode(value.ciphertext), associated, decode(value.nonce, 24), key);
|
|
38
|
+
}
|
|
39
|
+
function derive(password, e) {
|
|
40
|
+
const data = sodium.from_string(masterPassword(password));
|
|
41
|
+
try {
|
|
42
|
+
return sodium.crypto_pwhash(32, data, decode(e.kdf.salt, 16), e.kdf.ops, e.kdf.memory, sodium.crypto_pwhash_ALG_ARGON2ID13);
|
|
43
|
+
}
|
|
44
|
+
finally {
|
|
45
|
+
wipe(data);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
const summary = ({ secret: _secret, passphrase: _passphrase, usage, ...entry }) => ({ ...entry, ...(usage ? { usage: usage.kind === 'sftp.write' ? { kind: usage.kind, remotePath: usage.remotePath, bytes: Buffer.byteLength(usage.contents) } : usage } : {}) });
|
|
49
|
+
/** This belongs in an independently isolated broker. No file/OS-account key is created.
|
|
50
|
+
* JS strings/GC and WASM are not a secure enclave; same-UID process access must be
|
|
51
|
+
* prevented by deployment. Restart discards the DEK and always starts locked. */
|
|
52
|
+
export class CredentialVaultStore {
|
|
53
|
+
now;
|
|
54
|
+
beforeRename;
|
|
55
|
+
unlocked = new Map();
|
|
56
|
+
failures = new Map();
|
|
57
|
+
root;
|
|
58
|
+
onLock = () => { };
|
|
59
|
+
constructor(root, now = Date.now, beforeRename) {
|
|
60
|
+
this.now = now;
|
|
61
|
+
this.beforeRename = beforeRename;
|
|
62
|
+
this.root = resolve(root);
|
|
63
|
+
mkdirSync(this.root, { recursive: true, mode: 0o700 });
|
|
64
|
+
const stat = lstatSync(this.root);
|
|
65
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || (stat.mode & 0o077) || stat.uid !== process.getuid?.())
|
|
66
|
+
throw new Error('密码库目录必须为当前服务身份的私有目录');
|
|
67
|
+
}
|
|
68
|
+
static async create(root, now = Date.now, beforeRename) {
|
|
69
|
+
await sodium.ready;
|
|
70
|
+
return new CredentialVaultStore(root, now, beforeRename);
|
|
71
|
+
}
|
|
72
|
+
path(owner) {
|
|
73
|
+
parse(z.string().min(1).max(256), owner);
|
|
74
|
+
return join(this.root, createHash('sha256').update(owner).digest('hex') + '.vault');
|
|
75
|
+
}
|
|
76
|
+
load(owner) {
|
|
77
|
+
const path = this.path(owner);
|
|
78
|
+
try {
|
|
79
|
+
const e = parse(envelopeSchema, JSON.parse(readPrivateUtf8(path, MAX_BYTES)));
|
|
80
|
+
if (e.owner !== owner)
|
|
81
|
+
throw new Error();
|
|
82
|
+
return e;
|
|
83
|
+
}
|
|
84
|
+
catch (error) {
|
|
85
|
+
if (error.code === 'ENOENT')
|
|
86
|
+
return;
|
|
87
|
+
throw new HttpError(409, '密码库文件无效或权限不安全', 'vault_corrupt');
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
save(e) {
|
|
91
|
+
const value = JSON.stringify(e);
|
|
92
|
+
if (Buffer.byteLength(value) > MAX_BYTES)
|
|
93
|
+
throw new HttpError(413, '密码库已达到大小上限', 'vault_size_limit');
|
|
94
|
+
const path = this.path(e.owner), temp = path + '.' + randomUUID() + '.tmp';
|
|
95
|
+
try {
|
|
96
|
+
const fd = openSync(temp, 'wx', 0o600);
|
|
97
|
+
try {
|
|
98
|
+
writeFileSync(fd, value);
|
|
99
|
+
fsyncSync(fd);
|
|
100
|
+
}
|
|
101
|
+
finally {
|
|
102
|
+
closeSync(fd);
|
|
103
|
+
}
|
|
104
|
+
this.beforeRename?.();
|
|
105
|
+
renameSync(temp, path);
|
|
106
|
+
const directory = openSync(this.root, 'r');
|
|
107
|
+
try {
|
|
108
|
+
fsyncSync(directory);
|
|
109
|
+
}
|
|
110
|
+
finally {
|
|
111
|
+
closeSync(directory);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
finally {
|
|
115
|
+
rmSync(temp, { force: true });
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
active(owner) {
|
|
119
|
+
const session = this.unlocked.get(owner);
|
|
120
|
+
if (session && session.until <= this.now())
|
|
121
|
+
this.lock(owner);
|
|
122
|
+
const current = this.unlocked.get(owner);
|
|
123
|
+
if (!current)
|
|
124
|
+
throw new HttpError(423, '密码库已锁定,请在密码管理界面手动解锁', 'vault_locked');
|
|
125
|
+
return current;
|
|
126
|
+
}
|
|
127
|
+
state(owner) {
|
|
128
|
+
const s = this.unlocked.get(owner);
|
|
129
|
+
if (s && s.until <= this.now())
|
|
130
|
+
this.lock(owner);
|
|
131
|
+
const current = this.unlocked.get(owner);
|
|
132
|
+
return { initialized: !!this.load(owner), unlocked: !!current, ...(current ? { unlockExpiresAt: current.until } : {}) };
|
|
133
|
+
}
|
|
134
|
+
decodeDocument(e, key) {
|
|
135
|
+
const data = decrypt(e.payload, key, aad(e, 'entries'));
|
|
136
|
+
try {
|
|
137
|
+
return parse(documentSchema, JSON.parse(sodium.to_string(data))).entries;
|
|
138
|
+
}
|
|
139
|
+
finally {
|
|
140
|
+
wipe(data);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
encodeDocument(e, key, entries) {
|
|
144
|
+
const data = sodium.from_string(JSON.stringify({ entries }));
|
|
145
|
+
try {
|
|
146
|
+
return { ...e, payload: encrypt(data, key, aad(e, 'entries')) };
|
|
147
|
+
}
|
|
148
|
+
finally {
|
|
149
|
+
wipe(data);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
initialize(owner, password) {
|
|
153
|
+
if (this.load(owner))
|
|
154
|
+
throw new HttpError(409, '密码库已存在', 'vault_exists');
|
|
155
|
+
const key = sodium.randombytes_buf(32);
|
|
156
|
+
const e = { format: 'yaoyao-credential-vault', version: 1, owner, id: randomUUID(), revision: 1,
|
|
157
|
+
kdf: { algorithm: 'argon2id13', salt: encode(sodium.randombytes_buf(16)), ops: 3, memory: 67108864 },
|
|
158
|
+
wrapping: { nonce: '', ciphertext: '' }, payload: { nonce: '', ciphertext: '' } };
|
|
159
|
+
let kek;
|
|
160
|
+
try {
|
|
161
|
+
kek = derive(password, e);
|
|
162
|
+
e.wrapping = encrypt(key, kek, aad(e, 'key'));
|
|
163
|
+
this.save(this.encodeDocument(e, key, []));
|
|
164
|
+
}
|
|
165
|
+
finally {
|
|
166
|
+
wipe(kek);
|
|
167
|
+
wipe(key);
|
|
168
|
+
}
|
|
169
|
+
return this.state(owner); // Creation does not silently unlock.
|
|
170
|
+
}
|
|
171
|
+
unlock(owner, password, seconds = 300) {
|
|
172
|
+
parse(z.number().int().min(30).max(900), seconds);
|
|
173
|
+
if ((this.failures.get(owner)?.next ?? 0) > this.now())
|
|
174
|
+
throw new HttpError(429, '解锁尝试过多,请稍后重试', 'vault_unlock_throttled');
|
|
175
|
+
const e = this.load(owner);
|
|
176
|
+
if (!e)
|
|
177
|
+
throw new HttpError(404, '请先创建密码库', 'vault_missing');
|
|
178
|
+
this.lock(owner);
|
|
179
|
+
let kek, key;
|
|
180
|
+
try {
|
|
181
|
+
kek = derive(password, e);
|
|
182
|
+
key = decrypt(e.wrapping, kek, aad(e, 'key'));
|
|
183
|
+
if (key.length !== 32)
|
|
184
|
+
throw new Error();
|
|
185
|
+
const entries = this.decodeDocument(e, key);
|
|
186
|
+
this.unlocked.set(owner, { envelope: e, key, entries, until: this.now() + seconds * 1000 });
|
|
187
|
+
key = undefined;
|
|
188
|
+
this.failures.delete(owner);
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
const count = (this.failures.get(owner)?.count ?? 0) + 1;
|
|
192
|
+
this.failures.set(owner, { count, next: this.now() + Math.min(60000, 1000 * 2 ** Math.min(count - 1, 6)) });
|
|
193
|
+
throw new HttpError(401, '主密码错误或备份已损坏', 'vault_unlock_failed');
|
|
194
|
+
}
|
|
195
|
+
finally {
|
|
196
|
+
wipe(kek);
|
|
197
|
+
wipe(key);
|
|
198
|
+
}
|
|
199
|
+
return this.state(owner);
|
|
200
|
+
}
|
|
201
|
+
lock(owner) {
|
|
202
|
+
const session = this.unlocked.get(owner);
|
|
203
|
+
this.unlocked.delete(owner);
|
|
204
|
+
wipe(session?.key);
|
|
205
|
+
if (session) {
|
|
206
|
+
session.entries.length = 0;
|
|
207
|
+
this.onLock(owner);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
lockAll() { for (const owner of [...this.unlocked.keys()])
|
|
211
|
+
this.lock(owner); }
|
|
212
|
+
list(owner) { return this.active(owner).entries.map(summary); }
|
|
213
|
+
commit(owner, entries) {
|
|
214
|
+
const s = this.active(owner);
|
|
215
|
+
const next = this.encodeDocument({ ...s.envelope, revision: s.envelope.revision + 1 }, s.key, entries);
|
|
216
|
+
try {
|
|
217
|
+
this.save(next);
|
|
218
|
+
s.envelope = next;
|
|
219
|
+
s.entries = entries;
|
|
220
|
+
}
|
|
221
|
+
catch (error) {
|
|
222
|
+
this.lock(owner);
|
|
223
|
+
throw error;
|
|
224
|
+
} // A rename may have happened before a failed directory fsync.
|
|
225
|
+
}
|
|
226
|
+
add(owner, value) {
|
|
227
|
+
const s = this.active(owner), input = parse(entryInput, value);
|
|
228
|
+
if (s.entries.length >= 256)
|
|
229
|
+
throw new HttpError(413, '凭据数量已达到上限', 'vault_entry_limit');
|
|
230
|
+
const entry = { ...input, id: randomUUID(), revision: 1, updatedAt: this.now() };
|
|
231
|
+
this.commit(owner, [...s.entries, entry]);
|
|
232
|
+
return summary(entry);
|
|
233
|
+
}
|
|
234
|
+
update(owner, id, value) {
|
|
235
|
+
const s = this.active(owner), input = parse(updateInput, value), old = s.entries.find(v => v.id === id);
|
|
236
|
+
if (!old)
|
|
237
|
+
throw new HttpError(404, '凭据不存在', 'vault_entry_missing');
|
|
238
|
+
if (old.revision !== input.revision)
|
|
239
|
+
throw new HttpError(409, '凭据已变化,请刷新', 'vault_revision_conflict');
|
|
240
|
+
const changedUsage = input.usage?.kind === 'sftp.write' ? { ...input.usage, contents: input.usage.contents ?? (old.usage?.kind === 'sftp.write' ? old.usage.contents : undefined) } : input.usage ?? old.usage;
|
|
241
|
+
const next = parse(storedEntry, { ...old, ...input, usage: changedUsage, secret: input.secret ?? old.secret, revision: old.revision + 1, updatedAt: this.now() });
|
|
242
|
+
this.commit(owner, s.entries.map(v => v.id === id ? next : v));
|
|
243
|
+
this.onLock(owner);
|
|
244
|
+
return summary(next);
|
|
245
|
+
}
|
|
246
|
+
remove(owner, id) {
|
|
247
|
+
const s = this.active(owner);
|
|
248
|
+
if (!s.entries.some(v => v.id === id))
|
|
249
|
+
throw new HttpError(404, '凭据不存在', 'vault_entry_missing');
|
|
250
|
+
this.commit(owner, s.entries.filter(v => v.id !== id));
|
|
251
|
+
this.onLock(owner);
|
|
252
|
+
}
|
|
253
|
+
/** Only the isolated executor callback may receive this. No read-secret RPC exists. */
|
|
254
|
+
withSecret(owner, id, use) {
|
|
255
|
+
const s = this.active(owner), entry = s.entries.find(v => v.id === id);
|
|
256
|
+
if (!entry)
|
|
257
|
+
throw new HttpError(404, '凭据不存在', 'vault_entry_missing');
|
|
258
|
+
return use(entry);
|
|
259
|
+
}
|
|
260
|
+
backup(owner) {
|
|
261
|
+
this.active(owner);
|
|
262
|
+
return JSON.stringify(this.load(owner));
|
|
263
|
+
}
|
|
264
|
+
restore(owner, archive, password) {
|
|
265
|
+
if (this.load(owner))
|
|
266
|
+
throw new HttpError(409, '恢复需要尚未初始化的密码库,不能覆盖现有数据', 'vault_exists');
|
|
267
|
+
if (Buffer.byteLength(archive) > MAX_BYTES)
|
|
268
|
+
throw new HttpError(413, '备份过大', 'vault_size_limit');
|
|
269
|
+
const e = parse(envelopeSchema, JSON.parse(archive));
|
|
270
|
+
if (e.owner !== owner)
|
|
271
|
+
throw new HttpError(403, '备份不属于当前账号', 'vault_backup_owner');
|
|
272
|
+
let kek, key;
|
|
273
|
+
try {
|
|
274
|
+
kek = derive(password, e);
|
|
275
|
+
key = decrypt(e.wrapping, kek, aad(e, 'key'));
|
|
276
|
+
this.decodeDocument(e, key);
|
|
277
|
+
this.save(e);
|
|
278
|
+
}
|
|
279
|
+
catch {
|
|
280
|
+
throw new HttpError(400, '备份无法验证,原密码库未改变', 'vault_backup_invalid');
|
|
281
|
+
}
|
|
282
|
+
finally {
|
|
283
|
+
wipe(kek);
|
|
284
|
+
wipe(key);
|
|
285
|
+
}
|
|
286
|
+
return this.state(owner);
|
|
287
|
+
}
|
|
288
|
+
rotate(owner, password) {
|
|
289
|
+
const s = this.active(owner), key = sodium.randombytes_buf(32);
|
|
290
|
+
const next = { ...s.envelope, revision: s.envelope.revision + 1,
|
|
291
|
+
kdf: { ...s.envelope.kdf, salt: encode(sodium.randombytes_buf(16)) } };
|
|
292
|
+
let kek;
|
|
293
|
+
try {
|
|
294
|
+
kek = derive(password, next);
|
|
295
|
+
next.wrapping = encrypt(key, kek, aad(next, 'key'));
|
|
296
|
+
this.save(this.encodeDocument(next, key, s.entries));
|
|
297
|
+
this.lock(owner);
|
|
298
|
+
}
|
|
299
|
+
catch (error) {
|
|
300
|
+
this.lock(owner);
|
|
301
|
+
throw error;
|
|
302
|
+
}
|
|
303
|
+
finally {
|
|
304
|
+
wipe(kek);
|
|
305
|
+
wipe(key);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
}
|