@glassbox-ai/engine 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +31 -2
  3. package/dist/action/acc.d.ts +48 -0
  4. package/dist/action/acc.js +117 -0
  5. package/dist/action/inline.d.ts +14 -0
  6. package/dist/action/inline.js +54 -0
  7. package/dist/action/paths.d.ts +71 -0
  8. package/dist/action/paths.js +398 -0
  9. package/dist/action/powershell.d.ts +9 -0
  10. package/dist/action/powershell.js +848 -0
  11. package/dist/action/protected-write.d.ts +11 -0
  12. package/dist/action/protected-write.js +113 -0
  13. package/dist/action/schedule.d.ts +43 -0
  14. package/dist/action/schedule.js +213 -0
  15. package/dist/action/shell/analyze.d.ts +28 -0
  16. package/dist/action/shell/analyze.js +2030 -0
  17. package/dist/action/shell/parse.d.ts +74 -0
  18. package/dist/action/shell/parse.js +1037 -0
  19. package/dist/action/shell/view.d.ts +6 -0
  20. package/dist/action/shell/view.js +89 -0
  21. package/dist/action/sql.d.ts +3 -0
  22. package/dist/action/sql.js +259 -0
  23. package/dist/action/tools.d.ts +20 -0
  24. package/dist/action/tools.js +240 -0
  25. package/dist/action/upload.d.ts +17 -0
  26. package/dist/action/upload.js +72 -0
  27. package/dist/analysis/fields.d.ts +14 -0
  28. package/dist/analysis/fields.js +136 -0
  29. package/dist/analysis/findings.d.ts +25 -0
  30. package/dist/analysis/findings.js +82 -0
  31. package/dist/analysis/gate.d.ts +16 -0
  32. package/dist/analysis/gate.js +660 -0
  33. package/dist/analysis/manifest.d.ts +3 -0
  34. package/dist/analysis/manifest.js +369 -0
  35. package/dist/analysis/match.d.ts +54 -0
  36. package/dist/analysis/match.js +352 -0
  37. package/dist/analysis/scan.d.ts +17 -0
  38. package/dist/analysis/scan.js +97 -0
  39. package/dist/canon/confusables.generated.d.ts +3 -0
  40. package/dist/canon/confusables.generated.js +6 -0
  41. package/dist/canon/decode.d.ts +11 -0
  42. package/dist/canon/decode.js +147 -0
  43. package/dist/canon/views.d.ts +36 -0
  44. package/dist/canon/views.js +283 -0
  45. package/dist/evidence/evidence.d.ts +12 -0
  46. package/dist/evidence/evidence.js +149 -0
  47. package/dist/fingerprint/diff.d.ts +3 -0
  48. package/dist/fingerprint/diff.js +273 -0
  49. package/dist/fingerprint/fingerprint.d.ts +4 -0
  50. package/dist/fingerprint/fingerprint.js +77 -0
  51. package/dist/grade/score.d.ts +19 -0
  52. package/dist/grade/score.js +89 -0
  53. package/dist/index.d.ts +22 -0
  54. package/dist/index.js +148 -0
  55. package/dist/intake/json.d.ts +17 -0
  56. package/dist/intake/json.js +284 -0
  57. package/dist/intake/snapshot.d.ts +14 -0
  58. package/dist/intake/snapshot.js +130 -0
  59. package/dist/limits.d.ts +4 -0
  60. package/dist/limits.js +30 -0
  61. package/dist/policy/decide.d.ts +26 -0
  62. package/dist/policy/decide.js +74 -0
  63. package/dist/rules/ids.d.ts +2 -0
  64. package/dist/rules/ids.js +99 -0
  65. package/dist/ruleset/baseline-tests.generated.d.ts +6 -0
  66. package/dist/ruleset/baseline-tests.generated.js +2935 -0
  67. package/dist/ruleset/baseline.d.ts +3 -0
  68. package/dist/ruleset/baseline.generated.d.ts +3 -0
  69. package/dist/ruleset/baseline.generated.js +5 -0
  70. package/dist/ruleset/baseline.js +44 -0
  71. package/dist/ruleset/fakes.d.ts +3 -0
  72. package/dist/ruleset/fakes.js +26 -0
  73. package/dist/ruleset/load.d.ts +14 -0
  74. package/dist/ruleset/load.js +173 -0
  75. package/dist/ruleset/schema.d.ts +120 -0
  76. package/dist/ruleset/schema.js +54 -0
  77. package/dist/ruleset/selftest.d.ts +18 -0
  78. package/dist/ruleset/selftest.js +42 -0
  79. package/dist/ruleset-entry.d.ts +5 -0
  80. package/dist/ruleset-entry.js +7 -0
  81. package/dist/secrets/detect.d.ts +17 -0
  82. package/dist/secrets/detect.js +236 -0
  83. package/dist/secrets/redact.d.ts +19 -0
  84. package/dist/secrets/redact.js +116 -0
  85. package/dist/types.d.ts +434 -0
  86. package/dist/types.js +10 -0
  87. package/dist/util/hash.d.ts +4 -0
  88. package/dist/util/hash.js +16 -0
  89. package/dist/util/initclock.d.ts +3 -0
  90. package/dist/util/initclock.js +17 -0
  91. package/dist/util/jcs.d.ts +4 -0
  92. package/dist/util/jcs.js +91 -0
  93. package/dist/util/misc.d.ts +17 -0
  94. package/dist/util/misc.js +77 -0
  95. package/dist/util/re.d.ts +14 -0
  96. package/dist/util/re.js +47 -0
  97. package/dist/version.d.ts +2 -0
  98. package/dist/version.js +2 -0
  99. package/package.json +55 -3
@@ -0,0 +1,72 @@
1
+ import { isProtectedRead, sensitiveLabel } from "./paths.js";
2
+ /** True for loopback host names and addresses. */
3
+ export function isLoopbackHost(host) {
4
+ const h = host.toLowerCase().replace(/^\[|\]$/g, "");
5
+ if (h === "localhost" || h.endsWith(".localhost") || h === "::1" || h === "0.0.0.0")
6
+ return true;
7
+ const parts = h.split(".");
8
+ return parts.length === 4 && parts[0] === "127" && parts.every((p) => /^\d{1,3}$/.test(p) && Number(p) <= 255);
9
+ }
10
+ /**
11
+ * The host of a URL, a bare host[:port][/path], or user@host:path. Null when there is none
12
+ * (for example a value with no host-like start). String code only.
13
+ */
14
+ export function hostOf(v) {
15
+ let s = v.trim();
16
+ const scheme = s.indexOf("://");
17
+ if (scheme > 0)
18
+ s = s.slice(scheme + 3);
19
+ const at = s.indexOf("@");
20
+ const slash = s.indexOf("/");
21
+ if (at >= 0 && (slash < 0 || at < slash))
22
+ s = s.slice(at + 1);
23
+ if (s.startsWith("[")) {
24
+ const end = s.indexOf("]");
25
+ return end > 0 ? s.slice(0, end + 1) : null;
26
+ }
27
+ let end = s.length;
28
+ for (const ch of [":", "/", "?", "#"]) {
29
+ const i = s.indexOf(ch);
30
+ if (i >= 0 && i < end)
31
+ end = i;
32
+ }
33
+ const host = s.slice(0, end);
34
+ return host.length > 0 ? host : null;
35
+ }
36
+ /** Destinations are known and all on this machine. */
37
+ export function allLoopback(destinations) {
38
+ if (destinations.length === 0)
39
+ return false;
40
+ return destinations.every((d) => d !== null && (() => { const h = hostOf(d); return h !== null && isLoopbackHost(h); })());
41
+ }
42
+ /** Classifies an uploaded file. `projectDir` is the session's project directory. */
43
+ export function classifyUpload(np, pctx, projectDir) {
44
+ if (np === null || np.path === null) {
45
+ if (np !== null && sensitiveLabel(np, pctx))
46
+ return "sensitive";
47
+ return "outside"; // not known statically: it can't be shown to be a project file
48
+ }
49
+ if (isProtectedRead(np, pctx) || sensitiveLabel(np, pctx))
50
+ return "sensitive";
51
+ if (projectDir === null)
52
+ return "outside";
53
+ const fold = (s) => (pctx.caseInsensitive ? s.toLowerCase() : s);
54
+ const root = fold(projectDir.endsWith("/") ? projectDir.slice(0, -1) : projectDir);
55
+ const p = fold(np.path);
56
+ return p === root || p.startsWith(root + "/") ? "project" : "outside";
57
+ }
58
+ /** Records one uploaded file (the caller has checked the destination isn't loopback). */
59
+ export function recordUpload(acc, kind, what) {
60
+ acc.uploads.push(kind);
61
+ acc.tag("high-risk", "net.egress");
62
+ acc.network = true;
63
+ if (kind === "sensitive") {
64
+ acc.sensitiveArgs = true;
65
+ acc.find("CP-EXFIL-030", `uploads a sensitive file (${what})`);
66
+ }
67
+ else if (kind === "outside") {
68
+ acc.find("CP-EXFIL-035", `uploads a file from outside the project, or one that isn't known statically (${what})`);
69
+ }
70
+ acc.reason(`uploads a local file (${what})`);
71
+ }
72
+ //# sourceMappingURL=upload.js.map
@@ -0,0 +1,14 @@
1
+ export interface Field {
2
+ pointer: string;
3
+ kind: "string" | "key";
4
+ role: string;
5
+ text: string;
6
+ /** JSON key the string sits under (for key-name-sensitive detectors). */
7
+ keyName: string | undefined;
8
+ /** Index of the tool this field belongs to (manifest only). */
9
+ toolIndex?: number;
10
+ }
11
+ export declare function manifestFields(m: unknown, maxTools: number): Field[];
12
+ export declare function genericFields(root: unknown, base: string, role: string, keyRole: string): Field[];
13
+ export declare function roleMatches(patterns: readonly string[] | undefined, role: string): boolean;
14
+ //# sourceMappingURL=fields.d.ts.map
@@ -0,0 +1,136 @@
1
+ // C3 (engine-spec §5.3): field enumeration with roles, per surface. Iterative.
2
+ import { jcs } from "../util/jcs.js";
3
+ import { isRecord, ptrSeg } from "../util/misc.js";
4
+ function walk(root, base, emit, maxNodes = 200_000) {
5
+ const stack = [{ v: root, pointer: base, path: [], key: undefined }];
6
+ let n = 0;
7
+ while (stack.length > 0 && n++ < maxNodes) {
8
+ const w = stack.pop();
9
+ const v = w.v;
10
+ if (typeof v === "string")
11
+ emit(w, false);
12
+ else if (Array.isArray(v)) {
13
+ for (let i = v.length - 1; i >= 0; i--)
14
+ stack.push({ v: v[i], pointer: `${w.pointer}/${i}`, path: [...w.path, String(i)], key: w.key });
15
+ }
16
+ else if (isRecord(v)) {
17
+ const keys = Object.keys(v);
18
+ for (let i = keys.length - 1; i >= 0; i--) {
19
+ const k = keys[i];
20
+ const child = { v: v[k], pointer: `${w.pointer}/${ptrSeg(k)}`, path: [...w.path, k], key: k };
21
+ stack.push(child);
22
+ }
23
+ // Keys are fields too (emitted in document order before values).
24
+ for (const k of keys)
25
+ emit({ v: k, pointer: `${w.pointer}/${ptrSeg(k)}`, path: [...w.path, k], key: k }, true);
26
+ }
27
+ }
28
+ }
29
+ function schemaRole(path, isKey) {
30
+ // path inside inputSchema/outputSchema
31
+ const last = path[path.length - 1] ?? "";
32
+ const parent = path[path.length - 2] ?? "";
33
+ if (isKey)
34
+ return parent === "properties" ? "tool.schema.key" : "tool.schema.other";
35
+ if (path.includes("enum"))
36
+ return "tool.schema.enum";
37
+ if (path.includes("examples"))
38
+ return "tool.schema.examples";
39
+ if (last === "default" || path.includes("default"))
40
+ return "tool.schema.default";
41
+ if (last === "const")
42
+ return "tool.schema.const";
43
+ if (last === "description")
44
+ return "tool.schema.description";
45
+ if (last === "title")
46
+ return "tool.schema.title";
47
+ return "tool.schema.other";
48
+ }
49
+ export function manifestFields(m, maxTools) {
50
+ const out = [];
51
+ walk(m, "", (w, isKey) => {
52
+ // "key~dupN" (a duplicated JSON key, §5.2) takes the role of "key".
53
+ const p = w.path.map((seg) => seg.replace(/~dup\d+$/, ""));
54
+ let role = "manifest.other";
55
+ let toolIndex;
56
+ if (p[0] === "initialize") {
57
+ if (p[1] === "instructions" && !isKey)
58
+ role = "server.instructions";
59
+ else if (p[1] === "serverInfo")
60
+ role = "server.info";
61
+ }
62
+ else if (p[0] === "tools" && p.length >= 2) {
63
+ toolIndex = Number(p[1]);
64
+ if (toolIndex >= maxTools)
65
+ return;
66
+ const f = p[2];
67
+ if (p.length === 3 && !isKey && (f === "name" || f === "title" || f === "description"))
68
+ role = `tool.${f}`;
69
+ else if (f === "annotations")
70
+ role = "tool.annotation";
71
+ else if ((f === "inputSchema" || f === "outputSchema") && p.length > 3)
72
+ role = schemaRole(p.slice(3), isKey);
73
+ else if (isKey && p.length === 3)
74
+ role = "tool.key";
75
+ else
76
+ role = "tool.other";
77
+ }
78
+ else if (p[0] === "prompts")
79
+ role = p[2] === "name" && p.length === 3 ? "prompt.name" : "prompt.text";
80
+ else if (p[0] === "resources" || p[0] === "resourceTemplates")
81
+ role = "resource.text";
82
+ // Ordinary structural keys are not interesting text.
83
+ if (isKey && (role === "manifest.other" || role === "tool.key" || role === "tool.other" || role === "tool.annotation" || role === "server.info" || role === "prompt.text" || role === "resource.text"))
84
+ return;
85
+ out.push({ pointer: w.pointer, kind: isKey ? "key" : "string", role, text: String(w.v), keyName: w.key, ...(toolIndex !== undefined ? { toolIndex } : {}) });
86
+ });
87
+ // Non-string enum/default/const values are scanned in JCS form (§5.3).
88
+ const tools = isRecord(m) && Array.isArray(m["tools"]) ? m["tools"] : [];
89
+ tools.slice(0, maxTools).forEach((t, ti) => {
90
+ for (const s of ["inputSchema", "outputSchema"]) {
91
+ const sch = isRecord(t) ? t[s] : undefined;
92
+ walkNonString(sch, `/tools/${ti}/${s}`, (pointer, value, role) => out.push({ pointer, kind: "string", role, text: value, keyName: undefined, toolIndex: ti }));
93
+ }
94
+ });
95
+ return out;
96
+ }
97
+ function walkNonString(root, base, emit) {
98
+ const stack = [{ v: root, pointer: base }];
99
+ let n = 0;
100
+ while (stack.length > 0 && n++ < 50_000) {
101
+ const { v, pointer } = stack.pop();
102
+ if (Array.isArray(v))
103
+ v.forEach((x, i) => stack.push({ v: x, pointer: `${pointer}/${i}` }));
104
+ else if (isRecord(v)) {
105
+ for (const k of Object.keys(v)) {
106
+ const x = v[k];
107
+ if ((k === "default" || k === "const") && x !== null && typeof x === "object") {
108
+ try {
109
+ emit(`${pointer}/${ptrSeg(k)}`, jcs(x), k === "default" ? "tool.schema.default" : "tool.schema.const");
110
+ }
111
+ catch { /* skip */ }
112
+ }
113
+ stack.push({ v: x, pointer: `${pointer}/${ptrSeg(k)}` });
114
+ }
115
+ }
116
+ }
117
+ }
118
+ export function genericFields(root, base, role, keyRole) {
119
+ const out = [];
120
+ walk(root, base, (w, isKey) => {
121
+ out.push({ pointer: w.pointer, kind: isKey ? "key" : "string", role: isKey ? keyRole : role, text: String(w.v), keyName: w.key });
122
+ });
123
+ return out;
124
+ }
125
+ export function roleMatches(patterns, role) {
126
+ if (!patterns || patterns.length === 0)
127
+ return true;
128
+ for (const p of patterns) {
129
+ if (p === "*" || p === role)
130
+ return true;
131
+ if (p.endsWith(".*") && role.startsWith(p.slice(0, -1)))
132
+ return true;
133
+ }
134
+ return false;
135
+ }
136
+ //# sourceMappingURL=fields.js.map
@@ -0,0 +1,25 @@
1
+ import type { Finding, LoadedRuleset, RuleDef, Severity, ViaKind } from "../types.js";
2
+ export declare class FindingFactory {
3
+ readonly evidenceMode: "snippet" | "none";
4
+ private byId;
5
+ constructor(ruleset: LoadedRuleset, evidenceMode: "snippet" | "none");
6
+ rule(id: string): RuleDef | undefined;
7
+ has(id: string): boolean;
8
+ make(args: {
9
+ ruleId: string;
10
+ location: string;
11
+ text?: string;
12
+ start?: number;
13
+ end?: number;
14
+ via?: ViaKind[];
15
+ severity?: Severity;
16
+ confidence?: number;
17
+ related?: string[];
18
+ explanation?: string;
19
+ }): Finding | null;
20
+ }
21
+ export declare const sevRank: (s: Severity) => number;
22
+ export declare function sortFindings(fs: Finding[]): Finding[];
23
+ /** One finding per (rule, location): keep the most severe. */
24
+ export declare function dedupe(fs: (Finding | null)[]): Finding[];
25
+ //# sourceMappingURL=findings.d.ts.map
@@ -0,0 +1,82 @@
1
+ // Finding construction (engine-spec §4.1, §8.3) and the rule-metadata lookup.
2
+ import { makeEvidence } from "../evidence/evidence.js";
3
+ import { sha256Hex } from "../util/hash.js";
4
+ /** Minimal metadata for engine-emitted rules, used only if a ruleset lacks the rule. */
5
+ const FALLBACK = {
6
+ "CP-ACTION-001": ["dangerous-action", "critical"], "CP-FLOW-002": ["toxic-flow", "critical"], "CP-SRVREQ-002": ["server-request", "critical"],
7
+ "CP-SRVREQ-010": ["server-request", "critical"], "CP-SELF-001": ["self-protection", "high"], "CP-SELF-002": ["self-protection", "high"],
8
+ "CP-SELF-003": ["self-protection", "high"], "CP-SHELL-001": ["obfuscation", "medium"],
9
+ };
10
+ export class FindingFactory {
11
+ evidenceMode;
12
+ byId = new Map();
13
+ constructor(ruleset, evidenceMode) {
14
+ this.evidenceMode = evidenceMode;
15
+ for (const r of ruleset.rules)
16
+ this.byId.set(r.id, r);
17
+ }
18
+ rule(id) {
19
+ return this.byId.get(id);
20
+ }
21
+ has(id) {
22
+ return this.byId.has(id);
23
+ }
24
+ make(args) {
25
+ const r = this.byId.get(args.ruleId);
26
+ const fb = FALLBACK[args.ruleId];
27
+ if (!r && !fb)
28
+ return null;
29
+ const via = args.via ?? [];
30
+ const text = args.text ?? "";
31
+ const start = Math.max(0, Math.min(args.start ?? 0, text.length));
32
+ const end = Math.max(start, Math.min(args.end ?? Math.min(text.length, start + 80), text.length));
33
+ const f = {
34
+ id: sha256Hex(`${args.ruleId}\u0000${args.location}\u0000${via.join(",")}`).slice(0, 16),
35
+ ruleId: args.ruleId,
36
+ ruleSource: args.ruleId.startsWith("PV-") ? "private" : "baseline",
37
+ category: r?.category ?? fb[0],
38
+ severity: args.severity ?? r?.severity ?? fb[1],
39
+ confidence: Math.round((args.confidence ?? r?.confidence ?? 1) * 100) / 100,
40
+ location: args.location,
41
+ evidence: text.length > 0 ? makeEvidence(text, start, end, this.evidenceMode) : this.evidenceMode === "none" ? "[evidence withheld by policy]" : '""',
42
+ explanation: args.explanation ?? r?.explanation ?? `Glassbox rule ${args.ruleId} matched.`,
43
+ remediation: r?.remediation ?? "Review this action.",
44
+ };
45
+ if (text.length > 0)
46
+ f.span = { start: cpOffset(text, start), end: cpOffset(text, end) };
47
+ if (via.length > 0)
48
+ f.via = via;
49
+ if (args.related && args.related.length > 0)
50
+ f.related = args.related;
51
+ return f;
52
+ }
53
+ }
54
+ function cpOffset(s, utf16) {
55
+ let n = 0;
56
+ for (let i = 0; i < utf16 && i < s.length; i++) {
57
+ const c = s.charCodeAt(i);
58
+ if (c >= 0xd800 && c <= 0xdbff && i + 1 < utf16)
59
+ i++;
60
+ n++;
61
+ }
62
+ return n;
63
+ }
64
+ const SEV = ["info", "low", "medium", "high", "critical"];
65
+ export const sevRank = (s) => SEV.indexOf(s);
66
+ export function sortFindings(fs) {
67
+ return fs.sort((a, b) => sevRank(b.severity) - sevRank(a.severity) || (a.ruleId < b.ruleId ? -1 : a.ruleId > b.ruleId ? 1 : 0) || (a.location < b.location ? -1 : a.location > b.location ? 1 : 0));
68
+ }
69
+ /** One finding per (rule, location): keep the most severe. */
70
+ export function dedupe(fs) {
71
+ const m = new Map();
72
+ for (const f of fs) {
73
+ if (!f)
74
+ continue;
75
+ const k = f.ruleId + "\u0000" + f.location;
76
+ const prev = m.get(k);
77
+ if (!prev || sevRank(f.severity) > sevRank(prev.severity))
78
+ m.set(k, f);
79
+ }
80
+ return [...m.values()];
81
+ }
82
+ //# sourceMappingURL=findings.js.map
@@ -0,0 +1,16 @@
1
+ import { type IntakeIssue } from "../intake/json.js";
2
+ import type { ActionRisk, Decision, Limits, SessionContext } from "../types.js";
3
+ export declare const HIGH_RISK_UNKNOWN: ActionRisk;
4
+ interface Intake {
5
+ value: unknown;
6
+ issues: IntakeIssue[];
7
+ degraded: boolean;
8
+ tooBig: boolean;
9
+ }
10
+ export declare function intake(input: unknown, limits: Limits): Intake;
11
+ export declare function errorDecision(t0: number, mode: SessionContext["policy"]["mode"] | undefined, risk?: ActionRisk): Decision;
12
+ export declare function checkToolCallImpl(input: unknown, ctxIn: SessionContext, t0: number): Decision;
13
+ export declare function checkToolResultImpl(input: unknown, ctxIn: SessionContext, t0: number): Decision;
14
+ export declare function checkServerRequestImpl(input: unknown, ctxIn: SessionContext, t0: number): Decision;
15
+ export {};
16
+ //# sourceMappingURL=gate.d.ts.map