@jalaxy33/pi-permission 0.0.0-stage → 0.5.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.
@@ -0,0 +1,454 @@
1
+ /** Rule files: shipped defaults, user rulesets, presets, and composition. */
2
+
3
+ import { readFileSync } from "node:fs";
4
+ import { isAbsolute, resolve } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { expandTilde } from "./paths";
7
+ import { checkFields, isObject } from "./validate";
8
+ import {
9
+ SECTIONS,
10
+ type ActiveRuleSet,
11
+ type ConfigFile,
12
+ type IncludeRef,
13
+ type PathRule,
14
+ type Preset,
15
+ type PresetRef,
16
+ type Rule,
17
+ type RuleSet,
18
+ type Section,
19
+ } from "./types";
20
+
21
+ export function defaultConfigPath(): string {
22
+ return fileURLToPath(new URL("../rules/index.json", import.meta.url));
23
+ }
24
+
25
+ export function resolveRulePath(entry: string, baseDir: string): string {
26
+ const expanded = expandTilde(entry);
27
+ return isAbsolute(expanded) ? expanded : resolve(baseDir, expanded);
28
+ }
29
+
30
+ /** A file that exists but cannot be used. A missing file is not one of these. */
31
+ export interface ReadFailure {
32
+ path: string;
33
+ reason: string;
34
+ }
35
+
36
+ export function readJson(
37
+ path: string,
38
+ warnings: string[],
39
+ kind: "config" | "ruleset" = "config",
40
+ failures?: ReadFailure[],
41
+ ): ConfigFile | undefined {
42
+ let raw: string;
43
+ try {
44
+ raw = readFileSync(path, "utf8");
45
+ } catch {
46
+ return undefined;
47
+ }
48
+ try {
49
+ const parsed: unknown = JSON.parse(raw);
50
+ if (!isObject(parsed)) {
51
+ warnings.push(`${path}: expected a JSON object`);
52
+ failures?.push({ path, reason: "expected a JSON object" });
53
+ return undefined;
54
+ }
55
+ checkFields(parsed, path, warnings, kind);
56
+ return parsed as ConfigFile;
57
+ } catch (error) {
58
+ const reason = `invalid JSON (${(error as Error).message})`;
59
+ warnings.push(`${path}: ${reason}`);
60
+ failures?.push({ path, reason });
61
+ return undefined;
62
+ }
63
+ }
64
+
65
+ /** Fields only a config file may carry; a ruleset is rules and nothing else. */
66
+ const CONFIG_ONLY = [
67
+ "rulesets",
68
+ "presets",
69
+ "preset",
70
+ "include",
71
+ "defaultPermission",
72
+ "outsideCwd",
73
+ "enabled",
74
+ ] as const;
75
+
76
+ function forbiddenField(value: Record<string, unknown>): string | undefined {
77
+ return CONFIG_ONLY.find((key) => key in value);
78
+ }
79
+
80
+ /** A ruleset must be a plain object without composition or policy settings. */
81
+ export function checkRuleSetShape(value: unknown, label: string): string | undefined {
82
+ if (!isObject(value)) return `${label}: expected a ruleset object`;
83
+ const forbidden = forbiddenField(value);
84
+ if (forbidden) return `${label}: a ruleset must not contain "${forbidden}"`;
85
+ if (value.commands !== undefined && !isObject(value.commands)) return `${label}: "commands" must be an object`;
86
+ if (value.paths !== undefined && !Array.isArray(value.paths)) return `${label}: "paths" must be an array`;
87
+ return undefined;
88
+ }
89
+
90
+ export interface LoadedRuleSet {
91
+ id: string;
92
+ source?: string;
93
+ ruleset?: RuleSet;
94
+ error?: string;
95
+ }
96
+
97
+ export function loadRuleSetRef(
98
+ id: string,
99
+ ref: RuleSet | string,
100
+ baseDir: string,
101
+ warnings: string[],
102
+ ): LoadedRuleSet {
103
+ if (typeof ref === "string") {
104
+ const path = resolveRulePath(ref, baseDir);
105
+ const file = readJson(path, warnings, "ruleset");
106
+ if (!file) return { id, source: path, error: `rule file not found or invalid: ${path}` };
107
+ const shape = checkRuleSetShape({ commands: file.commands, paths: file.paths }, path);
108
+ if (shape) return { id, source: path, error: shape };
109
+ const forbidden = forbiddenField(file as unknown as Record<string, unknown>);
110
+ if (forbidden) return { id, source: path, error: `${path}: a ruleset must not contain "${forbidden}"` };
111
+ if (!file.commands && !file.paths) {
112
+ return { id, source: path, error: `${path}: expected "commands" or "paths"` };
113
+ }
114
+ return {
115
+ id,
116
+ source: path,
117
+ ruleset: { description: file.description, commands: file.commands, paths: file.paths },
118
+ };
119
+ }
120
+
121
+ const shapeError = checkRuleSetShape(ref, `ruleset "${id}"`);
122
+ if (shapeError) return { id, error: shapeError };
123
+ return { id, ruleset: ref };
124
+ }
125
+
126
+ export interface LoadedPreset {
127
+ id: string;
128
+ preset: Preset;
129
+ source: string;
130
+ }
131
+
132
+ export function loadPresets(file: ConfigFile, source: string, warnings: string[]): Map<string, LoadedPreset> {
133
+ const presets = new Map<string, LoadedPreset>();
134
+ if (file.presets !== undefined && !isObject(file.presets)) {
135
+ warnings.push(`${source}: "presets" must be an object`);
136
+ return presets;
137
+ }
138
+ for (const [id, preset] of Object.entries(file.presets ?? {})) {
139
+ const valid =
140
+ isObject(preset) &&
141
+ typeof preset.level === "number" &&
142
+ Array.isArray(preset.include) &&
143
+ preset.include.every((member) => typeof member === "string");
144
+ if (!valid) {
145
+ warnings.push(`${source}: preset "${id}" needs a numeric level and a string list`);
146
+ continue;
147
+ }
148
+ presets.set(id, { id, preset: preset as Preset, source });
149
+ }
150
+ return presets;
151
+ }
152
+
153
+ export interface SelectionEntry {
154
+ id: string;
155
+ /** Rule ids to drop from this ruleset. */
156
+ remove: string[];
157
+ }
158
+
159
+ export interface Selection {
160
+ entries: SelectionEntry[];
161
+ preset?: { name: string; level: number };
162
+ warnings: string[];
163
+ fatal?: string;
164
+ }
165
+
166
+ function entryOf(ref: IncludeRef | PresetRef, label: string): { id: string; remove: string[] } | string {
167
+ if (typeof ref === "string") return ref.trim() ? { id: ref, remove: [] } : `${label}: empty id`;
168
+ if (!isObject(ref) || typeof ref.id !== "string" || !ref.id) return `${label}: expected an id`;
169
+ if (ref.remove !== undefined) {
170
+ if (!Array.isArray(ref.remove) || !ref.remove.every((value) => typeof value === "string")) {
171
+ return `${label}: remove must be a list of rule ids`;
172
+ }
173
+ }
174
+ return { id: ref.id, remove: (ref.remove as string[] | undefined) ?? [] };
175
+ }
176
+
177
+ /**
178
+ * Expands the active preset and include list into an ordered set of rulesets.
179
+ * Duplicate ids inside the include list are an error: the list is a set.
180
+ */
181
+ export function resolveSelection(
182
+ presetRef: PresetRef | undefined,
183
+ includeList: IncludeRef[],
184
+ rulesets: Map<string, LoadedRuleSet>,
185
+ presets: Map<string, LoadedPreset>,
186
+ ): Selection {
187
+ const warnings: string[] = [];
188
+ let fatal: string | undefined;
189
+ const entries = new Map<string, SelectionEntry>();
190
+
191
+ const presetName = presetRef === undefined ? undefined : typeof presetRef === "string" ? presetRef : presetRef.id;
192
+ const preset = presetName === undefined ? undefined : presets.get(presetName);
193
+ if (presetName !== undefined && !preset) {
194
+ fatal = `pi-permission: unknown preset "${presetName}"`;
195
+ } else if (preset) {
196
+ const ref = entryOf(presetRef!, `preset "${preset.id}"`);
197
+ if (typeof ref === "string") {
198
+ fatal = ref;
199
+ } else {
200
+ const drop = new Set(ref.remove);
201
+ for (const member of preset.preset.include) {
202
+ if (drop.has(member)) continue;
203
+ if (!rulesets.has(member)) {
204
+ fatal = `pi-permission: preset "${preset.id}" includes unknown ruleset "${member}"`;
205
+ continue;
206
+ }
207
+ entries.set(member, { id: member, remove: [] });
208
+ }
209
+ for (const member of drop) {
210
+ if (!preset.preset.include.includes(member)) {
211
+ warnings.push(`${preset.source}: preset "${preset.id}": remove "${member}" matches no ruleset`);
212
+ }
213
+ }
214
+ }
215
+ }
216
+
217
+ const seen = new Set<string>();
218
+ for (const [index, raw] of includeList.entries()) {
219
+ const ref = entryOf(raw, `include[${index}]`);
220
+ if (typeof ref === "string") {
221
+ fatal ??= `pi-permission: ${ref}`;
222
+ continue;
223
+ }
224
+ if (!rulesets.has(ref.id)) {
225
+ fatal ??= `pi-permission: unknown ruleset "${ref.id}"`;
226
+ continue;
227
+ }
228
+ if (seen.has(ref.id)) {
229
+ fatal ??= `pi-permission: ruleset "${ref.id}" is listed twice in include`;
230
+ continue;
231
+ }
232
+ seen.add(ref.id);
233
+ entries.set(ref.id, ref);
234
+ }
235
+
236
+ return {
237
+ entries: [...entries.values()],
238
+ preset: preset ? { name: preset.id, level: preset.preset.level } : undefined,
239
+ warnings,
240
+ fatal,
241
+ };
242
+ }
243
+
244
+ export interface CommandContribution {
245
+ ruleset: string;
246
+ section: Section;
247
+ rule: Rule;
248
+ source?: string;
249
+ }
250
+
251
+ export interface PathContribution {
252
+ ruleset: string;
253
+ rule: PathRule;
254
+ source?: string;
255
+ }
256
+
257
+ export interface SelectedRules {
258
+ commands: CommandContribution[];
259
+ paths: PathContribution[];
260
+ active: ActiveRuleSet[];
261
+ warnings: string[];
262
+ fatal?: string;
263
+ }
264
+
265
+ function ruleList(ruleset: RuleSet): Array<{ section: Section; rule: Rule }> {
266
+ const out: Array<{ section: Section; rule: Rule }> = [];
267
+ for (const section of SECTIONS) {
268
+ const list = ruleset.commands?.[section];
269
+ if (!Array.isArray(list)) continue;
270
+ for (const rule of list) out.push({ section, rule });
271
+ }
272
+ return out;
273
+ }
274
+
275
+ /**
276
+ * Collects the rules of every selected ruleset, applying each entry's removals.
277
+ * A rule id shared by two selected rulesets is an error: composition never
278
+ * relies on load order to pick a winner.
279
+ */
280
+ export function collectSelected(
281
+ selection: Selection,
282
+ rulesets: Map<string, LoadedRuleSet>,
283
+ ): SelectedRules {
284
+ const commands: CommandContribution[] = [];
285
+ const paths: PathContribution[] = [];
286
+ const active: ActiveRuleSet[] = [];
287
+ const warnings: string[] = [];
288
+ let fatal: string | undefined = selection.fatal;
289
+ const commandOwner = new Map<string, string>();
290
+ const pathOwner = new Map<string, string>();
291
+
292
+ for (const entry of selection.entries) {
293
+ const loaded = rulesets.get(entry.id);
294
+ if (!loaded) {
295
+ fatal ??= `pi-permission: unknown ruleset "${entry.id}"`;
296
+ continue;
297
+ }
298
+ if (loaded.error || !loaded.ruleset) {
299
+ fatal ??= `pi-permission: ${loaded.error ?? `ruleset "${entry.id}" is empty`}`;
300
+ continue;
301
+ }
302
+
303
+ const remove = new Set(entry.remove);
304
+ const seen = new Set<string>();
305
+ const removed = new Set<string>();
306
+ const contributed: CommandContribution[] = [];
307
+ const contributedPaths: PathContribution[] = [];
308
+
309
+ for (const { section, rule } of ruleList(loaded.ruleset)) {
310
+ if (!rule?.id) {
311
+ warnings.push(`ruleset "${entry.id}": ignore rule without id`);
312
+ continue;
313
+ }
314
+ if (seen.has(rule.id)) {
315
+ fatal ??= `pi-permission: ruleset "${entry.id}" defines rule "${rule.id}" twice`;
316
+ continue;
317
+ }
318
+ seen.add(rule.id);
319
+ if (remove.has(rule.id)) {
320
+ removed.add(rule.id);
321
+ continue;
322
+ }
323
+ const owner = commandOwner.get(rule.id);
324
+ if (owner) {
325
+ fatal ??= `pi-permission: rule "${rule.id}" is defined by both "${owner}" and "${entry.id}"`;
326
+ continue;
327
+ }
328
+ commandOwner.set(rule.id, entry.id);
329
+ contributed.push({ ruleset: entry.id, section, rule, source: loaded.source });
330
+ }
331
+
332
+ const pathList = Array.isArray(loaded.ruleset.paths) ? loaded.ruleset.paths : [];
333
+ for (const rule of pathList) {
334
+ if (!rule?.id) {
335
+ warnings.push(`ruleset "${entry.id}": ignore path rule without id`);
336
+ continue;
337
+ }
338
+ if (seen.has(rule.id)) {
339
+ fatal ??= `pi-permission: ruleset "${entry.id}" defines rule "${rule.id}" twice`;
340
+ continue;
341
+ }
342
+ seen.add(rule.id);
343
+ if (remove.has(rule.id)) {
344
+ removed.add(rule.id);
345
+ continue;
346
+ }
347
+ const owner = pathOwner.get(rule.id);
348
+ if (owner) {
349
+ fatal ??= `pi-permission: path rule "${rule.id}" is defined by both "${owner}" and "${entry.id}"`;
350
+ continue;
351
+ }
352
+ pathOwner.set(rule.id, entry.id);
353
+ contributedPaths.push({ ruleset: entry.id, rule, source: loaded.source });
354
+ }
355
+
356
+ for (const id of remove) {
357
+ if (!seen.has(id)) warnings.push(`ruleset "${entry.id}": remove "${id}" matches no rule`);
358
+ }
359
+
360
+ commands.push(...contributed);
361
+ paths.push(...contributedPaths);
362
+ active.push({
363
+ id: entry.id,
364
+ source: loaded.source,
365
+ rules: contributed.length,
366
+ paths: contributedPaths.length,
367
+ removed: [...removed],
368
+ });
369
+ }
370
+
371
+ return { commands, paths, active, warnings, fatal };
372
+ }
373
+
374
+ export interface OwnRules {
375
+ commands: Map<string, CommandContribution>;
376
+ paths: Map<string, PathContribution>;
377
+ warnings: string[];
378
+ fatal?: string;
379
+ }
380
+
381
+ /** Rules written in config files. Later files win by id; duplicates in one file are errors. */
382
+ export function collectOwn(scopes: Array<{ path: string; file: ConfigFile }>): OwnRules {
383
+ const commands = new Map<string, CommandContribution>();
384
+ const paths = new Map<string, PathContribution>();
385
+ const warnings: string[] = [];
386
+ let fatal: string | undefined;
387
+
388
+ for (const scope of scopes) {
389
+ const local = new Set<string>();
390
+ for (const { section, rule } of ruleList(scope.file)) {
391
+ if (!rule?.id) {
392
+ warnings.push(`${scope.path}: ignore rule without id`);
393
+ continue;
394
+ }
395
+ if (local.has(`rule:${rule.id}`)) {
396
+ fatal ??= `pi-permission: ${scope.path} defines rule "${rule.id}" twice`;
397
+ continue;
398
+ }
399
+ local.add(`rule:${rule.id}`);
400
+ commands.set(rule.id, { ruleset: scope.path, section, rule, source: scope.path });
401
+ }
402
+ const pathList = Array.isArray(scope.file.paths) ? scope.file.paths : [];
403
+ for (const rule of pathList) {
404
+ if (!rule?.id) {
405
+ warnings.push(`${scope.path}: ignore path rule without id`);
406
+ continue;
407
+ }
408
+ if (local.has(`path:${rule.id}`)) {
409
+ fatal ??= `pi-permission: ${scope.path} defines path rule "${rule.id}" twice`;
410
+ continue;
411
+ }
412
+ local.add(`path:${rule.id}`);
413
+ paths.set(rule.id, { ruleset: scope.path, rule, source: scope.path });
414
+ }
415
+ }
416
+
417
+ return { commands, paths, warnings, fatal };
418
+ }
419
+
420
+ export interface MergedRules {
421
+ commands: { deny: Rule[]; ask: Rule[]; allow: Rule[] };
422
+ paths: PathRule[];
423
+ warnings: string[];
424
+ }
425
+
426
+ /**
427
+ * Config rules override selected rulesets by id (a more specific layer wins).
428
+ * A selected deny rule that a config turns into ask or allow is reported.
429
+ */
430
+ export function mergeRules(selected: SelectedRules, own: OwnRules): MergedRules {
431
+ const warnings: string[] = [];
432
+ const commands: MergedRules["commands"] = { deny: [], ask: [], allow: [] };
433
+ const bundled = new Map<string, CommandContribution>();
434
+ for (const contribution of selected.commands) bundled.set(contribution.rule.id, contribution);
435
+
436
+ for (const contribution of selected.commands) {
437
+ if (own.commands.has(contribution.rule.id)) continue;
438
+ commands[contribution.section].push(contribution.rule);
439
+ }
440
+
441
+ for (const [id, entry] of own.commands) {
442
+ const previous = bundled.get(id);
443
+ if (previous && previous.section === "deny" && entry.section !== "deny") {
444
+ warnings.push(`rule "${id}" dropped from deny by ${entry.source}`);
445
+ }
446
+ commands[entry.section].push(entry.rule);
447
+ }
448
+
449
+ const pathIds = new Set(selected.paths.map((contribution) => contribution.rule.id));
450
+ const paths = selected.paths.map((contribution) => own.paths.get(contribution.rule.id)?.rule ?? contribution.rule);
451
+ for (const [id, entry] of own.paths) if (!pathIds.has(id)) paths.push(entry.rule);
452
+
453
+ return { commands, paths, warnings };
454
+ }
package/src/scripts.ts ADDED
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Programs that run source code, and how to name that code in a session grant.
3
+ *
4
+ * A shell script can be read and judged like the command line it is. Every
5
+ * other language is a program the gate cannot parse, so its script becomes an
6
+ * opaque ask: once per file (by content), never for stdin.
7
+ */
8
+
9
+ import { createHash } from "node:crypto";
10
+ import { normalizeProgram } from "./program";
11
+
12
+ /** Programs whose first non-flag argument is source code. */
13
+ const INTERPRETERS =
14
+ /^(python[0-9.]*|pypy[0-9.]*|node|nodejs|bun|deno|perl|ruby|php|lua|rscript|osascript|pwsh|powershell|groovy|tclsh|wish)$/;
15
+
16
+ export function isCodeRunner(program: string): boolean {
17
+ return INTERPRETERS.test(normalizeProgram(program).toLowerCase());
18
+ }
19
+
20
+ const SCRIPT_NAME = /\.(sh|bash|zsh|ksh|dash|fish|py|pyw|js|mjs|cjs|ts|pl|rb|php|lua|ps1|tcl)$/i;
21
+
22
+ /** A positional that names source code rather than a data operand. */
23
+ export function scriptOperand(positional: string[]): string | undefined {
24
+ return positional.find(
25
+ (token) => SCRIPT_NAME.test(token) || token.startsWith("./") || token.startsWith("../") || token.startsWith("/"),
26
+ );
27
+ }
28
+
29
+ export function scriptHash(text: string): string {
30
+ return createHash("sha1").update(text).digest("hex").slice(0, 16);
31
+ }