@lsamien/yaoyao 0.4.80 → 0.4.82
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 +9 -7
- package/bin/hermes-yaoyao-updater.mjs +97 -1
- package/bin/lib/npm-release.d.mts +10 -0
- package/bin/lib/npm-release.mjs +93 -0
- package/build-info.json +20 -3
- package/desktop/main.mjs +41 -26
- package/dist/assets/{AboutDialog-on4AME1V.js → AboutDialog-DN7dG_c_.js} +2 -2
- package/dist/assets/{AboutDialog-on4AME1V.js.map → AboutDialog-DN7dG_c_.js.map} +1 -1
- package/dist/assets/{BotAutomationsView-Bmb14qI5.js → BotAutomationsView-CrzyWIZu.js} +2 -2
- package/dist/assets/{BotAutomationsView-Bmb14qI5.js.map → BotAutomationsView-CrzyWIZu.js.map} +1 -1
- package/dist/assets/{BotPluginsDialog-6WPFFQnG.js → BotPluginsDialog-Do0gqTTs.js} +2 -2
- package/dist/assets/{BotPluginsDialog-6WPFFQnG.js.map → BotPluginsDialog-Do0gqTTs.js.map} +1 -1
- package/dist/assets/BotSettingsDialog-D8VpvVd5.js +5 -0
- package/dist/assets/BotSettingsDialog-D8VpvVd5.js.map +1 -0
- package/dist/assets/BotSettingsDialog-yxqKMuZ-.css +1 -0
- package/dist/assets/{ChatView-BKNyjhWf.js → ChatView-DWY-aOYT.js} +2 -2
- package/dist/assets/{ChatView-BKNyjhWf.js.map → ChatView-DWY-aOYT.js.map} +1 -1
- package/dist/assets/ComputerPanel-DTKypGUK.css +1 -0
- package/dist/assets/ComputerPanel-xO0bFrL4.js +2 -0
- package/dist/assets/ComputerPanel-xO0bFrL4.js.map +1 -0
- package/dist/assets/{ComputerViewerView-BBAs4bzi.css → ComputerViewerView-BjlmQDlL.css} +1 -1
- package/dist/assets/ComputerViewerView-CZDBrNHV.js +2 -0
- package/dist/assets/ComputerViewerView-CZDBrNHV.js.map +1 -0
- package/dist/assets/{ConversationsView-CbArO1v2.css → ConversationsView-B5WktSdp.css} +1 -1
- package/dist/assets/ConversationsView-DOOcbFba.js +6 -0
- package/dist/assets/ConversationsView-DOOcbFba.js.map +1 -0
- package/dist/assets/{FilesView-ETwEkBC-.js → FilesView-CYL5X21L.js} +2 -2
- package/dist/assets/{FilesView-ETwEkBC-.js.map → FilesView-CYL5X21L.js.map} +1 -1
- package/dist/assets/FloatingResourceSearch-CfJKcq8o.js +9 -0
- package/dist/assets/{FloatingResourceSearch-CxF6Ko17.js.map → FloatingResourceSearch-CfJKcq8o.js.map} +1 -1
- package/dist/assets/{FloatingResourceSearch-3GOuDkuO.css → FloatingResourceSearch-CqauCQAf.css} +1 -1
- package/dist/assets/{HistoryView-uwkxvrTT.js → HistoryView-Aonx9TTr.js} +2 -2
- package/dist/assets/{HistoryView-uwkxvrTT.js.map → HistoryView-Aonx9TTr.js.map} +1 -1
- package/dist/assets/{KanbanView-BjiWhQiB.js → KanbanView-D0Cv9vS9.js} +2 -2
- package/dist/assets/{KanbanView-BjiWhQiB.js.map → KanbanView-D0Cv9vS9.js.map} +1 -1
- package/dist/assets/{LocalVmSettingsPanel-BAVywgEJ.js → LocalVmSettingsPanel-DFHsQSOV.js} +2 -2
- package/dist/assets/{LocalVmSettingsPanel-BAVywgEJ.js.map → LocalVmSettingsPanel-DFHsQSOV.js.map} +1 -1
- package/dist/assets/{RunnerSettingsPanel-spsPiohB.js → RunnerSettingsPanel-vMkjBH2d.js} +2 -2
- package/dist/assets/{RunnerSettingsPanel-spsPiohB.js.map → RunnerSettingsPanel-vMkjBH2d.js.map} +1 -1
- package/dist/assets/{StandaloneDialog-Ctcd4omg.js → StandaloneDialog-DVJNfO5_.js} +2 -2
- package/dist/assets/{StandaloneDialog-Ctcd4omg.js.map → StandaloneDialog-DVJNfO5_.js.map} +1 -1
- package/dist/assets/{UpdateCheckDialog-C43LDN1t.js → UpdateCheckDialog-Rs1LY4Fc.js} +2 -2
- package/dist/assets/{UpdateCheckDialog-C43LDN1t.js.map → UpdateCheckDialog-Rs1LY4Fc.js.map} +1 -1
- package/dist/assets/{WorkspaceKnowledgePanel-CDbdIzXZ.js → WorkspaceKnowledgePanel-Drg354A9.js} +2 -2
- package/dist/assets/{WorkspaceKnowledgePanel-CDbdIzXZ.js.map → WorkspaceKnowledgePanel-Drg354A9.js.map} +1 -1
- package/dist/assets/{WorkspaceRoutinesPanel-h7wcBTnK.js → WorkspaceRoutinesPanel-CIbD_8Cu.js} +2 -2
- package/dist/assets/{WorkspaceRoutinesPanel-h7wcBTnK.js.map → WorkspaceRoutinesPanel-CIbD_8Cu.js.map} +1 -1
- package/dist/assets/WorkspaceShell-BT92dIOL.css +1 -0
- package/dist/assets/WorkspaceShell-TvxgEyeR.js +44 -0
- package/dist/assets/WorkspaceShell-TvxgEyeR.js.map +1 -0
- package/dist/assets/{WorkspaceView-zDyCd5Ys.js → WorkspaceView-DwAQ1FO6.js} +2 -2
- package/dist/assets/{WorkspaceView-zDyCd5Ys.js.map → WorkspaceView-DwAQ1FO6.js.map} +1 -1
- package/dist/assets/{docx-preview-DOVGRYbk.js → docx-preview-C9VX9kln.js} +2 -2
- package/dist/assets/{docx-preview-DOVGRYbk.js.map → docx-preview-C9VX9kln.js.map} +1 -1
- package/dist/assets/{index-CRBIQ5t6.js → index-BjLiSGiH.js} +3 -3
- package/dist/assets/{index-CRBIQ5t6.js.map → index-BjLiSGiH.js.map} +1 -1
- package/dist/assets/{pdf-CyfBRmEm.js → pdf-DUuw6IdJ.js} +2 -2
- package/dist/assets/{pdf-CyfBRmEm.js.map → pdf-DUuw6IdJ.js.map} +1 -1
- package/dist/assets/{sessionOwnership-BhbWRxbS.js → sessionOwnership-CDSHgXVo.js} +2 -2
- package/dist/assets/{sessionOwnership-BhbWRxbS.js.map → sessionOwnership-CDSHgXVo.js.map} +1 -1
- package/dist/assets/{viewModels-DNhmBuoz.js → viewModels-C3J1drQ0.js} +5 -5
- package/dist/assets/viewModels-C3J1drQ0.js.map +1 -0
- package/dist/index.html +1 -1
- package/dist-server/server/app.js +2 -0
- package/dist-server/server/chatCache.js +3 -2
- package/dist-server/server/chatPresentation.js +32 -0
- package/dist-server/server/chatTranscriptApi.js +2 -1
- package/dist-server/server/config.js +2 -0
- package/dist-server/server/credentialVault/adapterExecutor.js +23 -0
- package/dist-server/server/credentialVault/botAccess.js +161 -0
- package/dist-server/server/credentialVault/broker.js +61 -6
- package/dist-server/server/credentialVault/coordinator.js +108 -15
- package/dist-server/server/credentialVault/localClient.js +129 -8
- package/dist-server/server/credentialVault/localExecutor.js +15 -0
- package/dist-server/server/credentialVault/protectedExecutor.js +3 -19
- package/dist-server/server/credentialVault/schema.js +11 -4
- package/dist-server/server/credentialVault/sshExecutor.js +111 -15
- package/dist-server/server/credentialVault/store.js +11 -5
- package/dist-server/server/credentialVault/transport.js +4 -1
- package/dist-server/server/desktopEnvironments.js +17 -17
- package/dist-server/server/jsonCompression.js +29 -0
- package/dist-server/server/routes.js +14 -1
- package/dist-server/server/runnerHub.js +12 -1
- package/dist-server/server/updateManager.js +42 -10
- package/dist-server/server/workspaceRoutes.js +30 -4
- package/dist-server/server/workspaceSync.js +22 -4
- package/dist-server/shared/desktopUpdate.js +1 -0
- package/package.json +1 -1
- package/release.json +3 -3
- package/dist/assets/BotSettingsDialog-BkjoAZtf.css +0 -1
- package/dist/assets/BotSettingsDialog-wWHnGtBg.js +0 -5
- package/dist/assets/BotSettingsDialog-wWHnGtBg.js.map +0 -1
- package/dist/assets/ComputerPanel-CQOv4v8E.css +0 -1
- package/dist/assets/ComputerPanel-DP9Sge1E.js +0 -2
- package/dist/assets/ComputerPanel-DP9Sge1E.js.map +0 -1
- package/dist/assets/ComputerViewerView-WjPHo035.js +0 -2
- package/dist/assets/ComputerViewerView-WjPHo035.js.map +0 -1
- package/dist/assets/ConversationsView-BRNIpK57.js +0 -6
- package/dist/assets/ConversationsView-BRNIpK57.js.map +0 -1
- package/dist/assets/FloatingResourceSearch-CxF6Ko17.js +0 -9
- package/dist/assets/WorkspaceShell-Bx8se0l7.js +0 -44
- package/dist/assets/WorkspaceShell-Bx8se0l7.js.map +0 -1
- package/dist/assets/WorkspaceShell-DXti6BpF.css +0 -1
- package/dist/assets/viewModels-DNhmBuoz.js.map +0 -1
|
@@ -1,35 +1,49 @@
|
|
|
1
1
|
import { join } from 'node:path';
|
|
2
2
|
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
3
4
|
import { CredentialVaultClient } from './transport.js';
|
|
4
5
|
import { CredentialVaultStore } from './store.js';
|
|
5
6
|
import { CredentialVaultBroker } from './broker.js';
|
|
6
7
|
import { HttpError } from '../errors.js';
|
|
7
8
|
import { acquireServiceInstance } from '../serviceInstance.js';
|
|
8
|
-
|
|
9
|
-
|
|
9
|
+
import { LocalCredentialExecutor } from './localExecutor.js';
|
|
10
|
+
import { z } from 'zod';
|
|
11
|
+
import { parse, leaseInput, updateInput, sshCommand, sshTimeout } from './schema.js';
|
|
12
|
+
import { BotCredentialAccess } from './botAccess.js';
|
|
13
|
+
/** Default encrypted vault with task-scoped execution in the trusted server. */
|
|
10
14
|
export class LocalCredentialVaultClient extends CredentialVaultClient {
|
|
11
15
|
home;
|
|
16
|
+
testCA;
|
|
12
17
|
controlEpoch = randomUUID();
|
|
13
18
|
broker;
|
|
14
19
|
instance;
|
|
20
|
+
executor;
|
|
15
21
|
closed = false;
|
|
16
|
-
|
|
22
|
+
botAccess;
|
|
23
|
+
constructor(home, testCA) {
|
|
17
24
|
super();
|
|
18
25
|
this.home = home;
|
|
26
|
+
this.testCA = testCA;
|
|
19
27
|
}
|
|
28
|
+
get configured() { return true; }
|
|
29
|
+
get executionLocation() { return 'server'; }
|
|
20
30
|
async call(owner, session, command, value) {
|
|
21
31
|
if (this.closed)
|
|
22
32
|
throw new HttpError(503, '密码保险箱已关闭', 'vault_offline');
|
|
23
|
-
if (['grant', 'execute'].includes(command))
|
|
24
|
-
throw new HttpError(409, '本机保险箱只保存凭据;Bot 自动使用需要连接独立密码库服务', 'vault_executor_not_enabled');
|
|
25
33
|
this.broker ??= CredentialVaultStore.create(join(this.home, 'credential-vault')).then(store => {
|
|
26
34
|
if (this.closed)
|
|
27
35
|
throw new Error('closed');
|
|
28
36
|
this.instance = acquireServiceInstance(store.root, 'credential-vault-v1');
|
|
29
|
-
|
|
37
|
+
this.executor = new LocalCredentialExecutor(join(store.root, 'executor'), this.testCA);
|
|
38
|
+
this.botAccess = new BotCredentialAccess(join(store.root, 'bot-access'));
|
|
39
|
+
const broker = new CredentialVaultBroker(store, Date.now, this.executor);
|
|
30
40
|
broker.hello(this.controlEpoch);
|
|
31
41
|
return broker;
|
|
32
42
|
}).catch(() => {
|
|
43
|
+
this.botAccess?.close();
|
|
44
|
+
this.botAccess = undefined;
|
|
45
|
+
this.executor?.close();
|
|
46
|
+
this.executor = undefined;
|
|
33
47
|
this.instance?.release();
|
|
34
48
|
this.instance = undefined;
|
|
35
49
|
this.broker = undefined;
|
|
@@ -39,18 +53,121 @@ export class LocalCredentialVaultClient extends CredentialVaultClient {
|
|
|
39
53
|
if (this.closed)
|
|
40
54
|
throw new HttpError(503, '密码保险箱已关闭', 'vault_offline');
|
|
41
55
|
try {
|
|
42
|
-
|
|
56
|
+
if (command === 'bot-refs')
|
|
57
|
+
return this.botAccess.summaries(owner, parse(z.object({ agentId: z.string().uuid().optional() }).strict(), value ?? {}).agentId);
|
|
58
|
+
if (command === 'bot-grant' || command === 'bot-revoke') {
|
|
59
|
+
if (!broker.status(owner, session).unlocked)
|
|
60
|
+
throw new HttpError(423, '请先解锁管理界面', 'vault_locked');
|
|
61
|
+
const b = parse(z.object({ credentialRef: z.string().uuid(), agentId: z.string().uuid() }).strict(), value);
|
|
62
|
+
if (command === 'bot-revoke') {
|
|
63
|
+
this.botAccess.revoke(owner, b.credentialRef, b.agentId);
|
|
64
|
+
broker.recordBotAction(owner, 'bot-revoke', b.credentialRef);
|
|
65
|
+
return { ok: true };
|
|
66
|
+
}
|
|
67
|
+
const entry = broker.store.list(owner).find(e => e.id === b.credentialRef);
|
|
68
|
+
if (!entry || entry.target.kind !== 'ssh' && !entry.usage)
|
|
69
|
+
throw new HttpError(403, '凭据不存在或尚未配置网站使用计划', 'vault_usage_forbidden');
|
|
70
|
+
broker.store.withSecret(owner, b.credentialRef, e => this.botAccess.grant(owner, b.agentId, e));
|
|
71
|
+
try {
|
|
72
|
+
broker.recordBotAction(owner, 'bot-grant', b.credentialRef);
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
this.botAccess.revoke(owner, b.credentialRef, b.agentId);
|
|
76
|
+
throw error;
|
|
77
|
+
}
|
|
78
|
+
return { ok: true };
|
|
79
|
+
}
|
|
80
|
+
if (command === 'update') {
|
|
81
|
+
if (!broker.status(owner, session).unlocked)
|
|
82
|
+
throw new HttpError(423, '请先解锁管理界面', 'vault_locked');
|
|
83
|
+
const b = parse(z.object({ id: z.string().uuid(), entry: updateInput }).strict(), value);
|
|
84
|
+
const old = broker.store.list(owner).find(e => e.id === b.id);
|
|
85
|
+
const changedEndpoint = old?.target.kind === 'ssh' && b.entry.target.kind === 'ssh' && (old.target.host !== b.entry.target.host || old.target.port !== b.entry.target.port);
|
|
86
|
+
// An automatic pin belongs to an endpoint, not to a credential's name.
|
|
87
|
+
if (changedEndpoint && old?.target.kind === 'ssh' && b.entry.target.kind === 'ssh' && b.entry.target.hostKey === old.target.hostKey)
|
|
88
|
+
delete b.entry.target.hostKey;
|
|
89
|
+
const preservePin = old?.target.kind === 'ssh' && b.entry.target.kind === 'ssh' && !changedEndpoint && !old.target.hostKey && !b.entry.target.hostKey;
|
|
90
|
+
try {
|
|
91
|
+
const result = broker.dispatch(this.controlEpoch, owner, session, command, b);
|
|
92
|
+
broker.store.withSecret(owner, b.id, e => this.botAccess.refresh(owner, e, !!preservePin));
|
|
93
|
+
return result;
|
|
94
|
+
}
|
|
95
|
+
catch (error) {
|
|
96
|
+
// Validation conflicts leave approval intact; uncertain writes cannot use old material.
|
|
97
|
+
if (!(error instanceof HttpError))
|
|
98
|
+
this.botAccess.revoke(owner, b.id);
|
|
99
|
+
throw error;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
if (command === 'remove') {
|
|
103
|
+
const id = parse(z.object({ id: z.string().uuid() }).passthrough(), value).id;
|
|
104
|
+
// Invalidate before mutation, including a partially committed write.
|
|
105
|
+
if (broker.status(owner, session).unlocked)
|
|
106
|
+
this.botAccess.revoke(owner, id);
|
|
107
|
+
}
|
|
108
|
+
const result = command === 'execute'
|
|
109
|
+
? await (() => { const body = parse(z.object({ id: z.string().uuid(), input: leaseInput }).strict(), value); return broker.execute(this.controlEpoch, owner, session, body.id, body.input); })()
|
|
110
|
+
: command === 'prepare-host' ? await broker.prepareHost(this.controlEpoch, owner, session, value)
|
|
111
|
+
: broker.dispatch(this.controlEpoch, owner, session, command, value);
|
|
43
112
|
return ['status', 'initialize', 'unlock', 'restore'].includes(command)
|
|
44
|
-
? { ...result, storageMode: 'local' }
|
|
113
|
+
? { ...result, storageMode: 'local', botGrants: this.botAccess.summaries(owner) }
|
|
45
114
|
: result;
|
|
46
115
|
}
|
|
47
116
|
catch (error) {
|
|
48
117
|
if (error instanceof HttpError)
|
|
49
118
|
throw error;
|
|
50
119
|
broker.disconnect();
|
|
120
|
+
this.onDisconnect();
|
|
51
121
|
throw new HttpError(409, '密码保险箱操作未完成,请刷新状态后重新解锁', 'vault_request_failed');
|
|
52
122
|
}
|
|
53
123
|
}
|
|
124
|
+
async executeBot(owner, input, signal) {
|
|
125
|
+
const b = parse(leaseInput, input);
|
|
126
|
+
if (b.command !== undefined)
|
|
127
|
+
parse(sshCommand, b.command);
|
|
128
|
+
if (b.timeoutSeconds !== undefined)
|
|
129
|
+
parse(sshTimeout, b.timeoutSeconds);
|
|
130
|
+
await this.call(owner, '', 'bot-refs', { agentId: b.agentId }); // Initialize the local broker without unlocking management.
|
|
131
|
+
const broker = await this.broker;
|
|
132
|
+
let submitted = false;
|
|
133
|
+
try {
|
|
134
|
+
return await this.botAccess.execute(owner, b.agentId, b.credentialRef, signal, async (entry, activeSignal) => {
|
|
135
|
+
const operation = entry.usage?.kind === 'website.form' ? 'website.login' : entry.usage?.kind;
|
|
136
|
+
const autonomous = entry.target.kind === 'ssh' && b.operation === 'ssh.exec';
|
|
137
|
+
const requestedTarget = b.target.kind === 'ssh' && !b.target.hostKey && entry.target.kind === 'ssh' ? { ...b.target, ...(entry.target.hostKey ? { hostKey: entry.target.hostKey } : {}) } : b.target;
|
|
138
|
+
if ((!autonomous && operation !== b.operation) || !isDeepStrictEqual(entry.target, requestedTarget) || (!autonomous && (b.command !== undefined || b.timeoutSeconds !== undefined)))
|
|
139
|
+
throw new HttpError(403, '操作不属于已授权的使用计划', 'vault_usage_forbidden');
|
|
140
|
+
if (autonomous)
|
|
141
|
+
parse(sshCommand, b.command ?? (entry.usage?.kind === 'ssh.exec' ? entry.usage.command : undefined));
|
|
142
|
+
if (entry.target.kind === 'ssh' && !entry.target.hostKey) {
|
|
143
|
+
const hostKey = await this.executor.prepareSshHost(entry.target, activeSignal);
|
|
144
|
+
activeSignal.throwIfAborted();
|
|
145
|
+
entry = this.botAccess.pinSshHost(owner, b.agentId, entry.id, entry.revision, hostKey);
|
|
146
|
+
}
|
|
147
|
+
broker.recordBotAction(owner, 'bot-execute-started', b.credentialRef);
|
|
148
|
+
submitted = true;
|
|
149
|
+
const receipt = await (autonomous ? this.executor.executeAutonomous(entry, { ...b, target: entry.target }, activeSignal) : this.executor.execute(entry, { ...b, target: entry.target }, activeSignal));
|
|
150
|
+
const result = parse(z.union([
|
|
151
|
+
z.object({ status: z.literal('complete'), operation: z.literal('ssh.exec'), exitCode: z.number().int(), stdout: z.string().max(65536), stderr: z.string().max(65536), truncated: z.boolean() }).strict(),
|
|
152
|
+
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(),
|
|
153
|
+
z.object({ status: z.literal('manual_takeover_required'), reason: z.enum(['unsupported_form_flow', 'usage_policy_required']), submitted: z.boolean() }).strict(),
|
|
154
|
+
]), receipt);
|
|
155
|
+
if (result.status === 'complete' && result.operation !== b.operation)
|
|
156
|
+
throw new Error('receipt scope changed');
|
|
157
|
+
broker.recordBotAction(owner, 'bot-execute-complete', b.credentialRef);
|
|
158
|
+
return result;
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
catch (error) {
|
|
162
|
+
if (error instanceof HttpError && ['vault_bot_forbidden', 'vault_scope_forbidden', 'vault_usage_forbidden', 'vault_host_key_rejected', 'vault_host_key_required'].includes(error.code))
|
|
163
|
+
throw error;
|
|
164
|
+
if (!submitted)
|
|
165
|
+
throw error;
|
|
166
|
+
broker.recordBotAction(owner, 'bot-execute-ended', b.credentialRef, 'not-confirmed');
|
|
167
|
+
throw new HttpError(409, '操作结果未确认,请人工核对,不能自动重试', 'vault_operation_uncertain');
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
revokeBot(owner, credentialRef, agentId) { this.botAccess?.revoke(owner, credentialRef, agentId); }
|
|
54
171
|
close() {
|
|
55
172
|
this.closed = true;
|
|
56
173
|
void this.broker?.then(broker => {
|
|
@@ -58,6 +175,10 @@ export class LocalCredentialVaultClient extends CredentialVaultClient {
|
|
|
58
175
|
broker.close();
|
|
59
176
|
}
|
|
60
177
|
finally {
|
|
178
|
+
this.botAccess?.close();
|
|
179
|
+
this.botAccess = undefined;
|
|
180
|
+
this.executor?.close();
|
|
181
|
+
this.executor = undefined;
|
|
61
182
|
this.instance?.release();
|
|
62
183
|
this.instance = undefined;
|
|
63
184
|
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { CredentialAdapterExecutor } from './adapterExecutor.js';
|
|
2
|
+
import { HttpError } from '../errors.js';
|
|
3
|
+
/** Trusted server execution; it does not claim protection from same-UID shells.
|
|
4
|
+
* The broker enforces owner, session, task, revision and one-use leases. */
|
|
5
|
+
export class LocalCredentialExecutor extends CredentialAdapterExecutor {
|
|
6
|
+
mode = 'local-adapters';
|
|
7
|
+
lifetime;
|
|
8
|
+
constructor(home, testCA) {
|
|
9
|
+
const lifetime = { closed: false };
|
|
10
|
+
super(home, { assert() { if (lifetime.closed)
|
|
11
|
+
throw new HttpError(503, '本机凭据执行器已关闭', 'vault_executor_unavailable'); } }, testCA);
|
|
12
|
+
this.lifetime = lifetime;
|
|
13
|
+
}
|
|
14
|
+
close() { this.lifetime.closed = true; }
|
|
15
|
+
}
|
|
@@ -1,21 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
export class ProtectedCredentialExecutor {
|
|
5
|
-
gate;
|
|
1
|
+
import { CredentialAdapterExecutor } from './adapterExecutor.js';
|
|
2
|
+
/** Independent deployment still supplies the operator-approved isolation gate. */
|
|
3
|
+
export class ProtectedCredentialExecutor extends CredentialAdapterExecutor {
|
|
6
4
|
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
5
|
}
|
|
@@ -13,7 +13,8 @@ export const website = z.object({ kind: z.literal('website'), origin: z.string()
|
|
|
13
13
|
}
|
|
14
14
|
}) }).strict();
|
|
15
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}=?$/)
|
|
16
|
+
port: z.number().int().min(1).max(65535), hostKey: z.string().regex(/^SHA256:[A-Za-z0-9+/]{43}=?$/).optional(),
|
|
17
|
+
auth: z.enum(['privateKey', 'password']).optional() }).strict();
|
|
17
18
|
export const target = z.discriminatedUnion('kind', [website, ssh]);
|
|
18
19
|
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
20
|
const name = z.string().min(1).max(100).regex(/^[A-Za-z][A-Za-z0-9_.:-]*$/);
|
|
@@ -23,17 +24,23 @@ const command = z.object({ kind: z.literal('ssh.exec'), command: z.string().max(
|
|
|
23
24
|
const read = z.object({ kind: z.literal('sftp.read'), remotePath: path, maxBytes: z.number().int().min(1).max(1048576).default(65536) }).strict();
|
|
24
25
|
const write = z.object({ kind: z.literal('sftp.write'), remotePath: path, contents: z.string().max(65536) }).strict();
|
|
25
26
|
export const usage = z.discriminatedUnion('kind', [form, command, read, write]);
|
|
27
|
+
export const sshCommand = z.string().min(1).max(32768).refine(v => !v.includes('\u0000'));
|
|
28
|
+
export const sshTimeout = z.number().int().min(1).max(600);
|
|
26
29
|
const updatedUsage = z.discriminatedUnion('kind', [form, command, read, write.extend({ contents: z.string().max(65536).optional() })]);
|
|
27
30
|
export const leaseInput = z.object({
|
|
28
31
|
credentialRef: z.string().uuid(), agentId: z.string().uuid(), workId: z.string().uuid(),
|
|
29
32
|
runnerId: z.string().uuid(), runnerInstance: z.string().uuid(), runnerEpoch: z.string().min(1).max(128),
|
|
30
33
|
operation: z.enum(['website.login', 'ssh.exec', 'sftp.read', 'sftp.write']), target,
|
|
34
|
+
command: sshCommand.optional(), timeoutSeconds: sshTimeout.optional(),
|
|
31
35
|
seconds: z.number().int().min(15).max(120).default(60),
|
|
32
36
|
}).strict();
|
|
33
|
-
|
|
37
|
+
const entryFields = z.object({ name: z.string().trim().min(1).max(120), username: z.string().min(1).max(256),
|
|
34
38
|
target, usage: usage.optional(), secret: z.string().min(1).max(32768), passphrase: z.string().max(4096).optional() }).strict();
|
|
35
|
-
|
|
36
|
-
|
|
39
|
+
const validPassphrase = (entry) => entry.target.kind !== 'ssh' || entry.target.auth !== 'password' || !entry.passphrase;
|
|
40
|
+
const passphraseError = { message: 'SSH 密码登录不使用私钥口令', path: ['passphrase'] };
|
|
41
|
+
export const entryInput = entryFields.refine(validPassphrase, passphraseError);
|
|
42
|
+
export const updateInput = entryFields.extend({ secret: entryFields.shape.secret.optional(), usage: updatedUsage.optional(), revision: z.number().int().positive() }).refine(validPassphrase, passphraseError);
|
|
43
|
+
export const storedEntry = entryFields.extend({ id: z.string().uuid(), revision: z.number().int().positive(), updatedAt: z.number().int().nonnegative() }).refine(validPassphrase, passphraseError);
|
|
37
44
|
export function parse(schema, value) {
|
|
38
45
|
const result = schema.safeParse(value);
|
|
39
46
|
if (!result.success)
|
|
@@ -1,24 +1,80 @@
|
|
|
1
1
|
import { Client } from 'ssh2';
|
|
2
2
|
import { createHash, timingSafeEqual } from 'node:crypto';
|
|
3
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
4
|
+
import { parse, sshCommand, sshTimeout } from './schema.js';
|
|
3
5
|
import { HttpError } from '../errors.js';
|
|
4
6
|
const call = (start) => new Promise((resolve, reject) => start((error, value) => error ? reject(error) : resolve(value)));
|
|
5
|
-
|
|
6
|
-
|
|
7
|
+
const serverHostKey = ['ssh-ed25519', 'rsa-sha2-512', 'rsa-sha2-256', 'ecdsa-sha2-nistp256'];
|
|
8
|
+
/** First-use discovery stops at key exchange. It never supplies credentials or authenticates. */
|
|
9
|
+
export async function probeSshHostKey(host, gate, externalSignal) {
|
|
10
|
+
gate.assert();
|
|
11
|
+
externalSignal.throwIfAborted();
|
|
12
|
+
const conn = new Client(), signal = AbortSignal.any([externalSignal, AbortSignal.timeout(5000)]);
|
|
13
|
+
let abort;
|
|
14
|
+
try {
|
|
15
|
+
return await new Promise((resolve, reject) => {
|
|
16
|
+
let settled = false;
|
|
17
|
+
const fail = () => { if (!settled) {
|
|
18
|
+
settled = true;
|
|
19
|
+
reject(new HttpError(503, '无法连接 SSH 服务器,密码已保存,请检查地址和端口', 'vault_host_probe_failed'));
|
|
20
|
+
} };
|
|
21
|
+
abort = () => { fail(); conn.destroy(); };
|
|
22
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
23
|
+
conn.on('error', fail);
|
|
24
|
+
conn.on('close', fail);
|
|
25
|
+
conn.connect({ host: host.host.replace(/^\[|\]$/g, ''), port: host.port, username: 'host-key-probe', authHandler: [], tryKeyboard: false, readyTimeout: 5000,
|
|
26
|
+
algorithms: { serverHostKey }, hostVerifier: (key) => {
|
|
27
|
+
try {
|
|
28
|
+
signal.throwIfAborted();
|
|
29
|
+
gate.assert();
|
|
30
|
+
if (!settled) {
|
|
31
|
+
settled = true;
|
|
32
|
+
resolve('SHA256:' + createHash('sha256').update(key).digest('base64').replace(/=+$/, ''));
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
fail();
|
|
37
|
+
}
|
|
38
|
+
return false; // Reject before authentication even when discovery succeeded.
|
|
39
|
+
} });
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
finally {
|
|
43
|
+
signal.removeEventListener('abort', abort);
|
|
44
|
+
conn.destroy();
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** Pinned SSH authentication. Autonomous commands are enabled only by trusted
|
|
48
|
+
* Bot approval; credentials, forwarding and a local shell are never exposed. */
|
|
7
49
|
export class SshSftpExecutor {
|
|
8
50
|
gate;
|
|
9
51
|
constructor(gate) {
|
|
10
52
|
this.gate = gate;
|
|
11
53
|
}
|
|
12
|
-
|
|
54
|
+
executeAutonomous(entry, input, signal) {
|
|
55
|
+
if (input.operation !== 'ssh.exec' || entry.target.kind !== 'ssh')
|
|
56
|
+
throw new HttpError(403, '此凭据不支持自主 SSH 运维', 'vault_usage_forbidden');
|
|
57
|
+
const command = parse(sshCommand, input.command ?? (entry.usage?.kind === 'ssh.exec' ? entry.usage.command : undefined)), timeout = parse(sshTimeout, input.timeoutSeconds ?? 60);
|
|
58
|
+
return this.run({ ...entry, usage: { kind: 'ssh.exec', command } }, { ...input, operation: 'ssh.exec' }, signal, { timeout });
|
|
59
|
+
}
|
|
60
|
+
execute(entry, input, externalSignal) {
|
|
61
|
+
if (input.command !== undefined || input.timeoutSeconds !== undefined)
|
|
62
|
+
throw new HttpError(403, '请先将 SSH 凭据授权给指定 Bot', 'vault_usage_forbidden');
|
|
63
|
+
return this.run(entry, input, externalSignal);
|
|
64
|
+
}
|
|
65
|
+
async run(entry, input, externalSignal, autonomous) {
|
|
13
66
|
this.gate.assert();
|
|
14
67
|
externalSignal.throwIfAborted();
|
|
15
68
|
const plan = entry.usage;
|
|
16
69
|
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
70
|
return { status: 'manual_takeover_required', reason: 'usage_policy_required', submitted: false };
|
|
18
|
-
const host = entry.target
|
|
71
|
+
const host = entry.target;
|
|
72
|
+
if (!host.hostKey)
|
|
73
|
+
throw new HttpError(403, '首次使用前需要确认 SSH 服务器', 'vault_host_key_required');
|
|
74
|
+
const expected = Buffer.from(host.hostKey.slice(7), 'base64');
|
|
19
75
|
if (expected.length !== 32)
|
|
20
76
|
throw new HttpError(403, 'SSH host key 指纹无效', 'vault_host_key_rejected');
|
|
21
|
-
const signal = AbortSignal.any([externalSignal, AbortSignal.timeout(15000)]), conn = new Client();
|
|
77
|
+
const signal = AbortSignal.any([externalSignal, AbortSignal.timeout(autonomous ? autonomous.timeout * 1000 : 15000)]), conn = new Client();
|
|
22
78
|
let hostRejected = false, finished = false, fail, ready;
|
|
23
79
|
const failure = new Promise((_r, reject) => { fail = reject; }), connected = new Promise(resolve => { ready = resolve; });
|
|
24
80
|
// connect() can synchronously reject a malformed key before work is created.
|
|
@@ -27,32 +83,72 @@ export class SshSftpExecutor {
|
|
|
27
83
|
const invoke = (start) => Promise.race([call(start), failure]);
|
|
28
84
|
const abort = () => { fail(new Error('operation cancelled')); conn.destroy(); };
|
|
29
85
|
signal.addEventListener('abort', abort, { once: true });
|
|
30
|
-
conn.on('error', () => fail(hostRejected ? new HttpError(403, 'SSH
|
|
86
|
+
conn.on('error', () => fail(hostRejected ? new HttpError(403, 'SSH 服务器指纹已改变,已停止连接', 'vault_host_key_rejected') : new Error('SSH connection unavailable')));
|
|
31
87
|
conn.on('close', () => { if (!finished)
|
|
32
88
|
fail(new Error('SSH receipt unavailable')); });
|
|
33
89
|
conn.once('ready', ready);
|
|
34
90
|
const check = () => { signal.throwIfAborted(); this.gate.assert(); };
|
|
35
91
|
try {
|
|
36
|
-
conn.connect({ host: host.host.replace(/^\[|\]$/g, ''), port: host.port, username: entry.username,
|
|
37
|
-
|
|
38
|
-
|
|
92
|
+
conn.connect({ host: host.host.replace(/^\[|\]$/g, ''), port: host.port, username: entry.username,
|
|
93
|
+
...(host.auth === 'password' ? { password: entry.secret } : { privateKey: entry.secret, ...(entry.passphrase ? { passphrase: entry.passphrase } : {}) }),
|
|
94
|
+
authHandler: [host.auth === 'password' ? 'password' : 'publickey'], tryKeyboard: false, agentForward: false, readyTimeout: 5000, keepaliveInterval: 0,
|
|
95
|
+
algorithms: { serverHostKey },
|
|
39
96
|
hostVerifier: (key) => { const digest = createHash('sha256').update(key).digest(); const match = timingSafeEqual(digest, expected); hostRejected = !match; return match; } });
|
|
40
97
|
const work = (async () => {
|
|
41
98
|
await Promise.race([connected, failure]);
|
|
42
99
|
check();
|
|
43
100
|
if (plan.kind === 'ssh.exec') {
|
|
44
|
-
//
|
|
45
|
-
//
|
|
101
|
+
// Autonomous commands run on the approved remote SSH account, never
|
|
102
|
+
// through a local shell. Restricted approval still uses its fixed plan.
|
|
46
103
|
const stream = await invoke(done => conn.exec(plan.command, { pty: false }, done));
|
|
47
104
|
check();
|
|
48
|
-
let output = 0;
|
|
49
|
-
const
|
|
105
|
+
let output = 0, truncated = false;
|
|
106
|
+
const stdout = [], stderr = [], limit = 65536;
|
|
107
|
+
const privateValues = [entry.secret, entry.passphrase].filter((s) => !!s).map(s => s.replace(/\r\n/g, '\n'));
|
|
108
|
+
if (entry.target.kind === 'ssh' && entry.target.auth !== 'password')
|
|
109
|
+
privateValues.push(...entry.secret.split(/\r?\n/).filter(s => s.length >= 8));
|
|
110
|
+
const retainedLimit = limit + Math.max(...privateValues.map(s => Buffer.byteLength(s)));
|
|
111
|
+
let outBytes = 0, errBytes = 0;
|
|
112
|
+
const capture = (chunks, data, bytes) => { const available = Math.max(0, retainedLimit - bytes); if (available < data.length)
|
|
113
|
+
truncated = true; if (available)
|
|
114
|
+
chunks.push(Buffer.from(data.subarray(0, available))); return bytes + Math.min(data.length, available); };
|
|
115
|
+
const discard = (data) => { output += data.length; if (output > limit)
|
|
50
116
|
abort(); };
|
|
51
|
-
stream.on('data',
|
|
52
|
-
|
|
117
|
+
stream.on('data', (data) => { if (autonomous)
|
|
118
|
+
outBytes = capture(stdout, data, outBytes);
|
|
119
|
+
else
|
|
120
|
+
discard(data); });
|
|
121
|
+
stream.stderr.on('data', (data) => { if (autonomous)
|
|
122
|
+
errBytes = capture(stderr, data, errBytes);
|
|
123
|
+
else
|
|
124
|
+
discard(data); });
|
|
53
125
|
stream.on('error', () => fail(new Error('SSH command interrupted')));
|
|
54
126
|
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
127
|
check();
|
|
128
|
+
if (autonomous) {
|
|
129
|
+
const sanitize = (chunks) => {
|
|
130
|
+
let text = Buffer.concat(chunks).toString('utf8').replace(/\r\n/g, '\n');
|
|
131
|
+
for (const value of privateValues) {
|
|
132
|
+
// The retained buffer may end partway through a credential.
|
|
133
|
+
for (let n = truncated ? Math.min(value.length - 1, text.length) : 0; n > 0; n--)
|
|
134
|
+
if (text.endsWith(value.slice(0, n))) {
|
|
135
|
+
text = text.slice(0, -n) + '[REDACTED]';
|
|
136
|
+
break;
|
|
137
|
+
}
|
|
138
|
+
text = text.split(value).join('[REDACTED]');
|
|
139
|
+
}
|
|
140
|
+
return text.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, '').replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, '');
|
|
141
|
+
};
|
|
142
|
+
try {
|
|
143
|
+
const out = Buffer.from(sanitize(stdout)), err = Buffer.from(sanitize(stderr)), outSize = Math.min(out.length, limit), errSize = Math.min(err.length, limit - outSize);
|
|
144
|
+
truncated ||= outSize < out.length || errSize < err.length;
|
|
145
|
+
return { status: 'complete', operation: 'ssh.exec', exitCode: code, stdout: new StringDecoder('utf8').write(out.subarray(0, outSize)), stderr: new StringDecoder('utf8').write(err.subarray(0, errSize)), truncated };
|
|
146
|
+
}
|
|
147
|
+
finally {
|
|
148
|
+
for (const b of [...stdout, ...stderr])
|
|
149
|
+
b.fill(0);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
56
152
|
return { status: 'complete', operation: 'ssh.exec', exitCode: code };
|
|
57
153
|
}
|
|
58
154
|
const sftp = await invoke(done => conn.sftp(done));
|
|
@@ -46,9 +46,9 @@ function derive(password, e) {
|
|
|
46
46
|
}
|
|
47
47
|
}
|
|
48
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
|
-
/**
|
|
50
|
-
* JS strings/GC and WASM are not a secure enclave; same-UID
|
|
51
|
-
*
|
|
49
|
+
/** Encrypted storage for a trusted local server or independently isolated broker.
|
|
50
|
+
* JS strings/GC and WASM are not a secure enclave; same-UID protection requires
|
|
51
|
+
* deployment isolation. Restart discards the DEK and always starts locked. */
|
|
52
52
|
export class CredentialVaultStore {
|
|
53
53
|
now;
|
|
54
54
|
beforeRename;
|
|
@@ -237,8 +237,14 @@ export class CredentialVaultStore {
|
|
|
237
237
|
throw new HttpError(404, '凭据不存在', 'vault_entry_missing');
|
|
238
238
|
if (old.revision !== input.revision)
|
|
239
239
|
throw new HttpError(409, '凭据已变化,请刷新', 'vault_revision_conflict');
|
|
240
|
+
const changedAuthentication = old.target.kind !== input.target.kind || old.target.kind === 'ssh' && input.target.kind === 'ssh'
|
|
241
|
+
&& (old.target.auth ?? 'privateKey') !== (input.target.auth ?? 'privateKey');
|
|
242
|
+
if (changedAuthentication && !input.secret)
|
|
243
|
+
throw new HttpError(400, '更换认证方式需要重新填写密码或私钥', 'vault_auth_secret_required');
|
|
240
244
|
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,
|
|
245
|
+
const next = parse(storedEntry, { ...old, ...input, usage: changedUsage, secret: input.secret ?? old.secret,
|
|
246
|
+
passphrase: input.target.kind === 'ssh' && input.target.auth === 'password' ? undefined : input.passphrase ?? old.passphrase,
|
|
247
|
+
revision: old.revision + 1, updatedAt: this.now() });
|
|
242
248
|
this.commit(owner, s.entries.map(v => v.id === id ? next : v));
|
|
243
249
|
this.onLock(owner);
|
|
244
250
|
return summary(next);
|
|
@@ -250,7 +256,7 @@ export class CredentialVaultStore {
|
|
|
250
256
|
this.commit(owner, s.entries.filter(v => v.id !== id));
|
|
251
257
|
this.onLock(owner);
|
|
252
258
|
}
|
|
253
|
-
/** Only
|
|
259
|
+
/** Only a broker-controlled executor callback may receive this. No read-secret RPC exists. */
|
|
254
260
|
withSecret(owner, id, use) {
|
|
255
261
|
const s = this.active(owner), entry = s.entries.find(v => v.id === id);
|
|
256
262
|
if (!entry)
|
|
@@ -32,7 +32,9 @@ export function serveCredentialVault(broker, token) {
|
|
|
32
32
|
const result = body.command === 'hello' ? broker.hello(body.epoch) : body.command === 'execute'
|
|
33
33
|
? await (() => { const v = parse(z.object({ id: z.string().uuid(), input: z.unknown() }).strict(), body.value); res.once('close', () => { if (!res.writableEnded)
|
|
34
34
|
broker.connectionClosed(body.owner, body.session, v.id); }); return broker.execute(body.epoch, body.owner, body.session, v.id, v.input); })()
|
|
35
|
-
:
|
|
35
|
+
: body.command === 'prepare-host' ? await (() => { const controller = new AbortController(); res.once('close', () => { if (!res.writableEnded)
|
|
36
|
+
controller.abort(); }); return broker.prepareHost(body.epoch, body.owner, body.session, body.value, controller.signal); })()
|
|
37
|
+
: broker.dispatch(body.epoch, body.owner, body.session, body.command, body.value);
|
|
36
38
|
res.setHeader('Content-Type', 'application/json');
|
|
37
39
|
res.end(JSON.stringify({ result }));
|
|
38
40
|
})().catch(error => {
|
|
@@ -59,6 +61,7 @@ export class CredentialVaultClient {
|
|
|
59
61
|
this.config = config;
|
|
60
62
|
}
|
|
61
63
|
get configured() { return !!this.config; }
|
|
64
|
+
get executionLocation() { return 'node'; }
|
|
62
65
|
close() { }
|
|
63
66
|
async send(owner, session, command, value) {
|
|
64
67
|
const c = this.config;
|
|
@@ -61,7 +61,6 @@ export class DesktopEnvironments {
|
|
|
61
61
|
auth;
|
|
62
62
|
nodes;
|
|
63
63
|
sessions = new Map();
|
|
64
|
-
authorizing = new Map();
|
|
65
64
|
toolFrames = new WeakMap();
|
|
66
65
|
closed = false;
|
|
67
66
|
constructor(store, auth, nodes) {
|
|
@@ -204,7 +203,18 @@ export class DesktopEnvironments {
|
|
|
204
203
|
agent(owner, id) { const a = this.store.require(owner, 'agent', id); this.nodes.requireSource(owner, a); if (a.archived || a.remoteAgentId)
|
|
205
204
|
throw new HttpError(409, '此机器人无法使用桌面环境', 'computer_unavailable'); return a; }
|
|
206
205
|
resource(owner, agent, mode) { return mode === 'local' ? 'local' : digest(this.ownerKey(owner) + ':' + agent.id + ':' + (agent.browserProfile ?? 'persistent')); }
|
|
207
|
-
hostStates(owner) {
|
|
206
|
+
hostStates(owner) {
|
|
207
|
+
const records = this.store.list('_system', 'desktop-host');
|
|
208
|
+
const states = [...this.sessions.values()];
|
|
209
|
+
for (const record of records)
|
|
210
|
+
if (record.enabled && !states.some(s => s.key === record.id))
|
|
211
|
+
states.push(newHostState(record.id, true));
|
|
212
|
+
return states.filter(s => !records.some(record => record.id === s.key && !record.enabled)).map(s => {
|
|
213
|
+
const online = this.hostOnline(s), info = online ? s.info : undefined;
|
|
214
|
+
return { id: s.key, name: this.label(s) || records.find(record => record.id === s.key)?.name || s.key, platform: info?.platform ?? '', online,
|
|
215
|
+
local: { supported: ['darwin', 'win32'].includes(info?.platform ?? ''), authorized: !!info && info.approved.includes(this.ownerKey(owner)), screen: info?.screen === true, accessibility: info?.accessibility === true, ready: !!info && this.ready(s, owner), fullAuthorized: !!info && (info.full ?? []).includes(this.ownerKey(owner)) }, browser: { available: online } };
|
|
216
|
+
}).sort((a, b) => a.id === 'local' ? -1 : b.id === 'local' ? 1 : a.name.localeCompare(b.name));
|
|
217
|
+
}
|
|
208
218
|
state(owner, agent) { const mode = this.selected(owner, agent), s = this.sessionFor(agent), online = !!s && this.hostOnline(s), info = online ? s.info : undefined; return { online, host: info ? { id: s.key, name: this.label(s), platform: info.platform } : null, local: { supported: ['darwin', 'win32'].includes(info?.platform ?? ''), authorized: !!info && info.approved.includes(this.ownerKey(owner)), screen: info?.screen === true, accessibility: info?.accessibility === true, ready: !!info && this.ready(s, owner), fullAuthorized: !!info && (info.full ?? []).includes(this.ownerKey(owner)) }, browser: { available: online, profile: agent.browserProfile ?? 'persistent' }, selected: mode ?? null, agent: this.store.agentSummary(agent), hosts: this.hostStates(owner) }; }
|
|
209
219
|
/** Every Bot follows the same global desktop policy. */
|
|
210
220
|
modeOpen(owner, agent, mode) { return this.selected(owner, agent) === mode; }
|
|
@@ -473,22 +483,12 @@ export class DesktopEnvironments {
|
|
|
473
483
|
router() {
|
|
474
484
|
const router = new Router();
|
|
475
485
|
router.get('/api/app/agents/:id/desktop-environment', ctx => { const owner = this.auth.require(ctx).id, a = this.store.require(owner, 'agent', ctx.params.id); this.nodes.requireSource(owner, a); ctx.set('Cache-Control', 'no-store'); ctx.body = this.state(owner, a); });
|
|
476
|
-
router.
|
|
477
|
-
|
|
486
|
+
router.get('/api/app/desktop-environment', ctx => { const user = this.auth.require(ctx); this.auth.requireAdmin(ctx); ctx.set('Cache-Control', 'no-store'); ctx.body = { hosts: this.hostStates(user.id) }; });
|
|
487
|
+
router.get('/api/app/desktop-environment/authorization', ctx => { const user = this.auth.require(ctx); this.auth.requireAdmin(ctx); ctx.set('Cache-Control', 'no-store'); ctx.body = { owner: this.ownerKey(user.id), account: user.username }; });
|
|
488
|
+
// Authorization is granted by the current native client, never dispatched to a selected host.
|
|
489
|
+
router.post('/api/app/agents/:id/desktop-environment/authorize', ctx => {
|
|
478
490
|
this.auth.requireAdmin(ctx);
|
|
479
|
-
|
|
480
|
-
const body = parse(z.object({ hostId: z.union([z.literal('local'), z.string().uuid()]).optional(), scope: z.enum(['screen', 'full']).default('screen') }).strict(), ctx.request.body ?? {});
|
|
481
|
-
const s = body.hostId !== undefined ? this.sessions.get(body.hostId) : this.sessionFor(a);
|
|
482
|
-
if (!s || !this.hostOnline(s))
|
|
483
|
-
throw new HttpError(409, '桌面端未连接,请在电脑上打开夭夭。', 'desktop_offline');
|
|
484
|
-
const owner = this.ownerKey(user.id), epoch = s.info.id, authorizeKey = user.id + ':' + s.key + ':' + body.scope;
|
|
485
|
-
let pending = this.authorizing.get(authorizeKey);
|
|
486
|
-
if (!pending) {
|
|
487
|
-
pending = this.command(s, { operation: 'authorize', owner, account: user.username, scope: body.scope }, () => { this.auth.requireAdmin(ctx); if (!this.hostOnline(s) || epoch !== s.info.id)
|
|
488
|
-
throw new HttpError(409, '桌面端已断开', 'desktop_offline'); }, 120000).finally(() => this.authorizing.delete(authorizeKey));
|
|
489
|
-
this.authorizing.set(authorizeKey, pending);
|
|
490
|
-
}
|
|
491
|
-
ctx.body = await pending;
|
|
491
|
+
throw new HttpError(403, '请在需要授权的那台电脑上打开客户端,在 Bot 设置中授权当前设备。', 'desktop_local_authorization_required');
|
|
492
492
|
});
|
|
493
493
|
router.put('/api/app/agents/:id/browser-profile', ctx => { const owner = this.auth.require(ctx).id, a = this.agent(owner, ctx.params.id), body = parse(z.object({ profile: z.enum(['persistent', 'temporary']) }).strict(), ctx.request.body); this.assertIdle(owner, a.id); this.store.updateAgent(owner, a.id, { browserProfile: body.profile }); ctx.body = { ok: true }; });
|
|
494
494
|
router.get('/api/app/agents/:id/browser', async (ctx) => { const owner = this.auth.require(ctx).id, a = this.agent(owner, ctx.params.id); if (this.selected(owner, a) !== 'browser')
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { gzip } from 'node:zlib';
|
|
2
|
+
import { promisify } from 'node:util';
|
|
3
|
+
const compress = promisify(gzip);
|
|
4
|
+
/** Compress completed API documents only; SSE must flush each event unchanged. */
|
|
5
|
+
export const jsonCompression = async (ctx, next) => {
|
|
6
|
+
await next();
|
|
7
|
+
if (!ctx.path.startsWith('/api/') || ctx.method === 'HEAD' || ctx.status !== 200
|
|
8
|
+
|| ctx.respond === false || ctx.res.headersSent || !ctx.response.is('application/json')
|
|
9
|
+
|| ctx.response.get('Content-Encoding') || ctx.body == null)
|
|
10
|
+
return;
|
|
11
|
+
const value = ctx.body;
|
|
12
|
+
if (!Buffer.isBuffer(value) && typeof value !== 'string' && typeof value !== 'object')
|
|
13
|
+
return;
|
|
14
|
+
if (typeof value === 'object' && !Buffer.isBuffer(value) && 'pipe' in value)
|
|
15
|
+
return;
|
|
16
|
+
const body = Buffer.isBuffer(value) ? value : Buffer.from(typeof value === 'string' ? value : JSON.stringify(value));
|
|
17
|
+
if (body.length < 1024)
|
|
18
|
+
return;
|
|
19
|
+
ctx.vary('Accept-Encoding');
|
|
20
|
+
if (ctx.acceptsEncodings('gzip', 'identity') !== 'gzip')
|
|
21
|
+
return;
|
|
22
|
+
const compressed = await compress(body);
|
|
23
|
+
if (compressed.length >= body.length)
|
|
24
|
+
return;
|
|
25
|
+
ctx.set('Content-Encoding', 'gzip');
|
|
26
|
+
ctx.remove('Content-Length');
|
|
27
|
+
ctx.body = compressed;
|
|
28
|
+
ctx.type = 'application/json';
|
|
29
|
+
};
|
|
@@ -147,7 +147,7 @@ function requireLocalSystemUpdate(ctx, dependencies) {
|
|
|
147
147
|
}
|
|
148
148
|
function updateFailure(error) {
|
|
149
149
|
const message = error instanceof Error ? error.message : String(error);
|
|
150
|
-
if (
|
|
150
|
+
if (/最新版本|目标版本|正在执行|可回滚|不支持|没有可生效|已准备更新/.test(message)) {
|
|
151
151
|
return new HttpError(409, message, 'system_update_conflict');
|
|
152
152
|
}
|
|
153
153
|
return new HttpError(502, `无法访问系统发布源:${message}`, 'system_update_source_failed');
|
|
@@ -1889,6 +1889,19 @@ export function createApiRouter(dependencies) {
|
|
|
1889
1889
|
throw updateFailure(error);
|
|
1890
1890
|
}
|
|
1891
1891
|
});
|
|
1892
|
+
router.post('/api/app/system/update/activate', (ctx) => {
|
|
1893
|
+
dependencies.auth.requireAdmin(ctx);
|
|
1894
|
+
requireLocalSystemUpdate(ctx, dependencies);
|
|
1895
|
+
const jobID = body(ctx).jobID;
|
|
1896
|
+
if (typeof jobID !== 'string' || !/^[0-9a-f-]{36}$/.test(jobID))
|
|
1897
|
+
throw new HttpError(400, 'jobID 无效', 'invalid_request');
|
|
1898
|
+
try {
|
|
1899
|
+
json(ctx, 202, dependencies.updates.startActivation(jobID));
|
|
1900
|
+
}
|
|
1901
|
+
catch (error) {
|
|
1902
|
+
throw updateFailure(error);
|
|
1903
|
+
}
|
|
1904
|
+
});
|
|
1892
1905
|
router.get('/api/app/system/update/jobs/:jobID', async (ctx) => {
|
|
1893
1906
|
dependencies.auth.requireAdmin(ctx);
|
|
1894
1907
|
const job = dependencies.updates.job(ctx.params.jobID);
|