@lsamien/yaoyao 0.4.77 → 0.4.79

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.
Files changed (120) hide show
  1. package/README.md +7 -5
  2. package/THIRD_PARTY_NOTICES.md +8 -0
  3. package/bin/hermes-yaoyao.mjs +15 -2
  4. package/build-info.json +23 -3
  5. package/desktop/main.mjs +6 -2
  6. package/dist/assets/{AboutDialog-k7oUOua0.js → AboutDialog-CrajAC--.js} +2 -2
  7. package/dist/assets/AboutDialog-CrajAC--.js.map +1 -0
  8. package/dist/assets/BotAutomationsView-DTOoFSEl.js +2 -0
  9. package/dist/assets/{BotAutomationsView-CUaMkVfT.js.map → BotAutomationsView-DTOoFSEl.js.map} +1 -1
  10. package/dist/assets/{BotPluginsDialog-BqfqrWdq.js → BotPluginsDialog-Ckiwmito.js} +2 -2
  11. package/dist/assets/{BotPluginsDialog-BqfqrWdq.js.map → BotPluginsDialog-Ckiwmito.js.map} +1 -1
  12. package/dist/assets/{BotSettingsDialog-BfW0Jxhg.js → BotSettingsDialog-ChffrjSM.js} +5 -5
  13. package/dist/assets/{BotSettingsDialog-BfW0Jxhg.js.map → BotSettingsDialog-ChffrjSM.js.map} +1 -1
  14. package/dist/assets/ChatView-C_7_7olu.css +1 -0
  15. package/dist/assets/ChatView-znZF8RZE.js +2 -0
  16. package/dist/assets/ChatView-znZF8RZE.js.map +1 -0
  17. package/dist/assets/{ComputerPanel-D_wWUzlj.js → ComputerPanel-bNkvZAiT.js} +2 -2
  18. package/dist/assets/{ComputerPanel-D_wWUzlj.js.map → ComputerPanel-bNkvZAiT.js.map} +1 -1
  19. package/dist/assets/{ComputerViewerView-C2nS7MWX.js → ComputerViewerView-DCTvbHr-.js} +2 -2
  20. package/dist/assets/{ComputerViewerView-C2nS7MWX.js.map → ComputerViewerView-DCTvbHr-.js.map} +1 -1
  21. package/dist/assets/ConversationsView-BnysxvX_.js +6 -0
  22. package/dist/assets/ConversationsView-BnysxvX_.js.map +1 -0
  23. package/dist/assets/{ConversationsView-C_VZl5g2.css → ConversationsView-CbArO1v2.css} +1 -1
  24. package/dist/assets/FilesView-D7tA6Nu1.js +2 -0
  25. package/dist/assets/{FilesView-xOEZGSrD.js.map → FilesView-D7tA6Nu1.js.map} +1 -1
  26. package/dist/assets/FloatingResourceSearch-3GOuDkuO.css +1 -0
  27. package/dist/assets/FloatingResourceSearch-c6l1JuAA.js +9 -0
  28. package/dist/assets/FloatingResourceSearch-c6l1JuAA.js.map +1 -0
  29. package/dist/assets/HistoryView-Cnsriop4.js +2 -0
  30. package/dist/assets/HistoryView-Cnsriop4.js.map +1 -0
  31. package/dist/assets/HistoryView-DlVfSP_p.css +1 -0
  32. package/dist/assets/KanbanView-CXm05b62.js +2 -0
  33. package/dist/assets/{KanbanView-DXJCj1E6.js.map → KanbanView-CXm05b62.js.map} +1 -1
  34. package/dist/assets/{LocalVmSettingsPanel-8wF6wA3P.js → LocalVmSettingsPanel-HgNC1SCF.js} +2 -2
  35. package/dist/assets/{LocalVmSettingsPanel-8wF6wA3P.js.map → LocalVmSettingsPanel-HgNC1SCF.js.map} +1 -1
  36. package/dist/assets/{RunnerSettingsPanel-DDEMgUS9.js → RunnerSettingsPanel-CLKZvWua.js} +2 -2
  37. package/dist/assets/{RunnerSettingsPanel-DDEMgUS9.js.map → RunnerSettingsPanel-CLKZvWua.js.map} +1 -1
  38. package/dist/assets/{StandaloneDialog-BN6RJ3uh.js → StandaloneDialog-DODllzh1.js} +2 -2
  39. package/dist/assets/{StandaloneDialog-BN6RJ3uh.js.map → StandaloneDialog-DODllzh1.js.map} +1 -1
  40. package/dist/assets/{UpdateCheckDialog-CZ6NZSkP.js → UpdateCheckDialog-DHcAuryL.js} +2 -2
  41. package/dist/assets/{UpdateCheckDialog-CZ6NZSkP.js.map → UpdateCheckDialog-DHcAuryL.js.map} +1 -1
  42. package/dist/assets/{WorkspaceKnowledgePanel-BA7yVvWK.js → WorkspaceKnowledgePanel-BrE8xSi2.js} +2 -2
  43. package/dist/assets/{WorkspaceKnowledgePanel-BA7yVvWK.js.map → WorkspaceKnowledgePanel-BrE8xSi2.js.map} +1 -1
  44. package/dist/assets/{WorkspaceRoutinesPanel-DgCqaACO.js → WorkspaceRoutinesPanel-CpDVEwHx.js} +2 -2
  45. package/dist/assets/{WorkspaceRoutinesPanel-DgCqaACO.js.map → WorkspaceRoutinesPanel-CpDVEwHx.js.map} +1 -1
  46. package/dist/assets/WorkspaceShell-Dhm3r61t.js +44 -0
  47. package/dist/assets/WorkspaceShell-Dhm3r61t.js.map +1 -0
  48. package/dist/assets/WorkspaceShell-Dk003lIq.css +1 -0
  49. package/dist/assets/{WorkspaceView-jMPyO8oT.js → WorkspaceView-CBWFRLki.js} +2 -2
  50. package/dist/assets/{WorkspaceView-jMPyO8oT.js.map → WorkspaceView-CBWFRLki.js.map} +1 -1
  51. package/dist/assets/{docx-preview-Ba7Ciq-i.js → docx-preview-CG4CK2Qm.js} +2 -2
  52. package/dist/assets/{docx-preview-Ba7Ciq-i.js.map → docx-preview-CG4CK2Qm.js.map} +1 -1
  53. package/dist/assets/index-BRP9NWum.js +17 -0
  54. package/dist/assets/index-BRP9NWum.js.map +1 -0
  55. package/dist/assets/{pdf-C3k8l1DI.js → pdf-CFWXmhVF.js} +2 -2
  56. package/dist/assets/{pdf-C3k8l1DI.js.map → pdf-CFWXmhVF.js.map} +1 -1
  57. package/dist/assets/sessionOwnership-B2YxdBdf.js +4 -0
  58. package/dist/assets/sessionOwnership-B2YxdBdf.js.map +1 -0
  59. package/dist/assets/{sessionOwnership-BTz0Fyp5.css → sessionOwnership-CfO8CfmZ.css} +1 -1
  60. package/dist/assets/{viewModels-OLQqqyt3.js → viewModels-CYJ8m5Uf.js} +12 -12
  61. package/dist/assets/{viewModels-OLQqqyt3.js.map → viewModels-CYJ8m5Uf.js.map} +1 -1
  62. package/dist/index.html +1 -1
  63. package/dist-server/runner/agent.js +2 -2
  64. package/dist-server/server/app.js +15 -1
  65. package/dist-server/server/chatTranscriptStore.js +16 -0
  66. package/dist-server/server/config.js +3 -0
  67. package/dist-server/server/credentialVault/broker.js +272 -0
  68. package/dist-server/server/credentialVault/coordinator.js +297 -0
  69. package/dist-server/server/credentialVault/executor.js +1 -0
  70. package/dist-server/server/credentialVault/fixtureWebsiteExecutor.js +51 -0
  71. package/dist-server/server/credentialVault/index.js +49 -0
  72. package/dist-server/server/credentialVault/isolation.js +37 -0
  73. package/dist-server/server/credentialVault/privateFiles.js +17 -0
  74. package/dist-server/server/credentialVault/protectedExecutor.js +21 -0
  75. package/dist-server/server/credentialVault/schema.js +45 -0
  76. package/dist-server/server/credentialVault/sshExecutor.js +135 -0
  77. package/dist-server/server/credentialVault/store.js +308 -0
  78. package/dist-server/server/credentialVault/transport.js +127 -0
  79. package/dist-server/server/credentialVault/websiteExecutor.js +102 -0
  80. package/dist-server/server/localAuth.js +5 -0
  81. package/dist-server/server/openVikingSessionSync.js +148 -37
  82. package/dist-server/server/pushCoordinator.js +7 -4
  83. package/dist-server/server/routes.js +18 -0
  84. package/dist-server/server/runnerHub.js +14 -1
  85. package/dist-server/server/subaccountAccess.js +12 -0
  86. package/dist-server/server/unreadCenter.js +61 -0
  87. package/dist-server/server/uploads.js +4 -1
  88. package/dist-server/server/workspaceAssets.js +2 -1
  89. package/dist-server/server/workspaceRoutes.js +1 -1
  90. package/dist-server/server/workspaceRuntime.js +18 -2
  91. package/dist-server/server/workspaceStore.js +104 -43
  92. package/dist-server/shared/credentialVault.js +2 -0
  93. package/dist-server/shared/unread.js +6 -0
  94. package/dist-server/shared/uploadNames.js +14 -0
  95. package/licenses/libsodium.js/LICENSE +16 -0
  96. package/licenses/ssh2/LICENSE +19 -0
  97. package/package.json +4 -2
  98. package/release.json +3 -3
  99. package/dist/assets/AboutDialog-k7oUOua0.js.map +0 -1
  100. package/dist/assets/BotAutomationsView-CUaMkVfT.js +0 -2
  101. package/dist/assets/ChatView-CTWvNlNq.js +0 -2
  102. package/dist/assets/ChatView-CTWvNlNq.js.map +0 -1
  103. package/dist/assets/ChatView-Dx8YlcPr.css +0 -1
  104. package/dist/assets/ConversationsView-D5KvMs7J.js +0 -6
  105. package/dist/assets/ConversationsView-D5KvMs7J.js.map +0 -1
  106. package/dist/assets/FilesView-xOEZGSrD.js +0 -2
  107. package/dist/assets/FloatingResourceSearch-BF2XOLd-.css +0 -1
  108. package/dist/assets/FloatingResourceSearch-D5XwWF0V.js +0 -9
  109. package/dist/assets/FloatingResourceSearch-D5XwWF0V.js.map +0 -1
  110. package/dist/assets/HistoryView-CnUN9Qik.js +0 -2
  111. package/dist/assets/HistoryView-CnUN9Qik.js.map +0 -1
  112. package/dist/assets/HistoryView-DvuCAjlo.css +0 -1
  113. package/dist/assets/KanbanView-DXJCj1E6.js +0 -2
  114. package/dist/assets/WorkspaceShell-7wn8iTne.css +0 -1
  115. package/dist/assets/WorkspaceShell-DQZKvx2p.js +0 -44
  116. package/dist/assets/WorkspaceShell-DQZKvx2p.js.map +0 -1
  117. package/dist/assets/index-dvKMU4Xy.js +0 -17
  118. package/dist/assets/index-dvKMU4Xy.js.map +0 -1
  119. package/dist/assets/sessionOwnership-HZsbONG-.js +0 -6
  120. package/dist/assets/sessionOwnership-HZsbONG-.js.map +0 -1
@@ -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
+ }
@@ -0,0 +1,127 @@
1
+ import { createServer, request } from 'node:http';
2
+ import { createHash, timingSafeEqual, randomUUID } from 'node:crypto';
3
+ import { lstatSync } from 'node:fs';
4
+ import { isAbsolute } from 'node:path';
5
+ import { z } from 'zod';
6
+ import { parse } from './schema.js';
7
+ import { HttpError } from '../errors.js';
8
+ import { readPrivateUtf8 } from './privateFiles.js';
9
+ const MAX_BYTES = 3 * 1024 * 1024;
10
+ export function serveCredentialVault(broker, token) {
11
+ if (token.length < 32)
12
+ throw new Error('密码库控制凭据格式无效');
13
+ const expected = createHash('sha256').update(token).digest();
14
+ const server = createServer((req, res) => {
15
+ void (async () => {
16
+ res.setHeader('Cache-Control', 'no-store');
17
+ if (req.method !== 'POST' || req.url !== '/v1' || req.headers.origin)
18
+ throw new HttpError(403, '密码库只接受私有控制请求', 'vault_control_forbidden');
19
+ const received = createHash('sha256').update(String(req.headers.authorization ?? '').replace(/^Bearer /, '')).digest();
20
+ if (!req.headers.authorization?.startsWith('Bearer ') || !timingSafeEqual(expected, received))
21
+ throw new HttpError(403, '密码库控制授权无效', 'vault_control_forbidden');
22
+ const chunks = [];
23
+ let size = 0;
24
+ for await (const chunk of req) {
25
+ size += chunk.length;
26
+ if (size > MAX_BYTES)
27
+ throw new HttpError(413, '密码库请求过大', 'vault_size_limit');
28
+ chunks.push(Buffer.from(chunk));
29
+ }
30
+ const body = parse(z.object({ epoch: z.string().uuid(), owner: z.string().min(1).max(256), session: z.string().regex(/^[a-f0-9]{64}$/),
31
+ command: z.string().max(64), value: z.unknown().optional() }).strict(), JSON.parse(Buffer.concat(chunks).toString('utf8')));
32
+ const result = body.command === 'hello' ? broker.hello(body.epoch) : body.command === 'execute'
33
+ ? await (() => { const v = parse(z.object({ id: z.string().uuid(), input: z.unknown() }).strict(), body.value); res.once('close', () => { if (!res.writableEnded)
34
+ broker.connectionClosed(body.owner, body.session, v.id); }); return broker.execute(body.epoch, body.owner, body.session, v.id, v.input); })()
35
+ : broker.dispatch(body.epoch, body.owner, body.session, body.command, body.value);
36
+ res.setHeader('Content-Type', 'application/json');
37
+ res.end(JSON.stringify({ result }));
38
+ })().catch(error => {
39
+ // Never forward parser, sodium, filesystem or executor exception messages.
40
+ res.statusCode = error instanceof HttpError ? error.status : 400;
41
+ res.setHeader('Content-Type', 'application/json');
42
+ res.end(JSON.stringify({ error: error instanceof HttpError ? error.message : '密码库请求失败', code: error instanceof HttpError ? error.code : 'vault_request_failed' }));
43
+ });
44
+ });
45
+ server.requestTimeout = 15000;
46
+ server.headersTimeout = 10000;
47
+ server.keepAliveTimeout = 1000;
48
+ server.on('close', () => broker.close());
49
+ server.on('clientError', (_e, socket) => socket.destroy());
50
+ return server;
51
+ }
52
+ /** Private IPC; no global fetch proxy, environment/argv secret or general Runner payload. */
53
+ export class CredentialVaultClient {
54
+ config;
55
+ epoch = randomUUID();
56
+ hello;
57
+ onDisconnect = () => { };
58
+ constructor(config) {
59
+ this.config = config;
60
+ }
61
+ get configured() { return !!this.config; }
62
+ async send(owner, session, command, value) {
63
+ const c = this.config;
64
+ if (!c)
65
+ throw new HttpError(503, '执行节点密码库尚未连接', 'vault_offline');
66
+ if (!process.getuid || process.getuid() === 0 || !Number.isSafeInteger(c.hermesUid) || c.hermesUid < 1 || process.getuid() === c.hermesUid)
67
+ throw new HttpError(503, '密码库控制面需要与 Hermes 分离的非 root OS 身份', 'vault_offline');
68
+ if (!isAbsolute(c.socket) || !isAbsolute(c.tokenFile))
69
+ throw new HttpError(503, '密码库控制配置无效', 'vault_offline');
70
+ let token;
71
+ try {
72
+ const socket = lstatSync(c.socket);
73
+ if (!socket.isSocket() || (socket.mode & 0o077) || socket.uid !== process.getuid?.())
74
+ throw new Error();
75
+ token = readPrivateUtf8(c.tokenFile, 4096).trim();
76
+ if (token.length < 32)
77
+ throw new Error();
78
+ }
79
+ catch {
80
+ throw new HttpError(503, '密码库私有连接不可用,请检查部署', 'vault_offline');
81
+ }
82
+ return new Promise((done, reject) => {
83
+ const req = request({ socketPath: c.socket, path: '/v1', method: 'POST', headers: { Authorization: 'Bearer ' + token, 'Content-Type': 'application/json' } }, res => {
84
+ const chunks = [];
85
+ let size = 0;
86
+ res.on('data', chunk => { size += chunk.length; if (size > MAX_BYTES)
87
+ req.destroy();
88
+ else
89
+ chunks.push(Buffer.from(chunk)); });
90
+ res.on('error', () => reject(new HttpError(503, '密码库连接中断', 'vault_offline')));
91
+ res.on('aborted', () => reject(new HttpError(503, '密码库连接中断', 'vault_offline')));
92
+ res.on('end', () => {
93
+ try {
94
+ const body = JSON.parse(Buffer.concat(chunks).toString());
95
+ if (res.statusCode !== 200)
96
+ reject(new HttpError(res.statusCode ?? 503, '密码库操作未完成,请检查解锁和任务授权', typeof body.code === 'string' && /^vault_[a-z_]+$/.test(body.code) ? body.code : 'vault_request_failed'));
97
+ else
98
+ done(body.result);
99
+ }
100
+ catch {
101
+ reject(new HttpError(503, '密码库响应无效', 'vault_offline'));
102
+ }
103
+ });
104
+ });
105
+ req.setTimeout(command === 'execute' ? 40000 : 15000, () => req.destroy());
106
+ req.on('error', () => reject(new HttpError(503, '密码库连接中断', 'vault_offline')));
107
+ req.end(JSON.stringify({ epoch: this.epoch, owner, session, command, value }));
108
+ });
109
+ }
110
+ async call(owner, session, command, value) {
111
+ try {
112
+ this.hello ??= this.send(owner, session, 'hello');
113
+ await this.hello;
114
+ return await this.send(owner, session, command, value);
115
+ }
116
+ catch (e) {
117
+ if (e instanceof HttpError && (e.code === 'vault_offline' || e.code === 'vault_control_changed')) {
118
+ this.hello = undefined;
119
+ this.epoch = randomUUID();
120
+ this.onDisconnect();
121
+ if (command === 'execute')
122
+ throw new HttpError(409, '执行连接中断,结果不确定,禁止自动重试', 'vault_operation_uncertain');
123
+ }
124
+ throw e;
125
+ }
126
+ }
127
+ }