@hop-top/kit 0.5.0-alpha.10 → 0.5.0-alpha.12
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 +42 -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-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-P3Y46PYF.js +138 -0
- 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/chunk-X4E5QGEB.js +171 -0
- 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/id/index.d.ts +1 -1
- package/dist/id/index.js +4 -2
- package/dist/{index-DCe1boBz.d.ts → index-CGE5yLBj.d.ts} +1 -1
- package/dist/{index-VLDcI5NF.d.ts → index-D9zpUrpE.d.ts} +18 -6
- package/dist/index.d.ts +4 -4
- package/dist/index.js +23 -23
- 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-BJ2z6Oqf.d.ts} +58 -4
- package/dist/upgrade.d.ts +1 -1
- package/dist/upgrade.js +4 -2
- package/package.json +9 -9
- 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/id/README.md +2 -2
- package/src/id/contract.test.ts +11 -8
- package/src/id/differential.test.ts +54 -0
- package/src/id/index.ts +123 -17
- 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 +393 -1
- package/src/upgrade.ts +183 -25
- package/dist/chunk-GHPJJV5L.js +0 -613
- package/dist/chunk-IXVQ62NZ.js +0 -334
- package/dist/chunk-L23O2FFE.js +0 -51
- package/dist/chunk-WWUKGJB5.js +0 -90
- package/dist/cli-C5B5tnpA.d.ts +0 -400
- package/dist/{chunk-PSFYJGDG.js → chunk-K7E34Q3A.js} +2 -2
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
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module sideeffect
|
|
3
|
+
* @package @hop-top/kit
|
|
4
|
+
*
|
|
5
|
+
* The `kit/side-effect` vocabulary and the one name-inference table every
|
|
6
|
+
* kit gate and projection reads. Mirrors Go's `cli.SideEffect` tiers and
|
|
7
|
+
* `cmdmeta.InferredDestructive`.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** Annotation key a command declares its side-effect tier under. */
|
|
11
|
+
export const SIDE_EFFECT_ANNOTATION = 'kit/side-effect';
|
|
12
|
+
|
|
13
|
+
/** The closed set of declarable tiers (legacy 4-tier plus the 6-tier ladder). */
|
|
14
|
+
export const SIDE_EFFECT_TIERS = [
|
|
15
|
+
'read',
|
|
16
|
+
'write',
|
|
17
|
+
'write-local',
|
|
18
|
+
'write-shared',
|
|
19
|
+
'destructive',
|
|
20
|
+
'destructive-local',
|
|
21
|
+
'destructive-shared',
|
|
22
|
+
'interactive',
|
|
23
|
+
] as const;
|
|
24
|
+
|
|
25
|
+
export type SideEffect = (typeof SIDE_EFFECT_TIERS)[number];
|
|
26
|
+
|
|
27
|
+
/** The tier an unannotated command with a destructive leaf name is gated as. */
|
|
28
|
+
export const INFERRED_TIER: SideEffect = 'destructive-shared';
|
|
29
|
+
|
|
30
|
+
const WRITE_LIKE = new Set<string>(['write', 'write-local', 'write-shared']);
|
|
31
|
+
const DESTRUCTIVE_LIKE = new Set<string>([
|
|
32
|
+
'destructive',
|
|
33
|
+
'destructive-local',
|
|
34
|
+
'destructive-shared',
|
|
35
|
+
]);
|
|
36
|
+
|
|
37
|
+
/** True for any tier that mutates state without irreversible loss. */
|
|
38
|
+
export function isWriteLike(tier: string): boolean {
|
|
39
|
+
return WRITE_LIKE.has(tier);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** True for any tier that performs an irreversible mutation. */
|
|
43
|
+
export function isDestructiveLike(tier: string): boolean {
|
|
44
|
+
return DESTRUCTIVE_LIKE.has(tier);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** True when `tier` names a declarable side-effect tier. */
|
|
48
|
+
export function isValidSideEffect(tier: string): boolean {
|
|
49
|
+
return (SIDE_EFFECT_TIERS as readonly string[]).includes(tier);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The one table of leaf names kit treats as destructive when a command
|
|
54
|
+
* carries no `kit/side-effect` annotation. Every gate and projection in
|
|
55
|
+
* this SDK reads it through {@link isDestructiveName} or
|
|
56
|
+
* {@link inferredDestructive}; none keeps its own copy.
|
|
57
|
+
*/
|
|
58
|
+
const DESTRUCTIVE_NAMES: ReadonlySet<string> = new Set([
|
|
59
|
+
'delete',
|
|
60
|
+
'remove',
|
|
61
|
+
'rm',
|
|
62
|
+
'destroy',
|
|
63
|
+
'purge',
|
|
64
|
+
'drop',
|
|
65
|
+
]);
|
|
66
|
+
|
|
67
|
+
/** True when `name` is in the destructive-name table. */
|
|
68
|
+
export function isDestructiveName(name: string): boolean {
|
|
69
|
+
return DESTRUCTIVE_NAMES.has(name);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The table's names, sorted. */
|
|
73
|
+
export function destructiveNames(): string[] {
|
|
74
|
+
return [...DESTRUCTIVE_NAMES].sort();
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* True when a command is destructive by name alone: its annotation is
|
|
79
|
+
* absent or empty and its leaf name is in the table. An explicit
|
|
80
|
+
* annotation, valid or not, always wins: a malformed value is a
|
|
81
|
+
* declaration defect, never inferred over.
|
|
82
|
+
*/
|
|
83
|
+
export function inferredDestructive(
|
|
84
|
+
name: string,
|
|
85
|
+
annotations: Readonly<Record<string, string>> | undefined,
|
|
86
|
+
): boolean {
|
|
87
|
+
const declared = annotations?.[SIDE_EFFECT_ANNOTATION];
|
|
88
|
+
if (declared !== undefined && declared !== '') return false;
|
|
89
|
+
return isDestructiveName(name);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* The tier the delegation gates act on: the declared `kit/side-effect`,
|
|
94
|
+
* else {@link INFERRED_TIER} for a destructive-named command. Undefined
|
|
95
|
+
* when neither says anything. A declared value, valid or malformed, is
|
|
96
|
+
* never replaced.
|
|
97
|
+
*/
|
|
98
|
+
export function gateSideEffect(
|
|
99
|
+
name: string,
|
|
100
|
+
annotations: Readonly<Record<string, string>> | undefined,
|
|
101
|
+
): string | undefined {
|
|
102
|
+
if (inferredDestructive(name, annotations)) return INFERRED_TIER;
|
|
103
|
+
const declared = annotations?.[SIDE_EFFECT_ANNOTATION];
|
|
104
|
+
return declared === undefined ? undefined : declared;
|
|
105
|
+
}
|
package/src/toolspec-manifest.ts
CHANGED
|
@@ -26,6 +26,7 @@ import {
|
|
|
26
26
|
walkCommands,
|
|
27
27
|
type Annotations,
|
|
28
28
|
} from "./toolspec-internal.js";
|
|
29
|
+
import { inferredDestructive } from "./sideeffect.js";
|
|
29
30
|
|
|
30
31
|
/** Env var a harness sets to request a manifest schema version. */
|
|
31
32
|
export const SCHEMA_VERSION_ENV = "KIT_TOOLSPEC_SCHEMA";
|
|
@@ -233,13 +234,17 @@ const DRY_RUN_SIDE_EFFECTS = new Set([
|
|
|
233
234
|
"destructive-shared",
|
|
234
235
|
]);
|
|
235
236
|
|
|
236
|
-
|
|
237
|
+
// Go cmdmeta.IsDryRunSupported: an explicit kit/dry-run wins, then an
|
|
238
|
+
// unannotated destructive-named leaf (inferred destructive) is supported,
|
|
239
|
+
// then the declared side-effect tier decides.
|
|
240
|
+
function dryRunSupported(name: string, ann: Annotations): boolean {
|
|
237
241
|
switch (ann["kit/dry-run"]) {
|
|
238
242
|
case "opted-out":
|
|
239
243
|
return false;
|
|
240
244
|
case "supported":
|
|
241
245
|
return true;
|
|
242
246
|
}
|
|
247
|
+
if (inferredDestructive(name, ann)) return true;
|
|
243
248
|
return DRY_RUN_SIDE_EFFECTS.has(ann["kit/side-effect"] ?? "");
|
|
244
249
|
}
|
|
245
250
|
|
|
@@ -362,7 +367,7 @@ function manifestCommand(
|
|
|
362
367
|
if (ann["kit/passthrough"] === "true") out.passthrough = true;
|
|
363
368
|
const token = ann["kit/destructive-token"];
|
|
364
369
|
if (token === "required" || token === "true") out.destructive_token_required = true;
|
|
365
|
-
out.dry_run_supported = dryRunSupported(ann);
|
|
370
|
+
out.dry_run_supported = dryRunSupported(cmd.name(), ann);
|
|
366
371
|
if (ann["kit/dry-run-rationale"]) out.dry_run_rationale = ann["kit/dry-run-rationale"];
|
|
367
372
|
if (reserved) out.reserved = true;
|
|
368
373
|
if (hidden) out.hidden = true;
|