@lsamien/yaoyao 0.4.79 → 0.4.81
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/THIRD_PARTY_NOTICES.md +4 -0
- 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 +22 -3
- package/desktop/main.mjs +28 -26
- package/dist/assets/{AboutDialog-CrajAC--.js → AboutDialog-g6pYSCjs.js} +2 -2
- package/dist/assets/{AboutDialog-CrajAC--.js.map → AboutDialog-g6pYSCjs.js.map} +1 -1
- package/dist/assets/{BotAutomationsView-DTOoFSEl.js → BotAutomationsView-D1qf-5yf.js} +2 -2
- package/dist/assets/{BotAutomationsView-DTOoFSEl.js.map → BotAutomationsView-D1qf-5yf.js.map} +1 -1
- package/dist/assets/BotPluginsDialog-B0iR4Jy2.css +1 -0
- package/dist/assets/BotPluginsDialog-BOSzPlLZ.js +2 -0
- package/dist/assets/BotPluginsDialog-BOSzPlLZ.js.map +1 -0
- package/dist/assets/{BotSettingsDialog-ChffrjSM.js → BotSettingsDialog-Ba-380qV.js} +4 -4
- package/dist/assets/{BotSettingsDialog-ChffrjSM.js.map → BotSettingsDialog-Ba-380qV.js.map} +1 -1
- package/dist/assets/ChatView-ClK12dmT.css +1 -0
- package/dist/assets/ChatView-DHyj3yzu.js +2 -0
- package/dist/assets/ChatView-DHyj3yzu.js.map +1 -0
- package/dist/assets/{ComputerPanel-bNkvZAiT.js → ComputerPanel-D1hglwwV.js} +2 -2
- package/dist/assets/{ComputerPanel-bNkvZAiT.js.map → ComputerPanel-D1hglwwV.js.map} +1 -1
- package/dist/assets/{ComputerViewerView-DCTvbHr-.js → ComputerViewerView-BDL1eNKT.js} +2 -2
- package/dist/assets/{ComputerViewerView-DCTvbHr-.js.map → ComputerViewerView-BDL1eNKT.js.map} +1 -1
- package/dist/assets/{ConversationsView-BnysxvX_.js → ConversationsView-BaWBEaBU.js} +5 -5
- package/dist/assets/{ConversationsView-BnysxvX_.js.map → ConversationsView-BaWBEaBU.js.map} +1 -1
- package/dist/assets/{ConversationsView-CbArO1v2.css → ConversationsView-CdPjaDik.css} +1 -1
- package/dist/assets/{FilesView-D7tA6Nu1.js → FilesView-AjaCIyCs.js} +2 -2
- package/dist/assets/{FilesView-D7tA6Nu1.js.map → FilesView-AjaCIyCs.js.map} +1 -1
- package/dist/assets/FloatingResourceSearch-CeLuyNWO.js +9 -0
- package/dist/assets/{FloatingResourceSearch-c6l1JuAA.js.map → FloatingResourceSearch-CeLuyNWO.js.map} +1 -1
- package/dist/assets/{FloatingResourceSearch-3GOuDkuO.css → FloatingResourceSearch-CqauCQAf.css} +1 -1
- package/dist/assets/{HistoryView-Cnsriop4.js → HistoryView-C96yRoyB.js} +2 -2
- package/dist/assets/{HistoryView-Cnsriop4.js.map → HistoryView-C96yRoyB.js.map} +1 -1
- package/dist/assets/{KanbanView-CXm05b62.js → KanbanView-CVbjfqiX.js} +2 -2
- package/dist/assets/{KanbanView-CXm05b62.js.map → KanbanView-CVbjfqiX.js.map} +1 -1
- package/dist/assets/{LocalVmSettingsPanel-HgNC1SCF.js → LocalVmSettingsPanel-DcDIRVsO.js} +2 -2
- package/dist/assets/{LocalVmSettingsPanel-HgNC1SCF.js.map → LocalVmSettingsPanel-DcDIRVsO.js.map} +1 -1
- package/dist/assets/{RunnerSettingsPanel-CLKZvWua.js → RunnerSettingsPanel-XYeXVx5y.js} +2 -2
- package/dist/assets/{RunnerSettingsPanel-CLKZvWua.js.map → RunnerSettingsPanel-XYeXVx5y.js.map} +1 -1
- package/dist/assets/{StandaloneDialog-DODllzh1.js → StandaloneDialog-C6HIM_jc.js} +2 -2
- package/dist/assets/{StandaloneDialog-DODllzh1.js.map → StandaloneDialog-C6HIM_jc.js.map} +1 -1
- package/dist/assets/{UpdateCheckDialog-DHcAuryL.js → UpdateCheckDialog-Dv1d1s42.js} +2 -2
- package/dist/assets/{UpdateCheckDialog-DHcAuryL.js.map → UpdateCheckDialog-Dv1d1s42.js.map} +1 -1
- package/dist/assets/{WorkspaceKnowledgePanel-BrE8xSi2.js → WorkspaceKnowledgePanel-Dnauu0Hw.js} +2 -2
- package/dist/assets/{WorkspaceKnowledgePanel-BrE8xSi2.js.map → WorkspaceKnowledgePanel-Dnauu0Hw.js.map} +1 -1
- package/dist/assets/{WorkspaceRoutinesPanel-CpDVEwHx.js → WorkspaceRoutinesPanel-WNI3qP4D.js} +2 -2
- package/dist/assets/{WorkspaceRoutinesPanel-CpDVEwHx.js.map → WorkspaceRoutinesPanel-WNI3qP4D.js.map} +1 -1
- package/dist/assets/WorkspaceShell-BT92dIOL.css +1 -0
- package/dist/assets/WorkspaceShell-Bl2QMnvN.js +44 -0
- package/dist/assets/WorkspaceShell-Bl2QMnvN.js.map +1 -0
- package/dist/assets/{WorkspaceView-CBWFRLki.js → WorkspaceView-Dhdw4Kml.js} +2 -2
- package/dist/assets/{WorkspaceView-CBWFRLki.js.map → WorkspaceView-Dhdw4Kml.js.map} +1 -1
- package/dist/assets/{docx-preview-CG4CK2Qm.js → docx-preview-BNRkFvPc.js} +2 -2
- package/dist/assets/{docx-preview-CG4CK2Qm.js.map → docx-preview-BNRkFvPc.js.map} +1 -1
- package/dist/assets/{index-BRP9NWum.js → index-DU4OTLup.js} +3 -3
- package/dist/assets/{index-BRP9NWum.js.map → index-DU4OTLup.js.map} +1 -1
- package/dist/assets/{pdf-CFWXmhVF.js → pdf-C6_9GF5Z.js} +2 -2
- package/dist/assets/{pdf-CFWXmhVF.js.map → pdf-C6_9GF5Z.js.map} +1 -1
- package/dist/assets/{sessionOwnership-B2YxdBdf.js → sessionOwnership-D9vGe33s.js} +2 -2
- package/dist/assets/{sessionOwnership-B2YxdBdf.js.map → sessionOwnership-D9vGe33s.js.map} +1 -1
- package/dist/assets/{viewModels-CYJ8m5Uf.js → viewModels-BLN4GfVX.js} +5 -5
- package/dist/assets/viewModels-BLN4GfVX.js.map +1 -0
- package/dist/index.html +1 -1
- package/dist/provider-logos/airtable.svg +13 -0
- package/dist/provider-logos/discord.svg +15 -0
- package/dist/provider-logos/github.svg +10 -0
- package/dist/provider-logos/gmail.svg +1 -0
- package/dist/provider-logos/googlecalendar.svg +148 -0
- package/dist/provider-logos/googledrive.svg +25 -0
- package/dist/provider-logos/linear.svg +5 -0
- package/dist/provider-logos/notion.svg +11 -0
- package/dist/provider-logos/outlook.svg +76 -0
- package/dist/provider-logos/slack.svg +22 -0
- package/dist/provider-logos/trello.svg +19 -0
- package/dist/provider-logos/twitter.svg +128 -0
- package/dist-server/server/app.js +4 -2
- package/dist-server/server/botPlugins/connectedApps.js +3 -2
- 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 +109 -14
- package/dist-server/server/credentialVault/localClient.js +191 -0
- 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 +5 -1
- package/dist-server/server/dashboardCommand.js +62 -0
- package/dist-server/server/dashboardController.js +117 -25
- package/dist-server/server/jsonCompression.js +29 -0
- package/dist-server/server/routes.js +19 -1
- package/dist-server/server/runnerHub.js +12 -1
- package/dist-server/server/security.js +2 -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/botProviderLogos.js +61 -0
- package/dist-server/shared/desktopUpdate.js +1 -0
- package/package.json +1 -1
- package/release.json +3 -3
- package/dist/assets/BotPluginsDialog-Ckiwmito.js +0 -2
- package/dist/assets/BotPluginsDialog-Ckiwmito.js.map +0 -1
- package/dist/assets/BotPluginsDialog-Db5dTqvg.css +0 -1
- package/dist/assets/ChatView-C_7_7olu.css +0 -1
- package/dist/assets/ChatView-znZF8RZE.js +0 -2
- package/dist/assets/ChatView-znZF8RZE.js.map +0 -1
- package/dist/assets/FloatingResourceSearch-c6l1JuAA.js +0 -9
- package/dist/assets/WorkspaceShell-Dhm3r61t.js +0 -44
- package/dist/assets/WorkspaceShell-Dhm3r61t.js.map +0 -1
- package/dist/assets/WorkspaceShell-Dk003lIq.css +0 -1
- package/dist/assets/viewModels-CYJ8m5Uf.js.map +0 -1
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
4
|
+
import { CredentialVaultClient } from './transport.js';
|
|
5
|
+
import { CredentialVaultStore } from './store.js';
|
|
6
|
+
import { CredentialVaultBroker } from './broker.js';
|
|
7
|
+
import { HttpError } from '../errors.js';
|
|
8
|
+
import { acquireServiceInstance } from '../serviceInstance.js';
|
|
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. */
|
|
14
|
+
export class LocalCredentialVaultClient extends CredentialVaultClient {
|
|
15
|
+
home;
|
|
16
|
+
testCA;
|
|
17
|
+
controlEpoch = randomUUID();
|
|
18
|
+
broker;
|
|
19
|
+
instance;
|
|
20
|
+
executor;
|
|
21
|
+
closed = false;
|
|
22
|
+
botAccess;
|
|
23
|
+
constructor(home, testCA) {
|
|
24
|
+
super();
|
|
25
|
+
this.home = home;
|
|
26
|
+
this.testCA = testCA;
|
|
27
|
+
}
|
|
28
|
+
get configured() { return true; }
|
|
29
|
+
get executionLocation() { return 'server'; }
|
|
30
|
+
async call(owner, session, command, value) {
|
|
31
|
+
if (this.closed)
|
|
32
|
+
throw new HttpError(503, '密码保险箱已关闭', 'vault_offline');
|
|
33
|
+
this.broker ??= CredentialVaultStore.create(join(this.home, 'credential-vault')).then(store => {
|
|
34
|
+
if (this.closed)
|
|
35
|
+
throw new Error('closed');
|
|
36
|
+
this.instance = acquireServiceInstance(store.root, 'credential-vault-v1');
|
|
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);
|
|
40
|
+
broker.hello(this.controlEpoch);
|
|
41
|
+
return broker;
|
|
42
|
+
}).catch(() => {
|
|
43
|
+
this.botAccess?.close();
|
|
44
|
+
this.botAccess = undefined;
|
|
45
|
+
this.executor?.close();
|
|
46
|
+
this.executor = undefined;
|
|
47
|
+
this.instance?.release();
|
|
48
|
+
this.instance = undefined;
|
|
49
|
+
this.broker = undefined;
|
|
50
|
+
throw new HttpError(503, '无法打开本机密码保险箱,请检查数据目录权限或是否已被其他服务使用', 'vault_offline');
|
|
51
|
+
});
|
|
52
|
+
const broker = await this.broker;
|
|
53
|
+
if (this.closed)
|
|
54
|
+
throw new HttpError(503, '密码保险箱已关闭', 'vault_offline');
|
|
55
|
+
try {
|
|
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);
|
|
112
|
+
return ['status', 'initialize', 'unlock', 'restore'].includes(command)
|
|
113
|
+
? { ...result, storageMode: 'local', botGrants: this.botAccess.summaries(owner) }
|
|
114
|
+
: result;
|
|
115
|
+
}
|
|
116
|
+
catch (error) {
|
|
117
|
+
if (error instanceof HttpError)
|
|
118
|
+
throw error;
|
|
119
|
+
broker.disconnect();
|
|
120
|
+
this.onDisconnect();
|
|
121
|
+
throw new HttpError(409, '密码保险箱操作未完成,请刷新状态后重新解锁', 'vault_request_failed');
|
|
122
|
+
}
|
|
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); }
|
|
171
|
+
close() {
|
|
172
|
+
this.closed = true;
|
|
173
|
+
void this.broker?.then(broker => {
|
|
174
|
+
try {
|
|
175
|
+
broker.close();
|
|
176
|
+
}
|
|
177
|
+
finally {
|
|
178
|
+
this.botAccess?.close();
|
|
179
|
+
this.botAccess = undefined;
|
|
180
|
+
this.executor?.close();
|
|
181
|
+
this.executor = undefined;
|
|
182
|
+
this.instance?.release();
|
|
183
|
+
this.instance = undefined;
|
|
184
|
+
}
|
|
185
|
+
}).catch(() => { });
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
export function createCredentialVaultClient(config, home) {
|
|
189
|
+
// An unavailable explicit deployment must never fall back to a different vault.
|
|
190
|
+
return config ? new CredentialVaultClient(config) : new LocalCredentialVaultClient(home);
|
|
191
|
+
}
|
|
@@ -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,8 @@ export class CredentialVaultClient {
|
|
|
59
61
|
this.config = config;
|
|
60
62
|
}
|
|
61
63
|
get configured() { return !!this.config; }
|
|
64
|
+
get executionLocation() { return 'node'; }
|
|
65
|
+
close() { }
|
|
62
66
|
async send(owner, session, command, value) {
|
|
63
67
|
const c = this.config;
|
|
64
68
|
if (!c)
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { basename, dirname, isAbsolute } from 'node:path';
|
|
2
|
+
const profile = /^[a-z0-9][a-z0-9_-]{0,63}$/;
|
|
3
|
+
/** Recognize Hermes' executable, script and module entry points, including serve. */
|
|
4
|
+
export function dashboardCommandIndex(args) {
|
|
5
|
+
let index;
|
|
6
|
+
const executable = basename(args[0] ?? '');
|
|
7
|
+
if (executable === 'hermes')
|
|
8
|
+
index = 1;
|
|
9
|
+
else if (/^python(?:\d+(?:\.\d+)*)?$/i.test(executable)) {
|
|
10
|
+
const script = args[1] ?? '';
|
|
11
|
+
if (basename(script) === 'hermes' || (basename(script) === 'main.py' && basename(dirname(script)) === 'hermes_cli'))
|
|
12
|
+
index = 2;
|
|
13
|
+
else if (script === '-m' && args[2] === 'hermes_cli.main')
|
|
14
|
+
index = 3;
|
|
15
|
+
else
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
else
|
|
19
|
+
return;
|
|
20
|
+
if (args[index] === '--profile' || args[index] === '-p') {
|
|
21
|
+
if (!profile.test(args[index + 1] ?? ''))
|
|
22
|
+
return;
|
|
23
|
+
index += 2;
|
|
24
|
+
}
|
|
25
|
+
else if (args[index]?.startsWith('--profile=')) {
|
|
26
|
+
if (!profile.test(args[index].slice(10)))
|
|
27
|
+
return;
|
|
28
|
+
index++;
|
|
29
|
+
}
|
|
30
|
+
else if (profile.test(args[index] ?? '') && ['dashboard', 'serve'].includes(args[index + 1] ?? ''))
|
|
31
|
+
index++;
|
|
32
|
+
return ['dashboard', 'serve'].includes(args[index] ?? '') ? index : undefined;
|
|
33
|
+
}
|
|
34
|
+
/** ps does not preserve argv boundaries. Only simple, bounded runtime flags can
|
|
35
|
+
* be replayed; shell wrappers, SSH backends and ambiguous paths are rejected. */
|
|
36
|
+
export function standaloneDashboardCommand(command) {
|
|
37
|
+
if (command.length > 8192 || /[\n\r'"\\]/.test(command))
|
|
38
|
+
return;
|
|
39
|
+
const args = command.trim().split(/\s+/), index = dashboardCommandIndex(args);
|
|
40
|
+
if (index === undefined || !isAbsolute(args[0]) || args.length > 32)
|
|
41
|
+
return;
|
|
42
|
+
if (index >= 2 && args[1] !== '-m' && !isAbsolute(args[1]))
|
|
43
|
+
return;
|
|
44
|
+
for (let i = index + 1; i < args.length; i++) {
|
|
45
|
+
const flag = args[i];
|
|
46
|
+
if (['--no-open', '--skip-build', '--insecure', '--isolated'].includes(flag))
|
|
47
|
+
continue;
|
|
48
|
+
const match = /^(--host|--port|--profile)(?:=(.*))?$/.exec(flag);
|
|
49
|
+
if (!match)
|
|
50
|
+
return;
|
|
51
|
+
const value = match[2] ?? args[++i];
|
|
52
|
+
if (!value)
|
|
53
|
+
return;
|
|
54
|
+
if (match[1] === '--host' && !['127.0.0.1', 'localhost', '0.0.0.0', '::', '::1'].includes(value))
|
|
55
|
+
return;
|
|
56
|
+
if (match[1] === '--port' && value !== '9119')
|
|
57
|
+
return;
|
|
58
|
+
if (match[1] === '--profile' && !profile.test(value))
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
return { command: args[0], args: args.slice(1) };
|
|
62
|
+
}
|