@hop-top/kit 0.5.0-alpha.10 → 0.5.0-alpha.11
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/CHANGELOG.md +24 -0
- package/README.md +4 -4
- package/dist/alias.js +3 -3
- package/dist/{chunk-T46YPHKN.js → chunk-4FMALWYB.js} +45 -45
- package/dist/{chunk-WWUKGJB5.js → chunk-4GPCWBBA.js} +60 -7
- package/dist/{chunk-JZ22ZUFA.js → chunk-65VPWMPV.js} +4 -1
- package/dist/{chunk-YGYQUFGY.js → chunk-BXJ2J27B.js} +10 -10
- package/dist/chunk-CXBZTONY.js +65 -0
- package/dist/{chunk-K7VCKJ27.js → chunk-EE4M2UOF.js} +8 -4
- package/dist/{chunk-72XZWQX7.js → chunk-GFRAYYRD.js} +475 -162
- package/dist/{chunk-2JV3A7OP.js → chunk-IVQHLI56.js} +6 -10
- package/dist/{chunk-NLMS7HGP.js → chunk-IZ6Q4SE3.js} +3 -3
- package/dist/chunk-MFVUENZR.js +1549 -0
- package/dist/{chunk-BLS2OBIQ.js → chunk-ML7D5DWY.js} +2 -2
- package/dist/{chunk-GGWJRWWA.js → chunk-RYKLVOVK.js} +7 -7
- package/dist/{chunk-QPUCXQXT.js → chunk-T6OZMPPV.js} +2 -1
- package/dist/{chunk-MUIQVU6E.js → chunk-VGOA5Y7S.js} +11 -11
- package/dist/{chunk-ABQSE7AI.js → chunk-VWGP4NVJ.js} +38 -38
- package/dist/cli-RSRk1M36.d.ts +707 -0
- package/dist/cli.d.ts +1 -1
- package/dist/cli.js +60 -5
- package/dist/completion.js +2 -2
- package/dist/{index-DCe1boBz.d.ts → index-CGE5yLBj.d.ts} +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +22 -22
- package/dist/llm-anthropic.js +5 -5
- package/dist/llm-openai.js +5 -5
- package/dist/llm.js +3 -3
- package/dist/log.js +3 -3
- package/dist/mcp/index.js +3 -2
- package/dist/output.js +2 -4
- package/dist/routellm.js +6 -6
- package/dist/toolspec.js +4 -4
- package/dist/tui/index.d.ts +2 -2
- package/dist/tui/index.js +3 -3
- package/dist/{upgrade-p_zh3pvV.d.ts → upgrade-C3RWGwRi.d.ts} +23 -0
- package/dist/upgrade.d.ts +1 -1
- package/dist/upgrade.js +2 -2
- package/package.json +1 -1
- package/src/cli.root.conformance.test.ts +166 -0
- package/src/cli.ts +39 -0
- package/src/completion.conformance.test.ts +3 -2
- package/src/completion.test.ts +12 -0
- package/src/completion.ts +8 -3
- package/src/delegation.test.ts +299 -0
- package/src/delegation.ts +807 -0
- package/src/mcp/bridge.test.ts +28 -0
- package/src/mcp/bridge.ts +5 -10
- package/src/plan.ts +89 -0
- package/src/policy.ts +472 -0
- package/src/sideeffect.ts +105 -0
- package/src/toolspec-manifest.ts +7 -2
- package/src/upgrade.test.ts +291 -0
- package/src/upgrade.ts +116 -7
- package/dist/chunk-GHPJJV5L.js +0 -613
- package/dist/chunk-IXVQ62NZ.js +0 -334
- package/dist/cli-C5B5tnpA.d.ts +0 -400
- package/dist/{chunk-PSFYJGDG.js → chunk-K7E34Q3A.js} +2 -2
package/src/mcp/bridge.test.ts
CHANGED
|
@@ -220,3 +220,31 @@ describe('commanderBridge', () => {
|
|
|
220
220
|
);
|
|
221
221
|
});
|
|
222
222
|
});
|
|
223
|
+
|
|
224
|
+
describe('classify: destructive-name inference', () => {
|
|
225
|
+
const leafOf = (name: string, ann?: Record<string, string>) => {
|
|
226
|
+
const root = new Command('root');
|
|
227
|
+
const c = new Command(name).description(name);
|
|
228
|
+
if (ann) annotate(c, ann);
|
|
229
|
+
root.addCommand(c);
|
|
230
|
+
return commanderBridge(root, { run }).leaves()[0]!;
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
it('treats an unannotated destructive-named leaf as destructive and blocks it', async () => {
|
|
234
|
+
const root = new Command('root');
|
|
235
|
+
root.addCommand(new Command('delete').description('d'));
|
|
236
|
+
const bridge = commanderBridge(root, { run });
|
|
237
|
+
expect(bridge.leaves()[0]!.class?.destructive).toBe(true);
|
|
238
|
+
await expect(
|
|
239
|
+
bridge.invoke({ path: ['delete'], args: [], flags: {}, meta: { surface: SURFACE_MCP } } as never),
|
|
240
|
+
).rejects.toThrow(/destructive command blocked on this surface/);
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
it('an explicit annotation wins, valid or malformed; empty infers; other names do not', () => {
|
|
244
|
+
expect(leafOf('delete', { 'kit/side-effect': 'read' }).class?.destructive).toBeUndefined();
|
|
245
|
+
expect(leafOf('delete', { 'kit/side-effect': 'bogus' }).class?.destructive).toBeUndefined();
|
|
246
|
+
expect(leafOf('delete', { 'kit/side-effect': '' }).class?.destructive).toBe(true);
|
|
247
|
+
expect(leafOf('delete-all').class?.destructive).toBeUndefined();
|
|
248
|
+
expect(leafOf('rm').class?.destructive).toBe(true);
|
|
249
|
+
});
|
|
250
|
+
});
|
package/src/mcp/bridge.ts
CHANGED
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
|
|
19
19
|
import type { Command, Option } from 'commander';
|
|
20
20
|
import { declaredArgs, takesNoValue } from '../toolspec-internal.js';
|
|
21
|
+
import { gateSideEffect, isDestructiveLike } from '../sideeffect.js';
|
|
21
22
|
import {
|
|
22
23
|
DestructiveBlockedError,
|
|
23
24
|
policyAllowed,
|
|
@@ -36,7 +37,6 @@ import {
|
|
|
36
37
|
} from './types.js';
|
|
37
38
|
|
|
38
39
|
/** Annotation keys read off a command, matching the kit/ vocabulary. */
|
|
39
|
-
const ANN_SIDE_EFFECT = 'kit/side-effect';
|
|
40
40
|
const ANN_AUTH_REQUIRED = 'kit/auth-required';
|
|
41
41
|
const ANN_REQUIRES_CONFIRM = 'kit/requires-confirmation';
|
|
42
42
|
const ANN_PERMISSIONS = 'kit/permissions';
|
|
@@ -134,15 +134,10 @@ export function commanderBridge(
|
|
|
134
134
|
export function classify(cmd: AnnotatedCommand): SafetyClass {
|
|
135
135
|
const ann = cmd.annotations ?? {};
|
|
136
136
|
const cls: SafetyClass = {};
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
cls.destructive = true;
|
|
142
|
-
break;
|
|
143
|
-
default:
|
|
144
|
-
break;
|
|
145
|
-
}
|
|
137
|
+
// A declared tier wins; an unannotated destructive-named leaf is the
|
|
138
|
+
// inferred destructive tier, as the CLI gate and Go's cmdreflect read it.
|
|
139
|
+
const tier = gateSideEffect(cmd.name(), ann);
|
|
140
|
+
if (tier !== undefined && isDestructiveLike(tier)) cls.destructive = true;
|
|
146
141
|
if (ann[ANN_AUTH_REQUIRED] === 'true') cls.authRequired = true;
|
|
147
142
|
if (ann[ANN_REQUIRES_CONFIRM] === 'true') cls.requiresConfirmation = true;
|
|
148
143
|
const perms = splitCSV(ann[ANN_PERMISSIONS]);
|
package/src/plan.ts
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module plan
|
|
3
|
+
* @package @hop-top/kit
|
|
4
|
+
*
|
|
5
|
+
* The structured dry-run output of a write or destructive command. Ports
|
|
6
|
+
* Go `cli.Plan` / `cli.RenderPlan`: a handler that sees `isDryRun(cmd)`
|
|
7
|
+
* builds a {@link Plan} of what it would change and renders it instead of
|
|
8
|
+
* acting.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import * as yaml from 'js-yaml';
|
|
12
|
+
|
|
13
|
+
import { render, TABLE_FORMAT } from './output.js';
|
|
14
|
+
|
|
15
|
+
/** One declared state change a {@link Plan} would apply. */
|
|
16
|
+
export interface Effect {
|
|
17
|
+
/** A short verb: `create`, `update`, `delete`. */
|
|
18
|
+
kind: string;
|
|
19
|
+
/** The addressable resource (`alias:foo`, `/etc/hosts`). */
|
|
20
|
+
target: string;
|
|
21
|
+
/** Whether the inverse command restores prior state losslessly. */
|
|
22
|
+
reversible: boolean;
|
|
23
|
+
/** A free-form one-line note. */
|
|
24
|
+
detail?: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** What a command would do if re-issued without `--dry-run`. */
|
|
28
|
+
export interface Plan {
|
|
29
|
+
/** The full command path; filled in by {@link renderPlan} when empty. */
|
|
30
|
+
command?: string;
|
|
31
|
+
/** The resolved arguments. */
|
|
32
|
+
args?: Record<string, unknown>;
|
|
33
|
+
/** The ordered changes. */
|
|
34
|
+
effects?: Effect[];
|
|
35
|
+
/** Pre-flight checks that passed while planning. */
|
|
36
|
+
prerequisites_checked?: string[];
|
|
37
|
+
/** Non-fatal advisories for the operator. */
|
|
38
|
+
warnings?: string[];
|
|
39
|
+
/** RFC 3339 UTC time of assembly; stamped when empty. */
|
|
40
|
+
generated_at?: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** `YYYY-MM-DDTHH:MM:SSZ` for now. */
|
|
44
|
+
function rfc3339Now(): string {
|
|
45
|
+
return new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The plan as its wire object: Go struct key order, empty optionals off. */
|
|
49
|
+
function toWire(p: Plan, commandPath: string): Record<string, unknown> {
|
|
50
|
+
const w: Record<string, unknown> = { command: p.command || commandPath };
|
|
51
|
+
if (p.args && Object.keys(p.args).length > 0) w['args'] = p.args;
|
|
52
|
+
w['effects'] = (p.effects ?? []).map((e) => {
|
|
53
|
+
const o: Record<string, unknown> = { kind: e.kind, target: e.target, reversible: e.reversible };
|
|
54
|
+
if (e.detail) o['detail'] = e.detail;
|
|
55
|
+
return o;
|
|
56
|
+
});
|
|
57
|
+
if (p.prerequisites_checked && p.prerequisites_checked.length > 0) {
|
|
58
|
+
w['prerequisites_checked'] = p.prerequisites_checked;
|
|
59
|
+
}
|
|
60
|
+
if (p.warnings && p.warnings.length > 0) w['warnings'] = p.warnings;
|
|
61
|
+
w['generated_at'] = p.generated_at || rfc3339Now();
|
|
62
|
+
return w;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Writes `plan` as the command's dry-run output in `format`: `json` and
|
|
67
|
+
* `yaml` serialize it, anything else prints the plan table. An empty
|
|
68
|
+
* `command` defaults to `commandPath` and an empty `generated_at` to now.
|
|
69
|
+
*/
|
|
70
|
+
export function renderPlan(
|
|
71
|
+
w: { write(chunk: string): unknown },
|
|
72
|
+
format: string,
|
|
73
|
+
plan: Plan,
|
|
74
|
+
commandPath = '',
|
|
75
|
+
): void {
|
|
76
|
+
const wire = toWire(plan, commandPath);
|
|
77
|
+
if (format === 'json') {
|
|
78
|
+
w.write(`${JSON.stringify(wire, null, 2)}\n`);
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
if (format === 'yaml') {
|
|
82
|
+
w.write(yaml.dump(wire));
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
w.write(`COMMAND ${wire['command'] as string}\n`);
|
|
86
|
+
w.write(`GENERATED ${wire['generated_at'] as string}\n`);
|
|
87
|
+
for (const warn of plan.warnings ?? []) w.write(`WARNING ${warn}\n`);
|
|
88
|
+
render(w as NodeJS.WritableStream, TABLE_FORMAT, wire['effects']);
|
|
89
|
+
}
|
package/src/policy.ts
ADDED
|
@@ -0,0 +1,472 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module policy
|
|
3
|
+
* @package @hop-top/kit
|
|
4
|
+
*
|
|
5
|
+
* The delegation-safety policy: which side-effect classes a named policy
|
|
6
|
+
* lets run, how many mutating operations one invocation may perform, and
|
|
7
|
+
* which commands always ask for confirmation. Ports Go
|
|
8
|
+
* `console/cli/policy` (policy, engine, loader, the shipped `kit-default`).
|
|
9
|
+
*
|
|
10
|
+
* `permissions:` rules are carried and shape-validated but never
|
|
11
|
+
* evaluated (the expression evaluator is Go's `celpermission`), and the
|
|
12
|
+
* `callers:` section is carried and validated but unused: the CLI has no
|
|
13
|
+
* transport-established caller, so only the policy's own rules answer.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import * as fs from 'node:fs';
|
|
17
|
+
import * as path from 'node:path';
|
|
18
|
+
import * as yaml from 'js-yaml';
|
|
19
|
+
|
|
20
|
+
import { configDir } from './xdg.js';
|
|
21
|
+
|
|
22
|
+
/** Name of the policy kit ships; reserved, never a file. */
|
|
23
|
+
export const KIT_DEFAULT_NAME = 'kit-default';
|
|
24
|
+
|
|
25
|
+
/** Tiers of the legacy vocabulary a policy's `allow` map is keyed by. */
|
|
26
|
+
type Class = 'read' | 'write' | 'destructive' | 'interactive';
|
|
27
|
+
|
|
28
|
+
/** One `permissions:` entry; carried and shape-validated, not evaluated. */
|
|
29
|
+
export interface PermissionRule {
|
|
30
|
+
name: string;
|
|
31
|
+
when: string;
|
|
32
|
+
effect: string;
|
|
33
|
+
otherwise: string;
|
|
34
|
+
message?: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** One `callers:` entry; carried and validated, unused on the CLI. */
|
|
38
|
+
export interface CallerRule {
|
|
39
|
+
principal?: string;
|
|
40
|
+
tenant?: string;
|
|
41
|
+
scope?: string;
|
|
42
|
+
allow?: Record<string, string[]>;
|
|
43
|
+
max_ops?: number;
|
|
44
|
+
window?: string;
|
|
45
|
+
require_declared_scope?: string[];
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface Policy {
|
|
49
|
+
name: string;
|
|
50
|
+
/** Per-class verb glob lists. An empty list refuses the class. */
|
|
51
|
+
allow?: Record<string, string[]>;
|
|
52
|
+
/** Per-invocation cap on mutating ops; 0 means unlimited. */
|
|
53
|
+
max_ops: number;
|
|
54
|
+
/** Command-path globs that always require confirmation. */
|
|
55
|
+
require_confirm: string[];
|
|
56
|
+
permissions: PermissionRule[];
|
|
57
|
+
/** Class a command declaring no side-effect is authorized as. */
|
|
58
|
+
unannotated?: string;
|
|
59
|
+
callers: CallerRule[];
|
|
60
|
+
/** Appended to every refusal; set by shipped policies only. */
|
|
61
|
+
remedy?: string;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Thrown by {@link Engine.recordOp} once the budget is hit. */
|
|
65
|
+
export class MaxOpsExceededError extends Error {
|
|
66
|
+
constructor() {
|
|
67
|
+
super('policy: max-ops budget exceeded');
|
|
68
|
+
this.name = 'MaxOpsExceededError';
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** A policy with no rules: default-permit. */
|
|
73
|
+
export function emptyPolicy(): Policy {
|
|
74
|
+
return { name: '', max_ops: 0, require_confirm: [], permissions: [], callers: [] };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* The policy kit ships: a command declaring no side effect is a write; a
|
|
79
|
+
* caller nobody established reads only; an established principal reads and
|
|
80
|
+
* writes and runs a destructive command that declares a permissions scope.
|
|
81
|
+
*/
|
|
82
|
+
export function kitDefault(): Policy {
|
|
83
|
+
return {
|
|
84
|
+
name: KIT_DEFAULT_NAME,
|
|
85
|
+
unannotated: 'write',
|
|
86
|
+
allow: { write: [], destructive: [] },
|
|
87
|
+
max_ops: 0,
|
|
88
|
+
require_confirm: [],
|
|
89
|
+
permissions: [],
|
|
90
|
+
callers: [
|
|
91
|
+
{
|
|
92
|
+
allow: { write: ['*'], destructive: ['*'] },
|
|
93
|
+
require_declared_scope: ['destructive'],
|
|
94
|
+
},
|
|
95
|
+
],
|
|
96
|
+
remedy:
|
|
97
|
+
"kit's default beyond loopback: writes need an authenticated caller, " +
|
|
98
|
+
'destructive commands a declared kit/permissions scope; ' +
|
|
99
|
+
'name a --policy to choose otherwise',
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Maps a tier onto its legacy class; undefined outside kit's vocabulary. */
|
|
104
|
+
export function classOf(tier: string): Class | undefined {
|
|
105
|
+
switch (tier) {
|
|
106
|
+
case 'read':
|
|
107
|
+
case 'write':
|
|
108
|
+
case 'destructive':
|
|
109
|
+
case 'interactive':
|
|
110
|
+
return tier;
|
|
111
|
+
case 'write-local':
|
|
112
|
+
case 'write-shared':
|
|
113
|
+
return 'write';
|
|
114
|
+
case 'destructive-local':
|
|
115
|
+
case 'destructive-shared':
|
|
116
|
+
return 'destructive';
|
|
117
|
+
default:
|
|
118
|
+
return undefined;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// ---------------------------------------------------------------------------
|
|
123
|
+
// path.Match
|
|
124
|
+
// ---------------------------------------------------------------------------
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Shell-style match with Go `path.Match` semantics: `*` any run of
|
|
128
|
+
* non-`/` characters, `?` one non-`/` character, `[...]` a class with
|
|
129
|
+
* ranges and `^` negation, `\` escapes. A malformed pattern matches
|
|
130
|
+
* nothing.
|
|
131
|
+
*/
|
|
132
|
+
export function pathMatch(pattern: string, name: string): boolean {
|
|
133
|
+
let re = '^';
|
|
134
|
+
for (let i = 0; i < pattern.length; i++) {
|
|
135
|
+
const c = pattern[i]!;
|
|
136
|
+
if (c === '*') {
|
|
137
|
+
re += '[^/]*';
|
|
138
|
+
} else if (c === '?') {
|
|
139
|
+
re += '[^/]';
|
|
140
|
+
} else if (c === '\\') {
|
|
141
|
+
i++;
|
|
142
|
+
if (i >= pattern.length) return false;
|
|
143
|
+
re += escapeRe(pattern[i]!);
|
|
144
|
+
} else if (c === '[') {
|
|
145
|
+
let j = i + 1;
|
|
146
|
+
let cls = '[';
|
|
147
|
+
if (pattern[j] === '^') {
|
|
148
|
+
cls += '^';
|
|
149
|
+
j++;
|
|
150
|
+
}
|
|
151
|
+
let n = 0;
|
|
152
|
+
for (;; j++) {
|
|
153
|
+
if (j >= pattern.length) return false;
|
|
154
|
+
const d = pattern[j]!;
|
|
155
|
+
if (d === ']' && n > 0) break;
|
|
156
|
+
n++;
|
|
157
|
+
if (d === '\\') {
|
|
158
|
+
j++;
|
|
159
|
+
if (j >= pattern.length) return false;
|
|
160
|
+
cls += escapeRe(pattern[j]!);
|
|
161
|
+
} else if (d === '-' && n > 1 && pattern[j + 1] !== ']') {
|
|
162
|
+
cls += '-';
|
|
163
|
+
} else {
|
|
164
|
+
cls += escapeRe(d);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
re += cls + ']';
|
|
168
|
+
i = j;
|
|
169
|
+
} else {
|
|
170
|
+
re += escapeRe(c);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
try {
|
|
174
|
+
return new RegExp(re + '$', 's').test(name);
|
|
175
|
+
} catch {
|
|
176
|
+
return false;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function escapeRe(c: string): string {
|
|
181
|
+
return c.replace(/[\\^$.*+?()[\]{}|/-]/g, '\\$&');
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function matchAny(patterns: readonly string[], value: string): boolean {
|
|
185
|
+
for (const p of patterns) {
|
|
186
|
+
if (p === '*') return true;
|
|
187
|
+
if (pathMatch(p, value)) return true;
|
|
188
|
+
// "delete:*" is the documented shorthand for the verb and its subverbs.
|
|
189
|
+
if (p.endsWith(':*')) {
|
|
190
|
+
const prefix = p.slice(0, -2);
|
|
191
|
+
if (value === prefix || value.startsWith(prefix + ' ')) return true;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return false;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// ---------------------------------------------------------------------------
|
|
198
|
+
// Engine
|
|
199
|
+
// ---------------------------------------------------------------------------
|
|
200
|
+
|
|
201
|
+
/** What the engine reads about the command being authorized. */
|
|
202
|
+
export interface CommandRef {
|
|
203
|
+
/** The command path minus the root name (`widget add`). */
|
|
204
|
+
verb: string;
|
|
205
|
+
/** The resolved tier (declared or inferred); undefined when untagged. */
|
|
206
|
+
sideEffect?: string;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export interface Verdict {
|
|
210
|
+
allowed: boolean;
|
|
211
|
+
requireConfirm: boolean;
|
|
212
|
+
reason: string;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function lookupClass(
|
|
216
|
+
allow: Record<string, string[]> | undefined,
|
|
217
|
+
tier: string,
|
|
218
|
+
): string[] | undefined {
|
|
219
|
+
if (!allow) return undefined;
|
|
220
|
+
if (Object.prototype.hasOwnProperty.call(allow, tier)) return allow[tier];
|
|
221
|
+
const cls = classOf(tier);
|
|
222
|
+
if (cls !== undefined && cls !== tier && Object.prototype.hasOwnProperty.call(allow, cls)) {
|
|
223
|
+
return allow[cls];
|
|
224
|
+
}
|
|
225
|
+
return undefined;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Per-invocation enforcement state: {@link Engine.authorize} each command
|
|
230
|
+
* before it runs, {@link Engine.recordOp} after a successful mutating run.
|
|
231
|
+
*/
|
|
232
|
+
export class Engine {
|
|
233
|
+
private ops = 0;
|
|
234
|
+
private readonly max: number;
|
|
235
|
+
|
|
236
|
+
/** `maxOpsOverride > 0` takes precedence over the policy's `max_ops`. */
|
|
237
|
+
constructor(
|
|
238
|
+
readonly policy: Policy,
|
|
239
|
+
maxOpsOverride = 0,
|
|
240
|
+
) {
|
|
241
|
+
this.max = maxOpsOverride > 0 ? maxOpsOverride : policy.max_ops;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
maxOps(): number {
|
|
245
|
+
return this.max;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
opsCount(): number {
|
|
249
|
+
return this.ops;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
authorize(cmd: CommandRef): Verdict {
|
|
253
|
+
const se = cmd.sideEffect ?? this.policy.unannotated;
|
|
254
|
+
// Untagged and unaddressed by the policy: defer to the validator.
|
|
255
|
+
if (se === undefined || se === '') return { allowed: true, requireConfirm: false, reason: '' };
|
|
256
|
+
if (se === 'read') return { allowed: true, requireConfirm: false, reason: '' };
|
|
257
|
+
// Fail closed: a tier outside kit's vocabulary matches no class.
|
|
258
|
+
if (classOf(se) === undefined) {
|
|
259
|
+
return {
|
|
260
|
+
allowed: false,
|
|
261
|
+
requireConfirm: false,
|
|
262
|
+
reason: this.refusal(`policy: unknown side-effect ${JSON.stringify(se)} for ${cmd.verb}`),
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
const patterns = lookupClass(this.policy.allow, se);
|
|
266
|
+
if (patterns !== undefined && !matchAny(patterns, cmd.verb)) {
|
|
267
|
+
return {
|
|
268
|
+
allowed: false,
|
|
269
|
+
requireConfirm: false,
|
|
270
|
+
reason: this.refusal(`policy: ${se} not allowed for ${cmd.verb}`),
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
return {
|
|
274
|
+
allowed: true,
|
|
275
|
+
requireConfirm: matchAny(this.policy.require_confirm, cmd.verb),
|
|
276
|
+
reason: '',
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** Accounts a successful mutating op; throws once the budget is hit. */
|
|
281
|
+
recordOp(): void {
|
|
282
|
+
this.ops++;
|
|
283
|
+
if (this.max > 0 && this.ops > this.max) throw new MaxOpsExceededError();
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
private refusal(reason: string): string {
|
|
287
|
+
const r = this.policy.remedy;
|
|
288
|
+
return r ? `${reason} (policy ${this.policy.name}: ${r})` : reason;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// ---------------------------------------------------------------------------
|
|
293
|
+
// Loader
|
|
294
|
+
// ---------------------------------------------------------------------------
|
|
295
|
+
|
|
296
|
+
const VALID_NAME = /^[A-Za-z0-9_-]{1,64}$/;
|
|
297
|
+
|
|
298
|
+
/** Resolves a policy name to a Policy; adopters supply one to the CLI. */
|
|
299
|
+
export type PolicyLoader = (name: string) => Policy;
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* The canonical path of a named policy:
|
|
303
|
+
* `$XDG_CONFIG_HOME/<tool>/policies/<name>.yaml`. A name is a file stem,
|
|
304
|
+
* never a path: anything outside `[A-Za-z0-9_-]{1,64}` is refused before
|
|
305
|
+
* any filesystem access.
|
|
306
|
+
*/
|
|
307
|
+
export function resolvePolicyPath(tool: string, name: string): string {
|
|
308
|
+
if (tool === '') throw new Error('policy: tool name required for XDG resolution');
|
|
309
|
+
if (name === '') throw new Error('policy: policy name required');
|
|
310
|
+
if (!VALID_NAME.test(name)) {
|
|
311
|
+
throw new Error(`policy: invalid policy name ${JSON.stringify(name)} (want [A-Za-z0-9_-]{1,64})`);
|
|
312
|
+
}
|
|
313
|
+
return path.join(configDir(tool), 'policies', `${name}.yaml`);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function isRecord(v: unknown): v is Record<string, unknown> {
|
|
317
|
+
return typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function strList(v: unknown, what: string): string[] {
|
|
321
|
+
if (v === undefined || v === null) return [];
|
|
322
|
+
if (!Array.isArray(v) || v.some((x) => typeof x !== 'string')) {
|
|
323
|
+
throw new Error(`${what}: want a list of strings`);
|
|
324
|
+
}
|
|
325
|
+
return v as string[];
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function allowMap(v: unknown, what: string): Record<string, string[]> | undefined {
|
|
329
|
+
if (v === undefined || v === null) return undefined;
|
|
330
|
+
if (!isRecord(v)) throw new Error(`${what}: want a mapping of class to patterns`);
|
|
331
|
+
const out: Record<string, string[]> = {};
|
|
332
|
+
for (const [k, list] of Object.entries(v)) out[k] = strList(list, `${what}.${k}`);
|
|
333
|
+
return out;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function int(v: unknown, what: string): number {
|
|
337
|
+
if (v === undefined || v === null) return 0;
|
|
338
|
+
if (typeof v !== 'number' || !Number.isInteger(v)) throw new Error(`${what}: want an integer`);
|
|
339
|
+
return v;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** Shape-checks a `permissions:` block (names unique, effects allow|deny). */
|
|
343
|
+
export function validatePermissionRules(rules: readonly PermissionRule[]): void {
|
|
344
|
+
const seen = new Set<string>();
|
|
345
|
+
rules.forEach((r, i) => {
|
|
346
|
+
if (!r.name) throw new Error(`permissions[${i}]: name required`);
|
|
347
|
+
if (seen.has(r.name)) throw new Error(`permission rule ${JSON.stringify(r.name)}: duplicate name`);
|
|
348
|
+
seen.add(r.name);
|
|
349
|
+
if (!r.when) throw new Error(`permission rule ${JSON.stringify(r.name)}: 'when' required`);
|
|
350
|
+
for (const [field, value] of [
|
|
351
|
+
['effect', r.effect],
|
|
352
|
+
['otherwise', r.otherwise],
|
|
353
|
+
] as const) {
|
|
354
|
+
if (value === '' || value === undefined) {
|
|
355
|
+
throw new Error(`permission rule ${JSON.stringify(r.name)}: ${field} required (allow|deny)`);
|
|
356
|
+
}
|
|
357
|
+
if (value !== 'allow' && value !== 'deny') {
|
|
358
|
+
throw new Error(
|
|
359
|
+
`permission rule ${JSON.stringify(r.name)}: ${field} ${JSON.stringify(value)} invalid (want allow|deny)`,
|
|
360
|
+
);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
function parsePolicy(doc: unknown): Policy {
|
|
367
|
+
if (doc === null || doc === undefined) return emptyPolicy();
|
|
368
|
+
if (!isRecord(doc)) throw new Error('want a mapping at the top level');
|
|
369
|
+
const p = emptyPolicy();
|
|
370
|
+
if (doc['name'] !== undefined && doc['name'] !== null) {
|
|
371
|
+
if (typeof doc['name'] !== 'string') throw new Error('name: want a string');
|
|
372
|
+
p.name = doc['name'];
|
|
373
|
+
}
|
|
374
|
+
const allow = allowMap(doc['allow'], 'allow');
|
|
375
|
+
if (allow) p.allow = allow;
|
|
376
|
+
p.max_ops = int(doc['max_ops'], 'max_ops');
|
|
377
|
+
p.require_confirm = strList(doc['require_confirm'], 'require_confirm');
|
|
378
|
+
if (doc['unannotated'] !== undefined && doc['unannotated'] !== null) {
|
|
379
|
+
if (typeof doc['unannotated'] !== 'string') throw new Error('unannotated: want a string');
|
|
380
|
+
p.unannotated = doc['unannotated'];
|
|
381
|
+
}
|
|
382
|
+
const perms = doc['permissions'];
|
|
383
|
+
if (perms !== undefined && perms !== null) {
|
|
384
|
+
if (!Array.isArray(perms) || perms.some((r) => !isRecord(r))) {
|
|
385
|
+
throw new Error('permissions: want a list of rules');
|
|
386
|
+
}
|
|
387
|
+
p.permissions = perms.map((r) => {
|
|
388
|
+
const rec = r as Record<string, unknown>;
|
|
389
|
+
const s = (k: string): string => (typeof rec[k] === 'string' ? (rec[k] as string) : '');
|
|
390
|
+
return { name: s('name'), when: s('when'), effect: s('effect'), otherwise: s('otherwise'), message: s('message') };
|
|
391
|
+
});
|
|
392
|
+
validatePermissionRules(p.permissions);
|
|
393
|
+
}
|
|
394
|
+
const callers = doc['callers'];
|
|
395
|
+
if (callers !== undefined && callers !== null) {
|
|
396
|
+
if (!Array.isArray(callers) || callers.some((r) => !isRecord(r))) {
|
|
397
|
+
throw new Error('callers: want a list of rules');
|
|
398
|
+
}
|
|
399
|
+
p.callers = callers.map((r, i) => {
|
|
400
|
+
const rec = r as Record<string, unknown>;
|
|
401
|
+
const at = `callers[${i}]`;
|
|
402
|
+
const rule: CallerRule = {};
|
|
403
|
+
for (const k of ['principal', 'tenant', 'scope', 'window'] as const) {
|
|
404
|
+
if (rec[k] !== undefined && rec[k] !== null) {
|
|
405
|
+
if (typeof rec[k] !== 'string') throw new Error(`${at}.${k}: want a string`);
|
|
406
|
+
rule[k] = rec[k] as string;
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
const ra = allowMap(rec['allow'], `${at}.allow`);
|
|
410
|
+
if (ra) rule.allow = ra;
|
|
411
|
+
rule.max_ops = int(rec['max_ops'], `${at}.max_ops`);
|
|
412
|
+
rule.require_declared_scope = strList(rec['require_declared_scope'], `${at}.require_declared_scope`);
|
|
413
|
+
return rule;
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
validate(p);
|
|
417
|
+
return p;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function validate(p: Policy): void {
|
|
421
|
+
const errs: string[] = [];
|
|
422
|
+
if (p.unannotated && classOf(p.unannotated) === undefined) {
|
|
423
|
+
errs.push(`unannotated: unknown side-effect class ${JSON.stringify(p.unannotated)}`);
|
|
424
|
+
}
|
|
425
|
+
p.callers.forEach((r, i) => {
|
|
426
|
+
for (const c of Object.keys(r.allow ?? {})) {
|
|
427
|
+
if (classOf(c) === undefined) errs.push(`callers[${i}]: allow: unknown side-effect class ${JSON.stringify(c)}`);
|
|
428
|
+
}
|
|
429
|
+
for (const c of r.require_declared_scope ?? []) {
|
|
430
|
+
if (classOf(c) === undefined) {
|
|
431
|
+
errs.push(`callers[${i}]: require_declared_scope: unknown side-effect class ${JSON.stringify(c)}`);
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
if ((r.max_ops ?? 0) < 0) errs.push(`callers[${i}]: max_ops ${r.max_ops} is negative; 0 means no budget`);
|
|
435
|
+
});
|
|
436
|
+
if (errs.length > 0) throw new Error(errs.join('\n'));
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* Reads a YAML policy file. A missing `name:` defaults to the file stem so
|
|
441
|
+
* audit output has a handle.
|
|
442
|
+
*/
|
|
443
|
+
export function loadPolicy(file: string): Policy {
|
|
444
|
+
let data: string;
|
|
445
|
+
try {
|
|
446
|
+
data = fs.readFileSync(file, 'utf8');
|
|
447
|
+
} catch (e) {
|
|
448
|
+
throw new Error(`policy: load ${file}: ${(e as Error).message}`);
|
|
449
|
+
}
|
|
450
|
+
let p: Policy;
|
|
451
|
+
try {
|
|
452
|
+
p = parsePolicy(yaml.load(data));
|
|
453
|
+
} catch (e) {
|
|
454
|
+
throw new Error(`policy: parse ${file}: ${(e as Error).message}`);
|
|
455
|
+
}
|
|
456
|
+
if (p.name === '') p.name = path.basename(file).replace(/\.(yaml|yml)$/, '');
|
|
457
|
+
return p;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/**
|
|
461
|
+
* Resolves and loads a named policy. {@link KIT_DEFAULT_NAME} is reserved:
|
|
462
|
+
* it always returns {@link kitDefault} and no file is read.
|
|
463
|
+
*/
|
|
464
|
+
export function loadNamedPolicy(tool: string, name: string): Policy {
|
|
465
|
+
if (name === KIT_DEFAULT_NAME) return kitDefault();
|
|
466
|
+
return loadPolicy(resolvePolicyPath(tool, name));
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/** A loader resolving names against `$XDG_CONFIG_HOME/<tool>/policies/`. */
|
|
470
|
+
export function defaultPolicyLoader(tool: string): PolicyLoader {
|
|
471
|
+
return (name) => loadNamedPolicy(tool, name);
|
|
472
|
+
}
|