@carrieros/cli 0.2.0 → 0.3.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/README.md +142 -57
- package/dist/commands/attach.js +45 -0
- package/dist/commands/btw.js +78 -0
- package/dist/commands/changes.js +167 -0
- package/dist/commands/chat.js +80 -14
- package/dist/commands/context.js +160 -0
- package/dist/commands/doctor.js +46 -1
- package/dist/commands/files.js +84 -23
- package/dist/commands/help.js +1 -0
- package/dist/commands/history.js +88 -23
- package/dist/commands/login.js +31 -7
- package/dist/commands/memory.js +162 -0
- package/dist/commands/mode-model.js +39 -3
- package/dist/commands/modes.js +4 -1
- package/dist/commands/project.js +106 -0
- package/dist/commands/repo.js +146 -0
- package/dist/commands/repos.js +61 -0
- package/dist/commands/review.js +92 -0
- package/dist/commands/search.js +92 -0
- package/dist/commands/sessions.js +219 -65
- package/dist/commands/settings.js +87 -0
- package/dist/commands/update.js +159 -0
- package/dist/commands/upload.js +204 -31
- package/dist/commands/usage.js +212 -16
- package/dist/ide/editor-context.js +172 -0
- package/dist/ide/ide-session.js +94 -0
- package/dist/ide/tool-host.js +109 -0
- package/dist/main.js +26 -1
- package/dist/services/api.js +140 -6
- package/dist/services/chat-stream.js +145 -0
- package/dist/services/checkpoints.js +116 -0
- package/dist/services/client-tools.js +260 -0
- package/dist/services/command-coordinator.js +200 -0
- package/dist/services/command-policy.js +404 -0
- package/dist/services/config.js +247 -22
- package/dist/services/context.js +265 -20
- package/dist/services/device-auth.js +42 -30
- package/dist/services/diff.js +196 -0
- package/dist/services/env-policy.js +108 -0
- package/dist/services/file-detect.js +104 -0
- package/dist/services/file-resolver.js +199 -0
- package/dist/services/file-upload.js +126 -0
- package/dist/services/git-tools.js +248 -0
- package/dist/services/glob-match.js +164 -0
- package/dist/services/helper-bin.js +64 -0
- package/dist/services/ignore-rules.js +189 -0
- package/dist/services/job-helper.js +307 -0
- package/dist/services/local-files.js +517 -0
- package/dist/services/local-tools.js +432 -0
- package/dist/services/login-flow.js +15 -8
- package/dist/services/meta.js +3 -1
- package/dist/services/mutation-coordinator.js +161 -0
- package/dist/services/mutations.js +493 -0
- package/dist/services/open-url.js +68 -0
- package/dist/services/output.js +5 -2
- package/dist/services/packaged.js +24 -0
- package/dist/services/process-runner.js +406 -0
- package/dist/services/project-context.js +298 -0
- package/dist/services/redaction.js +201 -0
- package/dist/services/secure-store.js +197 -0
- package/dist/services/session-resolver.js +108 -0
- package/dist/services/sia.js +51 -0
- package/dist/services/update.js +286 -0
- package/dist/services/workspace-registry.js +309 -0
- package/dist/services/workspace.js +573 -0
- package/dist/shell/shell-chat.js +1028 -57
- package/dist/shell/shell-commands.js +200 -11
- package/dist/shell/shell-prompt.js +81 -8
- package/dist/shell/shell-renderer.js +7 -19
- package/dist/shell/shell-router.js +19 -3
- package/dist/shell/shell.js +185 -17
- package/dist/types/index.js +3 -1
- package/dist/ui/approval.js +81 -0
- package/dist/ui/banner.js +39 -0
- package/dist/ui/btw-overlay.js +230 -0
- package/dist/ui/change-review.js +87 -0
- package/dist/ui/chat-renderer.js +206 -13
- package/dist/ui/colors.js +4 -0
- package/dist/ui/command-filter.js +26 -5
- package/dist/ui/command-palette.js +17 -4
- package/dist/ui/command-registry.js +84 -9
- package/dist/ui/command-review.js +138 -0
- package/dist/ui/composer-layout.js +41 -0
- package/dist/ui/conversation.js +398 -0
- package/dist/ui/interrupt.js +35 -0
- package/dist/ui/live.js +3 -1
- package/dist/ui/markdown.js +63 -9
- package/dist/ui/message.js +14 -31
- package/dist/ui/screen-prompt.js +181 -0
- package/dist/ui/screen.js +1 -1
- package/dist/ui/select.js +185 -29
- package/dist/ui/sia-qa.js +213 -0
- package/dist/ui/text-prompt.js +74 -0
- package/dist/ui/trust.js +93 -0
- package/dist/ui/ui.js +4 -1
- package/package.json +13 -2
- package/dist/ui/activity.js +0 -77
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import { PolicyError, evaluateCommand } from "./command-policy.js";
|
|
2
|
+
import { JobHelperError } from "./job-helper.js";
|
|
3
|
+
import { RunnerError, runProcess } from "./process-runner.js";
|
|
4
|
+
import { Redactor, projectEnvSecrets } from "./redaction.js";
|
|
5
|
+
import { neutralizingOverrides } from "./workspace.js";
|
|
6
|
+
import { RepositoryError, activeRepository, isWildcardSelector, listRepositories, resolveOperableRepository } from "./workspace-registry.js";
|
|
7
|
+
/**
|
|
8
|
+
* One turn's proposed local commands: check → ask → run → answer.
|
|
9
|
+
*
|
|
10
|
+
* Order is the whole point. The policy decides first, so a refused command
|
|
11
|
+
* never reaches the prompt. The person at the keyboard decides second, on
|
|
12
|
+
* exactly what will run — resolved script text included. Only then does the
|
|
13
|
+
* contained runner start anything. Commands run one at a time.
|
|
14
|
+
*
|
|
15
|
+
* Like the change reviewer, this is not an agent: it never proposes, retries or
|
|
16
|
+
* re-runs anything, and a "no" ends command proposals for the rest of the turn.
|
|
17
|
+
*/
|
|
18
|
+
/** Largest serialized result posted — under the server's 64 KB cap. */
|
|
19
|
+
const MAX_RESULT_BYTES = 62 * 1024;
|
|
20
|
+
/** Keep the posted result under the cap by trimming the middle of the output. */
|
|
21
|
+
export function fitCommandResult(result) {
|
|
22
|
+
let out = result;
|
|
23
|
+
let size = Buffer.byteLength(JSON.stringify(out), "utf8");
|
|
24
|
+
while (size > MAX_RESULT_BYTES && typeof out.output === "string" && out.output.length > 0) {
|
|
25
|
+
const text = out.output;
|
|
26
|
+
const keep = Math.floor(text.length * 0.8);
|
|
27
|
+
const head = text.slice(0, Math.floor(keep * 0.25));
|
|
28
|
+
const tail = text.slice(text.length - Math.floor(keep * 0.75));
|
|
29
|
+
out = { ...out, output: `${head}\n… [output trimmed to fit] …\n${tail}`, truncated: true };
|
|
30
|
+
size = Buffer.byteLength(JSON.stringify(out), "utf8");
|
|
31
|
+
}
|
|
32
|
+
return out;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* The repository a command runs in.
|
|
36
|
+
*
|
|
37
|
+
* Omitted means the active repository. A name may be any registered, TRUSTED
|
|
38
|
+
* repository — the user reads that name on the approval card before anything
|
|
39
|
+
* starts, and the active repository does not move. A wildcard, an unknown name
|
|
40
|
+
* or an untrusted one is an error the model sees.
|
|
41
|
+
*
|
|
42
|
+
* The returned root is what the policy, the cwd and the runner all use, so the
|
|
43
|
+
* package.json a script is read from is the SELECTED repository's, never the
|
|
44
|
+
* active one's.
|
|
45
|
+
*/
|
|
46
|
+
function commandRepository(selector, fallbackRoot) {
|
|
47
|
+
if (selector === undefined || selector === null || selector === "") {
|
|
48
|
+
return repositoryForRoot(fallbackRoot) ?? activeRepository();
|
|
49
|
+
}
|
|
50
|
+
if (isWildcardSelector(selector)) {
|
|
51
|
+
throw new RunnerError("REPOSITORY_WILDCARD_NOT_ALLOWED", 'A command must name one repository; "*" is not accepted.');
|
|
52
|
+
}
|
|
53
|
+
return resolveOperableRepository(selector);
|
|
54
|
+
}
|
|
55
|
+
/** The registered repository a root belongs to, for the result and the audit. */
|
|
56
|
+
function repositoryForRoot(root) {
|
|
57
|
+
const norm = (p) => (process.platform === "win32" ? p.toLowerCase() : p);
|
|
58
|
+
return listRepositories().find((r) => norm(r.root) === norm(root));
|
|
59
|
+
}
|
|
60
|
+
function errorCodeOf(err) {
|
|
61
|
+
if (err instanceof PolicyError || err instanceof RunnerError || err instanceof JobHelperError || err instanceof RepositoryError) {
|
|
62
|
+
return { code: err.code, message: err.message };
|
|
63
|
+
}
|
|
64
|
+
return { code: "START_FAILED", message: err?.message ?? "The command could not be run." };
|
|
65
|
+
}
|
|
66
|
+
export function createCommandCoordinator(opts) {
|
|
67
|
+
const { ui } = opts;
|
|
68
|
+
let chain = Promise.resolve();
|
|
69
|
+
let declined = false;
|
|
70
|
+
const fail = (call, started, code, message) => opts.submit({ tool_call_id: call.tool_call_id, ok: false, error: { code, message }, duration_ms: Date.now() - started });
|
|
71
|
+
async function process(call) {
|
|
72
|
+
const started = Date.now();
|
|
73
|
+
const args = (call.arguments ?? {});
|
|
74
|
+
const reason = typeof args.reason === "string" ? args.reason.slice(0, 300) : "";
|
|
75
|
+
if (declined) {
|
|
76
|
+
await fail(call, started, "COMMAND_REJECTED", "The user already declined a command in this turn. Nothing ran; ask how to proceed.");
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
if (opts.signal.aborted) {
|
|
80
|
+
await fail(call, started, "COMMAND_CANCELLED", "The turn was stopped. Nothing ran.");
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
// 1. Which repository, then policy — both before anyone is asked. A command
|
|
84
|
+
// runs in ONE repository: the active one, or one explicitly named as long as
|
|
85
|
+
// it IS the active one. Naming another is refused, never redirected.
|
|
86
|
+
let root = opts.root;
|
|
87
|
+
let repository = repositoryForRoot(opts.root);
|
|
88
|
+
try {
|
|
89
|
+
repository = commandRepository(args.repository, opts.root);
|
|
90
|
+
root = repository.root;
|
|
91
|
+
}
|
|
92
|
+
catch (err) {
|
|
93
|
+
const e = errorCodeOf(err);
|
|
94
|
+
ui.finished({ decision: null, errorCode: e.code, message: e.message });
|
|
95
|
+
await fail(call, started, e.code, e.message);
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
let decision;
|
|
99
|
+
try {
|
|
100
|
+
const { reason: _r, repository: _repo, ...proposal } = args;
|
|
101
|
+
decision = evaluateCommand(proposal, root);
|
|
102
|
+
}
|
|
103
|
+
catch (err) {
|
|
104
|
+
const e = errorCodeOf(err);
|
|
105
|
+
ui.finished({ decision: null, errorCode: e.code, message: e.message });
|
|
106
|
+
await fail(call, started, e.code, e.message);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
// Git reads file content through repository-configured programs; neutralize
|
|
110
|
+
// them for this call exactly as repository detection does.
|
|
111
|
+
if (decision.program === "git") {
|
|
112
|
+
const overrides = neutralizingOverrides(root);
|
|
113
|
+
if (!overrides) {
|
|
114
|
+
const message = "The repository's Git configuration could not be read safely, so the command was not run.";
|
|
115
|
+
ui.finished({ decision, errorCode: "COMMAND_DENIED", message });
|
|
116
|
+
await fail(call, started, "COMMAND_DENIED", message);
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
const sub = decision.effectiveArgs.indexOf(decision.args[0]);
|
|
120
|
+
decision = { ...decision, effectiveArgs: [...decision.effectiveArgs.slice(0, sub), ...overrides, ...decision.effectiveArgs.slice(sub)] };
|
|
121
|
+
}
|
|
122
|
+
// 2. Approval, then 3. run — both while holding the terminal.
|
|
123
|
+
await opts.withTerminal(async () => {
|
|
124
|
+
const answer = await ui.review(decision, reason, repository?.name);
|
|
125
|
+
if (answer !== "approve") {
|
|
126
|
+
declined = true;
|
|
127
|
+
const code = answer === "timeout" ? "APPROVAL_TIMEOUT" : answer === "cancel" ? "COMMAND_CANCELLED" : "COMMAND_REJECTED";
|
|
128
|
+
const message = answer === "timeout"
|
|
129
|
+
? "No one approved the command in time. Nothing ran."
|
|
130
|
+
: answer === "cancel"
|
|
131
|
+
? "The user stopped the turn. Nothing ran."
|
|
132
|
+
: "The user rejected the command. Nothing ran.";
|
|
133
|
+
ui.finished({ decision, errorCode: code, message });
|
|
134
|
+
await fail(call, started, code, message);
|
|
135
|
+
if (answer === "cancel")
|
|
136
|
+
ui.cancelTurn();
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
let result;
|
|
140
|
+
try {
|
|
141
|
+
const redactor = new Redactor([...projectEnvSecrets(root), ...(opts.cliSecrets ?? [])]);
|
|
142
|
+
result = await runProcess({
|
|
143
|
+
program: decision.program,
|
|
144
|
+
args: decision.effectiveArgs,
|
|
145
|
+
cwd: decision.cwdAbsolute,
|
|
146
|
+
root,
|
|
147
|
+
timeoutMs: decision.timeoutMs,
|
|
148
|
+
signal: opts.signal,
|
|
149
|
+
redactor,
|
|
150
|
+
onStart: () => ui.started(decision),
|
|
151
|
+
onOutput: (stream, text) => ui.output(stream, text)
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
catch (err) {
|
|
155
|
+
const e = errorCodeOf(err);
|
|
156
|
+
ui.finished({ decision, errorCode: e.code, message: e.message });
|
|
157
|
+
await fail(call, started, e.code, e.message);
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
ui.finished({ decision, result });
|
|
161
|
+
const payload = fitCommandResult({
|
|
162
|
+
// Reported from the RESOLVED handle, so the audit records which
|
|
163
|
+
// repository was selected rather than inferring one from a path.
|
|
164
|
+
repository: repository?.name,
|
|
165
|
+
repository_id: repository?.id,
|
|
166
|
+
program: decision.program,
|
|
167
|
+
args: decision.args,
|
|
168
|
+
cwd: decision.cwdRelative,
|
|
169
|
+
risk_tier: decision.tier,
|
|
170
|
+
network_label: decision.network,
|
|
171
|
+
exit_code: result.exit_code,
|
|
172
|
+
signal: result.signal,
|
|
173
|
+
timed_out: result.timed_out,
|
|
174
|
+
cancelled: result.cancelled,
|
|
175
|
+
tree_killed: result.tree_killed,
|
|
176
|
+
started_at: result.started_at,
|
|
177
|
+
ended_at: result.ended_at,
|
|
178
|
+
duration_ms: result.duration_ms,
|
|
179
|
+
stdout_bytes: result.stdout_bytes,
|
|
180
|
+
stderr_bytes: result.stderr_bytes,
|
|
181
|
+
truncated: result.truncated,
|
|
182
|
+
redaction_count: result.redaction_count,
|
|
183
|
+
dropped_environment_names: result.dropped_environment_names,
|
|
184
|
+
...(decision.script ? { script: { name: decision.script.name, text: decision.script.text.slice(0, 500) } } : {}),
|
|
185
|
+
output: result.output
|
|
186
|
+
});
|
|
187
|
+
await opts.submit({ tool_call_id: call.tool_call_id, ok: true, result: payload, duration_ms: Date.now() - started });
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
return {
|
|
191
|
+
handle(call) {
|
|
192
|
+
const next = chain.then(() => process(call)).catch(async (err) => {
|
|
193
|
+
// A bug here must still answer the call, never leave the turn waiting.
|
|
194
|
+
await fail(call, Date.now(), "START_FAILED", err?.message ?? "The command could not be processed.").catch(() => undefined);
|
|
195
|
+
});
|
|
196
|
+
chain = next;
|
|
197
|
+
return next;
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
}
|
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { isInside } from "./local-files.js";
|
|
4
|
+
import { MAX_TIMEOUT_MS, RunnerError, resolveCwd } from "./process-runner.js";
|
|
5
|
+
export class PolicyError extends Error {
|
|
6
|
+
code;
|
|
7
|
+
constructor(code, message) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.code = code;
|
|
10
|
+
this.name = "PolicyError";
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
const deny = (message) => {
|
|
14
|
+
throw new PolicyError("COMMAND_DENIED", message);
|
|
15
|
+
};
|
|
16
|
+
const SHELL_OPERATOR = /[&|;<>`\r\n\0]|\$\(/;
|
|
17
|
+
/**
|
|
18
|
+
* The boundary, in the user's words, on every command that runs project code.
|
|
19
|
+
*
|
|
20
|
+
* Containment is real but narrow: the Job Object ends every process the command
|
|
21
|
+
* STARTS. It cannot govern work the command hands to something already running
|
|
22
|
+
* or to a Windows service — a document opened through a file association lands
|
|
23
|
+
* in an editor that was already open, a URL in the browser, a process created
|
|
24
|
+
* through WMI or the Task Scheduler is started by a service. None of those are
|
|
25
|
+
* the command's children, so none of them are in its job. R0 commands run no
|
|
26
|
+
* project code and do not get this note; R1 and R2 always do.
|
|
27
|
+
* See docs/SECURITY-local-execution.md.
|
|
28
|
+
*/
|
|
29
|
+
export const PROJECT_CODE_NOTE = "Project code runs as your Windows account and may open other applications — those are not contained by this command.";
|
|
30
|
+
const MIN_TIMEOUT_MS = 5_000;
|
|
31
|
+
const DEFAULT_TIMEOUT = { R0: 60_000, R1: 10 * 60_000, R2: 10 * 60_000 };
|
|
32
|
+
/** Named so the refusal says why, not just "not allowed". */
|
|
33
|
+
const KNOWN_DANGEROUS = {
|
|
34
|
+
cmd: "a shell",
|
|
35
|
+
powershell: "a shell",
|
|
36
|
+
pwsh: "a shell",
|
|
37
|
+
bash: "a shell",
|
|
38
|
+
sh: "a shell",
|
|
39
|
+
zsh: "a shell",
|
|
40
|
+
wsl: "a shell",
|
|
41
|
+
python: "an interpreter",
|
|
42
|
+
python3: "an interpreter",
|
|
43
|
+
py: "an interpreter",
|
|
44
|
+
ruby: "an interpreter",
|
|
45
|
+
perl: "an interpreter",
|
|
46
|
+
deno: "an interpreter",
|
|
47
|
+
bun: "an interpreter",
|
|
48
|
+
npx: "a remote package runner",
|
|
49
|
+
curl: "a network tool",
|
|
50
|
+
wget: "a network tool",
|
|
51
|
+
"invoke-webrequest": "a network tool",
|
|
52
|
+
"invoke-restmethod": "a network tool",
|
|
53
|
+
"invoke-expression": "a shell command",
|
|
54
|
+
certutil: "a download tool",
|
|
55
|
+
bitsadmin: "a download tool",
|
|
56
|
+
rm: "a deletion command",
|
|
57
|
+
del: "a deletion command",
|
|
58
|
+
erase: "a deletion command",
|
|
59
|
+
rd: "a deletion command",
|
|
60
|
+
rmdir: "a deletion command",
|
|
61
|
+
format: "a system command",
|
|
62
|
+
reg: "a system command",
|
|
63
|
+
sc: "a system command",
|
|
64
|
+
schtasks: "a system command",
|
|
65
|
+
icacls: "a system command",
|
|
66
|
+
takeown: "a system command",
|
|
67
|
+
net: "a system command",
|
|
68
|
+
netsh: "a system command",
|
|
69
|
+
taskkill: "a system command",
|
|
70
|
+
msiexec: "an installer",
|
|
71
|
+
start: "a shell command",
|
|
72
|
+
explorer: "a launcher",
|
|
73
|
+
rundll32: "a launcher",
|
|
74
|
+
mshta: "a launcher",
|
|
75
|
+
cscript: "a script host",
|
|
76
|
+
wscript: "a script host"
|
|
77
|
+
};
|
|
78
|
+
// ── Shared checks ────────────────────────────────────────────────────────────
|
|
79
|
+
function asArgs(value) {
|
|
80
|
+
if (value === undefined)
|
|
81
|
+
return [];
|
|
82
|
+
if (!Array.isArray(value) || value.some((a) => typeof a !== "string")) {
|
|
83
|
+
throw new PolicyError("INVALID_COMMAND", "args must be an array of strings.");
|
|
84
|
+
}
|
|
85
|
+
if (value.length > 32)
|
|
86
|
+
throw new PolicyError("INVALID_COMMAND", "Too many arguments.");
|
|
87
|
+
for (const a of value) {
|
|
88
|
+
if (a.length > 1024)
|
|
89
|
+
throw new PolicyError("INVALID_COMMAND", "An argument is too long.");
|
|
90
|
+
if (SHELL_OPERATOR.test(a))
|
|
91
|
+
deny(`Shell syntax is not accepted: ${JSON.stringify(a.slice(0, 60))}`);
|
|
92
|
+
}
|
|
93
|
+
return value;
|
|
94
|
+
}
|
|
95
|
+
/** A positional argument that names a path must stay inside the project. */
|
|
96
|
+
function checkPathArg(arg, cwdAbs, root) {
|
|
97
|
+
if (/^[A-Za-z]:/.test(arg) || arg.startsWith("\\\\") || arg.startsWith("/")) {
|
|
98
|
+
const abs = path.resolve(arg);
|
|
99
|
+
if (!isInside(root, abs)) {
|
|
100
|
+
throw new PolicyError("OUTSIDE_WORKSPACE", `${arg} is outside the project.`);
|
|
101
|
+
}
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
if (!/[\\/]/.test(arg) && arg !== "..")
|
|
105
|
+
return; // a bare name or a revision
|
|
106
|
+
const abs = path.resolve(cwdAbs, arg);
|
|
107
|
+
if (!isInside(root, abs))
|
|
108
|
+
throw new PolicyError("OUTSIDE_WORKSPACE", `${arg} is outside the project.`);
|
|
109
|
+
try {
|
|
110
|
+
const real = fs.realpathSync.native(abs);
|
|
111
|
+
if (!isInside(fs.realpathSync.native(root), real)) {
|
|
112
|
+
throw new PolicyError("OUTSIDE_WORKSPACE", `${arg} links outside the project.`);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
catch (err) {
|
|
116
|
+
if (err instanceof PolicyError)
|
|
117
|
+
throw err;
|
|
118
|
+
/* does not exist (yet) — the lexical check above is what applies */
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
function timeoutFor(tier, requested) {
|
|
122
|
+
if (requested === undefined || requested === null)
|
|
123
|
+
return DEFAULT_TIMEOUT[tier];
|
|
124
|
+
if (typeof requested !== "number" || !Number.isInteger(requested)) {
|
|
125
|
+
throw new PolicyError("INVALID_COMMAND", "timeout_ms must be an integer.");
|
|
126
|
+
}
|
|
127
|
+
return Math.min(MAX_TIMEOUT_MS, Math.max(MIN_TIMEOUT_MS, requested));
|
|
128
|
+
}
|
|
129
|
+
// ── git ──────────────────────────────────────────────────────────────────────
|
|
130
|
+
/** Global hardening, placed before the subcommand. */
|
|
131
|
+
const GIT_GLOBAL = ["--no-pager", "-c", "core.fsmonitor=false", "-c", "core.hooksPath=NUL", "-c", "diff.external="];
|
|
132
|
+
/** Never allowed in any git invocation: each reads or writes outside the command's intent. */
|
|
133
|
+
const GIT_FORBIDDEN = /^(-c|-C|--git-dir|--work-tree|--exec-path|--namespace|--super-prefix|--config-env|--output|--ext-diff|--textconv|--no-index|--upload-pack|--receive-pack|--open-files-in-pager|-O)(=|$)/;
|
|
134
|
+
const GIT_FLAGS = {
|
|
135
|
+
status: /^(-s|--short|-b|--branch|--porcelain(=v[12])?|--long|-u(no|normal|all)?|--untracked-files(=(no|normal|all))?|--ignored(=(traditional|no|matching))?|--ignore-submodules(=(none|untracked|dirty|all))?|-z|--no-renames|--renames|--ahead-behind|--no-ahead-behind|-v|--verbose)$/,
|
|
136
|
+
diff: /^(--stat(=\d+(,\d+)?)?|--numstat|--shortstat|--dirstat|--name-only|--name-status|--summary|--cached|--staged|-U\d+|--unified=\d+|-w|--ignore-all-space|-b|--ignore-space-change|--ignore-blank-lines|--word-diff(=(color|plain|porcelain|none))?|--color=never|--no-color|-p|--patch|-s|--no-patch|--minimal|--patience|--histogram|--diff-filter=[ACDMRTUXB*a-z]+|-M\d*%?|--find-renames(=\d+%?)?|--relative(=.+)?|--check|--exit-code|--quiet|-R|--merge-base|--)$/,
|
|
137
|
+
log: /^(--oneline|-n\d*|-\d+|--max-count=\d+|--skip=\d+|--since=.+|--after=.+|--until=.+|--before=.+|--author=.+|--committer=.+|--grep=.+|-i|--regexp-ignore-case|--stat(=\d+)?|--numstat|--shortstat|--name-only|--name-status|-p|--patch|--graph|--decorate(=(short|full|no))?|--no-decorate|--all|--branches(=.+)?|--tags(=.+)?|--remotes(=.+)?|--format=.+|--pretty(=.+)?|--abbrev-commit|--no-abbrev-commit|--date=.+|--follow|--reverse|--first-parent|--no-merges|--merges|--color=never|--no-color|-U\d+|--)$/,
|
|
138
|
+
show: /^(--stat(=\d+)?|--numstat|--shortstat|--name-only|--name-status|--oneline|--format=.+|--pretty(=.+)?|-p|--patch|-s|--no-patch|--abbrev-commit|--date=.+|--color=never|--no-color|-U\d+|--)$/,
|
|
139
|
+
branch: /^(--list|-l|-a|--all|-r|--remotes|-v|-vv|--verbose|--show-current|--no-color|--color=never|--contains(=.+)?|--no-contains(=.+)?|--merged(=.+)?|--no-merged(=.+)?|--sort=.+|--format=.+|--points-at(=.+)?)$/
|
|
140
|
+
};
|
|
141
|
+
const GIT_WRITE_SUBCOMMANDS = new Set([
|
|
142
|
+
"commit", "push", "pull", "fetch", "reset", "checkout", "switch", "restore", "clean", "rebase", "merge",
|
|
143
|
+
"cherry-pick", "revert", "am", "apply", "stash", "tag", "config", "remote", "rm", "mv", "add", "init",
|
|
144
|
+
"clone", "submodule", "worktree", "gc", "prune", "filter-branch", "update-ref", "update-index", "notes",
|
|
145
|
+
"bisect", "lfs", "credential", "daemon", "archive", "bundle", "format-patch", "send-email", "instaweb"
|
|
146
|
+
]);
|
|
147
|
+
function evaluateGit(args, cwdAbs, root) {
|
|
148
|
+
const sub = args[0];
|
|
149
|
+
if (!sub)
|
|
150
|
+
deny("A git subcommand is required.");
|
|
151
|
+
if (sub.startsWith("-"))
|
|
152
|
+
deny("git options before the subcommand are not allowed.");
|
|
153
|
+
if (GIT_WRITE_SUBCOMMANDS.has(sub))
|
|
154
|
+
deny(`git ${sub} can change the repository or reach the network, and is not allowed.`);
|
|
155
|
+
const flags = GIT_FLAGS[sub];
|
|
156
|
+
if (!flags)
|
|
157
|
+
deny(`git ${sub} is not in the allowed read-only set (status, diff, log, show, branch --list).`);
|
|
158
|
+
const rest = args.slice(1);
|
|
159
|
+
let afterDashDash = false;
|
|
160
|
+
let positional = 0;
|
|
161
|
+
for (const a of rest) {
|
|
162
|
+
if (!afterDashDash && a === "--") {
|
|
163
|
+
afterDashDash = true;
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
if (!afterDashDash && a.startsWith("-")) {
|
|
167
|
+
if (GIT_FORBIDDEN.test(a))
|
|
168
|
+
deny(`git ${a} is not allowed.`);
|
|
169
|
+
if (!flags.test(a))
|
|
170
|
+
deny(`git ${sub} ${a} is not in the allowed set of options.`);
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
positional += 1;
|
|
174
|
+
checkPathArg(a, cwdAbs, root);
|
|
175
|
+
}
|
|
176
|
+
if (sub === "branch" && positional > 0 && !rest.some((a) => a === "--list" || a === "-l")) {
|
|
177
|
+
deny("git branch with a name creates a branch; only listing (--list) is allowed.");
|
|
178
|
+
}
|
|
179
|
+
const readsFiles = ["diff", "log", "show"].includes(sub);
|
|
180
|
+
return {
|
|
181
|
+
tier: "R0",
|
|
182
|
+
program: "git",
|
|
183
|
+
args,
|
|
184
|
+
effectiveArgs: [...GIT_GLOBAL, sub, ...(readsFiles ? ["--no-ext-diff", "--no-textconv"] : []), ...rest],
|
|
185
|
+
network: "none-expected",
|
|
186
|
+
notes: ["Read-only Git command."]
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
// ── node ─────────────────────────────────────────────────────────────────────
|
|
190
|
+
function evaluateNode(args, cwdAbs, root) {
|
|
191
|
+
if (args.length === 1 && (args[0] === "--version" || args[0] === "-v")) {
|
|
192
|
+
return { tier: "R0", program: "node", args, effectiveArgs: args, network: "none-expected", notes: ["Prints the Node.js version."] };
|
|
193
|
+
}
|
|
194
|
+
const [scriptArg, ...rest] = args;
|
|
195
|
+
if (!scriptArg)
|
|
196
|
+
deny("node needs a script file from this project.");
|
|
197
|
+
if (scriptArg.startsWith("-"))
|
|
198
|
+
deny(`node ${scriptArg} is not allowed — only running a script file from this project.`);
|
|
199
|
+
if (!/\.(c|m)?js$/i.test(scriptArg))
|
|
200
|
+
deny("node may only run a .js, .cjs or .mjs file.");
|
|
201
|
+
checkPathArg(scriptArg.includes("/") || scriptArg.includes("\\") ? scriptArg : `./${scriptArg}`, cwdAbs, root);
|
|
202
|
+
const abs = path.resolve(cwdAbs, scriptArg);
|
|
203
|
+
if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) {
|
|
204
|
+
throw new PolicyError("SCRIPT_NOT_FOUND", `${scriptArg} does not exist in this project.`);
|
|
205
|
+
}
|
|
206
|
+
for (const a of rest)
|
|
207
|
+
checkPathArg(a, cwdAbs, root);
|
|
208
|
+
return {
|
|
209
|
+
tier: "R1",
|
|
210
|
+
program: "node",
|
|
211
|
+
args,
|
|
212
|
+
effectiveArgs: args,
|
|
213
|
+
network: "project-code-may-use-network",
|
|
214
|
+
notes: ["Runs a script from this project — project code runs with your permissions."]
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
function nearestPackageJson(cwdAbs, root) {
|
|
218
|
+
let dir = cwdAbs;
|
|
219
|
+
for (;;) {
|
|
220
|
+
const file = path.join(dir, "package.json");
|
|
221
|
+
try {
|
|
222
|
+
if (fs.statSync(file).isFile() && fs.statSync(file).size < 1024 * 1024) {
|
|
223
|
+
return { file, data: JSON.parse(fs.readFileSync(file, "utf8")) };
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
catch {
|
|
227
|
+
/* none or unreadable here */
|
|
228
|
+
}
|
|
229
|
+
if (path.resolve(dir).toLowerCase() === path.resolve(root).toLowerCase())
|
|
230
|
+
return null;
|
|
231
|
+
const parent = path.dirname(dir);
|
|
232
|
+
if (parent === dir || !isInside(root, parent))
|
|
233
|
+
return null;
|
|
234
|
+
dir = parent;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
function projectUses(manager, root, pkg) {
|
|
238
|
+
const lock = manager === "pnpm" ? "pnpm-lock.yaml" : "yarn.lock";
|
|
239
|
+
if (fs.existsSync(path.join(root, lock)))
|
|
240
|
+
return true;
|
|
241
|
+
return typeof pkg?.packageManager === "string" && pkg.packageManager.startsWith(`${manager}@`);
|
|
242
|
+
}
|
|
243
|
+
/** Scripts named for publishing or deploying are never run from here. */
|
|
244
|
+
const DENIED_SCRIPT_NAME = /(^|[:_-])(publish|prepublish|prepublishonly|postpublish|release|deploy|login|logout|adduser)($|[:_-])/i;
|
|
245
|
+
/** Script names that usually rewrite files. */
|
|
246
|
+
const WRITING_SCRIPT_NAME = /(^|[:_-])(format|fmt|fix|prettier|generate|gen|codegen|migrate|migration|seed|install|clean|bump|version|update|upgrade|snapshot)($|[:_-])/i;
|
|
247
|
+
/** Script text that pushes, publishes or deploys: refused. */
|
|
248
|
+
const DENIED_SCRIPT_TEXT = /\b(npm\s+publish|yarn\s+publish|pnpm\s+publish|git\s+push|git\s+commit|git\s+tag|gh\s+release|vercel\s+(--prod|deploy)|netlify\s+deploy|firebase\s+deploy|aws\s+s3\s+(cp|sync)|docker\s+push|twine\s+upload)\b/i;
|
|
249
|
+
/** Script text that writes files or installs: at least R2. */
|
|
250
|
+
const WRITING_SCRIPT_TEXT = /(--write\b|--fix\b|\brimraf\b|\brm\s+-|\bdel\s+\/|\bRemove-Item\b|\bmigrate\b|\bprisma\s+(db|migrate|generate)\b|\bnpm\s+(i|install|ci|update)\b|\byarn\s+(add|install)\b|\bpnpm\s+(add|install)\b|\bnpx\b|\bcurl\b|\bwget\b)/i;
|
|
251
|
+
function evaluatePackageManager(manager, args, cwdAbs, root) {
|
|
252
|
+
if (args.length === 1 && (args[0] === "--version" || args[0] === "-v")) {
|
|
253
|
+
return { tier: "R0", program: manager, args, effectiveArgs: args, network: "none-expected", notes: [`Prints the ${manager} version.`] };
|
|
254
|
+
}
|
|
255
|
+
const pkg = nearestPackageJson(cwdAbs, root);
|
|
256
|
+
if (manager !== "npm" && !projectUses(manager, root, pkg?.data)) {
|
|
257
|
+
deny(`This project does not use ${manager}.`);
|
|
258
|
+
}
|
|
259
|
+
const [verb, ...rest] = args;
|
|
260
|
+
const installVerbs = {
|
|
261
|
+
npm: ["install", "i", "ci", "update"],
|
|
262
|
+
pnpm: ["install", "i", "update"],
|
|
263
|
+
yarn: ["install", "upgrade"]
|
|
264
|
+
};
|
|
265
|
+
if (verb && installVerbs[manager].includes(verb)) {
|
|
266
|
+
if (rest.length > 0)
|
|
267
|
+
deny(`${manager} ${verb} with extra arguments is not allowed — only installing what the project already declares.`);
|
|
268
|
+
if (!pkg)
|
|
269
|
+
throw new PolicyError("SCRIPT_NOT_FOUND", "There is no package.json here.");
|
|
270
|
+
return {
|
|
271
|
+
tier: "R2",
|
|
272
|
+
program: manager,
|
|
273
|
+
args,
|
|
274
|
+
effectiveArgs: args,
|
|
275
|
+
network: "uses-network",
|
|
276
|
+
notes: [
|
|
277
|
+
"Changes files: node_modules and possibly the lockfile.",
|
|
278
|
+
"Uses the network to download packages, and installs can run package scripts.",
|
|
279
|
+
"/undo cannot restore what this command changes."
|
|
280
|
+
]
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
let scriptName;
|
|
284
|
+
if (verb === "test" || verb === "t") {
|
|
285
|
+
if (rest.length)
|
|
286
|
+
deny(`${manager} test with extra arguments is not allowed.`);
|
|
287
|
+
scriptName = "test";
|
|
288
|
+
}
|
|
289
|
+
else if (verb === "run" || verb === "run-script") {
|
|
290
|
+
if (rest.length !== 1)
|
|
291
|
+
deny(`${manager} ${verb} takes exactly one script name and no extra arguments.`);
|
|
292
|
+
scriptName = rest[0];
|
|
293
|
+
}
|
|
294
|
+
else {
|
|
295
|
+
deny(`${manager} ${verb ?? ""} is not allowed. Allowed: --version, test, run <script>, and install.`.replace(" ", " "));
|
|
296
|
+
}
|
|
297
|
+
if (!scriptName || !/^[A-Za-z0-9:_.-]{1,80}$/.test(scriptName))
|
|
298
|
+
deny("That is not a valid script name.");
|
|
299
|
+
if (!pkg)
|
|
300
|
+
throw new PolicyError("SCRIPT_NOT_FOUND", "There is no package.json here.");
|
|
301
|
+
const scripts = pkg.data.scripts ?? {};
|
|
302
|
+
const text = scripts[scriptName];
|
|
303
|
+
if (typeof text !== "string") {
|
|
304
|
+
throw new PolicyError("SCRIPT_NOT_FOUND", `package.json has no "${scriptName}" script.`);
|
|
305
|
+
}
|
|
306
|
+
const pre = typeof scripts[`pre${scriptName}`] === "string" ? scripts[`pre${scriptName}`] : undefined;
|
|
307
|
+
const post = typeof scripts[`post${scriptName}`] === "string" ? scripts[`post${scriptName}`] : undefined;
|
|
308
|
+
const allText = [pre, text, post].filter(Boolean).join("\n");
|
|
309
|
+
if (DENIED_SCRIPT_NAME.test(scriptName))
|
|
310
|
+
deny(`The "${scriptName}" script publishes or deploys, and is not run from here.`);
|
|
311
|
+
if (DENIED_SCRIPT_TEXT.test(allText))
|
|
312
|
+
deny(`The "${scriptName}" script pushes, publishes or deploys, and is not run from here.`);
|
|
313
|
+
const writes = WRITING_SCRIPT_NAME.test(scriptName) || WRITING_SCRIPT_TEXT.test(allText);
|
|
314
|
+
const tier = writes ? "R2" : "R1";
|
|
315
|
+
const notes = ["Runs project code with your permissions."];
|
|
316
|
+
if (writes)
|
|
317
|
+
notes.push("This script looks like it changes files.", "/undo cannot restore what this command changes.");
|
|
318
|
+
if (pre || post)
|
|
319
|
+
notes.push(`Also runs ${[pre && `pre${scriptName}`, post && `post${scriptName}`].filter(Boolean).join(" and ")}.`);
|
|
320
|
+
return {
|
|
321
|
+
tier,
|
|
322
|
+
program: manager,
|
|
323
|
+
args,
|
|
324
|
+
effectiveArgs: verb === "t" ? ["test"] : args,
|
|
325
|
+
network: writes ? "uses-network" : "project-code-may-use-network",
|
|
326
|
+
script: {
|
|
327
|
+
manager,
|
|
328
|
+
name: scriptName,
|
|
329
|
+
text,
|
|
330
|
+
...(pre ? { pre } : {}),
|
|
331
|
+
...(post ? { post } : {}),
|
|
332
|
+
packageJson: path.relative(root, pkg.file).split(path.sep).join("/") || "package.json"
|
|
333
|
+
},
|
|
334
|
+
notes
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
// ── Entry point ──────────────────────────────────────────────────────────────
|
|
338
|
+
/**
|
|
339
|
+
* Decide on one proposed command. Returns the decision for the approval prompt,
|
|
340
|
+
* or throws PolicyError — in which case the user is never asked.
|
|
341
|
+
*/
|
|
342
|
+
export function evaluateCommand(proposal, root) {
|
|
343
|
+
if (!proposal || typeof proposal !== "object" || Array.isArray(proposal)) {
|
|
344
|
+
throw new PolicyError("INVALID_COMMAND", "A command must be an object with program and args.");
|
|
345
|
+
}
|
|
346
|
+
for (const raw of ["command", "cmd", "shell", "script", "commandLine", "command_line"]) {
|
|
347
|
+
if (raw in proposal)
|
|
348
|
+
throw new PolicyError("INVALID_COMMAND", "Raw command strings are not accepted — use program and args.");
|
|
349
|
+
}
|
|
350
|
+
const { program } = proposal;
|
|
351
|
+
if (typeof program !== "string" || !program.trim())
|
|
352
|
+
throw new PolicyError("INVALID_COMMAND", "program is required.");
|
|
353
|
+
if (/\s/.test(program.trim())) {
|
|
354
|
+
throw new PolicyError("INVALID_COMMAND", "program must be a single name — put arguments in args.");
|
|
355
|
+
}
|
|
356
|
+
const args = asArgs(proposal.args);
|
|
357
|
+
const lower = program.trim().toLowerCase();
|
|
358
|
+
if (/[\\/]/.test(lower) || /^[a-z]:/.test(lower))
|
|
359
|
+
deny("program must be a bare name, not a path.");
|
|
360
|
+
const ext = path.extname(lower);
|
|
361
|
+
if (ext === ".cmd" || ext === ".bat" || ext === ".ps1" || ext === ".vbs" || ext === ".js" || ext === ".sh") {
|
|
362
|
+
deny(`${program} is a script file and cannot be run directly.`);
|
|
363
|
+
}
|
|
364
|
+
const name = ext === ".exe" ? lower.slice(0, -4) : lower;
|
|
365
|
+
if (KNOWN_DANGEROUS[name] || name.startsWith("invoke-")) {
|
|
366
|
+
deny(`${program} is ${KNOWN_DANGEROUS[name] ?? "a shell command"} and is never run from here.`);
|
|
367
|
+
}
|
|
368
|
+
let cwdAbsolute;
|
|
369
|
+
const cwdRaw = proposal.cwd === undefined || proposal.cwd === null || proposal.cwd === "" ? "." : proposal.cwd;
|
|
370
|
+
if (typeof cwdRaw !== "string")
|
|
371
|
+
throw new PolicyError("INVALID_COMMAND", "cwd must be a string.");
|
|
372
|
+
try {
|
|
373
|
+
cwdAbsolute = resolveCwd(cwdRaw, root);
|
|
374
|
+
}
|
|
375
|
+
catch (err) {
|
|
376
|
+
if (err instanceof RunnerError) {
|
|
377
|
+
throw new PolicyError(err.code === "OUTSIDE_WORKSPACE" ? "OUTSIDE_WORKSPACE" : "INVALID_COMMAND", err.message);
|
|
378
|
+
}
|
|
379
|
+
throw err;
|
|
380
|
+
}
|
|
381
|
+
const cwdRelative = path.relative(fs.realpathSync.native(root), cwdAbsolute).split(path.sep).join("/") || ".";
|
|
382
|
+
let partial;
|
|
383
|
+
switch (name) {
|
|
384
|
+
case "git":
|
|
385
|
+
partial = evaluateGit(args, cwdAbsolute, root);
|
|
386
|
+
break;
|
|
387
|
+
case "node":
|
|
388
|
+
partial = evaluateNode(args, cwdAbsolute, root);
|
|
389
|
+
break;
|
|
390
|
+
case "npm":
|
|
391
|
+
case "pnpm":
|
|
392
|
+
case "yarn":
|
|
393
|
+
partial = evaluatePackageManager(name, args, cwdAbsolute, root);
|
|
394
|
+
break;
|
|
395
|
+
default:
|
|
396
|
+
return deny(`${program} is not in the allowed command set (git, node, npm, pnpm, yarn).`);
|
|
397
|
+
}
|
|
398
|
+
const notes = partial.tier === "R0" ? partial.notes : [...partial.notes, PROJECT_CODE_NOTE];
|
|
399
|
+
return { ...partial, notes, cwdRelative, cwdAbsolute, timeoutMs: timeoutFor(partial.tier, proposal.timeout_ms) };
|
|
400
|
+
}
|
|
401
|
+
/** One line for display: `npm run build`. Arguments with spaces are quoted for reading only. */
|
|
402
|
+
export function displayCommand(program, args) {
|
|
403
|
+
return [program, ...args.map((a) => (/[\s"]/.test(a) || a === "" ? JSON.stringify(a) : a))].join(" ");
|
|
404
|
+
}
|