@lsamien/yaoyao 0.4.77 → 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.
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 +20 -3
  5. package/desktop/main.mjs +6 -2
  6. package/dist/assets/{AboutDialog-k7oUOua0.js → AboutDialog-jvhTP8-J.js} +2 -2
  7. package/dist/assets/AboutDialog-jvhTP8-J.js.map +1 -0
  8. package/dist/assets/BotAutomationsView-ktoci79V.js +2 -0
  9. package/dist/assets/{BotAutomationsView-CUaMkVfT.js.map → BotAutomationsView-ktoci79V.js.map} +1 -1
  10. package/dist/assets/{BotPluginsDialog-BqfqrWdq.js → BotPluginsDialog-H85RI-7P.js} +2 -2
  11. package/dist/assets/{BotPluginsDialog-BqfqrWdq.js.map → BotPluginsDialog-H85RI-7P.js.map} +1 -1
  12. package/dist/assets/{BotSettingsDialog-BfW0Jxhg.js → BotSettingsDialog-Ci_DZL4m.js} +5 -5
  13. package/dist/assets/{BotSettingsDialog-BfW0Jxhg.js.map → BotSettingsDialog-Ci_DZL4m.js.map} +1 -1
  14. package/dist/assets/ChatView-6cdLMsuy.js +2 -0
  15. package/dist/assets/ChatView-6cdLMsuy.js.map +1 -0
  16. package/dist/assets/ChatView-C_7_7olu.css +1 -0
  17. package/dist/assets/{ComputerPanel-D_wWUzlj.js → ComputerPanel-Dbwgx5n8.js} +2 -2
  18. package/dist/assets/{ComputerPanel-D_wWUzlj.js.map → ComputerPanel-Dbwgx5n8.js.map} +1 -1
  19. package/dist/assets/{ComputerViewerView-C2nS7MWX.js → ComputerViewerView-csnhRedK.js} +2 -2
  20. package/dist/assets/{ComputerViewerView-C2nS7MWX.js.map → ComputerViewerView-csnhRedK.js.map} +1 -1
  21. package/dist/assets/ConversationsView-CEO2SVGT.js +6 -0
  22. package/dist/assets/ConversationsView-CEO2SVGT.js.map +1 -0
  23. package/dist/assets/{ConversationsView-C_VZl5g2.css → ConversationsView-CHLGKsJt.css} +1 -1
  24. package/dist/assets/FilesView-t5jA-H2-.js +2 -0
  25. package/dist/assets/{FilesView-xOEZGSrD.js.map → FilesView-t5jA-H2-.js.map} +1 -1
  26. package/dist/assets/FloatingResourceSearch-3GOuDkuO.css +1 -0
  27. package/dist/assets/FloatingResourceSearch-BAYymuJV.js +9 -0
  28. package/dist/assets/FloatingResourceSearch-BAYymuJV.js.map +1 -0
  29. package/dist/assets/HistoryView-BqMSV9iC.js +2 -0
  30. package/dist/assets/HistoryView-BqMSV9iC.js.map +1 -0
  31. package/dist/assets/HistoryView-DlVfSP_p.css +1 -0
  32. package/dist/assets/KanbanView-CWwrwH9S.js +2 -0
  33. package/dist/assets/{KanbanView-DXJCj1E6.js.map → KanbanView-CWwrwH9S.js.map} +1 -1
  34. package/dist/assets/{LocalVmSettingsPanel-8wF6wA3P.js → LocalVmSettingsPanel-BXvZwFQP.js} +2 -2
  35. package/dist/assets/{LocalVmSettingsPanel-8wF6wA3P.js.map → LocalVmSettingsPanel-BXvZwFQP.js.map} +1 -1
  36. package/dist/assets/{RunnerSettingsPanel-DDEMgUS9.js → RunnerSettingsPanel-KkpIkkob.js} +2 -2
  37. package/dist/assets/{RunnerSettingsPanel-DDEMgUS9.js.map → RunnerSettingsPanel-KkpIkkob.js.map} +1 -1
  38. package/dist/assets/{StandaloneDialog-BN6RJ3uh.js → StandaloneDialog-D4BQqjpB.js} +2 -2
  39. package/dist/assets/{StandaloneDialog-BN6RJ3uh.js.map → StandaloneDialog-D4BQqjpB.js.map} +1 -1
  40. package/dist/assets/{UpdateCheckDialog-CZ6NZSkP.js → UpdateCheckDialog-Ct0bT6xU.js} +2 -2
  41. package/dist/assets/{UpdateCheckDialog-CZ6NZSkP.js.map → UpdateCheckDialog-Ct0bT6xU.js.map} +1 -1
  42. package/dist/assets/{WorkspaceKnowledgePanel-BA7yVvWK.js → WorkspaceKnowledgePanel-WBcPB49x.js} +2 -2
  43. package/dist/assets/{WorkspaceKnowledgePanel-BA7yVvWK.js.map → WorkspaceKnowledgePanel-WBcPB49x.js.map} +1 -1
  44. package/dist/assets/{WorkspaceRoutinesPanel-DgCqaACO.js → WorkspaceRoutinesPanel-JubUwGsV.js} +2 -2
  45. package/dist/assets/{WorkspaceRoutinesPanel-DgCqaACO.js.map → WorkspaceRoutinesPanel-JubUwGsV.js.map} +1 -1
  46. package/dist/assets/WorkspaceShell-0m4gg6AW.css +1 -0
  47. package/dist/assets/WorkspaceShell-Do2VAwIz.js +44 -0
  48. package/dist/assets/WorkspaceShell-Do2VAwIz.js.map +1 -0
  49. package/dist/assets/{WorkspaceView-jMPyO8oT.js → WorkspaceView-DTanioWW.js} +2 -2
  50. package/dist/assets/{WorkspaceView-jMPyO8oT.js.map → WorkspaceView-DTanioWW.js.map} +1 -1
  51. package/dist/assets/{docx-preview-Ba7Ciq-i.js → docx-preview-B1SjJgD_.js} +2 -2
  52. package/dist/assets/{docx-preview-Ba7Ciq-i.js.map → docx-preview-B1SjJgD_.js.map} +1 -1
  53. package/dist/assets/index-CWamgtSb.js +17 -0
  54. package/dist/assets/index-CWamgtSb.js.map +1 -0
  55. package/dist/assets/{pdf-C3k8l1DI.js → pdf-DVDddcFC.js} +2 -2
  56. package/dist/assets/{pdf-C3k8l1DI.js.map → pdf-DVDddcFC.js.map} +1 -1
  57. package/dist/assets/sessionOwnership-0hdKcwOs.js +4 -0
  58. package/dist/assets/sessionOwnership-0hdKcwOs.js.map +1 -0
  59. package/dist/assets/{sessionOwnership-BTz0Fyp5.css → sessionOwnership-CfO8CfmZ.css} +1 -1
  60. package/dist/assets/{viewModels-OLQqqyt3.js → viewModels-DKBqaDRg.js} +12 -12
  61. package/dist/assets/{viewModels-OLQqqyt3.js.map → viewModels-DKBqaDRg.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
package/dist/index.html CHANGED
@@ -9,7 +9,7 @@
9
9
  <link rel="apple-touch-icon" sizes="180x180" href="/icons/apple-touch-icon.png" />
10
10
  <link rel="manifest" href="/manifest.webmanifest" />
11
11
  <title>夭夭</title>
12
- <script type="module" crossorigin src="/assets/index-dvKMU4Xy.js"></script>
12
+ <script type="module" crossorigin src="/assets/index-CWamgtSb.js"></script>
13
13
  <link rel="modulepreload" crossorigin href="/assets/_plugin-vue_export-helper-CscYwSBt.js">
14
14
  <link rel="stylesheet" crossorigin href="/assets/index-g5POnMkp.css">
15
15
  </head>
@@ -76,8 +76,8 @@ export class RunnerAgent {
76
76
  url.hostname = '127.0.0.1';
77
77
  const toolId = body && typeof body === 'object' && 'toolId' in body ? body.toolId : undefined;
78
78
  const response = await (isLocalAuthorizationTarget(url) && this.fetchImpl === fetch ? this.controlTransport.fetch.bind(this.controlTransport) : this.fetchImpl)(url, {
79
- method: body === undefined ? 'GET' : 'POST', redirect: 'error', signal: AbortSignal.any([this.controlAbort.signal, AbortSignal.timeout(path === 'desktop' ? 75000 : path === 'tool' && typeof toolId === 'string' && toolId.startsWith('managed_browser_') ? 600000 : 25000)]),
80
- headers: { Authorization: `Bearer ${this.config.token}`, 'x-runner-instance': this.instance, 'x-runner-protocol': '1', 'x-runner-features': (this.computers ? 'execution-context-v1,vm-egress-v1,workspace-memory-bind-v1,hermes-computer-v2,profile-computer-v1,host-computer-tools-v1,file-transfer-v1,idle-stop-policy-v1,computer-worker-v1,artifact-chunks-v1,computer-control-v1,shared-computer-v1,local-vm-v1' + (this.computers.provider.fixedCapacity ? ',compose-desktops-v1' : ',helper-retirement-v1,image-options-v1') + (this.computers.config.imageId !== UNCONFIGURED_COMPUTER_IMAGE ? ',image-ready-v1' : '') : 'execution-context-v1,workspace-memory-bind-v1') + (this.browsers ? ',managed-browser-setup-v1,managed-browser-retention-v1' : ',managed-browser-disabled-v1') + (this.browsers?.available ? ',managed-browser-v1' : ''), ...(this.serverEpoch ? { 'x-runner-epoch': this.serverEpoch } : {}), 'Content-Type': 'application/json', ...(path === 'poll' && !this.connected ? { 'x-runner-reset': '1' } : {}) },
79
+ method: body === undefined ? 'GET' : 'POST', redirect: 'error', signal: AbortSignal.any([this.controlAbort.signal, AbortSignal.timeout(path === 'desktop' ? 75000 : path === 'tool' && typeof toolId === 'string' && (toolId.startsWith('managed_browser_') || toolId.startsWith('credential_')) ? 600000 : 25000)]),
80
+ headers: { Authorization: `Bearer ${this.config.token}`, 'x-runner-instance': this.instance, 'x-runner-protocol': '1', 'x-runner-features': (this.computers ? 'execution-context-v1,vm-egress-v1,workspace-memory-bind-v1,hermes-computer-v2,profile-computer-v1,host-computer-tools-v1,file-transfer-v1,idle-stop-policy-v1,computer-worker-v1,artifact-chunks-v1,computer-control-v1,shared-computer-v1,local-vm-v1' + (this.computers.provider.fixedCapacity ? ',compose-desktops-v1' : ',helper-retirement-v1,image-options-v1') + (this.computers.config.imageId !== UNCONFIGURED_COMPUTER_IMAGE ? ',image-ready-v1' : '') : 'execution-context-v1,workspace-memory-bind-v1') + (this.browsers ? ',managed-browser-setup-v1,managed-browser-retention-v1' : ',managed-browser-disabled-v1') + (this.browsers?.available ? ',managed-browser-v1' : '') + ',credential-ref-v1', ...(this.serverEpoch ? { 'x-runner-epoch': this.serverEpoch } : {}), 'Content-Type': 'application/json', ...(path === 'poll' && !this.connected ? { 'x-runner-reset': '1' } : {}) },
81
81
  ...(body === undefined ? {} : { body: JSON.stringify(body) }),
82
82
  });
83
83
  if (!response.ok) {
@@ -1,4 +1,7 @@
1
+ import { unreadSnapshot } from './unreadCenter.js';
1
2
  import { ExecutionSettings } from './executionSettings.js';
3
+ import { CredentialVaultCoordinator } from './credentialVault/coordinator.js';
4
+ import { CredentialVaultClient } from './credentialVault/transport.js';
2
5
  import { ManagedBrowsers } from './managedBrowsers.js';
3
6
  import { isWorkspaceAccountPath } from './subaccountAccess.js';
4
7
  import { chatTranscriptRouter } from './chatTranscriptApi.js';
@@ -155,6 +158,7 @@ export function createApplication(options = {}) {
155
158
  });
156
159
  // The application owns group events. No Dashboard plugin is queried.
157
160
  const workspace = new WorkspaceStore(config.home);
161
+ push.setUnreadCounter(owner => unreadSnapshot(workspace, chatCache.store, owner, (node, profile) => auth.canUseSource(owner, node, profile)).total);
158
162
  const openVikingService = new OpenVikingService(workspace, openVikingConfiguration);
159
163
  const workspaceNodes = new WorkspaceNodes(workspace, config, { url: config.upstream, client: upstream, session: upstreamSession }, pairings.nodeID);
160
164
  workspaceNodes.sourceAllowed = (owner, nodeId, profile) => auth.canUseSource(owner, nodeId, profile);
@@ -168,8 +172,10 @@ export function createApplication(options = {}) {
168
172
  runners.controlAllowed = (id, runnerId) => computerControls.allowed(id, runnerId);
169
173
  workspaceNodes.runnerTarget = (owner, nodeId, computer) => runners.target(owner, nodeId, computer);
170
174
  const executionSettings = new ExecutionSettings(workspace, workspaceNodes, auth);
175
+ const credentialVault = new CredentialVaultCoordinator(new CredentialVaultClient(config.credentialVault), workspace, auth, runners);
171
176
  const workspaceRuntime = new WorkspaceRuntime(workspace, workspaceNodes, uploads, owner => auth.isUserActive(owner), owner => auth.pushAuthorizationVersion(owner) ?? 0, openVikingService);
172
177
  workspaceRuntime.executionSettings = executionSettings;
178
+ workspaceRuntime.credentialVault = credentialVault;
173
179
  runners.executionSettings = executionSettings;
174
180
  executionSettings.onProxyChange = () => runners.configureNetworks();
175
181
  executionSettings.testProxy = () => runners.testNetworks();
@@ -427,7 +433,13 @@ export function createApplication(options = {}) {
427
433
  else
428
434
  await next();
429
435
  });
430
- for (const router of [executionSettings.router(), managedBrowsers.router(), desktopEnvironments.router(), grokCloud.authorization.router(), grokCloud.router(), workspaceInspector.router(), workspaceRoutines.router(), workspacePlugins.router()]) {
436
+ app.use(async (ctx, next) => {
437
+ const user = ctx.state.localUser, cookie = ctx.get('cookie');
438
+ if (['/api/app/logout', '/auth/logout'].includes(ctx.path) && ctx.method === 'POST' && user)
439
+ await credentialVault.logout(user.id, cookie);
440
+ await next();
441
+ });
442
+ for (const router of [credentialVault.router(), executionSettings.router(), managedBrowsers.router(), desktopEnvironments.router(), grokCloud.authorization.router(), grokCloud.router(), workspaceInspector.router(), workspaceRoutines.router(), workspacePlugins.router()]) {
431
443
  app.use(router.routes());
432
444
  app.use(router.allowedMethods());
433
445
  }
@@ -511,6 +523,7 @@ export function createApplication(options = {}) {
511
523
  await next();
512
524
  });
513
525
  return {
526
+ credentialVault,
514
527
  runners,
515
528
  hermesBridge,
516
529
  localVm,
@@ -545,6 +558,7 @@ export function createApplication(options = {}) {
545
558
  chatCache,
546
559
  startBackground,
547
560
  close: () => {
561
+ credentialVault.close();
548
562
  closed = true;
549
563
  openVikingSessionSync.close();
550
564
  workspaceMemory.close();
@@ -447,6 +447,22 @@ export class ChatTranscriptStore {
447
447
  .prepare('INSERT OR IGNORE INTO chat_transcript_reads VALUES(?,?,?,?)')
448
448
  .run(owner, profile, sessionId, m.id);
449
449
  }
450
+ unreadMessages(...scope) {
451
+ this.unread(...scope);
452
+ return this.db.prepare(`SELECT m.data FROM chat_transcript_messages m LEFT JOIN chat_transcript_reads r USING(owner,profile,session_id,id)
453
+ WHERE m.owner=? AND m.profile=? AND m.session_id=? AND m.deleted=0 AND r.id IS NULL ORDER BY m.seq,m.id`).all(...scope)
454
+ .map(row => JSON.parse(String(row.data))).filter(m => m.final_result === true && isFinalChatResult(m));
455
+ }
456
+ markMessagesRead(owner, profile, sessionId, ids) {
457
+ const selected = new Set(ids);
458
+ const head = this.head(owner, profile, sessionId);
459
+ head.localReadEstablished = true;
460
+ this.db.prepare('UPDATE chat_transcript_heads SET data=? WHERE owner=? AND profile=? AND session_id=?').run(JSON.stringify(head), owner, profile, sessionId);
461
+ for (const m of this.unreadMessages(owner, profile, sessionId))
462
+ if (selected.has(m.id))
463
+ this.db.prepare('INSERT OR IGNORE INTO chat_transcript_reads VALUES(?,?,?,?)').run(owner, profile, sessionId, m.id);
464
+ this.notify();
465
+ }
450
466
  unread(...scope) {
451
467
  // Legacy read cursors can finish importing after the initial local snapshot.
452
468
  // Map only persisted source rows, never consume a live streaming result.
@@ -151,6 +151,9 @@ export function loadServerConfig(env = process.env) {
151
151
  attachmentsRoot,
152
152
  imagesRoot,
153
153
  mediaOwner: basename(homedir()),
154
+ ...(env.HERMES_YAOYAO_VAULT_SOCKET || env.HERMES_YAOYAO_VAULT_TOKEN_FILE ? { credentialVault: {
155
+ socket: env.HERMES_YAOYAO_VAULT_SOCKET || '', tokenFile: env.HERMES_YAOYAO_VAULT_TOKEN_FILE || '', hermesUid: Number(env.HERMES_YAOYAO_VAULT_HERMES_UID),
156
+ } } : {}),
154
157
  tlsCert,
155
158
  tlsKey,
156
159
  allowInsecureLan,
@@ -0,0 +1,272 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { constants, openSync, closeSync, fsyncSync, fstatSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { z } from 'zod';
5
+ import { HttpError } from '../errors.js';
6
+ import { CredentialVaultStore } from './store.js';
7
+ import { parse, leaseInput } from './schema.js';
8
+ export class CredentialVaultBroker {
9
+ store;
10
+ now;
11
+ executor;
12
+ sessions = new Map();
13
+ epochs = new Map();
14
+ leases = new Map();
15
+ controlEpoch = '';
16
+ timer;
17
+ constructor(store, now = Date.now, executor) {
18
+ this.store = store;
19
+ this.now = now;
20
+ this.executor = executor;
21
+ store.onLock = owner => this.revokeOwner(owner);
22
+ this.timer = setInterval(() => {
23
+ try {
24
+ this.executor?.assertAvailable?.();
25
+ }
26
+ catch {
27
+ this.disconnect();
28
+ }
29
+ for (const owner of this.sessions.keys()) {
30
+ try {
31
+ store.state(owner);
32
+ }
33
+ catch {
34
+ store.lock(owner);
35
+ this.sessions.delete(owner);
36
+ this.revokeOwner(owner);
37
+ }
38
+ }
39
+ for (const [id, lease] of this.leases)
40
+ if (lease.expiresAt <= this.now())
41
+ this.revoke(id);
42
+ }, 1000);
43
+ this.timer.unref();
44
+ }
45
+ audit(owner, action, ref, outcome = 'ok') {
46
+ // No request body, username, target, secret, transport error or task output.
47
+ const row = { at: this.now(), owner, action, ...(ref ? { ref } : {}), outcome };
48
+ const path = join(this.store.root, 'audit.jsonl');
49
+ let fd;
50
+ try {
51
+ fd = openSync(path, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW, 0o600);
52
+ const stat = fstatSync(fd);
53
+ if (!stat.isFile() || (stat.mode & 0o077) || stat.uid !== process.getuid?.())
54
+ throw new Error('密码库审计文件权限不安全');
55
+ writeFileSync(fd, JSON.stringify(row) + '\n');
56
+ fsyncSync(fd);
57
+ }
58
+ catch {
59
+ this.store.lock(owner);
60
+ this.sessions.delete(owner);
61
+ this.revokeOwner(owner);
62
+ throw new HttpError(503, '密码库审计不可用,已锁定并撤销授权', 'vault_audit_unavailable');
63
+ }
64
+ finally {
65
+ if (fd !== undefined)
66
+ closeSync(fd);
67
+ }
68
+ }
69
+ hello(epoch) {
70
+ parse(z.string().uuid(), epoch);
71
+ if (epoch !== this.controlEpoch) {
72
+ this.store.lockAll();
73
+ this.revokeAll();
74
+ this.sessions.clear();
75
+ this.controlEpoch = epoch;
76
+ }
77
+ return { protocol: 1, execution: this.execution().execution };
78
+ }
79
+ execution() {
80
+ if (!this.executor)
81
+ return { execution: 'disabled', reason: 'executor_not_enabled' };
82
+ try {
83
+ this.executor.assertAvailable?.();
84
+ return { execution: this.executor.mode ?? 'dummy-fixture', reason: this.executor.mode === 'protected-adapters' ? 'operator_approved' : 'dummy_fixture_only' };
85
+ }
86
+ catch {
87
+ this.disconnect();
88
+ return { execution: 'disabled', reason: 'isolation_required' };
89
+ }
90
+ }
91
+ authorize(owner, session) {
92
+ if (this.sessions.get(owner) !== session || !this.store.state(owner).unlocked)
93
+ throw new HttpError(423, '请在本次登录的密码管理界面手动解锁', 'vault_locked');
94
+ }
95
+ status(owner, session) {
96
+ const execution = this.execution(), state = this.store.state(owner), own = this.sessions.get(owner) === session && state.unlocked;
97
+ return { protocol: 1, online: true, initialized: state.initialized, unlocked: own,
98
+ ...(own ? { unlockExpiresAt: state.unlockExpiresAt } : {}), ...execution,
99
+ entries: own ? this.store.list(owner) : [], leases: own ? [...this.leases.values()].filter(l => l.owner === owner).map(({ id, credentialRef, agentId, workId, runnerId, operation, expiresAt }) => ({ id, credentialRef, agentId, workId, runnerId, operation, expiresAt })) : [] };
100
+ }
101
+ revokeOwner(owner) {
102
+ this.epochs.set(owner, (this.epochs.get(owner) ?? 0) + 1);
103
+ for (const [id, l] of this.leases)
104
+ if (l.owner === owner)
105
+ this.revoke(id);
106
+ }
107
+ revokeAll() { for (const id of [...this.leases.keys()])
108
+ this.revoke(id); }
109
+ revoke(id) { const l = this.leases.get(id); this.leases.delete(id); l?.controller.abort(); }
110
+ disconnect() { this.store.lockAll(); this.revokeAll(); this.sessions.clear(); }
111
+ close() { clearInterval(this.timer); this.disconnect(); }
112
+ dispatch(epoch, owner, session, command, value) {
113
+ parse(z.string().min(1).max(256), owner);
114
+ parse(z.string().regex(/^[a-f0-9]{64}$/), session);
115
+ if (epoch !== this.controlEpoch)
116
+ throw new HttpError(410, '控制连接已更换,旧授权失效', 'vault_control_changed');
117
+ if (command === 'status')
118
+ return this.status(owner, session);
119
+ if (command === 'initialize') {
120
+ const body = parse(z.object({ password: z.string() }).strict(), value);
121
+ this.store.initialize(owner, body.password);
122
+ this.audit(owner, 'initialize');
123
+ return this.status(owner, session);
124
+ }
125
+ if (command === 'restore') {
126
+ const b = parse(z.object({ archive: z.string(), password: z.string() }).strict(), value);
127
+ this.store.restore(owner, b.archive, b.password);
128
+ this.audit(owner, 'restore');
129
+ return this.status(owner, session);
130
+ }
131
+ if (command === 'unlock') {
132
+ const b = parse(z.object({ password: z.string(), seconds: z.number().int().min(30).max(900).default(300) }).strict(), value);
133
+ try {
134
+ this.store.unlock(owner, b.password, b.seconds);
135
+ this.sessions.set(owner, session);
136
+ this.audit(owner, 'unlock');
137
+ }
138
+ catch (e) {
139
+ this.audit(owner, 'unlock', undefined, 'denied');
140
+ throw e;
141
+ }
142
+ return this.status(owner, session);
143
+ }
144
+ if (command === 'logout') {
145
+ if (this.sessions.get(owner) === session) {
146
+ this.store.lock(owner);
147
+ this.sessions.delete(owner);
148
+ this.audit(owner, 'logout');
149
+ }
150
+ ;
151
+ return { ok: true };
152
+ }
153
+ if (command === 'lock') {
154
+ this.store.lock(owner);
155
+ this.sessions.delete(owner);
156
+ this.revokeOwner(owner);
157
+ this.audit(owner, 'lock');
158
+ return { ok: true };
159
+ }
160
+ if (command === 'revoke-work') {
161
+ const b = parse(z.object({ workId: z.string().uuid() }).strict(), value);
162
+ for (const [id, l] of this.leases)
163
+ if (l.owner === owner && l.workId === b.workId)
164
+ this.revoke(id);
165
+ this.audit(owner, 'revoke-work', b.workId);
166
+ return { ok: true };
167
+ }
168
+ this.authorize(owner, session);
169
+ if (command === 'add') {
170
+ const e = this.store.add(owner, value);
171
+ this.audit(owner, 'add', e.id);
172
+ return e;
173
+ }
174
+ if (command === 'update') {
175
+ const b = parse(z.object({ id: z.string().uuid(), entry: z.unknown() }).strict(), value);
176
+ const e = this.store.update(owner, b.id, b.entry);
177
+ this.audit(owner, 'update', e.id);
178
+ return e;
179
+ }
180
+ if (command === 'remove') {
181
+ const b = parse(z.object({ id: z.string().uuid() }).strict(), value);
182
+ this.store.remove(owner, b.id);
183
+ this.audit(owner, 'remove', b.id);
184
+ return { ok: true };
185
+ }
186
+ if (command === 'backup') {
187
+ this.audit(owner, 'backup');
188
+ return { archive: this.store.backup(owner) };
189
+ }
190
+ if (command === 'rotate') {
191
+ const b = parse(z.object({ password: z.string() }).strict(), value);
192
+ this.store.rotate(owner, b.password);
193
+ this.audit(owner, 'rotate');
194
+ return { ok: true };
195
+ }
196
+ if (command === 'grant') {
197
+ const b = parse(leaseInput, value);
198
+ const entry = this.store.list(owner).find(e => e.id === b.credentialRef);
199
+ if (!entry || JSON.stringify(entry.target) !== JSON.stringify(b.target) || (entry.target.kind === 'website') !== (b.operation === 'website.login'))
200
+ throw new HttpError(403, '凭据目标或操作不匹配', 'vault_target_forbidden');
201
+ if (entry.usage && (entry.usage.kind === 'website.form' ? 'website.login' : entry.usage.kind) !== b.operation)
202
+ throw new HttpError(403, '操作不属于用户批准的凭据使用计划', 'vault_usage_forbidden');
203
+ if ([...this.leases.values()].filter(l => l.owner === owner).length >= 64)
204
+ throw new HttpError(429, '任务授权数量已达到上限', 'vault_lease_limit');
205
+ const { seconds: _seconds, target: _target, runnerInstance: _instance, runnerEpoch: _epoch, ...publicInput } = b;
206
+ const result = { ...publicInput, id: randomUUID(), expiresAt: Math.min(this.now() + b.seconds * 1000, this.store.state(owner).unlockExpiresAt) };
207
+ this.leases.set(result.id, { ...result, owner, session, version: entry.revision, target: entry.target, runnerInstance: b.runnerInstance,
208
+ runnerEpoch: b.runnerEpoch, epoch: this.epochs.get(owner) ?? 0, consumed: false, controller: new AbortController() });
209
+ this.audit(owner, 'grant', result.id);
210
+ return result;
211
+ }
212
+ if (command === 'revoke') {
213
+ const b = parse(z.object({ id: z.string().uuid() }).strict(), value);
214
+ if (this.leases.get(b.id)?.owner !== owner)
215
+ throw new HttpError(404, '授权不存在', 'vault_lease_missing');
216
+ this.revoke(b.id);
217
+ this.audit(owner, 'revoke', b.id);
218
+ return { ok: true };
219
+ }
220
+ throw new HttpError(404, '密码库操作不存在', 'vault_command_unknown');
221
+ }
222
+ async execute(epoch, owner, session, id, input) {
223
+ const b = parse(leaseInput, input), l = this.leases.get(id);
224
+ const check = () => {
225
+ if (epoch !== this.controlEpoch || !l || this.leases.get(id) !== l || l.owner !== owner || l.epoch !== (this.epochs.get(owner) ?? 0)
226
+ || l.expiresAt <= this.now() || l.controller.signal.aborted)
227
+ throw new HttpError(410, '凭据任务授权已失效', 'vault_lease_revoked');
228
+ this.authorize(owner, l.session);
229
+ if (session !== l.session)
230
+ throw new HttpError(403, '执行请求不属于解锁会话', 'vault_scope_forbidden');
231
+ if (['agentId', 'workId', 'runnerId', 'runnerInstance', 'runnerEpoch', 'credentialRef', 'operation'].some(k => l[k] !== b[k])
232
+ || JSON.stringify(l.target) !== JSON.stringify(b.target))
233
+ throw new HttpError(403, '凭据任务范围不匹配', 'vault_scope_forbidden');
234
+ const entry = this.store.list(owner).find(e => e.id === l.credentialRef);
235
+ if (entry?.revision !== l.version)
236
+ throw new HttpError(410, '凭据版本已变化', 'vault_lease_revoked');
237
+ };
238
+ check();
239
+ if (!this.executor)
240
+ throw new HttpError(409, '受保护的浏览器与 SSH 执行器尚未启用,请人工接管', 'vault_executor_not_enabled');
241
+ this.executor.assertAvailable?.();
242
+ if (l.consumed)
243
+ throw new HttpError(409, '此授权已提交,不能重复执行', 'vault_operation_uncertain');
244
+ l.consumed = true;
245
+ this.audit(owner, 'execute-started', id);
246
+ try {
247
+ const result = await this.store.withSecret(owner, l.credentialRef, entry => this.executor.execute(entry, b, l.controller.signal));
248
+ check();
249
+ if (result === undefined && this.executor.mode === 'protected-adapters')
250
+ throw new Error('protected executor receipt missing');
251
+ const receipt = result === undefined ? { status: 'complete', operation: b.operation } : parse(z.union([
252
+ z.object({ status: z.literal('complete'), operation: leaseInput.shape.operation, exitCode: z.number().int().optional(), bytes: z.number().int().nonnegative().optional(), sha256: z.string().regex(/^[a-f0-9]{64}$/).optional() }).strict(),
253
+ z.object({ status: z.literal('manual_takeover_required'), reason: z.enum(['unsupported_form_flow', 'usage_policy_required']), submitted: z.boolean() }).strict(),
254
+ ]), result);
255
+ if (receipt.status === 'complete' && receipt.operation !== b.operation)
256
+ throw new Error('receipt scope changed');
257
+ this.audit(owner, receipt.status === 'complete' ? 'execute-complete' : 'execute-manual', id);
258
+ return receipt; // No raw executor output, URL, exception, Cookie or secret.
259
+ }
260
+ catch (error) {
261
+ this.audit(owner, 'execute-ended', id, 'not-confirmed');
262
+ if (error instanceof HttpError && ['vault_host_key_rejected', 'vault_usage_forbidden', 'vault_isolation_required'].includes(error.code))
263
+ throw error;
264
+ throw new HttpError(409, '操作结果未确认,授权不再允许重试,请人工核对', 'vault_operation_uncertain');
265
+ }
266
+ finally {
267
+ this.revoke(id);
268
+ }
269
+ }
270
+ connectionClosed(owner, session, id) { const l = this.leases.get(id); if (l?.owner === owner && l.session === session)
271
+ this.revoke(id); }
272
+ }