@nulladrift/core 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,18 +1,4 @@
1
- import { a as JsonObject, J as JsonValue } from '../types-lvJ3uBbs.js';
2
-
3
- /**
4
- * Just enough JSON Schema to see through the indirection servers actually use.
5
- *
6
- * Two parts of this tool have to look inside a tool's `inputSchema`: the widening heuristic and
7
- * the `x-mcp-header` scan. Both used to read only the literal node in front of them, so a schema
8
- * that put its properties behind `$ref` or `allOf` -- which the generators for Pydantic, Zod and
9
- * most OpenAPI toolchains do by default -- looked empty to both. A widened parameter went out as
10
- * a bare `.changed`, and a parameter newly mirrored into an HTTP header was missed entirely.
11
- *
12
- * This is not a validator. It resolves local `$ref`, flattens `allOf`, and leaves the
13
- * alternation keywords for the caller to branch on. Remote `$ref` is never fetched: an audit
14
- * that reaches out to a URL named by the thing it is auditing is not an audit.
15
- */
1
+ import { J as JsonValue, a as JsonObject } from '../types-lvJ3uBbs.js';
16
2
 
17
3
  /** Depth caps. A hostile or merely recursive schema must not be able to hang the run. */
18
4
  declare const MAX_REF_DEPTH = 32;
@@ -23,6 +9,33 @@ declare const MAX_FACTS = 5000;
23
9
  * one path goes; see `effectiveSchema`.
24
10
  */
25
11
  declare const MAX_RESOLUTIONS = 100000;
12
+ /**
13
+ * Keys every call against one schema may copy between them. `MAX_RESOLUTIONS` is per call, and a
14
+ * walk makes a call for every node it reaches; see `effectiveSchema`. The largest of 92,512 tool
15
+ * schemas in the public registry crawl copies 6,550 keys across the header scan, the capability
16
+ * scan and the widening heuristic together, so this is fifteen times anything published.
17
+ */
18
+ declare const MAX_MERGED_KEYS = 100000;
19
+ /**
20
+ * Starts a walk of `root` with nothing remembered and the whole budget.
21
+ *
22
+ * Every reader that walks a schema starts here, so what one of them spent cannot change what the
23
+ * next one sees. The budget is per schema, and the collector runs the header scan on the very
24
+ * object a fresh reading is later compared with: a budget the scan had used up made the two sides
25
+ * of a comparison read a hostile schema differently, which is a verdict an attacker can steer.
26
+ */
27
+ declare function beginWalk(root: JsonValue): void;
28
+ /**
29
+ * What `allOf` said that one object cannot hold: a second `pattern`, a second schema for the same
30
+ * property. Kept beside the effective schema rather than in it, so a reader that wants only the
31
+ * merged view -- the header scan, whose answer is part of a tool's digest -- reads what it always
32
+ * read, and the widening heuristic can still see a constraint come or go.
33
+ */
34
+ interface Shadowed {
35
+ keywords: Map<string, JsonValue[]>;
36
+ properties: Map<string, JsonValue[]>;
37
+ }
38
+ declare function shadowedIn(effective: JsonObject): Shadowed | undefined;
26
39
  declare function asObject(value: JsonValue | undefined): JsonObject | undefined;
27
40
  /** Resolves a local JSON pointer. Anything with a non-empty URI part is left unresolved. */
28
41
  declare function resolvePointer(root: JsonValue, ref: string): JsonValue | undefined;
@@ -30,15 +43,21 @@ declare function resolvePointer(root: JsonValue, ref: string): JsonValue | undef
30
43
  * The keywords in effect at a node, with `$ref` followed and `allOf` folded in.
31
44
  *
32
45
  * The node's own keywords win over anything it inherits, `properties` are unioned, and
33
- * `required` is the union of every contributor -- which is what `allOf` means. Alternation
34
- * (`anyOf` / `oneOf` / `then` / `else`) is deliberately left in place: a caller that wants to
35
- * treat branches as separate possibilities can, and one that does not is no worse off.
46
+ * `required` is the union of every contributor -- which is what `allOf` means. Bounds, `enum` and
47
+ * `type` are intersected, for the same reason; anything else a later contributor says differently
48
+ * is kept aside (see `shadowedIn`). Alternation (`anyOf` / `oneOf` / `then` / `else`) is
49
+ * deliberately left in place: a caller that wants to treat branches as separate possibilities
50
+ * can, and one that does not is no worse off.
51
+ *
52
+ * The result is shared: callers read it and never write to it.
36
53
  */
37
54
  declare function effectiveSchema(node: JsonValue | undefined, root: JsonValue, seenRefs?: ReadonlySet<string>, depth?: number): JsonObject | undefined;
55
+ /** `Object.entries`, read once per object. */
56
+ declare function entriesOf(object: JsonObject): ReadonlyArray<readonly [string, JsonValue]>;
38
57
  /** The alternation branches at a node, labelled so a caller can key facts by them. */
39
- declare function alternatives(object: JsonObject): Array<{
58
+ declare function alternatives(object: JsonObject): ReadonlyArray<{
40
59
  label: string;
41
60
  schema: JsonValue;
42
61
  }>;
43
62
 
44
- export { MAX_FACTS, MAX_REF_DEPTH, MAX_RESOLUTIONS, MAX_VISIT_DEPTH, alternatives, asObject, effectiveSchema, resolvePointer };
63
+ export { MAX_FACTS, MAX_MERGED_KEYS, MAX_REF_DEPTH, MAX_RESOLUTIONS, MAX_VISIT_DEPTH, type Shadowed, alternatives, asObject, beginWalk, effectiveSchema, entriesOf, resolvePointer, shadowedIn };
@@ -1,21 +1,30 @@
1
1
  import {
2
2
  MAX_FACTS,
3
+ MAX_MERGED_KEYS,
3
4
  MAX_REF_DEPTH,
4
5
  MAX_RESOLUTIONS,
5
6
  MAX_VISIT_DEPTH,
6
7
  alternatives,
7
8
  asObject,
9
+ beginWalk,
8
10
  effectiveSchema,
9
- resolvePointer
10
- } from "../chunk-FVT77BL4.js";
11
+ entriesOf,
12
+ resolvePointer,
13
+ shadowedIn
14
+ } from "../chunk-Z4M6ZRTP.js";
15
+ import "../chunk-SZKRNTJP.js";
11
16
  export {
12
17
  MAX_FACTS,
18
+ MAX_MERGED_KEYS,
13
19
  MAX_REF_DEPTH,
14
20
  MAX_RESOLUTIONS,
15
21
  MAX_VISIT_DEPTH,
16
22
  alternatives,
17
23
  asObject,
24
+ beginWalk,
18
25
  effectiveSchema,
19
- resolvePointer
26
+ entriesOf,
27
+ resolvePointer,
28
+ shadowedIn
20
29
  };
21
30
  //# sourceMappingURL=jsonschema.js.map
@@ -20,8 +20,8 @@ declare function isEscalation(previous: LockedBehavior, next: LockedBehavior): b
20
20
  * because order *is* significant in `prefixItems`, `allOf` and `icons`, and we only reorder where
21
21
  * we can show it is safe.
22
22
  *
23
- * Only where `required` is a keyword: not inside a value (`const`, `default`, `enum`,
24
- * `examples`), and not as the name of a property, which is a schema of its own.
23
+ * Only where `required` is a keyword of a schema: not inside a value (`const`, `default`, `enum`,
24
+ * `examples`, an `x-` extension), and not as the name of a property, which is a schema of its own.
25
25
  */
26
26
  declare function normalizeSchema(value: JsonValue): JsonValue;
27
27
  /**
@@ -37,9 +37,11 @@ declare function normalizeSchema(value: JsonValue): JsonValue;
37
37
  declare function extractHeaderParams(schema: JsonValue): string[];
38
38
  /** How many schema nodes the header scan visits before it stops and says so. */
39
39
  declare const MAX_HEADER_VISITS = 20000;
40
+ /** How many properties and branches the header scan reads, across every visit, before it stops and says so. */
41
+ declare const MAX_HEADER_READS: number;
40
42
  /** Drops `_meta` keys under any ignored prefix. Returns undefined when nothing is left to pin. */
41
43
  declare function stripIgnoredMeta(meta: JsonValue | undefined, ignoredPrefixes: readonly string[]): JsonObject | undefined;
42
44
  /** Strips the query string: query strings routinely carry tokens, and the lock is committed. */
43
45
  declare function sanitizeUrl(raw: string): string;
44
46
 
45
- export { MAX_HEADER_VISITS, extractHeaderParams, isEscalation, normalizeSchema, resolveBehavior, sanitizeUrl, stripIgnoredMeta };
47
+ export { MAX_HEADER_READS, MAX_HEADER_VISITS, extractHeaderParams, isEscalation, normalizeSchema, resolveBehavior, sanitizeUrl, stripIgnoredMeta };
@@ -1,4 +1,5 @@
1
1
  import {
2
+ MAX_HEADER_READS,
2
3
  MAX_HEADER_VISITS,
3
4
  extractHeaderParams,
4
5
  isEscalation,
@@ -6,10 +7,12 @@ import {
6
7
  resolveBehavior,
7
8
  sanitizeUrl,
8
9
  stripIgnoredMeta
9
- } from "../chunk-5OCXDAFS.js";
10
- import "../chunk-ZD2C4FMT.js";
11
- import "../chunk-FVT77BL4.js";
10
+ } from "../chunk-CP2XTAKE.js";
11
+ import "../chunk-MQJ54E63.js";
12
+ import "../chunk-Z4M6ZRTP.js";
13
+ import "../chunk-SZKRNTJP.js";
12
14
  export {
15
+ MAX_HEADER_READS,
13
16
  MAX_HEADER_VISITS,
14
17
  extractHeaderParams,
15
18
  isEscalation,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nulladrift/core",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "type": "module",
5
5
  "description": "The lockfile model and the drift engine, shared by the collector and the control plane.",
6
6
  "exports": {
@@ -19,7 +19,7 @@
19
19
  "eslint": "^9.32.0",
20
20
  "globals": "^15.15.0",
21
21
  "typescript": "^5.9.3",
22
- "typescript-eslint": "^8.72.0",
22
+ "typescript-eslint": "^8.73.0",
23
23
  "vitest": "^4.1.12",
24
24
  "tsup": "^8.5.1"
25
25
  },
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lock/normalize.ts"],"sourcesContent":["/** Turning what a server sent into the stable, reviewable form the lock stores. */\nimport { redactPath } from \"./credentials\";\nimport { alternatives, asObject, effectiveSchema, MAX_VISIT_DEPTH } from \"./jsonschema\";\nimport type { JsonObject, JsonValue, LockedAnnotations, LockedBehavior } from \"./types\";\n\n/**\n * Resolves the four behavioural annotations against the spec's defaults, which are not neutral:\n * an absent `readOnlyHint` means \"may modify\" and an absent `destructiveHint` means \"may\n * destroy\". A server deleting an annotation is therefore an escalation, and the lock has to be\n * able to show it as a changed value rather than a removed line. See docs/lockfile.md §4.\n *\n * `destructiveHint` and `idempotentHint` are defined to be meaningful only when `readOnlyHint`\n * is false, so a read-only tool resolves to non-destructive and idempotent regardless of what\n * it claims: a tool that changes nothing cannot destroy anything, and repeating it has no\n * additional effect.\n */\nexport function resolveBehavior(annotations: LockedAnnotations | undefined): LockedBehavior {\n const readOnly = annotations?.readOnlyHint ?? false;\n return {\n readOnly,\n destructive: readOnly ? false : (annotations?.destructiveHint ?? true),\n idempotent: readOnly ? true : (annotations?.idempotentHint ?? false),\n openWorld: annotations?.openWorldHint ?? true,\n };\n}\n\n/** True when `next` claims any power `previous` did not. */\nexport function isEscalation(previous: LockedBehavior, next: LockedBehavior): boolean {\n return (\n (previous.readOnly && !next.readOnly) ||\n (!previous.destructive && next.destructive) ||\n (previous.idempotent && !next.idempotent) ||\n (!previous.openWorld && next.openWorld)\n );\n}\n\n/*\n * Keywords whose value is data rather than a schema. A `required` array inside a `const` or a\n * `default` is part of a value the model is shown, and its order is the server's to choose:\n * sorting it there made `[\"backup\", \"delete\"]` and `[\"delete\", \"backup\"]` compare as the same.\n */\nconst DATA_KEYWORDS = new Set([\"const\", \"default\", \"enum\", \"examples\", \"example\"]);\n/** Keywords whose value maps names to schemas: the keys are names, never keywords. */\nconst NAMED_SCHEMAS = new Set([\"properties\", \"patternProperties\", \"$defs\", \"definitions\", \"dependentSchemas\"]);\n\n/**\n * Sorts the `required` keyword's array. Member order there is semantically insignificant and is\n * the most common source of diffs that mean nothing. Every other array keeps server order,\n * because order *is* significant in `prefixItems`, `allOf` and `icons`, and we only reorder where\n * we can show it is safe.\n *\n * Only where `required` is a keyword: not inside a value (`const`, `default`, `enum`,\n * `examples`), and not as the name of a property, which is a schema of its own.\n */\nexport function normalizeSchema(value: JsonValue): JsonValue {\n return normalizeNode(value, false);\n}\n\nfunction normalizeNode(value: JsonValue, namesOnly: boolean): JsonValue {\n if (Array.isArray(value)) return value.map((member) => normalizeNode(member, false));\n if (value === null || typeof value !== \"object\") return value;\n\n // No prototype, so a member named `__proto__` is kept (see toJson in canonical.ts).\n const out = Object.create(null) as JsonObject;\n for (const [key, member] of Object.entries(value)) {\n if (namesOnly) {\n out[key] = normalizeNode(member, false);\n continue;\n }\n if (key === \"required\" && Array.isArray(member) && member.every((entry) => typeof entry === \"string\")) {\n out[key] = [...(member as string[])].sort();\n continue;\n }\n if (DATA_KEYWORDS.has(key)) {\n out[key] = member;\n continue;\n }\n out[key] = normalizeNode(member, NAMED_SCHEMAS.has(key));\n }\n return out;\n}\n\n/**\n * Finds input properties carrying an `x-mcp-header` annotation, which mirrors the argument's\n * value into an `Mcp-Param-*` HTTP header on Streamable HTTP, where proxies and WAFs can read\n * it. A server adding this to an existing parameter redirects that argument's data with no\n * visible change to the tool's signature, so it gets its own line in the lock.\n *\n * `$ref` and `allOf` are resolved first. Schema generators put properties behind `$defs` as a\n * matter of course, and a scan that only read literal nodes found nothing in those -- which is\n * the worst outcome for a field whose entire purpose is to move data somewhere new.\n */\nexport function extractHeaderParams(schema: JsonValue): string[] {\n const found: string[] = [];\n /*\n * Bounded twice. A `$ref` already on the way down is not followed again: a definition whose\n * properties point back at it was walked once per property per level, P^12 calls, so a\n * 200-byte schema held `check` for minutes on a blocked event loop that no timeout could\n * interrupt. Headers inside a recursion are the ones its first pass already found. And a hard\n * ceiling on visits, which leaves a marker in the lock rather than an incomplete list that\n * looks complete.\n */\n let budget = MAX_HEADER_VISITS;\n\n const walk = (node: JsonValue, path: string[], depth: number, refsOnPath: ReadonlySet<string>): void => {\n if (depth > MAX_VISIT_DEPTH) return;\n if (budget <= 0) return;\n budget -= 1;\n const object = effectiveSchema(node, schema);\n if (!object) return;\n\n const properties = asObject(object[\"properties\"]);\n if (properties) {\n for (const [name, child] of Object.entries(properties)) {\n const resolved = effectiveSchema(child, schema);\n if (!resolved) continue;\n const header = resolved[\"x-mcp-header\"];\n if (typeof header === \"string\" && header.length > 0) found.push(`${[...path, name].join(\".\")} -> ${header}`);\n const ref = asObject(child)?.[\"$ref\"];\n if (typeof ref === \"string\" && refsOnPath.has(ref)) continue;\n walk(child, [...path, name], depth + 1, typeof ref === \"string\" ? new Set([...refsOnPath, ref]) : refsOnPath);\n }\n }\n\n // A parameter reachable only through one branch of an `anyOf` is still reachable.\n for (const branch of alternatives(object)) {\n const ref = asObject(branch.schema)?.[\"$ref\"];\n if (typeof ref === \"string\" && refsOnPath.has(ref)) continue;\n walk(branch.schema, path, depth + 1, typeof ref === \"string\" ? new Set([...refsOnPath, ref]) : refsOnPath);\n }\n };\n\n const rootRef = asObject(schema)?.[\"$ref\"];\n walk(schema, [], 0, new Set(typeof rootRef === \"string\" ? [rootRef] : []));\n if (budget <= 0) found.push(`(schema too large to scan for headers past ${MAX_HEADER_VISITS} nodes)`);\n return [...new Set(found)].sort();\n}\n\n/** How many schema nodes the header scan visits before it stops and says so. */\nexport const MAX_HEADER_VISITS = 20_000;\n\n/** Drops `_meta` keys under any ignored prefix. Returns undefined when nothing is left to pin. */\nexport function stripIgnoredMeta(meta: JsonValue | undefined, ignoredPrefixes: readonly string[]): JsonObject | undefined {\n if (meta === null || meta === undefined || typeof meta !== \"object\" || Array.isArray(meta)) return undefined;\n const out = Object.create(null) as JsonObject;\n for (const [key, value] of Object.entries(meta)) {\n if (ignoredPrefixes.some((prefix) => key.startsWith(prefix))) continue;\n out[key] = value;\n }\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/** Strips the query string: query strings routinely carry tokens, and the lock is committed. */\nexport function sanitizeUrl(raw: string): string {\n /*\n * A placeholder (`${HOST}`, `${PORT}`) is kept exactly as written. Parsing first lowercased a\n * placeholder in the host, so the lock named a variable the config never used, and failed on one\n * in the port, which wrote the address raw, query string and all.\n */\n if (raw.includes(\"${\")) return sanitizeText(raw);\n try {\n const url = new URL(raw);\n url.search = \"\";\n url.hash = \"\";\n /*\n * `https://alice:s3cr3t@host/mcp` survived this untouched, because `toString()` keeps\n * userinfo. The query string was stripped on the grounds that credentials usually sit there;\n * userinfo is the one place a credential sits by definition.\n */\n url.username = \"\";\n url.password = \"\";\n // A hosted server whose address embeds the key keeps it in the path, past both of the above.\n url.pathname = redactPath(url.pathname);\n return url.toString();\n } catch {\n return sanitizeText(raw);\n }\n}\n\n/** The same, as text, for an address a URL parser cannot or should not normalize. */\nfunction sanitizeText(raw: string): string {\n const withoutUser = raw.replace(/^([a-z][a-z0-9+.-]*:\\/\\/)[^/@]*@/i, \"$1\");\n const base = withoutUser.split(/[?#]/)[0] ?? withoutUser;\n const parts = /^([a-z][a-z0-9+.-]*:\\/\\/[^/]*)(\\/.*)?$/i.exec(base);\n return parts ? `${parts[1]}${parts[2] ? redactPath(parts[2]) : \"\"}` : base;\n}\n"],"mappings":";;;;;;;;;;;AAgBO,SAAS,gBAAgB,aAA4D;AAC1F,QAAM,WAAW,aAAa,gBAAgB;AAC9C,SAAO;AAAA,IACL;AAAA,IACA,aAA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/capability.ts","../src/diff/index.ts"],"sourcesContent":["/**\n * Coercion for values that arrived from somewhere else.\n *\n * Everything in `risk/` reads a declaration a server sent, or a reading a collector posted. The\n * types say `{ name?: string }[]`, and a type is a claim about a value this code never checked:\n * `tools` is whatever was in the JSON, so it can be absent, a string, or an array with a `null`\n * in it. `tool.name` on that `null` throws a TypeError.\n *\n * In the CLI that aborts one audit, which is survivable. In the control plane the same call sits\n * inside ingest, where one malformed element in one tool of one server would fail the whole\n * request -- every other server in that reading included. A classifier is a security control, and\n * a security control that can be switched off by sending it a `null` is one an attacker turns off\n * rather than evades.\n *\n * So the guard belongs here, at the point the value is first believed, rather than at each of the\n * places that go on to read it.\n */\n\n/** The members of `value` that are objects, or an empty list if it is not a list at all. */\nexport function objectsIn(value: unknown): Array<Record<string, unknown>> {\n if (!Array.isArray(value)) return [];\n return value.filter((member): member is Record<string, unknown> => typeof member === \"object\" && member !== null);\n}\n\n/** `value` if it is a non-null object, otherwise an empty one, so a property read is always safe. */\nexport function objectOr(value: unknown): Record<string, unknown> {\n return typeof value === \"object\" && value !== null ? (value as Record<string, unknown>) : {};\n}\n\n/** `value` if it is a string, otherwise undefined: a `name` that is a number is not a name. */\nexport function stringOr(value: unknown): string | undefined {\n return typeof value === \"string\" ? value : undefined;\n}\n","/**\n * What a server could do to you, derived from what it declares.\n *\n * This answers one question and refuses another. It answers *what could this tool do if the\n * model decides to use it*, from the tool's name, its argument names and its schema shape. It\n * does not answer *is this tool malicious*, which is a judgement, needs a corpus, and would make\n * a verdict depend on something other than the bytes on the wire.\n *\n * The distinction matters because it is the same one the severity table already makes: rank by\n * shape, never by intent. A tool named `run_command` taking a `command` argument is arbitrary\n * execution whatever its description claims, and that is a fact about the declaration rather\n * than an opinion about the author.\n *\n * Nothing here is stored in the lockfile. Capabilities are derived from the schemas that *are*\n * stored, so sharpening a pattern re-reads existing locks instead of showing every user a wave\n * of drift that no server caused.\n */\n\n/** Ordered worst-first; the order is the comparison. */\nimport { objectOr, objectsIn, stringOr } from \"./untrusted\";\n\nexport const CAPABILITY_SEVERITIES = [\"critical\", \"high\", \"medium\", \"low\"] as const;\nexport type CapabilitySeverity = (typeof CAPABILITY_SEVERITIES)[number];\n\nexport const CAPABILITY_KINDS = [\n \"process-exec\",\n \"code-eval\",\n \"credential-access\",\n \"file-write\",\n \"network-egress\",\n \"database\",\n \"privilege\",\n \"agent-control\",\n \"env-access\",\n \"file-read\",\n] as const;\nexport type CapabilityKind = (typeof CAPABILITY_KINDS)[number];\n\nexport interface Capability {\n kind: CapabilityKind;\n severity: CapabilitySeverity;\n /** Where it was seen: `name`, or `arg:<argument>`. Shown so a finding can be checked. */\n evidence: string;\n}\n\ninterface Rule {\n kind: CapabilityKind;\n severity: CapabilitySeverity;\n /** Matched against the tool name, with separators normalised to `_`. */\n name?: RegExp;\n /** Matched against each top-level argument name, normalised the same way. */\n arg?: RegExp;\n}\n\n/*\n * Deliberately narrow. A pattern that fires on `get_user` because it contains \"user\" teaches\n * people to ignore the output, and an ignored signal is worse than none: it spends the attention\n * the real findings need.\n */\nconst RULES: Rule[] = [\n { kind: \"process-exec\", severity: \"critical\", name: /(^|_)(exec|execute|spawn|shell|bash|sh|cmd|command|run_command|terminal|subprocess)(_|$)/, arg: /(^|_)(command|cmd|argv|shell|exec|script)(_|$)/ },\n // `source` is deliberately absent: in `copy_file(source, destination)` it is a path, and\n // labelling a file copy as arbitrary code execution at CRITICAL is the false positive that\n // teaches people to stop reading the line. `code` has to be the whole argument name for the\n // same reason -- a crawl of 468 published tools flagged `location_code` as arbitrary code\n // execution, and `country_code`, `status_code` and `zip_code` are all waiting behind it.\n { kind: \"code-eval\", severity: \"critical\", name: /(^|_)(eval|evaluate|run_code|exec_code|interpret|compile)(_|$)/, arg: /^code$|(^|_)(source_code|code_to_run|js_code|python_code|expression|program|snippet)(_|$)/ },\n { kind: \"credential-access\", severity: \"critical\", name: /(^|_)(secret|secrets|credential|credentials|token|keychain|vault|password)(_|$)/, arg: /(^|_)(secret|credential|password|private_key|api_key|access_token)(_|$)/ },\n { kind: \"network-egress\", severity: \"high\", name: /(^|_)(fetch|request|http|curl|download|upload|post|webhook|navigate|browse|send)(_|$)/, arg: /(^|_)(url|uri|endpoint|host|hostname|webhook|callback)(_|$)/ },\n // Narrowed to things that are actually SQL-shaped. `query`, `select` and `update` on their\n // own matched `simulate-research-query`, `browser_select_option` and `trigger-resource-update`,\n // none of which is a database.\n { kind: \"database\", severity: \"high\", name: /(^|_)(sql|execute_sql|run_sql|query_db|db_query|migrate)(_|$)/, arg: /(^|_)(sql|statement|dsn|connection_string)(_|$)/ },\n { kind: \"privilege\", severity: \"high\", name: /(^|_)(sudo|root|admin|grant|revoke|permission|permissions|acl|policy)(_|$)/, arg: /(^|_)(role|scope|scopes|permission|permissions|privilege)(_|$)/ },\n { kind: \"agent-control\", severity: \"high\", name: /(^|_)(prompt|system_prompt|instruction|instructions|memory|context|persona)(_|$)/, arg: /(^|_)(system_prompt|instruction|instructions|persona)(_|$)/ },\n { kind: \"env-access\", severity: \"medium\", name: /(^|_)(env|environment|getenv|setenv|config|settings)(_|$)/, arg: /(^|_)(env|environment|env_var)(_|$)/ },\n // `read`, `open` and `load` are not here; see `fileRead` below.\n { kind: \"file-read\", severity: \"low\", name: /(^|_)(read_file|cat|list_directory|ls|glob|search_files)(_|$)/, arg: /(^|_)(path|file|filename|filepath|directory|dir)(_|$)/ },\n];\n\n/*\n * Writing files, which needs more than a verb.\n *\n * It was one rule like the others: any of a dozen verbs in the name, or an argument called\n * `content` or `data`. So the official memory server -- `delete_entities`, `delete_relations`,\n * and `add_observations` with a `contents` field -- was labelled as writing files at HIGH, and an\n * organization's overview said two of its three servers could write files when one could. Found\n * by using the product. A verb like `delete` or `move` says something changes; whether it is a\n * file depends on what is being deleted or moved.\n *\n * So, in order:\n * - verbs that only mean one thing (`write`, `unlink`, `chmod`, `mkdir`...) count on their own;\n * - other changing verbs count when the name says what they act on is a file, directory or path,\n * or the tool takes a path;\n * - an argument naming where something is written (`destination`) counts on its own, and one\n * carrying what is written (`content`, `data`) counts only beside a path.\n */\nconst FILE_ONLY_VERBS = /(^|_)(write|create_file|put_file|unlink|chmod|chown|mkdir|rmdir|truncate)(_|$)/;\nconst CHANGING_VERBS = /(^|_)(create|save|delete|remove|rename|move|copy|edit|append|put|overwrite|replace|patch)(_|$)/;\nconst FILE_NOUNS = /(^|_)(file|files|filename|dir|dirs|directory|directories|folder|folders|path|paths)(_|$)/;\nconst PATH_ARGS = /^(path|paths|file|files|filename|filepath|file_path|directory|dir|folder|source_path)$|(^|_)(path|filepath|filename)$/;\nconst DESTINATION_ARGS = /(^|_)(destination|dest|dest_path|target_path|output_path|out_path)(_|$)/;\nconst CONTENT_ARGS = /(^|_)(contents|content|data|text|body)$/;\n\nfunction fileWrite(name: string, args: ReadonlyArray<readonly [string, string]>): string | undefined {\n if (FILE_ONLY_VERBS.test(name)) return \"name\";\n const path = args.find(([, normalized]) => PATH_ARGS.test(normalized));\n if (CHANGING_VERBS.test(name) && (FILE_NOUNS.test(name) || path)) return \"name\";\n const destination = args.find(([, normalized]) => DESTINATION_ARGS.test(normalized));\n if (destination) return `arg:${destination[0]}`;\n const content = args.find(([, normalized]) => CONTENT_ARGS.test(normalized));\n if (content && path) return `arg:${content[0]}`;\n return undefined;\n}\n\n/*\n * Reading files, by the same reasoning: `read_graph` and `open_nodes` read the memory server's\n * own graph, and were labelled as reading files because of the verb alone. A reading verb counts\n * when the name says what it reads is a file, directory or path; a tool taking a path is caught\n * by the rule's argument pattern whatever it is called.\n */\nconst READING_VERBS = /(^|_)(read|open|load)(_|$)/;\n\nfunction fileRead(name: string): boolean {\n return READING_VERBS.test(name) && FILE_NOUNS.test(name);\n}\n\n/*\n * Cyrillic and Greek letters that are drawn like Latin ones. `run_comm\\u0430nd` reads as\n * `run_command` to a person and matched nothing at all, so a single substituted character\n * bought a tool complete invisibility to a classifier whose whole job is reading names.\n * Folding them is the difference between a check and a formality.\n */\nconst CONFUSABLES: Record<string, string> = {\n \"\\u0430\": \"a\", \"\\u0435\": \"e\", \"\\u043E\": \"o\", \"\\u0441\": \"c\", \"\\u0440\": \"p\", \"\\u0445\": \"x\",\n \"\\u0443\": \"y\", \"\\u0456\": \"i\", \"\\u0458\": \"j\", \"\\u04BB\": \"h\", \"\\u0501\": \"d\", \"\\u051B\": \"q\",\n \"\\u03BF\": \"o\", \"\\u03B1\": \"a\", \"\\u03B5\": \"e\", \"\\u03BD\": \"v\", \"\\u03C1\": \"p\", \"\\u03C5\": \"u\",\n \"\\u0131\": \"i\", \"\\u1E9E\": \"s\",\n};\n\n/** Built from the map above, so the pattern and the replacements cannot drift apart. */\nconst CONFUSABLE_PATTERN = new RegExp(`[${Object.keys(CONFUSABLES).join(\"\")}]`, \"g\");\n\n/** `browser.take-screenshot` and `browser_take_screenshot` are the same shape. */\nfunction normalize(identifier: string): string {\n return identifier\n .toLowerCase()\n .replace(CONFUSABLE_PATTERN, (character) => CONFUSABLES[character] ?? character)\n .replace(/[-.\\s/]+/g, \"_\");\n}\n\n/*\n * Nested properties count. `tool({ opts: { command } })` is the same capability as\n * `tool({ command })`, and only the top level was examined, so one wrapping object hid it.\n * Depth is bounded because a schema is attacker-supplied and need not terminate.\n */\nfunction argumentNames(inputSchema: unknown, depth = 0): string[] {\n if (depth > 6 || typeof inputSchema !== \"object\" || inputSchema === null) return [];\n const node = inputSchema as { properties?: unknown; items?: unknown };\n const names: string[] = [];\n const properties = node.properties;\n if (typeof properties === \"object\" && properties !== null) {\n for (const [name, child] of Object.entries(properties as Record<string, unknown>)) {\n names.push(name);\n names.push(...argumentNames(child, depth + 1));\n }\n }\n if (node.items !== undefined) names.push(...argumentNames(node.items, depth + 1));\n return names;\n}\n\n/**\n * The capabilities one tool declares. Worst first, one entry per kind: a tool matching\n * `process-exec` by both its name and an argument is not twice as dangerous.\n */\nexport function toolCapabilities(tool: { name?: string; inputSchema?: unknown } | null | undefined): Capability[] {\n // The argument is whatever was in the JSON; see risk/untrusted.\n const subject = objectOr(tool);\n const name = normalize(stringOr(subject.name) ?? \"\");\n const args = argumentNames(subject.inputSchema).map((argument) => [argument, normalize(argument)] as const);\n const found = new Map<CapabilityKind, Capability>();\n\n for (const rule of RULES) {\n if (found.has(rule.kind)) continue;\n if (rule.name?.test(name)) {\n found.set(rule.kind, { kind: rule.kind, severity: rule.severity, evidence: \"name\" });\n continue;\n }\n const hit = rule.arg ? args.find(([, normalized]) => rule.arg?.test(normalized)) : undefined;\n if (hit) found.set(rule.kind, { kind: rule.kind, severity: rule.severity, evidence: `arg:${hit[0]}` });\n }\n if (!found.has(\"file-read\") && fileRead(name)) found.set(\"file-read\", { kind: \"file-read\", severity: \"low\", evidence: \"name\" });\n const writes = fileWrite(name, args);\n if (writes) found.set(\"file-write\", { kind: \"file-write\", severity: \"high\", evidence: writes });\n\n return [...found.values()].sort(\n (a, b) => CAPABILITY_SEVERITIES.indexOf(a.severity) - CAPABILITY_SEVERITIES.indexOf(b.severity) || a.kind.localeCompare(b.kind),\n );\n}\n\n/** Every capability a set of tools declares between them, with the tools that declare each. */\nexport function surfaceCapabilities(\n tools: ReadonlyArray<{ name?: string; inputSchema?: unknown }> | null | undefined,\n): Array<Capability & { tools: string[] }> {\n const byKind = new Map<CapabilityKind, Capability & { tools: string[] }>();\n for (const tool of objectsIn(tools)) {\n const label = stringOr(tool.name) ?? \"?\";\n for (const capability of toolCapabilities(tool)) {\n const existing = byKind.get(capability.kind);\n if (existing) existing.tools.push(label);\n else byKind.set(capability.kind, { ...capability, tools: [label] });\n }\n }\n return [...byKind.values()].sort(\n (a, b) => CAPABILITY_SEVERITIES.indexOf(a.severity) - CAPABILITY_SEVERITIES.indexOf(b.severity) || a.kind.localeCompare(b.kind),\n );\n}\n","/** Comparing a freshly captured lock against the committed one. */\nimport { stableKey } from \"../lock/canonical\";\nimport { isEscalation } from \"../lock/normalize\";\nimport type {\n LockedPrompt,\n LockedResource,\n LockedResourceTemplate,\n LockedMcpServer,\n LockedTool,\n Lockfile,\n} from \"../lock/types\";\nimport { toolCapabilities, type CapabilitySeverity } from \"../risk/capability\";\nimport { classifySchemaChange } from \"./schema\";\nimport type { Change, ChangeKind, Severity } from \"./types\";\nimport { SEVERITY, sortChanges } from \"./types\";\n\nfunction change(kind: ChangeKind, server: string, summary: string, extra?: Partial<Change>): Change {\n return { kind, severity: SEVERITY[kind], server, summary, ...extra };\n}\n\nfunction same(a: unknown, b: unknown): boolean {\n return stableKey(a ?? null) === stableKey(b ?? null);\n}\n\n/**\n * Members grouped by their key, every copy kept.\n *\n * A Map from key to member kept the last of two tools with the same name and dropped the first\n * without a word. A server that listed a poisoned `read_file` ahead of the approved one compared\n * clean: the approved copy was the one compared, and the poisoned one was never looked at. Which\n * copy a client uses is the client's business, so every copy is compared.\n */\nfunction groupBy<T>(members: T[] | undefined, key: (member: T) => string): Map<string, T[]> {\n const groups = new Map<string, T[]>();\n for (const member of members ?? []) {\n const k = key(member);\n const group = groups.get(k);\n if (group) group.push(member);\n else groups.set(k, [member]);\n }\n return groups;\n}\n\n/**\n * What a server declares, flattened so that an extension is one of the names.\n *\n * `capabilities` is a handful of top-level keys, and one of them, `extensions`, is a map of\n * reverse-DNS ids: that is the mechanism the specification uses to ship capability outside the\n * core. Comparing only the top level means a server that gains an extension still has\n * `extensions` before and after, so nothing reads as gained and the finding lands on the generic\n * \"declared capabilities changed\" with the detail left inside a JSON blob for a reviewer to go\n * and read. As more of what a server can do arrives as an extension, \"what did this one just\n * gain\" becomes an extension question, and it deserves an answer in words.\n *\n * The `extensions` key itself is not a name. Reporting both it and the id it contains would say\n * the same thing twice on the reading where a server declares its first extension.\n */\nfunction declaredNames(capabilities: LockedMcpServer[\"capabilities\"]): string[] {\n const names: string[] = [];\n for (const [key, value] of Object.entries(capabilities ?? {})) {\n if (key === \"extensions\" && value !== null && typeof value === \"object\" && !Array.isArray(value)) {\n for (const id of Object.keys(value)) names.push(`extensions/${id}`);\n continue;\n }\n names.push(key);\n }\n return names;\n}\n\n/** Describes the delta between two capability maps in the direction that matters. */\nfunction compareCapabilities(before: LockedMcpServer, after: LockedMcpServer, name: string): Change[] {\n if (same(before.capabilities, after.capabilities)) return [];\n const previous = declaredNames(before.capabilities);\n const next = declaredNames(after.capabilities);\n const gained = next.filter((key) => !previous.includes(key));\n const lost = previous.filter((key) => !next.includes(key));\n\n if (gained.length > 0 && lost.length === 0) {\n return [change(\"server.capabilities.widened\", name, `server now declares ${gained.join(\", \")}`, { before: before.capabilities, after: after.capabilities })];\n }\n if (lost.length > 0 && gained.length === 0) {\n return [change(\"server.capabilities.narrowed\", name, `server no longer declares ${lost.join(\", \")}`, { before: before.capabilities, after: after.capabilities })];\n }\n return [change(\"server.capabilities.changed\", name, \"declared capabilities changed\", { before: before.capabilities, after: after.capabilities })];\n}\n\n\n/*\n * What a tool can do, compared across a reading.\n *\n * The schema diff says a tool \"accepts input it did not before\", which is the same sentence\n * whether the new argument is `nickname` or `command`. The classifier already knows the\n * difference and says so at pin time; the diff did not ask, so the finding a reviewer approved\n * described arbitrary command execution in the words of an optional string.\n *\n * A tool that is new is compared against nothing, so everything it can do is gained. That is the\n * honest reading: a server that adds a tool taking `command` has gained command execution just as\n * surely as one that adds the argument to a tool already there.\n */\nconst CAPABILITY_SEVERITY: Record<CapabilitySeverity, Severity> = {\n critical: \"high\",\n high: \"high\",\n medium: \"medium\",\n low: \"low\",\n};\n\nfunction compareToolCapabilities(server: string, before: LockedTool[] | undefined, after: LockedTool[] | undefined): Change[] {\n const previous = groupBy(before, (tool) => tool.name);\n const changes: Change[] = [];\n\n for (const tool of after ?? []) {\n /*\n * Only tools that were already here. A tool that is new is reported once, by `tool.added`,\n * which names what it can do: raising a second finding for the same fact makes a reviewer\n * read the arrival of one tool twice.\n */\n const existing = previous.get(tool.name);\n if (!existing) continue;\n // Against every copy that was pinned under this name: what any of them could do was approved.\n const had = new Set(existing.flatMap((copy) => toolCapabilities(copy).map((capability) => capability.kind)));\n for (const capability of toolCapabilities(tool)) {\n if (had.has(capability.kind)) continue;\n changes.push(\n change(\"tool.capability.gained\", server, `can now ${capability.kind} (${capability.evidence})`, {\n member: tool.name,\n severity: CAPABILITY_SEVERITY[capability.severity],\n after: { kind: capability.kind, severity: capability.severity, evidence: capability.evidence },\n }),\n );\n }\n }\n return changes;\n}\n\nfunction compareTool(name: string, before: LockedTool, after: LockedTool): Change[] {\n if (before.digest === after.digest) return [];\n const changes: Change[] = [];\n const at = { member: before.name };\n\n if (!same(before.description, after.description)) {\n changes.push(\n change(\"tool.description.changed\", name, `description changed (${before.description?.length ?? 0} → ${after.description?.length ?? 0} characters)`, {\n ...at,\n before: before.description,\n after: after.description,\n }),\n );\n }\n\n const inputVerdict = classifySchemaChange(before.inputSchema, after.inputSchema);\n if (inputVerdict !== \"same\") {\n const kind = (`tool.input_schema.${inputVerdict}` satisfies ChangeKind) as ChangeKind;\n const wording = inputVerdict === \"widened\" ? \"accepts input it did not before\" : inputVerdict === \"narrowed\" ? \"accepts less input than before\" : \"input schema changed\";\n changes.push(change(kind, name, wording, { ...at, before: before.inputSchema, after: after.inputSchema }));\n }\n\n if (!same(before.outputSchema, after.outputSchema)) {\n changes.push(change(\"tool.output_schema.changed\", name, \"output schema changed\", { ...at, before: before.outputSchema, after: after.outputSchema }));\n }\n\n if (!same(before.behavior, after.behavior)) {\n const escalated = isEscalation(before.behavior, after.behavior);\n changes.push(\n change(escalated ? \"tool.behavior.escalated\" : \"tool.behavior.relaxed\", name, escalated ? describeEscalation(before, after) : \"declares fewer powers than before\", {\n ...at,\n before: before.behavior,\n after: after.behavior,\n }),\n );\n }\n\n if (!same(before.headerParams, after.headerParams)) {\n changes.push(\n change(\"tool.header_params.changed\", name, \"arguments mirrored into HTTP headers changed\", { ...at, before: before.headerParams ?? [], after: after.headerParams ?? [] }),\n );\n }\n\n /*\n * The digest covers more than the fields called out above -- title, icons, `_meta`. If none of\n * them fired, something in that remainder moved, and silence would be worse than a vague\n * finding.\n */\n if (changes.length === 0) {\n const moved = [\n !same(before.title, after.title) ? \"title\" : \"\",\n !same(before.icons, after.icons) ? \"icons\" : \"\",\n !same(before.execution, after.execution) ? `how it may be run (${describeExecution(before.execution)} → ${describeExecution(after.execution)})` : \"\",\n !same(before.meta, after.meta) ? \"_meta\" : \"\",\n ].filter(Boolean);\n changes.push(change(\"tool.changed\", name, `tool definition changed: ${moved.length > 0 ? moved.join(\", \") : \"a field this report has no finding for\"}`, { ...at, before, after }));\n }\n return changes;\n}\n\nfunction describeExecution(execution: LockedTool[\"execution\"]): string {\n const support = execution?.[\"taskSupport\"];\n return typeof support === \"string\" ? `task support ${support}` : \"unstated\";\n}\n\nfunction describeEscalation(before: LockedTool, after: LockedTool): string {\n const gained: string[] = [];\n if (before.behavior.readOnly && !after.behavior.readOnly) gained.push(\"may now modify\");\n if (!before.behavior.destructive && after.behavior.destructive) gained.push(\"may now destroy\");\n if (before.behavior.idempotent && !after.behavior.idempotent) gained.push(\"repeat calls now compound\");\n if (!before.behavior.openWorld && after.behavior.openWorld) gained.push(\"may now reach external systems\");\n return gained.join(\"; \");\n}\n\ninterface MemberSpec<T> {\n key: (member: T) => string;\n label: (member: T) => string;\n added: ChangeKind;\n removed: ChangeKind;\n changed: ChangeKind;\n noun: string;\n /** Extra wording for a member that is new, where arriving is itself the finding. */\n arriving?: (member: T) => string;\n}\n\nfunction compareMembers<T extends { digest: string }>(\n name: string,\n before: T[] | undefined,\n after: T[] | undefined,\n spec: MemberSpec<T>,\n deep?: (key: string, a: T, b: T) => Change[],\n): Change[] {\n const changes: Change[] = [];\n const previous = groupBy(before, spec.key);\n const next = groupBy(after, spec.key);\n\n for (const [key, members] of next) {\n const existing = previous.get(key);\n if (!existing) {\n for (const member of members) {\n const extra = spec.arriving?.(member);\n changes.push(\n change(spec.added, name, `new ${spec.noun} ${spec.label(member)}${extra ? ` \\u00b7 ${extra}` : \"\"}`, { member: spec.label(member), after: member }),\n );\n }\n continue;\n }\n\n /*\n * Identical copies pair off first, so a server that reorders its list compares clean. What is\n * left on the new side is compared against what is left on the old one, or, where a copy was\n * added beside the approved one, against the approved one: a second `read_file` is described\n * by how it differs from the first, which is the finding a reviewer needs.\n */\n const unpairedBefore = [...existing];\n const unpairedAfter: T[] = [];\n for (const member of members) {\n const twin = unpairedBefore.findIndex((candidate) => candidate.digest === member.digest);\n if (twin === -1) unpairedAfter.push(member);\n else unpairedBefore.splice(twin, 1);\n }\n for (const [index, member] of unpairedAfter.entries()) {\n const counterpart = unpairedBefore[index] ?? existing[0]!;\n if (counterpart.digest === member.digest) {\n changes.push(\n change(spec.changed, name, `${spec.noun} ${spec.label(member)} is now declared ${members.length} times`, { member: spec.label(member), before: existing, after: members }),\n );\n continue;\n }\n changes.push(\n ...(deep\n ? deep(key, counterpart, member)\n : [change(spec.changed, name, `${spec.noun} ${spec.label(member)} changed`, { member: spec.label(member), before: counterpart, after: member })]),\n );\n }\n for (const member of unpairedBefore.slice(unpairedAfter.length)) {\n changes.push(change(spec.removed, name, `one of the ${spec.noun}s declared as ${spec.label(member)} is gone`, { member: spec.label(member), before: member }));\n }\n }\n for (const [key, members] of previous) {\n if (next.has(key)) continue;\n for (const member of members) changes.push(change(spec.removed, name, `${spec.noun} ${spec.label(member)} is gone`, { member: spec.label(member), before: member }));\n }\n return changes;\n}\n\n/**\n * Whether the code behind the server is the code that was pinned.\n *\n * Absence on either side says nothing. A lock written before provenance existed, or a run that\n * could not reach a registry, has none, and reporting that would turn every upgrade of this tool\n * and every offline run into drift against servers nobody touched. Neither does a change of\n * package name: that only happens when the command or its arguments changed, which\n * `server.transport.changed` already reports, and saying it twice is how a reviewer learns to\n * skim.\n */\n/** What differs between two lists of a release's files, said briefly, or nothing when they match. */\nfunction filesMoved(was: Record<string, string> | undefined, now: Record<string, string> | undefined): string | undefined {\n if (was === undefined || now === undefined) return undefined;\n const added = Object.keys(now).filter((file) => !Object.hasOwn(was, file));\n const removed = Object.keys(was).filter((file) => !Object.hasOwn(now, file));\n const changed = Object.keys(now).filter((file) => Object.hasOwn(was, file) && was[file] !== now[file]);\n if (added.length + removed.length + changed.length === 0) return undefined;\n const list = (files: string[]) => `${files.slice(0, 3).join(\", \")}${files.length > 3 ? ` +${files.length - 3}` : \"\"}`;\n return [\n added.length > 0 ? `added ${list(added)}` : \"\",\n removed.length > 0 ? `removed ${list(removed)}` : \"\",\n changed.length > 0 ? `different contents for ${list(changed)}` : \"\",\n ]\n .filter(Boolean)\n .join(\"; \");\n}\n\nfunction compareProvenance(name: string, before: LockedMcpServer, after: LockedMcpServer): Change[] {\n const was = before.provenance;\n const now = after.provenance;\n if (!was || !now) return [];\n if (was.ecosystem !== now.ecosystem || was.name !== now.name) return [];\n\n const surfaceHeld = before.digest === after.digest;\n\n /*\n * Said out loud when the surface held still, because that is the case nothing else in the\n * report covers. A release that changed its tools is described by the tool changes; one that\n * changed only its code is described by this line and nothing else.\n */\n const unexplained = surfaceHeld ? \", and the declared surface did not change: nothing else in this report describes what the new code does\" : \"\";\n const integrityMoved = was.integrity !== undefined && now.integrity !== undefined && was.integrity !== now.integrity;\n\n if (was.version !== undefined && was.version === now.version) {\n if (!integrityMoved) {\n /*\n * The pinned file is one of a release's files, and an installer picks among all of them.\n * A wheel added to the release, or the pinned file taken away, changes what runs without\n * moving `integrity`; when both sides list the release's files, that is compared too.\n */\n const files = filesMoved(was.files, now.files);\n if (files) {\n return [change(\"server.artifact.changed\", name, `the files published for ${was.name}@${was.version} are not the ones that were pinned (${files})${unexplained}`, { before: was, after: now })];\n }\n if (was.integrity !== undefined && now.integrity === undefined) {\n return [change(\"server.artifact.changed\", name, `the file pinned for ${was.name}@${was.version} is no longer published, so something else is installed in its place${unexplained}`, { before: was, after: now })];\n }\n return [];\n }\n /*\n * Substitution is claimed only where the registry guarantees one artifact per version. npm\n * refuses to republish a version, so different bytes under the same one means something\n * between here and the registry served them. PyPI lets a maintainer add files to a release\n * after the fact, so the same version with a different recorded file has an ordinary\n * explanation, and it is reported as the milder kind.\n */\n if (was.ecosystem === \"npm\") {\n return [\n change(\n \"server.artifact.substituted\",\n name,\n `${was.name}@${was.version} now has different contents than when it was pinned: the same version, different bytes`,\n { before: was, after: now },\n ),\n ];\n }\n return [change(\"server.artifact.changed\", name, `the files published for ${was.name}@${was.version} are not the ones that were pinned${unexplained}`, { before: was, after: now })];\n }\n\n if (was.version !== now.version) {\n const moved = `the package behind this server moved from ${was.version ?? \"an unknown version\"} to ${now.version ?? \"an unknown version\"}`;\n return [change(\"server.artifact.changed\", name, `${moved}${unexplained}`, { before: was, after: now })];\n }\n\n /*\n * No version on either side: a file, or an image, whose tag is a pointer rather than a release.\n * A moved tag and a rebuilt binary are both ordinary, so both are the medium kind.\n */\n if (!integrityMoved) return [];\n const what =\n was.ecosystem === \"oci\"\n ? `the image ${was.name}:${was.requested ?? \"latest\"} now resolves to a different digest`\n : \"the file this server runs from has different contents than when it was pinned\";\n return [change(\"server.artifact.changed\", name, `${what}${unexplained}`, { before: was, after: now })];\n}\n\n/**\n * What the server digest covers, with each member list taken as a set.\n *\n * Members are stored sorted by name, so copies that share a name keep the order the server sent\n * them in, and a server that swaps two of them moves its digest without changing anything. The\n * member comparison already reads that as clean; this is what lets the fallback below agree.\n *\n * Everything but the fields the digest leaves out is taken as it is, rather than listed, so a\n * field the format gains later is covered here on the day it is added.\n */\nfunction orderless(entry: LockedMcpServer): string {\n const { kind: _kind, source: _source, digest: _digest, provenance: _provenance, coverage: _coverage, tools, resources, resourceTemplates, prompts, ...rest } = entry;\n const digests = (members: Array<{ digest: string }> | undefined) => (members ?? []).map((member) => member.digest).sort();\n return stableKey({\n ...rest,\n tools: digests(tools),\n resources: digests(resources),\n resourceTemplates: digests(resourceTemplates),\n prompts: digests(prompts),\n });\n}\n\nfunction compareServer(name: string, before: LockedMcpServer, after: LockedMcpServer): Change[] {\n /*\n * Provenance first, and outside the short-circuit: the attack it exists for is new code behind\n * an unchanged surface, which is exactly the case where the digests match.\n */\n const provenance = compareProvenance(name, before, after);\n if (before.digest === after.digest) return provenance;\n const changes: Change[] = [...provenance];\n\n if (!same(before.transport, after.transport)) {\n changes.push(change(\"server.transport.changed\", name, \"the server is reached differently than when it was pinned\", { before: before.transport, after: after.transport }));\n }\n if (!same(before.serverInfo, after.serverInfo)) {\n const from = before.serverInfo?.version ?? \"unknown\";\n const to = after.serverInfo?.version ?? \"unknown\";\n changes.push(change(\"server.identity.changed\", name, `server identity changed (version ${from} → ${to})`, { before: before.serverInfo, after: after.serverInfo }));\n }\n if (!same(before.protocol, after.protocol)) {\n changes.push(\n change(\"server.protocol.changed\", name, `protocol changed (${before.protocol.era}/${before.protocol.version} → ${after.protocol.era}/${after.protocol.version})`, {\n before: before.protocol,\n after: after.protocol,\n }),\n );\n }\n if (!same(before.instructions, after.instructions)) {\n changes.push(\n change(\"server.instructions.changed\", name, \"server instructions changed: this text goes into the model's system prompt\", {\n before: before.instructions,\n after: after.instructions,\n }),\n );\n }\n changes.push(...compareCapabilities(before, after, name));\n\n changes.push(\n ...compareMembers<LockedTool>(name, before.tools, after.tools, {\n key: (t) => t.name,\n label: (t) => t.name,\n added: \"tool.added\",\n removed: \"tool.removed\",\n changed: \"tool.changed\",\n noun: \"tool\",\n arriving: (t) => {\n const can = toolCapabilities(t);\n return can.length > 0 ? `can ${can.map((capability) => capability.kind).join(\", \")}` : \"\";\n },\n }, (_key, a, b) =>\n compareTool(name, a, b),\n ),\n );\n changes.push(...compareToolCapabilities(name, before.tools, after.tools));\n changes.push(\n ...compareMembers<LockedResource>(name, before.resources, after.resources, {\n key: (r) => r.uri,\n label: (r) => `${r.name} (${r.uri})`,\n added: \"resource.added\",\n removed: \"resource.removed\",\n changed: \"resource.changed\",\n noun: \"resource\",\n }),\n );\n changes.push(\n ...compareMembers<LockedResourceTemplate>(name, before.resourceTemplates, after.resourceTemplates, {\n key: (t) => t.uriTemplate,\n // The template itself is the capability -- widening it from file:///project/{path} to\n // file:///{path} is the whole finding -- so it belongs in the label, not just the body.\n label: (t) => `${t.name} (${t.uriTemplate})`,\n added: \"resource_template.added\",\n removed: \"resource_template.removed\",\n changed: \"resource_template.changed\",\n noun: \"resource template\",\n }),\n );\n changes.push(\n ...compareMembers<LockedPrompt>(name, before.prompts, after.prompts, {\n key: (p) => p.name,\n label: (p) => p.name,\n added: \"prompt.added\",\n removed: \"prompt.removed\",\n changed: \"prompt.changed\",\n noun: \"prompt\",\n }),\n );\n\n /*\n * The digest moved and nothing above says why. Every field the digest covers is compared above,\n * so this should not happen; when it does, a field was missed, and the honest report is a vague\n * finding rather than a clean one. A false clean is the one failure this engine exists to avoid.\n */\n if (changes.length === 0 && orderless(before) !== orderless(after)) {\n changes.push(\n change(\"server.capabilities.changed\", name, \"the server's pinned definition changed in a way no other finding describes; compare the lock entries\", {\n before: before.digest,\n after: after.digest,\n }),\n );\n }\n\n return changes;\n}\n\n/**\n * A server renamed in config would naively read as a removal plus an addition: two alarming\n * findings for a cosmetic edit. Collapsing requires an identical transport *and* an identical\n * digest, so a rename that also changed capabilities stays a remove and an add -- which is what\n * it is, and hiding a capability change inside a cosmetic one is the failure mode worth avoiding.\n */\nfunction detectRenames(before: Lockfile, after: Lockfile, removed: string[], added: string[]): { changes: Change[]; renamed: Set<string> } {\n const changes: Change[] = [];\n const renamed = new Set<string>();\n const availableAdds = [...added];\n\n for (const oldName of removed) {\n const oldEntry = before.subjects[oldName];\n if (!oldEntry) continue;\n const match = availableAdds.find((newName) => {\n const candidate = after.subjects[newName];\n return candidate !== undefined && candidate.digest === oldEntry.digest && same(candidate.transport, oldEntry.transport);\n });\n if (!match) continue;\n\n availableAdds.splice(availableAdds.indexOf(match), 1);\n renamed.add(oldName);\n renamed.add(match);\n changes.push(change(\"server.renamed\", match, `renamed from \"${oldName}\"; capabilities are unchanged`, { before: oldName, after: match }));\n }\n return { changes, renamed };\n}\n\nexport function diffLockfiles(before: Lockfile, after: Lockfile): Change[] {\n const beforeNames = Object.keys(before.subjects);\n const afterNames = Object.keys(after.subjects);\n const removed = beforeNames.filter((name) => !afterNames.includes(name));\n const added = afterNames.filter((name) => !beforeNames.includes(name));\n\n const { changes: renameChanges, renamed } = detectRenames(before, after, removed, added);\n const changes: Change[] = [...renameChanges];\n\n for (const name of added) {\n if (renamed.has(name)) continue;\n const entry = after.subjects[name];\n const toolCount = entry?.tools?.length ?? 0;\n changes.push(change(\"server.added\", name, `new server with ${toolCount} tool${toolCount === 1 ? \"\" : \"s\"}`, { after: entry }));\n }\n for (const name of removed) {\n if (renamed.has(name)) continue;\n changes.push(change(\"server.removed\", name, \"server is no longer configured\", { before: before.subjects[name] }));\n }\n for (const name of afterNames) {\n const a = before.subjects[name];\n const b = after.subjects[name];\n if (!a || !b) continue;\n changes.push(...compareServer(name, a, b));\n }\n\n return sortChanges(changes);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAmBO,SAAS,UAAU,OAAgD;AACxE,MAAI,CAAC,MAAM,QAAQ,KAAK,EAAG,QAAO,CAAC;AACnC,SAAO,MAAM,OAAO,CAAC,WAA8C,OAAO,WAAW,YAAY,WAAW,IAAI;AAClH;AAGO,SAAS,SAAS,OAAyC;AAChE,SAAO,OAAO,UAAU,YAAY,UAAU,OAAQ,QAAoC,CAAC;AAC7F;AAGO,SAAS,SAAS,OAAoC;AAC3D,SAAO,OAAO,UAAU,WAAW,QAAQ;AAC7C;;;ACXO,IAAM,wBAAwB,CAAC,YAAY,QAAQ,UAAU,KAAK;AAGlE,IAAM,mBAAmB;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAwBA,IAAM,QAAgB;AAAA,EACpB,EAAE,MAAM,gBAAgB,UAAU,YAAY,MAAM,4FAA4F,KAAK,iDAAiD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMtM,EAAE,MAAM,aAAa,UAAU,YAAY,MAAM,kEAAkE,KAAK,4FAA4F;AAAA,EACpN,EAAE,MAAM,qBAAqB,UAAU,YAAY,MAAM,mFAAmF,KAAK,0EAA0E;AAAA,EAC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,EAC3C;AAEA,SAAO,YAAY,OAAO;AAC5B;","names":[]}
@@ -1,107 +0,0 @@
1
- // src/lock/jsonschema.ts
2
- var MAX_REF_DEPTH = 32;
3
- var MAX_VISIT_DEPTH = 12;
4
- var MAX_FACTS = 5e3;
5
- var MAX_RESOLUTIONS = 1e5;
6
- var states = /* @__PURE__ */ new WeakMap();
7
- function stateOf(root) {
8
- if (root === null || typeof root !== "object") return { refs: /* @__PURE__ */ new Map(), spent: 0 };
9
- let state = states.get(root);
10
- if (!state) {
11
- state = { refs: /* @__PURE__ */ new Map(), spent: 0 };
12
- states.set(root, state);
13
- }
14
- return state;
15
- }
16
- function asObject(value) {
17
- return value !== null && value !== void 0 && typeof value === "object" && !Array.isArray(value) ? value : void 0;
18
- }
19
- function decodeToken(token) {
20
- let decoded = token;
21
- try {
22
- decoded = decodeURIComponent(token);
23
- } catch {
24
- }
25
- return decoded.replace(/~1/g, "/").replace(/~0/g, "~");
26
- }
27
- function resolvePointer(root, ref) {
28
- if (!ref.startsWith("#")) return void 0;
29
- const pointer = ref.slice(1);
30
- if (pointer !== "" && !pointer.startsWith("/")) return void 0;
31
- let node = root;
32
- for (const token of pointer.split("/").slice(1)) {
33
- const object = asObject(node);
34
- if (object === void 0) return void 0;
35
- node = object[decodeToken(token)];
36
- }
37
- return node;
38
- }
39
- function effectiveSchema(node, root, seenRefs = /* @__PURE__ */ new Set(), depth = 0) {
40
- const object = asObject(node);
41
- if (object === void 0) return void 0;
42
- if (depth > MAX_REF_DEPTH) return object;
43
- const state = stateOf(root);
44
- if (depth === 0) state.spent = 0;
45
- if (++state.spent > MAX_RESOLUTIONS) return object;
46
- const out = /* @__PURE__ */ Object.create(null);
47
- const merge = (source) => {
48
- for (const [key, value] of Object.entries(source)) {
49
- if (key === "$ref" || key === "allOf") continue;
50
- if (key === "properties") {
51
- const merged = Object.assign(/* @__PURE__ */ Object.create(null), asObject(out["properties"]) ?? {});
52
- for (const [name, schema] of Object.entries(asObject(value) ?? {})) {
53
- if (!Object.hasOwn(merged, name)) Object.defineProperty(merged, name, { value: schema, enumerable: true, writable: true, configurable: true });
54
- }
55
- out["properties"] = merged;
56
- } else if (key === "required" && Array.isArray(value)) {
57
- const already = Array.isArray(out["required"]) ? out["required"] : [];
58
- out["required"] = [...new Set([...already, ...value].filter((entry) => typeof entry === "string"))];
59
- } else if (!Object.hasOwn(out, key)) {
60
- out[key] = value;
61
- }
62
- }
63
- };
64
- merge(object);
65
- const ref = object["$ref"];
66
- if (typeof ref === "string" && !seenRefs.has(ref)) {
67
- let resolved;
68
- if (state.refs.has(ref)) resolved = state.refs.get(ref);
69
- else {
70
- resolved = effectiveSchema(resolvePointer(root, ref), root, /* @__PURE__ */ new Set([...seenRefs, ref]), depth + 1);
71
- state.refs.set(ref, resolved);
72
- }
73
- if (resolved) merge(resolved);
74
- }
75
- const allOf = object["allOf"];
76
- if (Array.isArray(allOf)) {
77
- for (const branch of allOf) {
78
- const resolved = effectiveSchema(branch, root, seenRefs, depth + 1);
79
- if (resolved) merge(resolved);
80
- }
81
- }
82
- return out;
83
- }
84
- function alternatives(object) {
85
- const branches = [];
86
- for (const keyword of ["anyOf", "oneOf"]) {
87
- const value = object[keyword];
88
- if (!Array.isArray(value)) continue;
89
- value.forEach((schema, index) => branches.push({ label: `${keyword}[${index}]`, schema }));
90
- }
91
- for (const keyword of ["then", "else", "not"]) {
92
- if (object[keyword] !== void 0) branches.push({ label: keyword, schema: object[keyword] });
93
- }
94
- return branches;
95
- }
96
-
97
- export {
98
- MAX_REF_DEPTH,
99
- MAX_VISIT_DEPTH,
100
- MAX_FACTS,
101
- MAX_RESOLUTIONS,
102
- asObject,
103
- resolvePointer,
104
- effectiveSchema,
105
- alternatives
106
- };
107
- //# sourceMappingURL=chunk-FVT77BL4.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lock/jsonschema.ts"],"sourcesContent":["/**\n * Just enough JSON Schema to see through the indirection servers actually use.\n *\n * Two parts of this tool have to look inside a tool's `inputSchema`: the widening heuristic and\n * the `x-mcp-header` scan. Both used to read only the literal node in front of them, so a schema\n * that put its properties behind `$ref` or `allOf` -- which the generators for Pydantic, Zod and\n * most OpenAPI toolchains do by default -- looked empty to both. A widened parameter went out as\n * a bare `.changed`, and a parameter newly mirrored into an HTTP header was missed entirely.\n *\n * This is not a validator. It resolves local `$ref`, flattens `allOf`, and leaves the\n * alternation keywords for the caller to branch on. Remote `$ref` is never fetched: an audit\n * that reaches out to a URL named by the thing it is auditing is not an audit.\n */\nimport type { JsonObject, JsonValue } from \"./types\";\n\n/** Depth caps. A hostile or merely recursive schema must not be able to hang the run. */\nexport const MAX_REF_DEPTH = 32;\nexport const MAX_VISIT_DEPTH = 12;\nexport const MAX_FACTS = 5_000;\n/**\n * Nodes one call may merge. A ceiling on total work, where the depth caps only bound how far down\n * one path goes; see `effectiveSchema`.\n */\nexport const MAX_RESOLUTIONS = 100_000;\n\n/*\n * What each `$ref` resolves to, per schema root. Without it, `allOf: [{$ref: next} x4]` at each of\n * sixteen levels resolved `next` once per path to it: 4^16 resolutions for an 1.8 KB schema,\n * synchronously, after the server had answered, so no timeout could stop it. A definition means\n * the same thing wherever it is referenced from, so it is resolved once.\n */\ninterface ResolutionState {\n refs: Map<string, JsonObject | undefined>;\n spent: number;\n}\nconst states = new WeakMap<object, ResolutionState>();\n\nfunction stateOf(root: JsonValue): ResolutionState {\n if (root === null || typeof root !== \"object\") return { refs: new Map(), spent: 0 };\n let state = states.get(root);\n if (!state) {\n state = { refs: new Map(), spent: 0 };\n states.set(root, state);\n }\n return state;\n}\n\nexport function asObject(value: JsonValue | undefined): JsonObject | undefined {\n return value !== null && value !== undefined && typeof value === \"object\" && !Array.isArray(value) ? (value as JsonObject) : undefined;\n}\n\n/** RFC 6901 token decoding: `~1` is `/` and `~0` is `~`, in that order. */\nfunction decodeToken(token: string): string {\n let decoded = token;\n try {\n decoded = decodeURIComponent(token);\n } catch {\n // A malformed escape is a literal, not a reason to abandon the schema.\n }\n return decoded.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n}\n\n/** Resolves a local JSON pointer. Anything with a non-empty URI part is left unresolved. */\nexport function resolvePointer(root: JsonValue, ref: string): JsonValue | undefined {\n if (!ref.startsWith(\"#\")) return undefined;\n const pointer = ref.slice(1);\n if (pointer !== \"\" && !pointer.startsWith(\"/\")) return undefined; // `#anchor`, which needs an anchor index.\n\n let node: JsonValue | undefined = root;\n for (const token of pointer.split(\"/\").slice(1)) {\n const object = asObject(node);\n if (object === undefined) return undefined;\n node = object[decodeToken(token)];\n }\n return node;\n}\n\n/**\n * The keywords in effect at a node, with `$ref` followed and `allOf` folded in.\n *\n * The node's own keywords win over anything it inherits, `properties` are unioned, and\n * `required` is the union of every contributor -- which is what `allOf` means. Alternation\n * (`anyOf` / `oneOf` / `then` / `else`) is deliberately left in place: a caller that wants to\n * treat branches as separate possibilities can, and one that does not is no worse off.\n */\nexport function effectiveSchema(node: JsonValue | undefined, root: JsonValue, seenRefs: ReadonlySet<string> = new Set(), depth = 0): JsonObject | undefined {\n const object = asObject(node);\n if (object === undefined) return undefined;\n if (depth > MAX_REF_DEPTH) return object;\n const state = stateOf(root);\n if (depth === 0) state.spent = 0;\n // Past the budget, a node is taken as written. Less precise, and never unbounded.\n if (++state.spent > MAX_RESOLUTIONS) return object;\n\n /*\n * No prototype, and own-property checks rather than `in`. `name in merged` on a plain object is\n * true for `constructor`, `toString` and `__proto__`, so a property with one of those names was\n * skipped as already merged, and `merged[\"__proto__\"] = ...` set the prototype instead.\n */\n const out = Object.create(null) as JsonObject;\n const merge = (source: JsonObject): void => {\n for (const [key, value] of Object.entries(source)) {\n if (key === \"$ref\" || key === \"allOf\") continue;\n if (key === \"properties\") {\n // First contributor wins on a conflict, and keeps its position: the merged object reads\n // in the order a person wrote it, not inside-out from the inheritance chain.\n const merged = Object.assign(Object.create(null) as JsonObject, asObject(out[\"properties\"]) ?? {});\n for (const [name, schema] of Object.entries(asObject(value) ?? {})) {\n if (!Object.hasOwn(merged, name)) Object.defineProperty(merged, name, { value: schema, enumerable: true, writable: true, configurable: true });\n }\n out[\"properties\"] = merged;\n } else if (key === \"required\" && Array.isArray(value)) {\n const already = Array.isArray(out[\"required\"]) ? (out[\"required\"] as JsonValue[]) : [];\n out[\"required\"] = [...new Set([...already, ...value].filter((entry): entry is string => typeof entry === \"string\"))];\n } else if (!Object.hasOwn(out, key)) {\n out[key] = value;\n }\n }\n };\n\n // The node itself first, so its own keywords take precedence over what it inherits.\n merge(object);\n\n const ref = object[\"$ref\"];\n if (typeof ref === \"string\" && !seenRefs.has(ref)) {\n let resolved: JsonObject | undefined;\n if (state.refs.has(ref)) resolved = state.refs.get(ref);\n else {\n resolved = effectiveSchema(resolvePointer(root, ref), root, new Set([...seenRefs, ref]), depth + 1);\n state.refs.set(ref, resolved);\n }\n if (resolved) merge(resolved);\n }\n\n const allOf = object[\"allOf\"];\n if (Array.isArray(allOf)) {\n for (const branch of allOf) {\n const resolved = effectiveSchema(branch, root, seenRefs, depth + 1);\n if (resolved) merge(resolved);\n }\n }\n\n return out;\n}\n\n/** The alternation branches at a node, labelled so a caller can key facts by them. */\nexport function alternatives(object: JsonObject): Array<{ label: string; schema: JsonValue }> {\n const branches: Array<{ label: string; schema: JsonValue }> = [];\n for (const keyword of [\"anyOf\", \"oneOf\"] as const) {\n const value = object[keyword];\n if (!Array.isArray(value)) continue;\n value.forEach((schema, index) => branches.push({ label: `${keyword}[${index}]`, schema }));\n }\n for (const keyword of [\"then\", \"else\", \"not\"] as const) {\n if (object[keyword] !== undefined) branches.push({ label: keyword, schema: object[keyword] as JsonValue });\n }\n return branches;\n}\n"],"mappings":";AAgBO,IAAM,gBAAgB;AACtB,IAAM,kBAAkB;AACxB,IAAM,YAAY;AAKlB,IAAM,kBAAkB;AAY/B,IAAM,SAAS,oBAAI,QAAiC;AAEpD,SAAS,QAAQ,MAAkC;AACjD,MAAI,SAAS,QAAQ,OAAO,SAAS,SAAU,QAAO,EAAE,MAAM,oBAAI,IAA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AK,QAAQ;AAAA,IAC9B;AACA,QAAI,SAAU,OAAM,QAAQ;AAAA,EAC9B;AAEA,QAAM,QAAQ,OAAO,OAAO;AAC5B,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,eAAW,UAAU,OAAO;AAC1B,YAAM,WAAW,gBAAgB,QAAQ,MAAM,UAAU,QAAQ,CAAC;AAClE,UAAI,SAAU,OAAM,QAAQ;AAAA,IAC9B;AAAA,EACF;AAEA,SAAO;AACT;AAGO,SAAS,aAAa,QAAiE;AAC5F,QAAM,WAAwD,CAAC;AAC/D,aAAW,WAAW,CAAC,SAAS,OAAO,GAAY;AACjD,UAAM,QAAQ,OAAO,OAAO;AAC5B,QAAI,CAAC,MAAM,QAAQ,KAAK,EAAG;AAC3B,UAAM,QAAQ,CAAC,QAAQ,UAAU,SAAS,KAAK,EAAE,OAAO,GAAG,OAAO,IAAI,KAAK,KAAK,OAAO,CAAC,CAAC;AAAA,EAC3F;AACA,aAAW,WAAW,CAAC,QAAQ,QAAQ,KAAK,GAAY;AACtD,QAAI,OAAO,OAAO,MAAM,OAAW,UAAS,KAAK,EAAE,OAAO,SAAS,QAAQ,OAAO,OAAO,EAAe,CAAC;AAAA,EAC3G;AACA,SAAO;AACT;","names":[]}
@@ -1,127 +0,0 @@
1
- import {
2
- canonicalize,
3
- stableKey
4
- } from "./chunk-SZKRNTJP.js";
5
- import {
6
- MAX_FACTS,
7
- MAX_VISIT_DEPTH,
8
- alternatives,
9
- asObject,
10
- effectiveSchema
11
- } from "./chunk-FVT77BL4.js";
12
-
13
- // src/diff/schema.ts
14
- function numberAt(node, key) {
15
- const value = node[key];
16
- return typeof value === "number" ? value : void 0;
17
- }
18
- function collectFacts(schema) {
19
- const facts = /* @__PURE__ */ new Map();
20
- const visit = (node, path, required, depth) => {
21
- if (depth > MAX_VISIT_DEPTH || facts.size >= MAX_FACTS) return;
22
- const object = effectiveSchema(node, schema);
23
- if (!object) return;
24
- const typeValue = object["type"];
25
- const types = typeof typeValue === "string" ? [typeValue] : Array.isArray(typeValue) ? typeValue.filter((entry) => typeof entry === "string").sort() : void 0;
26
- const enumValue = object["enum"];
27
- facts.set(path, {
28
- required,
29
- additionalProperties: typeof object["additionalProperties"] === "boolean" ? object["additionalProperties"] : void 0,
30
- enumMembers: Array.isArray(enumValue) ? enumValue.map((entry) => canonicalize(entry)).sort() : void 0,
31
- types,
32
- minimum: numberAt(object, "minimum"),
33
- maximum: numberAt(object, "maximum"),
34
- minLength: numberAt(object, "minLength"),
35
- maxLength: numberAt(object, "maxLength")
36
- });
37
- const properties = asObject(object["properties"]);
38
- if (properties) {
39
- const requiredList = Array.isArray(object["required"]) ? object["required"].filter((entry) => typeof entry === "string") : [];
40
- const requiredSet = new Set(requiredList);
41
- for (const [name, child] of Object.entries(properties)) {
42
- visit(child, path === "" ? name : `${path}.${name}`, requiredSet.has(name), depth + 1);
43
- }
44
- }
45
- const items = object["items"];
46
- if (items !== void 0) visit(items, `${path}[]`, false, depth + 1);
47
- const prefixItems = object["prefixItems"];
48
- if (Array.isArray(prefixItems)) prefixItems.forEach((entry, index) => visit(entry, `${path}[${index}]`, false, depth + 1));
49
- for (const branch of alternatives(object)) visit(branch.schema, `${path}|${branch.label}`, false, depth + 1);
50
- };
51
- visit(schema, "", true, 0);
52
- return facts;
53
- }
54
- function isSuperset(next, previous) {
55
- const members = new Set(next);
56
- return previous.every((entry) => members.has(entry));
57
- }
58
- function classifySchemaChange(before, after) {
59
- if (stableKey(before) === stableKey(after)) return "same";
60
- const previous = collectFacts(before);
61
- const next = collectFacts(after);
62
- let widened = false;
63
- let narrowed = false;
64
- for (const path of /* @__PURE__ */ new Set([...previous.keys(), ...next.keys()])) {
65
- const a = previous.get(path);
66
- const b = next.get(path);
67
- if (!a && b) {
68
- widened = true;
69
- continue;
70
- }
71
- if (a && !b) {
72
- narrowed = true;
73
- continue;
74
- }
75
- if (!a || !b) continue;
76
- if (a.required && !b.required) widened = true;
77
- if (!a.required && b.required) narrowed = true;
78
- const beforeAdditional = a.additionalProperties ?? true;
79
- const afterAdditional = b.additionalProperties ?? true;
80
- if (!beforeAdditional && afterAdditional) widened = true;
81
- if (beforeAdditional && !afterAdditional) narrowed = true;
82
- if (a.enumMembers && b.enumMembers) {
83
- if (isSuperset(b.enumMembers, a.enumMembers) && b.enumMembers.length > a.enumMembers.length) widened = true;
84
- else if (isSuperset(a.enumMembers, b.enumMembers) && a.enumMembers.length > b.enumMembers.length) narrowed = true;
85
- else if (canonicalize(a.enumMembers) !== canonicalize(b.enumMembers)) {
86
- widened = true;
87
- narrowed = true;
88
- }
89
- } else if (a.enumMembers && !b.enumMembers) widened = true;
90
- else if (!a.enumMembers && b.enumMembers) narrowed = true;
91
- if (a.types && b.types) {
92
- if (isSuperset(b.types, a.types) && b.types.length > a.types.length) widened = true;
93
- else if (isSuperset(a.types, b.types) && a.types.length > b.types.length) narrowed = true;
94
- else if (canonicalize(a.types) !== canonicalize(b.types)) {
95
- widened = true;
96
- narrowed = true;
97
- }
98
- } else if (a.types && !b.types) widened = true;
99
- else if (!a.types && b.types) narrowed = true;
100
- const lowerBounds = [["minimum", a.minimum, b.minimum], ["minLength", a.minLength, b.minLength]];
101
- for (const [, before_, after_] of lowerBounds) {
102
- if (before_ !== void 0 && after_ === void 0) widened = true;
103
- else if (before_ === void 0 && after_ !== void 0) narrowed = true;
104
- else if (before_ !== void 0 && after_ !== void 0) {
105
- if (after_ < before_) widened = true;
106
- if (after_ > before_) narrowed = true;
107
- }
108
- }
109
- const upperBounds = [["maximum", a.maximum, b.maximum], ["maxLength", a.maxLength, b.maxLength]];
110
- for (const [, before_, after_] of upperBounds) {
111
- if (before_ !== void 0 && after_ === void 0) widened = true;
112
- else if (before_ === void 0 && after_ !== void 0) narrowed = true;
113
- else if (before_ !== void 0 && after_ !== void 0) {
114
- if (after_ > before_) widened = true;
115
- if (after_ < before_) narrowed = true;
116
- }
117
- }
118
- }
119
- if (widened && !narrowed) return "widened";
120
- if (narrowed && !widened) return "narrowed";
121
- return "changed";
122
- }
123
-
124
- export {
125
- classifySchemaChange
126
- };
127
- //# sourceMappingURL=chunk-TRNJNLQQ.js.map