hmcp-core 0.0.1 → 0.1.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.
Files changed (76) hide show
  1. package/README.md +19 -3
  2. package/dist/approvals.d.ts +508 -0
  3. package/dist/approvals.js +1445 -0
  4. package/dist/argpath.d.ts +75 -0
  5. package/dist/argpath.js +189 -0
  6. package/dist/audit.d.ts +289 -0
  7. package/dist/audit.js +512 -0
  8. package/dist/canonical.d.ts +78 -0
  9. package/dist/canonical.js +146 -0
  10. package/dist/classify-held.d.ts +47 -0
  11. package/dist/classify-held.js +60 -0
  12. package/dist/classify-name.d.ts +55 -0
  13. package/dist/classify-name.js +255 -0
  14. package/dist/decide.d.ts +168 -0
  15. package/dist/decide.js +518 -0
  16. package/dist/egress.d.ts +123 -0
  17. package/dist/egress.js +544 -0
  18. package/dist/enforce.d.ts +78 -0
  19. package/dist/enforce.js +231 -0
  20. package/dist/exposure-apply.d.ts +51 -0
  21. package/dist/exposure-apply.js +69 -0
  22. package/dist/exposure.d.ts +81 -0
  23. package/dist/exposure.js +65 -0
  24. package/dist/file-lock.d.ts +70 -0
  25. package/dist/file-lock.js +165 -0
  26. package/dist/glob.d.ts +11 -0
  27. package/dist/glob.js +55 -0
  28. package/dist/grants.d.ts +204 -0
  29. package/dist/grants.js +372 -0
  30. package/dist/http-util.d.ts +52 -0
  31. package/dist/http-util.js +81 -0
  32. package/dist/index.d.ts +35 -0
  33. package/dist/index.js +36 -0
  34. package/dist/inventory.d.ts +100 -0
  35. package/dist/inventory.js +88 -0
  36. package/dist/ip.d.ts +15 -0
  37. package/dist/ip.js +186 -0
  38. package/dist/jwt.d.ts +57 -0
  39. package/dist/jwt.js +199 -0
  40. package/dist/live-state.d.ts +76 -0
  41. package/dist/live-state.js +57 -0
  42. package/dist/migrate.d.ts +22 -0
  43. package/dist/migrate.js +318 -0
  44. package/dist/pins.d.ts +119 -0
  45. package/dist/pins.js +125 -0
  46. package/dist/policy-batch.d.ts +89 -0
  47. package/dist/policy-batch.js +340 -0
  48. package/dist/policy-source.d.ts +161 -0
  49. package/dist/policy-source.js +299 -0
  50. package/dist/policy-write.d.ts +627 -0
  51. package/dist/policy-write.js +1697 -0
  52. package/dist/policy.d.ts +456 -0
  53. package/dist/policy.js +448 -0
  54. package/dist/redact.d.ts +65 -0
  55. package/dist/redact.js +191 -0
  56. package/dist/registry.d.ts +41 -0
  57. package/dist/registry.js +121 -0
  58. package/dist/remember-defaults.d.ts +9 -0
  59. package/dist/remember-defaults.js +9 -0
  60. package/dist/remember.d.ts +91 -0
  61. package/dist/remember.js +371 -0
  62. package/dist/resolve.d.ts +22 -0
  63. package/dist/resolve.js +34 -0
  64. package/dist/runtime-state.d.ts +65 -0
  65. package/dist/runtime-state.js +35 -0
  66. package/dist/secrets.d.ts +159 -0
  67. package/dist/secrets.js +361 -0
  68. package/dist/tenant.d.ts +83 -0
  69. package/dist/tenant.js +182 -0
  70. package/dist/unicode.d.ts +40 -0
  71. package/dist/unicode.js +103 -0
  72. package/dist/within-host.d.ts +33 -0
  73. package/dist/within-host.js +91 -0
  74. package/dist/within-real.d.ts +7 -0
  75. package/dist/within-real.js +28 -0
  76. package/package.json +33 -4
package/dist/policy.js ADDED
@@ -0,0 +1,448 @@
1
+ import { z } from "zod";
2
+ import { parse as parseYaml } from "yaml";
3
+ import { readFileSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { resolve, isAbsolute } from "node:path";
6
+ import { parseArgPath } from "./argpath.js";
7
+ /**
8
+ * What a tool does to the world. Classification drives every default: a tool
9
+ * with no effect is unclassified and therefore denied.
10
+ */
11
+ export const EffectSchema = z.enum(["read", "write", "destructive"]);
12
+ export const DecisionKindSchema = z.enum(["allow", "approve", "deny"]);
13
+ /**
14
+ * Default posture when no rule matches. `read-only` is the shipped default:
15
+ * reads pass, anything that mutates is refused outright.
16
+ */
17
+ export const PostureSchema = z.enum(["read-only", "approve-writes", "locked"]);
18
+ /**
19
+ * Bounds on a single argument, checked before a rule's decision is honored.
20
+ *
21
+ * The key a constraint is written under is an argument *path*, so a bound can
22
+ * reach a nested or repeated value: `amount`, `transfer.amount`, `items[].qty`.
23
+ * See `argpath.ts`.
24
+ *
25
+ * A constraint that bounds a value also requires that value to be *present*.
26
+ * An absent argument used to satisfy every bound written about it, which meant
27
+ * `amount: { max: 500 }` was satisfied by a call that simply omitted `amount`
28
+ * and let the upstream apply its own default -- the unbounded value the bound
29
+ * existed to prevent. `optional: true` restores that leniency where a tool
30
+ * genuinely has a safe default. A path that fans out is exempt: having no
31
+ * elements to bound is not an absence, and `maxItems` is how a count is
32
+ * bounded.
33
+ */
34
+ /**
35
+ * What happens to what a tool returns.
36
+ *
37
+ * The scan on a tool's *description* protects against the server. This
38
+ * protects against what the server was asked to fetch: an issue body, a web
39
+ * page, a row someone else can write to. The server can be behaving
40
+ * perfectly.
41
+ *
42
+ * `label` is the default for injected text because a result is data the agent
43
+ * asked for: replacing it would break the call, and telling the model where
44
+ * the text came from is the honest minimum. `quarantine` withholds the
45
+ * content and says why, for a deployment that would rather lose a result than
46
+ * pass one on.
47
+ *
48
+ * A secret found in a result is `warn` by default: recorded, and the result
49
+ * passed on. By the time it is seen the value has already been through this
50
+ * process, so withholding it protects the transcript and not the secret --
51
+ * worth choosing deliberately rather than by default.
52
+ */
53
+ export const ResultScanConfigSchema = z
54
+ .object({
55
+ on_injection: z.enum(["allow", "label", "quarantine"]).default("label"),
56
+ on_secret: z.enum(["allow", "warn", "quarantine"]).default("warn")
57
+ })
58
+ .strict();
59
+ /** One directory a `within` bound admits. */
60
+ const WithinPath = z
61
+ .string()
62
+ .min(1)
63
+ .refine((v) => v.startsWith("/") || /^[a-zA-Z]:[\\/]/.test(v), {
64
+ message: "within must be an absolute path: a gateway is started from whatever directory its client " +
65
+ "happens to be in, so a relative bound would mean somewhere different on every machine"
66
+ });
67
+ export const ArgConstraintSchema = z
68
+ .object({
69
+ max: z.number().optional(),
70
+ min: z.number().optional(),
71
+ enum: z.array(z.union([z.string(), z.number(), z.boolean()])).optional(),
72
+ pattern: z.string().optional(),
73
+ /** String length, or array length. `maxItems` is the unambiguous spelling. */
74
+ maxLength: z.number().int().positive().optional(),
75
+ /** Length of an array. */
76
+ maxItems: z.number().int().nonnegative().optional(),
77
+ /**
78
+ * Ceiling on the total across every match of a fanned-out path. Without
79
+ * it, `items[].qty: { max: 10 }` is satisfied by a thousand items of ten.
80
+ */
81
+ sum_max: z.number().optional(),
82
+ /** Ceiling on how many places a fanned-out path matched. */
83
+ count_max: z.number().int().nonnegative().optional(),
84
+ /**
85
+ * The value must be a path under this directory, or under one of these
86
+ * directories. Compared after resolution, so `..` cannot climb out and a
87
+ * sibling that merely starts with the same letters is not admitted. Where
88
+ * the gateway runs (Node), both sides are compared as real paths: a folder
89
+ * reached through a symlink is the same folder under either spelling, and
90
+ * a symlink inside the directory that points out of it is outside.
91
+ */
92
+ within: z.union([WithinPath, z.array(WithinPath).nonempty()]).optional(),
93
+ /**
94
+ * The value must be an http or https URL whose host is one of these. An
95
+ * entry beginning with a dot (`.example.com`) means the domain and every
96
+ * host under it.
97
+ */
98
+ host: z.array(z.string().min(1)).nonempty().optional(),
99
+ required: z.boolean().optional(),
100
+ /** Absence satisfies this constraint. */
101
+ optional: z.boolean().optional(),
102
+ /**
103
+ * Accept a value that is not a number for `min`/`max` by converting it.
104
+ * Off by default: `Number("500")`, `Number(true)` and `Number([500])` all
105
+ * produce a number that satisfies a bound while the upstream may parse the
106
+ * value as something else entirely.
107
+ */
108
+ coerce: z.boolean().optional(),
109
+ /** `null` pins an argument that was sent as null (a remembered approval). */
110
+ const: z.union([z.string(), z.number(), z.boolean(), z.null()]).optional(),
111
+ /**
112
+ * The list must hold exactly these items (a remembered approval). Each
113
+ * item is compared whole -- the same keys, values and types -- and each
114
+ * approved item counts once per time it was approved, so items cannot be
115
+ * re-paired, repeated or left out. A list of objects or lists may come in
116
+ * any order; a list holding plain values (`["cp", "a", "b"]`) is
117
+ * positional and must keep its order. See `sameItems` in decide.ts.
118
+ */
119
+ same_items: z.array(z.unknown()).optional()
120
+ })
121
+ .strict();
122
+ export const RuleSchema = z
123
+ .object({
124
+ /** Stable identifier recorded in the audit log for every decision. */
125
+ id: z.string().min(1),
126
+ /** Glob over the agent-facing tool name. */
127
+ match: z.string().min(1),
128
+ /** Reclassifies the tool's effect when set. */
129
+ effect: EffectSchema.optional(),
130
+ decision: DecisionKindSchema,
131
+ /** Bounds, keyed by argument path. See `ArgConstraintSchema`. */
132
+ args: z.record(z.string(), ArgConstraintSchema).optional(),
133
+ /**
134
+ * What an out-of-bounds call gets. `deny` refuses it outright; `approve`
135
+ * holds it for a human, bound to those exact arguments and single-use.
136
+ *
137
+ * `deny` is the default because it is what this rule has always meant, so
138
+ * no policy already written changes behaviour on upgrade. A rule that
139
+ * wants the middle state -- inside the bounds it runs, outside them a human
140
+ * decides -- says so.
141
+ */
142
+ on_violation: DecisionKindSchema.exclude(["allow"]).default("deny"),
143
+ /**
144
+ * What to do with an argument no constraint in `args` claims. `allow`
145
+ * leaves it unbounded, which is an open world: `amount` bounded while
146
+ * `amount_cents` or `force: true` passes freely. Defaults to `allow` so an
147
+ * existing policy is unchanged; new policies should set `deny`.
148
+ */
149
+ unknown_args: z.enum(["allow", "deny", "approve"]).default("allow"),
150
+ reason: z.string().optional()
151
+ })
152
+ .strict();
153
+ /**
154
+ * A tenant read out of a signature-verified bearer token.
155
+ *
156
+ * The only source kind safe to use when the token arrives per request from
157
+ * the caller, which is the hosted-gateway case. The others take their value
158
+ * from the deployment -- an env var, a static string, a credential the
159
+ * operator placed -- and are trustworthy precisely because nothing the caller
160
+ * controls reaches them.
161
+ *
162
+ * Kept separate from `jwt-claim` rather than added to it as a flag. There is
163
+ * no setting here that turns verification off, and `jwt-claim` keeps meaning
164
+ * what it has always meant instead of quietly becoming unsafe.
165
+ */
166
+ export const JwtVerifiedSourceSchema = z
167
+ .object({
168
+ kind: z.literal("jwt-verified"),
169
+ /** The claim carrying the tenant, e.g. "org_id". */
170
+ claim: z.string().min(1),
171
+ /** Where to fetch the signing keys. Dialled through the egress guard. */
172
+ jwks_uri: z.string().url().optional(),
173
+ /** A pinned PEM public key, for a deployment with no JWKS endpoint. */
174
+ public_key: z.string().min(1).optional(),
175
+ /** Both required: a token valid for somewhere else is not valid here. */
176
+ issuer: z.string().min(1),
177
+ audience: z.string().min(1),
178
+ /** Header carrying the token. */
179
+ header_name: z.string().min(1).default("authorization")
180
+ })
181
+ .strict()
182
+ .refine((v) => (v.jwks_uri === undefined) !== (v.public_key === undefined), {
183
+ message: "exactly one of tenant.source.jwks_uri or tenant.source.public_key is required"
184
+ });
185
+ /**
186
+ * Who may change this deployment's configuration through an API.
187
+ *
188
+ * Deliberately its own block rather than a field on `tenant.source`.
189
+ * `tenant.source` answers "which customer is this", which is a tenancy
190
+ * question; this answers "may they flip a switch", which is an authorization
191
+ * one. Folding them together would also make an admin surface appear the
192
+ * moment anyone configured JWT tenancy, and the common case is multi-tenant
193
+ * hosting with no admin surface at all.
194
+ *
195
+ * One field on purpose. A list of privileged subjects here would be
196
+ * operational state wearing the clothes of reviewed policy.
197
+ */
198
+ export const AdminConfigSchema = z
199
+ .object({
200
+ /**
201
+ * The scope a token must carry, compared with exact string equality.
202
+ *
203
+ * Pick one only this deployment's authorization server grants. A scope
204
+ * some other resource server hands out would otherwise let its tokens
205
+ * administer this one — `aud` is verified too, which limits the damage,
206
+ * but the rule should not have to lean on that.
207
+ */
208
+ scope: z.string().min(1)
209
+ })
210
+ .strict();
211
+ export const TenantSourceSchema = z.union([
212
+ z.object({ kind: z.literal("env"), name: z.string().min(1) }).strict(),
213
+ z.object({ kind: z.literal("header"), name: z.string().min(1) }).strict(),
214
+ z.object({ kind: z.literal("jwt-claim"), name: z.string().min(1), token_env: z.string().min(1) }).strict(),
215
+ z.object({ kind: z.literal("static"), value: z.string().min(1) }).strict(),
216
+ JwtVerifiedSourceSchema
217
+ ]);
218
+ export const TenantConfigSchema = z
219
+ .object({
220
+ /** Canonical parameter name, e.g. `org_id`. */
221
+ field: z.string().min(1),
222
+ /** Other spellings the same identifier appears under. */
223
+ aliases: z.array(z.string().min(1)).default([]),
224
+ source: TenantSourceSchema,
225
+ /** Where the value is injected into the upstream request. */
226
+ inject: z.array(z.enum(["path", "query", "body", "header"])).default(["path", "query", "body"]),
227
+ /** Header name when `inject` includes "header". */
228
+ header_name: z.string().optional(),
229
+ /**
230
+ * What to do when the agent supplies a tenant value that differs from the
231
+ * one bound to the credential. `deny` refuses the call; `override` silently
232
+ * replaces it. `deny` is the default because a mismatch is a signal.
233
+ */
234
+ on_mismatch: z.enum(["deny", "override"]).default("deny"),
235
+ /** Refuse to start when the source yields no value. */
236
+ required: z.boolean().default(true)
237
+ })
238
+ .strict();
239
+ export const EgressConfigSchema = z
240
+ .object({
241
+ /** Hostnames, optionally `*.` prefixed and optionally `:port` suffixed. */
242
+ allow: z.array(z.string().min(1)).default([]),
243
+ methods: z.array(z.string().min(1)).default(["GET", "HEAD"]),
244
+ max_body_bytes: z.number().int().positive().default(1_048_576),
245
+ max_request_body_bytes: z.number().int().positive().default(262_144),
246
+ timeout_ms: z.number().int().positive().default(10_000),
247
+ max_redirects: z.number().int().min(0).default(0),
248
+ /** Refuse targets that resolve to loopback, link-local or RFC1918 space. */
249
+ block_private_ips: z.boolean().default(true),
250
+ /** Permit plaintext HTTP. Off by default. */
251
+ allow_http: z.boolean().default(false),
252
+ /** Permit bare IP literals as targets. Off by default. */
253
+ allow_ip_literals: z.boolean().default(false)
254
+ })
255
+ .strict();
256
+ export const ApprovalsConfigSchema = z
257
+ .object({
258
+ /**
259
+ * `elicit` asks the MCP host; `cli` parks the request for out-of-band
260
+ * review; `both` tries elicitation and falls back to the CLI, which is the
261
+ * only option that works across clients with and without the capability.
262
+ */
263
+ mode: z.enum(["elicit", "cli", "both", "deny"]).default("both"),
264
+ ttl_seconds: z.number().int().positive().default(300),
265
+ /** A grant releases exactly one call. */
266
+ single_use: z.boolean().default(true),
267
+ /**
268
+ * How long a held call stays open waiting for a person to decide in the
269
+ * console, before it is handed back as "waiting for approval". 0 hands it
270
+ * back at once. Kept under a minute, because AI apps give up on a tool
271
+ * call that takes longer than that; a decision made after it is still
272
+ * picked up by the AI's retry of the same call.
273
+ */
274
+ wait_seconds: z.number().int().min(0).max(55).default(0),
275
+ store_path: z.string().default("~/.hmcp/approvals.sqlite")
276
+ })
277
+ .strict();
278
+ export const AuditConfigSchema = z
279
+ .object({
280
+ enabled: z.boolean().default(true),
281
+ path: z.string().default("~/.hmcp/audit.jsonl"),
282
+ /** Tamper-evident chaining. Disabling it is a scanner finding. */
283
+ hash_chain: z.boolean().default(true),
284
+ /** Extra argument names to redact beyond the built-in denylist. */
285
+ redact: z.array(z.string().min(1)).default([]),
286
+ /** Record redacted arguments alongside their hash. */
287
+ record_args: z.boolean().default(true),
288
+ /**
289
+ * What happens to a call policy *permits* when the log cannot take its
290
+ * record: `refuse` does not run it, `continue` runs it unrecorded.
291
+ *
292
+ * `refuse` is the default because "every decision is recorded" is
293
+ * otherwise only true while the disk is healthy. A refusal is never
294
+ * affected either way -- a broken log must not become a way to switch
295
+ * enforcement off.
296
+ */
297
+ on_failure: z.enum(["refuse", "continue"]).default("refuse")
298
+ })
299
+ .strict();
300
+ export const DefaultsSchema = z
301
+ .object({
302
+ mode: PostureSchema.default("read-only"),
303
+ /** Tools whose effect is unknown. Denying is the whole point. */
304
+ on_unclassified: z.enum(["deny", "approve"]).default("deny")
305
+ })
306
+ .strict();
307
+ export const PolicySchema = z
308
+ .object({
309
+ version: z.literal(1),
310
+ name: z.string().optional(),
311
+ /**
312
+ * Whether this policy is applied or only reported.
313
+ *
314
+ * `enforce` is what the rest of this file describes. Under `observe` every
315
+ * call runs, and the audit record of it says what the policy would have
316
+ * decided: the way to put a gateway in front of real work without breaking
317
+ * it, and learn what the agent does before choosing what to allow.
318
+ *
319
+ * Observe mode protects nothing, with one exception: a tool an operator
320
+ * has switched off stays off. It is never the default, so a file that does
321
+ * not ask for it is enforced.
322
+ */
323
+ enforcement: z.enum(["enforce", "observe"]).default("enforce"),
324
+ /**
325
+ * What happens when a tool's advertised contract has changed since this
326
+ * gateway last looked: its description, its schema, its annotations or
327
+ * what it classifies as.
328
+ *
329
+ * `warn` records the finding and goes on serving the tool. It is the
330
+ * default because an upstream rewording its own description is the common
331
+ * case by far, and a gateway that withheld a tool every time its server
332
+ * was upgraded is a gateway people turn off -- which protects nothing at
333
+ * all. The finding is in the audit log, in `status` and in the console.
334
+ *
335
+ * `deny` withholds the tool until someone accepts the change
336
+ * (`hmcp-gateway pin accept <tool>`). That is the right setting wherever
337
+ * the tool list is supposed to be stable, and the wrong one on a laptop
338
+ * that updates its servers weekly.
339
+ */
340
+ on_tool_change: z.enum(["warn", "deny"]).default("warn"),
341
+ results: ResultScanConfigSchema.default(() => ResultScanConfigSchema.parse({})),
342
+ defaults: DefaultsSchema.default(() => DefaultsSchema.parse({})),
343
+ rules: z.array(RuleSchema).default([]),
344
+ tenant: TenantConfigSchema.optional(),
345
+ admin: AdminConfigSchema.optional(),
346
+ egress: EgressConfigSchema.default(() => EgressConfigSchema.parse({})),
347
+ approvals: ApprovalsConfigSchema.default(() => ApprovalsConfigSchema.parse({})),
348
+ audit: AuditConfigSchema.default(() => AuditConfigSchema.parse({})),
349
+ /** Cap on how many tools may be exposed at once. */
350
+ tool_budget: z.number().int().positive().default(40)
351
+ })
352
+ .strict()
353
+ .superRefine((policy, ctx) => {
354
+ const seen = new Set();
355
+ policy.rules.forEach((rule, i) => {
356
+ if (seen.has(rule.id)) {
357
+ ctx.addIssue({
358
+ code: "custom",
359
+ path: ["rules", i, "id"],
360
+ message: `duplicate rule id "${rule.id}" - ids appear in the audit log and must be unique`
361
+ });
362
+ }
363
+ seen.add(rule.id);
364
+ if (rule.args) {
365
+ for (const [arg, c] of Object.entries(rule.args)) {
366
+ // An unwritable path is a startup failure, not a silent no-match
367
+ // that would read as a satisfied bound.
368
+ const parsed = parseArgPath(arg);
369
+ if (!parsed.ok) {
370
+ ctx.addIssue({
371
+ code: "custom",
372
+ path: ["rules", i, "args", arg],
373
+ message: `not a usable argument path: ${parsed.error}`
374
+ });
375
+ }
376
+ if (c.pattern) {
377
+ try {
378
+ new RegExp(c.pattern);
379
+ }
380
+ catch {
381
+ ctx.addIssue({
382
+ code: "custom",
383
+ path: ["rules", i, "args", arg, "pattern"],
384
+ message: `invalid regular expression: ${c.pattern}`
385
+ });
386
+ }
387
+ }
388
+ if (c.required && c.optional) {
389
+ ctx.addIssue({
390
+ code: "custom",
391
+ path: ["rules", i, "args", arg],
392
+ message: "required and optional cannot both be set"
393
+ });
394
+ }
395
+ }
396
+ }
397
+ });
398
+ if (policy.tenant?.inject.includes("header") && !policy.tenant.header_name) {
399
+ ctx.addIssue({
400
+ code: "custom",
401
+ path: ["tenant", "header_name"],
402
+ message: 'tenant.header_name is required when inject includes "header"'
403
+ });
404
+ }
405
+ });
406
+ /** Expands a leading `~` and resolves against `base`. */
407
+ export function expandPath(p, base = process.cwd()) {
408
+ const expanded = p.startsWith("~/") || p === "~" ? resolve(homedir(), p.slice(1).replace(/^\//, "")) : p;
409
+ return isAbsolute(expanded) ? expanded : resolve(base, expanded);
410
+ }
411
+ export class PolicyError extends Error {
412
+ issues;
413
+ constructor(message, issues) {
414
+ super(message);
415
+ this.issues = issues;
416
+ this.name = "PolicyError";
417
+ }
418
+ }
419
+ export function parsePolicy(raw, source = "<inline>") {
420
+ const result = PolicySchema.safeParse(raw);
421
+ if (!result.success) {
422
+ const issues = result.error.issues.map((i) => ({
423
+ path: i.path.join("."),
424
+ message: i.message
425
+ }));
426
+ const detail = issues.map((i) => ` ${i.path || "(root)"}: ${i.message}`).join("\n");
427
+ throw new PolicyError(`invalid policy in ${source}:\n${detail}`, issues);
428
+ }
429
+ return result.data;
430
+ }
431
+ export function loadPolicy(path) {
432
+ const full = expandPath(path);
433
+ let text;
434
+ try {
435
+ text = readFileSync(full, "utf8");
436
+ }
437
+ catch (err) {
438
+ throw new PolicyError(`cannot read policy at ${full}: ${err.message}`);
439
+ }
440
+ return parsePolicy(parseYaml(text), full);
441
+ }
442
+ /**
443
+ * The posture this project ships: reads allowed, writes and deletes refused,
444
+ * nothing leaves the machine, everything logged.
445
+ */
446
+ export function defaultPolicy() {
447
+ return parsePolicy({ version: 1, name: "default-read-only" });
448
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Redaction runs before anything is written to the audit log or shown in an
3
+ * approval prompt. The same patterns back scanner rule HMCP004, which looks for
4
+ * secrets that leaked into an API spec.
5
+ */
6
+ /** Argument/field names whose values are never recorded. */
7
+ export declare const SECRET_KEY_PATTERN: RegExp;
8
+ /** True when an argument or field name says its value is a secret. */
9
+ export declare function isSecretKeyName(key: string): boolean;
10
+ export interface SecretPattern {
11
+ readonly id: string;
12
+ readonly label: string;
13
+ readonly regex: RegExp;
14
+ }
15
+ /**
16
+ * Value shapes that are secrets regardless of the key they sit under. Ordered
17
+ * most-specific first so the reported label is the useful one.
18
+ */
19
+ export declare const SECRET_VALUE_PATTERNS: readonly SecretPattern[];
20
+ export interface SecretHit {
21
+ readonly patternId: string;
22
+ readonly label: string;
23
+ readonly match: string;
24
+ }
25
+ /** Finds secret-shaped substrings. Used by the scanner; returns [] for clean text. */
26
+ export declare function findSecrets(text: string): SecretHit[];
27
+ export interface RedactOptions {
28
+ /** Extra key names (exact, case-insensitive) to redact. */
29
+ readonly extraKeys?: readonly string[];
30
+ /** Strings longer than this are truncated. */
31
+ readonly maxStringLength?: number;
32
+ /** Depth beyond which subtrees collapse to a marker. */
33
+ readonly maxDepth?: number;
34
+ /** Arrays longer than this are truncated. */
35
+ readonly maxArrayLength?: number;
36
+ }
37
+ /**
38
+ * Deep copy with secrets removed. Never mutates the input, tolerates cycles,
39
+ * and always returns something JSON-serializable - it sits on the path to the
40
+ * audit log, so it must not be able to throw.
41
+ */
42
+ export declare function redact(value: unknown, options?: RedactOptions): unknown;
43
+ /** Convenience wrapper for argument objects. */
44
+ export declare function redactArgs(args: Record<string, unknown> | undefined, extraKeys?: readonly string[]): Record<string, unknown>;
45
+ export interface RedactTextOptions {
46
+ /** The call's arguments: values under a secret key are removed wherever they are quoted. */
47
+ readonly args?: unknown;
48
+ /** Extra key names (exact, case-insensitive) whose values are secret. */
49
+ readonly extraKeys?: readonly string[];
50
+ readonly maxLength?: number;
51
+ }
52
+ /**
53
+ * Redacts free text that was written by someone else and may quote a secret.
54
+ *
55
+ * `redact` works on structure: it knows which key a value sits under. An
56
+ * error message has no structure, and the commonest way one leaks is an
57
+ * upstream's validation error that quotes the value it rejected -- the same
58
+ * value `redactArgs` has just removed from the field beside it. So this takes
59
+ * the arguments too, and blanks the value of every secret-named argument
60
+ * wherever it is quoted, before looking for anything secret-*shaped*.
61
+ *
62
+ * Unlike `redact` on a string, a match replaces only itself: the rest of the
63
+ * message is what makes the record useful.
64
+ */
65
+ export declare function redactText(text: string, options?: RedactTextOptions): string;