@glassbox-ai/engine 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +33 -2
  3. package/dist/action/acc.d.ts +48 -0
  4. package/dist/action/acc.js +117 -0
  5. package/dist/action/builtin-tools.d.ts +5 -0
  6. package/dist/action/builtin-tools.js +74 -0
  7. package/dist/action/inline.d.ts +14 -0
  8. package/dist/action/inline.js +54 -0
  9. package/dist/action/paths.d.ts +71 -0
  10. package/dist/action/paths.js +398 -0
  11. package/dist/action/powershell.d.ts +9 -0
  12. package/dist/action/powershell.js +848 -0
  13. package/dist/action/protected-write.d.ts +11 -0
  14. package/dist/action/protected-write.js +113 -0
  15. package/dist/action/schedule.d.ts +43 -0
  16. package/dist/action/schedule.js +213 -0
  17. package/dist/action/shell/analyze.d.ts +28 -0
  18. package/dist/action/shell/analyze.js +2057 -0
  19. package/dist/action/shell/parse.d.ts +74 -0
  20. package/dist/action/shell/parse.js +1037 -0
  21. package/dist/action/shell/view.d.ts +6 -0
  22. package/dist/action/shell/view.js +89 -0
  23. package/dist/action/sql.d.ts +3 -0
  24. package/dist/action/sql.js +259 -0
  25. package/dist/action/tools.d.ts +20 -0
  26. package/dist/action/tools.js +305 -0
  27. package/dist/action/upload.d.ts +17 -0
  28. package/dist/action/upload.js +72 -0
  29. package/dist/analysis/fields.d.ts +14 -0
  30. package/dist/analysis/fields.js +136 -0
  31. package/dist/analysis/findings.d.ts +25 -0
  32. package/dist/analysis/findings.js +82 -0
  33. package/dist/analysis/gate.d.ts +16 -0
  34. package/dist/analysis/gate.js +662 -0
  35. package/dist/analysis/manifest.d.ts +3 -0
  36. package/dist/analysis/manifest.js +369 -0
  37. package/dist/analysis/match.d.ts +54 -0
  38. package/dist/analysis/match.js +352 -0
  39. package/dist/analysis/scan.d.ts +17 -0
  40. package/dist/analysis/scan.js +97 -0
  41. package/dist/canon/confusables.generated.d.ts +3 -0
  42. package/dist/canon/confusables.generated.js +6 -0
  43. package/dist/canon/decode.d.ts +11 -0
  44. package/dist/canon/decode.js +147 -0
  45. package/dist/canon/views.d.ts +36 -0
  46. package/dist/canon/views.js +283 -0
  47. package/dist/evidence/evidence.d.ts +12 -0
  48. package/dist/evidence/evidence.js +149 -0
  49. package/dist/fingerprint/diff.d.ts +3 -0
  50. package/dist/fingerprint/diff.js +273 -0
  51. package/dist/fingerprint/fingerprint.d.ts +4 -0
  52. package/dist/fingerprint/fingerprint.js +77 -0
  53. package/dist/grade/score.d.ts +19 -0
  54. package/dist/grade/score.js +89 -0
  55. package/dist/index.d.ts +26 -0
  56. package/dist/index.js +152 -0
  57. package/dist/intake/json.d.ts +17 -0
  58. package/dist/intake/json.js +284 -0
  59. package/dist/intake/snapshot.d.ts +14 -0
  60. package/dist/intake/snapshot.js +130 -0
  61. package/dist/limits.d.ts +4 -0
  62. package/dist/limits.js +30 -0
  63. package/dist/policy/decide.d.ts +32 -0
  64. package/dist/policy/decide.js +105 -0
  65. package/dist/rules/ids.d.ts +2 -0
  66. package/dist/rules/ids.js +99 -0
  67. package/dist/ruleset/baseline-tests.generated.d.ts +6 -0
  68. package/dist/ruleset/baseline-tests.generated.js +2935 -0
  69. package/dist/ruleset/baseline.d.ts +3 -0
  70. package/dist/ruleset/baseline.generated.d.ts +3 -0
  71. package/dist/ruleset/baseline.generated.js +5 -0
  72. package/dist/ruleset/baseline.js +44 -0
  73. package/dist/ruleset/fakes.d.ts +3 -0
  74. package/dist/ruleset/fakes.js +26 -0
  75. package/dist/ruleset/load.d.ts +13 -0
  76. package/dist/ruleset/load.js +187 -0
  77. package/dist/ruleset/schema.d.ts +120 -0
  78. package/dist/ruleset/schema.js +54 -0
  79. package/dist/ruleset/selftest.d.ts +18 -0
  80. package/dist/ruleset/selftest.js +42 -0
  81. package/dist/ruleset-entry.d.ts +5 -0
  82. package/dist/ruleset-entry.js +7 -0
  83. package/dist/secrets/detect.d.ts +17 -0
  84. package/dist/secrets/detect.js +236 -0
  85. package/dist/secrets/redact.d.ts +19 -0
  86. package/dist/secrets/redact.js +116 -0
  87. package/dist/types.d.ts +455 -0
  88. package/dist/types.js +10 -0
  89. package/dist/util/hash.d.ts +4 -0
  90. package/dist/util/hash.js +16 -0
  91. package/dist/util/initclock.d.ts +3 -0
  92. package/dist/util/initclock.js +17 -0
  93. package/dist/util/jcs.d.ts +4 -0
  94. package/dist/util/jcs.js +91 -0
  95. package/dist/util/misc.d.ts +17 -0
  96. package/dist/util/misc.js +77 -0
  97. package/dist/util/re.d.ts +14 -0
  98. package/dist/util/re.js +47 -0
  99. package/dist/version.d.ts +2 -0
  100. package/dist/version.js +2 -0
  101. package/package.json +57 -4
@@ -0,0 +1,120 @@
1
+ import * as v from "valibot";
2
+ import { type Matcher } from "../types.js";
3
+ export declare const RuleSchema: v.ObjectSchema<{
4
+ readonly id: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>;
5
+ readonly revision: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 1, undefined>]>;
6
+ readonly category: v.PicklistSchema<readonly ["tool-poisoning", "hidden-content", "prompt-injection", "shadowing", "rug-pull", "exfiltration", "secret-exposure", "dangerous-action", "obfuscation", "capability-mismatch", "self-protection", "integrity", "resource-limit", "hygiene", "server-request", "toxic-flow"], undefined>;
7
+ readonly severity: v.PicklistSchema<readonly ["info", "low", "medium", "high", "critical"], undefined>;
8
+ readonly confidence: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.MinValueAction<number, 0, undefined>, v.MaxValueAction<number, 1, undefined>]>;
9
+ readonly surfaces: v.SchemaWithPipe<readonly [v.ArraySchema<v.PicklistSchema<readonly ["manifest", "call", "result", "server-request"], undefined>, undefined>, v.MinLengthAction<("server-request" | "manifest" | "call" | "result")[], 1, undefined>]>;
10
+ readonly target: v.ObjectSchema<{
11
+ readonly roles: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
12
+ readonly keys: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
13
+ }, undefined>;
14
+ readonly views: v.SchemaWithPipe<readonly [v.ArraySchema<v.PicklistSchema<readonly ["norm", "skeleton", "visible", "original", "tagDecoded", "decoded"], undefined>, undefined>, v.MinLengthAction<("skeleton" | "norm" | "visible" | "original" | "tagDecoded" | "decoded")[], 1, undefined>]>;
15
+ readonly matcher: v.GenericSchema<Matcher>;
16
+ readonly escalation: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
17
+ readonly suppressible: v.BooleanSchema<undefined>;
18
+ readonly explanation: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 500, undefined>]>;
19
+ readonly remediation: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 500, undefined>]>;
20
+ readonly testCases: v.ObjectSchema<{
21
+ readonly positive: v.ArraySchema<v.ObjectSchema<{
22
+ readonly surface: v.PicklistSchema<readonly ["manifest", "call", "result", "server-request"], undefined>;
23
+ readonly input: v.UnknownSchema;
24
+ readonly note: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
25
+ }, undefined>, undefined>;
26
+ readonly negative: v.ArraySchema<v.ObjectSchema<{
27
+ readonly surface: v.PicklistSchema<readonly ["manifest", "call", "result", "server-request"], undefined>;
28
+ readonly input: v.UnknownSchema;
29
+ readonly note: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
30
+ }, undefined>, undefined>;
31
+ }, undefined>;
32
+ }, undefined>;
33
+ export declare const PayloadSchema: v.ObjectSchema<{
34
+ readonly rulesetId: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 100, undefined>]>;
35
+ readonly channel: v.PicklistSchema<["baseline", "private"], undefined>;
36
+ readonly version: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MaxLengthAction<string, 50, undefined>]>;
37
+ readonly sequence: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
38
+ readonly createdAt: v.StringSchema<undefined>;
39
+ readonly expiresAt: v.StringSchema<undefined>;
40
+ readonly minEngineVersion: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>;
41
+ readonly irreversibleTags: v.OptionalSchema<v.ArraySchema<v.PicklistSchema<readonly ["fs.read", "fs.read.sensitive", "fs.write", "fs.delete", "fs.destroy", "fs.move", "net.egress", "net.fetch.package-manager", "net.fetch.vcs", "vcs.commit", "vcs.push", "vcs.force-push", "vcs.history-rewrite", "vcs.discard-changes", "db.read", "db.write", "db.delete", "db.ddl", "db.unscoped-write", "deploy.prod", "deploy.other", "infra.change", "payment", "publish.public", "message.send", "perm.change", "exec.inline-code", "exec.project-code", "exec.unknown", "exec.nested-agent", "config.agent", "self-protection"], undefined>, undefined>, undefined>;
42
+ readonly rules: v.SchemaWithPipe<readonly [v.ArraySchema<v.ObjectSchema<{
43
+ readonly id: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>;
44
+ readonly revision: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 1, undefined>]>;
45
+ readonly category: v.PicklistSchema<readonly ["tool-poisoning", "hidden-content", "prompt-injection", "shadowing", "rug-pull", "exfiltration", "secret-exposure", "dangerous-action", "obfuscation", "capability-mismatch", "self-protection", "integrity", "resource-limit", "hygiene", "server-request", "toxic-flow"], undefined>;
46
+ readonly severity: v.PicklistSchema<readonly ["info", "low", "medium", "high", "critical"], undefined>;
47
+ readonly confidence: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.MinValueAction<number, 0, undefined>, v.MaxValueAction<number, 1, undefined>]>;
48
+ readonly surfaces: v.SchemaWithPipe<readonly [v.ArraySchema<v.PicklistSchema<readonly ["manifest", "call", "result", "server-request"], undefined>, undefined>, v.MinLengthAction<("server-request" | "manifest" | "call" | "result")[], 1, undefined>]>;
49
+ readonly target: v.ObjectSchema<{
50
+ readonly roles: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
51
+ readonly keys: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
52
+ }, undefined>;
53
+ readonly views: v.SchemaWithPipe<readonly [v.ArraySchema<v.PicklistSchema<readonly ["norm", "skeleton", "visible", "original", "tagDecoded", "decoded"], undefined>, undefined>, v.MinLengthAction<("skeleton" | "norm" | "visible" | "original" | "tagDecoded" | "decoded")[], 1, undefined>]>;
54
+ readonly matcher: v.GenericSchema<Matcher>;
55
+ readonly escalation: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
56
+ readonly suppressible: v.BooleanSchema<undefined>;
57
+ readonly explanation: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 500, undefined>]>;
58
+ readonly remediation: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 500, undefined>]>;
59
+ readonly testCases: v.ObjectSchema<{
60
+ readonly positive: v.ArraySchema<v.ObjectSchema<{
61
+ readonly surface: v.PicklistSchema<readonly ["manifest", "call", "result", "server-request"], undefined>;
62
+ readonly input: v.UnknownSchema;
63
+ readonly note: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
64
+ }, undefined>, undefined>;
65
+ readonly negative: v.ArraySchema<v.ObjectSchema<{
66
+ readonly surface: v.PicklistSchema<readonly ["manifest", "call", "result", "server-request"], undefined>;
67
+ readonly input: v.UnknownSchema;
68
+ readonly note: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
69
+ }, undefined>, undefined>;
70
+ }, undefined>;
71
+ }, undefined>, undefined>, v.MaxLengthAction<{
72
+ id: string;
73
+ revision: number;
74
+ category: "tool-poisoning" | "hidden-content" | "prompt-injection" | "shadowing" | "rug-pull" | "exfiltration" | "secret-exposure" | "dangerous-action" | "obfuscation" | "capability-mismatch" | "self-protection" | "integrity" | "resource-limit" | "hygiene" | "server-request" | "toxic-flow";
75
+ severity: "info" | "low" | "medium" | "high" | "critical";
76
+ confidence: number;
77
+ surfaces: ("server-request" | "manifest" | "call" | "result")[];
78
+ target: {
79
+ roles?: string[] | undefined;
80
+ keys?: boolean | undefined;
81
+ };
82
+ views: ("skeleton" | "norm" | "visible" | "original" | "tagDecoded" | "decoded")[];
83
+ matcher: Matcher;
84
+ escalation?: boolean | undefined;
85
+ suppressible: boolean;
86
+ explanation: string;
87
+ remediation: string;
88
+ testCases: {
89
+ positive: {
90
+ surface: "server-request" | "manifest" | "call" | "result";
91
+ input: unknown;
92
+ note?: string | undefined;
93
+ }[];
94
+ negative: {
95
+ surface: "server-request" | "manifest" | "call" | "result";
96
+ input: unknown;
97
+ note?: string | undefined;
98
+ }[];
99
+ };
100
+ }[], 5000, undefined>]>;
101
+ }, undefined>;
102
+ export type RulesetPayload = v.InferOutput<typeof PayloadSchema>;
103
+ export declare const EnvelopeSchema: v.ObjectSchema<{
104
+ readonly format: v.LiteralSchema<"glassbox-ruleset-envelope/v1", undefined>;
105
+ readonly payload: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MaxLengthAction<string, number, undefined>]>;
106
+ readonly signatures: v.SchemaWithPipe<readonly [v.ArraySchema<v.ObjectSchema<{
107
+ readonly keyId: v.StringSchema<undefined>;
108
+ readonly alg: v.LiteralSchema<"ed25519", undefined>;
109
+ readonly sig: v.StringSchema<undefined>;
110
+ }, undefined>, undefined>, v.MinLengthAction<{
111
+ keyId: string;
112
+ alg: "ed25519";
113
+ sig: string;
114
+ }[], 1, undefined>, v.MaxLengthAction<{
115
+ keyId: string;
116
+ alg: "ed25519";
117
+ sig: string;
118
+ }[], 8, undefined>]>;
119
+ }, undefined>;
120
+ //# sourceMappingURL=schema.d.ts.map
@@ -0,0 +1,54 @@
1
+ // Ruleset payload schema, validated with valibot.
2
+ import * as v from "valibot";
3
+ import { ACTION_TAGS } from "../types.js";
4
+ const CATEGORIES = [
5
+ "tool-poisoning", "hidden-content", "prompt-injection", "shadowing", "rug-pull", "exfiltration", "secret-exposure",
6
+ "dangerous-action", "obfuscation", "capability-mismatch", "self-protection", "integrity", "resource-limit", "hygiene",
7
+ "server-request", "toxic-flow",
8
+ ];
9
+ const SEVERITIES = ["info", "low", "medium", "high", "critical"];
10
+ const SURFACES = ["manifest", "call", "result", "server-request"];
11
+ const VIEWS = ["norm", "skeleton", "visible", "original", "tagDecoded", "decoded"];
12
+ const MatcherSchema = v.lazy(() => v.variant("type", [
13
+ v.object({ type: v.literal("phrase"), phrases: v.pipe(v.array(v.pipe(v.string(), v.minLength(1), v.maxLength(200))), v.minLength(1), v.maxLength(500)), wordBoundary: v.boolean(), maxGapWords: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0), v.maxValue(5))) }),
14
+ v.object({ type: v.literal("regex"), pattern: v.pipe(v.string(), v.minLength(1), v.maxLength(2000)), flags: v.optional(v.literal("i")), anchors: v.optional(v.pipe(v.array(v.pipe(v.string(), v.minLength(1), v.maxLength(64))), v.minLength(1), v.maxLength(64))) }),
15
+ v.object({ type: v.literal("codepoints"), ranges: v.array(v.tuple([v.number(), v.number()])), minCount: v.number(), exclude: v.optional(v.literal("emoji-sequences")) }),
16
+ v.object({ type: v.literal("secret"), detector: v.string() }),
17
+ v.object({ type: v.literal("structural"), check: v.string() }),
18
+ v.object({ type: v.picklist(["all", "any"]), of: v.pipe(v.array(MatcherSchema), v.minLength(1), v.maxLength(10)), scope: v.literal("field") }),
19
+ v.object({ type: v.literal("not"), of: MatcherSchema }),
20
+ ]));
21
+ const TestCase = v.object({ surface: v.picklist(SURFACES), input: v.unknown(), note: v.optional(v.string()) });
22
+ export const RuleSchema = v.object({
23
+ id: v.pipe(v.string(), v.regex(/^(CP|PV)-[A-Z]+-\d{3}$/)),
24
+ revision: v.pipe(v.number(), v.integer(), v.minValue(1)),
25
+ category: v.picklist(CATEGORIES),
26
+ severity: v.picklist(SEVERITIES),
27
+ confidence: v.pipe(v.number(), v.minValue(0), v.maxValue(1)),
28
+ surfaces: v.pipe(v.array(v.picklist(SURFACES)), v.minLength(1)),
29
+ target: v.object({ roles: v.optional(v.array(v.string())), keys: v.optional(v.boolean()) }),
30
+ views: v.pipe(v.array(v.picklist(VIEWS)), v.minLength(1)),
31
+ matcher: MatcherSchema,
32
+ escalation: v.optional(v.boolean()),
33
+ suppressible: v.boolean(),
34
+ explanation: v.pipe(v.string(), v.minLength(1), v.maxLength(500)),
35
+ remediation: v.pipe(v.string(), v.minLength(1), v.maxLength(500)),
36
+ testCases: v.object({ positive: v.array(TestCase), negative: v.array(TestCase) }),
37
+ });
38
+ export const PayloadSchema = v.object({
39
+ rulesetId: v.pipe(v.string(), v.minLength(1), v.maxLength(100)),
40
+ channel: v.picklist(["baseline", "private"]),
41
+ version: v.pipe(v.string(), v.maxLength(50)),
42
+ sequence: v.pipe(v.number(), v.integer(), v.minValue(0)),
43
+ createdAt: v.string(),
44
+ expiresAt: v.string(),
45
+ minEngineVersion: v.pipe(v.string(), v.regex(/^\d+\.\d+\.\d+$/)),
46
+ irreversibleTags: v.optional(v.array(v.picklist(ACTION_TAGS))),
47
+ rules: v.pipe(v.array(RuleSchema), v.maxLength(5000)),
48
+ });
49
+ export const EnvelopeSchema = v.object({
50
+ format: v.literal("glassbox-ruleset-envelope/v1"),
51
+ payload: v.pipe(v.string(), v.maxLength(6 * 1024 * 1024)),
52
+ signatures: v.pipe(v.array(v.object({ keyId: v.string(), alg: v.literal("ed25519"), sig: v.string() })), v.minLength(1), v.maxLength(8)),
53
+ });
54
+ //# sourceMappingURL=schema.js.map
@@ -0,0 +1,18 @@
1
+ import type { LoadedRuleset, RuleTestCase } from "../types.js";
2
+ export interface SelfTestReport {
3
+ failures: {
4
+ ruleId: string;
5
+ reason: string;
6
+ }[];
7
+ }
8
+ type Cases = {
9
+ positive: readonly RuleTestCase[];
10
+ negative: readonly RuleTestCase[];
11
+ };
12
+ /**
13
+ * Runs each rule's test cases. `extra` supplies cases for rules that don't carry their own
14
+ * (the embedded baseline ships its cases separately to keep start-up small).
15
+ */
16
+ export declare function runRuleSelfTests(ruleset: LoadedRuleset, extra?: Readonly<Record<string, Cases>>): SelfTestReport;
17
+ export {};
18
+ //# sourceMappingURL=selftest.d.ts.map
@@ -0,0 +1,42 @@
1
+ import { analyzeServerImpl } from "../analysis/manifest.js";
2
+ import { checkServerRequestImpl, checkToolCallImpl, checkToolResultImpl } from "../analysis/gate.js";
3
+ import { expandFakes } from "./fakes.js";
4
+ function ctxFor(ruleset) {
5
+ return {
6
+ sessionId: "selftest", platform: "linux", homeDir: "/home/selftest", cwd: "/home/selftest/project", caseInsensitiveFs: false,
7
+ glassboxDirs: ["/home/selftest/.glassbox"], servers: [], policy: { mode: "balanced" }, ruleset,
8
+ };
9
+ }
10
+ function fires(ruleId, tc, ruleset) {
11
+ const t0 = performance.now();
12
+ const ctx = ctxFor(ruleset);
13
+ const input = expandFakes(tc.input);
14
+ const findings = (() => {
15
+ switch (tc.surface) {
16
+ case "manifest": return analyzeServerImpl(input, { ruleset }, t0).findings;
17
+ case "call": return checkToolCallImpl(input, ctx, t0).findings;
18
+ case "result": return checkToolResultImpl(input, ctx, t0).findings;
19
+ case "server-request": return checkServerRequestImpl(input, ctx, t0).findings;
20
+ }
21
+ })();
22
+ return findings.some((f) => f.ruleId === ruleId);
23
+ }
24
+ /**
25
+ * Runs each rule's test cases. `extra` supplies cases for rules that don't carry their own
26
+ * (the embedded baseline ships its cases separately to keep start-up small).
27
+ */
28
+ export function runRuleSelfTests(ruleset, extra = {}) {
29
+ const failures = [];
30
+ for (const r of ruleset.rules) {
31
+ const own = r.testCases.positive.length + r.testCases.negative.length > 0;
32
+ const cases = own ? r.testCases : extra[r.id];
33
+ if (!cases)
34
+ continue;
35
+ cases.positive.forEach((tc, i) => { if (!fires(r.id, tc, ruleset))
36
+ failures.push({ ruleId: r.id, reason: `positive case ${i + 1} did not match` }); });
37
+ cases.negative.forEach((tc, i) => { if (fires(r.id, tc, ruleset))
38
+ failures.push({ ruleId: r.id, reason: `negative case ${i + 1} matched` }); });
39
+ }
40
+ return { failures };
41
+ }
42
+ //# sourceMappingURL=selftest.js.map
@@ -0,0 +1,5 @@
1
+ export { loadRuleset, EMBEDDED_TRUSTED_KEYS, REVOKED_KEY_IDS } from "./ruleset/load.js";
2
+ export { runRuleSelfTests, type SelfTestReport } from "./ruleset/selftest.js";
3
+ export { BASELINE_TEST_CASES } from "./ruleset/baseline-tests.generated.js";
4
+ export type { LoadedRuleset, LoadRulesetOptions, TrustedKey } from "./types.js";
5
+ //# sourceMappingURL=ruleset-entry.d.ts.map
@@ -0,0 +1,7 @@
1
+ // @glassbox-ai/engine/ruleset: loading signed ruleset caches.
2
+ // Kept out of the main entry so an ordinary hook call doesn't pay for Ed25519 and schema
3
+ // validation at start-up (150 ms hook budget). Import this only when a cache file exists.
4
+ export { loadRuleset, EMBEDDED_TRUSTED_KEYS, REVOKED_KEY_IDS } from "./ruleset/load.js";
5
+ export { runRuleSelfTests } from "./ruleset/selftest.js";
6
+ export { BASELINE_TEST_CASES } from "./ruleset/baseline-tests.generated.js";
7
+ //# sourceMappingURL=ruleset-entry.js.map
@@ -0,0 +1,17 @@
1
+ export interface SecretHit {
2
+ type: string;
3
+ start: number;
4
+ end: number;
5
+ value: string;
6
+ confidence: number;
7
+ example: boolean;
8
+ }
9
+ /**
10
+ * Detects secrets in `text`. `keyName` is the JSON key the text sits under (for the
11
+ * generic high-entropy detector, which needs a key-like name).
12
+ */
13
+ export declare function detectSecrets(text: string, keyName?: string, memo?: SecretMemo): SecretHit[];
14
+ /** Per-call cache: keyName → text → hits. Owned by one scan, never shared across calls. */
15
+ export type SecretMemo = Map<string, Map<string, SecretHit[]>>;
16
+ export declare function mask(type: string, value: string): string;
17
+ //# sourceMappingURL=detect.d.ts.map
@@ -0,0 +1,236 @@
1
+ // Secret detectors. Patterns run on the linear regex engine (re2js).
2
+ import { findAll } from "../util/re.js";
3
+ const PLACEHOLDER = /^(\*+|x+|password|passwd|secret|changeme|<[^>]*>|\$\{[^}]*\}|\$[A-Z_]+|%[A-Z_]+%|\{\{[^}]*\}\})$/i;
4
+ function entropy(s) {
5
+ const counts = new Map();
6
+ for (const ch of s)
7
+ counts.set(ch, (counts.get(ch) ?? 0) + 1);
8
+ let h = 0;
9
+ const n = [...s].length;
10
+ for (const c of counts.values()) {
11
+ const p = c / n;
12
+ h -= p * Math.log2(p);
13
+ }
14
+ return h;
15
+ }
16
+ function classes(s) {
17
+ let lower = 0, upper = 0, digit = 0, other = 0;
18
+ for (let i = 0; i < s.length; i++) {
19
+ const c = s.charCodeAt(i);
20
+ if (c >= 97 && c <= 122)
21
+ lower = 1;
22
+ else if (c >= 65 && c <= 90)
23
+ upper = 1;
24
+ else if (c >= 48 && c <= 57)
25
+ digit = 1;
26
+ else
27
+ other = 1;
28
+ }
29
+ return lower + upper + digit + other;
30
+ }
31
+ const DETECTORS = [
32
+ { type: "private-key", anchors: ["PRIVATE KEY"], pattern: "-----BEGIN (?:RSA |EC |DSA |OPENSSH |ENCRYPTED |PGP )?PRIVATE KEY(?: BLOCK)?-----", confidence: 0.99 },
33
+ { type: "anthropic-key", anchors: ["sk-ant-"], pattern: "sk-ant-(?:api|admin)\\d\\d-[A-Za-z0-9_\\-]{80,}", confidence: 0.98 },
34
+ { type: "github-token", anchors: ["ghp_", "gho_", "ghu_", "ghs_", "ghr_", "github_pat_"], pattern: "(?:gh[pousr]_[A-Za-z0-9]{36,255}|github_pat_[A-Za-z0-9_]{82})", confidence: 0.95 },
35
+ { type: "gitlab-token", anchors: ["glpat-", "gldt-", "glrt-"], pattern: "gl(?:pat|dt|rt)-[A-Za-z0-9_\\-]{20,}", confidence: 0.95 },
36
+ { type: "slack-webhook", anchors: ["https://hooks.slack.com/services/"], pattern: "https://hooks\\.slack\\.com/services/T[A-Z0-9]+/B[A-Z0-9]+/[A-Za-z0-9]+", confidence: 0.95 },
37
+ { type: "slack-token", anchors: ["xoxa-", "xoxb-", "xoxp-", "xoxr-", "xoxs-", "xapp-"], pattern: "(?:xox[abprs]|xapp)-[A-Za-z0-9\\-]{10,}", confidence: 0.95 },
38
+ { type: "stripe-key", anchors: ["sk_live_", "sk_test_", "rk_live_", "rk_test_", "whsec_"], pattern: "(?:(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{24,}|whsec_[A-Za-z0-9]{24,})", confidence: 0.95 },
39
+ { type: "gcp-api-key", anchors: ["AIza"], pattern: "AIza[0-9A-Za-z_\\-]{35}", confidence: 0.95 },
40
+ { type: "aws-access-key-id", anchors: ["AKIA", "ASIA", "ABIA", "ACCA"], pattern: "(?:AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}", confidence: 0.95 },
41
+ {
42
+ type: "aws-secret-access-key", anchors: ["aws"], anchorsCI: true,
43
+ pattern: "(?i)aws[A-Za-z0-9_\\-]{0,20}(?:secret|key)[A-Za-z0-9_\\-]{0,20}[\"']?\\s*[:=]\\s*[\"']?([A-Za-z0-9/+]{40})",
44
+ group: 1, confidence: 0.8,
45
+ validate: (v) => (entropy(v) >= 4.0 ? null : -1),
46
+ },
47
+ { type: "azure-storage-key", anchors: ["AccountKey="], pattern: "AccountKey=[A-Za-z0-9+/=]{20,}", confidence: 0.9 },
48
+ { type: "azure-conn-string", anchors: ["SharedAccessSignature="], pattern: "SharedAccessSignature=[^;\\s\"']{16,}", confidence: 0.9 },
49
+ {
50
+ type: "openai-key", anchors: ["sk-"], pattern: "sk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_\\-]{20,}", confidence: 0.85,
51
+ validate: (v) => (v.startsWith("sk-ant-") ? -1 : null),
52
+ },
53
+ {
54
+ type: "jwt", anchors: ["eyJ"], pattern: "eyJ[A-Za-z0-9_\\-]{5,}\\.eyJ[A-Za-z0-9_\\-]{5,}\\.[A-Za-z0-9_\\-]{10,}", confidence: 0.85,
55
+ validate: (v) => {
56
+ try {
57
+ const head = (v.split(".")[0] ?? "").replace(/-/g, "+").replace(/_/g, "/");
58
+ const json = atob(head + "=".repeat((4 - (head.length % 4)) % 4));
59
+ return json.includes('"alg"') ? null : -1;
60
+ }
61
+ catch {
62
+ return -1;
63
+ }
64
+ },
65
+ },
66
+ {
67
+ type: "db-connection-string", anchors: ["postgres://", "postgresql://", "mysql://", "mongodb://", "mongodb+srv://", "redis://", "rediss://", "amqp://", "amqps://", "mssql://"],
68
+ pattern: "(?:postgres(?:ql)?|mysql|mongodb(?:\\+srv)?|redis|rediss|amqps?|mssql)://([^:@/\\s\"']+):([^@\\s\"']+)@[^\\s/\"']+",
69
+ confidence: 0.9,
70
+ validate: (v) => {
71
+ // user:password@ right after the scheme, parsed without a regex (linear).
72
+ const head = v.slice(0, 512);
73
+ const auth = head.slice(head.indexOf("://") + 3);
74
+ const at = auth.indexOf("@");
75
+ const colon = auth.indexOf(":");
76
+ const pw = at > 0 && colon > 0 && colon < at && !/[\s/]/.test(auth.slice(0, at)) ? auth.slice(colon + 1, at) : "";
77
+ return pw.length === 0 || PLACEHOLDER.test(pw) ? -1 : null;
78
+ },
79
+ },
80
+ ];
81
+ const GENERIC_ANCHORS = ["key", "token", "secret", "passw", "pwd", "auth", "credential", "bearer", "session", "private"];
82
+ const KEYWORD = "(?i)[A-Za-z0-9_.\\-]*(?:key|token|secret|passw(?:or)?d|pwd|auth|credential|bearer|session|private)[A-Za-z0-9_.\\-]*";
83
+ const KEY_NAME = /(key|token|secret|passw(or)?d|pwd|auth|credential|api[-_]?key|private|bearer|session)/i;
84
+ const EXCLUDED_KEY = /(^|[^a-z])(sha|commit|hash|checksum|integrity|digest|etag|id)$/i;
85
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
86
+ const HEXONLY = /^[0-9a-f]+$/i;
87
+ function looksGeneric(v) {
88
+ if (v.length < 20 || v.length > 512)
89
+ return false;
90
+ if (UUID.test(v) || PLACEHOLDER.test(v))
91
+ return false;
92
+ if (HEXONLY.test(v) && (v.length === 40 || v.length === 64 || v.length === 32))
93
+ return false;
94
+ if (v.includes(" ") || v.includes("/") && v.split("/").length > 3)
95
+ return false;
96
+ return entropy(v) >= 3.5 && classes(v) >= 2;
97
+ }
98
+ function isExample(v) {
99
+ return /EXAMPLE|example|xxxxxxxx|XXXXXXXX|0000000000|1234567890abcdef/.test(v.slice(0, 512)) || v === "AKIAIOSFODNN7EXAMPLE";
100
+ }
101
+ /** Private keys: extend the hit to the matching END line when present. */
102
+ function extendPem(text, start, end) {
103
+ const endMarker = text.indexOf("-----END", end);
104
+ if (endMarker < 0 || endMarker - end > 64 * 1024)
105
+ return Math.min(text.length, end + 4096);
106
+ const close = text.indexOf("-----", endMarker + 8);
107
+ return close < 0 ? text.length : close + 5;
108
+ }
109
+ /**
110
+ * Detects secrets in `text`. `keyName` is the JSON key the text sits under (for the
111
+ * generic high-entropy detector, which needs a key-like name).
112
+ */
113
+ export function detectSecrets(text, keyName, memo) {
114
+ if (!memo)
115
+ return detectUncached(text, keyName);
116
+ const k = keyName ?? "\u0000";
117
+ let byText = memo.get(k);
118
+ if (!byText) {
119
+ byText = new Map();
120
+ memo.set(k, byText);
121
+ }
122
+ let hits = byText.get(text);
123
+ if (!hits) {
124
+ hits = detectUncached(text, keyName);
125
+ byText.set(text, hits);
126
+ }
127
+ return hits;
128
+ }
129
+ function detectUncached(text, keyName) {
130
+ const hits = [];
131
+ if (text.length < 8)
132
+ return hits;
133
+ let lower;
134
+ const has = (lits, ci) => {
135
+ // re2 (?i) folds U+017F (long s) to s and U+212A (Kelvin) to k; toLowerCase handles the
136
+ // Kelvin sign but not long s, so fold it here or "\u017fecret=..." would skip the pass.
137
+ if (ci)
138
+ lower ??= text.toLowerCase().replaceAll("\u017f", "s");
139
+ const hay = ci ? lower : text;
140
+ return lits.some((l) => hay.includes(l));
141
+ };
142
+ for (const d of DETECTORS) {
143
+ if (!has(d.anchors, d.anchorsCI))
144
+ continue;
145
+ for (const m of findAll(d.pattern, text, d.flags, 50)) {
146
+ let start = m.start, end = m.end;
147
+ let value = m.text;
148
+ if (d.group !== undefined) {
149
+ const g = m.groups[d.group - 1];
150
+ if (!g)
151
+ continue;
152
+ const off = m.text.lastIndexOf(g);
153
+ start = m.start + off;
154
+ end = start + g.length;
155
+ value = g;
156
+ }
157
+ if (d.type === "private-key") {
158
+ end = extendPem(text, start, end);
159
+ value = text.slice(start, end);
160
+ }
161
+ let confidence = d.confidence;
162
+ if (d.validate) {
163
+ const r = d.validate(value, text);
164
+ if (r !== null && r < 0)
165
+ continue;
166
+ if (r !== null)
167
+ confidence = r;
168
+ }
169
+ const example = isExample(value);
170
+ hits.push({ type: d.type, start, end, value, confidence: example ? 0.3 : confidence, example });
171
+ }
172
+ }
173
+ // Generic: key=value pairs inside text with a key-like name.
174
+ const generic = (text.includes("=") || text.includes(":")) && has(GENERIC_ANCHORS, true);
175
+ for (const m of generic ? findAll(`(${KEYWORD})\\s*["']?\\s*[:=]\\s*["']?([^\\s"'&,;]{20,512})`, text, undefined, 50) : []) {
176
+ const v = m.groups[1] ?? "";
177
+ const name = m.groups[0] ?? "";
178
+ if (EXCLUDED_KEY.test(name) || !looksGeneric(v))
179
+ continue;
180
+ const start = m.start + m.text.lastIndexOf(v);
181
+ hits.push({ type: "generic-high-entropy", start, end: start + v.length, value: v, confidence: 0.6, example: isExample(v) });
182
+ }
183
+ // Generic: the whole field under a key-like JSON key.
184
+ if (keyName !== undefined && KEY_NAME.test(keyName) && !EXCLUDED_KEY.test(keyName)) {
185
+ const v = text.trim();
186
+ if (looksGeneric(v)) {
187
+ const start = text.indexOf(v);
188
+ hits.push({ type: "generic-high-entropy", start, end: start + v.length, value: v, confidence: 0.6, example: isExample(v) });
189
+ }
190
+ }
191
+ return resolveOverlaps(hits);
192
+ }
193
+ /** Keep the most specific hit when hits overlap (generic loses; longer wins on ties). */
194
+ function resolveOverlaps(hits) {
195
+ const rank = (h) => (h.type === "generic-high-entropy" ? 0 : h.type === "openai-key" ? 1 : 2);
196
+ hits.sort((a, b) => rank(b) - rank(a) || (b.end - b.start) - (a.end - a.start) || a.start - b.start);
197
+ const kept = [];
198
+ for (const h of hits) {
199
+ if (kept.some((k) => h.start < k.end && k.start < h.end))
200
+ continue;
201
+ kept.push(h);
202
+ }
203
+ return kept.sort((a, b) => a.start - b.start);
204
+ }
205
+ // ── Masking ───────────────────────────────────────────────────────
206
+ const PUBLIC_PREFIXES = [
207
+ "github_pat_", "ghp_", "gho_", "ghu_", "ghs_", "ghr_", "glpat-", "gldt-", "glrt-", "xoxb-", "xoxa-", "xoxp-", "xoxr-", "xoxs-", "xapp-",
208
+ "sk_live_", "sk_test_", "rk_live_", "rk_test_", "whsec_", "sk-proj-", "sk-svcacct-", "sk-admin-", "AKIA", "ASIA", "ABIA", "ACCA", "AIza", "eyJ",
209
+ ];
210
+ export function mask(type, value) {
211
+ if (type === "private-key") {
212
+ const lines = value.split("\n").length;
213
+ return `private-key:[REDACTED PEM, ${lines} lines]`;
214
+ }
215
+ if (type === "db-connection-string") {
216
+ const at = value.indexOf("@");
217
+ const scheme = value.indexOf("://");
218
+ const colon = value.indexOf(":", scheme + 3);
219
+ if (scheme > 0 && colon > 0 && at > colon)
220
+ return value.slice(0, colon + 1) + "****" + value.slice(at);
221
+ return "db-connection-string:****";
222
+ }
223
+ let prefix = "";
224
+ const ant = /^sk-ant-(api|admin)\d\d-/.exec(value.slice(0, 20));
225
+ if (ant)
226
+ prefix = ant[0];
227
+ else
228
+ for (const p of PUBLIC_PREFIXES)
229
+ if (value.startsWith(p)) {
230
+ prefix = p;
231
+ break;
232
+ }
233
+ const tail = value.length >= 24 ? value.slice(-4) : "";
234
+ return `${type}:${prefix}****…${tail}`;
235
+ }
236
+ //# sourceMappingURL=detect.js.map
@@ -0,0 +1,19 @@
1
+ import type { Limits, Redacted } from "../types.js";
2
+ import { type SecretHit } from "./detect.js";
3
+ export interface StringRedaction {
4
+ text: string;
5
+ hits: SecretHit[];
6
+ masked: {
7
+ type: string;
8
+ masked: string;
9
+ }[];
10
+ truncated: boolean;
11
+ }
12
+ /** Redact one string. `minConfidence` lets strict-mode result rewriting mask only high-confidence hits. */
13
+ export declare function redactString(text: string, keyName: string | undefined, limits: Limits, minConfidence?: number): StringRedaction;
14
+ /** Deep redaction over a snapshot value. */
15
+ export declare function redactValue(value: unknown, limits: Limits, minConfidence?: number): Redacted;
16
+ export declare function redact(value: unknown, opts?: {
17
+ limits?: Partial<Limits>;
18
+ }): Redacted;
19
+ //# sourceMappingURL=redact.d.ts.map
@@ -0,0 +1,116 @@
1
+ // redact(): deep copy with every detected secret masked.
2
+ // Unscanned content is replaced, never passed through raw.
3
+ import { findDecodable } from "../canon/decode.js";
4
+ import { resolveLimits } from "../limits.js";
5
+ import { snapshot } from "../intake/snapshot.js";
6
+ import { isRecord, ptrSeg } from "../util/misc.js";
7
+ import { detectSecrets, mask } from "./detect.js";
8
+ /** Redact one string. `minConfidence` lets strict-mode result rewriting mask only high-confidence hits. */
9
+ export function redactString(text, keyName, limits, minConfidence = 0) {
10
+ let truncated = false;
11
+ let head = text;
12
+ let tail = "";
13
+ let skipped = 0;
14
+ if (text.length > limits.maxFieldScanBytes) {
15
+ const h = Math.floor(limits.maxFieldScanBytes * 0.75);
16
+ const t = limits.maxFieldScanBytes - h;
17
+ head = text.slice(0, h);
18
+ tail = text.slice(text.length - t);
19
+ skipped = text.length - h - t;
20
+ truncated = true;
21
+ }
22
+ const doPart = (part) => {
23
+ const hits = detectSecrets(part, keyName).filter((x) => x.confidence >= minConfidence);
24
+ // Secrets wrapped in base64/hex/url encoding: mask the whole blob.
25
+ for (const d of findDecodable(part, { bytes: limits.maxDecodedBytes })) {
26
+ if (hits.some((x) => x.start < d.end && d.start < x.end))
27
+ continue;
28
+ const inner = detectSecrets(d.text).filter((x) => x.confidence >= minConfidence);
29
+ const first = inner[0];
30
+ if (first)
31
+ hits.push({ ...first, start: d.start, end: d.end, value: part.slice(d.start, d.end), wrapped: true });
32
+ }
33
+ hits.sort((a, b) => a.start - b.start);
34
+ let out = "";
35
+ let pos = 0;
36
+ const masked = [];
37
+ for (const x of hits) {
38
+ if (x.start < pos)
39
+ continue;
40
+ const m = x.wrapped ? `${x.type}:[REDACTED encoded]` : mask(x.type, x.value);
41
+ out += part.slice(pos, x.start) + m;
42
+ masked.push({ type: x.type, masked: m });
43
+ pos = x.end;
44
+ }
45
+ out += part.slice(pos);
46
+ return { out, hits, masked };
47
+ };
48
+ const a = doPart(head);
49
+ if (!truncated)
50
+ return { text: a.out, hits: a.hits, masked: a.masked, truncated };
51
+ const b = doPart(tail);
52
+ return {
53
+ text: `${a.out}[UNSCANNED ${skipped} bytes]${b.out}`,
54
+ hits: [...a.hits, ...b.hits],
55
+ masked: [...a.masked, ...b.masked],
56
+ truncated,
57
+ };
58
+ }
59
+ function setKey(o, k, v) {
60
+ Object.defineProperty(o, k, { value: v, enumerable: true, writable: true, configurable: true });
61
+ }
62
+ /** Deep redaction over a snapshot value. */
63
+ export function redactValue(value, limits, minConfidence = 0) {
64
+ const redactions = [];
65
+ let truncated = false;
66
+ let budget = limits.maxInputBytes * 4;
67
+ let root = null;
68
+ const jobs = [{ v: value, set: (x) => { root = x; }, pointer: "", key: undefined }];
69
+ while (jobs.length > 0) {
70
+ const j = jobs.pop();
71
+ const v = j.v;
72
+ if (typeof v === "string") {
73
+ if (budget <= 0) {
74
+ j.set(`[UNSCANNED ${v.length} bytes]`);
75
+ truncated = true;
76
+ continue;
77
+ }
78
+ budget -= v.length;
79
+ const r = redactString(v, j.key, limits, minConfidence);
80
+ if (r.truncated)
81
+ truncated = true;
82
+ for (const m of r.masked)
83
+ redactions.push({ pointer: j.pointer, type: m.type, masked: m.masked });
84
+ j.set(r.text);
85
+ }
86
+ else if (Array.isArray(v)) {
87
+ const out = new Array(v.length).fill(null);
88
+ j.set(out);
89
+ v.forEach((x, i) => jobs.push({ v: x, set: (y) => { out[i] = y; }, pointer: `${j.pointer}/${i}`, key: j.key }));
90
+ }
91
+ else if (isRecord(v)) {
92
+ const out = {};
93
+ j.set(out);
94
+ for (const k of Object.keys(v)) {
95
+ setKey(out, k, null);
96
+ jobs.push({ v: v[k], set: (y) => setKey(out, k, y), pointer: `${j.pointer}/${ptrSeg(k)}`, key: k });
97
+ }
98
+ }
99
+ else {
100
+ j.set(v);
101
+ }
102
+ }
103
+ return { value: root, redactions, truncated };
104
+ }
105
+ export function redact(value, opts) {
106
+ try {
107
+ const limits = resolveLimits(opts?.limits);
108
+ const snap = snapshot(value, { maxDepth: limits.maxDepth, maxNodes: limits.maxNodes });
109
+ const r = redactValue(snap.value, limits);
110
+ return { ...r, truncated: r.truncated || snap.degraded };
111
+ }
112
+ catch {
113
+ return { value: "[UNSCANNED]", redactions: [], truncated: true };
114
+ }
115
+ }
116
+ //# sourceMappingURL=redact.js.map