@agent-corpus/policy-manager 0.1.0 → 0.2.1
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 +29 -0
- package/dist/audit.d.ts +1 -0
- package/dist/audit.js +5 -2
- package/dist/cli.js +47 -3
- package/dist/evidence.d.ts +7 -0
- package/dist/evidence.js +33 -2
- package/dist/index.d.ts +6 -0
- package/dist/index.js +4 -0
- package/dist/merged.d.ts +14 -0
- package/dist/merged.js +96 -0
- package/dist/permissive.d.ts +23 -0
- package/dist/permissive.js +491 -0
- package/dist/policy.d.ts +5 -2
- package/dist/policy.js +22 -9
- package/dist/profile.d.ts +24 -0
- package/dist/profile.js +113 -0
- package/dist/replay.d.ts +18 -0
- package/dist/replay.js +81 -0
- package/dist/service.d.ts +7 -0
- package/dist/service.js +42 -3
- package/dist/session.d.ts +3 -1
- package/dist/session.js +6 -3
- package/dist/shell.d.ts +13 -0
- package/dist/shell.js +201 -0
- package/package.json +1 -1
package/dist/profile.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { lstatSync, readFileSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { dirname, isAbsolute, join } from "node:path";
|
|
5
|
+
import { canonical, git } from "./evidence.js";
|
|
6
|
+
export const strictProfile = {
|
|
7
|
+
mode: "strict",
|
|
8
|
+
cloudWrites: "human",
|
|
9
|
+
humanPatterns: [],
|
|
10
|
+
scratchRoots: [],
|
|
11
|
+
};
|
|
12
|
+
export function defaultProfilePath() {
|
|
13
|
+
const base = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
|
|
14
|
+
return join(base, "agent-corpus", "policy-manager", "policy.json");
|
|
15
|
+
}
|
|
16
|
+
export class ProfileError extends Error {
|
|
17
|
+
}
|
|
18
|
+
function verifyLocation(path) {
|
|
19
|
+
if (!isAbsolute(path))
|
|
20
|
+
throw new ProfileError("Profile path must be absolute");
|
|
21
|
+
const stat = lstatSync(path);
|
|
22
|
+
if (!stat.isFile() || stat.isSymbolicLink())
|
|
23
|
+
throw new ProfileError("Profile must be a regular file");
|
|
24
|
+
// POSIX ownership and mode bits do not exist on Windows. There the trust boundary is the NTFS
|
|
25
|
+
// ACL of the user's profile directory, which Node cannot inspect, so only the file type,
|
|
26
|
+
// symlink and Git-checkout checks apply.
|
|
27
|
+
if (process.platform !== "win32") {
|
|
28
|
+
if (process.getuid && stat.uid !== process.getuid())
|
|
29
|
+
throw new ProfileError("Profile must be owned by the current user");
|
|
30
|
+
if ((stat.mode & 0o022) !== 0)
|
|
31
|
+
throw new ProfileError("Profile must not be group or world writable");
|
|
32
|
+
}
|
|
33
|
+
try {
|
|
34
|
+
git(dirname(canonical(path)), ["rev-parse", "--show-toplevel"]);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return; // not inside a Git checkout: an agent cannot rewrite it from a worktree
|
|
38
|
+
}
|
|
39
|
+
throw new ProfileError("Profile must live outside Git checkouts");
|
|
40
|
+
}
|
|
41
|
+
export function parseProfile(text) {
|
|
42
|
+
let raw;
|
|
43
|
+
try {
|
|
44
|
+
raw = JSON.parse(text);
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
throw new ProfileError("Profile is not valid JSON");
|
|
48
|
+
}
|
|
49
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
50
|
+
throw new ProfileError("Profile must be an object");
|
|
51
|
+
const value = raw;
|
|
52
|
+
const allowed = new Set([
|
|
53
|
+
"version",
|
|
54
|
+
"mode",
|
|
55
|
+
"cloudWrites",
|
|
56
|
+
"humanPatterns",
|
|
57
|
+
"scratchRoots",
|
|
58
|
+
"description",
|
|
59
|
+
]);
|
|
60
|
+
for (const key of Object.keys(value))
|
|
61
|
+
if (!allowed.has(key))
|
|
62
|
+
throw new ProfileError(`Unknown profile key: ${key}`);
|
|
63
|
+
if (value.version !== 1)
|
|
64
|
+
throw new ProfileError("Unsupported profile version");
|
|
65
|
+
if (value.mode !== "strict" && value.mode !== "permissive")
|
|
66
|
+
throw new ProfileError("mode must be strict or permissive");
|
|
67
|
+
const cloudWrites = value.cloudWrites ?? "human";
|
|
68
|
+
if (cloudWrites !== "human" && cloudWrites !== "allow")
|
|
69
|
+
throw new ProfileError("cloudWrites must be human or allow");
|
|
70
|
+
const patterns = value.humanPatterns ?? [];
|
|
71
|
+
const roots = value.scratchRoots ?? [];
|
|
72
|
+
if (!Array.isArray(patterns) || patterns.some((p) => typeof p !== "string" || p.length > 300))
|
|
73
|
+
throw new ProfileError("humanPatterns must be short strings");
|
|
74
|
+
if (!Array.isArray(roots) || roots.some((r) => typeof r !== "string" || !isAbsolute(r)))
|
|
75
|
+
throw new ProfileError("scratchRoots must be absolute paths");
|
|
76
|
+
let humanPatterns;
|
|
77
|
+
try {
|
|
78
|
+
humanPatterns = patterns.map((p) => new RegExp(p));
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
throw new ProfileError("humanPatterns contains an invalid expression");
|
|
82
|
+
}
|
|
83
|
+
const scratchRoots = new Set();
|
|
84
|
+
for (const root of roots) {
|
|
85
|
+
try {
|
|
86
|
+
scratchRoots.add(canonical(root));
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
/* a missing scratch directory simply grants nothing */
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return {
|
|
93
|
+
mode: value.mode,
|
|
94
|
+
cloudWrites,
|
|
95
|
+
humanPatterns,
|
|
96
|
+
scratchRoots: value.mode === "permissive" ? [...scratchRoots] : [],
|
|
97
|
+
digest: createHash("sha256").update(text).digest("hex"),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
/** Loads the installed profile. A missing file means strict; an invalid one is an error. */
|
|
101
|
+
export function loadProfile(path = defaultProfilePath()) {
|
|
102
|
+
try {
|
|
103
|
+
lstatSync(path);
|
|
104
|
+
}
|
|
105
|
+
catch (error) {
|
|
106
|
+
if (error.code === "ENOENT")
|
|
107
|
+
return strictProfile;
|
|
108
|
+
throw new ProfileError("Profile is not readable");
|
|
109
|
+
}
|
|
110
|
+
verifyLocation(path);
|
|
111
|
+
return parseProfile(readFileSync(path, "utf8"));
|
|
112
|
+
}
|
|
113
|
+
//# sourceMappingURL=profile.js.map
|
package/dist/replay.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { type Profile } from "./profile.js";
|
|
2
|
+
export interface ReplayReport {
|
|
3
|
+
commands: number;
|
|
4
|
+
approved: number;
|
|
5
|
+
strictApproved: number;
|
|
6
|
+
reasons: Array<{
|
|
7
|
+
reason: string;
|
|
8
|
+
count: number;
|
|
9
|
+
examples: string[];
|
|
10
|
+
}>;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Replays the Bash commands recorded in Claude Code transcripts (`~/.claude/projects/**.jsonl`)
|
|
14
|
+
* through the evaluator and reports the approval rate with and without a profile. Commands are
|
|
15
|
+
* not executed. Output lists reasons and a first-line excerpt of examples, so keep reports local.
|
|
16
|
+
*/
|
|
17
|
+
export declare function replayTranscripts(paths: string[], profile: Profile, files?: number): ReplayReport;
|
|
18
|
+
//# sourceMappingURL=replay.d.ts.map
|
package/dist/replay.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { readdirSync, readFileSync, statSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { evaluate } from "./policy.js";
|
|
4
|
+
import { strictProfile } from "./profile.js";
|
|
5
|
+
function transcriptFiles(paths, limit) {
|
|
6
|
+
const files = [];
|
|
7
|
+
const visit = (path) => {
|
|
8
|
+
const stat = statSync(path);
|
|
9
|
+
if (stat.isDirectory())
|
|
10
|
+
for (const name of readdirSync(path))
|
|
11
|
+
visit(join(path, name));
|
|
12
|
+
else if (path.endsWith(".jsonl"))
|
|
13
|
+
files.push([path, stat.mtimeMs]);
|
|
14
|
+
};
|
|
15
|
+
for (const path of paths)
|
|
16
|
+
visit(path);
|
|
17
|
+
return files
|
|
18
|
+
.sort((a, b) => b[1] - a[1])
|
|
19
|
+
.slice(0, limit)
|
|
20
|
+
.map(([path]) => path);
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Replays the Bash commands recorded in Claude Code transcripts (`~/.claude/projects/**.jsonl`)
|
|
24
|
+
* through the evaluator and reports the approval rate with and without a profile. Commands are
|
|
25
|
+
* not executed. Output lists reasons and a first-line excerpt of examples, so keep reports local.
|
|
26
|
+
*/
|
|
27
|
+
export function replayTranscripts(paths, profile, files = 50) {
|
|
28
|
+
const seen = new Set();
|
|
29
|
+
const reasons = new Map();
|
|
30
|
+
const report = { commands: 0, approved: 0, strictApproved: 0, reasons: [] };
|
|
31
|
+
for (const file of transcriptFiles(paths, files))
|
|
32
|
+
for (const line of readFileSync(file, "utf8").split("\n")) {
|
|
33
|
+
if (!line.includes('"tool_use"'))
|
|
34
|
+
continue;
|
|
35
|
+
let entry;
|
|
36
|
+
try {
|
|
37
|
+
entry = JSON.parse(line);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
const content = entry.message?.content;
|
|
43
|
+
if (!Array.isArray(content))
|
|
44
|
+
continue;
|
|
45
|
+
for (const item of content) {
|
|
46
|
+
const command = item.input?.command;
|
|
47
|
+
if (item.type !== "tool_use" || item.name !== "Bash" || typeof command !== "string")
|
|
48
|
+
continue;
|
|
49
|
+
const cwd = entry.cwd ?? process.cwd();
|
|
50
|
+
const key = `${cwd}\0${command}`;
|
|
51
|
+
if (seen.has(key))
|
|
52
|
+
continue;
|
|
53
|
+
seen.add(key);
|
|
54
|
+
const request = {
|
|
55
|
+
sessionId: "replay",
|
|
56
|
+
harness: "claude",
|
|
57
|
+
cwd,
|
|
58
|
+
tool: "Bash",
|
|
59
|
+
input: { command },
|
|
60
|
+
};
|
|
61
|
+
const decision = evaluate(request, undefined, profile);
|
|
62
|
+
report.commands++;
|
|
63
|
+
if (evaluate(request, undefined, strictProfile).decision === "approve")
|
|
64
|
+
report.strictApproved++;
|
|
65
|
+
if (decision.decision === "approve") {
|
|
66
|
+
report.approved++;
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
const bucket = reasons.get(decision.reason) ?? { count: 0, examples: [] };
|
|
70
|
+
bucket.count++;
|
|
71
|
+
if (bucket.examples.length < 3)
|
|
72
|
+
bucket.examples.push(command.split("\n")[0]?.slice(0, 100) ?? "");
|
|
73
|
+
reasons.set(decision.reason, bucket);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
report.reasons = [...reasons]
|
|
77
|
+
.map(([reason, value]) => ({ reason, ...value }))
|
|
78
|
+
.sort((a, b) => b.count - a.count);
|
|
79
|
+
return report;
|
|
80
|
+
}
|
|
81
|
+
//# sourceMappingURL=replay.js.map
|
package/dist/service.d.ts
CHANGED
|
@@ -8,6 +8,13 @@ interface Message {
|
|
|
8
8
|
}
|
|
9
9
|
export declare function serve(harness: string, sessionId: string): Promise<void>;
|
|
10
10
|
export declare function send(harness: string, sessionId: string, message: Omit<Message, "token">): Promise<unknown>;
|
|
11
|
+
/**
|
|
12
|
+
* Stops a session's service. A session with no service (it never started, already ended, or the
|
|
13
|
+
* harness fired SessionEnd outside a real session such as `claude update`) is not an error:
|
|
14
|
+
* there is nothing left to stop, and no session directory is created for it. Unsafe directories
|
|
15
|
+
* and other failures still throw.
|
|
16
|
+
*/
|
|
17
|
+
export declare function stop(harness: string, sessionId: string): Promise<"stopped" | "not-running">;
|
|
11
18
|
export declare function start(harness: string, sessionId: string, cliPath: string): Promise<string>;
|
|
12
19
|
export {};
|
|
13
20
|
//# sourceMappingURL=service.d.ts.map
|
package/dist/service.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
|
-
import { chmodSync } from "node:fs";
|
|
2
|
+
import { chmodSync, existsSync } from "node:fs";
|
|
3
3
|
import { createConnection, createServer } from "node:net";
|
|
4
4
|
import { join } from "node:path";
|
|
5
|
-
import { audit, sessionDirectory, sessionToken } from "./audit.js";
|
|
5
|
+
import { audit, sessionDirectory, sessionDirectoryPath, sessionToken } from "./audit.js";
|
|
6
6
|
import { hash } from "./policy.js";
|
|
7
|
+
import { loadProfile, strictProfile } from "./profile.js";
|
|
7
8
|
import { PolicySession } from "./session.js";
|
|
8
9
|
function endpoint(directory) {
|
|
9
10
|
return process.platform === "win32"
|
|
@@ -12,7 +13,15 @@ function endpoint(directory) {
|
|
|
12
13
|
}
|
|
13
14
|
export async function serve(harness, sessionId) {
|
|
14
15
|
const directory = sessionDirectory(harness, sessionId), token = sessionToken(directory);
|
|
15
|
-
|
|
16
|
+
let profile = strictProfile;
|
|
17
|
+
let profileFailure = false;
|
|
18
|
+
try {
|
|
19
|
+
profile = loadProfile();
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
profileFailure = true; // an unreadable or untrusted profile must never loosen policy
|
|
23
|
+
}
|
|
24
|
+
const session = new PolicySession(directory, harness, sessionId, profile);
|
|
16
25
|
const server = createServer((socket) => {
|
|
17
26
|
socket.setTimeout(3000, () => socket.destroy());
|
|
18
27
|
let data = "";
|
|
@@ -92,6 +101,16 @@ export async function serve(harness, sessionId) {
|
|
|
92
101
|
});
|
|
93
102
|
});
|
|
94
103
|
audit(directory, { event: "session-start", harness, sessionHash: hash(sessionId) });
|
|
104
|
+
audit(directory, {
|
|
105
|
+
event: "profile",
|
|
106
|
+
mode: profile.mode,
|
|
107
|
+
status: profileFailure
|
|
108
|
+
? "invalid-using-strict"
|
|
109
|
+
: profile.digest
|
|
110
|
+
? "loaded"
|
|
111
|
+
: "none-using-strict",
|
|
112
|
+
...(profile.digest ? { digest: profile.digest } : {}),
|
|
113
|
+
});
|
|
95
114
|
}
|
|
96
115
|
export function send(harness, sessionId, message) {
|
|
97
116
|
const directory = sessionDirectory(harness, sessionId);
|
|
@@ -120,6 +139,26 @@ export function send(harness, sessionId, message) {
|
|
|
120
139
|
});
|
|
121
140
|
});
|
|
122
141
|
}
|
|
142
|
+
/**
|
|
143
|
+
* Stops a session's service. A session with no service (it never started, already ended, or the
|
|
144
|
+
* harness fired SessionEnd outside a real session such as `claude update`) is not an error:
|
|
145
|
+
* there is nothing left to stop, and no session directory is created for it. Unsafe directories
|
|
146
|
+
* and other failures still throw.
|
|
147
|
+
*/
|
|
148
|
+
export async function stop(harness, sessionId) {
|
|
149
|
+
if (!existsSync(sessionDirectoryPath(harness, sessionId)))
|
|
150
|
+
return "not-running";
|
|
151
|
+
try {
|
|
152
|
+
await send(harness, sessionId, { action: "stop" });
|
|
153
|
+
return "stopped";
|
|
154
|
+
}
|
|
155
|
+
catch (error) {
|
|
156
|
+
const code = error.code;
|
|
157
|
+
if (code === "ENOENT" || code === "ECONNREFUSED")
|
|
158
|
+
return "not-running";
|
|
159
|
+
throw error;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
123
162
|
export async function start(harness, sessionId, cliPath) {
|
|
124
163
|
const directory = sessionDirectory(harness, sessionId);
|
|
125
164
|
try {
|
package/dist/session.d.ts
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
|
+
import { type Profile } from "./profile.js";
|
|
1
2
|
import type { Classification, Decision, OutcomeReport, Request } from "./types.js";
|
|
2
3
|
export declare class PolicySession {
|
|
3
4
|
readonly directory: string;
|
|
4
5
|
readonly harness: string;
|
|
5
6
|
readonly sessionId: string;
|
|
7
|
+
readonly profile: Profile;
|
|
6
8
|
private cache;
|
|
7
9
|
private pending;
|
|
8
|
-
constructor(directory: string, harness: string, sessionId: string);
|
|
10
|
+
constructor(directory: string, harness: string, sessionId: string, profile?: Profile);
|
|
9
11
|
review(request: Request, ai?: Classification): Decision;
|
|
10
12
|
record(report: OutcomeReport): void;
|
|
11
13
|
classify(classification: Classification): Decision;
|
package/dist/session.js
CHANGED
|
@@ -1,15 +1,18 @@
|
|
|
1
1
|
import { audit, requestSummary } from "./audit.js";
|
|
2
2
|
import { evaluate, hash } from "./policy.js";
|
|
3
|
+
import { strictProfile } from "./profile.js";
|
|
3
4
|
export class PolicySession {
|
|
4
5
|
directory;
|
|
5
6
|
harness;
|
|
6
7
|
sessionId;
|
|
8
|
+
profile;
|
|
7
9
|
cache = new Map();
|
|
8
10
|
pending = new Map();
|
|
9
|
-
constructor(directory, harness, sessionId) {
|
|
11
|
+
constructor(directory, harness, sessionId, profile = strictProfile) {
|
|
10
12
|
this.directory = directory;
|
|
11
13
|
this.harness = harness;
|
|
12
14
|
this.sessionId = sessionId;
|
|
15
|
+
this.profile = profile;
|
|
13
16
|
}
|
|
14
17
|
review(request, ai) {
|
|
15
18
|
if (request.sessionId !== this.sessionId || request.harness !== this.harness)
|
|
@@ -38,7 +41,7 @@ export class PolicySession {
|
|
|
38
41
|
});
|
|
39
42
|
throw new Error("Malformed AI classification");
|
|
40
43
|
}
|
|
41
|
-
const key = hash([hash(request), "policy-v1"]);
|
|
44
|
+
const key = hash([hash(request), "policy-v1", this.profile.digest ?? this.profile.mode]);
|
|
42
45
|
const entry = this.cache.get(key);
|
|
43
46
|
const cachedAi = entry && entry.expires > Date.now() ? entry.ai : undefined;
|
|
44
47
|
if (ai)
|
|
@@ -48,7 +51,7 @@ export class PolicySession {
|
|
|
48
51
|
category: ai.category,
|
|
49
52
|
confidence: ai.confidence,
|
|
50
53
|
});
|
|
51
|
-
const decision = evaluate(request, ai ?? cachedAi);
|
|
54
|
+
const decision = evaluate(request, ai ?? cachedAi, this.profile);
|
|
52
55
|
if (decision.decision === "human")
|
|
53
56
|
this.cache.delete(key);
|
|
54
57
|
// Evaluation always precedes lookup. Filesystem evidence is never cached.
|
package/dist/shell.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export interface Redirect {
|
|
2
|
+
fd: string;
|
|
3
|
+
op: ">" | ">>" | "<" | ">&";
|
|
4
|
+
target: string;
|
|
5
|
+
}
|
|
6
|
+
export interface SimpleCommand {
|
|
7
|
+
env: Array<[string, string]>;
|
|
8
|
+
argv: string[];
|
|
9
|
+
redirects: Redirect[];
|
|
10
|
+
}
|
|
11
|
+
export type Pipeline = SimpleCommand[];
|
|
12
|
+
export declare function parseShell(command: string): Pipeline[] | undefined;
|
|
13
|
+
//# sourceMappingURL=shell.d.ts.map
|
package/dist/shell.js
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
// Parses a bounded subset of POSIX shell: simple commands joined by `;`, newlines, `&&`, `||`
|
|
2
|
+
// and `|`, with quoting, leading VAR=value assignments and file redirections. Anything whose
|
|
3
|
+
// effects depend on expansion (`$`, backticks, subshells, braces, heredocs, background jobs,
|
|
4
|
+
// comments, process substitution) is rejected so a caller can fall back to a human.
|
|
5
|
+
const ASSIGNMENT_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
6
|
+
export function parseShell(command) {
|
|
7
|
+
if (!command || command.includes("\0") || command.includes("\r"))
|
|
8
|
+
return undefined;
|
|
9
|
+
const pipelines = [];
|
|
10
|
+
let pipeline = [];
|
|
11
|
+
let words = [];
|
|
12
|
+
let redirects = [];
|
|
13
|
+
let pendingRedirect;
|
|
14
|
+
let current = "";
|
|
15
|
+
let active = false;
|
|
16
|
+
let quoted = false;
|
|
17
|
+
// A word is an assignment only if its `NAME=` prefix was typed plainly. Quotes or escapes later,
|
|
18
|
+
// in the value, are fine (`FOO="a b" cmd`); a quote or escape before the `=` is not an assignment.
|
|
19
|
+
let plain = true;
|
|
20
|
+
let eqAt = -1;
|
|
21
|
+
let quote = "";
|
|
22
|
+
let dangling = false;
|
|
23
|
+
const endWord = () => {
|
|
24
|
+
if (!active)
|
|
25
|
+
return true;
|
|
26
|
+
const word = { text: current, assignAt: plain ? eqAt : -1 };
|
|
27
|
+
current = "";
|
|
28
|
+
active = false;
|
|
29
|
+
quoted = false;
|
|
30
|
+
plain = true;
|
|
31
|
+
eqAt = -1;
|
|
32
|
+
if (pendingRedirect) {
|
|
33
|
+
redirects.push({ ...pendingRedirect, target: word.text });
|
|
34
|
+
pendingRedirect = undefined;
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
words.push(word);
|
|
38
|
+
dangling = false;
|
|
39
|
+
}
|
|
40
|
+
return true;
|
|
41
|
+
};
|
|
42
|
+
const endSimple = () => {
|
|
43
|
+
if (pendingRedirect)
|
|
44
|
+
return false;
|
|
45
|
+
if (!words.length && !redirects.length)
|
|
46
|
+
return true;
|
|
47
|
+
const env = [];
|
|
48
|
+
let index = 0;
|
|
49
|
+
while (index < words.length) {
|
|
50
|
+
const word = words[index];
|
|
51
|
+
if (!word || word.assignAt < 1 || !ASSIGNMENT_NAME.test(word.text.slice(0, word.assignAt)))
|
|
52
|
+
break;
|
|
53
|
+
env.push([word.text.slice(0, word.assignAt), word.text.slice(word.assignAt + 1)]);
|
|
54
|
+
index++;
|
|
55
|
+
}
|
|
56
|
+
const argv = words.slice(index).map((word) => word.text);
|
|
57
|
+
if (!argv.length)
|
|
58
|
+
return false;
|
|
59
|
+
// Bash also treats `FOO+=x`, `FOO[0]=x` and quoted or escaped forms as assignments and then runs
|
|
60
|
+
// the next word. A program name never contains `=`, so a leading word that still has one is
|
|
61
|
+
// an assignment this parser cannot represent: reject it instead of judging it as the program.
|
|
62
|
+
if (argv[0]?.includes("="))
|
|
63
|
+
return false;
|
|
64
|
+
pipeline.push({ env, argv, redirects });
|
|
65
|
+
words = [];
|
|
66
|
+
redirects = [];
|
|
67
|
+
return true;
|
|
68
|
+
};
|
|
69
|
+
const endPipeline = (allowEmpty) => {
|
|
70
|
+
if (!endSimple())
|
|
71
|
+
return false;
|
|
72
|
+
if (!pipeline.length)
|
|
73
|
+
return allowEmpty;
|
|
74
|
+
pipelines.push(pipeline);
|
|
75
|
+
pipeline = [];
|
|
76
|
+
return true;
|
|
77
|
+
};
|
|
78
|
+
for (let i = 0; i < command.length; i++) {
|
|
79
|
+
const char = command[i];
|
|
80
|
+
if (quote) {
|
|
81
|
+
if (quote === '"') {
|
|
82
|
+
if (char === "\\") {
|
|
83
|
+
// Inside double quotes a backslash only escapes `"`, `\`, `$` and a backtick; before any
|
|
84
|
+
// other character it is literal. Either way nothing is expanded or executed.
|
|
85
|
+
const next = command[i + 1];
|
|
86
|
+
if (next === undefined || next === "\n")
|
|
87
|
+
return undefined;
|
|
88
|
+
if ('"\\$`'.includes(next)) {
|
|
89
|
+
current += next;
|
|
90
|
+
i++;
|
|
91
|
+
}
|
|
92
|
+
else
|
|
93
|
+
current += char;
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
if (char === "$" || char === "`")
|
|
97
|
+
return undefined;
|
|
98
|
+
}
|
|
99
|
+
if (char === quote)
|
|
100
|
+
quote = "";
|
|
101
|
+
else
|
|
102
|
+
current += char;
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
if (char === "'" || char === '"') {
|
|
106
|
+
quote = char;
|
|
107
|
+
active = true;
|
|
108
|
+
quoted = true;
|
|
109
|
+
if (eqAt < 0)
|
|
110
|
+
plain = false;
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
if (char === "\\") {
|
|
114
|
+
// An unquoted backslash makes the next character literal (`\.`, `\|`, `\ `).
|
|
115
|
+
const next = command[i + 1];
|
|
116
|
+
if (next === undefined || next === "\n")
|
|
117
|
+
return undefined;
|
|
118
|
+
current += next;
|
|
119
|
+
active = true;
|
|
120
|
+
quoted = true;
|
|
121
|
+
if (eqAt < 0)
|
|
122
|
+
plain = false;
|
|
123
|
+
i++;
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if (/[`$(){}#!]/.test(char)) {
|
|
127
|
+
// `#` only starts a comment at a word boundary, but rejecting it everywhere is simpler.
|
|
128
|
+
return undefined;
|
|
129
|
+
}
|
|
130
|
+
if (char === " " || char === "\t") {
|
|
131
|
+
endWord();
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
if (char === "\n" || char === ";") {
|
|
135
|
+
endWord();
|
|
136
|
+
if (dangling || !endPipeline(true))
|
|
137
|
+
return undefined;
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
if (char === "&") {
|
|
141
|
+
if (command[i + 1] !== "&")
|
|
142
|
+
return undefined;
|
|
143
|
+
endWord();
|
|
144
|
+
if (!endPipeline(false))
|
|
145
|
+
return undefined;
|
|
146
|
+
dangling = true;
|
|
147
|
+
i++;
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
if (char === "|") {
|
|
151
|
+
endWord();
|
|
152
|
+
if (command[i + 1] === "|") {
|
|
153
|
+
if (!endPipeline(false))
|
|
154
|
+
return undefined;
|
|
155
|
+
i++;
|
|
156
|
+
}
|
|
157
|
+
else if (!words.length || !endSimple())
|
|
158
|
+
return undefined;
|
|
159
|
+
dangling = true;
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
if (char === ">" || char === "<") {
|
|
163
|
+
if (command[i + 1] === "(" || (char === "<" && command[i + 1] === "<"))
|
|
164
|
+
return undefined;
|
|
165
|
+
let fd = char === ">" ? "1" : "0";
|
|
166
|
+
if (active && !quoted && /^[0-9]$/.test(current)) {
|
|
167
|
+
fd = current;
|
|
168
|
+
current = "";
|
|
169
|
+
active = false;
|
|
170
|
+
}
|
|
171
|
+
else
|
|
172
|
+
endWord();
|
|
173
|
+
let op = char;
|
|
174
|
+
if (char === ">" && command[i + 1] === ">") {
|
|
175
|
+
op = ">>";
|
|
176
|
+
i++;
|
|
177
|
+
}
|
|
178
|
+
else if (char === ">" && command[i + 1] === "&") {
|
|
179
|
+
op = ">&";
|
|
180
|
+
i++;
|
|
181
|
+
}
|
|
182
|
+
else if (char === ">" && command[i + 1] === "|")
|
|
183
|
+
return undefined;
|
|
184
|
+
if (pendingRedirect)
|
|
185
|
+
return undefined;
|
|
186
|
+
pendingRedirect = { fd, op };
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
if (plain && eqAt < 0 && char === "=")
|
|
190
|
+
eqAt = current.length;
|
|
191
|
+
current += char;
|
|
192
|
+
active = true;
|
|
193
|
+
}
|
|
194
|
+
if (quote)
|
|
195
|
+
return undefined;
|
|
196
|
+
endWord();
|
|
197
|
+
if (dangling || !endPipeline(true))
|
|
198
|
+
return undefined;
|
|
199
|
+
return pipelines.length ? pipelines : undefined;
|
|
200
|
+
}
|
|
201
|
+
//# sourceMappingURL=shell.js.map
|
package/package.json
CHANGED