@agenttrail/guardrails 0.2.2 → 0.2.5
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 +132 -116
- package/dist/{chunk-GNN4TGRY.js → chunk-SLJLCAZK.js} +306 -33
- package/dist/chunk-SLJLCAZK.js.map +1 -0
- package/dist/chunk-T6MJIV52.js +72 -0
- package/dist/chunk-T6MJIV52.js.map +1 -0
- package/dist/{chunk-FTTMZCDH.js → chunk-U7KZ447W.js} +65 -4
- package/dist/chunk-U7KZ447W.js.map +1 -0
- package/dist/guardrails.cjs +374 -32
- package/dist/guardrails.cjs.map +1 -1
- package/dist/guardrails.d.cts +60 -65
- package/dist/guardrails.d.ts +60 -65
- package/dist/guardrails.js +17 -1
- package/dist/index.cjs +433 -35
- 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 +20 -2
- package/dist/schema-B2pYoi9Z.d.cts +951 -0
- package/dist/schema-B2pYoi9Z.d.ts +951 -0
- package/dist/schema.cjs +91 -3
- package/dist/schema.cjs.map +1 -1
- package/dist/schema.d.cts +2 -892
- package/dist/schema.d.ts +2 -892
- package/dist/schema.js +4 -1
- package/package.json +2 -2
- package/dist/chunk-FTTMZCDH.js.map +0 -1
- package/dist/chunk-GNN4TGRY.js.map +0 -1
package/dist/schema.cjs
CHANGED
|
@@ -28,6 +28,7 @@ __export(schema_exports, {
|
|
|
28
28
|
FixturesSchema: () => FixturesSchema,
|
|
29
29
|
MatchConditionSchema: () => MatchConditionSchema,
|
|
30
30
|
MatchSchema: () => MatchSchema,
|
|
31
|
+
OwaspIdsSchema: () => OwaspIdsSchema,
|
|
31
32
|
RuleSchema: () => RuleSchema,
|
|
32
33
|
SEVERITIES: () => SEVERITIES,
|
|
33
34
|
SeveritySchema: () => SeveritySchema,
|
|
@@ -38,6 +39,38 @@ __export(schema_exports, {
|
|
|
38
39
|
});
|
|
39
40
|
module.exports = __toCommonJS(schema_exports);
|
|
40
41
|
var import_zod = require("zod");
|
|
42
|
+
|
|
43
|
+
// src/owasp.ts
|
|
44
|
+
var OWASP_IDS = [
|
|
45
|
+
"ASI01",
|
|
46
|
+
"ASI02",
|
|
47
|
+
"ASI03",
|
|
48
|
+
"ASI04",
|
|
49
|
+
"ASI05",
|
|
50
|
+
"ASI06",
|
|
51
|
+
"ASI07",
|
|
52
|
+
"ASI08",
|
|
53
|
+
"ASI09",
|
|
54
|
+
"ASI10",
|
|
55
|
+
"LLM01",
|
|
56
|
+
"LLM02",
|
|
57
|
+
"LLM03",
|
|
58
|
+
"LLM04",
|
|
59
|
+
"LLM05",
|
|
60
|
+
"LLM06",
|
|
61
|
+
"LLM07",
|
|
62
|
+
"LLM08",
|
|
63
|
+
"LLM09",
|
|
64
|
+
"LLM10"
|
|
65
|
+
];
|
|
66
|
+
function isOwaspId(value) {
|
|
67
|
+
return typeof value === "string" && OWASP_IDS.includes(value);
|
|
68
|
+
}
|
|
69
|
+
function owaspIndex(id) {
|
|
70
|
+
return OWASP_IDS.indexOf(id);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// src/schema.ts
|
|
41
74
|
var SEVERITIES = ["critical", "high", "medium", "low", "info"];
|
|
42
75
|
var SeveritySchema = import_zod.z.enum(SEVERITIES);
|
|
43
76
|
var ACTIONS = ["block", "require_approval", "warn"];
|
|
@@ -153,15 +186,70 @@ var FixturesSchema = import_zod.z.object({
|
|
|
153
186
|
block: import_zod.z.array(FixtureSchema).min(1),
|
|
154
187
|
allow: import_zod.z.array(FixtureSchema).min(1)
|
|
155
188
|
}).strict();
|
|
189
|
+
function unknownOwaspIdMessage(value) {
|
|
190
|
+
const shown = typeof value === "string" ? `\`${value}\`` : JSON.stringify(value);
|
|
191
|
+
if (typeof value === "string") {
|
|
192
|
+
const fixed = value.trim().toUpperCase().replace(/:\d{4}$/, "");
|
|
193
|
+
if (isOwaspId(fixed)) {
|
|
194
|
+
return `owasp: ${shown} is not an OWASP id. Use the upper-case id without a suffix: \`${fixed}\``;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return `owasp: ${shown} is not an OWASP id. Use an id from the OWASP Top 10 for Agentic Applications (ASI01 to ASI10) or for LLM Applications 2026 (LLM01 to LLM10)`;
|
|
198
|
+
}
|
|
199
|
+
var OwaspIdsSchema = import_zod.z.array(import_zod.z.unknown()).superRefine((ids, ctx) => {
|
|
200
|
+
if (ids.length === 0) {
|
|
201
|
+
ctx.addIssue({
|
|
202
|
+
code: import_zod.z.ZodIssueCode.custom,
|
|
203
|
+
message: "owasp: omit the field rather than giving an empty list"
|
|
204
|
+
});
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
const seen = /* @__PURE__ */ new Set();
|
|
208
|
+
let clean = true;
|
|
209
|
+
ids.forEach((id, i) => {
|
|
210
|
+
if (!isOwaspId(id)) {
|
|
211
|
+
clean = false;
|
|
212
|
+
ctx.addIssue({
|
|
213
|
+
code: import_zod.z.ZodIssueCode.custom,
|
|
214
|
+
path: [i],
|
|
215
|
+
message: unknownOwaspIdMessage(id)
|
|
216
|
+
});
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
if (seen.has(id)) {
|
|
220
|
+
clean = false;
|
|
221
|
+
ctx.addIssue({
|
|
222
|
+
code: import_zod.z.ZodIssueCode.custom,
|
|
223
|
+
path: [i],
|
|
224
|
+
message: `owasp: \`${id}\` is listed twice`
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
seen.add(id);
|
|
228
|
+
});
|
|
229
|
+
if (!clean) return;
|
|
230
|
+
const indexes = ids.map(owaspIndex);
|
|
231
|
+
if (indexes.some((at, i) => i > 0 && at < (indexes[i - 1] ?? at))) {
|
|
232
|
+
ctx.addIssue({
|
|
233
|
+
code: import_zod.z.ZodIssueCode.custom,
|
|
234
|
+
message: "owasp: out of order; list ASI ids before LLM ids, each ascending"
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
}).transform((ids) => ids);
|
|
156
238
|
var RuleSchema = import_zod.z.object({
|
|
157
|
-
/** Stable: a
|
|
239
|
+
/** Stable: a guardrail id is never renamed. */
|
|
158
240
|
id: import_zod.z.string().min(1),
|
|
159
|
-
/** The pack this
|
|
241
|
+
/** The pack this guardrail belongs to. Validated against `PACKS` by the registry. */
|
|
160
242
|
category: import_zod.z.string().min(1),
|
|
161
243
|
severity: SeveritySchema,
|
|
162
244
|
defaultAction: ActionSchema,
|
|
163
245
|
title: import_zod.z.string().min(1),
|
|
164
246
|
description: import_zod.z.string().min(1),
|
|
247
|
+
/**
|
|
248
|
+
* The OWASP risks this guardrail addresses. Optional: a guardrail that cites none omits it. An id is
|
|
249
|
+
* never a claim that the guardrail covers the whole risk, only that it acts where the risk turns
|
|
250
|
+
* into a command or a file change.
|
|
251
|
+
*/
|
|
252
|
+
owasp: OwaspIdsSchema.optional(),
|
|
165
253
|
match: MatchSchema,
|
|
166
254
|
fixtures: FixturesSchema
|
|
167
255
|
}).strict();
|
|
@@ -172,7 +260,7 @@ function parseRuleOrThrow(input) {
|
|
|
172
260
|
const result = parseRule(input);
|
|
173
261
|
if (!result.success) {
|
|
174
262
|
const id = typeof input === "object" && input !== null && "id" in input ? String(input.id) : "<unknown id>";
|
|
175
|
-
throw new Error(`invalid
|
|
263
|
+
throw new Error(`invalid guardrail ${id}: ${result.error.message}`);
|
|
176
264
|
}
|
|
177
265
|
return result.data;
|
|
178
266
|
}
|
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/**\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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;AAChB;AAMO,SAAS,WAAW,MAAuB;AAChD,SAAO,iBAAiB,IAAI;AAC9B;","names":["inClass"]}
|
|
1
|
+
{"version":3,"sources":["../src/schema.ts","../src/owasp.ts"],"sourcesContent":["/**\n * The guardrail format — self-contained, and deliberately so.\n *\n * This file defines the guardrail format and imports nothing but zod and the OWASP id list\n * (`./owasp.ts`, plain data), so the package builds on its own. The condition and match\n * shapes mirror the evaluator's rather than importing them; a change to either has to be\n * made in both places.\n *\n * A guardrail 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\";\nimport { isOwaspId, type OwaspId, owaspIndex } from \"./owasp.js\";\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 guardrail 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 guardrail 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 guardrail 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 guardrail 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 guardrail; 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 guardrail in the guard is a disabled guardrail.\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 guardrails 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 guardrail can never fire — and, worse, **`lt`\n * is always true, so the guardrail 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 guardrail\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 guardrail 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 guardrail\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 guardrail must match, or must not.\n *\n * A bare string is shorthand for `{ tool: \"Bash\", command: \"<string>\" }`, which\n * covers most guardrails 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` guardrail\n * would match nothing, silently — the same failure `scope` is banned for. There\n * are no website guardrails 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 guardrail must prove, through the real evaluator.\n *\n * **`block` means \"this guardrail MUST match\"; `allow` means \"this guardrail 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` guardrail and make the negative fixture\n * vacuous for them.\n *\n * Both are `.min(1)`: CI only has to fail on a guardrail 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// ── OWASP ids ───────────────────────────────────────────────────────────────\n\n/**\n * Explain why one entry of an `owasp` list is not an id. A real id written in lower case or with\n * the list's year suffix (`asi02`, `LLM06:2026`) gets the exact spelling to use instead.\n */\nfunction unknownOwaspIdMessage(value: unknown): string {\n const shown = typeof value === \"string\" ? `\\`${value}\\`` : JSON.stringify(value);\n if (typeof value === \"string\") {\n const fixed = value\n .trim()\n .toUpperCase()\n .replace(/:\\d{4}$/, \"\");\n if (isOwaspId(fixed)) {\n return `owasp: ${shown} is not an OWASP id. Use the upper-case id without a suffix: \\`${fixed}\\``;\n }\n }\n return `owasp: ${shown} is not an OWASP id. Use an id from the OWASP Top 10 for Agentic Applications (ASI01 to ASI10) or for LLM Applications 2026 (LLM01 to LLM10)`;\n}\n\n/**\n * The OWASP risks a guardrail addresses, e.g. `[\"ASI02\", \"LLM03\"]`.\n *\n * - Every entry is one of `OWASP_IDS`, spelled exactly: upper-case, no `:2026` suffix.\n * - No id twice, and the list is in `OWASP_IDS` order (ASI ids before LLM ids, each ascending),\n * so a guardrail's ids have one spelling and a diff of them is a diff of meaning.\n * - Not empty. A guardrail that cites no risk omits the field.\n *\n * The parsed type is `OwaspId[]`, so a typo is a compile error for a TypeScript author too.\n * Each problem is reported at the entry it concerns (`owasp.<i>`), or at `owasp` for order and\n * emptiness, in words a person can act on, because `guardrails validate` prints them.\n */\nexport const OwaspIdsSchema = z\n .array(z.unknown())\n .superRefine((ids, ctx) => {\n if (ids.length === 0) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"owasp: omit the field rather than giving an empty list\",\n });\n return;\n }\n const seen = new Set<string>();\n let clean = true;\n ids.forEach((id, i) => {\n if (!isOwaspId(id)) {\n clean = false;\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [i],\n message: unknownOwaspIdMessage(id),\n });\n return;\n }\n if (seen.has(id)) {\n clean = false;\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [i],\n message: `owasp: \\`${id}\\` is listed twice`,\n });\n }\n seen.add(id);\n });\n if (!clean) return;\n const indexes = (ids as OwaspId[]).map(owaspIndex);\n if (indexes.some((at, i) => i > 0 && at < (indexes[i - 1] ?? at))) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"owasp: out of order; list ASI ids before LLM ids, each ascending\",\n });\n }\n })\n .transform((ids) => ids as OwaspId[]) as unknown as z.ZodType<OwaspId[], z.ZodTypeDef, OwaspId[]>;\n// The cast fixes the INPUT type as well as the output: `z.array(z.unknown())` would make\n// `RuleInput[\"owasp\"]` `unknown[]`, so a typo in `defineRule({ owasp: [...] })` would compile and\n// only fail at load. The runtime checks above are unchanged and still run on any input.\n\n// ── The guardrail ───────────────────────────────────────────────────────────\n\n/**\n * One published guardrail.\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 guardrail's COVERAGE LIMITS, verbatim — e.g. that an\n * `rm -rf` guardrail 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 guardrail id is never renamed. */\n id: z.string().min(1),\n /** The pack this guardrail 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 /**\n * The OWASP risks this guardrail addresses. Optional: a guardrail that cites none omits it. An id is\n * never a claim that the guardrail covers the whole risk, only that it acts where the risk turns\n * into a command or a file change.\n */\n owasp: OwaspIdsSchema.optional(),\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 guardrail ships. */\nexport type Fixtures = z.infer<typeof FixturesSchema>;\n\n/** One published guardrail, as authored. */\nexport type RuleInput = z.input<typeof RuleSchema>;\n\n/** One published guardrail, parsed and normalized. */\nexport type Rule = z.output<typeof RuleSchema>;\n\n// ── Parsing ─────────────────────────────────────────────────────────────────\n\n/**\n * Validate a guardrail from unknown input.\n *\n * It answers \"is this a well-formed guardrail?\" — it does NOT answer \"does this guardrail\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 guardrail 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 guardrail, or throw with the reason.\n *\n * Used by guardrail 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 guardrail ${id}: ${result.error.message}`);\n }\n return result.data;\n}\n\n/**\n * Declare a guardrail. Validates at module load, so a malformed guardrail 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","/**\n * The two OWASP lists a guardrail's `owasp` field may cite, as plain data.\n *\n * No zod here, so the corpus entry (`./rules.ts`) can re-export it and stay validator-free.\n * `schema.ts` validates a guardrail's `owasp` field against `OWASP_IDS`.\n *\n * - OWASP Top 10 for Agentic Applications (v1.0, the 2026 edition): ASI01 to ASI10.\n * - OWASP Top 10 for LLM Applications 2026 (v1.0): LLM01 to LLM10.\n *\n * An id names the risk a guardrail addresses at the point where it becomes a command or a file\n * change. It is never a claim that the guardrail covers the whole risk.\n */\n\n/** Every id a guardrail may cite, in list order: the agentic list first, then the LLM list. */\nexport const OWASP_IDS = [\n \"ASI01\",\n \"ASI02\",\n \"ASI03\",\n \"ASI04\",\n \"ASI05\",\n \"ASI06\",\n \"ASI07\",\n \"ASI08\",\n \"ASI09\",\n \"ASI10\",\n \"LLM01\",\n \"LLM02\",\n \"LLM03\",\n \"LLM04\",\n \"LLM05\",\n \"LLM06\",\n \"LLM07\",\n \"LLM08\",\n \"LLM09\",\n \"LLM10\",\n] as const;\n\n/** One OWASP risk id, e.g. `ASI02` or `LLM06`. */\nexport type OwaspId = (typeof OWASP_IDS)[number];\n\n/** One risk on an OWASP list. */\nexport interface OwaspRisk {\n readonly id: OwaspId;\n readonly title: string;\n}\n\n/** OWASP Top 10 for Agentic Applications, v1.0. */\nexport const OWASP_AGENTIC: readonly OwaspRisk[] = [\n { id: \"ASI01\", title: \"Agent Goal Hijack\" },\n { id: \"ASI02\", title: \"Tool Misuse and Exploitation\" },\n { id: \"ASI03\", title: \"Identity and Privilege Abuse\" },\n { id: \"ASI04\", title: \"Agentic Supply Chain Vulnerabilities\" },\n { id: \"ASI05\", title: \"Unexpected Code Execution\" },\n { id: \"ASI06\", title: \"Memory and Context Poisoning\" },\n { id: \"ASI07\", title: \"Insecure Inter-Agent Communication\" },\n { id: \"ASI08\", title: \"Cascading Failures\" },\n { id: \"ASI09\", title: \"Human-Agent Trust Exploitation\" },\n { id: \"ASI10\", title: \"Rogue Agents\" },\n];\n\n/** OWASP Top 10 for LLM Applications 2026, v1.0. */\nexport const OWASP_LLM: readonly OwaspRisk[] = [\n { id: \"LLM01\", title: \"Prompt Injection\" },\n { id: \"LLM02\", title: \"Sensitive Information Disclosure\" },\n { id: \"LLM03\", title: \"Excessive Agency\" },\n { id: \"LLM04\", title: \"Supply Chain\" },\n { id: \"LLM05\", title: \"Data and Model Poisoning\" },\n { id: \"LLM06\", title: \"Unbounded Consumption\" },\n { id: \"LLM07\", title: \"Misinformation\" },\n { id: \"LLM08\", title: \"Hidden Context Exposure\" },\n { id: \"LLM09\", title: \"Vector and Embedding Weaknesses\" },\n { id: \"LLM10\", title: \"Improper Output Handling\" },\n];\n\n/** Where each list is published. */\nexport const OWASP_SOURCES = {\n agentic: \"https://genai.owasp.org/resource/owasp-top-10-for-agentic-applications-for-2026/\",\n llm: \"https://genai.owasp.org/resource/owasp-genai-llm-top-10-2026/\",\n} as const;\n\n/** True when `value` is one of `OWASP_IDS`, spelled exactly (upper-case, no suffix). */\nexport function isOwaspId(value: unknown): value is OwaspId {\n return typeof value === \"string\" && (OWASP_IDS as readonly string[]).includes(value);\n}\n\n/** The id's position in `OWASP_IDS`, or -1. The order a guardrail must list its ids in. */\nexport function owaspIndex(id: string): number {\n return (OWASP_IDS as readonly string[]).indexOf(id);\n}\n\n/** The risk's title, e.g. `owaspTitle(\"ASI02\")` is \"Tool Misuse and Exploitation\". */\nexport function owaspTitle(id: OwaspId): string {\n const risk = [...OWASP_AGENTIC, ...OWASP_LLM].find((r) => r.id === id);\n // Unreachable for a typed `OwaspId`: the two lists hold every id, which a test pins.\n return risk?.title ?? id;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAYA,iBAAkB;;;ACEX,IAAM,YAAY;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AA8CO,SAAS,UAAU,OAAkC;AAC1D,SAAO,OAAO,UAAU,YAAa,UAAgC,SAAS,KAAK;AACrF;AAGO,SAAS,WAAW,IAAoB;AAC7C,SAAQ,UAAgC,QAAQ,EAAE;AACpD;;;AD9DO,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,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