@jalaxy33/pi-permission 0.0.0-stage → 0.4.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/LICENSE +21 -0
- package/README.md +134 -2
- package/docs/configuration.md +237 -0
- package/index.ts +97 -0
- package/package.json +54 -4
- package/rules/index.json +71 -0
- package/rules/packs/bulk-delete.json +83 -0
- package/rules/packs/database.json +30 -0
- package/rules/packs/git-local.json +81 -0
- package/rules/packs/git-remote.json +27 -0
- package/rules/packs/infra.json +45 -0
- package/rules/packs/irreversible.json +93 -0
- package/rules/packs/privilege.json +50 -0
- package/rules/packs/publish.json +33 -0
- package/rules/packs/secrets.json +43 -0
- package/schema.json +348 -0
- package/src/argv.ts +67 -0
- package/src/config.ts +201 -0
- package/src/decide.ts +90 -0
- package/src/gate.ts +208 -0
- package/src/match.ts +58 -0
- package/src/ops.ts +244 -0
- package/src/outside.ts +87 -0
- package/src/paths.ts +194 -0
- package/src/prompt.ts +275 -0
- package/src/rulesets.ts +444 -0
- package/src/tokenize.ts +222 -0
- package/src/types.ts +167 -0
- package/src/validate.ts +125 -0
package/src/paths.ts
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
/** File path rules: glob matching against resolved absolute paths. */
|
|
2
|
+
|
|
3
|
+
import { existsSync, lstatSync, readlinkSync, realpathSync } from "node:fs";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { basename, dirname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
|
|
6
|
+
import type { CompiledPathRule, PathAction, PathOp, PathRule } from "./types";
|
|
7
|
+
|
|
8
|
+
const ALL_OPS: PathOp[] = ["read", "write", "delete"];
|
|
9
|
+
|
|
10
|
+
export function expandTilde(path: string): string {
|
|
11
|
+
if (path === "~") return homedir();
|
|
12
|
+
if (path.startsWith("~/")) return resolve(homedir(), path.slice(2));
|
|
13
|
+
return path;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function globToRegExp(glob: string): RegExp {
|
|
17
|
+
let out = "";
|
|
18
|
+
for (let i = 0; i < glob.length; i++) {
|
|
19
|
+
const ch = glob[i] as string;
|
|
20
|
+
if (ch === "*") {
|
|
21
|
+
if (glob[i + 1] === "*") {
|
|
22
|
+
out += ".*";
|
|
23
|
+
i += 1;
|
|
24
|
+
} else {
|
|
25
|
+
out += "[^/]*";
|
|
26
|
+
}
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
if (ch === "?") {
|
|
30
|
+
out += "[^/]";
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
out += ch.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
34
|
+
}
|
|
35
|
+
return new RegExp(`^${out}$`);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function kindOf(pattern: string): "base" | "abs" | "rel" {
|
|
39
|
+
// `**` is the project tree, not "any basename": a whitelist needs one pattern.
|
|
40
|
+
if (pattern === "**") return "rel";
|
|
41
|
+
if (!pattern.includes("/")) return "base";
|
|
42
|
+
if (pattern.startsWith("~") || isAbsolute(pattern)) return "abs";
|
|
43
|
+
return "rel";
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function compilePattern(pattern: string): CompiledPathRule["compiled"][number] {
|
|
47
|
+
return { value: pattern, kind: kindOf(pattern), re: globToRegExp(expandTilde(pattern)) };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function compilePathRules(rules: PathRule[]): { rules: CompiledPathRule[]; warnings: string[] } {
|
|
51
|
+
const warnings: string[] = [];
|
|
52
|
+
const compiled: CompiledPathRule[] = [];
|
|
53
|
+
|
|
54
|
+
for (const rule of rules) {
|
|
55
|
+
if (!rule || typeof rule.id !== "string" || !rule.id.trim()) {
|
|
56
|
+
warnings.push(`ignore path rule without id: ${JSON.stringify(rule)}`);
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
if (!Array.isArray(rule.patterns) || rule.patterns.length === 0) {
|
|
60
|
+
warnings.push(`path rule ${rule.id}: no patterns, ignored`);
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
compiled.push({
|
|
64
|
+
...rule,
|
|
65
|
+
compiled: rule.patterns.map(compilePattern),
|
|
66
|
+
compiledExcept: (rule.except ?? []).map(compilePattern),
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
return { rules: compiled, warnings };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
interface Candidate {
|
|
74
|
+
abs: string;
|
|
75
|
+
real?: string;
|
|
76
|
+
rel: string;
|
|
77
|
+
relReal?: string;
|
|
78
|
+
base: string;
|
|
79
|
+
baseReal?: string;
|
|
80
|
+
exists: boolean;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Real path of a target that may not exist yet: symlinked ancestors are resolved,
|
|
85
|
+
* and so is a symlink whose own target is missing, since a write follows it there.
|
|
86
|
+
* The missing tail is appended unchanged.
|
|
87
|
+
*/
|
|
88
|
+
function realPathOf(abs: string, seen = new Set<string>()): string | undefined {
|
|
89
|
+
let current = abs;
|
|
90
|
+
const tail: string[] = [];
|
|
91
|
+
for (;;) {
|
|
92
|
+
try {
|
|
93
|
+
const real = realpathSync(current);
|
|
94
|
+
return tail.length > 0 ? join(real, ...tail.reverse()) : real;
|
|
95
|
+
} catch {
|
|
96
|
+
if (!seen.has(current) && seen.size < 16) {
|
|
97
|
+
try {
|
|
98
|
+
if (lstatSync(current).isSymbolicLink()) {
|
|
99
|
+
seen.add(current);
|
|
100
|
+
const target = realPathOf(resolve(dirname(current), readlinkSync(current)), seen);
|
|
101
|
+
if (target) return tail.length > 0 ? join(target, ...tail.reverse()) : target;
|
|
102
|
+
}
|
|
103
|
+
} catch {
|
|
104
|
+
// Unreadable link: fall through to the parent.
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
const parent = dirname(current);
|
|
108
|
+
if (parent === current) return undefined;
|
|
109
|
+
tail.push(basename(current));
|
|
110
|
+
current = parent;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function resolveCandidate(rawPath: string, cwd: string): Candidate {
|
|
116
|
+
const expanded = expandTilde(rawPath);
|
|
117
|
+
const abs = normalize(isAbsolute(expanded) ? expanded : resolve(cwd, expanded));
|
|
118
|
+
const exists = existsSync(abs);
|
|
119
|
+
const real = realPathOf(abs);
|
|
120
|
+
return {
|
|
121
|
+
abs,
|
|
122
|
+
real,
|
|
123
|
+
rel: relative(cwd, abs),
|
|
124
|
+
relReal: real ? relative(cwd, real) : undefined,
|
|
125
|
+
base: basename(abs),
|
|
126
|
+
baseReal: real ? basename(real) : undefined,
|
|
127
|
+
exists,
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function patternMatches(
|
|
132
|
+
pattern: { value: string; kind: "base" | "abs" | "rel"; re: RegExp },
|
|
133
|
+
candidate: Candidate,
|
|
134
|
+
): boolean {
|
|
135
|
+
if (pattern.kind === "rel") {
|
|
136
|
+
// A relative pattern describes paths under the project, never `../outside`.
|
|
137
|
+
// Both the written path and the real path must stay inside, so a symlink in
|
|
138
|
+
// the workspace cannot make an allow rule cover an outside file.
|
|
139
|
+
const inside = (value: string) => value !== ".." && !value.startsWith(`..${sep}`);
|
|
140
|
+
if (!inside(candidate.rel)) return false;
|
|
141
|
+
if (candidate.relReal !== undefined && !inside(candidate.relReal)) return false;
|
|
142
|
+
return pattern.re.test(candidate.rel) || (candidate.relReal !== undefined && pattern.re.test(candidate.relReal));
|
|
143
|
+
}
|
|
144
|
+
const paths = pattern.kind === "base" ? [candidate.base, candidate.baseReal] : [candidate.abs, candidate.real];
|
|
145
|
+
return paths.some((value) => typeof value === "string" && pattern.re.test(value));
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export interface PathHit {
|
|
149
|
+
rule: string;
|
|
150
|
+
reason: string;
|
|
151
|
+
path: string;
|
|
152
|
+
action: PathAction;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** All matching rules for the operation, in rule order. */
|
|
156
|
+
export function matchPath(
|
|
157
|
+
rules: CompiledPathRule[],
|
|
158
|
+
rawPath: string,
|
|
159
|
+
cwd: string,
|
|
160
|
+
op: PathOp,
|
|
161
|
+
options: { basenameOnly?: boolean } = {},
|
|
162
|
+
): PathHit[] {
|
|
163
|
+
const candidate = resolveCandidate(rawPath, cwd);
|
|
164
|
+
const testable = (pattern: CompiledPathRule["compiled"][number]) =>
|
|
165
|
+
!options.basenameOnly || pattern.kind === "base";
|
|
166
|
+
|
|
167
|
+
const hits: PathHit[] = [];
|
|
168
|
+
for (const rule of rules) {
|
|
169
|
+
const ops = rule.ops ?? ALL_OPS;
|
|
170
|
+
if (!ops.includes(op)) continue;
|
|
171
|
+
if (rule.onlyIfExists && !candidate.exists && !options.basenameOnly) continue;
|
|
172
|
+
if (rule.compiledExcept.some((pattern) => testable(pattern) && patternMatches(pattern, candidate))) continue;
|
|
173
|
+
if (!rule.compiled.some((pattern) => testable(pattern) && patternMatches(pattern, candidate))) continue;
|
|
174
|
+
hits.push({
|
|
175
|
+
rule: rule.id,
|
|
176
|
+
path: candidate.abs,
|
|
177
|
+
action: rule.action ?? "deny",
|
|
178
|
+
reason: rule.message ?? `pi-permission: ${rule.id} protects ${candidate.abs}`,
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
return hits;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** First matching rule, for callers that only need one. */
|
|
186
|
+
export function checkPath(
|
|
187
|
+
rules: CompiledPathRule[],
|
|
188
|
+
rawPath: string,
|
|
189
|
+
cwd: string,
|
|
190
|
+
op: PathOp,
|
|
191
|
+
options: { basenameOnly?: boolean } = {},
|
|
192
|
+
): PathHit | undefined {
|
|
193
|
+
return matchPath(rules, rawPath, cwd, op, options)[0];
|
|
194
|
+
}
|
package/src/prompt.ts
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
/** Confirmation prompt built from pi-tui components, plus per-session grants. */
|
|
2
|
+
|
|
3
|
+
import { DynamicBorder } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import { Container, Key, matchesKey, Spacer, Text, truncateToWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
|
|
5
|
+
|
|
6
|
+
export type Choice = "allow" | "allow-session" | "deny" | "stop";
|
|
7
|
+
|
|
8
|
+
export type Outcome = { block: false } | { block: true; reason: string };
|
|
9
|
+
|
|
10
|
+
const KEYS: Record<string, Choice> = {
|
|
11
|
+
y: "allow",
|
|
12
|
+
Y: "allow",
|
|
13
|
+
a: "allow-session",
|
|
14
|
+
A: "allow-session",
|
|
15
|
+
n: "deny",
|
|
16
|
+
N: "deny",
|
|
17
|
+
s: "stop",
|
|
18
|
+
S: "stop",
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
const TOGGLE_KEYS = new Set(["o", "O", "\u000f"]);
|
|
22
|
+
/** Enter accepts, matching the usual convention for confirmation prompts. */
|
|
23
|
+
const ENTER_KEYS = new Set(["\r", "\n"]);
|
|
24
|
+
const VIEWPORT_ROWS = 12;
|
|
25
|
+
const EXPANDED_ROWS = 40;
|
|
26
|
+
|
|
27
|
+
export function chooseFromKey(key: string): Choice | undefined {
|
|
28
|
+
return KEYS[key];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface PromptComponent {
|
|
32
|
+
render(width: number): string[];
|
|
33
|
+
handleInput(data: string): void;
|
|
34
|
+
invalidate(): void;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
type Done = (value: unknown) => void;
|
|
38
|
+
|
|
39
|
+
export interface CustomPromptOptions {
|
|
40
|
+
blocked?: { kind: string; message: string };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export type CustomPrompt = (
|
|
44
|
+
factory: (tui: unknown, theme: unknown, keybindings: unknown, done: Done) => PromptComponent,
|
|
45
|
+
options?: CustomPromptOptions,
|
|
46
|
+
) => Promise<unknown>;
|
|
47
|
+
|
|
48
|
+
export type SelectPrompt = (title: string, options: string[]) => Promise<string | undefined>;
|
|
49
|
+
|
|
50
|
+
export class SessionGrants {
|
|
51
|
+
private granted = new Set<string>();
|
|
52
|
+
|
|
53
|
+
has(command: string): boolean {
|
|
54
|
+
return this.granted.has(command);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
add(command: string): void {
|
|
58
|
+
this.granted.add(command);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
clear(): void {
|
|
62
|
+
this.granted.clear();
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
get size(): number {
|
|
66
|
+
return this.granted.size;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
interface Theme {
|
|
71
|
+
fg?: (name: string, text: string) => string;
|
|
72
|
+
bold?: (text: string) => string;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const RAW_FG: Record<string, string> = { error: "91", warning: "93", dim: "90" };
|
|
76
|
+
|
|
77
|
+
/** Theme colors, falling back to raw ANSI when the theme returns text unchanged. */
|
|
78
|
+
function paint(theme: unknown) {
|
|
79
|
+
const api = (theme ?? {}) as Theme;
|
|
80
|
+
|
|
81
|
+
const fg = (name: string, text: string): string => {
|
|
82
|
+
const themed = typeof api.fg === "function" ? api.fg(name, text) : undefined;
|
|
83
|
+
if (themed && themed !== text) return themed;
|
|
84
|
+
const code = RAW_FG[name];
|
|
85
|
+
return code ? `\u001b[${code}m${text}\u001b[39m` : text;
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
const bold = (text: string): string => {
|
|
89
|
+
const themed = typeof api.bold === "function" ? api.bold(text) : undefined;
|
|
90
|
+
return themed && themed !== text ? themed : `\u001b[1m${text}\u001b[22m`;
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
return { fg, bold };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function numberedRows(command: string, textWidth: number, dim: (text: string) => string) {
|
|
97
|
+
const logical = command.split("\n");
|
|
98
|
+
const numberWidth = Math.max(2, String(logical.length).length);
|
|
99
|
+
const rows: string[] = [];
|
|
100
|
+
for (const [index, line] of logical.entries()) {
|
|
101
|
+
const label = dim(String(index + 1).padStart(numberWidth));
|
|
102
|
+
const wrapped = wrapTextWithAnsi(line, Math.max(4, textWidth - numberWidth - 1));
|
|
103
|
+
for (const chunk of wrapped.length > 0 ? wrapped : [""]) rows.push(`${label} ${chunk}`);
|
|
104
|
+
}
|
|
105
|
+
return rows;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function rule(width: number, label: string, dim: (text: string) => string): string {
|
|
109
|
+
const clipped = truncateToWidth(label, width);
|
|
110
|
+
const used = width - clipped.length;
|
|
111
|
+
return dim(`${"─".repeat(Math.max(0, used))}${clipped}`);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function createPromptComponent(
|
|
115
|
+
command: string,
|
|
116
|
+
reason: string,
|
|
117
|
+
title: string,
|
|
118
|
+
theme: unknown,
|
|
119
|
+
tui: unknown,
|
|
120
|
+
done: Done,
|
|
121
|
+
): PromptComponent {
|
|
122
|
+
const { fg, bold } = paint(theme);
|
|
123
|
+
const dim = (text: string) => fg("dim", text);
|
|
124
|
+
|
|
125
|
+
let expanded = false;
|
|
126
|
+
let scroll = 0;
|
|
127
|
+
|
|
128
|
+
const container = new Container();
|
|
129
|
+
const hint = new Text("", 0, 0);
|
|
130
|
+
const topBorder = new Text("", 0, 0);
|
|
131
|
+
const body = new Text("", 1, 0);
|
|
132
|
+
const bottomBorder = new Text("", 0, 0);
|
|
133
|
+
|
|
134
|
+
container.addChild(new DynamicBorder((text: string) => fg("error", text)));
|
|
135
|
+
container.addChild(new Text(fg("error", bold(`pi-permission · ${title}`)), 1, 0));
|
|
136
|
+
container.addChild(new Spacer(1));
|
|
137
|
+
container.addChild(new Text(fg("warning", `Reason: ${reason}`), 1, 0));
|
|
138
|
+
container.addChild(new Spacer(1));
|
|
139
|
+
container.addChild(topBorder);
|
|
140
|
+
container.addChild(body);
|
|
141
|
+
container.addChild(bottomBorder);
|
|
142
|
+
container.addChild(new Spacer(1));
|
|
143
|
+
container.addChild(new Text(" Allow execution?", 0, 0));
|
|
144
|
+
container.addChild(new Spacer(1));
|
|
145
|
+
container.addChild(hint);
|
|
146
|
+
container.addChild(new DynamicBorder((text: string) => fg("error", text)));
|
|
147
|
+
|
|
148
|
+
const requestRender = () => (tui as { requestRender?: () => void } | undefined)?.requestRender?.();
|
|
149
|
+
const terminalWidth = () => {
|
|
150
|
+
const columns = (tui as { terminal?: { columns?: number } } | undefined)?.terminal?.columns;
|
|
151
|
+
return typeof columns === "number" && columns > 0 ? columns : 80;
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
return {
|
|
155
|
+
render(width: number): string[] {
|
|
156
|
+
const w = Math.max(28, width || terminalWidth());
|
|
157
|
+
const inner = Math.max(10, w - 4);
|
|
158
|
+
const rows = numberedRows(command, inner, dim);
|
|
159
|
+
const viewport = expanded ? EXPANDED_ROWS : VIEWPORT_ROWS;
|
|
160
|
+
const maxScroll = Math.max(0, rows.length - viewport);
|
|
161
|
+
if (scroll > maxScroll) scroll = maxScroll;
|
|
162
|
+
|
|
163
|
+
const visible = rows.slice(scroll, scroll + viewport);
|
|
164
|
+
const above = scroll;
|
|
165
|
+
const below = rows.length - scroll - visible.length;
|
|
166
|
+
|
|
167
|
+
const toggle = expanded ? "o collapse" : "o expand";
|
|
168
|
+
const variants = [
|
|
169
|
+
`y/Enter allow · a session · n deny · s stop · esc cancel${maxScroll > 0 ? " · j/k scroll" : ""} · ${toggle}`,
|
|
170
|
+
`y/Enter allow · a session · n deny · s stop · esc${maxScroll > 0 ? " · j/k" : ""} · ${toggle}`,
|
|
171
|
+
`y/Enter · a · n · s${maxScroll > 0 ? " · j/k" : ""} · esc · ${toggle}`,
|
|
172
|
+
];
|
|
173
|
+
const keyHint = variants.find((candidate) => candidate.length <= w - 2) ?? variants[variants.length - 1];
|
|
174
|
+
hint.setText(dim(` ${keyHint}`));
|
|
175
|
+
|
|
176
|
+
topBorder.setText(rule(w, above > 0 ? ` ↑ ${above} more ` : "", dim));
|
|
177
|
+
body.setText(visible.join("\n"));
|
|
178
|
+
bottomBorder.setText(rule(w, below > 0 ? ` ↓ ${below} more ` : "", dim));
|
|
179
|
+
|
|
180
|
+
return container.render(w);
|
|
181
|
+
},
|
|
182
|
+
|
|
183
|
+
handleInput(data: string): void {
|
|
184
|
+
if (TOGGLE_KEYS.has(data)) {
|
|
185
|
+
expanded = !expanded;
|
|
186
|
+
scroll = 0;
|
|
187
|
+
requestRender();
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
if (matchesKey(data, Key.up) || data === "k") {
|
|
191
|
+
if (scroll > 0) {
|
|
192
|
+
scroll -= 1;
|
|
193
|
+
requestRender();
|
|
194
|
+
}
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
if (matchesKey(data, Key.down) || data === "j") {
|
|
198
|
+
scroll += 1;
|
|
199
|
+
requestRender();
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
if (matchesKey(data, Key.escape) || matchesKey(data, Key.ctrl("c"))) {
|
|
203
|
+
done("deny");
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
if (ENTER_KEYS.has(data) || matchesKey(data, Key.enter)) {
|
|
207
|
+
done("allow");
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
const choice = chooseFromKey(data);
|
|
211
|
+
if (choice) done(choice);
|
|
212
|
+
},
|
|
213
|
+
|
|
214
|
+
invalidate(): void {
|
|
215
|
+
container.invalidate();
|
|
216
|
+
},
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const OPTIONS = ["Allow once", "Allow for this session", "Deny", "Deny and stop"];
|
|
221
|
+
|
|
222
|
+
export interface PromptRequest {
|
|
223
|
+
command: string;
|
|
224
|
+
reason: string;
|
|
225
|
+
/** Heading line; defaults to "Dangerous command". */
|
|
226
|
+
title?: string;
|
|
227
|
+
hasUI: boolean;
|
|
228
|
+
grants: SessionGrants;
|
|
229
|
+
/** Session grant keys; defaults to the command string. */
|
|
230
|
+
grantKeys?: string[];
|
|
231
|
+
custom?: CustomPrompt;
|
|
232
|
+
select?: SelectPrompt;
|
|
233
|
+
abort: () => void;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function resolveChoice(choice: Choice | undefined, request: PromptRequest): Outcome {
|
|
237
|
+
const { command, reason } = request;
|
|
238
|
+
if (choice === "allow") return { block: false };
|
|
239
|
+
if (choice === "allow-session") {
|
|
240
|
+
for (const key of request.grantKeys ?? [command]) request.grants.add(key);
|
|
241
|
+
return { block: false };
|
|
242
|
+
}
|
|
243
|
+
if (choice === "stop") {
|
|
244
|
+
request.abort();
|
|
245
|
+
return { block: true, reason: `pi-permission: denied and stopped (${reason})` };
|
|
246
|
+
}
|
|
247
|
+
return { block: true, reason: `pi-permission: denied (${reason}). Ask the user instead of retrying.` };
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
export async function ask(request: PromptRequest): Promise<Outcome> {
|
|
251
|
+
const { command, reason } = request;
|
|
252
|
+
|
|
253
|
+
if (!request.hasUI) {
|
|
254
|
+
return { block: true, reason: `pi-permission (no UI to confirm): ${reason}. Ask the user to run it.` };
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
if (request.custom) {
|
|
258
|
+
const choice = (await request.custom(
|
|
259
|
+
(tui, theme, _keybindings, done) =>
|
|
260
|
+
createPromptComponent(command, reason, request.title ?? "Dangerous command", theme, tui, done),
|
|
261
|
+
{ blocked: { kind: "permission", message: `pi-permission: ${reason}` } },
|
|
262
|
+
)) as Choice | undefined;
|
|
263
|
+
return resolveChoice(choice, request);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
if (request.select) {
|
|
267
|
+
const body = command.replace(/\n/g, "\n ");
|
|
268
|
+
const picked = await request.select(`pi-permission: ${reason}\n\n ${body}`, [...OPTIONS]);
|
|
269
|
+
const index = OPTIONS.indexOf(picked ?? "");
|
|
270
|
+
const byIndex: Choice[] = ["allow", "allow-session", "deny", "stop"];
|
|
271
|
+
return resolveChoice(index >= 0 ? byIndex[index] : undefined, request);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
return { block: true, reason: `pi-permission (no UI to confirm): ${reason}. Ask the user to run it.` };
|
|
275
|
+
}
|