@agenttrail/guardrails 0.1.0 → 0.2.1
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/README.md +12 -0
- package/dist/{chunk-C4B2NPWH.js → chunk-FTTMZCDH.js} +2 -2
- package/dist/chunk-FTTMZCDH.js.map +1 -0
- package/dist/{chunk-DBB7HO4T.js → chunk-SLWHBH7H.js} +444 -249
- package/dist/chunk-SLWHBH7H.js.map +1 -0
- package/dist/guardrails.cjs +443 -248
- package/dist/guardrails.cjs.map +1 -1
- package/dist/guardrails.d.cts +101 -12
- package/dist/guardrails.d.ts +101 -12
- package/dist/guardrails.js +7 -1
- package/dist/index.cjs +444 -249
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +8 -2
- package/dist/schema.cjs +1 -1
- package/dist/schema.cjs.map +1 -1
- package/dist/schema.d.cts +7 -2
- package/dist/schema.d.ts +7 -2
- package/dist/schema.js +1 -1
- package/package.json +53 -29
- package/dist/chunk-C4B2NPWH.js.map +0 -1
- package/dist/chunk-DBB7HO4T.js.map +0 -1
package/dist/index.d.cts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { CATALOG_PUBLISHED_AT, CATALOG_VERSION, GIT_TEXT_MENTION, HTTP_BODY_MENTION, PACKS, PRINT_MENTION, Pack, QUOTED_MENTION, RULES, RULES_BY_PACK, SEARCH_MENTION, bash, file, getRule, isPack, mentionInCommit, mentionInEcho, mentionInPost, mentionInSearch, mentions, pwsh, rulesForPack } from './guardrails.cjs';
|
|
1
|
+
export { CATALOG_PUBLISHED_AT, CATALOG_VERSION, GIT_TEXT_MENTION, HTTP_BODY_MENTION, LEADING_FLAGS, PACKS, PRINT_MENTION, Pack, QUOTED_MENTION, RULES, RULES_BY_PACK, SEARCH_MENTION, SHELL_AND_MCP, bash, file, getRule, isPack, mcp, mentionInCommit, mentionInEcho, mentionInPost, mentionInSearch, mentions, pwsh, rulesForPack } from './guardrails.cjs';
|
|
2
2
|
export { ACTIONS, Action, ActionSchema, DETAIL_MATCHES_MAX_PATTERNS, DETAIL_MATCHES_MAX_PATTERN_LENGTH, Fixture, FixtureInput, FixtureSchema, Fixtures, FixturesSchema, Match, MatchCondition, MatchConditionSchema, MatchSchema, Rule, RuleInput, RuleSchema, SEVERITIES, Severity, SeveritySchema, defineRule, hasNestedUnboundedQuantifier, parseRule, parseRuleOrThrow } from './schema.cjs';
|
|
3
3
|
import 'zod';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { CATALOG_PUBLISHED_AT, CATALOG_VERSION, GIT_TEXT_MENTION, HTTP_BODY_MENTION, PACKS, PRINT_MENTION, Pack, QUOTED_MENTION, RULES, RULES_BY_PACK, SEARCH_MENTION, bash, file, getRule, isPack, mentionInCommit, mentionInEcho, mentionInPost, mentionInSearch, mentions, pwsh, rulesForPack } from './guardrails.js';
|
|
1
|
+
export { CATALOG_PUBLISHED_AT, CATALOG_VERSION, GIT_TEXT_MENTION, HTTP_BODY_MENTION, LEADING_FLAGS, PACKS, PRINT_MENTION, Pack, QUOTED_MENTION, RULES, RULES_BY_PACK, SEARCH_MENTION, SHELL_AND_MCP, bash, file, getRule, isPack, mcp, mentionInCommit, mentionInEcho, mentionInPost, mentionInSearch, mentions, pwsh, rulesForPack } from './guardrails.js';
|
|
2
2
|
export { ACTIONS, Action, ActionSchema, DETAIL_MATCHES_MAX_PATTERNS, DETAIL_MATCHES_MAX_PATTERN_LENGTH, Fixture, FixtureInput, FixtureSchema, Fixtures, FixturesSchema, Match, MatchCondition, MatchConditionSchema, MatchSchema, Rule, RuleInput, RuleSchema, SEVERITIES, Severity, SeveritySchema, defineRule, hasNestedUnboundedQuantifier, parseRule, parseRuleOrThrow } from './schema.js';
|
|
3
3
|
import 'zod';
|
package/dist/index.js
CHANGED
|
@@ -3,16 +3,19 @@ import {
|
|
|
3
3
|
CATALOG_VERSION,
|
|
4
4
|
GIT_TEXT_MENTION,
|
|
5
5
|
HTTP_BODY_MENTION,
|
|
6
|
+
LEADING_FLAGS,
|
|
6
7
|
PACKS,
|
|
7
8
|
PRINT_MENTION,
|
|
8
9
|
QUOTED_MENTION,
|
|
9
10
|
RULES,
|
|
10
11
|
RULES_BY_PACK,
|
|
11
12
|
SEARCH_MENTION,
|
|
13
|
+
SHELL_AND_MCP,
|
|
12
14
|
bash,
|
|
13
15
|
file,
|
|
14
16
|
getRule,
|
|
15
17
|
isPack,
|
|
18
|
+
mcp,
|
|
16
19
|
mentionInCommit,
|
|
17
20
|
mentionInEcho,
|
|
18
21
|
mentionInPost,
|
|
@@ -20,7 +23,7 @@ import {
|
|
|
20
23
|
mentions,
|
|
21
24
|
pwsh,
|
|
22
25
|
rulesForPack
|
|
23
|
-
} from "./chunk-
|
|
26
|
+
} from "./chunk-SLWHBH7H.js";
|
|
24
27
|
import {
|
|
25
28
|
ACTIONS,
|
|
26
29
|
ActionSchema,
|
|
@@ -37,7 +40,7 @@ import {
|
|
|
37
40
|
hasNestedUnboundedQuantifier,
|
|
38
41
|
parseRule,
|
|
39
42
|
parseRuleOrThrow
|
|
40
|
-
} from "./chunk-
|
|
43
|
+
} from "./chunk-FTTMZCDH.js";
|
|
41
44
|
export {
|
|
42
45
|
ACTIONS,
|
|
43
46
|
ActionSchema,
|
|
@@ -49,6 +52,7 @@ export {
|
|
|
49
52
|
FixturesSchema,
|
|
50
53
|
GIT_TEXT_MENTION,
|
|
51
54
|
HTTP_BODY_MENTION,
|
|
55
|
+
LEADING_FLAGS,
|
|
52
56
|
MatchConditionSchema,
|
|
53
57
|
MatchSchema,
|
|
54
58
|
PACKS,
|
|
@@ -59,6 +63,7 @@ export {
|
|
|
59
63
|
RuleSchema,
|
|
60
64
|
SEARCH_MENTION,
|
|
61
65
|
SEVERITIES,
|
|
66
|
+
SHELL_AND_MCP,
|
|
62
67
|
SeveritySchema,
|
|
63
68
|
bash,
|
|
64
69
|
defineRule,
|
|
@@ -66,6 +71,7 @@ export {
|
|
|
66
71
|
getRule,
|
|
67
72
|
hasNestedUnboundedQuantifier,
|
|
68
73
|
isPack,
|
|
74
|
+
mcp,
|
|
69
75
|
mentionInCommit,
|
|
70
76
|
mentionInEcho,
|
|
71
77
|
mentionInPost,
|
package/dist/schema.cjs
CHANGED
|
@@ -42,7 +42,7 @@ var SEVERITIES = ["critical", "high", "medium", "low", "info"];
|
|
|
42
42
|
var SeveritySchema = import_zod.z.enum(SEVERITIES);
|
|
43
43
|
var ACTIONS = ["block", "require_approval", "warn"];
|
|
44
44
|
var ActionSchema = import_zod.z.enum(ACTIONS);
|
|
45
|
-
var DETAIL_MATCHES_MAX_PATTERN_LENGTH =
|
|
45
|
+
var DETAIL_MATCHES_MAX_PATTERN_LENGTH = 320;
|
|
46
46
|
var DETAIL_MATCHES_MAX_PATTERNS = 10;
|
|
47
47
|
function hasNestedUnboundedQuantifier(source) {
|
|
48
48
|
const unboundedQuantifierAt = (s, i) => {
|
package/dist/schema.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/schema.ts"],"sourcesContent":["/**\n * The guardrails rule format — self-contained, and deliberately so.\n *\n * This file defines the rule format and imports nothing but zod, so the package\n * builds on its own. The condition and match shapes mirror the evaluator's rather\n * than importing them; a change to either has to be made in both places.\n *\n * A rule carries `defaultAction` (what the guard does when it matches) and no\n * `version`; the package version is the corpus version.\n */\n\nimport { z } from \"zod\";\n\n// ── Severity ────────────────────────────────────────────────────────────────\n\n/**\n * The five severities, in order, most→least severe.\n *\n * `info` earns its place: seven of the eleven packs default to `ask`/`warn`, and a\n * warn-only rule labelled `low` overstates itself.\n *\n * Severity says how serious a match is. This package maps it to nothing else,\n * including cost: the guard prints no currency.\n */\nexport const SEVERITIES = [\"critical\", \"high\", \"medium\", \"low\", \"info\"] as const;\n\n/** How dangerous the thing a rule catches is. An authoring signal, not a price. */\nexport const SeveritySchema = z.enum(SEVERITIES);\n\n// ── Actions ─────────────────────────────────────────────────────────────────\n\n/**\n * What the guard does when a rule matches.\n *\n * The guard maps these onto Claude Code's `PreToolUse` verdicts:\n * `block` → deny, `require_approval` → ask, `warn` → allow-but-recorded.\n */\nexport const ACTIONS = [\"block\", \"require_approval\", \"warn\"] as const;\n\n/** The action a rule takes by default, before any user override. */\nexport const ActionSchema = z.enum(ACTIONS);\n\n// ── detail_matches: regex limits, mirrored from the engine ───────────────────\n\n/** Longest accepted `detail_matches` pattern. Long enough for any real rule. */\nexport const DETAIL_MATCHES_MAX_PATTERN_LENGTH = 200;\n\n/** Most `detail_matches` patterns allowed on one condition (they are ORed). */\nexport const DETAIL_MATCHES_MAX_PATTERNS = 10;\n\n/**\n * Reject a regex that can backtrack catastrophically, at PARSE time.\n *\n * Node has no regex timeout, so the only real bounds are a non-backtracking\n * engine (RE2 — a runtime dependency deliberately not taken) or a syntactic\n * restriction. This is the syntactic one: it rejects **star height >= 2**, an\n * unbounded quantifier applied to a group that itself contains an unbounded\n * quantifier — `(a+)+`, `(a*)*`, `(\\s+x?)+` — the shape behind essentially every\n * practical ReDoS.\n *\n * The guard's hook has a 10s Claude Code timeout, no internal watchdog, and it\n * **fails open**: a pattern that backtracks does not merely make enforcement slow,\n * it lets the action through. A slow rule in the guard is a disabled rule.\n *\n * HONEST LIMIT: this is a bound, not a proof. Star height 1 can still be\n * quadratic (`(a|a)*`), which is slow but not exponential, and is acceptable\n * against the length cap above. A hard guarantee needs RE2.\n *\n * @param source - The regex body (no delimiters, no flags).\n * @returns `true` when the pattern nests unbounded quantifiers.\n */\nexport function hasNestedUnboundedQuantifier(source: string): boolean {\n /** Is `source[i]` an unbounded quantifier (`*`, `+`, or `{n,}`)? */\n const unboundedQuantifierAt = (s: string, i: number): boolean => {\n const ch = s[i];\n if (ch === \"*\" || ch === \"+\") return true;\n if (ch !== \"{\") return false;\n const close = s.indexOf(\"}\", i);\n // `{n,}` is unbounded; `{n}` and `{n,m}` are not.\n return close !== -1 && /^\\{\\d*,\\}$/.test(s.slice(i, close + 1));\n };\n\n /** Does `body` contain an unbounded quantifier outside a character class? */\n const containsUnbounded = (body: string): boolean => {\n let inClass = false;\n for (let i = 0; i < body.length; i++) {\n const ch = body[i];\n if (ch === \"\\\\\") {\n i++;\n continue;\n }\n if (inClass) {\n if (ch === \"]\") inClass = false;\n continue;\n }\n if (ch === \"[\") {\n inClass = true;\n continue;\n }\n if (unboundedQuantifierAt(body, i)) return true;\n }\n return false;\n };\n\n const groupStarts: number[] = [];\n let inClass = false;\n for (let i = 0; i < source.length; i++) {\n const ch = source[i];\n if (ch === \"\\\\\") {\n i++; // skip the escaped char — `\\(` is a literal, not a group\n continue;\n }\n if (inClass) {\n if (ch === \"]\") inClass = false;\n continue;\n }\n if (ch === \"[\") {\n inClass = true;\n continue;\n }\n if (ch === \"(\") {\n groupStarts.push(i);\n continue;\n }\n if (ch === \")\") {\n const start = groupStarts.pop();\n if (start === undefined) continue; // unbalanced — the RegExp compile catches it\n // Quantified group? Then its body must not itself repeat unboundedly.\n if (unboundedQuantifierAt(source, i + 1) && containsUnbounded(source.slice(start + 1, i))) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * One `detail_matches` pattern: compilable, length-capped, and free of nested\n * unbounded quantifiers. The engine compiles these with `i` and never `g`/`y` —\n * a global regex carries `lastIndex` between calls and would intermittently miss.\n */\nconst DetailMatchPatternSchema = z\n .string()\n .min(1)\n .max(DETAIL_MATCHES_MAX_PATTERN_LENGTH)\n .superRefine((pattern, ctx) => {\n try {\n new RegExp(pattern, \"i\");\n } catch (error) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `detail_matches: not a valid regular expression (${\n error instanceof Error ? error.message : \"unknown error\"\n })`,\n });\n return;\n }\n if (hasNestedUnboundedQuantifier(pattern)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message:\n \"detail_matches: nested unbounded quantifier (e.g. `(a+)+`) can backtrack catastrophically; rewrite without repeating a repeating group\",\n });\n }\n });\n\n// ── Match conditions ────────────────────────────────────────────────────────\n\n/**\n * One condition matched against a tool call.\n *\n * - `kind`: required. The span kind, e.g. `execute_tool`. Case-insensitive.\n * - `label`: optional. The tool name — a case-insensitive GLOB, so\n * `mcp__chrome__*` and `{Bash,PowerShell}` are one condition rather than a\n * list that rots. A plain label has no glob character and matches exactly.\n * - `detail_contains`: optional. Substrings that must ALL appear (AND).\n * **CASE-SENSITIVE**, and deliberately: `AKIA`, `ghp_`, `sk_live_` and the\n * upper-case `TRUNCATE` arm are rules where case IS the signal. Author\n * case-insensitive text matches with `detail_matches` instead.\n * - `detail_matches`: optional. Regex patterns against the same text; at least\n * one must match (OR, unlike `detail_contains`). Case-insensitive.\n * - `file_glob`: optional. Case-insensitive glob against the file path.\n *\n * ── Two engine fields are deliberately absent ────────────────────────────────\n *\n * `numeric` is BANNED. At guard decision time `tokens`,\n * `cachedTokens` and `durationMs` are all 0, because the action has not run yet.\n * `gt` is therefore always false — the rule can never fire — and, worse, **`lt`\n * is always true, so the rule fires on every single command.** Omitting the key\n * from a `.strict()` object makes that a parse error rather than a lint finding.\n *\n * `scope` is BANNED for the same class of reason and is absent from the rule\n * envelope below: `agent_in` compares literally against an agent id that is\n * always a UUID, never the string `\"claude-code\"`, so a scoped rule matches\n * nothing, forever, silently.\n *\n * ── The third ban needs an actual check ──────────────────────────────────────\n *\n * A command matcher (`detail_contains` / `detail_matches`) and a file matcher\n * (`file_glob`) in ONE condition can never both be satisfied: the guard's mapper\n * is an if/else chain, so no real tool call ever carries both a command and a\n * file path. This schema refuses the combination.\n */\nexport const MatchConditionSchema = z\n .object({\n kind: z.string().min(1),\n label: z.string().min(1).optional(),\n detail_contains: z.array(z.string().min(1)).min(1).optional(),\n detail_matches: z\n .array(DetailMatchPatternSchema)\n .min(1)\n .max(DETAIL_MATCHES_MAX_PATTERNS)\n .optional(),\n file_glob: z.string().min(1).optional(),\n })\n .strict()\n .superRefine((condition, ctx) => {\n const hasCommandMatcher =\n condition.detail_contains !== undefined || condition.detail_matches !== undefined;\n if (hasCommandMatcher && condition.file_glob !== undefined) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message:\n \"a condition may not combine a command matcher (detail_contains / detail_matches) with a file matcher (file_glob): no real tool call carries both, so the condition can never match. Split it into two conditions under any_of.\",\n });\n }\n });\n\n/**\n * Match composition — conditions combined with `any_of` (OR), `all_of` (AND)\n * and/or `none_of` (negation).\n *\n * At least one of `any_of` or `all_of` must be present. `none_of` is an optional\n * refinement that CANNOT stand alone: a match must positively select calls\n * before excluding some. A pure-negation match is satisfied by every\n * non-matching call and, at `block`, would deny everything the agent does.\n */\nexport const MatchSchema = z\n .object({\n any_of: z.array(MatchConditionSchema).min(1).optional(),\n all_of: z.array(MatchConditionSchema).min(1).optional(),\n none_of: z.array(MatchConditionSchema).min(1).optional(),\n })\n .strict()\n .refine((data) => data.any_of !== undefined || data.all_of !== undefined, {\n message: \"At least one of 'any_of' or 'all_of' must be provided\",\n });\n\n// ── Fixtures ────────────────────────────────────────────────────────────────\n\n/**\n * The tools a fixture may name. Free-form on purpose — the guard's matcher grows\n * (`mcp__*` alone is unbounded) and a closed enum here would reject a valid rule\n * for a tool this package has not heard of yet.\n */\nconst FixtureToolSchema = z.string().min(1);\n\n/**\n * A fixture on the COMMAND channel: `Bash`, `PowerShell`, `WebSearch` (its\n * query is ordinary text), and `mcp__*` (its serialized input).\n */\nconst CommandFixtureSchema = z\n .object({ tool: FixtureToolSchema, command: z.string().min(1) })\n .strict();\n\n/** A fixture on the FILE channel: `Edit`, `Write`, `Read`, `NotebookEdit`. */\nconst FileFixtureSchema = z\n .object({ tool: FixtureToolSchema, file_path: z.string().min(1) })\n .strict();\n\n/**\n * One fixture: a tool call this rule must match, or must not.\n *\n * A bare string is shorthand for `{ tool: \"Bash\", command: \"<string>\" }`, which\n * covers most rules and keeps them terse. Anything else is an object with a\n * `tool` plus **exactly one** of `command` or `file_path` — the two channels.\n * `.strict()` on each variant is what makes \"exactly one\" true: a\n * `command` object carrying a `file_path` matches neither variant.\n *\n * The parse output is always normalized to the object form, so the harness has\n * exactly one shape to feed the evaluator.\n *\n * ── There is no `url` channel ─────────────────────────────────────────────────\n *\n * **The evaluator cannot see a URL**: the only two attribute keys any matcher\n * reads are `detail` and `file_path`, and there is no `url` field in the condition\n * schema. A value written to `url` would be read by nothing, so a `WebFetch` rule\n * would match nothing, silently — the same failure `scope` is banned for. There\n * are no website rules and `WebFetch` is not intercepted; `WebSearch` is, because\n * its query is text on the command channel.\n *\n * A `url` key therefore fails to parse rather than becoming a fixture that tests\n * nothing. `__tests__/schema.test.ts` pins that.\n */\nexport const FixtureSchema = z.union([\n z\n .string()\n .min(1)\n .transform((command) => ({ tool: \"Bash\" as const, command })),\n CommandFixtureSchema,\n FileFixtureSchema,\n]);\n\n/**\n * The two directions every rule must prove, through the real evaluator.\n *\n * **`block` means \"this rule MUST match\"; `allow` means \"this rule MUST NOT\n * match\".** They are not verdicts. Seven of the eleven packs default to `ask` or\n * `warn`, and `warn` folds into an allow verdict, so reading `block` as \"the\n * guard denies\" would fail every `warn` rule and make the negative fixture\n * vacuous for them.\n *\n * Both are `.min(1)`: CI only has to fail on a rule missing a\n * negative fixture, but requiring it here moves that failure to authoring time,\n * where it costs a keystroke instead of a pull-request round trip.\n */\nexport const FixturesSchema = z\n .object({\n block: z.array(FixtureSchema).min(1),\n allow: z.array(FixtureSchema).min(1),\n })\n .strict();\n\n// ── The rule ────────────────────────────────────────────────────────────────\n\n/**\n * One published rule.\n *\n * `.strict()` rejects any key not declared here, so an unknown field fails to parse\n * rather than riding along into the published package.\n *\n * `description` carries the rule's COVERAGE LIMITS, verbatim — e.g. that an\n * `rm -rf` rule misses `rm -fr`. It is a convention rather than a schema\n * constraint, because no validator can tell a real limit from a sentence shaped\n * like one.\n */\nexport const RuleSchema = z\n .object({\n /** Stable: a rule id is never renamed. */\n id: z.string().min(1),\n /** The pack this rule belongs to. Validated against `PACKS` by the registry. */\n category: z.string().min(1),\n severity: SeveritySchema,\n defaultAction: ActionSchema,\n title: z.string().min(1),\n description: z.string().min(1),\n match: MatchSchema,\n fixtures: FixturesSchema,\n })\n .strict();\n\n// ── Types ───────────────────────────────────────────────────────────────────\n\n/** How dangerous the caught action is. Never a price. */\nexport type Severity = (typeof SEVERITIES)[number];\n\n/** What the guard does on a match. */\nexport type Action = (typeof ACTIONS)[number];\n\n/** One condition matched against a tool call. */\nexport type MatchCondition = z.infer<typeof MatchConditionSchema>;\n\n/** A composed match — `any_of` / `all_of` / `none_of`. */\nexport type Match = z.infer<typeof MatchSchema>;\n\n/** A fixture as authored: a bare command string, or a tagged single-channel object. */\nexport type FixtureInput = z.input<typeof FixtureSchema>;\n\n/** A fixture after parsing — always the tagged object form. */\nexport type Fixture = z.output<typeof FixtureSchema>;\n\n/** The must-match / must-not-match pair every rule ships. */\nexport type Fixtures = z.infer<typeof FixturesSchema>;\n\n/** One published rule, as authored. */\nexport type RuleInput = z.input<typeof RuleSchema>;\n\n/** One published rule, parsed and normalized. */\nexport type Rule = z.output<typeof RuleSchema>;\n\n// ── Parsing ─────────────────────────────────────────────────────────────────\n\n/**\n * Validate a rule from unknown input.\n *\n * It answers \"is this a well-formed rule?\" — it does NOT answer \"does this rule\n * actually fire on the command you think it does.\" That needs the evaluator, which\n * is not part of this package.\n *\n * @param input - Unknown input, e.g. parsed JSON or a rule module's default export.\n * @returns A Zod SafeParseReturnType — check `.success` before reading `.data`.\n */\nexport function parseRule(input: unknown): z.SafeParseReturnType<unknown, Rule> {\n return RuleSchema.safeParse(input);\n}\n\n/**\n * Parse a rule, or throw with the reason.\n *\n * Used by rule modules themselves via {@link defineRule}, so an authoring\n * mistake fails at import — which is to say, at test time — rather than\n * surviving into a corpus that only validates what it remembers to check.\n */\nexport function parseRuleOrThrow(input: unknown): Rule {\n const result = parseRule(input);\n if (!result.success) {\n const id =\n typeof input === \"object\" && input !== null && \"id\" in input\n ? String((input as { id: unknown }).id)\n : \"<unknown id>\";\n throw new Error(`invalid guardrails rule ${id}: ${result.error.message}`);\n }\n return result.data;\n}\n\n/**\n * Declare a rule. Validates at module load, so a malformed rule cannot reach the\n * registry — the corpus is only as trustworthy as its weakest unvalidated entry.\n */\nexport function defineRule(rule: RuleInput): Rule {\n return parseRuleOrThrow(rule);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWA,iBAAkB;AAaX,IAAM,aAAa,CAAC,YAAY,QAAQ,UAAU,OAAO,MAAM;AAG/D,IAAM,iBAAiB,aAAE,KAAK,UAAU;AAUxC,IAAM,UAAU,CAAC,SAAS,oBAAoB,MAAM;AAGpD,IAAM,eAAe,aAAE,KAAK,OAAO;AAKnC,IAAM,oCAAoC;AAG1C,IAAM,8BAA8B;AAuBpC,SAAS,6BAA6B,QAAyB;AAEpE,QAAM,wBAAwB,CAAC,GAAW,MAAuB;AAC/D,UAAM,KAAK,EAAE,CAAC;AACd,QAAI,OAAO,OAAO,OAAO,IAAK,QAAO;AACrC,QAAI,OAAO,IAAK,QAAO;AACvB,UAAM,QAAQ,EAAE,QAAQ,KAAK,CAAC;AAE9B,WAAO,UAAU,MAAM,aAAa,KAAK,EAAE,MAAM,GAAG,QAAQ,CAAC,CAAC;AAAA,EAChE;AAGA,QAAM,oBAAoB,CAAC,SAA0B;AACnD,QAAIA,WAAU;AACd,aAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,YAAM,KAAK,KAAK,CAAC;AACjB,UAAI,OAAO,MAAM;AACf;AACA;AAAA,MACF;AACA,UAAIA,UAAS;AACX,YAAI,OAAO,IAAK,CAAAA,WAAU;AAC1B;AAAA,MACF;AACA,UAAI,OAAO,KAAK;AACd,QAAAA,WAAU;AACV;AAAA,MACF;AACA,UAAI,sBAAsB,MAAM,CAAC,EAAG,QAAO;AAAA,IAC7C;A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A;AACF,CAAC;AAeM,IAAM,iBAAiB,aAC3B,OAAO;AAAA,EACN,OAAO,aAAE,MAAM,aAAa,EAAE,IAAI,CAAC;AAAA,EACnC,OAAO,aAAE,MAAM,aAAa,EAAE,IAAI,CAAC;AACrC,CAAC,EACA,OAAO;AAeH,IAAM,aAAa,aACvB,OAAO;AAAA;AAAA,EAEN,IAAI,aAAE,OAAO,EAAE,IAAI,CAAC;AAAA;AAAA,EAEpB,UAAU,aAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EAC1B,UAAU;AAAA,EACV,eAAe;AAAA,EACf,OAAO,aAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACvB,aAAa,aAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EAC7B,OAAO;AAAA,EACP,UAAU;AACZ,CAAC,EACA,OAAO;AA2CH,SAAS,UAAU,OAAsD;AAC9E,SAAO,WAAW,UAAU,KAAK;AACnC;AASO,SAAS,iBAAiB,OAAsB;AACrD,QAAM,SAAS,UAAU,KAAK;AAC9B,MAAI,CAAC,OAAO,SAAS;AACnB,UAAM,KACJ,OAAO,UAAU,YAAY,UAAU,QAAQ,QAAQ,QACnD,OAAQ,MAA0B,EAAE,IACpC;AACN,UAAM,IAAI,MAAM,2BAA2B,EAAE,KAAK,OAAO,MAAM,OAAO,EAAE;AAAA,EAC1E;AACA,SAAO,OAAO;AAChB;AAMO,SAAS,WAAW,MAAuB;AAChD,SAAO,iBAAiB,IAAI;AAC9B;","names":["inClass"]}
|
|
1
|
+
{"version":3,"sources":["../src/schema.ts"],"sourcesContent":["/**\n * The guardrails rule format — self-contained, and deliberately so.\n *\n * This file defines the rule format and imports nothing but zod, so the package\n * builds on its own. The condition and match shapes mirror the evaluator's rather\n * than importing them; a change to either has to be made in both places.\n *\n * A rule carries `defaultAction` (what the guard does when it matches) and no\n * `version`; the package version is the corpus version.\n */\n\nimport { z } from \"zod\";\n\n// ── Severity ────────────────────────────────────────────────────────────────\n\n/**\n * The five severities, in order, most→least severe.\n *\n * `info` earns its place: seven of the eleven packs default to `ask`/`warn`, and a\n * warn-only rule labelled `low` overstates itself.\n *\n * Severity says how serious a match is. This package maps it to nothing else,\n * including cost: the guard prints no currency.\n */\nexport const SEVERITIES = [\"critical\", \"high\", \"medium\", \"low\", \"info\"] as const;\n\n/** How dangerous the thing a rule catches is. An authoring signal, not a price. */\nexport const SeveritySchema = z.enum(SEVERITIES);\n\n// ── Actions ─────────────────────────────────────────────────────────────────\n\n/**\n * What the guard does when a rule matches.\n *\n * The guard maps these onto Claude Code's `PreToolUse` verdicts:\n * `block` → deny, `require_approval` → ask, `warn` → allow-but-recorded.\n */\nexport const ACTIONS = [\"block\", \"require_approval\", \"warn\"] as const;\n\n/** The action a rule takes by default, before any user override. */\nexport const ActionSchema = z.enum(ACTIONS);\n\n// ── detail_matches: regex limits, mirrored from the engine ───────────────────\n\n/**\n * Longest accepted `detail_matches` pattern. Long enough for any real rule; raised\n * from 200 to fit the compound-command quoted-mention exemption, whose longest arm\n * (a carrier wrapped in a bounded chain of read-only surrounding segments) is ~300.\n * Kept in lockstep with the engine's own copy of this limit.\n */\nexport const DETAIL_MATCHES_MAX_PATTERN_LENGTH = 320;\n\n/** Most `detail_matches` patterns allowed on one condition (they are ORed). */\nexport const DETAIL_MATCHES_MAX_PATTERNS = 10;\n\n/**\n * Reject a regex that can backtrack catastrophically, at PARSE time.\n *\n * Node has no regex timeout, so the only real bounds are a non-backtracking\n * engine (RE2 — a runtime dependency deliberately not taken) or a syntactic\n * restriction. This is the syntactic one: it rejects **star height >= 2**, an\n * unbounded quantifier applied to a group that itself contains an unbounded\n * quantifier — `(a+)+`, `(a*)*`, `(\\s+x?)+` — the shape behind essentially every\n * practical ReDoS.\n *\n * The guard's hook has a 10s Claude Code timeout, no internal watchdog, and it\n * **fails open**: a pattern that backtracks does not merely make enforcement slow,\n * it lets the action through. A slow rule in the guard is a disabled rule.\n *\n * HONEST LIMIT: this is a bound, not a proof. Star height 1 can still be\n * quadratic (`(a|a)*`), which is slow but not exponential, and is acceptable\n * against the length cap above. A hard guarantee needs RE2.\n *\n * @param source - The regex body (no delimiters, no flags).\n * @returns `true` when the pattern nests unbounded quantifiers.\n */\nexport function hasNestedUnboundedQuantifier(source: string): boolean {\n /** Is `source[i]` an unbounded quantifier (`*`, `+`, or `{n,}`)? */\n const unboundedQuantifierAt = (s: string, i: number): boolean => {\n const ch = s[i];\n if (ch === \"*\" || ch === \"+\") return true;\n if (ch !== \"{\") return false;\n const close = s.indexOf(\"}\", i);\n // `{n,}` is unbounded; `{n}` and `{n,m}` are not.\n return close !== -1 && /^\\{\\d*,\\}$/.test(s.slice(i, close + 1));\n };\n\n /** Does `body` contain an unbounded quantifier outside a character class? */\n const containsUnbounded = (body: string): boolean => {\n let inClass = false;\n for (let i = 0; i < body.length; i++) {\n const ch = body[i];\n if (ch === \"\\\\\") {\n i++;\n continue;\n }\n if (inClass) {\n if (ch === \"]\") inClass = false;\n continue;\n }\n if (ch === \"[\") {\n inClass = true;\n continue;\n }\n if (unboundedQuantifierAt(body, i)) return true;\n }\n return false;\n };\n\n const groupStarts: number[] = [];\n let inClass = false;\n for (let i = 0; i < source.length; i++) {\n const ch = source[i];\n if (ch === \"\\\\\") {\n i++; // skip the escaped char — `\\(` is a literal, not a group\n continue;\n }\n if (inClass) {\n if (ch === \"]\") inClass = false;\n continue;\n }\n if (ch === \"[\") {\n inClass = true;\n continue;\n }\n if (ch === \"(\") {\n groupStarts.push(i);\n continue;\n }\n if (ch === \")\") {\n const start = groupStarts.pop();\n if (start === undefined) continue; // unbalanced — the RegExp compile catches it\n // Quantified group? Then its body must not itself repeat unboundedly.\n if (unboundedQuantifierAt(source, i + 1) && containsUnbounded(source.slice(start + 1, i))) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * One `detail_matches` pattern: compilable, length-capped, and free of nested\n * unbounded quantifiers. The engine compiles these with `i` and never `g`/`y` —\n * a global regex carries `lastIndex` between calls and would intermittently miss.\n */\nconst DetailMatchPatternSchema = z\n .string()\n .min(1)\n .max(DETAIL_MATCHES_MAX_PATTERN_LENGTH)\n .superRefine((pattern, ctx) => {\n try {\n new RegExp(pattern, \"i\");\n } catch (error) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `detail_matches: not a valid regular expression (${\n error instanceof Error ? error.message : \"unknown error\"\n })`,\n });\n return;\n }\n if (hasNestedUnboundedQuantifier(pattern)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message:\n \"detail_matches: nested unbounded quantifier (e.g. `(a+)+`) can backtrack catastrophically; rewrite without repeating a repeating group\",\n });\n }\n });\n\n// ── Match conditions ────────────────────────────────────────────────────────\n\n/**\n * One condition matched against a tool call.\n *\n * - `kind`: required. The span kind, e.g. `execute_tool`. Case-insensitive.\n * - `label`: optional. The tool name — a case-insensitive GLOB, so\n * `mcp__chrome__*` and `{Bash,PowerShell}` are one condition rather than a\n * list that rots. A plain label has no glob character and matches exactly.\n * - `detail_contains`: optional. Substrings that must ALL appear (AND).\n * **CASE-SENSITIVE**, and deliberately: `AKIA`, `ghp_`, `sk_live_` and the\n * upper-case `TRUNCATE` arm are rules where case IS the signal. Author\n * case-insensitive text matches with `detail_matches` instead.\n * - `detail_matches`: optional. Regex patterns against the same text; at least\n * one must match (OR, unlike `detail_contains`). Case-insensitive.\n * - `file_glob`: optional. Case-insensitive glob against the file path.\n *\n * ── Two engine fields are deliberately absent ────────────────────────────────\n *\n * `numeric` is BANNED. At guard decision time `tokens`,\n * `cachedTokens` and `durationMs` are all 0, because the action has not run yet.\n * `gt` is therefore always false — the rule can never fire — and, worse, **`lt`\n * is always true, so the rule fires on every single command.** Omitting the key\n * from a `.strict()` object makes that a parse error rather than a lint finding.\n *\n * `scope` is BANNED for the same class of reason and is absent from the rule\n * envelope below: `agent_in` compares literally against an agent id that is\n * always a UUID, never the string `\"claude-code\"`, so a scoped rule matches\n * nothing, forever, silently.\n *\n * ── The third ban needs an actual check ──────────────────────────────────────\n *\n * A command matcher (`detail_contains` / `detail_matches`) and a file matcher\n * (`file_glob`) in ONE condition can never both be satisfied: the guard's mapper\n * is an if/else chain, so no real tool call ever carries both a command and a\n * file path. This schema refuses the combination.\n */\nexport const MatchConditionSchema = z\n .object({\n kind: z.string().min(1),\n label: z.string().min(1).optional(),\n detail_contains: z.array(z.string().min(1)).min(1).optional(),\n detail_matches: z\n .array(DetailMatchPatternSchema)\n .min(1)\n .max(DETAIL_MATCHES_MAX_PATTERNS)\n .optional(),\n file_glob: z.string().min(1).optional(),\n })\n .strict()\n .superRefine((condition, ctx) => {\n const hasCommandMatcher =\n condition.detail_contains !== undefined || condition.detail_matches !== undefined;\n if (hasCommandMatcher && condition.file_glob !== undefined) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message:\n \"a condition may not combine a command matcher (detail_contains / detail_matches) with a file matcher (file_glob): no real tool call carries both, so the condition can never match. Split it into two conditions under any_of.\",\n });\n }\n });\n\n/**\n * Match composition — conditions combined with `any_of` (OR), `all_of` (AND)\n * and/or `none_of` (negation).\n *\n * At least one of `any_of` or `all_of` must be present. `none_of` is an optional\n * refinement that CANNOT stand alone: a match must positively select calls\n * before excluding some. A pure-negation match is satisfied by every\n * non-matching call and, at `block`, would deny everything the agent does.\n */\nexport const MatchSchema = z\n .object({\n any_of: z.array(MatchConditionSchema).min(1).optional(),\n all_of: z.array(MatchConditionSchema).min(1).optional(),\n none_of: z.array(MatchConditionSchema).min(1).optional(),\n })\n .strict()\n .refine((data) => data.any_of !== undefined || data.all_of !== undefined, {\n message: \"At least one of 'any_of' or 'all_of' must be provided\",\n });\n\n// ── Fixtures ────────────────────────────────────────────────────────────────\n\n/**\n * The tools a fixture may name. Free-form on purpose — the guard's matcher grows\n * (`mcp__*` alone is unbounded) and a closed enum here would reject a valid rule\n * for a tool this package has not heard of yet.\n */\nconst FixtureToolSchema = z.string().min(1);\n\n/**\n * A fixture on the COMMAND channel: `Bash`, `PowerShell`, `WebSearch` (its\n * query is ordinary text), and `mcp__*` (its serialized input).\n */\nconst CommandFixtureSchema = z\n .object({ tool: FixtureToolSchema, command: z.string().min(1) })\n .strict();\n\n/** A fixture on the FILE channel: `Edit`, `Write`, `Read`, `NotebookEdit`. */\nconst FileFixtureSchema = z\n .object({ tool: FixtureToolSchema, file_path: z.string().min(1) })\n .strict();\n\n/**\n * One fixture: a tool call this rule must match, or must not.\n *\n * A bare string is shorthand for `{ tool: \"Bash\", command: \"<string>\" }`, which\n * covers most rules and keeps them terse. Anything else is an object with a\n * `tool` plus **exactly one** of `command` or `file_path` — the two channels.\n * `.strict()` on each variant is what makes \"exactly one\" true: a\n * `command` object carrying a `file_path` matches neither variant.\n *\n * The parse output is always normalized to the object form, so the harness has\n * exactly one shape to feed the evaluator.\n *\n * ── There is no `url` channel ─────────────────────────────────────────────────\n *\n * **The evaluator cannot see a URL**: the only two attribute keys any matcher\n * reads are `detail` and `file_path`, and there is no `url` field in the condition\n * schema. A value written to `url` would be read by nothing, so a `WebFetch` rule\n * would match nothing, silently — the same failure `scope` is banned for. There\n * are no website rules and `WebFetch` is not intercepted; `WebSearch` is, because\n * its query is text on the command channel.\n *\n * A `url` key therefore fails to parse rather than becoming a fixture that tests\n * nothing. `__tests__/schema.test.ts` pins that.\n */\nexport const FixtureSchema = z.union([\n z\n .string()\n .min(1)\n .transform((command) => ({ tool: \"Bash\" as const, command })),\n CommandFixtureSchema,\n FileFixtureSchema,\n]);\n\n/**\n * The two directions every rule must prove, through the real evaluator.\n *\n * **`block` means \"this rule MUST match\"; `allow` means \"this rule MUST NOT\n * match\".** They are not verdicts. Seven of the eleven packs default to `ask` or\n * `warn`, and `warn` folds into an allow verdict, so reading `block` as \"the\n * guard denies\" would fail every `warn` rule and make the negative fixture\n * vacuous for them.\n *\n * Both are `.min(1)`: CI only has to fail on a rule missing a\n * negative fixture, but requiring it here moves that failure to authoring time,\n * where it costs a keystroke instead of a pull-request round trip.\n */\nexport const FixturesSchema = z\n .object({\n block: z.array(FixtureSchema).min(1),\n allow: z.array(FixtureSchema).min(1),\n })\n .strict();\n\n// ── The rule ────────────────────────────────────────────────────────────────\n\n/**\n * One published rule.\n *\n * `.strict()` rejects any key not declared here, so an unknown field fails to parse\n * rather than riding along into the published package.\n *\n * `description` carries the rule's COVERAGE LIMITS, verbatim — e.g. that an\n * `rm -rf` rule misses `rm -fr`. It is a convention rather than a schema\n * constraint, because no validator can tell a real limit from a sentence shaped\n * like one.\n */\nexport const RuleSchema = z\n .object({\n /** Stable: a rule id is never renamed. */\n id: z.string().min(1),\n /** The pack this rule belongs to. Validated against `PACKS` by the registry. */\n category: z.string().min(1),\n severity: SeveritySchema,\n defaultAction: ActionSchema,\n title: z.string().min(1),\n description: z.string().min(1),\n match: MatchSchema,\n fixtures: FixturesSchema,\n })\n .strict();\n\n// ── Types ───────────────────────────────────────────────────────────────────\n\n/** How dangerous the caught action is. Never a price. */\nexport type Severity = (typeof SEVERITIES)[number];\n\n/** What the guard does on a match. */\nexport type Action = (typeof ACTIONS)[number];\n\n/** One condition matched against a tool call. */\nexport type MatchCondition = z.infer<typeof MatchConditionSchema>;\n\n/** A composed match — `any_of` / `all_of` / `none_of`. */\nexport type Match = z.infer<typeof MatchSchema>;\n\n/** A fixture as authored: a bare command string, or a tagged single-channel object. */\nexport type FixtureInput = z.input<typeof FixtureSchema>;\n\n/** A fixture after parsing — always the tagged object form. */\nexport type Fixture = z.output<typeof FixtureSchema>;\n\n/** The must-match / must-not-match pair every rule ships. */\nexport type Fixtures = z.infer<typeof FixturesSchema>;\n\n/** One published rule, as authored. */\nexport type RuleInput = z.input<typeof RuleSchema>;\n\n/** One published rule, parsed and normalized. */\nexport type Rule = z.output<typeof RuleSchema>;\n\n// ── Parsing ─────────────────────────────────────────────────────────────────\n\n/**\n * Validate a rule from unknown input.\n *\n * It answers \"is this a well-formed rule?\" — it does NOT answer \"does this rule\n * actually fire on the command you think it does.\" That needs the evaluator, which\n * is not part of this package.\n *\n * @param input - Unknown input, e.g. parsed JSON or a rule module's default export.\n * @returns A Zod SafeParseReturnType — check `.success` before reading `.data`.\n */\nexport function parseRule(input: unknown): z.SafeParseReturnType<unknown, Rule> {\n return RuleSchema.safeParse(input);\n}\n\n/**\n * Parse a rule, or throw with the reason.\n *\n * Used by rule modules themselves via {@link defineRule}, so an authoring\n * mistake fails at import — which is to say, at test time — rather than\n * surviving into a corpus that only validates what it remembers to check.\n */\nexport function parseRuleOrThrow(input: unknown): Rule {\n const result = parseRule(input);\n if (!result.success) {\n const id =\n typeof input === \"object\" && input !== null && \"id\" in input\n ? String((input as { id: unknown }).id)\n : \"<unknown id>\";\n throw new Error(`invalid guardrails rule ${id}: ${result.error.message}`);\n }\n return result.data;\n}\n\n/**\n * Declare a rule. Validates at module load, so a malformed rule cannot reach the\n * registry — the corpus is only as trustworthy as its weakest unvalidated entry.\n */\nexport function defineRule(rule: RuleInput): Rule {\n return parseRuleOrThrow(rule);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWA,iBAAkB;AAaX,IAAM,aAAa,CAAC,YAAY,QAAQ,UAAU,OAAO,MAAM;AAG/D,IAAM,iBAAiB,aAAE,KAAK,UAAU;AAUxC,IAAM,UAAU,CAAC,SAAS,oBAAoB,MAAM;AAGpD,IAAM,eAAe,aAAE,KAAK,OAAO;AAUnC,IAAM,oCAAoC;AAG1C,IAAM,8BAA8B;AAuBpC,SAAS,6BAA6B,QAAyB;AAEpE,QAAM,wBAAwB,CAAC,GAAW,MAAuB;AAC/D,UAAM,KAAK,EAAE,CAAC;AACd,QAAI,OAAO,OAAO,OAAO,IAAK,QAAO;AACrC,QAAI,OAAO,IAAK,QAAO;AACvB,UAAM,QAAQ,EAAE,QAAQ,KAAK,CAAC;AAE9B,WAAO,UAAU,MAAM,aAAa,KAAK,EAAE,MAAM,GAAG,QAAQ,CAAC,CAAC;AAAA,E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AW,MAAuB;AAChD,SAAO,iBAAiB,IAAI;AAC9B;","names":["inClass"]}
|
package/dist/schema.d.cts
CHANGED
|
@@ -32,8 +32,13 @@ declare const SeveritySchema: z.ZodEnum<["critical", "high", "medium", "low", "i
|
|
|
32
32
|
declare const ACTIONS: readonly ["block", "require_approval", "warn"];
|
|
33
33
|
/** The action a rule takes by default, before any user override. */
|
|
34
34
|
declare const ActionSchema: z.ZodEnum<["block", "require_approval", "warn"]>;
|
|
35
|
-
/**
|
|
36
|
-
|
|
35
|
+
/**
|
|
36
|
+
* Longest accepted `detail_matches` pattern. Long enough for any real rule; raised
|
|
37
|
+
* from 200 to fit the compound-command quoted-mention exemption, whose longest arm
|
|
38
|
+
* (a carrier wrapped in a bounded chain of read-only surrounding segments) is ~300.
|
|
39
|
+
* Kept in lockstep with the engine's own copy of this limit.
|
|
40
|
+
*/
|
|
41
|
+
declare const DETAIL_MATCHES_MAX_PATTERN_LENGTH = 320;
|
|
37
42
|
/** Most `detail_matches` patterns allowed on one condition (they are ORed). */
|
|
38
43
|
declare const DETAIL_MATCHES_MAX_PATTERNS = 10;
|
|
39
44
|
/**
|
package/dist/schema.d.ts
CHANGED
|
@@ -32,8 +32,13 @@ declare const SeveritySchema: z.ZodEnum<["critical", "high", "medium", "low", "i
|
|
|
32
32
|
declare const ACTIONS: readonly ["block", "require_approval", "warn"];
|
|
33
33
|
/** The action a rule takes by default, before any user override. */
|
|
34
34
|
declare const ActionSchema: z.ZodEnum<["block", "require_approval", "warn"]>;
|
|
35
|
-
/**
|
|
36
|
-
|
|
35
|
+
/**
|
|
36
|
+
* Longest accepted `detail_matches` pattern. Long enough for any real rule; raised
|
|
37
|
+
* from 200 to fit the compound-command quoted-mention exemption, whose longest arm
|
|
38
|
+
* (a carrier wrapped in a bounded chain of read-only surrounding segments) is ~300.
|
|
39
|
+
* Kept in lockstep with the engine's own copy of this limit.
|
|
40
|
+
*/
|
|
41
|
+
declare const DETAIL_MATCHES_MAX_PATTERN_LENGTH = 320;
|
|
37
42
|
/** Most `detail_matches` patterns allowed on one condition (they are ORed). */
|
|
38
43
|
declare const DETAIL_MATCHES_MAX_PATTERNS = 10;
|
|
39
44
|
/**
|
package/dist/schema.js
CHANGED
package/package.json
CHANGED
|
@@ -1,8 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agenttrail/guardrails",
|
|
3
|
-
"version": "0.1
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "The agenttrail guard rule corpus, its self-contained schema, and its fixtures.",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"guardrails",
|
|
8
|
+
"ai-agent",
|
|
9
|
+
"agent-security",
|
|
10
|
+
"claude-code",
|
|
11
|
+
"cursor",
|
|
12
|
+
"security-rules",
|
|
13
|
+
"policy"
|
|
14
|
+
],
|
|
6
15
|
"repository": {
|
|
7
16
|
"type": "git",
|
|
8
17
|
"url": "git+https://github.com/agenttrailhq/guardrails.git"
|
|
@@ -12,53 +21,68 @@
|
|
|
12
21
|
"url": "https://github.com/agenttrailhq/guardrails/issues"
|
|
13
22
|
},
|
|
14
23
|
"license": "Apache-2.0",
|
|
15
|
-
"
|
|
24
|
+
"packageManager": "pnpm@11.5.2",
|
|
25
|
+
"main": "./src/index.ts",
|
|
16
26
|
"exports": {
|
|
17
|
-
".":
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
"require": "./dist/index.cjs"
|
|
21
|
-
},
|
|
22
|
-
"./guardrails": {
|
|
23
|
-
"types": "./dist/guardrails.d.ts",
|
|
24
|
-
"import": "./dist/guardrails.js",
|
|
25
|
-
"require": "./dist/guardrails.cjs"
|
|
26
|
-
},
|
|
27
|
-
"./schema": {
|
|
28
|
-
"types": "./dist/schema.d.ts",
|
|
29
|
-
"import": "./dist/schema.js",
|
|
30
|
-
"require": "./dist/schema.cjs"
|
|
31
|
-
}
|
|
27
|
+
".": "./src/index.ts",
|
|
28
|
+
"./guardrails": "./src/rules.ts",
|
|
29
|
+
"./schema": "./src/schema.ts"
|
|
32
30
|
},
|
|
33
31
|
"publishConfig": {
|
|
34
|
-
"access": "public"
|
|
32
|
+
"access": "public",
|
|
33
|
+
"main": "./dist/index.cjs",
|
|
34
|
+
"module": "./dist/index.js",
|
|
35
|
+
"types": "./dist/index.d.ts",
|
|
36
|
+
"exports": {
|
|
37
|
+
".": {
|
|
38
|
+
"types": "./dist/index.d.ts",
|
|
39
|
+
"import": "./dist/index.js",
|
|
40
|
+
"require": "./dist/index.cjs"
|
|
41
|
+
},
|
|
42
|
+
"./guardrails": {
|
|
43
|
+
"types": "./dist/guardrails.d.ts",
|
|
44
|
+
"import": "./dist/guardrails.js",
|
|
45
|
+
"require": "./dist/guardrails.cjs"
|
|
46
|
+
},
|
|
47
|
+
"./schema": {
|
|
48
|
+
"types": "./dist/schema.d.ts",
|
|
49
|
+
"import": "./dist/schema.js",
|
|
50
|
+
"require": "./dist/schema.cjs"
|
|
51
|
+
}
|
|
52
|
+
}
|
|
35
53
|
},
|
|
36
54
|
"files": [
|
|
37
55
|
"dist",
|
|
38
56
|
"README.md",
|
|
39
57
|
"LICENSE"
|
|
40
58
|
],
|
|
59
|
+
"scripts": {
|
|
60
|
+
"build": "tsup",
|
|
61
|
+
"lint": "biome check .",
|
|
62
|
+
"prepack": "tsup",
|
|
63
|
+
"spell": "cspell --no-progress .",
|
|
64
|
+
"test": "vitest run",
|
|
65
|
+
"typecheck": "tsc --noEmit"
|
|
66
|
+
},
|
|
41
67
|
"dependencies": {
|
|
42
68
|
"zod": "^3.25.17"
|
|
43
69
|
},
|
|
44
70
|
"devDependencies": {
|
|
45
71
|
"@biomejs/biome": "2.4.15",
|
|
72
|
+
"@commitlint/cli": "^21.2.3",
|
|
73
|
+
"@commitlint/config-conventional": "^21.2.3",
|
|
74
|
+
"@semantic-release/changelog": "^7.0.0",
|
|
75
|
+
"@semantic-release/exec": "^7.1.0",
|
|
76
|
+
"@semantic-release/git": "^11.0.1",
|
|
46
77
|
"@types/node": "^25.9.1",
|
|
78
|
+
"conventional-changelog-conventionalcommits": "^9.1.0",
|
|
47
79
|
"cspell": "^8.19.4",
|
|
80
|
+
"semantic-release": "^25.0.9",
|
|
48
81
|
"tsup": "^8.3.5",
|
|
49
82
|
"typescript": "^6.0.3",
|
|
50
83
|
"vitest": "^4.1.7"
|
|
51
84
|
},
|
|
52
85
|
"engines": {
|
|
53
86
|
"node": ">=22.13"
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
"build": "tsup",
|
|
57
|
-
"lint": "biome check .",
|
|
58
|
-
"spell": "cspell --no-progress .",
|
|
59
|
-
"test": "vitest run",
|
|
60
|
-
"typecheck": "tsc --noEmit"
|
|
61
|
-
},
|
|
62
|
-
"module": "./dist/index.js",
|
|
63
|
-
"types": "./dist/index.d.ts"
|
|
64
|
-
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/schema.ts"],"sourcesContent":["/**\n * The guardrails rule format — self-contained, and deliberately so.\n *\n * This file defines the rule format and imports nothing but zod, so the package\n * builds on its own. The condition and match shapes mirror the evaluator's rather\n * than importing them; a change to either has to be made in both places.\n *\n * A rule carries `defaultAction` (what the guard does when it matches) and no\n * `version`; the package version is the corpus version.\n */\n\nimport { z } from \"zod\";\n\n// ── Severity ────────────────────────────────────────────────────────────────\n\n/**\n * The five severities, in order, most→least severe.\n *\n * `info` earns its place: seven of the eleven packs default to `ask`/`warn`, and a\n * warn-only rule labelled `low` overstates itself.\n *\n * Severity says how serious a match is. This package maps it to nothing else,\n * including cost: the guard prints no currency.\n */\nexport const SEVERITIES = [\"critical\", \"high\", \"medium\", \"low\", \"info\"] as const;\n\n/** How dangerous the thing a rule catches is. An authoring signal, not a price. */\nexport const SeveritySchema = z.enum(SEVERITIES);\n\n// ── Actions ─────────────────────────────────────────────────────────────────\n\n/**\n * What the guard does when a rule matches.\n *\n * The guard maps these onto Claude Code's `PreToolUse` verdicts:\n * `block` → deny, `require_approval` → ask, `warn` → allow-but-recorded.\n */\nexport const ACTIONS = [\"block\", \"require_approval\", \"warn\"] as const;\n\n/** The action a rule takes by default, before any user override. */\nexport const ActionSchema = z.enum(ACTIONS);\n\n// ── detail_matches: regex limits, mirrored from the engine ───────────────────\n\n/** Longest accepted `detail_matches` pattern. Long enough for any real rule. */\nexport const DETAIL_MATCHES_MAX_PATTERN_LENGTH = 200;\n\n/** Most `detail_matches` patterns allowed on one condition (they are ORed). */\nexport const DETAIL_MATCHES_MAX_PATTERNS = 10;\n\n/**\n * Reject a regex that can backtrack catastrophically, at PARSE time.\n *\n * Node has no regex timeout, so the only real bounds are a non-backtracking\n * engine (RE2 — a runtime dependency deliberately not taken) or a syntactic\n * restriction. This is the syntactic one: it rejects **star height >= 2**, an\n * unbounded quantifier applied to a group that itself contains an unbounded\n * quantifier — `(a+)+`, `(a*)*`, `(\\s+x?)+` — the shape behind essentially every\n * practical ReDoS.\n *\n * The guard's hook has a 10s Claude Code timeout, no internal watchdog, and it\n * **fails open**: a pattern that backtracks does not merely make enforcement slow,\n * it lets the action through. A slow rule in the guard is a disabled rule.\n *\n * HONEST LIMIT: this is a bound, not a proof. Star height 1 can still be\n * quadratic (`(a|a)*`), which is slow but not exponential, and is acceptable\n * against the length cap above. A hard guarantee needs RE2.\n *\n * @param source - The regex body (no delimiters, no flags).\n * @returns `true` when the pattern nests unbounded quantifiers.\n */\nexport function hasNestedUnboundedQuantifier(source: string): boolean {\n /** Is `source[i]` an unbounded quantifier (`*`, `+`, or `{n,}`)? */\n const unboundedQuantifierAt = (s: string, i: number): boolean => {\n const ch = s[i];\n if (ch === \"*\" || ch === \"+\") return true;\n if (ch !== \"{\") return false;\n const close = s.indexOf(\"}\", i);\n // `{n,}` is unbounded; `{n}` and `{n,m}` are not.\n return close !== -1 && /^\\{\\d*,\\}$/.test(s.slice(i, close + 1));\n };\n\n /** Does `body` contain an unbounded quantifier outside a character class? */\n const containsUnbounded = (body: string): boolean => {\n let inClass = false;\n for (let i = 0; i < body.length; i++) {\n const ch = body[i];\n if (ch === \"\\\\\") {\n i++;\n continue;\n }\n if (inClass) {\n if (ch === \"]\") inClass = false;\n continue;\n }\n if (ch === \"[\") {\n inClass = true;\n continue;\n }\n if (unboundedQuantifierAt(body, i)) return true;\n }\n return false;\n };\n\n const groupStarts: number[] = [];\n let inClass = false;\n for (let i = 0; i < source.length; i++) {\n const ch = source[i];\n if (ch === \"\\\\\") {\n i++; // skip the escaped char — `\\(` is a literal, not a group\n continue;\n }\n if (inClass) {\n if (ch === \"]\") inClass = false;\n continue;\n }\n if (ch === \"[\") {\n inClass = true;\n continue;\n }\n if (ch === \"(\") {\n groupStarts.push(i);\n continue;\n }\n if (ch === \")\") {\n const start = groupStarts.pop();\n if (start === undefined) continue; // unbalanced — the RegExp compile catches it\n // Quantified group? Then its body must not itself repeat unboundedly.\n if (unboundedQuantifierAt(source, i + 1) && containsUnbounded(source.slice(start + 1, i))) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * One `detail_matches` pattern: compilable, length-capped, and free of nested\n * unbounded quantifiers. The engine compiles these with `i` and never `g`/`y` —\n * a global regex carries `lastIndex` between calls and would intermittently miss.\n */\nconst DetailMatchPatternSchema = z\n .string()\n .min(1)\n .max(DETAIL_MATCHES_MAX_PATTERN_LENGTH)\n .superRefine((pattern, ctx) => {\n try {\n new RegExp(pattern, \"i\");\n } catch (error) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `detail_matches: not a valid regular expression (${\n error instanceof Error ? error.message : \"unknown error\"\n })`,\n });\n return;\n }\n if (hasNestedUnboundedQuantifier(pattern)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message:\n \"detail_matches: nested unbounded quantifier (e.g. `(a+)+`) can backtrack catastrophically; rewrite without repeating a repeating group\",\n });\n }\n });\n\n// ── Match conditions ────────────────────────────────────────────────────────\n\n/**\n * One condition matched against a tool call.\n *\n * - `kind`: required. The span kind, e.g. `execute_tool`. Case-insensitive.\n * - `label`: optional. The tool name — a case-insensitive GLOB, so\n * `mcp__chrome__*` and `{Bash,PowerShell}` are one condition rather than a\n * list that rots. A plain label has no glob character and matches exactly.\n * - `detail_contains`: optional. Substrings that must ALL appear (AND).\n * **CASE-SENSITIVE**, and deliberately: `AKIA`, `ghp_`, `sk_live_` and the\n * upper-case `TRUNCATE` arm are rules where case IS the signal. Author\n * case-insensitive text matches with `detail_matches` instead.\n * - `detail_matches`: optional. Regex patterns against the same text; at least\n * one must match (OR, unlike `detail_contains`). Case-insensitive.\n * - `file_glob`: optional. Case-insensitive glob against the file path.\n *\n * ── Two engine fields are deliberately absent ────────────────────────────────\n *\n * `numeric` is BANNED. At guard decision time `tokens`,\n * `cachedTokens` and `durationMs` are all 0, because the action has not run yet.\n * `gt` is therefore always false — the rule can never fire — and, worse, **`lt`\n * is always true, so the rule fires on every single command.** Omitting the key\n * from a `.strict()` object makes that a parse error rather than a lint finding.\n *\n * `scope` is BANNED for the same class of reason and is absent from the rule\n * envelope below: `agent_in` compares literally against an agent id that is\n * always a UUID, never the string `\"claude-code\"`, so a scoped rule matches\n * nothing, forever, silently.\n *\n * ── The third ban needs an actual check ──────────────────────────────────────\n *\n * A command matcher (`detail_contains` / `detail_matches`) and a file matcher\n * (`file_glob`) in ONE condition can never both be satisfied: the guard's mapper\n * is an if/else chain, so no real tool call ever carries both a command and a\n * file path. This schema refuses the combination.\n */\nexport const MatchConditionSchema = z\n .object({\n kind: z.string().min(1),\n label: z.string().min(1).optional(),\n detail_contains: z.array(z.string().min(1)).min(1).optional(),\n detail_matches: z\n .array(DetailMatchPatternSchema)\n .min(1)\n .max(DETAIL_MATCHES_MAX_PATTERNS)\n .optional(),\n file_glob: z.string().min(1).optional(),\n })\n .strict()\n .superRefine((condition, ctx) => {\n const hasCommandMatcher =\n condition.detail_contains !== undefined || condition.detail_matches !== undefined;\n if (hasCommandMatcher && condition.file_glob !== undefined) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message:\n \"a condition may not combine a command matcher (detail_contains / detail_matches) with a file matcher (file_glob): no real tool call carries both, so the condition can never match. Split it into two conditions under any_of.\",\n });\n }\n });\n\n/**\n * Match composition — conditions combined with `any_of` (OR), `all_of` (AND)\n * and/or `none_of` (negation).\n *\n * At least one of `any_of` or `all_of` must be present. `none_of` is an optional\n * refinement that CANNOT stand alone: a match must positively select calls\n * before excluding some. A pure-negation match is satisfied by every\n * non-matching call and, at `block`, would deny everything the agent does.\n */\nexport const MatchSchema = z\n .object({\n any_of: z.array(MatchConditionSchema).min(1).optional(),\n all_of: z.array(MatchConditionSchema).min(1).optional(),\n none_of: z.array(MatchConditionSchema).min(1).optional(),\n })\n .strict()\n .refine((data) => data.any_of !== undefined || data.all_of !== undefined, {\n message: \"At least one of 'any_of' or 'all_of' must be provided\",\n });\n\n// ── Fixtures ────────────────────────────────────────────────────────────────\n\n/**\n * The tools a fixture may name. Free-form on purpose — the guard's matcher grows\n * (`mcp__*` alone is unbounded) and a closed enum here would reject a valid rule\n * for a tool this package has not heard of yet.\n */\nconst FixtureToolSchema = z.string().min(1);\n\n/**\n * A fixture on the COMMAND channel: `Bash`, `PowerShell`, `WebSearch` (its\n * query is ordinary text), and `mcp__*` (its serialized input).\n */\nconst CommandFixtureSchema = z\n .object({ tool: FixtureToolSchema, command: z.string().min(1) })\n .strict();\n\n/** A fixture on the FILE channel: `Edit`, `Write`, `Read`, `NotebookEdit`. */\nconst FileFixtureSchema = z\n .object({ tool: FixtureToolSchema, file_path: z.string().min(1) })\n .strict();\n\n/**\n * One fixture: a tool call this rule must match, or must not.\n *\n * A bare string is shorthand for `{ tool: \"Bash\", command: \"<string>\" }`, which\n * covers most rules and keeps them terse. Anything else is an object with a\n * `tool` plus **exactly one** of `command` or `file_path` — the two channels.\n * `.strict()` on each variant is what makes \"exactly one\" true: a\n * `command` object carrying a `file_path` matches neither variant.\n *\n * The parse output is always normalized to the object form, so the harness has\n * exactly one shape to feed the evaluator.\n *\n * ── There is no `url` channel ─────────────────────────────────────────────────\n *\n * **The evaluator cannot see a URL**: the only two attribute keys any matcher\n * reads are `detail` and `file_path`, and there is no `url` field in the condition\n * schema. A value written to `url` would be read by nothing, so a `WebFetch` rule\n * would match nothing, silently — the same failure `scope` is banned for. There\n * are no website rules and `WebFetch` is not intercepted; `WebSearch` is, because\n * its query is text on the command channel.\n *\n * A `url` key therefore fails to parse rather than becoming a fixture that tests\n * nothing. `__tests__/schema.test.ts` pins that.\n */\nexport const FixtureSchema = z.union([\n z\n .string()\n .min(1)\n .transform((command) => ({ tool: \"Bash\" as const, command })),\n CommandFixtureSchema,\n FileFixtureSchema,\n]);\n\n/**\n * The two directions every rule must prove, through the real evaluator.\n *\n * **`block` means \"this rule MUST match\"; `allow` means \"this rule MUST NOT\n * match\".** They are not verdicts. Seven of the eleven packs default to `ask` or\n * `warn`, and `warn` folds into an allow verdict, so reading `block` as \"the\n * guard denies\" would fail every `warn` rule and make the negative fixture\n * vacuous for them.\n *\n * Both are `.min(1)`: CI only has to fail on a rule missing a\n * negative fixture, but requiring it here moves that failure to authoring time,\n * where it costs a keystroke instead of a pull-request round trip.\n */\nexport const FixturesSchema = z\n .object({\n block: z.array(FixtureSchema).min(1),\n allow: z.array(FixtureSchema).min(1),\n })\n .strict();\n\n// ── The rule ────────────────────────────────────────────────────────────────\n\n/**\n * One published rule.\n *\n * `.strict()` rejects any key not declared here, so an unknown field fails to parse\n * rather than riding along into the published package.\n *\n * `description` carries the rule's COVERAGE LIMITS, verbatim — e.g. that an\n * `rm -rf` rule misses `rm -fr`. It is a convention rather than a schema\n * constraint, because no validator can tell a real limit from a sentence shaped\n * like one.\n */\nexport const RuleSchema = z\n .object({\n /** Stable: a rule id is never renamed. */\n id: z.string().min(1),\n /** The pack this rule belongs to. Validated against `PACKS` by the registry. */\n category: z.string().min(1),\n severity: SeveritySchema,\n defaultAction: ActionSchema,\n title: z.string().min(1),\n description: z.string().min(1),\n match: MatchSchema,\n fixtures: FixturesSchema,\n })\n .strict();\n\n// ── Types ───────────────────────────────────────────────────────────────────\n\n/** How dangerous the caught action is. Never a price. */\nexport type Severity = (typeof SEVERITIES)[number];\n\n/** What the guard does on a match. */\nexport type Action = (typeof ACTIONS)[number];\n\n/** One condition matched against a tool call. */\nexport type MatchCondition = z.infer<typeof MatchConditionSchema>;\n\n/** A composed match — `any_of` / `all_of` / `none_of`. */\nexport type Match = z.infer<typeof MatchSchema>;\n\n/** A fixture as authored: a bare command string, or a tagged single-channel object. */\nexport type FixtureInput = z.input<typeof FixtureSchema>;\n\n/** A fixture after parsing — always the tagged object form. */\nexport type Fixture = z.output<typeof FixtureSchema>;\n\n/** The must-match / must-not-match pair every rule ships. */\nexport type Fixtures = z.infer<typeof FixturesSchema>;\n\n/** One published rule, as authored. */\nexport type RuleInput = z.input<typeof RuleSchema>;\n\n/** One published rule, parsed and normalized. */\nexport type Rule = z.output<typeof RuleSchema>;\n\n// ── Parsing ─────────────────────────────────────────────────────────────────\n\n/**\n * Validate a rule from unknown input.\n *\n * It answers \"is this a well-formed rule?\" — it does NOT answer \"does this rule\n * actually fire on the command you think it does.\" That needs the evaluator, which\n * is not part of this package.\n *\n * @param input - Unknown input, e.g. parsed JSON or a rule module's default export.\n * @returns A Zod SafeParseReturnType — check `.success` before reading `.data`.\n */\nexport function parseRule(input: unknown): z.SafeParseReturnType<unknown, Rule> {\n return RuleSchema.safeParse(input);\n}\n\n/**\n * Parse a rule, or throw with the reason.\n *\n * Used by rule modules themselves via {@link defineRule}, so an authoring\n * mistake fails at import — which is to say, at test time — rather than\n * surviving into a corpus that only validates what it remembers to check.\n */\nexport function parseRuleOrThrow(input: unknown): Rule {\n const result = parseRule(input);\n if (!result.success) {\n const id =\n typeof input === \"object\" && input !== null && \"id\" in input\n ? String((input as { id: unknown }).id)\n : \"<unknown id>\";\n throw new Error(`invalid guardrails rule ${id}: ${result.error.message}`);\n }\n return result.data;\n}\n\n/**\n * Declare a rule. Validates at module load, so a malformed rule cannot reach the\n * registry — the corpus is only as trustwor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