dsh-desktop-kit 2.24.0 → 2.30.0
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/CHANGELOG.md +74 -6
- package/README.md +192 -291
- package/client.js +1 -1
- package/cordis.patch.yml +5 -151
- package/docs/ARCHITECTURE.md +10 -16
- package/docs/COMPATIBILITY.md +1 -1
- package/docs/DEVELOPMENT.md +0 -1
- package/docs/PROPOSAL-2.25-quality-pipeline.md +435 -0
- package/docs/PROPOSAL-NEXUM-FINDINGS.md +259 -0
- package/docs/TEST-2.24.1.md +66 -0
- package/docs/TEST-2.30.0.md +83 -0
- package/docs/images/capability-map-2.30.png +0 -0
- package/docs/images/hero-2.30.png +0 -0
- package/docs/images/quality-pipeline-2.30.png +0 -0
- package/docs/preview/capability-map-2.30.html +106 -0
- package/docs/preview/hero-2.30.html +133 -0
- package/docs/preview/quality-pipeline-2.30.html +142 -0
- package/docs/preview/readme-visuals.css +111 -0
- package/index.js +6 -0
- package/package.json +11 -4
- package/plugins/dsh-agent-extensions/lib/routing.js +4 -0
- package/plugins/dsh-agent-extensions/lib/scaffold.js +152 -27
- package/plugins/dsh-agent-extensions/lib/settings.js +19 -0
- package/plugins/dsh-agent-extensions/lib/swarm.js +6 -2
- package/plugins/dsh-browser-qa/index.js +202 -9
- package/plugins/dsh-browser-qa/lib/design-more.js +688 -0
- package/plugins/dsh-browser-qa/lib/extras.js +1313 -0
- package/plugins/dsh-browser-qa/lib/pages.js +4 -3
- package/plugins/dsh-browser-qa/lib/png.js +190 -0
- package/plugins/dsh-browser-qa/lib/ui-gate.js +171 -31
- package/plugins/dsh-i18n/README.md +36 -0
- package/plugins/dsh-i18n/cordis.patch.yml +3 -0
- package/plugins/dsh-i18n/index.js +294 -0
- package/plugins/dsh-i18n/lib/lang.js +179 -0
- package/plugins/dsh-i18n/package.json +29 -0
- package/plugins/dsh-quality-pipeline/README.md +53 -0
- package/plugins/dsh-quality-pipeline/cordis.patch.yml +3 -0
- package/plugins/dsh-quality-pipeline/index.js +647 -0
- package/plugins/dsh-quality-pipeline/lib/acceptance.js +132 -0
- package/plugins/dsh-quality-pipeline/lib/autostart.js +159 -0
- package/plugins/dsh-quality-pipeline/lib/design.js +123 -0
- package/plugins/dsh-quality-pipeline/lib/machine.js +312 -0
- package/plugins/dsh-quality-pipeline/lib/prework.js +215 -0
- package/plugins/dsh-quality-pipeline/lib/release.js +53 -0
- package/plugins/dsh-quality-pipeline/lib/schema.js +256 -0
- package/plugins/dsh-quality-pipeline/lib/store.js +114 -0
- package/plugins/dsh-quality-pipeline/lib/text.js +109 -0
- package/plugins/dsh-quality-pipeline/package.json +33 -0
- package/plugins/dsh-remote-ops/README.md +38 -0
- package/plugins/dsh-remote-ops/cordis.patch.yml +3 -0
- package/plugins/dsh-remote-ops/index.js +268 -0
- package/plugins/dsh-remote-ops/lib/hosts.js +118 -0
- package/plugins/dsh-remote-ops/lib/ssh.js +96 -0
- package/plugins/dsh-remote-ops/lib/state.js +66 -0
- package/plugins/dsh-remote-ops/package.json +31 -0
- package/plugins/dsh-skill-autopilot/index.js +204 -15
- package/skills/a11y-audit/SKILL.md +67 -0
- package/skills/cms-ops/SKILL.md +74 -0
- package/skills/design-system/SKILL.md +100 -0
- package/skills/legal-ru-web/SKILL.md +68 -0
- package/skills/manifest.json +38 -18
- package/skills/release-pipeline/SKILL.md +67 -0
- package/skills/ui-batch/SKILL.md +60 -0
- package/skills/web-build/SKILL.md +106 -0
- package/skills/web-build/recipes/form.md +16 -0
- package/skills/web-build/recipes/payment.md +16 -0
- package/skills/web-build/recipes/review.md +16 -0
- package/skills-baseline.json +192 -0
- package/docs/TEST-2.24.0.md +0 -123
- package/skills/ui-design-system/references/accessibility-and-responsive.md +0 -50
- package/skills/ui-design-system/references/tokens-and-components.md +0 -67
- package/skills/ui-design-system/references/visual-qa.md +0 -44
- package/skills/visual-qa/references/commands.md +0 -32
- /package/skills/{ui-craft/SKILL.md → design-system/references/ui-craft.md} +0 -0
- /package/skills/{ui-design-system/SKILL.md → design-system/references/ui-design-system.md} +0 -0
- /package/skills/{visual-qa/SKILL.md → ui-batch/references/visual-qa.md} +0 -0
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-remote-ops — typed ssh/scp for DSH agents.
|
|
3
|
+
*
|
|
4
|
+
* Replaces hand-built `sandbox_run ssh …` chains: hosts are declared in
|
|
5
|
+
* `.dsh/hosts.json`, commands are argv (no shell on our side), destructive
|
|
6
|
+
* commands need `confirm=true`, and the result is written to the quality
|
|
7
|
+
* evidence log. `sync` copies only files whose sha256 differs.
|
|
8
|
+
*/
|
|
9
|
+
import fs from "node:fs";
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
|
|
12
|
+
import { hostByName, isDestructive, readHosts, splitCommand } from "./lib/hosts.js";
|
|
13
|
+
import { copyFile, listLocal, runRemote, DEFAULT_TIMEOUT_MS } from "./lib/ssh.js";
|
|
14
|
+
import { diffState, formatDiff, formatState, parseState, probeScript } from "./lib/state.js";
|
|
15
|
+
|
|
16
|
+
export const inject = ["tools"];
|
|
17
|
+
|
|
18
|
+
const TOOL_NAME = "remote_ops";
|
|
19
|
+
const ACTIONS = ["hosts", "run", "dry-run", "sync", "state", "diff", "logs"];
|
|
20
|
+
const MAX_COPY = 50;
|
|
21
|
+
|
|
22
|
+
function sessionCwd(exec) {
|
|
23
|
+
const cwd = exec?.agent?.session?.header?.cwd;
|
|
24
|
+
return typeof cwd === "string" && cwd.length > 0 ? cwd : process.cwd();
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function appendEvidence(cwd, record) {
|
|
28
|
+
try {
|
|
29
|
+
const dir = path.join(cwd, ".dsh", "quality");
|
|
30
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
31
|
+
fs.appendFileSync(
|
|
32
|
+
path.join(dir, "evidence.jsonl"),
|
|
33
|
+
`${JSON.stringify({ at: new Date().toISOString(), ...record, note: String(record?.note ?? "").slice(0, 600) })}\n`,
|
|
34
|
+
"utf8",
|
|
35
|
+
);
|
|
36
|
+
} catch {
|
|
37
|
+
/* evidence must never break a tool call */
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function fail(text) {
|
|
42
|
+
return { ok: false, text };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function readState(host, options = {}) {
|
|
46
|
+
const result = await runRemote(host, ["sh", "-lc", probeScript(host)], options);
|
|
47
|
+
const state = parseState(result.output);
|
|
48
|
+
return { ...result, state };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function parseHostList(value) {
|
|
52
|
+
return String(value ?? "")
|
|
53
|
+
.split(",")
|
|
54
|
+
.map((item) => item.trim())
|
|
55
|
+
.filter(Boolean);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async function actionHosts(cwd) {
|
|
59
|
+
const { hosts, error } = readHosts(cwd);
|
|
60
|
+
const names = Object.keys(hosts);
|
|
61
|
+
if (names.length === 0) {
|
|
62
|
+
return {
|
|
63
|
+
ok: false,
|
|
64
|
+
text: `${error || "хостов нет"}. Создайте .dsh/hosts.json:\n${JSON.stringify({ hosts: { prod: { host: "1.2.3.4", user: "root", key: "~/.ssh/id_vps", root: "/var/www/cms" } } }, null, 2)}`,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
const lines = names.map((name) => {
|
|
68
|
+
const host = hosts[name];
|
|
69
|
+
return ` ${name}: ${host.user}@${host.host}:${host.port}${host.root ? ` · root=${host.root}` : ""}${host.key ? " · key=set" : " · key=(ssh-agent)"}`;
|
|
70
|
+
});
|
|
71
|
+
return { ok: true, hosts: Object.keys(hosts), text: `Хосты (${names.length}):\n${lines.join("\n")}` };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async function actionRun(cwd, args, dryRun) {
|
|
75
|
+
const resolved = hostByName(cwd, args?.host);
|
|
76
|
+
if (!resolved.ok) return fail(resolved.error);
|
|
77
|
+
const host = resolved.host;
|
|
78
|
+
const split = splitCommand(args?.command);
|
|
79
|
+
if (!split.ok) return fail(`команда: ${split.reason}`);
|
|
80
|
+
const destructive = isDestructive(args?.command);
|
|
81
|
+
if (destructive && args?.confirm !== true) {
|
|
82
|
+
return fail(`команда выглядит деструктивной (${args?.command}). Повторите с confirm=true — действие попадёт в evidence.`);
|
|
83
|
+
}
|
|
84
|
+
if (dryRun) {
|
|
85
|
+
return {
|
|
86
|
+
ok: true,
|
|
87
|
+
dryRun: true,
|
|
88
|
+
text: `dry-run: ssh ${host.user}@${host.host}:${host.port}${destructive ? " [деструктивная]" : ""}\n ${split.argv.join(" ")}`,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
const result = await runRemote(host, split.argv, { timeoutMs: Number(args?.timeoutMs) || undefined });
|
|
92
|
+
appendEvidence(cwd, {
|
|
93
|
+
kind: "remote:run",
|
|
94
|
+
gate: "G13",
|
|
95
|
+
value: result.ok ? "ok" : `exit ${result.code}`,
|
|
96
|
+
note: `${args?.host}: ${args?.command}`,
|
|
97
|
+
});
|
|
98
|
+
return {
|
|
99
|
+
ok: result.ok,
|
|
100
|
+
code: result.code,
|
|
101
|
+
output: result.output,
|
|
102
|
+
text: `${result.ok ? "OK" : `FAIL (${result.code})`} ${args?.host}: ${args?.command}\n${result.output || "(пусто)"}`,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function actionState(cwd, args) {
|
|
107
|
+
const names = parseHostList(args?.host) ?? [];
|
|
108
|
+
if (names.length === 0) return fail("нужно host=prod (или hosts=prod,demo через action=diff)");
|
|
109
|
+
const rows = [];
|
|
110
|
+
for (const name of names) {
|
|
111
|
+
const resolved = hostByName(cwd, name);
|
|
112
|
+
if (!resolved.ok) return fail(resolved.error);
|
|
113
|
+
const result = await readState(resolved.host, { timeoutMs: Number(args?.timeoutMs) || undefined });
|
|
114
|
+
if (!result.ok) return { ok: false, text: `state ${name}: FAIL (${result.code})\n${result.output}` };
|
|
115
|
+
rows.push(formatState(name, result.state));
|
|
116
|
+
appendEvidence(cwd, { kind: "remote:state", value: name, note: Object.entries(result.state).map(([k, v]) => `${k}=${v}`).join(" ") });
|
|
117
|
+
}
|
|
118
|
+
return { ok: true, text: rows.join("\n") };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async function actionDiff(cwd, args) {
|
|
122
|
+
const names = parseHostList(args?.hosts ?? args?.host);
|
|
123
|
+
if (names.length !== 2) return fail("нужно hosts=prod,demo (ровно два)");
|
|
124
|
+
const states = {};
|
|
125
|
+
for (const name of names) {
|
|
126
|
+
const resolved = hostByName(cwd, name);
|
|
127
|
+
if (!resolved.ok) return fail(resolved.error);
|
|
128
|
+
const result = await readState(resolved.host);
|
|
129
|
+
if (!result.ok) return { ok: false, text: `state ${name}: FAIL (${result.code})\n${result.output}` };
|
|
130
|
+
states[name] = result.state;
|
|
131
|
+
}
|
|
132
|
+
const rows = diffState(states[names[0]], states[names[1]], names[0], names[1]);
|
|
133
|
+
const text = formatDiff(rows, names[0], names[1]);
|
|
134
|
+
appendEvidence(cwd, { kind: "remote:diff", value: `${rows.length} расхождений`, note: `${names[0]} ↔ ${names[1]}` });
|
|
135
|
+
return { ok: rows.length === 0, rows, text };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function actionLogs(cwd, args) {
|
|
139
|
+
const resolved = hostByName(cwd, args?.host);
|
|
140
|
+
if (!resolved.ok) return fail(resolved.error);
|
|
141
|
+
const unit = String(args?.unit ?? "php8.5-fpm");
|
|
142
|
+
const lines = Math.max(10, Math.min(500, Number(args?.lines) || 80));
|
|
143
|
+
const result = await runRemote(resolved.host, ["journalctl", "-u", unit, "-n", String(lines), "--no-pager"], { timeoutMs: 60_000 });
|
|
144
|
+
return {
|
|
145
|
+
ok: result.ok,
|
|
146
|
+
text: `${result.ok ? "OK" : `FAIL (${result.code})`} journalctl -u ${unit} -n ${lines}\n${result.output}`,
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
async function remoteList(host, dir) {
|
|
151
|
+
const result = await runRemote(host, ["sh", "-lc", `cd ${JSON.stringify(dir)} 2>/dev/null && find . -type f -exec sha256sum {} +`], { timeoutMs: 90_000 });
|
|
152
|
+
if (!result.ok) return { ok: false, error: result.output, files: [] };
|
|
153
|
+
const files = [];
|
|
154
|
+
for (const line of result.output.split("\n")) {
|
|
155
|
+
const at = line.indexOf(" ");
|
|
156
|
+
if (at !== 64) continue;
|
|
157
|
+
const hash = line.slice(0, 64);
|
|
158
|
+
const rel = line.slice(at + 2).replace(/^\.\//u, "").trim();
|
|
159
|
+
if (!rel) continue;
|
|
160
|
+
files.push({ rel, hash });
|
|
161
|
+
}
|
|
162
|
+
return { ok: true, error: "", files };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async function actionSync(cwd, args) {
|
|
166
|
+
const resolved = hostByName(cwd, args?.host);
|
|
167
|
+
if (!resolved.ok) return fail(resolved.error);
|
|
168
|
+
const host = resolved.host;
|
|
169
|
+
const from = String(args?.from ?? "").trim();
|
|
170
|
+
const to = String(args?.to ?? "").trim();
|
|
171
|
+
if (!from || !to) return fail("нужны from=<локальная папка> и to=<папка на сервере>");
|
|
172
|
+
const localDir = path.isAbsolute(from) ? from : path.join(cwd, from);
|
|
173
|
+
const local = listLocal(localDir);
|
|
174
|
+
if (local.length === 0) return fail(`локально пусто: ${localDir}`);
|
|
175
|
+
const remote = await remoteList(host, to);
|
|
176
|
+
if (!remote.ok) return { ok: false, text: `не удалось прочитать ${to} на ${args?.host}:\n${remote.error}` };
|
|
177
|
+
const remoteMap = new Map(remote.files.map((file) => [file.rel, file.hash]));
|
|
178
|
+
const changed = local.filter((file) => remoteMap.get(file.rel) !== file.hash);
|
|
179
|
+
const head = [
|
|
180
|
+
`sync ${args?.host}: ${local.length} файлов локально · ${remote.files.length} на сервере · к копированию ${changed.length}`,
|
|
181
|
+
...changed.slice(0, 20).map((file) => ` ${remoteMap.has(file.rel) ? "changed" : "new"} ${file.rel} (${file.size} B)`),
|
|
182
|
+
].join("\n");
|
|
183
|
+
if (args?.apply !== true) {
|
|
184
|
+
return { ok: true, changed: changed.length, text: `${head}\nКопирование не выполнялось: повторите с apply=true.` };
|
|
185
|
+
}
|
|
186
|
+
if (changed.length > MAX_COPY) return fail(`слишком много файлов (${changed.length} > ${MAX_COPY}); укажите более узкую папку`);
|
|
187
|
+
const failures = [];
|
|
188
|
+
for (const file of changed) {
|
|
189
|
+
const target = `${to.replace(/\/$/u, "")}/${file.rel}`;
|
|
190
|
+
const copied = await copyFile(host, path.join(localDir, file.rel), target);
|
|
191
|
+
if (!copied.ok) failures.push(`${file.rel}: ${copied.error || copied.code}`);
|
|
192
|
+
}
|
|
193
|
+
appendEvidence(cwd, {
|
|
194
|
+
kind: "remote:sync",
|
|
195
|
+
gate: "G13",
|
|
196
|
+
value: failures.length === 0 ? `${changed.length} файлов` : `${failures.length} ошибок`,
|
|
197
|
+
note: `${args?.host}: ${from} -> ${to}`,
|
|
198
|
+
});
|
|
199
|
+
return {
|
|
200
|
+
ok: failures.length === 0,
|
|
201
|
+
text: `${head}\nСкопировано: ${changed.length - failures.length}${failures.length ? `\nОшибки:\n${failures.join("\n")}` : ""}`,
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function makeToolDefinition() {
|
|
206
|
+
return {
|
|
207
|
+
name: TOOL_NAME,
|
|
208
|
+
description:
|
|
209
|
+
"Typed ssh/scp for a CMS or VPS: hosts are declared in .dsh/hosts.json (host, user, key, root). hosts: list profiles. run: execute one command (argv, no shell; destructive commands need confirm=true). dry-run: show what would be executed. sync: sha256-compare a local folder with a remote folder and copy only changed files (apply=true). state: probe php/unix/git/env-keys/release on a host. diff: compare state of two hosts — catches 'preview works, prod does not'. logs: tail journalctl for a unit. Every run/sync is written to .dsh/quality/evidence.jsonl.",
|
|
210
|
+
parameters: {
|
|
211
|
+
type: "object",
|
|
212
|
+
additionalProperties: false,
|
|
213
|
+
properties: {
|
|
214
|
+
action: { type: "string", enum: ACTIONS, description: "hosts | run | dry-run | sync | state | diff | logs" },
|
|
215
|
+
host: { type: "string", description: "host name from .dsh/hosts.json" },
|
|
216
|
+
hosts: { type: "string", description: "diff: two host names, comma-separated" },
|
|
217
|
+
command: { type: "string", description: "run/dry-run: command line; argv only, ; | & > < $ are rejected" },
|
|
218
|
+
from: { type: "string", description: "sync: local folder (relative to the session cwd)" },
|
|
219
|
+
to: { type: "string", description: "sync: remote folder" },
|
|
220
|
+
apply: { type: "boolean", description: "sync: actually copy changed files (default false = dry run)" },
|
|
221
|
+
confirm: { type: "boolean", description: "run: required for destructive commands" },
|
|
222
|
+
unit: { type: "string", description: "logs: systemd unit (default php8.5-fpm)" },
|
|
223
|
+
lines: { type: "integer", description: "logs: how many lines (10..500, default 80)" },
|
|
224
|
+
timeoutMs: { type: "integer", description: "run/state: timeout in ms (default 120000)" },
|
|
225
|
+
},
|
|
226
|
+
required: ["action"],
|
|
227
|
+
},
|
|
228
|
+
timeoutMs: 300_000,
|
|
229
|
+
output: {
|
|
230
|
+
schema: { type: "object", additionalProperties: true },
|
|
231
|
+
render(_args, value) {
|
|
232
|
+
const text = value && typeof value === "object" && typeof value.text === "string" ? value.text : JSON.stringify(value);
|
|
233
|
+
return [{ type: "text", text: text.length <= 12_000 ? text : `${text.slice(0, 12_000)}\n…` }];
|
|
234
|
+
},
|
|
235
|
+
},
|
|
236
|
+
async execute(args, exec) {
|
|
237
|
+
const cwd = sessionCwd(exec);
|
|
238
|
+
const action = String(args?.action ?? "").trim().toLowerCase();
|
|
239
|
+
try {
|
|
240
|
+
if (!ACTIONS.includes(action)) return fail(`remote_ops: неизвестное действие «${action}». Доступно: ${ACTIONS.join(", ")}`);
|
|
241
|
+
if (action === "hosts") return await actionHosts(cwd);
|
|
242
|
+
if (action === "run") return await actionRun(cwd, args, false);
|
|
243
|
+
if (action === "dry-run") return await actionRun(cwd, args, true);
|
|
244
|
+
if (action === "sync") return await actionSync(cwd, args);
|
|
245
|
+
if (action === "state") return await actionState(cwd, args);
|
|
246
|
+
if (action === "diff") return await actionDiff(cwd, args);
|
|
247
|
+
if (action === "logs") return await actionLogs(cwd, args);
|
|
248
|
+
return fail(`remote_ops: действие ${action} не реализовано`);
|
|
249
|
+
} catch (error) {
|
|
250
|
+
return fail(`remote_ops: ${error instanceof Error ? error.message : String(error)}`);
|
|
251
|
+
}
|
|
252
|
+
},
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export function apply(ctx) {
|
|
257
|
+
try {
|
|
258
|
+
const tool = makeToolDefinition();
|
|
259
|
+
const register = () => ctx.tools.register(tool);
|
|
260
|
+
if (typeof ctx.effect === "function") ctx.effect(register, "remote-ops: tool");
|
|
261
|
+
else register();
|
|
262
|
+
} catch (error) {
|
|
263
|
+
ctx.logger?.warn?.(`[remote-ops] tool registration failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
264
|
+
}
|
|
265
|
+
ctx.logger?.info?.("[remote-ops] ready");
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
export { makeToolDefinition, DEFAULT_TIMEOUT_MS };
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host profiles for dsh-remote-ops.
|
|
3
|
+
*
|
|
4
|
+
* Stored in `<cwd>/.dsh/hosts.json`. Only connection data lives here — never
|
|
5
|
+
* passwords: authentication is by key path, exactly as the project already
|
|
6
|
+
* documents for its VPS.
|
|
7
|
+
*
|
|
8
|
+
* {
|
|
9
|
+
* "hosts": {
|
|
10
|
+
* "prod": { "host": "1.2.3.4", "user": "root", "key": "~/.ssh/id_vps", "port": 22,
|
|
11
|
+
* "root": "/var/www/cms", "probe": "…optional shell probe…" },
|
|
12
|
+
* "demo": { "host": "1.2.3.4", "user": "nexumdemo", "key": "~/.ssh/id_vps",
|
|
13
|
+
* "root": "/var/www/demo" }
|
|
14
|
+
* }
|
|
15
|
+
* }
|
|
16
|
+
*/
|
|
17
|
+
import fs from "node:fs";
|
|
18
|
+
import os from "node:os";
|
|
19
|
+
import path from "node:path";
|
|
20
|
+
|
|
21
|
+
export const HOSTS_FILE = path.join(".dsh", "hosts.json");
|
|
22
|
+
|
|
23
|
+
export function hostsPath(cwd) {
|
|
24
|
+
return path.join(cwd || process.cwd(), HOSTS_FILE);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function readHosts(cwd) {
|
|
28
|
+
try {
|
|
29
|
+
const parsed = JSON.parse(fs.readFileSync(hostsPath(cwd), "utf8"));
|
|
30
|
+
const hosts = parsed?.hosts && typeof parsed.hosts === "object" ? parsed.hosts : {};
|
|
31
|
+
const clean = {};
|
|
32
|
+
for (const [name, value] of Object.entries(hosts)) {
|
|
33
|
+
if (!value || typeof value !== "object") continue;
|
|
34
|
+
const host = String(value.host ?? "").trim();
|
|
35
|
+
const user = String(value.user ?? "").trim();
|
|
36
|
+
if (!host || !user) continue;
|
|
37
|
+
clean[name] = {
|
|
38
|
+
name,
|
|
39
|
+
host,
|
|
40
|
+
user,
|
|
41
|
+
port: Number.isFinite(Number(value.port)) ? Math.max(1, Math.min(65535, Number(value.port))) : 22,
|
|
42
|
+
key: expandHome(String(value.key ?? "").trim()),
|
|
43
|
+
root: String(value.root ?? "").trim(),
|
|
44
|
+
probe: typeof value.probe === "string" ? value.probe : "",
|
|
45
|
+
label: String(value.label ?? "").trim(),
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
return { ok: true, hosts: clean, error: "" };
|
|
49
|
+
} catch (error) {
|
|
50
|
+
const missing = error && typeof error === "object" && "code" in error && error.code === "ENOENT";
|
|
51
|
+
return { ok: false, hosts: {}, error: missing ? "нет .dsh/hosts.json" : "hosts.json не читается" };
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function expandHome(value) {
|
|
56
|
+
if (!value) return "";
|
|
57
|
+
if (value === "~") return os.homedir();
|
|
58
|
+
if (value.startsWith("~/") || value.startsWith("~\\")) return path.join(os.homedir(), value.slice(2));
|
|
59
|
+
return value;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function hostByName(cwd, name) {
|
|
63
|
+
const { hosts } = readHosts(cwd);
|
|
64
|
+
const key = String(name ?? "").trim();
|
|
65
|
+
if (!key) return { ok: false, error: "нужно имя хоста (hosts покажет список)", host: null };
|
|
66
|
+
const host = hosts[key];
|
|
67
|
+
if (!host) return { ok: false, error: `хост не найден: ${key} (есть: ${Object.keys(hosts).join(", ") || "ни одного"})`, host: null };
|
|
68
|
+
return { ok: true, error: "", host };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** POSIX single-quote escaping: safe for ssh remote commands. */
|
|
72
|
+
export function shellQuote(value) {
|
|
73
|
+
const text = String(value ?? "");
|
|
74
|
+
return `'${text.replace(/'/gu, `'\\''`)}'`;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Split a command line into argv without a shell. `; | & > < $ \`` are
|
|
79
|
+
* rejected: a remote command must be one program plus arguments.
|
|
80
|
+
*/
|
|
81
|
+
export function splitCommand(command) {
|
|
82
|
+
const text = String(command ?? "").trim();
|
|
83
|
+
if (!text) return { ok: false, reason: "пустая команда", argv: [] };
|
|
84
|
+
const argv = [];
|
|
85
|
+
let current = "";
|
|
86
|
+
let quote = "";
|
|
87
|
+
for (const char of text) {
|
|
88
|
+
if (quote) {
|
|
89
|
+
if (char === quote) quote = "";
|
|
90
|
+
else current += char;
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
if (char === '"' || char === "'") {
|
|
94
|
+
quote = char;
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
if (/\s/u.test(char)) {
|
|
98
|
+
if (current.length > 0) {
|
|
99
|
+
argv.push(current);
|
|
100
|
+
current = "";
|
|
101
|
+
}
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
if ([";", "|", "&", ">", "<", "`", "$"].includes(char)) {
|
|
105
|
+
return { ok: false, reason: `запрещённый символ: ${char} (shell не используется)`, argv: [] };
|
|
106
|
+
}
|
|
107
|
+
current += char;
|
|
108
|
+
}
|
|
109
|
+
if (quote) return { ok: false, reason: "незакрытая кавычка", argv: [] };
|
|
110
|
+
if (current.length > 0) argv.push(current);
|
|
111
|
+
return argv.length > 0 ? { ok: true, reason: "", argv } : { ok: false, reason: "пустая команда", argv: [] };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const DESTRUCTIVE = /(?:^|[\s;&|])(?:rm|rmdir|dropdb|drop\s+table|truncate|updates:apply|systemctl\s+(?:restart|reload|stop)|chmod\s+-R|chown\s+-R|git\s+push\s+--force|kill\s+-9)/iu;
|
|
115
|
+
|
|
116
|
+
export function isDestructive(command) {
|
|
117
|
+
return DESTRUCTIVE.test(String(command ?? ""));
|
|
118
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ssh/scp transport for dsh-remote-ops.
|
|
3
|
+
*
|
|
4
|
+
* `execFile` only: the remote command is built from argv and POSIX-quoted, so
|
|
5
|
+
* a `; rm -rf` inside an argument stays an argument. No shell on either side.
|
|
6
|
+
*/
|
|
7
|
+
import { execFile } from "node:child_process";
|
|
8
|
+
import { createHash } from "node:crypto";
|
|
9
|
+
import fs from "node:fs";
|
|
10
|
+
import os from "node:os";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
|
|
13
|
+
import { shellQuote } from "./hosts.js";
|
|
14
|
+
|
|
15
|
+
export const DEFAULT_TIMEOUT_MS = 120_000;
|
|
16
|
+
const OUT_LIMIT = 6_000;
|
|
17
|
+
|
|
18
|
+
function sshArgs(host, remoteCommand) {
|
|
19
|
+
const args = [
|
|
20
|
+
"-o", "BatchMode=yes",
|
|
21
|
+
"-o", "StrictHostKeyChecking=accept-new",
|
|
22
|
+
"-o", "ConnectTimeout=10",
|
|
23
|
+
"-p", String(host.port),
|
|
24
|
+
];
|
|
25
|
+
if (host.key) args.push("-i", host.key.replace(/^~(?=$|[\\/])/u, os.homedir()));
|
|
26
|
+
args.push(`${host.user}@${host.host}`, remoteCommand);
|
|
27
|
+
return args;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function scpArgs(host, localFile, remotePath) {
|
|
31
|
+
const args = [
|
|
32
|
+
"-o", "BatchMode=yes",
|
|
33
|
+
"-o", "StrictHostKeyChecking=accept-new",
|
|
34
|
+
"-P", String(host.port),
|
|
35
|
+
];
|
|
36
|
+
if (host.key) args.push("-i", host.key.replace(/^~(?=$|[\\/])/u, os.homedir()));
|
|
37
|
+
args.push(localFile, `${host.user}@${host.host}:${remotePath}`);
|
|
38
|
+
return args;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function tail(text, limit = OUT_LIMIT) {
|
|
42
|
+
const clean = String(text ?? "").replace(/\r/gu, "");
|
|
43
|
+
return clean.length <= limit ? clean : `…${clean.slice(-limit)}`;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function exec(bin, args, timeoutMs) {
|
|
47
|
+
return new Promise((resolve) => {
|
|
48
|
+
execFile(bin, args, { timeout: timeoutMs, windowsHide: true, maxBuffer: 8 * 1024 * 1024 }, (error, stdout, stderr) => {
|
|
49
|
+
const code = error ? (typeof error.code === "number" ? error.code : error.killed ? "timeout" : "error") : 0;
|
|
50
|
+
resolve({
|
|
51
|
+
ok: code === 0,
|
|
52
|
+
code,
|
|
53
|
+
stdout: String(stdout ?? ""),
|
|
54
|
+
stderr: String(stderr ?? ""),
|
|
55
|
+
output: tail(`${stdout ?? ""}${stderr ?? ""}`),
|
|
56
|
+
error: error ? String(error.message ?? error) : "",
|
|
57
|
+
});
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Run one command on a host: argv -> POSIX-quoted remote command line. */
|
|
63
|
+
export async function runRemote(host, argv, options = {}) {
|
|
64
|
+
if (!Array.isArray(argv) || argv.length === 0) {
|
|
65
|
+
return { ok: false, code: "bad-input", output: "", error: "пустая команда" };
|
|
66
|
+
}
|
|
67
|
+
const remote = argv.map(shellQuote).join(" ");
|
|
68
|
+
const result = await exec("ssh", sshArgs(host, remote), options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
|
69
|
+
return { ...result, command: `${host.user}@${host.host}: ${argv.join(" ")}` };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Copy one local file to a remote path. */
|
|
73
|
+
export async function copyFile(host, localFile, remotePath, options = {}) {
|
|
74
|
+
if (!fs.existsSync(localFile)) return { ok: false, code: "missing", output: "", error: `нет файла: ${localFile}` };
|
|
75
|
+
const result = await exec("scp", scpArgs(host, localFile, remotePath), options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
|
76
|
+
return { ...result, file: path.basename(localFile), remotePath };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Hash, size and name of every file under a local directory. */
|
|
80
|
+
export function listLocal(dir) {
|
|
81
|
+
const out = [];
|
|
82
|
+
const walk = (current, prefix) => {
|
|
83
|
+
for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
|
|
84
|
+
if (entry.name === ".git" || entry.name === "node_modules") continue;
|
|
85
|
+
const full = path.join(current, entry.name);
|
|
86
|
+
const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
87
|
+
if (entry.isDirectory()) walk(full, rel);
|
|
88
|
+
else if (entry.isFile()) {
|
|
89
|
+
const buffer = fs.readFileSync(full);
|
|
90
|
+
out.push({ rel, size: buffer.length, hash: createHash("sha256").update(buffer).digest("hex") });
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
if (fs.existsSync(dir)) walk(dir, "");
|
|
95
|
+
return out;
|
|
96
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host state probe and cross-host diff.
|
|
3
|
+
*
|
|
4
|
+
* The probe is one POSIX script; every line it prints becomes `key=value`.
|
|
5
|
+
* A project can override it with `probe` in `.dsh/hosts.json`, which is the
|
|
6
|
+
* right place for CMS-specific versions (Laravel, PHP, PostgreSQL, theme).
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export function probeScript(host) {
|
|
10
|
+
if (host?.probe) return host.probe;
|
|
11
|
+
const root = host?.root ? host.root.replace(/'/gu, `'\\''`) : "/var/www";
|
|
12
|
+
return [
|
|
13
|
+
`root='${root}'`,
|
|
14
|
+
'echo "uname=$(uname -sr)"',
|
|
15
|
+
'echo "php=$(php -v 2>/dev/null | head -1 | cut -d\' \' -f2)"',
|
|
16
|
+
'echo "git=$(git -C "$root" rev-parse --short HEAD 2>/dev/null)"',
|
|
17
|
+
'echo "env_keys=$(grep -cE \'^[A-Za-z0-9_]+=\' "$root/.env" 2>/dev/null || echo 0)"',
|
|
18
|
+
'echo "updates=$(ls "$root/storage/app/updates" 2>/dev/null | tail -1)"',
|
|
19
|
+
'echo "release=$(ls /var/www/updates/download 2>/dev/null | sort -V | tail -1)"',
|
|
20
|
+
].join("; ");
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** `key=value` lines -> plain object; unknown lines are ignored. */
|
|
24
|
+
export function parseState(output) {
|
|
25
|
+
const state = {};
|
|
26
|
+
for (const line of String(output ?? "").split("\n")) {
|
|
27
|
+
const at = line.indexOf("=");
|
|
28
|
+
if (at <= 0) continue;
|
|
29
|
+
const key = line.slice(0, at).trim();
|
|
30
|
+
const value = line.slice(at + 1).trim().replace(/^["']|["']$/gu, "");
|
|
31
|
+
if (!/^[a-z0-9_]+$/iu.test(key)) continue;
|
|
32
|
+
state[key] = value;
|
|
33
|
+
}
|
|
34
|
+
return state;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Compare two hosts' state maps. */
|
|
38
|
+
export function diffState(left, right, leftName = "a", rightName = "b") {
|
|
39
|
+
const rows = [];
|
|
40
|
+
const keys = [...new Set([...Object.keys(left ?? {}), ...Object.keys(right ?? {})])].sort();
|
|
41
|
+
for (const key of keys) {
|
|
42
|
+
const a = left?.[key];
|
|
43
|
+
const b = right?.[key];
|
|
44
|
+
if (a === b) continue;
|
|
45
|
+
rows.push({
|
|
46
|
+
key,
|
|
47
|
+
[leftName]: a ?? "(нет)",
|
|
48
|
+
[rightName]: b ?? "(нет)",
|
|
49
|
+
kind: a === undefined ? "only-right" : b === undefined ? "only-left" : "changed",
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
return rows;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function formatState(hostName, state) {
|
|
56
|
+
const keys = Object.keys(state ?? {});
|
|
57
|
+
if (keys.length === 0) return `${hostName}: пусто (проверьте probe в .dsh/hosts.json)`;
|
|
58
|
+
return [`${hostName}:`, ...keys.map((key) => ` ${key} = ${state[key] || "—"}`)].join("\n");
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function formatDiff(rows, leftName, rightName) {
|
|
62
|
+
if (rows.length === 0) return `Расхождений между ${leftName} и ${rightName} нет.`;
|
|
63
|
+
const head = `Расхождения ${leftName} ↔ ${rightName}: ${rows.length}`;
|
|
64
|
+
const body = rows.slice(0, 40).map((row) => ` ${row.key}: ${row[leftName]} ↔ ${row[rightName]}${row.kind === "changed" ? "" : " (нет на одной стороне)"}`);
|
|
65
|
+
return [head, ...body].join("\n");
|
|
66
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "dsh-remote-ops",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"private": true,
|
|
5
|
+
"description": "Typed ssh/scp for DSH agents: host profiles in .dsh/hosts.json, argv-only commands, destructive-action confirmation, sha256 sync and cross-host state diff.",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"main": "index.js",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": "./index.js",
|
|
11
|
+
"./lib/hosts": "./lib/hosts.js",
|
|
12
|
+
"./lib/ssh": "./lib/ssh.js",
|
|
13
|
+
"./lib/state": "./lib/state.js",
|
|
14
|
+
"./package.json": "./package.json"
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"index.js",
|
|
18
|
+
"lib/**",
|
|
19
|
+
"cordis.patch.yml",
|
|
20
|
+
"README.md"
|
|
21
|
+
],
|
|
22
|
+
"engines": {
|
|
23
|
+
"node": ">=22.0.0"
|
|
24
|
+
},
|
|
25
|
+
"dsh": {
|
|
26
|
+
"manifestVersion": 1,
|
|
27
|
+
"bundle": {
|
|
28
|
+
"patch": "./cordis.patch.yml"
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|