dsh-ssh-compute 0.0.0-stage → 1.2.3

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/lib/config.js ADDED
@@ -0,0 +1,307 @@
1
+ // Configuration: what a server entry means, which entry a call names, and the
2
+ // defaults that keep the tool usable with an almost-empty settings form.
3
+
4
+ import { readdirSync, statSync } from 'node:fs'
5
+ import { homedir } from 'node:os'
6
+ import { join } from 'node:path'
7
+
8
+ /** A server name that can be a path segment and part of a job id. */
9
+ export const SERVER_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/
10
+
11
+ /** An address or user name with no whitespace, quote or control character. */
12
+ const TOKEN_RE = /^[^\s'"`\\\x00-\x1f\x7f]+$/
13
+
14
+ /** Where job directories live when the settings leave `remoteRoot` empty. */
15
+ export const DEFAULT_REMOTE_ROOT = '~/dsh-compute'
16
+
17
+ /**
18
+ * Private keys tried, in order, when an entry names none. These are the names
19
+ * `ssh-keygen` gives its own defaults, so an existing setup needs no copying.
20
+ */
21
+ const KEY_CANDIDATES = [
22
+ 'id_ed25519',
23
+ 'id_ecdsa',
24
+ 'id_rsa',
25
+ 'id_dsa',
26
+ 'id_ed25519_sk',
27
+ ]
28
+
29
+ /**
30
+ * Expand a leading `~` to the home directory of the user DSH runs as.
31
+ *
32
+ * Only a LEADING `~` is expanded; ssh itself does not expand anything, and a
33
+ * path from the settings form is handed to `-i` verbatim.
34
+ * @param path - a configured path, possibly `~`-relative.
35
+ * @returns an absolute path, or the input when it has no leading `~`.
36
+ */
37
+ export function expandHome(path) {
38
+ const text = String(path ?? '').trim()
39
+ if (text === '~') return homedir()
40
+ if (text.startsWith('~/') || text.startsWith('~\\')) return join(homedir(), text.slice(2))
41
+ return text
42
+ }
43
+
44
+ /**
45
+ * The private keys that exist in `~/.ssh`, best-known names first.
46
+ *
47
+ * Discovery is a convenience, not a decision: the first hit is what a server
48
+ * entry without `keyPath` uses, and an empty answer means ssh falls back to its
49
+ * own configuration and agent.
50
+ * @returns absolute paths, most preferred first.
51
+ */
52
+ export function discoverPrivateKeys() {
53
+ const directory = join(homedir(), '.ssh')
54
+ let names
55
+ try {
56
+ names = readdirSync(directory)
57
+ } catch {
58
+ return []
59
+ }
60
+ const usable = (name) => {
61
+ if (name.endsWith('.pub')) return false
62
+ if (name === 'known_hosts' || name === 'config' || name === 'authorized_keys') return false
63
+ if (name.endsWith('.backup') || name.endsWith('.old')) return false
64
+ try {
65
+ return statSync(join(directory, name)).isFile()
66
+ } catch {
67
+ return false
68
+ }
69
+ }
70
+ const ordered = []
71
+ for (const candidate of KEY_CANDIDATES) {
72
+ if (usable(candidate)) ordered.push(join(directory, candidate))
73
+ }
74
+ // Anything else key-shaped is still better than nothing, after the defaults.
75
+ for (const name of names.sort()) {
76
+ if (!name.startsWith('id_') || !usable(name)) continue
77
+ const full = join(directory, name)
78
+ if (!ordered.includes(full)) ordered.push(full)
79
+ }
80
+ return ordered
81
+ }
82
+
83
+ /**
84
+ * Read one configuration value, unwrapping a volatile cell.
85
+ *
86
+ * A `.volatile()` schema field does not resolve to its value: schemastery wraps
87
+ * it with cosmokit's `createVolatile(default)`. The cell is written IN PLACE
88
+ * when the user edits the row, which is what makes an edit apply without
89
+ * remounting the plugin — so reading through `.get()` is both required for
90
+ * correctness and how live updates arrive. A plain value (a hand-built settings
91
+ * object in a test, or an older host) passes through untouched.
92
+ * @param value - a configuration field, possibly a volatile cell.
93
+ * @returns the current value.
94
+ */
95
+ export function unbox(value) {
96
+ return value !== null && typeof value === 'object' && typeof value.get === 'function'
97
+ ? value.get()
98
+ : value
99
+ }
100
+
101
+ /**
102
+ * Split a server's extra ssh arguments into argv tokens.
103
+ *
104
+ * Whitespace-split on purpose: ssh options are a flat argv, and adding a quoting
105
+ * language here would mean a second parser to get wrong. Control bytes are
106
+ * refused because these tokens are handed to `spawn` as-is.
107
+ * @param raw - the configured string.
108
+ * @param name - the server name, for messages.
109
+ * @param problems - where an unusable entry is reported.
110
+ * @returns the tokens, or null when the field cannot be used.
111
+ */
112
+ function parseExtraArgs(raw, name, problems) {
113
+ if (raw === undefined || raw === null) return []
114
+ if (typeof raw !== 'string') {
115
+ problems.push(`server "${name}" has an unusable extra ssh arguments field and was ignored`)
116
+ return null
117
+ }
118
+ const text = raw.trim()
119
+ if (text === '') return []
120
+ if (/[\u0000-\u001f\u007f]/.test(text)) {
121
+ problems.push(`server "${name}" has control characters in its extra ssh arguments and was ignored`)
122
+ return null
123
+ }
124
+ return text.split(/\s+/).filter((token) => token !== '')
125
+ }
126
+
127
+ /**
128
+ * One server entry, with the fields the tool needs and nothing else.
129
+ *
130
+ * A half-written entry is reported and skipped rather than thrown: the settings
131
+ * form writes the whole array at once, so saving a card that is still missing
132
+ * its host must not take the plugin down.
133
+ * @param raw - the configured object.
134
+ * @param index - its position, for messages.
135
+ * @param problems - where an unusable entry is reported.
136
+ * @returns the normalized entry, or undefined when it cannot be used.
137
+ */
138
+ function normalizeServer(raw, index, problems) {
139
+ if (raw === null || typeof raw !== 'object') {
140
+ problems.push(`servers[${index}] is not an object and was ignored`)
141
+ return undefined
142
+ }
143
+ const name = typeof raw.name === 'string' ? raw.name.trim() : ''
144
+ const host = typeof raw.host === 'string' ? raw.host.trim() : ''
145
+ const user = typeof raw.user === 'string' ? raw.user.trim() : ''
146
+ // The name is not decoration: a job id starts with it, and the job directory is
147
+ // built as `<quoted root>/<job id>` with the id OUTSIDE the quotes. A name with a
148
+ // space, a quote or a shell metacharacter would therefore change the remote
149
+ // command, so only a path-safe token is accepted.
150
+ if (name !== '' && !SERVER_NAME_RE.test(name)) {
151
+ problems.push(`server name "${name}" may only use letters, digits, dot, dash and underscore (1-64 characters) and was ignored`)
152
+ return undefined
153
+ }
154
+ if (name === '' && host === '' && user === '') {
155
+ // An empty card the user added and has not filled in yet: silent, since it is
156
+ // the expected state during editing.
157
+ return undefined
158
+ }
159
+ if (name === '') {
160
+ problems.push(`servers[${index}] ("${host}") has no name and was ignored`)
161
+ return undefined
162
+ }
163
+ if (host === '') {
164
+ problems.push(`server "${name}" has no address and was ignored`)
165
+ return undefined
166
+ }
167
+ if (user === '') {
168
+ problems.push(`server "${name}" has no user and was ignored`)
169
+ return undefined
170
+ }
171
+ // `user@host` travels as one argv element, so whitespace is legal for ssh but
172
+ // never for anything this plugin builds out of it; quotes and control bytes are
173
+ // refused outright.
174
+ for (const [field, value] of [['address', host], ['user', user]]) {
175
+ if (!TOKEN_RE.test(value)) {
176
+ problems.push(`server "${name}" has an unusable ${field} (${JSON.stringify(value)}) and was ignored`)
177
+ return undefined
178
+ }
179
+ }
180
+ const extraArgs = parseExtraArgs(raw.extraArgs, name, problems)
181
+ if (extraArgs === null) return undefined
182
+ const port = Number(raw.port ?? 22)
183
+ return {
184
+ name,
185
+ extraArgs,
186
+ host,
187
+ user,
188
+ port: Number.isInteger(port) && port > 0 && port < 65536 ? port : 22,
189
+ keyPath: typeof raw.keyPath === 'string' ? raw.keyPath.trim() : '',
190
+ keyText: typeof raw.keyText === 'string' ? raw.keyText.trim() : '',
191
+ }
192
+ }
193
+
194
+ /**
195
+ * Turn the plugin's settings row into the values the tool reads.
196
+ *
197
+ * Called on every tool call rather than once at mount: every field is volatile,
198
+ * so the cells it reads hold the user's latest edit without a remount.
199
+ * @param settings - the row's config, possibly every field a volatile cell.
200
+ * @returns the resolved configuration and the entries that could not be used.
201
+ */
202
+ export function resolveConfig(settings = {}) {
203
+ const raw = unbox(settings.servers)
204
+ const list = Array.isArray(raw) ? raw : []
205
+ const problems = []
206
+ const servers = []
207
+ const seen = new Set()
208
+ for (let index = 0; index < list.length; index += 1) {
209
+ const server = normalizeServer(list[index], index, problems)
210
+ if (server === undefined) continue
211
+ const key = server.name.toLowerCase()
212
+ if (seen.has(key)) {
213
+ problems.push(`server "${server.name}" is defined twice; only the first entry is used`)
214
+ continue
215
+ }
216
+ seen.add(key)
217
+ servers.push(server)
218
+ }
219
+ const number = (value, fallback) => {
220
+ const parsed = Number(unbox(value))
221
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback
222
+ }
223
+ // Zero is a MEANING here ("no per-file limit"), not a missing value, so it must
224
+ // not fall through to the default the way `number` does.
225
+ const allowance = (value, fallback) => {
226
+ const parsed = Number(unbox(value))
227
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback
228
+ }
229
+ const text = (value) => {
230
+ const raw = unbox(value)
231
+ return typeof raw === 'string' ? raw.trim() : ''
232
+ }
233
+ return {
234
+ servers,
235
+ problems,
236
+ remoteRoot: text(settings.remoteRoot) || DEFAULT_REMOTE_ROOT,
237
+ guard: unbox(settings.guard) !== false,
238
+ connectTimeoutMs: number(settings.connectTimeoutMs, 15000),
239
+ commandTimeoutMs: number(settings.commandTimeoutMs, 30000),
240
+ logTailLines: number(settings.logTailLines, 40),
241
+ maxLogBytes: number(settings.maxLogBytes, 65536),
242
+ listLimit: number(settings.listLimit, 60),
243
+ // Wrapper-side limits. A job that runs away is the failure this plugin has
244
+ // already caused once: an unbounded log grew to 145 GB before anyone noticed.
245
+ maxFileSizeMb: allowance(settings.maxFileSizeMb, 10240),
246
+ minFreeSpaceMb: allowance(settings.minFreeSpaceMb, 1024),
247
+ waitTimeoutMs: number(settings.waitTimeoutMs, 300000),
248
+ // Multiplexing is a no-op on Windows, where OpenSSH tears the connection down
249
+ // when a ControlPath is set; `lib/ssh.js` decides, this only carries the wish.
250
+ reuseConnection: unbox(settings.reuseConnection) !== false,
251
+ reuseIdleSeconds: number(settings.reuseIdleSeconds, 300),
252
+ maxRunningJobs: allowance(settings.maxRunningJobs, 64),
253
+ recordResources: unbox(settings.recordResources) !== false,
254
+ }
255
+ }
256
+
257
+ /**
258
+ * The one server a call runs against.
259
+ *
260
+ * A single configured server needs no name; with several, the name is required
261
+ * so a typo cannot silently run a job on the wrong machine.
262
+ * @param config - the resolved configuration.
263
+ * @param requested - the call's `server` argument.
264
+ * @param fallback - a server name inferred from a job id, used when the call names none.
265
+ * @returns the server entry.
266
+ */
267
+ export function selectServer(config, requested, fallback) {
268
+ const wanted = (typeof requested === 'string' && requested.trim() !== '')
269
+ ? requested.trim()
270
+ : (typeof fallback === 'string' ? fallback : '')
271
+ if (wanted === '') {
272
+ if (config.servers.length === 0) {
273
+ throw new Error('dsh-ssh-compute: no servers are configured. Add one in Plugins → SSH compute.')
274
+ }
275
+ if (config.servers.length === 1) return config.servers[0]
276
+ throw new Error(
277
+ `dsh-ssh-compute: more than one server is configured, so \`server\` is required. ` +
278
+ `Available: ${config.servers.map((server) => server.name).join(', ')}`,
279
+ )
280
+ }
281
+ const exact = config.servers.find((server) => server.name === wanted)
282
+ const loose = exact ?? config.servers.find((server) => server.name.toLowerCase() === wanted.toLowerCase())
283
+ if (loose !== undefined) return loose
284
+ const names = config.servers.map((server) => server.name).join(', ')
285
+ throw new Error(
286
+ config.servers.length === 0
287
+ ? `dsh-ssh-compute: server "${wanted}" is not configured; no servers are configured yet.`
288
+ : `dsh-ssh-compute: server "${wanted}" is not configured. Available: ${names}`,
289
+ )
290
+ }
291
+
292
+ /**
293
+ * The server name a job id starts with, or `undefined` when it names none.
294
+ *
295
+ * A job id is `<server>-<stamp>-<random>`, so `status`, `logs` and `kill` can
296
+ * find their machine without the caller repeating it.
297
+ * @param config - the resolved configuration.
298
+ * @param jobId - the call's job id.
299
+ * @returns the matching server name.
300
+ */
301
+ export function serverNameFromJobId(config, jobId) {
302
+ if (typeof jobId !== 'string') return undefined
303
+ return config.servers
304
+ .filter((server) => jobId.startsWith(`${server.name}-`))
305
+ .sort((left, right) => right.name.length - left.name.length)
306
+ .at(0)?.name
307
+ }
package/lib/glob.js ADDED
@@ -0,0 +1,189 @@
1
+ // Local path expansion for upload.
2
+ //
3
+ // `upload` accepts plain paths, several of them, directories, and `*` / `?` /
4
+ // `**` patterns. A local shell never sees the patterns (ssh is spawned from an
5
+ // argv array), so the expansion has to happen here or a pattern would travel to
6
+ // the server as a literal filename.
7
+
8
+ import { readdirSync, statSync } from 'node:fs'
9
+ import { isAbsolute, join, normalize, relative, sep } from 'node:path'
10
+
11
+ const WINDOWS = process.platform === 'win32'
12
+
13
+ /** Whether one path segment contains pattern syntax. */
14
+ function hasMagic(segment) {
15
+ return /[*?[\]]/.test(segment)
16
+ }
17
+
18
+ /**
19
+ * Compile one pattern segment into an anchored regular expression.
20
+ * @param segment - one path segment.
21
+ * @returns the matcher.
22
+ */
23
+ function segmentMatcher(segment) {
24
+ let pattern = ''
25
+ for (const character of segment) {
26
+ if (character === '*') pattern += '[^/]*'
27
+ else if (character === '?') pattern += '[^/]'
28
+ else if (character === '[') pattern += '['
29
+ else if (character === ']') pattern += ']'
30
+ else pattern += character.replace(/[.+^${}()|\\]/g, '\\$&')
31
+ }
32
+ return new RegExp(`^${pattern}$`, WINDOWS ? 'i' : '')
33
+ }
34
+
35
+ /** List the entries of one directory, or nothing when it is unreadable. */
36
+ function entries(directory) {
37
+ try {
38
+ return readdirSync(directory, { withFileTypes: true })
39
+ } catch {
40
+ return []
41
+ }
42
+ }
43
+
44
+ /**
45
+ * Walk one segment list from a starting directory.
46
+ * @param directory - where the walk stands (forward slashes).
47
+ * @param segments - the remaining pattern segments.
48
+ * @param index - which segment is next.
49
+ * @param found - the accumulator.
50
+ */
51
+ function walk(directory, segments, index, found) {
52
+ if (index >= segments.length) {
53
+ found.push(directory)
54
+ return
55
+ }
56
+ const segment = segments[index]
57
+ if (segment === '**') {
58
+ // `**` matches zero or more directories: continue here, or descend once and retry.
59
+ walk(directory, segments, index + 1, found)
60
+ for (const entry of entries(directory)) {
61
+ if (!entry.isDirectory()) continue
62
+ walk(`${directory}/${entry.name}`, segments, index, found)
63
+ }
64
+ return
65
+ }
66
+ if (!hasMagic(segment)) {
67
+ const candidate = `${directory}/${segment}`
68
+ if (index === segments.length - 1) {
69
+ try {
70
+ statSync(candidate)
71
+ found.push(candidate)
72
+ } catch {
73
+ // A missing final segment is a missing match, reported by the caller.
74
+ }
75
+ return
76
+ }
77
+ walk(candidate, segments, index + 1, found)
78
+ return
79
+ }
80
+ const matcher = segmentMatcher(segment)
81
+ for (const entry of entries(directory)) {
82
+ if (!matcher.test(entry.name)) continue
83
+ const candidate = `${directory}/${entry.name}`
84
+ if (index === segments.length - 1) {
85
+ found.push(candidate)
86
+ continue
87
+ }
88
+ if (entry.isDirectory()) walk(candidate, segments, index + 1, found)
89
+ }
90
+ }
91
+
92
+ /** Convert a platform path to the forward-slash form the walker uses. */
93
+ function toForwardSlashes(path) {
94
+ return String(path).replace(/\\/g, '/')
95
+ }
96
+
97
+ /**
98
+ * Expand the caller's local paths into existing absolute paths.
99
+ * @param patterns - paths or patterns, relative to `cwd` when not absolute.
100
+ * @param cwd - the directory a relative pattern resolves against.
101
+ * @returns the matched paths and the patterns that matched nothing.
102
+ */
103
+ export function expandLocalPaths(patterns, cwd) {
104
+ const matches = []
105
+ const missing = []
106
+ for (const raw of patterns) {
107
+ const text = String(raw ?? '').trim()
108
+ if (text === '') continue
109
+ const absolute = isAbsolute(text) ? text : join(cwd, text)
110
+ const forward = toForwardSlashes(absolute)
111
+ if (!/[*?[\]]/.test(forward)) {
112
+ try {
113
+ statSync(absolute)
114
+ matches.push(normalize(absolute))
115
+ continue
116
+ } catch {
117
+ missing.push(text)
118
+ continue
119
+ }
120
+ }
121
+ const rooted = forward.startsWith('/')
122
+ const segments = forward.split('/').filter((segment) => segment !== '' && segment !== '.')
123
+ // A Windows drive keeps its `C:` as the first segment and is not a child of `/`.
124
+ const drive = /^[A-Za-z]:$/.test(segments[0] ?? '') ? segments.shift() : undefined
125
+ const start = drive !== undefined ? `${drive}/` : rooted ? '/' : ''
126
+ const found = []
127
+ walk(start === '' ? '.' : start, segments, 0, found)
128
+ if (found.length === 0) {
129
+ missing.push(text)
130
+ continue
131
+ }
132
+ for (const hit of found) matches.push(normalize(hit))
133
+ }
134
+ const unique = [...new Set(matches)]
135
+ unique.sort((left, right) => left.localeCompare(right))
136
+ return { matches: unique, missing }
137
+ }
138
+
139
+ /**
140
+ * The deepest directory that contains every path.
141
+ *
142
+ * tar needs one `-C` directory and relative names, and this is how both are
143
+ * derived without ever passing an absolute path to tar.
144
+ * @param paths - absolute file or directory paths.
145
+ * @returns the shared ancestor directory.
146
+ */
147
+ export function commonParent(paths) {
148
+ if (paths.length === 0) return undefined
149
+ const roots = paths.map((path) => toForwardSlashes(path).split('/').filter(Boolean))
150
+ const shared = []
151
+ const shortest = Math.min(...roots.map((parts) => parts.length))
152
+ for (let index = 0; index < shortest; index += 1) {
153
+ const value = roots[0][index]
154
+ if (!roots.every((parts) => parts[index] === value)) break
155
+ shared.push(value)
156
+ }
157
+ // A Windows drive is its own root: `C:/x`, never `/C:/x`. Building the path as a
158
+ // POSIX one turned every Windows upload into an archive rooted at the drive,
159
+ // which extracted a `Users/` tree instead of the files.
160
+ const toAbsolute = (segments) => {
161
+ const joined = segments.join('/')
162
+ return /^[A-Za-z]:$/.test(segments[0]) ? `${joined}/` : `/${joined}`
163
+ }
164
+ // The last shared element may be a FILE, so step back one when it is not a directory.
165
+ while (shared.length > 0) {
166
+ const absolute = toAbsolute(shared)
167
+ try {
168
+ if (statSync(absolute).isDirectory()) return absolute
169
+ } catch {
170
+ // Fall through to the parent.
171
+ }
172
+ shared.pop()
173
+ }
174
+ return undefined
175
+ }
176
+
177
+ /**
178
+ * A path relative to a base directory, in the platform's separators.
179
+ * @param base - the containing directory.
180
+ * @param path - an absolute path inside it.
181
+ * @returns the relative path.
182
+ */
183
+ export function relativeTo(base, path) {
184
+ const value = relative(base, path)
185
+ return value === '' ? '.' : value
186
+ }
187
+
188
+ /** Re-export for callers that need the platform separator. */
189
+ export { sep }
package/lib/guard.js ADDED
@@ -0,0 +1,169 @@
1
+ // Two refusals, both about the same thing: an unattended agent should not be
2
+ // able to erase a host or overwrite its system directories by typing a short
3
+ // command. Everything is escapable with `allowDangerous: true`, so the guard
4
+ // is a speed bump on accidents, not a permission system.
5
+
6
+ /** Operands that name a whole filesystem root or the login home. */
7
+ const ROOT_OPERANDS = new Set(['/', '//', '/*', '//*', '~', '~/', '~/*', '$HOME', '$HOME/', '$HOME/*'])
8
+
9
+ /** Device trees where a write is indistinguishable from destroying the machine. */
10
+ const DEVICE_PREFIXES = ['/dev/disk', '/dev/sd', '/dev/nvme', '/dev/hd', '/dev/vd', '/dev/mmcblk', '/dev/mapper']
11
+
12
+ /** Remote directories `upload` will not write into. */
13
+ const PROTECTED_TARGETS = [
14
+ '/etc', '/boot', '/usr', '/bin', '/sbin', '/lib', '/lib32', '/lib64',
15
+ '/dev', '/proc', '/sys', '/var/lib',
16
+ ]
17
+
18
+ /** Split a command line into simple commands at the operators a shell honours. */
19
+ function segments(command) {
20
+ return String(command).split(/&&|\|\||[;\n|]/).map((part) => part.trim()).filter((part) => part !== '')
21
+ }
22
+
23
+ /**
24
+ * Tokenize one simple command, keeping quoted runs together.
25
+ *
26
+ * This is not a shell parser: it only needs to see `rm`, its flags and its
27
+ * operands correctly for the shapes below.
28
+ * @param segment - one simple command.
29
+ * @returns its words.
30
+ */
31
+ function words(segment) {
32
+ const result = []
33
+ let current = ''
34
+ let quote = ''
35
+ for (const character of segment) {
36
+ if (quote !== '') {
37
+ if (character === quote) quote = ''
38
+ else current += character
39
+ continue
40
+ }
41
+ if (character === '"' || character === "'") {
42
+ quote = character
43
+ continue
44
+ }
45
+ if (/\s/.test(character)) {
46
+ if (current !== '') {
47
+ result.push(current)
48
+ current = ''
49
+ }
50
+ continue
51
+ }
52
+ current += character
53
+ }
54
+ if (current !== '') result.push(current)
55
+ return result
56
+ }
57
+
58
+ /**
59
+ * Resolve `.` and `..` so a detour cannot hide the real destination.
60
+ *
61
+ * `upload remote="/tmp/../etc/passwd"` reaches /etc just as directly as the
62
+ * literal path, so the check has to see the same directory the shell will.
63
+ * @param path - the destination as the caller wrote it.
64
+ * @returns an absolute-looking, dot-free path.
65
+ */
66
+ function normalizeTarget(path) {
67
+ const parts = []
68
+ for (const segment of String(path ?? '').replace(/\\/g, '/').split('/')) {
69
+ if (segment === '' || segment === '.') continue
70
+ if (segment === '..') {
71
+ parts.pop()
72
+ continue
73
+ }
74
+ parts.push(segment)
75
+ }
76
+ return `/${parts.join('/')}`
77
+ }
78
+
79
+ /** Whether a path lands inside a protected system directory. */
80
+ function isProtectedTarget(path) {
81
+ const text = String(path ?? '').trim()
82
+ if (text === '') return false
83
+ const normalized = normalizeTarget(text)
84
+ return PROTECTED_TARGETS.some(
85
+ (target) => normalized === target || normalized.startsWith(`${target}/`),
86
+ )
87
+ }
88
+
89
+ /** Whether a device-looking operand names a whole disk. */
90
+ function isDeviceOperand(operand) {
91
+ return DEVICE_PREFIXES.some((prefix) => operand.startsWith(prefix))
92
+ }
93
+
94
+ /**
95
+ * Refuse a command that would obviously destroy the remote machine.
96
+ * @param config - the resolved configuration.
97
+ * @param command - the caller's command text.
98
+ * @param allowDangerous - the caller's explicit override.
99
+ * @returns nothing; throws when refused.
100
+ */
101
+ export function assertCommandAllowed(config, command, allowDangerous) {
102
+ if (config.guard !== true || allowDangerous === true) return
103
+ const text = String(command)
104
+
105
+ const forkBomb = /:\s*\(\s*\)\s*\{[^}]*:\s*\|\s*:[^}]*&[^}]*\}/
106
+ if (forkBomb.test(text)) {
107
+ refuse('a fork bomb')
108
+ }
109
+
110
+ for (const segment of segments(text)) {
111
+ const tokens = words(segment)
112
+ if (tokens.length === 0) continue
113
+ const program = tokens[0].replace(/^.*\//, '')
114
+
115
+ if (program === 'rm') {
116
+ const flags = tokens.slice(1).filter((token) => token.startsWith('-'))
117
+ const recursive = flags.some((flag) => /[rR]/.test(flag)) || flags.includes('--recursive')
118
+ const operands = tokens.slice(1).filter((token) => !token.startsWith('-'))
119
+ if (!recursive) continue
120
+ const root = operands.find((operand) => ROOT_OPERANDS.has(operand))
121
+ if (root !== undefined) refuse(`recursive removal of ${root}`)
122
+ if (flags.includes('--no-preserve-root')) refuse('rm --no-preserve-root')
123
+ continue
124
+ }
125
+
126
+ if (program === 'mkfs' || program.startsWith('mkfs.') || program === 'wipefs' || program === 'mkswap') {
127
+ refuse(`filesystem creation or erasure (${program})`)
128
+ }
129
+
130
+ if (program === 'shred') {
131
+ if (tokens.slice(1).some((token) => isDeviceOperand(token))) refuse('shredding a block device')
132
+ continue
133
+ }
134
+
135
+ if (program === 'dd') {
136
+ const target = tokens.slice(1).find((token) => token.startsWith('of='))
137
+ if (target !== undefined && isDeviceOperand(target.slice(3))) {
138
+ refuse(`writing over a block device (dd ${target})`)
139
+ }
140
+ continue
141
+ }
142
+
143
+ if (program === 'shutdown' || program === 'poweroff' || program === 'reboot' || program === 'halt') {
144
+ refuse(`${program} would take the server down`)
145
+ }
146
+ }
147
+ }
148
+
149
+ /**
150
+ * Refuse an upload into a system directory.
151
+ * @param config - the resolved configuration.
152
+ * @param remoteTarget - the destination directory or file on the server.
153
+ * @param allowDangerous - the caller's explicit override.
154
+ * @returns nothing; throws when refused.
155
+ */
156
+ export function assertUploadAllowed(config, remoteTarget, allowDangerous) {
157
+ if (config.guard !== true || allowDangerous === true) return
158
+ if (isProtectedTarget(remoteTarget)) {
159
+ refuse(`writing into a system directory (${remoteTarget})`)
160
+ }
161
+ }
162
+
163
+ /** One message shape, so the escape hatch is always named the same way. */
164
+ function refuse(what) {
165
+ throw new Error(
166
+ `dsh-ssh-compute: refused — ${what}. The command guard blocked this; ` +
167
+ 'pass `allowDangerous: true` if this is really intended.',
168
+ )
169
+ }