@enclave-vm/core 0.0.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 (169) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +732 -0
  3. package/SECURITY-AUDIT.md +916 -0
  4. package/package.json +59 -0
  5. package/src/adapters/vm-adapter.d.ts +32 -0
  6. package/src/adapters/vm-adapter.js +1140 -0
  7. package/src/adapters/vm-adapter.js.map +1 -0
  8. package/src/adapters/worker-pool/config.d.ts +149 -0
  9. package/src/adapters/worker-pool/config.js +129 -0
  10. package/src/adapters/worker-pool/config.js.map +1 -0
  11. package/src/adapters/worker-pool/errors.d.ts +109 -0
  12. package/src/adapters/worker-pool/errors.js +181 -0
  13. package/src/adapters/worker-pool/errors.js.map +1 -0
  14. package/src/adapters/worker-pool/execution-queue.d.ts +85 -0
  15. package/src/adapters/worker-pool/execution-queue.js +179 -0
  16. package/src/adapters/worker-pool/execution-queue.js.map +1 -0
  17. package/src/adapters/worker-pool/index.d.ts +48 -0
  18. package/src/adapters/worker-pool/index.js +73 -0
  19. package/src/adapters/worker-pool/index.js.map +1 -0
  20. package/src/adapters/worker-pool/memory-monitor.d.ts +106 -0
  21. package/src/adapters/worker-pool/memory-monitor.js +184 -0
  22. package/src/adapters/worker-pool/memory-monitor.js.map +1 -0
  23. package/src/adapters/worker-pool/protocol.d.ts +314 -0
  24. package/src/adapters/worker-pool/protocol.js +143 -0
  25. package/src/adapters/worker-pool/protocol.js.map +1 -0
  26. package/src/adapters/worker-pool/rate-limiter.d.ts +60 -0
  27. package/src/adapters/worker-pool/rate-limiter.js +101 -0
  28. package/src/adapters/worker-pool/rate-limiter.js.map +1 -0
  29. package/src/adapters/worker-pool/safe-deserialize.d.ts +50 -0
  30. package/src/adapters/worker-pool/safe-deserialize.js +141 -0
  31. package/src/adapters/worker-pool/safe-deserialize.js.map +1 -0
  32. package/src/adapters/worker-pool/worker-pool-adapter.d.ts +84 -0
  33. package/src/adapters/worker-pool/worker-pool-adapter.js +506 -0
  34. package/src/adapters/worker-pool/worker-pool-adapter.js.map +1 -0
  35. package/src/adapters/worker-pool/worker-script.d.ts +12 -0
  36. package/src/adapters/worker-pool/worker-script.js +770 -0
  37. package/src/adapters/worker-pool/worker-script.js.map +1 -0
  38. package/src/adapters/worker-pool/worker-slot.d.ts +116 -0
  39. package/src/adapters/worker-pool/worker-slot.js +301 -0
  40. package/src/adapters/worker-pool/worker-slot.js.map +1 -0
  41. package/src/babel/babel-wrapper.d.ts +118 -0
  42. package/src/babel/babel-wrapper.js +395 -0
  43. package/src/babel/babel-wrapper.js.map +1 -0
  44. package/src/babel/index.d.ts +9 -0
  45. package/src/babel/index.js +17 -0
  46. package/src/babel/index.js.map +1 -0
  47. package/src/babel/multi-file-transform.d.ts +122 -0
  48. package/src/babel/multi-file-transform.js +344 -0
  49. package/src/babel/multi-file-transform.js.map +1 -0
  50. package/src/double-vm/double-vm-wrapper.d.ts +65 -0
  51. package/src/double-vm/double-vm-wrapper.js +523 -0
  52. package/src/double-vm/double-vm-wrapper.js.map +1 -0
  53. package/src/double-vm/index.d.ts +31 -0
  54. package/src/double-vm/index.js +34 -0
  55. package/src/double-vm/index.js.map +1 -0
  56. package/src/double-vm/parent-vm-bootstrap.d.ts +63 -0
  57. package/src/double-vm/parent-vm-bootstrap.js +1695 -0
  58. package/src/double-vm/parent-vm-bootstrap.js.map +1 -0
  59. package/src/double-vm/suspicious-patterns.d.ts +57 -0
  60. package/src/double-vm/suspicious-patterns.js +304 -0
  61. package/src/double-vm/suspicious-patterns.js.map +1 -0
  62. package/src/double-vm/types.d.ts +178 -0
  63. package/src/double-vm/types.js +11 -0
  64. package/src/double-vm/types.js.map +1 -0
  65. package/src/double-vm/wrap-adapter.d.ts +36 -0
  66. package/src/double-vm/wrap-adapter.js +59 -0
  67. package/src/double-vm/wrap-adapter.js.map +1 -0
  68. package/src/enclave.d.ts +159 -0
  69. package/src/enclave.js +671 -0
  70. package/src/enclave.js.map +1 -0
  71. package/src/globals-validator.d.ts +80 -0
  72. package/src/globals-validator.js +206 -0
  73. package/src/globals-validator.js.map +1 -0
  74. package/src/index.d.ts +29 -0
  75. package/src/index.js +130 -0
  76. package/src/index.js.map +1 -0
  77. package/src/memory-proxy.d.ts +69 -0
  78. package/src/memory-proxy.js +310 -0
  79. package/src/memory-proxy.js.map +1 -0
  80. package/src/memory-tracker.d.ts +170 -0
  81. package/src/memory-tracker.js +230 -0
  82. package/src/memory-tracker.js.map +1 -0
  83. package/src/safe-error.d.ts +18 -0
  84. package/src/safe-error.js +76 -0
  85. package/src/safe-error.js.map +1 -0
  86. package/src/safe-runtime.d.ts +72 -0
  87. package/src/safe-runtime.js +656 -0
  88. package/src/safe-runtime.js.map +1 -0
  89. package/src/scoring/cache.d.ts +68 -0
  90. package/src/scoring/cache.js +158 -0
  91. package/src/scoring/cache.js.map +1 -0
  92. package/src/scoring/feature-extractor.d.ts +61 -0
  93. package/src/scoring/feature-extractor.js +366 -0
  94. package/src/scoring/feature-extractor.js.map +1 -0
  95. package/src/scoring/index.d.ts +33 -0
  96. package/src/scoring/index.js +53 -0
  97. package/src/scoring/index.js.map +1 -0
  98. package/src/scoring/scorer.interface.d.ts +65 -0
  99. package/src/scoring/scorer.interface.js +49 -0
  100. package/src/scoring/scorer.interface.js.map +1 -0
  101. package/src/scoring/scorers/disabled.scorer.d.ts +19 -0
  102. package/src/scoring/scorers/disabled.scorer.js +34 -0
  103. package/src/scoring/scorers/disabled.scorer.js.map +1 -0
  104. package/src/scoring/scorers/external-api.scorer.d.ts +29 -0
  105. package/src/scoring/scorers/external-api.scorer.js +141 -0
  106. package/src/scoring/scorers/external-api.scorer.js.map +1 -0
  107. package/src/scoring/scorers/index.d.ts +10 -0
  108. package/src/scoring/scorers/index.js +22 -0
  109. package/src/scoring/scorers/index.js.map +1 -0
  110. package/src/scoring/scorers/local-llm.scorer.d.ts +116 -0
  111. package/src/scoring/scorers/local-llm.scorer.js +474 -0
  112. package/src/scoring/scorers/local-llm.scorer.js.map +1 -0
  113. package/src/scoring/scorers/progressive.scorer.d.ts +77 -0
  114. package/src/scoring/scorers/progressive.scorer.js +199 -0
  115. package/src/scoring/scorers/progressive.scorer.js.map +1 -0
  116. package/src/scoring/scorers/rule-based.scorer.d.ts +66 -0
  117. package/src/scoring/scorers/rule-based.scorer.js +316 -0
  118. package/src/scoring/scorers/rule-based.scorer.js.map +1 -0
  119. package/src/scoring/scoring-gate.d.ts +76 -0
  120. package/src/scoring/scoring-gate.js +246 -0
  121. package/src/scoring/scoring-gate.js.map +1 -0
  122. package/src/scoring/types.d.ts +690 -0
  123. package/src/scoring/types.js +107 -0
  124. package/src/scoring/types.js.map +1 -0
  125. package/src/secure-proxy.d.ts +157 -0
  126. package/src/secure-proxy.js +609 -0
  127. package/src/secure-proxy.js.map +1 -0
  128. package/src/session/channels/embedded-channel.d.ts +76 -0
  129. package/src/session/channels/embedded-channel.js +130 -0
  130. package/src/session/channels/embedded-channel.js.map +1 -0
  131. package/src/session/channels/index.d.ts +9 -0
  132. package/src/session/channels/index.js +14 -0
  133. package/src/session/channels/index.js.map +1 -0
  134. package/src/session/index.d.ts +15 -0
  135. package/src/session/index.js +27 -0
  136. package/src/session/index.js.map +1 -0
  137. package/src/session/session-emitter.d.ts +119 -0
  138. package/src/session/session-emitter.js +253 -0
  139. package/src/session/session-emitter.js.map +1 -0
  140. package/src/session/session-state-machine.d.ts +108 -0
  141. package/src/session/session-state-machine.js +182 -0
  142. package/src/session/session-state-machine.js.map +1 -0
  143. package/src/session/session.d.ts +135 -0
  144. package/src/session/session.js +398 -0
  145. package/src/session/session.js.map +1 -0
  146. package/src/session-types.d.ts +313 -0
  147. package/src/session-types.js +39 -0
  148. package/src/session-types.js.map +1 -0
  149. package/src/sidecar/index.d.ts +12 -0
  150. package/src/sidecar/index.js +31 -0
  151. package/src/sidecar/index.js.map +1 -0
  152. package/src/sidecar/reference-config.d.ts +81 -0
  153. package/src/sidecar/reference-config.js +118 -0
  154. package/src/sidecar/reference-config.js.map +1 -0
  155. package/src/sidecar/reference-resolver.d.ts +115 -0
  156. package/src/sidecar/reference-resolver.js +262 -0
  157. package/src/sidecar/reference-resolver.js.map +1 -0
  158. package/src/sidecar/reference-sidecar.d.ts +161 -0
  159. package/src/sidecar/reference-sidecar.js +226 -0
  160. package/src/sidecar/reference-sidecar.js.map +1 -0
  161. package/src/tool-bridge.d.ts +4 -0
  162. package/src/tool-bridge.js +306 -0
  163. package/src/tool-bridge.js.map +1 -0
  164. package/src/types.d.ts +775 -0
  165. package/src/types.js +187 -0
  166. package/src/types.js.map +1 -0
  167. package/src/value-sanitizer.d.ts +133 -0
  168. package/src/value-sanitizer.js +421 -0
  169. package/src/value-sanitizer.js.map +1 -0
@@ -0,0 +1,107 @@
1
+ "use strict";
2
+ /**
3
+ * AI Scoring Gate Types and Interfaces
4
+ *
5
+ * Core types for the semantic security scoring system that detects
6
+ * attack patterns beyond what static AST validation can catch.
7
+ *
8
+ * @packageDocumentation
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.RULE_THRESHOLDS = exports.DEFAULT_SCORING_CONFIG = exports.DEFAULT_PROGRESSIVE_CONFIG = void 0;
12
+ exports.normalizeScoringConfig = normalizeScoringConfig;
13
+ /**
14
+ * Default values for progressive scoring
15
+ */
16
+ exports.DEFAULT_PROGRESSIVE_CONFIG = {
17
+ escalationThreshold: 30,
18
+ combination: 'max',
19
+ };
20
+ /**
21
+ * Default scoring gate configuration
22
+ */
23
+ exports.DEFAULT_SCORING_CONFIG = {
24
+ blockThreshold: 70,
25
+ warnThreshold: 40,
26
+ failOpen: true,
27
+ verbose: false,
28
+ cache: {
29
+ enabled: true,
30
+ ttlMs: 300000, // 5 minutes
31
+ maxEntries: 1000,
32
+ },
33
+ };
34
+ /**
35
+ * Normalize a ScoringGateConfig to NormalizedScoringConfig
36
+ *
37
+ * Handles both legacy single-scorer mode and new progressive mode,
38
+ * producing a consistent internal representation.
39
+ *
40
+ * @param config - User-provided configuration
41
+ * @returns Normalized configuration for internal use
42
+ */
43
+ function normalizeScoringConfig(config) {
44
+ // Determine scorer type: progressive config takes precedence
45
+ let scorerType;
46
+ let progressiveConfig;
47
+ let localLlm = config.localLlm;
48
+ let externalApi = config.externalApi;
49
+ let customRules = config.customRules;
50
+ if (config.scoring) {
51
+ // New progressive mode
52
+ scorerType = 'progressive';
53
+ progressiveConfig = config.scoring;
54
+ // Extract nested configs from progressive
55
+ if (progressiveConfig.detailed.localLlm) {
56
+ localLlm = progressiveConfig.detailed.localLlm;
57
+ }
58
+ if (progressiveConfig.detailed.externalApi) {
59
+ externalApi = progressiveConfig.detailed.externalApi;
60
+ }
61
+ if (progressiveConfig.fast.customRules) {
62
+ customRules = { ...customRules, ...progressiveConfig.fast.customRules };
63
+ }
64
+ }
65
+ else {
66
+ // Legacy single-scorer mode
67
+ scorerType = config.scorer ?? 'disabled';
68
+ }
69
+ return {
70
+ scorerType,
71
+ progressiveConfig,
72
+ blockThreshold: config.blockThreshold ?? exports.DEFAULT_SCORING_CONFIG.blockThreshold,
73
+ warnThreshold: config.warnThreshold ?? exports.DEFAULT_SCORING_CONFIG.warnThreshold,
74
+ failOpen: config.failOpen ?? exports.DEFAULT_SCORING_CONFIG.failOpen,
75
+ verbose: config.verbose ?? exports.DEFAULT_SCORING_CONFIG.verbose,
76
+ cache: {
77
+ enabled: config.cache?.enabled ?? exports.DEFAULT_SCORING_CONFIG.cache.enabled,
78
+ ttlMs: config.cache?.ttlMs ?? exports.DEFAULT_SCORING_CONFIG.cache.ttlMs,
79
+ maxEntries: config.cache?.maxEntries ?? exports.DEFAULT_SCORING_CONFIG.cache.maxEntries,
80
+ },
81
+ localLlm,
82
+ externalApi,
83
+ customRules,
84
+ };
85
+ }
86
+ /**
87
+ * Thresholds for various detection rules
88
+ */
89
+ exports.RULE_THRESHOLDS = {
90
+ /**
91
+ * Limit value considered excessive
92
+ */
93
+ EXCESSIVE_LIMIT: 10000,
94
+ /**
95
+ * Numeric value considered extreme
96
+ */
97
+ EXTREME_VALUE: 1000000,
98
+ /**
99
+ * Minimum tool calls to consider high density
100
+ */
101
+ HIGH_DENSITY_CALLS: 5,
102
+ /**
103
+ * Fan-out risk threshold
104
+ */
105
+ HIGH_FAN_OUT: 3,
106
+ };
107
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/scoring/types.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;AAqxBH,wDA4CC;AA1PD;;GAEG;AACU,QAAA,0BAA0B,GAAG;IACxC,mBAAmB,EAAE,EAAE;IACvB,WAAW,EAAE,KAAc;CAC5B,CAAC;AAoHF;;GAEG;AACU,QAAA,sBAAsB,GAI/B;IACF,cAAc,EAAE,EAAE;IAClB,aAAa,EAAE,EAAE;IACjB,QAAQ,EAAE,IAAI;IACd,OAAO,EAAE,KAAK;IACd,KAAK,EAAE;QACL,OAAO,EAAE,IAAI;QACb,KAAK,EAAE,MAAM,EAAE,YAAY;QAC3B,UAAU,EAAE,IAAI;KACjB;CACF,CAAC;AA0DF;;;;;;;;GAQG;AACH,SAAgB,sBAAsB,CAAC,MAAyB;IAC9D,6DAA6D;IAC7D,IAAI,UAAsB,CAAC;IAC3B,IAAI,iBAAuD,CAAC;IAC5D,IAAI,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC;IAC/B,IAAI,WAAW,GAAG,MAAM,CAAC,WAAW,CAAC;IACrC,IAAI,WAAW,GAAG,MAAM,CAAC,WAAW,CAAC;IAErC,IAAI,MAAM,CAAC,OAAO,EAAE,CAAC;QACnB,uBAAuB;QACvB,UAAU,GAAG,aAAa,CAAC;QAC3B,iBAAiB,GAAG,MAAM,CAAC,OAAO,CAAC;QAEnC,0CAA0C;QAC1C,IAAI,iBAAiB,CAAC,QAAQ,CAAC,QAAQ,EAAE,CAAC;YACxC,QAAQ,GAAG,iBAAiB,CAAC,QAAQ,CAAC,QAAQ,CAAC;QACjD,CAAC;QACD,IAAI,iBAAiB,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC;YAC3C,WAAW,GAAG,iBAAiB,CAAC,QAAQ,CAAC,WAAW,CAAC;QACvD,CAAC;QACD,IAAI,iBAAiB,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC;YACvC,WAAW,GAAG,EAAE,GAAG,WAAW,EAAE,GAAG,iBAAiB,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC;QAC1E,CAAC;IACH,CAAC;SAAM,CAAC;QACN,4BAA4B;QAC5B,UAAU,GAAG,MAAM,CAAC,MAAM,IAAI,UAAU,CAAC;IAC3C,CAAC;IAED,OAAO;QACL,UAAU;QACV,iBAAiB;QACjB,cAAc,EAAE,MAAM,CAAC,cAAc,IAAI,8BAAsB,CAAC,cAAc;QAC9E,aAAa,EAAE,MAAM,CAAC,aAAa,IAAI,8BAAsB,CAAC,aAAa;QAC3E,QAAQ,EAAE,MAAM,CAAC,QAAQ,IAAI,8BAAsB,CAAC,QAAQ;QAC5D,OAAO,EAAE,MAAM,CAAC,OAAO,IAAI,8BAAsB,CAAC,OAAO;QACzD,KAAK,EAAE;YACL,OAAO,EAAE,MAAM,CAAC,KAAK,EAAE,OAAO,IAAI,8BAAsB,CAAC,KAAK,CAAC,OAAO;YACtE,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,KAAK,IAAI,8BAAsB,CAAC,KAAK,CAAC,KAAK;YAChE,UAAU,EAAE,MAAM,CAAC,KAAK,EAAE,UAAU,IAAI,8BAAsB,CAAC,KAAK,CAAC,UAAU;SAChF;QACD,QAAQ;QACR,WAAW;QACX,WAAW;KACZ,CAAC;AACJ,CAAC;AAED;;GAEG;AACU,QAAA,eAAe,GAAG;IAC7B;;OAEG;IACH,eAAe,EAAE,KAAK;IAEtB;;OAEG;IACH,aAAa,EAAE,OAAO;IAEtB;;OAEG;IACH,kBAAkB,EAAE,CAAC;IAErB;;OAEG;IACH,YAAY,EAAE,CAAC;CACP,CAAC","sourcesContent":["/**\n * AI Scoring Gate Types and Interfaces\n *\n * Core types for the semantic security scoring system that detects\n * attack patterns beyond what static AST validation can catch.\n *\n * @packageDocumentation\n */\n\n/**\n * Scorer implementation types\n *\n * - `disabled`: No scoring, pass-through mode (0ms latency)\n * - `rule-based`: Pure TypeScript rules, zero dependencies (~1ms latency)\n * - `local-llm`: On-device LLM scoring (~5-10ms latency, model download required)\n * - `external-api`: External API-based scoring (~100ms latency, best detection)\n * - `progressive`: Fast rule-based check, escalate to ML if suspicious\n */\nexport type ScorerType = 'disabled' | 'rule-based' | 'local-llm' | 'external-api' | 'progressive';\n\n/**\n * Scoring strategy types\n *\n * - `single`: Use a single scorer (legacy behavior)\n * - `progressive`: Fast check first, escalate to detailed if suspicious\n */\nexport type ScoringStrategy = 'single' | 'progressive';\n\n/**\n * Risk level classification\n */\nexport type RiskLevel = 'none' | 'low' | 'medium' | 'high' | 'critical';\n\n/**\n * Categories of sensitive data that may be accessed\n */\nexport type SensitiveCategory =\n | 'authentication' // password, token, secret, apiKey\n | 'pii' // email, ssn, phone, creditCard\n | 'financial' // bankAccount, routing\n | 'internal'; // __internal, _private\n\n/**\n * Rule IDs for detection rules\n */\nexport type RuleId =\n | 'SENSITIVE_FIELD' // Queries password/token/secret fields\n | 'EXCESSIVE_LIMIT' // limit > 10,000\n | 'WILDCARD_QUERY' // query=\"*\" or filter={}\n | 'LOOP_TOOL_CALL' // callTool inside for/for-of\n | 'EXFIL_PATTERN' // list→send or query→export sequence\n | 'EXTREME_VALUE' // numeric arg > 1,000,000\n | 'DYNAMIC_TOOL' // Variable tool name (not static)\n | 'BULK_OPERATION'; // Tool name contains bulk/batch/all\n\n/**\n * Individual tool call extracted from the code\n */\nexport interface ExtractedToolCall {\n /**\n * The tool name (e.g., 'users:list', 'billing:getInvoices')\n */\n toolName: string;\n\n /**\n * Whether the tool name is a static string literal\n * Dynamic tool names are more suspicious\n */\n isStaticName: boolean;\n\n /**\n * Keys of arguments passed to the tool\n */\n argumentKeys: string[];\n\n /**\n * String literals found in arguments\n */\n stringLiterals: string[];\n\n /**\n * Numeric literals found in arguments\n */\n numericLiterals: number[];\n\n /**\n * Whether this call is inside a loop\n */\n insideLoop: boolean;\n\n /**\n * How deeply nested in loops (0 = not in loop)\n */\n loopDepth: number;\n\n /**\n * Source location for debugging\n */\n location: { line: number; column: number };\n}\n\n/**\n * Pattern signals extracted from the code\n */\nexport interface PatternSignals {\n /**\n * Total number of tool calls in the code\n */\n totalToolCalls: number;\n\n /**\n * Number of unique tools called\n */\n uniqueToolsCount: number;\n\n /**\n * Tool names that are called inside loops (fan-out risk)\n */\n toolsInLoops: string[];\n\n /**\n * Maximum loop nesting depth\n */\n maxLoopNesting: number;\n\n /**\n * Sequence of tool calls in order (for exfiltration detection)\n * Only includes static tool names\n */\n toolSequence: string[];\n\n /**\n * Whether the code iterates over tool results\n */\n iteratesOverToolResults: boolean;\n}\n\n/**\n * Numeric signals extracted from the code\n */\nexport interface NumericSignals {\n /**\n * Maximum limit/pageSize value found\n */\n maxLimit: number;\n\n /**\n * Maximum string length in arguments\n */\n maxStringLength: number;\n\n /**\n * Tool call density (calls per line)\n */\n toolCallDensity: number;\n\n /**\n * Computed fan-out risk score (0-100)\n */\n fanOutRisk: number;\n}\n\n/**\n * Sensitive field access detected in the code\n */\nexport interface SensitiveAccess {\n /**\n * Field names that may contain sensitive data\n */\n fieldsAccessed: string[];\n\n /**\n * Categories of sensitive data that may be accessed\n */\n categories: SensitiveCategory[];\n}\n\n/**\n * Metadata about the feature extraction\n */\nexport interface ExtractionMeta {\n /**\n * Time taken to extract features in milliseconds\n */\n extractionTimeMs: number;\n\n /**\n * SHA-256 hash of the code (for caching)\n */\n codeHash: string;\n\n /**\n * Number of lines in the code\n */\n lineCount: number;\n}\n\n/**\n * Complete features extracted from code for scoring\n */\nexport interface ExtractedFeatures {\n /**\n * Individual tool calls extracted\n */\n toolCalls: ExtractedToolCall[];\n\n /**\n * Pattern-based signals\n */\n patterns: PatternSignals;\n\n /**\n * Numeric signals\n */\n signals: NumericSignals;\n\n /**\n * Sensitive data access detection\n */\n sensitive: SensitiveAccess;\n\n /**\n * Extraction metadata\n */\n meta: ExtractionMeta;\n}\n\n/**\n * Individual risk signal from a scorer\n */\nexport interface RiskSignal {\n /**\n * Rule identifier\n */\n id: RuleId | string;\n\n /**\n * Risk score contribution (0-100)\n */\n score: number;\n\n /**\n * Human-readable description\n */\n description: string;\n\n /**\n * Risk level\n */\n level: RiskLevel;\n\n /**\n * Additional context data\n */\n context?: Record<string, unknown>;\n}\n\n/**\n * Result from a scorer\n */\nexport interface ScoringResult {\n /**\n * Total risk score (0-100)\n */\n totalScore: number;\n\n /**\n * Overall risk level\n */\n riskLevel: RiskLevel;\n\n /**\n * Individual risk signals\n */\n signals: RiskSignal[];\n\n /**\n * Time taken to score in milliseconds\n */\n scoringTimeMs: number;\n\n /**\n * Scorer that produced this result\n */\n scorerType: ScorerType;\n}\n\n/**\n * Result from the scoring gate evaluation\n */\nexport interface ScoringGateResult {\n /**\n * Whether execution is allowed\n */\n allowed: boolean;\n\n /**\n * Whether a warning was triggered (score >= warnThreshold but < blockThreshold)\n */\n warned?: boolean;\n\n /**\n * Total risk score (0-100)\n */\n totalScore?: number;\n\n /**\n * Overall risk level\n */\n riskLevel?: RiskLevel;\n\n /**\n * Individual risk signals\n */\n signals?: RiskSignal[];\n\n /**\n * Human-readable reason for the decision\n */\n reason?: string;\n\n /**\n * Total evaluation time in milliseconds\n */\n latencyMs: number;\n\n /**\n * Whether the result was served from cache\n */\n cached: boolean;\n\n /**\n * Feature extraction time (if not cached)\n */\n extractionTimeMs?: number;\n\n /**\n * Scoring time (if not cached)\n */\n scoringTimeMs?: number;\n}\n\n/**\n * Configuration for VectoriaDB-based similarity scoring\n *\n * Requires the `vectoriadb` package to be installed:\n * ```bash\n * npm install vectoriadb\n * ```\n * See: https://github.com/agentfront/vectoriadb\n *\n * @breaking v2.x removed the `indexPath` option. VectoriaDB v2.x handles persistence\n * via storage adapters (MemoryStorageAdapter, FileStorageAdapter, RedisStorageAdapter)\n * instead of loadIndex(). If you need to persist patterns, use VectoriaDB's\n * saveToStorage() API directly.\n *\n * @example\n * ```typescript\n * const config: VectoriaConfigForScoring = {\n * threshold: 0.85, // Match threshold\n * topK: 5, // Return top 5 matches\n * modelName: 'Xenova/all-MiniLM-L6-v2',\n * };\n * ```\n */\nexport interface VectoriaConfigForScoring {\n /**\n * Similarity threshold (0-1) for considering a match\n * @default 0.85\n */\n threshold?: number;\n\n /**\n * Top K results to consider\n * @default 5\n */\n topK?: number;\n\n /**\n * Model for embeddings\n * @default Uses the modelId from LocalLlmConfig or 'Xenova/all-MiniLM-L6-v2'\n */\n modelName?: string;\n}\n\n/**\n * Custom analyzer interface for extending LocalLlmScorer\n *\n * Developers can implement this interface to provide custom scoring logic\n * using external LLMs, static analyzers, or other tools.\n *\n * @example\n * ```typescript\n * const myAnalyzer: CustomAnalyzer = {\n * async analyze(prompt, features) {\n * const response = await fetch('https://my-llm-api.com/analyze', {\n * method: 'POST',\n * body: JSON.stringify({ prompt, features }),\n * });\n * const result = await response.json();\n * return { score: result.riskScore, signals: result.signals };\n * }\n * };\n * ```\n */\nexport interface CustomAnalyzer {\n /**\n * Analyze the prompt and features to produce risk signals\n *\n * @param prompt - Text representation of the code features\n * @param features - Extracted features from the code\n * @returns Score (0-100) and risk signals\n */\n analyze(\n prompt: string,\n features: ExtractedFeatures,\n ): Promise<{\n score: number;\n signals: RiskSignal[];\n }>;\n\n /**\n * Optional initialization (e.g., connect to external service)\n */\n initialize?(): Promise<void>;\n\n /**\n * Optional cleanup\n */\n dispose?(): void;\n}\n\n/**\n * Configuration for local LLM scorer\n */\nexport interface LocalLlmConfig {\n /**\n * Model identifier from HuggingFace\n * @example 'Xenova/codebert-base', 'Xenova/all-MiniLM-L6-v2'\n */\n modelId: 'Xenova/codebert-base' | 'Xenova/all-MiniLM-L6-v2' | string;\n\n /**\n * Scoring mode\n * - classification: Use text classification model for direct scoring\n * - similarity: Use embeddings + VectoriaDB for similarity-based scoring\n * @default 'classification'\n */\n mode?: 'classification' | 'similarity';\n\n /**\n * Model cache directory\n * @default '~/.enclave/models'\n */\n cacheDir?: string;\n\n /**\n * Configuration for similarity mode (VectoriaDB)\n * Required when mode='similarity'\n *\n * Requires the `vectoriadb` package to be installed:\n * ```bash\n * npm install vectoriadb\n * ```\n */\n vectoriaConfig?: VectoriaConfigForScoring;\n\n /**\n * Whether to fall back to rule-based scorer on model errors\n * @default true\n */\n fallbackToRules?: boolean;\n\n /**\n * @deprecated Use cacheDir instead\n */\n modelDir?: string;\n\n /**\n * @deprecated Not used in new implementation\n */\n quantization?: 'int4' | 'int8' | 'fp16';\n\n /**\n * @deprecated Not used in new implementation\n */\n maxTokens?: number;\n\n /**\n * Custom analyzer for external LLM or static code analysis\n *\n * If provided, this analyzer will be used instead of the built-in\n * heuristic-based analysis. The HuggingFace pipeline will still be\n * loaded for potential embedding support.\n *\n * @example\n * ```typescript\n * const scorer = new LocalLlmScorer({\n * modelId: 'Xenova/all-MiniLM-L6-v2',\n * customAnalyzer: {\n * async analyze(prompt, features) {\n * const response = await myExternalLLM.score(prompt);\n * return { score: response.score, signals: response.signals };\n * }\n * }\n * });\n * ```\n */\n customAnalyzer?: CustomAnalyzer;\n}\n\n/**\n * Configuration for external API scorer\n */\nexport interface ExternalApiConfig {\n /**\n * API endpoint URL\n * @example 'https://api.example.com/score'\n */\n endpoint: string;\n\n /**\n * API key for authentication (sent as Bearer token)\n */\n apiKey?: string;\n\n /**\n * Request timeout in milliseconds\n * @default 5000\n */\n timeoutMs?: number;\n\n /**\n * Additional headers to include in requests\n */\n headers?: Record<string, string>;\n\n /**\n * Number of retries on failure\n * @default 1\n */\n retries?: number;\n}\n\n/**\n * Configuration for progressive scoring strategy\n *\n * Fast rule-based check first, escalate to detailed ML scoring\n * if the initial score exceeds the escalation threshold.\n */\nexport interface ProgressiveScoringConfig {\n /**\n * Strategy type identifier\n */\n strategy: 'progressive';\n\n /**\n * Fast initial scorer configuration (always rule-based)\n */\n fast: {\n type: 'rule-based';\n customRules?: Record<string, number>;\n };\n\n /**\n * Detailed follow-up scorer configuration\n */\n detailed: {\n type: 'local-llm' | 'external-api';\n localLlm?: LocalLlmConfig;\n externalApi?: ExternalApiConfig;\n };\n\n /**\n * Score threshold to trigger detailed scoring\n * If fast scorer returns >= this value, detailed scorer runs\n * @default 30\n */\n escalationThreshold?: number;\n\n /**\n * How to combine fast and detailed scores\n * - 'replace': Use detailed score only\n * - 'max': Use higher of the two scores\n * - 'avg': Average of both scores\n * @default 'max'\n */\n combination?: 'replace' | 'max' | 'avg';\n}\n\n/**\n * Default values for progressive scoring\n */\nexport const DEFAULT_PROGRESSIVE_CONFIG = {\n escalationThreshold: 30,\n combination: 'max' as const,\n};\n\n/**\n * Configuration for scoring cache\n */\nexport interface ScoringCacheConfig {\n /**\n * Whether caching is enabled\n * @default true\n */\n enabled: boolean;\n\n /**\n * Cache entry time-to-live in milliseconds\n * @default 300000 (5 minutes)\n */\n ttlMs?: number;\n\n /**\n * Maximum number of cached entries\n * @default 1000\n */\n maxEntries?: number;\n}\n\n/**\n * Configuration for the scoring gate\n *\n * Supports two configuration styles:\n * 1. Legacy single-scorer mode: Use `scorer` property\n * 2. Progressive mode: Use `scoring` property with ProgressiveScoringConfig\n *\n * @example\n * // Legacy single-scorer mode\n * { scorer: 'rule-based', blockThreshold: 70 }\n *\n * @example\n * // Progressive mode\n * {\n * scoring: {\n * strategy: 'progressive',\n * fast: { type: 'rule-based' },\n * detailed: { type: 'local-llm', localLlm: { modelId: 'Xenova/codebert-base' } },\n * escalationThreshold: 30\n * },\n * blockThreshold: 70\n * }\n */\nexport interface ScoringGateConfig {\n /**\n * Scorer mode to use (legacy single-scorer mode)\n * Mutually exclusive with `scoring` property\n * @default 'disabled'\n */\n scorer?: ScorerType;\n\n /**\n * Progressive scoring configuration (new mode)\n * Mutually exclusive with `scorer` property\n * Takes precedence over `scorer` if both are provided\n */\n scoring?: ProgressiveScoringConfig;\n\n /**\n * Score threshold for blocking execution (0-100)\n * Scripts with scores >= this value will be blocked\n * @default 70\n */\n blockThreshold?: number;\n\n /**\n * Score threshold for warning (0-100)\n * Scripts with scores >= this value will log a warning\n * @default 40\n */\n warnThreshold?: number;\n\n /**\n * Configuration for local LLM scorer\n * Required when scorer='local-llm'\n */\n localLlm?: LocalLlmConfig;\n\n /**\n * Configuration for external API scorer\n * Required when scorer='external-api'\n */\n externalApi?: ExternalApiConfig;\n\n /**\n * Cache configuration\n */\n cache?: ScoringCacheConfig;\n\n /**\n * Behavior on scoring errors\n *\n * - true (fail-open): Allow execution if scoring fails\n * - false (fail-closed): Block execution if scoring fails\n *\n * @default true\n */\n failOpen?: boolean;\n\n /**\n * Custom rules to add or override for rule-based scorer\n */\n customRules?: Record<string, number>;\n\n /**\n * Log detailed scoring information\n * @default false\n */\n verbose?: boolean;\n}\n\n/**\n * Default scoring gate configuration\n */\nexport const DEFAULT_SCORING_CONFIG: Required<\n Pick<ScoringGateConfig, 'blockThreshold' | 'warnThreshold' | 'failOpen' | 'verbose'>\n> & {\n cache: Required<ScoringCacheConfig>;\n} = {\n blockThreshold: 70,\n warnThreshold: 40,\n failOpen: true,\n verbose: false,\n cache: {\n enabled: true,\n ttlMs: 300000, // 5 minutes\n maxEntries: 1000,\n },\n};\n\n/**\n * Normalized internal configuration used by ScoringGate\n * This is the result of normalizing ScoringGateConfig\n */\nexport interface NormalizedScoringConfig {\n /**\n * The effective scorer type\n */\n scorerType: ScorerType;\n\n /**\n * Progressive config if using progressive strategy\n */\n progressiveConfig?: ProgressiveScoringConfig;\n\n /**\n * Block threshold\n */\n blockThreshold: number;\n\n /**\n * Warn threshold\n */\n warnThreshold: number;\n\n /**\n * Fail-open behavior\n */\n failOpen: boolean;\n\n /**\n * Verbose logging\n */\n verbose: boolean;\n\n /**\n * Cache configuration\n */\n cache: Required<ScoringCacheConfig>;\n\n /**\n * Local LLM configuration (from direct config or progressive)\n */\n localLlm?: LocalLlmConfig;\n\n /**\n * External API configuration (from direct config or progressive)\n */\n externalApi?: ExternalApiConfig;\n\n /**\n * Custom rules for rule-based scorer\n */\n customRules?: Record<string, number>;\n}\n\n/**\n * Normalize a ScoringGateConfig to NormalizedScoringConfig\n *\n * Handles both legacy single-scorer mode and new progressive mode,\n * producing a consistent internal representation.\n *\n * @param config - User-provided configuration\n * @returns Normalized configuration for internal use\n */\nexport function normalizeScoringConfig(config: ScoringGateConfig): NormalizedScoringConfig {\n // Determine scorer type: progressive config takes precedence\n let scorerType: ScorerType;\n let progressiveConfig: ProgressiveScoringConfig | undefined;\n let localLlm = config.localLlm;\n let externalApi = config.externalApi;\n let customRules = config.customRules;\n\n if (config.scoring) {\n // New progressive mode\n scorerType = 'progressive';\n progressiveConfig = config.scoring;\n\n // Extract nested configs from progressive\n if (progressiveConfig.detailed.localLlm) {\n localLlm = progressiveConfig.detailed.localLlm;\n }\n if (progressiveConfig.detailed.externalApi) {\n externalApi = progressiveConfig.detailed.externalApi;\n }\n if (progressiveConfig.fast.customRules) {\n customRules = { ...customRules, ...progressiveConfig.fast.customRules };\n }\n } else {\n // Legacy single-scorer mode\n scorerType = config.scorer ?? 'disabled';\n }\n\n return {\n scorerType,\n progressiveConfig,\n blockThreshold: config.blockThreshold ?? DEFAULT_SCORING_CONFIG.blockThreshold,\n warnThreshold: config.warnThreshold ?? DEFAULT_SCORING_CONFIG.warnThreshold,\n failOpen: config.failOpen ?? DEFAULT_SCORING_CONFIG.failOpen,\n verbose: config.verbose ?? DEFAULT_SCORING_CONFIG.verbose,\n cache: {\n enabled: config.cache?.enabled ?? DEFAULT_SCORING_CONFIG.cache.enabled,\n ttlMs: config.cache?.ttlMs ?? DEFAULT_SCORING_CONFIG.cache.ttlMs,\n maxEntries: config.cache?.maxEntries ?? DEFAULT_SCORING_CONFIG.cache.maxEntries,\n },\n localLlm,\n externalApi,\n customRules,\n };\n}\n\n/**\n * Thresholds for various detection rules\n */\nexport const RULE_THRESHOLDS = {\n /**\n * Limit value considered excessive\n */\n EXCESSIVE_LIMIT: 10000,\n\n /**\n * Numeric value considered extreme\n */\n EXTREME_VALUE: 1000000,\n\n /**\n * Minimum tool calls to consider high density\n */\n HIGH_DENSITY_CALLS: 5,\n\n /**\n * Fan-out risk threshold\n */\n HIGH_FAN_OUT: 3,\n} as const;\n"]}
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Secure Proxy - Runtime Property Access Protection
3
+ *
4
+ * Wraps objects with Proxies that block access to dangerous properties like:
5
+ * - constructor: Gives access to Function constructor for code execution
6
+ * - __proto__: Prototype chain manipulation
7
+ * - prototype: Prototype access
8
+ *
9
+ * This provides defense-in-depth against attacks like:
10
+ * ```javascript
11
+ * const m = 'const';
12
+ * const Func = callTool[m + 'ructor']; // Blocked!
13
+ * ```
14
+ *
15
+ * @packageDocumentation
16
+ */
17
+ import type { SecureProxyLevelConfig, SecurityLevel } from './types';
18
+ /**
19
+ * Categorized blocked properties for defense-in-depth
20
+ *
21
+ * Organized by attack category to support per-security-level configuration
22
+ */
23
+ export declare const BLOCKED_PROPERTY_CATEGORIES: {
24
+ /**
25
+ * Core prototype manipulation properties (always blocked except PERMISSIVE)
26
+ */
27
+ readonly PROTOTYPE: Set<string>;
28
+ /**
29
+ * Node.js 24 Iterator helper method names
30
+ * Blocked at STRICT/SECURE to prevent prototype chain access via iterators
31
+ */
32
+ readonly ITERATOR_HELPERS: Set<string>;
33
+ /**
34
+ * Reflection properties on Object
35
+ * Blocked at STRICT to prevent introspection attacks
36
+ */
37
+ readonly REFLECTION: Set<string>;
38
+ /**
39
+ * Timing API properties
40
+ * Blocked at STRICT to prevent timing attacks
41
+ */
42
+ readonly TIMING: Set<string>;
43
+ };
44
+ /**
45
+ * Type representing the available blocked property categories
46
+ *
47
+ * Each category groups related dangerous properties that can be selectively
48
+ * blocked based on security level requirements.
49
+ */
50
+ export type BlockedPropertyCategory = keyof typeof BLOCKED_PROPERTY_CATEGORIES;
51
+ /**
52
+ * Get blocked properties for a security level
53
+ *
54
+ * @param level Security level
55
+ * @returns Set of property names to block
56
+ */
57
+ export declare function getBlockedPropertiesForLevel(level: SecurityLevel): Set<string>;
58
+ /**
59
+ * Build blocked properties set from SecureProxyLevelConfig
60
+ *
61
+ * @param config The security level proxy configuration
62
+ * @returns Set of property names to block
63
+ */
64
+ export declare function buildBlockedPropertiesFromConfig(config: SecureProxyLevelConfig): Set<string>;
65
+ /**
66
+ * Default SecureProxyLevelConfig (matches current behavior - blocks everything)
67
+ */
68
+ export declare const DEFAULT_SECURE_PROXY_CONFIG: SecureProxyLevelConfig;
69
+ /**
70
+ * Create a safe Reflect wrapper that blocks dangerous operations
71
+ *
72
+ * @param securityLevel The security level to apply
73
+ * @returns A safe Reflect object or undefined (STRICT blocks Reflect entirely)
74
+ */
75
+ export declare function createSafeReflect(securityLevel: SecurityLevel): typeof Reflect | undefined;
76
+ /**
77
+ * Options for secure proxy creation
78
+ */
79
+ export interface SecureProxyOptions {
80
+ /**
81
+ * Security level configuration for the proxy
82
+ * When provided, uses this to determine which properties to block
83
+ */
84
+ levelConfig?: SecureProxyLevelConfig;
85
+ /**
86
+ * Additional properties to block
87
+ */
88
+ additionalBlocked?: string[];
89
+ /**
90
+ * Maximum depth for recursive proxying
91
+ * Default: 10
92
+ */
93
+ maxDepth?: number;
94
+ /**
95
+ * Custom handler for blocked property access
96
+ * If not provided, returns undefined (or throws if throwOnBlocked is true)
97
+ */
98
+ onBlocked?: (target: unknown, property: string | symbol) => void;
99
+ /**
100
+ * Whether to throw an error when blocked properties are accessed.
101
+ *
102
+ * Default behavior:
103
+ * - When using `createSecureProxy()` directly without options: `false` (returns undefined)
104
+ * - When using security levels STRICT/SECURE/STANDARD: `true` (throws error)
105
+ * - When using security level PERMISSIVE: `false` (returns undefined)
106
+ *
107
+ * When true, accessing blocked properties like 'constructor', '__proto__',
108
+ * 'prototype' will throw a SecurityError instead of returning undefined.
109
+ * This makes security violations explicit and easier to detect.
110
+ *
111
+ * **Breaking change note**: Prior versions returned undefined for all security levels.
112
+ * Code that relied on silent undefined returns should either:
113
+ * - Use PERMISSIVE security level, or
114
+ * - Explicitly set `throwOnBlocked: false` in options
115
+ */
116
+ throwOnBlocked?: boolean;
117
+ }
118
+ /**
119
+ * Create a secure proxy that blocks dangerous property access
120
+ *
121
+ * @param target The object to wrap
122
+ * @param options Configuration options
123
+ * @returns A proxy that blocks dangerous property access
124
+ */
125
+ export declare function createSecureProxy<T extends object>(target: T, options?: SecureProxyOptions): T;
126
+ /**
127
+ * Wrap multiple globals with secure proxies
128
+ *
129
+ * @param globals Object containing global values to wrap
130
+ * @param options Proxy options
131
+ * @returns New object with all values wrapped in secure proxies
132
+ */
133
+ export declare function wrapGlobalsWithSecureProxy(globals: Record<string, unknown>, options?: SecureProxyOptions): Record<string, unknown>;
134
+ /**
135
+ * Create a secure version of standard library objects
136
+ *
137
+ * This creates proxied versions of Math, JSON, Array, Object, etc.
138
+ * that block access to dangerous properties.
139
+ */
140
+ export declare function createSecureStandardLibrary(options?: SecureProxyOptions): Record<string, unknown>;
141
+ /**
142
+ * Check if an object is a secure proxy
143
+ *
144
+ * @param obj Object to check
145
+ * @returns true if the object is wrapped in a secure proxy
146
+ */
147
+ export declare function isSecureProxy(obj: unknown): boolean;
148
+ /**
149
+ * Clear the proxy cache
150
+ *
151
+ * @deprecated This function always throws an error. WeakMap and WeakSet entries are
152
+ * automatically garbage collected when their target objects become unreachable.
153
+ * Manual cache clearing is not supported or necessary.
154
+ *
155
+ * @throws {Error} Always throws to inform callers that this operation is not supported
156
+ */
157
+ export declare function clearProxyCache(): void;