@aisac/cli 0.4.0-beta.2 → 0.4.0-beta.22
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 +146 -10
- package/dist/assets/claude/hooks/context-compaction.ts +17 -5
- package/dist/assets/claude/hooks/native-host-contract-runtime.ts +1 -1
- package/dist/assets/claude/hooks/native-host-contract.test.ts +8 -4
- package/dist/assets/claude/hooks/provider-window.d.ts +83 -0
- package/dist/assets/codex-context-compaction.mjs +846 -14
- package/dist/assets/jev-paid-pilot-terminal.mjs +12 -1
- package/dist/claude-compatibility.mjs +26 -25
- package/dist/claude-observation.mjs +2 -1
- package/dist/cli.mjs +641 -35
- package/dist/codex-compatibility.mjs +48 -2
- package/dist/codex-engineering.mjs +165 -0
- package/dist/codex-hooks.mjs +411 -0
- package/dist/codex-permissions.mjs +67 -34
- package/dist/codex-protocol-fingerprint.json +11 -11
- package/dist/engineering-init.mjs +615 -0
- package/dist/engineering-pack.mjs +276 -23
- package/dist/engineering-scan-pins.json +42 -0
- package/dist/engineering-scan-report.mjs +1274 -0
- package/dist/engineering-scan-tools.mjs +1418 -0
- package/dist/engineering-scan.mjs +1265 -0
- package/dist/extensions-catalog.mjs +390 -0
- package/dist/extensions-cli.mjs +492 -0
- package/dist/extensions-preferences.mjs +151 -0
- package/dist/guardrails/continuity.mjs +239 -0
- package/dist/guardrails/format.mjs +111 -0
- package/dist/guardrails/guards.mjs +1557 -0
- package/dist/guardrails/patch.mjs +33 -0
- package/dist/guardrails/run.mjs +286 -0
- package/dist/guardrails/shell-words.mjs +206 -0
- package/dist/guardrails-plugin.mjs +207 -0
- package/dist/launch.mjs +403 -47
- package/dist/managed-host.mjs +977 -0
- package/dist/manager/bus.mjs +1921 -0
- package/dist/manager/delegation.mjs +354 -0
- package/dist/manager/hooks.mjs +918 -0
- package/dist/manager/launch-role.mjs +476 -0
- package/dist/manager/mcp-stdio.mjs +463 -0
- package/dist/manager/messages.mjs +791 -0
- package/dist/manager/reserve.mjs +2166 -0
- package/dist/manager/room.mjs +106 -0
- package/dist/manager/server.mjs +1792 -0
- package/dist/manager/status.mjs +118 -0
- package/dist/manager/watch.mjs +87 -0
- package/dist/manager/worker.mjs +2793 -0
- package/dist/manager/workers-cli.mjs +1403 -0
- package/dist/mcp-servers.mjs +192 -0
- package/dist/mcp.mjs +10 -2
- package/dist/monitor.mjs +76 -1
- package/dist/package.json +1 -1
- package/dist/platform.mjs +78 -29
- package/dist/release-manifest-public-keys.json +10 -0
- package/dist/release-manifest.json +328 -0
- package/dist/release-manifest.mjs +817 -0
- package/dist/release-settings.mjs +210 -0
- package/dist/self-update.mjs +1036 -0
- package/dist/state.mjs +25 -1
- package/dist/token-guide.mjs +132 -0
- package/dist/update-actions.mjs +442 -0
- package/package.json +1 -1
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/**
|
|
3
|
+
* Paths a Codex patch touches (spec aisac-engineering-extensions FR6, E6b).
|
|
4
|
+
* Codex sends an edit as `tool_name: "apply_patch"` with the whole patch text in
|
|
5
|
+
* `tool_input.command` and no `file_path` (measured on Codex 0.166.0), so the
|
|
6
|
+
* guardrails read the file names from the patch headers. Names only: the patch
|
|
7
|
+
* body is never interpreted.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export const PATCH_TOOL = 'apply_patch';
|
|
11
|
+
|
|
12
|
+
// `*** Add File: <path>`, `*** Update File: <path>`, `*** Delete File: <path>`
|
|
13
|
+
// and `*** Move to: <path>` (the new name of an updated file).
|
|
14
|
+
const HEADER = /^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$/u;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The paths named in a patch, in order and without repeats. Anything that is
|
|
18
|
+
* not a string, or has no header, names no path. There is no cap: the hook
|
|
19
|
+
* input is already bounded (1 MiB), and a cap would let a patch hide a secret
|
|
20
|
+
* file after the limit.
|
|
21
|
+
* @param {unknown} patch
|
|
22
|
+
* @returns {string[]}
|
|
23
|
+
*/
|
|
24
|
+
export function patchPaths(patch) {
|
|
25
|
+
if (typeof patch !== 'string' || patch.length === 0) return [];
|
|
26
|
+
/** @type {Set<string>} */
|
|
27
|
+
const paths = new Set();
|
|
28
|
+
for (const line of patch.split(/\r?\n/u)) {
|
|
29
|
+
const path = HEADER.exec(line)?.[1]?.trim();
|
|
30
|
+
if (path !== undefined && path.length > 0) paths.add(path);
|
|
31
|
+
}
|
|
32
|
+
return [...paths];
|
|
33
|
+
}
|
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// @ts-check
|
|
3
|
+
/**
|
|
4
|
+
* Guardrail dispatcher (spec aisac-engineering-extensions FR2, FR5, FR6): the
|
|
5
|
+
* command the hosts run for each hook event.
|
|
6
|
+
* - Claude Code: the session plugin `aisac-guardrails` registers one command per
|
|
7
|
+
* event, and that one process runs every enabled hook bound to it, so a tool
|
|
8
|
+
* call pays for one Node start. The launcher passes the state folder, the
|
|
9
|
+
* preferences file and the locale as arguments.
|
|
10
|
+
* - Codex (`--client codex`, E6b): one command per hook and event, byte-stable so
|
|
11
|
+
* the user's review in `/hooks` holds. The enabled set, the locale, the state
|
|
12
|
+
* folder and the preferences file come from GUARDRAILS_SESSION_ENV, which the
|
|
13
|
+
* monitor put in the app-server's environment; without it the hook does
|
|
14
|
+
* nothing. The project is the payload's `cwd`, never an inherited
|
|
15
|
+
* CLAUDE_PROJECT_DIR, and a patch (`apply_patch`) is an edit of every file its
|
|
16
|
+
* headers name.
|
|
17
|
+
* The event payload comes from the host on stdin and is untrusted.
|
|
18
|
+
*
|
|
19
|
+
* Exit 0 always, except exit 2 for a PreToolUse refusal (reason on stderr).
|
|
20
|
+
* Any error lets the tool call run: a broken guard must not stop all work.
|
|
21
|
+
*/
|
|
22
|
+
import { homedir } from 'node:os';
|
|
23
|
+
import { isAbsolute, join, resolve } from 'node:path';
|
|
24
|
+
import { pathToFileURL } from 'node:url';
|
|
25
|
+
import { GUARDRAILS_SESSION_ENV, parseGuardrailsSession } from '../codex-hooks.mjs';
|
|
26
|
+
import { hookById } from '../extensions-catalog.mjs';
|
|
27
|
+
import { GUARDS } from './guards.mjs';
|
|
28
|
+
import { PATCH_TOOL, patchPaths } from './patch.mjs';
|
|
29
|
+
import {
|
|
30
|
+
continuityReminder,
|
|
31
|
+
docsReminder,
|
|
32
|
+
recordEdit,
|
|
33
|
+
resetTurn,
|
|
34
|
+
restoreCompactSnapshot,
|
|
35
|
+
saveCompactSnapshot,
|
|
36
|
+
sessionContext,
|
|
37
|
+
} from './continuity.mjs';
|
|
38
|
+
import { formatEdited } from './format.mjs';
|
|
39
|
+
|
|
40
|
+
const MAX_INPUT_BYTES = 1024 * 1024;
|
|
41
|
+
const EVENTS = new Set([
|
|
42
|
+
'PreToolUse',
|
|
43
|
+
'PostToolUse',
|
|
44
|
+
'UserPromptSubmit',
|
|
45
|
+
'SessionStart',
|
|
46
|
+
'PreCompact',
|
|
47
|
+
'Stop',
|
|
48
|
+
]);
|
|
49
|
+
const REFUSAL_EXIT_CODE = 2;
|
|
50
|
+
const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f]/u;
|
|
51
|
+
const ARGUMENT_NAMES = ['--client', '--event', '--hooks', '--state', '--prefs', '--locale'];
|
|
52
|
+
// Codex matches a patch with the edit tool names too (`Edit|Write` fires for
|
|
53
|
+
// `apply_patch`, measured on 0.166.0), so the catalog's Claude matchers bind it.
|
|
54
|
+
/** @type {Readonly<Record<string, readonly string[]>>} */
|
|
55
|
+
const TOOL_ALIASES = Object.freeze({
|
|
56
|
+
[PATCH_TOOL]: Object.freeze([PATCH_TOOL, 'Edit', 'Write']),
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* @typedef {object} RunOptions
|
|
61
|
+
* @property {'claude' | 'codex'} client
|
|
62
|
+
* @property {import('../extensions-catalog.mjs').HookEvent} event
|
|
63
|
+
* @property {string[]} hooks
|
|
64
|
+
* @property {string} stateDir
|
|
65
|
+
* @property {string} prefsPath
|
|
66
|
+
* @property {'pt-BR' | 'en'} locale
|
|
67
|
+
*/
|
|
68
|
+
|
|
69
|
+
/** Catalog ids bound to the event. @param {string[]} ids @param {string} event */
|
|
70
|
+
function boundIds(ids, event) {
|
|
71
|
+
return ids.filter((id) => {
|
|
72
|
+
const entry = hookById(id);
|
|
73
|
+
return entry !== undefined && entry.bindings.some((binding) => binding.event === event);
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Strict launcher arguments; null when anything is off. In Codex the enabled
|
|
79
|
+
* set and the paths come from the session value in the environment, and a hook
|
|
80
|
+
* the session did not enable is dropped.
|
|
81
|
+
* @param {string[]} argv
|
|
82
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
83
|
+
* @returns {RunOptions | null}
|
|
84
|
+
*/
|
|
85
|
+
export function parseArguments(argv, env = process.env) {
|
|
86
|
+
/** @type {Record<string, string>} */
|
|
87
|
+
const values = {};
|
|
88
|
+
for (let index = 0; index < argv.length; index += 2) {
|
|
89
|
+
const name = argv[index] ?? '';
|
|
90
|
+
const value = argv[index + 1];
|
|
91
|
+
if (!ARGUMENT_NAMES.includes(name) || value === undefined || Object.hasOwn(values, name))
|
|
92
|
+
return null;
|
|
93
|
+
values[name] = value;
|
|
94
|
+
}
|
|
95
|
+
const event = values['--event'] ?? '';
|
|
96
|
+
if (!EVENTS.has(event)) return null;
|
|
97
|
+
const typedEvent = /** @type {import('../extensions-catalog.mjs').HookEvent} */ (event);
|
|
98
|
+
const requested = (values['--hooks'] ?? '').split(',');
|
|
99
|
+
if (values['--client'] === 'codex') {
|
|
100
|
+
if (['--state', '--prefs', '--locale'].some((name) => Object.hasOwn(values, name))) return null;
|
|
101
|
+
const session = parseGuardrailsSession(env[GUARDRAILS_SESSION_ENV]);
|
|
102
|
+
if (session === null) return null;
|
|
103
|
+
return {
|
|
104
|
+
client: 'codex',
|
|
105
|
+
event: typedEvent,
|
|
106
|
+
hooks: boundIds(requested, event).filter((id) => session.hooks.includes(id)),
|
|
107
|
+
stateDir: session.stateDir,
|
|
108
|
+
prefsPath: session.prefsPath,
|
|
109
|
+
locale: session.locale,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
if (values['--client'] !== undefined && values['--client'] !== 'claude') return null;
|
|
113
|
+
const stateDir = values['--state'] ?? '';
|
|
114
|
+
const prefsPath = values['--prefs'] ?? '';
|
|
115
|
+
if (!isAbsolute(stateDir) || !isAbsolute(prefsPath)) return null;
|
|
116
|
+
return {
|
|
117
|
+
client: 'claude',
|
|
118
|
+
event: typedEvent,
|
|
119
|
+
hooks: boundIds(requested, event),
|
|
120
|
+
stateDir,
|
|
121
|
+
prefsPath,
|
|
122
|
+
locale: values['--locale'] === 'pt-BR' ? 'pt-BR' : 'en',
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Codex's user config files: `~/.codex/config.toml`, and `$CODEX_HOME/config.toml`
|
|
128
|
+
* when CODEX_HOME is set. They hold the off switch of every Codex hook, so
|
|
129
|
+
* `secrets-guard` keeps the agent out of them (FR2.2, E6b).
|
|
130
|
+
* @param {NodeJS.ProcessEnv} env @param {string} home
|
|
131
|
+
*/
|
|
132
|
+
export function codexConfigPaths(env, home) {
|
|
133
|
+
const paths = [join(home, '.codex', 'config.toml')];
|
|
134
|
+
const codexHome = env.CODEX_HOME;
|
|
135
|
+
if (typeof codexHome === 'string' && isAbsolute(codexHome) && !CONTROL_CHARACTERS.test(codexHome))
|
|
136
|
+
paths.push(join(resolve(codexHome), 'config.toml'));
|
|
137
|
+
return [...new Set(paths)];
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** @returns {Promise<string | null>} */
|
|
141
|
+
async function readInput() {
|
|
142
|
+
/** @type {Buffer[]} */
|
|
143
|
+
const chunks = [];
|
|
144
|
+
let size = 0;
|
|
145
|
+
for await (const chunk of process.stdin) {
|
|
146
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
|
|
147
|
+
size += buffer.length;
|
|
148
|
+
if (size > MAX_INPUT_BYTES) return null;
|
|
149
|
+
chunks.push(buffer);
|
|
150
|
+
}
|
|
151
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Does a hook's binding for this event accept the tool or source? @param {string} id @param {string} event @param {string} subject */
|
|
155
|
+
function bound(id, event, subject) {
|
|
156
|
+
const names = TOOL_ALIASES[subject] ?? [subject];
|
|
157
|
+
return (hookById(id)?.bindings ?? []).some(
|
|
158
|
+
(binding) =>
|
|
159
|
+
binding.event === event &&
|
|
160
|
+
(binding.matcher === undefined ||
|
|
161
|
+
binding.matcher.split('|').some((name) => names.includes(name))),
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* The files a tool call edits: `file_path`, or every path a Codex patch names.
|
|
167
|
+
* @param {string} tool @param {Record<string, unknown>} toolInput
|
|
168
|
+
* @returns {unknown[]}
|
|
169
|
+
*/
|
|
170
|
+
function editedFiles(tool, toolInput) {
|
|
171
|
+
return tool === PATCH_TOOL ? patchPaths(toolInput.command) : [toolInput.file_path];
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Run the enabled hooks for one event.
|
|
176
|
+
* @param {RunOptions} options
|
|
177
|
+
* @param {Record<string, unknown>} input
|
|
178
|
+
* @returns {Promise<{ exitCode: number, stdout: string, stderr: string }>}
|
|
179
|
+
*/
|
|
180
|
+
export async function dispatch(options, input) {
|
|
181
|
+
// Codex adds no project variable: one in its environment was inherited from the
|
|
182
|
+
// user's shell (for example a Claude Code terminal), so Codex uses the payload cwd.
|
|
183
|
+
const envProject = options.client === 'codex' ? undefined : process.env.CLAUDE_PROJECT_DIR;
|
|
184
|
+
const projectDir =
|
|
185
|
+
typeof envProject === 'string' && isAbsolute(envProject)
|
|
186
|
+
? envProject
|
|
187
|
+
: typeof input.cwd === 'string' && isAbsolute(input.cwd)
|
|
188
|
+
? input.cwd
|
|
189
|
+
: process.cwd();
|
|
190
|
+
const home = homedir();
|
|
191
|
+
const context = {
|
|
192
|
+
projectDir,
|
|
193
|
+
stateDir: options.stateDir,
|
|
194
|
+
prefsPath: options.prefsPath,
|
|
195
|
+
codexConfigs: codexConfigPaths(process.env, home),
|
|
196
|
+
home,
|
|
197
|
+
locale: options.locale,
|
|
198
|
+
};
|
|
199
|
+
const enabled = new Set(options.hooks);
|
|
200
|
+
const tool = typeof input.tool_name === 'string' ? input.tool_name : '';
|
|
201
|
+
const toolInput =
|
|
202
|
+
typeof input.tool_input === 'object' && input.tool_input !== null
|
|
203
|
+
? /** @type {Record<string, unknown>} */ (input.tool_input)
|
|
204
|
+
: {};
|
|
205
|
+
const quiet = { exitCode: 0, stdout: '', stderr: '' };
|
|
206
|
+
|
|
207
|
+
if (options.event === 'PreToolUse') {
|
|
208
|
+
for (const [id, guard] of Object.entries(GUARDS)) {
|
|
209
|
+
if (!enabled.has(id) || !bound(id, 'PreToolUse', tool)) continue;
|
|
210
|
+
const reason = guard(input, context);
|
|
211
|
+
if (reason !== null)
|
|
212
|
+
return { exitCode: REFUSAL_EXIT_CODE, stdout: '', stderr: `[aisac ${id}] ${reason}\n` };
|
|
213
|
+
}
|
|
214
|
+
return quiet;
|
|
215
|
+
}
|
|
216
|
+
if (options.event === 'PostToolUse') {
|
|
217
|
+
let reminder = '';
|
|
218
|
+
for (const filePath of editedFiles(tool, toolInput)) {
|
|
219
|
+
if (enabled.has('format-on-edit') && bound('format-on-edit', 'PostToolUse', tool))
|
|
220
|
+
await formatEdited(projectDir, filePath);
|
|
221
|
+
if (enabled.has('continuity-reminder') && bound('continuity-reminder', 'PostToolUse', tool))
|
|
222
|
+
await recordEdit(context, input.session_id, filePath);
|
|
223
|
+
if (
|
|
224
|
+
reminder.length === 0 &&
|
|
225
|
+
enabled.has('docs-reminder') &&
|
|
226
|
+
bound('docs-reminder', 'PostToolUse', tool)
|
|
227
|
+
)
|
|
228
|
+
reminder = await docsReminder(context, input.session_id, filePath);
|
|
229
|
+
}
|
|
230
|
+
return reminder.length === 0
|
|
231
|
+
? quiet
|
|
232
|
+
: {
|
|
233
|
+
exitCode: 0,
|
|
234
|
+
stdout: JSON.stringify({
|
|
235
|
+
hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: reminder },
|
|
236
|
+
}),
|
|
237
|
+
stderr: '',
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
if (options.event === 'UserPromptSubmit') {
|
|
241
|
+
if (enabled.has('docs-reminder') || enabled.has('continuity-reminder'))
|
|
242
|
+
await resetTurn(context, input.session_id);
|
|
243
|
+
return quiet;
|
|
244
|
+
}
|
|
245
|
+
if (options.event === 'Stop') {
|
|
246
|
+
const reason = enabled.has('continuity-reminder')
|
|
247
|
+
? await continuityReminder(context, input.session_id, input.stop_hook_active)
|
|
248
|
+
: '';
|
|
249
|
+
return reason.length === 0
|
|
250
|
+
? quiet
|
|
251
|
+
: { exitCode: 0, stdout: JSON.stringify({ decision: 'block', reason }), stderr: '' };
|
|
252
|
+
}
|
|
253
|
+
if (options.event === 'PreCompact') {
|
|
254
|
+
if (enabled.has('compact-continuity')) await saveCompactSnapshot(context, input.session_id);
|
|
255
|
+
return quiet;
|
|
256
|
+
}
|
|
257
|
+
const source = typeof input.source === 'string' ? input.source : 'startup';
|
|
258
|
+
const text =
|
|
259
|
+
source === 'compact'
|
|
260
|
+
? enabled.has('compact-continuity')
|
|
261
|
+
? await restoreCompactSnapshot(context, input.session_id)
|
|
262
|
+
: ''
|
|
263
|
+
: enabled.has('session-context') && bound('session-context', 'SessionStart', source)
|
|
264
|
+
? await sessionContext(context)
|
|
265
|
+
: '';
|
|
266
|
+
return { exitCode: 0, stdout: text, stderr: '' };
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
async function main() {
|
|
270
|
+
const options = parseArguments(process.argv.slice(2));
|
|
271
|
+
if (options === null || options.hooks.length === 0) return;
|
|
272
|
+
const raw = await readInput();
|
|
273
|
+
if (raw === null) return;
|
|
274
|
+
/** @type {unknown} */
|
|
275
|
+
const parsed = JSON.parse(raw);
|
|
276
|
+
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return;
|
|
277
|
+
const result = await dispatch(options, /** @type {Record<string, unknown>} */ (parsed));
|
|
278
|
+
if (result.stdout.length > 0) process.stdout.write(result.stdout);
|
|
279
|
+
if (result.stderr.length > 0) process.stderr.write(result.stderr);
|
|
280
|
+
process.exitCode = result.exitCode;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href)
|
|
284
|
+
main().catch(() => {
|
|
285
|
+
process.exitCode = 0;
|
|
286
|
+
});
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/**
|
|
3
|
+
* A small POSIX-style shell word splitter for guardrail decisions. It never
|
|
4
|
+
* runs anything. It keeps quotes, escapes and command substitutions inside
|
|
5
|
+
* their word, splits commands on control operators, and marks redirection
|
|
6
|
+
* targets. When the text cannot be split (an unterminated quote), `ok` is
|
|
7
|
+
* false and callers fall back to a word-boundary scan of the raw text.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* @typedef {object} ShellCommand
|
|
12
|
+
* @property {string[]} words Words of one simple command, without redirections.
|
|
13
|
+
* @property {string[]} targets File targets of its redirections (`>`, `>>`, `<`, `&>`, ...).
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
const CONTROL_OPERATORS = ['&&', '||', ';;', '|&', ';', '|', '&', '(', ')'];
|
|
17
|
+
const REDIRECTIONS = ['&>>', '&>', '>>', '>|', '<>', '<<<', '<<', '>', '<'];
|
|
18
|
+
const HEREDOC_OPERATORS = new Set(['<<', '<<<']);
|
|
19
|
+
const MAX_COMMAND_LENGTH = 64 * 1024;
|
|
20
|
+
|
|
21
|
+
/** @param {string} text @param {number} index @param {string[]} candidates */
|
|
22
|
+
function operatorAt(text, index, candidates) {
|
|
23
|
+
return candidates.find((candidate) => text.startsWith(candidate, index));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Read a `$(...)` or backtick substitution verbatim, so its text stays in the word.
|
|
28
|
+
* @param {string} text @param {number} start index of `$(` or the backtick
|
|
29
|
+
* @returns {number} index after the substitution, or -1 when it never closes
|
|
30
|
+
*/
|
|
31
|
+
function substitutionEnd(text, start) {
|
|
32
|
+
if (text[start] === '`') {
|
|
33
|
+
const close = text.indexOf('`', start + 1);
|
|
34
|
+
return close === -1 ? -1 : close + 1;
|
|
35
|
+
}
|
|
36
|
+
let depth = 0;
|
|
37
|
+
for (let index = start; index < text.length; index += 1) {
|
|
38
|
+
if (text[index] === '(') depth += 1;
|
|
39
|
+
else if (text[index] === ')') {
|
|
40
|
+
depth -= 1;
|
|
41
|
+
if (depth === 0) return index + 1;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return -1;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Split a shell command line into simple commands.
|
|
49
|
+
* @param {string} text
|
|
50
|
+
* @returns {{ ok: boolean, commands: ShellCommand[] }}
|
|
51
|
+
*/
|
|
52
|
+
export function splitShell(text) {
|
|
53
|
+
if (typeof text !== 'string' || text.length > MAX_COMMAND_LENGTH)
|
|
54
|
+
return { ok: false, commands: [] };
|
|
55
|
+
/** @type {ShellCommand[]} */
|
|
56
|
+
const commands = [];
|
|
57
|
+
/** @type {ShellCommand} */
|
|
58
|
+
let current = { words: [], targets: [] };
|
|
59
|
+
let word = '';
|
|
60
|
+
let inWord = false;
|
|
61
|
+
/** @type {string | null} */
|
|
62
|
+
let pendingRedirection = null;
|
|
63
|
+
|
|
64
|
+
const endWord = () => {
|
|
65
|
+
if (!inWord) return;
|
|
66
|
+
if (pendingRedirection !== null) {
|
|
67
|
+
if (!HEREDOC_OPERATORS.has(pendingRedirection)) current.targets.push(word);
|
|
68
|
+
pendingRedirection = null;
|
|
69
|
+
} else current.words.push(word);
|
|
70
|
+
word = '';
|
|
71
|
+
inWord = false;
|
|
72
|
+
};
|
|
73
|
+
const endCommand = () => {
|
|
74
|
+
endWord();
|
|
75
|
+
if (current.words.length > 0 || current.targets.length > 0) commands.push(current);
|
|
76
|
+
current = { words: [], targets: [] };
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
let index = 0;
|
|
80
|
+
while (index < text.length) {
|
|
81
|
+
const char = text[index];
|
|
82
|
+
if (char === ' ' || char === '\t') {
|
|
83
|
+
endWord();
|
|
84
|
+
index += 1;
|
|
85
|
+
} else if (char === '\n') {
|
|
86
|
+
endCommand();
|
|
87
|
+
index += 1;
|
|
88
|
+
} else if (char === '#' && !inWord) {
|
|
89
|
+
const newline = text.indexOf('\n', index);
|
|
90
|
+
index = newline === -1 ? text.length : newline;
|
|
91
|
+
} else if (char === "'") {
|
|
92
|
+
const close = text.indexOf("'", index + 1);
|
|
93
|
+
if (close === -1) return { ok: false, commands: [] };
|
|
94
|
+
word += text.slice(index + 1, close);
|
|
95
|
+
inWord = true;
|
|
96
|
+
index = close + 1;
|
|
97
|
+
} else if (char === '"') {
|
|
98
|
+
let cursor = index + 1;
|
|
99
|
+
let closed = false;
|
|
100
|
+
while (cursor < text.length) {
|
|
101
|
+
const inner = text[cursor];
|
|
102
|
+
if (
|
|
103
|
+
inner === '\\' &&
|
|
104
|
+
cursor + 1 < text.length &&
|
|
105
|
+
'"\\$`\n'.includes(text[cursor + 1] ?? '')
|
|
106
|
+
) {
|
|
107
|
+
if (text[cursor + 1] !== '\n') word += text[cursor + 1];
|
|
108
|
+
cursor += 2;
|
|
109
|
+
} else if (inner === '"') {
|
|
110
|
+
closed = true;
|
|
111
|
+
cursor += 1;
|
|
112
|
+
break;
|
|
113
|
+
} else if (inner === '$' && text[cursor + 1] === '(') {
|
|
114
|
+
const end = substitutionEnd(text, cursor + 1);
|
|
115
|
+
if (end === -1) return { ok: false, commands: [] };
|
|
116
|
+
word += text.slice(cursor, end);
|
|
117
|
+
cursor = end;
|
|
118
|
+
} else {
|
|
119
|
+
word += inner;
|
|
120
|
+
cursor += 1;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
if (!closed) return { ok: false, commands: [] };
|
|
124
|
+
inWord = true;
|
|
125
|
+
index = cursor;
|
|
126
|
+
} else if (char === '\\') {
|
|
127
|
+
if (text[index + 1] === '\n') index += 2;
|
|
128
|
+
else {
|
|
129
|
+
word += text[index + 1] ?? '';
|
|
130
|
+
inWord = true;
|
|
131
|
+
index += 2;
|
|
132
|
+
}
|
|
133
|
+
} else if ((char === '$' && text[index + 1] === '(') || char === '`') {
|
|
134
|
+
const end = substitutionEnd(text, char === '`' ? index : index + 1);
|
|
135
|
+
if (end === -1) return { ok: false, commands: [] };
|
|
136
|
+
word += text.slice(index, end);
|
|
137
|
+
inWord = true;
|
|
138
|
+
index = end;
|
|
139
|
+
} else {
|
|
140
|
+
const redirection = operatorAt(text, index, REDIRECTIONS);
|
|
141
|
+
const descriptorWord = inWord && /^\d+$/u.test(word);
|
|
142
|
+
if (redirection !== undefined && (!inWord || descriptorWord)) {
|
|
143
|
+
if (descriptorWord) {
|
|
144
|
+
word = '';
|
|
145
|
+
inWord = false;
|
|
146
|
+
} else endWord();
|
|
147
|
+
index += redirection.length;
|
|
148
|
+
// `2>&1` and `>&2` duplicate a descriptor; they name no file.
|
|
149
|
+
if (text[index] === '&' && /\d|-/u.test(text[index + 1] ?? '')) {
|
|
150
|
+
index += 2;
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
pendingRedirection = redirection;
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
const operator = operatorAt(text, index, CONTROL_OPERATORS);
|
|
157
|
+
if (operator !== undefined) {
|
|
158
|
+
endCommand();
|
|
159
|
+
index += operator.length;
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
word += char;
|
|
163
|
+
inWord = true;
|
|
164
|
+
index += 1;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
endCommand();
|
|
168
|
+
return { ok: true, commands };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Basename of a program word (`/usr/bin/git` -> `git`). @param {string} word */
|
|
172
|
+
export function programName(word) {
|
|
173
|
+
const slash = word.lastIndexOf('/');
|
|
174
|
+
return slash === -1 ? word : word.slice(slash + 1);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const WRAPPERS = new Set([
|
|
178
|
+
'sudo',
|
|
179
|
+
'doas',
|
|
180
|
+
'env',
|
|
181
|
+
'command',
|
|
182
|
+
'nice',
|
|
183
|
+
'nohup',
|
|
184
|
+
'time',
|
|
185
|
+
'exec',
|
|
186
|
+
'npx',
|
|
187
|
+
'bunx',
|
|
188
|
+
]);
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* The words of a command with leading `VAR=value` assignments and wrappers
|
|
192
|
+
* such as `sudo` or `env` removed, so `sudo rm -rf /` is seen as `rm -rf /`.
|
|
193
|
+
* @param {string[]} words
|
|
194
|
+
*/
|
|
195
|
+
export function effectiveWords(words) {
|
|
196
|
+
let index = 0;
|
|
197
|
+
while (index < words.length) {
|
|
198
|
+
const word = words[index] ?? '';
|
|
199
|
+
if (/^[A-Za-z_][A-Za-z0-9_]*=/u.test(word)) index += 1;
|
|
200
|
+
else if (WRAPPERS.has(programName(word))) {
|
|
201
|
+
index += 1;
|
|
202
|
+
while ((words[index] ?? '').startsWith('-')) index += 1;
|
|
203
|
+
} else break;
|
|
204
|
+
}
|
|
205
|
+
return words.slice(index);
|
|
206
|
+
}
|