@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.
- package/LICENSE +201 -0
- package/README.md +732 -0
- package/SECURITY-AUDIT.md +916 -0
- package/package.json +59 -0
- package/src/adapters/vm-adapter.d.ts +32 -0
- package/src/adapters/vm-adapter.js +1140 -0
- package/src/adapters/vm-adapter.js.map +1 -0
- package/src/adapters/worker-pool/config.d.ts +149 -0
- package/src/adapters/worker-pool/config.js +129 -0
- package/src/adapters/worker-pool/config.js.map +1 -0
- package/src/adapters/worker-pool/errors.d.ts +109 -0
- package/src/adapters/worker-pool/errors.js +181 -0
- package/src/adapters/worker-pool/errors.js.map +1 -0
- package/src/adapters/worker-pool/execution-queue.d.ts +85 -0
- package/src/adapters/worker-pool/execution-queue.js +179 -0
- package/src/adapters/worker-pool/execution-queue.js.map +1 -0
- package/src/adapters/worker-pool/index.d.ts +48 -0
- package/src/adapters/worker-pool/index.js +73 -0
- package/src/adapters/worker-pool/index.js.map +1 -0
- package/src/adapters/worker-pool/memory-monitor.d.ts +106 -0
- package/src/adapters/worker-pool/memory-monitor.js +184 -0
- package/src/adapters/worker-pool/memory-monitor.js.map +1 -0
- package/src/adapters/worker-pool/protocol.d.ts +314 -0
- package/src/adapters/worker-pool/protocol.js +143 -0
- package/src/adapters/worker-pool/protocol.js.map +1 -0
- package/src/adapters/worker-pool/rate-limiter.d.ts +60 -0
- package/src/adapters/worker-pool/rate-limiter.js +101 -0
- package/src/adapters/worker-pool/rate-limiter.js.map +1 -0
- package/src/adapters/worker-pool/safe-deserialize.d.ts +50 -0
- package/src/adapters/worker-pool/safe-deserialize.js +141 -0
- package/src/adapters/worker-pool/safe-deserialize.js.map +1 -0
- package/src/adapters/worker-pool/worker-pool-adapter.d.ts +84 -0
- package/src/adapters/worker-pool/worker-pool-adapter.js +506 -0
- package/src/adapters/worker-pool/worker-pool-adapter.js.map +1 -0
- package/src/adapters/worker-pool/worker-script.d.ts +12 -0
- package/src/adapters/worker-pool/worker-script.js +770 -0
- package/src/adapters/worker-pool/worker-script.js.map +1 -0
- package/src/adapters/worker-pool/worker-slot.d.ts +116 -0
- package/src/adapters/worker-pool/worker-slot.js +301 -0
- package/src/adapters/worker-pool/worker-slot.js.map +1 -0
- package/src/babel/babel-wrapper.d.ts +118 -0
- package/src/babel/babel-wrapper.js +395 -0
- package/src/babel/babel-wrapper.js.map +1 -0
- package/src/babel/index.d.ts +9 -0
- package/src/babel/index.js +17 -0
- package/src/babel/index.js.map +1 -0
- package/src/babel/multi-file-transform.d.ts +122 -0
- package/src/babel/multi-file-transform.js +344 -0
- package/src/babel/multi-file-transform.js.map +1 -0
- package/src/double-vm/double-vm-wrapper.d.ts +65 -0
- package/src/double-vm/double-vm-wrapper.js +523 -0
- package/src/double-vm/double-vm-wrapper.js.map +1 -0
- package/src/double-vm/index.d.ts +31 -0
- package/src/double-vm/index.js +34 -0
- package/src/double-vm/index.js.map +1 -0
- package/src/double-vm/parent-vm-bootstrap.d.ts +63 -0
- package/src/double-vm/parent-vm-bootstrap.js +1695 -0
- package/src/double-vm/parent-vm-bootstrap.js.map +1 -0
- package/src/double-vm/suspicious-patterns.d.ts +57 -0
- package/src/double-vm/suspicious-patterns.js +304 -0
- package/src/double-vm/suspicious-patterns.js.map +1 -0
- package/src/double-vm/types.d.ts +178 -0
- package/src/double-vm/types.js +11 -0
- package/src/double-vm/types.js.map +1 -0
- package/src/double-vm/wrap-adapter.d.ts +36 -0
- package/src/double-vm/wrap-adapter.js +59 -0
- package/src/double-vm/wrap-adapter.js.map +1 -0
- package/src/enclave.d.ts +159 -0
- package/src/enclave.js +671 -0
- package/src/enclave.js.map +1 -0
- package/src/globals-validator.d.ts +80 -0
- package/src/globals-validator.js +206 -0
- package/src/globals-validator.js.map +1 -0
- package/src/index.d.ts +29 -0
- package/src/index.js +130 -0
- package/src/index.js.map +1 -0
- package/src/memory-proxy.d.ts +69 -0
- package/src/memory-proxy.js +310 -0
- package/src/memory-proxy.js.map +1 -0
- package/src/memory-tracker.d.ts +170 -0
- package/src/memory-tracker.js +230 -0
- package/src/memory-tracker.js.map +1 -0
- package/src/safe-error.d.ts +18 -0
- package/src/safe-error.js +76 -0
- package/src/safe-error.js.map +1 -0
- package/src/safe-runtime.d.ts +72 -0
- package/src/safe-runtime.js +656 -0
- package/src/safe-runtime.js.map +1 -0
- package/src/scoring/cache.d.ts +68 -0
- package/src/scoring/cache.js +158 -0
- package/src/scoring/cache.js.map +1 -0
- package/src/scoring/feature-extractor.d.ts +61 -0
- package/src/scoring/feature-extractor.js +366 -0
- package/src/scoring/feature-extractor.js.map +1 -0
- package/src/scoring/index.d.ts +33 -0
- package/src/scoring/index.js +53 -0
- package/src/scoring/index.js.map +1 -0
- package/src/scoring/scorer.interface.d.ts +65 -0
- package/src/scoring/scorer.interface.js +49 -0
- package/src/scoring/scorer.interface.js.map +1 -0
- package/src/scoring/scorers/disabled.scorer.d.ts +19 -0
- package/src/scoring/scorers/disabled.scorer.js +34 -0
- package/src/scoring/scorers/disabled.scorer.js.map +1 -0
- package/src/scoring/scorers/external-api.scorer.d.ts +29 -0
- package/src/scoring/scorers/external-api.scorer.js +141 -0
- package/src/scoring/scorers/external-api.scorer.js.map +1 -0
- package/src/scoring/scorers/index.d.ts +10 -0
- package/src/scoring/scorers/index.js +22 -0
- package/src/scoring/scorers/index.js.map +1 -0
- package/src/scoring/scorers/local-llm.scorer.d.ts +116 -0
- package/src/scoring/scorers/local-llm.scorer.js +474 -0
- package/src/scoring/scorers/local-llm.scorer.js.map +1 -0
- package/src/scoring/scorers/progressive.scorer.d.ts +77 -0
- package/src/scoring/scorers/progressive.scorer.js +199 -0
- package/src/scoring/scorers/progressive.scorer.js.map +1 -0
- package/src/scoring/scorers/rule-based.scorer.d.ts +66 -0
- package/src/scoring/scorers/rule-based.scorer.js +316 -0
- package/src/scoring/scorers/rule-based.scorer.js.map +1 -0
- package/src/scoring/scoring-gate.d.ts +76 -0
- package/src/scoring/scoring-gate.js +246 -0
- package/src/scoring/scoring-gate.js.map +1 -0
- package/src/scoring/types.d.ts +690 -0
- package/src/scoring/types.js +107 -0
- package/src/scoring/types.js.map +1 -0
- package/src/secure-proxy.d.ts +157 -0
- package/src/secure-proxy.js +609 -0
- package/src/secure-proxy.js.map +1 -0
- package/src/session/channels/embedded-channel.d.ts +76 -0
- package/src/session/channels/embedded-channel.js +130 -0
- package/src/session/channels/embedded-channel.js.map +1 -0
- package/src/session/channels/index.d.ts +9 -0
- package/src/session/channels/index.js +14 -0
- package/src/session/channels/index.js.map +1 -0
- package/src/session/index.d.ts +15 -0
- package/src/session/index.js +27 -0
- package/src/session/index.js.map +1 -0
- package/src/session/session-emitter.d.ts +119 -0
- package/src/session/session-emitter.js +253 -0
- package/src/session/session-emitter.js.map +1 -0
- package/src/session/session-state-machine.d.ts +108 -0
- package/src/session/session-state-machine.js +182 -0
- package/src/session/session-state-machine.js.map +1 -0
- package/src/session/session.d.ts +135 -0
- package/src/session/session.js +398 -0
- package/src/session/session.js.map +1 -0
- package/src/session-types.d.ts +313 -0
- package/src/session-types.js +39 -0
- package/src/session-types.js.map +1 -0
- package/src/sidecar/index.d.ts +12 -0
- package/src/sidecar/index.js +31 -0
- package/src/sidecar/index.js.map +1 -0
- package/src/sidecar/reference-config.d.ts +81 -0
- package/src/sidecar/reference-config.js +118 -0
- package/src/sidecar/reference-config.js.map +1 -0
- package/src/sidecar/reference-resolver.d.ts +115 -0
- package/src/sidecar/reference-resolver.js +262 -0
- package/src/sidecar/reference-resolver.js.map +1 -0
- package/src/sidecar/reference-sidecar.d.ts +161 -0
- package/src/sidecar/reference-sidecar.js +226 -0
- package/src/sidecar/reference-sidecar.js.map +1 -0
- package/src/tool-bridge.d.ts +4 -0
- package/src/tool-bridge.js +306 -0
- package/src/tool-bridge.js.map +1 -0
- package/src/types.d.ts +775 -0
- package/src/types.js +187 -0
- package/src/types.js.map +1 -0
- package/src/value-sanitizer.d.ts +133 -0
- package/src/value-sanitizer.js +421 -0
- package/src/value-sanitizer.js.map +1 -0
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Scoring Gate
|
|
3
|
+
*
|
|
4
|
+
* Main orchestrator for the AI scoring system. Handles:
|
|
5
|
+
* - Feature extraction from code
|
|
6
|
+
* - Scorer selection and initialization
|
|
7
|
+
* - Result caching
|
|
8
|
+
* - Decision making (allow/warn/block)
|
|
9
|
+
*
|
|
10
|
+
* @packageDocumentation
|
|
11
|
+
*/
|
|
12
|
+
import { ScoringCache } from './cache';
|
|
13
|
+
import type { ScoringGateConfig, ScoringGateResult, ScorerType } from './types';
|
|
14
|
+
/**
|
|
15
|
+
* Scoring Gate - orchestrates the AI scoring system
|
|
16
|
+
*/
|
|
17
|
+
export declare class ScoringGate {
|
|
18
|
+
private readonly extractor;
|
|
19
|
+
private readonly config;
|
|
20
|
+
private scorer;
|
|
21
|
+
private cache;
|
|
22
|
+
private initialized;
|
|
23
|
+
constructor(config: ScoringGateConfig);
|
|
24
|
+
/**
|
|
25
|
+
* Initialize the scoring gate
|
|
26
|
+
*
|
|
27
|
+
* Must be called before evaluate() for scorers that require initialization
|
|
28
|
+
* (e.g., local-llm needs to download the model)
|
|
29
|
+
*/
|
|
30
|
+
initialize(): Promise<void>;
|
|
31
|
+
/**
|
|
32
|
+
* Create the appropriate scorer based on configuration
|
|
33
|
+
*/
|
|
34
|
+
private createScorer;
|
|
35
|
+
/**
|
|
36
|
+
* Evaluate code for security risks
|
|
37
|
+
*
|
|
38
|
+
* @param code - Source code to evaluate
|
|
39
|
+
* @returns Scoring gate result with allow/warn/block decision
|
|
40
|
+
*/
|
|
41
|
+
evaluate(code: string): Promise<ScoringGateResult>;
|
|
42
|
+
/**
|
|
43
|
+
* Get the current scorer type
|
|
44
|
+
*/
|
|
45
|
+
getScorerType(): ScorerType;
|
|
46
|
+
/**
|
|
47
|
+
* Get cache statistics
|
|
48
|
+
*/
|
|
49
|
+
getCacheStats(): ReturnType<ScoringCache['getStats']> | null;
|
|
50
|
+
/**
|
|
51
|
+
* Clear the cache
|
|
52
|
+
*/
|
|
53
|
+
clearCache(): void;
|
|
54
|
+
/**
|
|
55
|
+
* Dispose of resources
|
|
56
|
+
*/
|
|
57
|
+
dispose(): void;
|
|
58
|
+
/**
|
|
59
|
+
* Check if the gate is ready to evaluate
|
|
60
|
+
*/
|
|
61
|
+
isReady(): boolean;
|
|
62
|
+
/**
|
|
63
|
+
* Get the effective configuration
|
|
64
|
+
*/
|
|
65
|
+
getConfig(): Readonly<typeof this.config>;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Error thrown by the scoring gate
|
|
69
|
+
*/
|
|
70
|
+
export declare class ScoringGateError extends Error {
|
|
71
|
+
constructor(message: string);
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Factory function to create a scoring gate
|
|
75
|
+
*/
|
|
76
|
+
export declare function createScoringGate(config: ScoringGateConfig): ScoringGate;
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Scoring Gate
|
|
4
|
+
*
|
|
5
|
+
* Main orchestrator for the AI scoring system. Handles:
|
|
6
|
+
* - Feature extraction from code
|
|
7
|
+
* - Scorer selection and initialization
|
|
8
|
+
* - Result caching
|
|
9
|
+
* - Decision making (allow/warn/block)
|
|
10
|
+
*
|
|
11
|
+
* @packageDocumentation
|
|
12
|
+
*/
|
|
13
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
14
|
+
exports.ScoringGateError = exports.ScoringGate = void 0;
|
|
15
|
+
exports.createScoringGate = createScoringGate;
|
|
16
|
+
const feature_extractor_1 = require("./feature-extractor");
|
|
17
|
+
const cache_1 = require("./cache");
|
|
18
|
+
const scorers_1 = require("./scorers");
|
|
19
|
+
const types_1 = require("./types");
|
|
20
|
+
/**
|
|
21
|
+
* Scoring Gate - orchestrates the AI scoring system
|
|
22
|
+
*/
|
|
23
|
+
class ScoringGate {
|
|
24
|
+
extractor;
|
|
25
|
+
config;
|
|
26
|
+
scorer = null;
|
|
27
|
+
cache = null;
|
|
28
|
+
initialized = false;
|
|
29
|
+
constructor(config) {
|
|
30
|
+
this.extractor = new feature_extractor_1.FeatureExtractor();
|
|
31
|
+
// Normalize configuration (handles both legacy and new progressive mode)
|
|
32
|
+
this.config = (0, types_1.normalizeScoringConfig)(config);
|
|
33
|
+
// Initialize cache if enabled
|
|
34
|
+
if (this.config.cache.enabled && this.config.scorerType !== 'disabled') {
|
|
35
|
+
this.cache = new cache_1.ScoringCache(this.config.cache);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Initialize the scoring gate
|
|
40
|
+
*
|
|
41
|
+
* Must be called before evaluate() for scorers that require initialization
|
|
42
|
+
* (e.g., local-llm needs to download the model)
|
|
43
|
+
*/
|
|
44
|
+
async initialize() {
|
|
45
|
+
if (this.initialized) {
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
// Create the scorer
|
|
49
|
+
this.scorer = this.createScorer();
|
|
50
|
+
// Initialize the scorer (may download models, etc.)
|
|
51
|
+
await this.scorer.initialize?.();
|
|
52
|
+
this.initialized = true;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Create the appropriate scorer based on configuration
|
|
56
|
+
*/
|
|
57
|
+
createScorer() {
|
|
58
|
+
switch (this.config.scorerType) {
|
|
59
|
+
case 'disabled':
|
|
60
|
+
return new scorers_1.DisabledScorer();
|
|
61
|
+
case 'rule-based':
|
|
62
|
+
return new scorers_1.RuleBasedScorer(this.config.customRules);
|
|
63
|
+
case 'local-llm':
|
|
64
|
+
if (!this.config.localLlm) {
|
|
65
|
+
if (this.config.verbose) {
|
|
66
|
+
console.warn('[ScoringGate] local-llm scorer requires localLlm config, using rule-based fallback');
|
|
67
|
+
}
|
|
68
|
+
return new scorers_1.RuleBasedScorer(this.config.customRules);
|
|
69
|
+
}
|
|
70
|
+
return new scorers_1.LocalLlmScorer(this.config.localLlm);
|
|
71
|
+
case 'external-api':
|
|
72
|
+
if (!this.config.externalApi) {
|
|
73
|
+
throw new ScoringGateError('external-api scorer requires externalApi configuration');
|
|
74
|
+
}
|
|
75
|
+
return new scorers_1.ExternalApiScorer(this.config.externalApi);
|
|
76
|
+
case 'progressive':
|
|
77
|
+
if (!this.config.progressiveConfig) {
|
|
78
|
+
throw new ScoringGateError('progressive scorer requires scoring configuration');
|
|
79
|
+
}
|
|
80
|
+
return new scorers_1.ProgressiveScorer(this.config.progressiveConfig);
|
|
81
|
+
default:
|
|
82
|
+
throw new ScoringGateError(`Unknown scorer type: ${this.config.scorerType}`);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Evaluate code for security risks
|
|
87
|
+
*
|
|
88
|
+
* @param code - Source code to evaluate
|
|
89
|
+
* @returns Scoring gate result with allow/warn/block decision
|
|
90
|
+
*/
|
|
91
|
+
async evaluate(code) {
|
|
92
|
+
const startTime = performance.now();
|
|
93
|
+
// Disabled mode - always allow
|
|
94
|
+
if (this.config.scorerType === 'disabled') {
|
|
95
|
+
return {
|
|
96
|
+
allowed: true,
|
|
97
|
+
reason: 'Scoring disabled',
|
|
98
|
+
latencyMs: performance.now() - startTime,
|
|
99
|
+
cached: false,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
// Ensure initialized
|
|
103
|
+
if (!this.initialized) {
|
|
104
|
+
await this.initialize();
|
|
105
|
+
}
|
|
106
|
+
if (!this.scorer) {
|
|
107
|
+
throw new ScoringGateError('Scorer not initialized');
|
|
108
|
+
}
|
|
109
|
+
try {
|
|
110
|
+
// Extract features
|
|
111
|
+
const extractionStart = performance.now();
|
|
112
|
+
const features = this.extractor.extract(code);
|
|
113
|
+
const extractionTimeMs = performance.now() - extractionStart;
|
|
114
|
+
// Check cache
|
|
115
|
+
if (this.cache) {
|
|
116
|
+
const cached = this.cache.get(features.meta.codeHash);
|
|
117
|
+
if (cached) {
|
|
118
|
+
const allowed = cached.totalScore < this.config.blockThreshold;
|
|
119
|
+
const warned = cached.totalScore >= this.config.warnThreshold;
|
|
120
|
+
if (this.config.verbose) {
|
|
121
|
+
console.log(`[ScoringGate] Cache hit: score=${cached.totalScore}`);
|
|
122
|
+
}
|
|
123
|
+
return {
|
|
124
|
+
allowed,
|
|
125
|
+
warned,
|
|
126
|
+
totalScore: cached.totalScore,
|
|
127
|
+
riskLevel: cached.riskLevel,
|
|
128
|
+
signals: cached.signals,
|
|
129
|
+
latencyMs: performance.now() - startTime,
|
|
130
|
+
cached: true,
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
// Run scorer
|
|
135
|
+
const scoringStart = performance.now();
|
|
136
|
+
const result = await this.scorer.score(features);
|
|
137
|
+
const scoringTimeMs = performance.now() - scoringStart;
|
|
138
|
+
// Cache result
|
|
139
|
+
if (this.cache) {
|
|
140
|
+
this.cache.set(features.meta.codeHash, result);
|
|
141
|
+
}
|
|
142
|
+
// Make decision
|
|
143
|
+
const allowed = result.totalScore < this.config.blockThreshold;
|
|
144
|
+
const warned = result.totalScore >= this.config.warnThreshold && allowed;
|
|
145
|
+
if (this.config.verbose) {
|
|
146
|
+
console.log(`[ScoringGate] Score: ${result.totalScore} (${result.riskLevel}), ` +
|
|
147
|
+
`allowed: ${allowed}, warned: ${warned}`);
|
|
148
|
+
if (result.signals.length > 0) {
|
|
149
|
+
for (const signal of result.signals) {
|
|
150
|
+
console.log(` - ${signal.id}: ${signal.score} (${signal.level}): ${signal.description}`);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return {
|
|
155
|
+
allowed,
|
|
156
|
+
warned,
|
|
157
|
+
totalScore: result.totalScore,
|
|
158
|
+
riskLevel: result.riskLevel,
|
|
159
|
+
signals: result.signals,
|
|
160
|
+
latencyMs: performance.now() - startTime,
|
|
161
|
+
cached: false,
|
|
162
|
+
extractionTimeMs,
|
|
163
|
+
scoringTimeMs,
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
catch (error) {
|
|
167
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
168
|
+
if (this.config.verbose) {
|
|
169
|
+
console.error(`[ScoringGate] Error: ${errorMessage}`);
|
|
170
|
+
}
|
|
171
|
+
// Fail-open or fail-closed
|
|
172
|
+
if (this.config.failOpen) {
|
|
173
|
+
return {
|
|
174
|
+
allowed: true,
|
|
175
|
+
reason: `Scoring error (fail-open): ${errorMessage}`,
|
|
176
|
+
latencyMs: performance.now() - startTime,
|
|
177
|
+
cached: false,
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
return {
|
|
181
|
+
allowed: false,
|
|
182
|
+
reason: `Scoring error (fail-closed): ${errorMessage}`,
|
|
183
|
+
latencyMs: performance.now() - startTime,
|
|
184
|
+
cached: false,
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Get the current scorer type
|
|
190
|
+
*/
|
|
191
|
+
getScorerType() {
|
|
192
|
+
return this.config.scorerType;
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Get cache statistics
|
|
196
|
+
*/
|
|
197
|
+
getCacheStats() {
|
|
198
|
+
return this.cache?.getStats() ?? null;
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Clear the cache
|
|
202
|
+
*/
|
|
203
|
+
clearCache() {
|
|
204
|
+
this.cache?.clear();
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Dispose of resources
|
|
208
|
+
*/
|
|
209
|
+
dispose() {
|
|
210
|
+
this.scorer?.dispose?.();
|
|
211
|
+
this.cache?.clear();
|
|
212
|
+
this.scorer = null;
|
|
213
|
+
this.cache = null;
|
|
214
|
+
this.initialized = false;
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Check if the gate is ready to evaluate
|
|
218
|
+
*/
|
|
219
|
+
isReady() {
|
|
220
|
+
return this.initialized && (this.scorer?.isReady() ?? false);
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* Get the effective configuration
|
|
224
|
+
*/
|
|
225
|
+
getConfig() {
|
|
226
|
+
return this.config;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
exports.ScoringGate = ScoringGate;
|
|
230
|
+
/**
|
|
231
|
+
* Error thrown by the scoring gate
|
|
232
|
+
*/
|
|
233
|
+
class ScoringGateError extends Error {
|
|
234
|
+
constructor(message) {
|
|
235
|
+
super(message);
|
|
236
|
+
this.name = 'ScoringGateError';
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
exports.ScoringGateError = ScoringGateError;
|
|
240
|
+
/**
|
|
241
|
+
* Factory function to create a scoring gate
|
|
242
|
+
*/
|
|
243
|
+
function createScoringGate(config) {
|
|
244
|
+
return new ScoringGate(config);
|
|
245
|
+
}
|
|
246
|
+
//# sourceMappingURL=scoring-gate.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scoring-gate.js","sourceRoot":"","sources":["../../../src/scoring/scoring-gate.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;GAUG;;;AA4QH,8CAEC;AA3QD,2DAAuD;AACvD,mCAAuC;AACvC,uCAAkH;AAElH,mCAAiD;AAEjD;;GAEG;AACH,MAAa,WAAW;IACL,SAAS,CAAmB;IAC5B,MAAM,CAA0B;IACzC,MAAM,GAAkB,IAAI,CAAC;IAC7B,KAAK,GAAwB,IAAI,CAAC;IAClC,WAAW,GAAG,KAAK,CAAC;IAE5B,YAAY,MAAyB;QACnC,IAAI,CAAC,SAAS,GAAG,IAAI,oCAAgB,EAAE,CAAC;QAExC,yEAAyE;QACzE,IAAI,CAAC,MAAM,GAAG,IAAA,8BAAsB,EAAC,MAAM,CAAC,CAAC;QAE7C,8BAA8B;QAC9B,IAAI,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,IAAI,IAAI,CAAC,MAAM,CAAC,UAAU,KAAK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AAkB,CAAC;IACjC,CAAC;CACF;AALD,4CAKC;AAED;;GAEG;AACH,SAAgB,iBAAiB,CAAC,MAAyB;IACzD,OAAO,IAAI,WAAW,CAAC,MAAM,CAAC,CAAC;AACjC,CAAC","sourcesContent":["/**\n * Scoring Gate\n *\n * Main orchestrator for the AI scoring system. Handles:\n * - Feature extraction from code\n * - Scorer selection and initialization\n * - Result caching\n * - Decision making (allow/warn/block)\n *\n * @packageDocumentation\n */\n\nimport type { Scorer } from './scorer.interface';\nimport { FeatureExtractor } from './feature-extractor';\nimport { ScoringCache } from './cache';\nimport { DisabledScorer, RuleBasedScorer, ExternalApiScorer, ProgressiveScorer, LocalLlmScorer } from './scorers';\nimport type { ScoringGateConfig, ScoringGateResult, ScorerType, NormalizedScoringConfig } from './types';\nimport { normalizeScoringConfig } from './types';\n\n/**\n * Scoring Gate - orchestrates the AI scoring system\n */\nexport class ScoringGate {\n private readonly extractor: FeatureExtractor;\n private readonly config: NormalizedScoringConfig;\n private scorer: Scorer | null = null;\n private cache: ScoringCache | null = null;\n private initialized = false;\n\n constructor(config: ScoringGateConfig) {\n this.extractor = new FeatureExtractor();\n\n // Normalize configuration (handles both legacy and new progressive mode)\n this.config = normalizeScoringConfig(config);\n\n // Initialize cache if enabled\n if (this.config.cache.enabled && this.config.scorerType !== 'disabled') {\n this.cache = new ScoringCache(this.config.cache);\n }\n }\n\n /**\n * Initialize the scoring gate\n *\n * Must be called before evaluate() for scorers that require initialization\n * (e.g., local-llm needs to download the model)\n */\n async initialize(): Promise<void> {\n if (this.initialized) {\n return;\n }\n\n // Create the scorer\n this.scorer = this.createScorer();\n\n // Initialize the scorer (may download models, etc.)\n await this.scorer.initialize?.();\n\n this.initialized = true;\n }\n\n /**\n * Create the appropriate scorer based on configuration\n */\n private createScorer(): Scorer {\n switch (this.config.scorerType) {\n case 'disabled':\n return new DisabledScorer();\n\n case 'rule-based':\n return new RuleBasedScorer(this.config.customRules);\n\n case 'local-llm':\n if (!this.config.localLlm) {\n if (this.config.verbose) {\n console.warn('[ScoringGate] local-llm scorer requires localLlm config, using rule-based fallback');\n }\n return new RuleBasedScorer(this.config.customRules);\n }\n return new LocalLlmScorer(this.config.localLlm);\n\n case 'external-api':\n if (!this.config.externalApi) {\n throw new ScoringGateError('external-api scorer requires externalApi configuration');\n }\n return new ExternalApiScorer(this.config.externalApi);\n\n case 'progressive':\n if (!this.config.progressiveConfig) {\n throw new ScoringGateError('progressive scorer requires scoring configuration');\n }\n return new ProgressiveScorer(this.config.progressiveConfig);\n\n default:\n throw new ScoringGateError(`Unknown scorer type: ${this.config.scorerType}`);\n }\n }\n\n /**\n * Evaluate code for security risks\n *\n * @param code - Source code to evaluate\n * @returns Scoring gate result with allow/warn/block decision\n */\n async evaluate(code: string): Promise<ScoringGateResult> {\n const startTime = performance.now();\n\n // Disabled mode - always allow\n if (this.config.scorerType === 'disabled') {\n return {\n allowed: true,\n reason: 'Scoring disabled',\n latencyMs: performance.now() - startTime,\n cached: false,\n };\n }\n\n // Ensure initialized\n if (!this.initialized) {\n await this.initialize();\n }\n\n if (!this.scorer) {\n throw new ScoringGateError('Scorer not initialized');\n }\n\n try {\n // Extract features\n const extractionStart = performance.now();\n const features = this.extractor.extract(code);\n const extractionTimeMs = performance.now() - extractionStart;\n\n // Check cache\n if (this.cache) {\n const cached = this.cache.get(features.meta.codeHash);\n if (cached) {\n const allowed = cached.totalScore < this.config.blockThreshold;\n const warned = cached.totalScore >= this.config.warnThreshold;\n\n if (this.config.verbose) {\n console.log(`[ScoringGate] Cache hit: score=${cached.totalScore}`);\n }\n\n return {\n allowed,\n warned,\n totalScore: cached.totalScore,\n riskLevel: cached.riskLevel,\n signals: cached.signals,\n latencyMs: performance.now() - startTime,\n cached: true,\n };\n }\n }\n\n // Run scorer\n const scoringStart = performance.now();\n const result = await this.scorer.score(features);\n const scoringTimeMs = performance.now() - scoringStart;\n\n // Cache result\n if (this.cache) {\n this.cache.set(features.meta.codeHash, result);\n }\n\n // Make decision\n const allowed = result.totalScore < this.config.blockThreshold;\n const warned = result.totalScore >= this.config.warnThreshold && allowed;\n\n if (this.config.verbose) {\n console.log(\n `[ScoringGate] Score: ${result.totalScore} (${result.riskLevel}), ` +\n `allowed: ${allowed}, warned: ${warned}`,\n );\n if (result.signals.length > 0) {\n for (const signal of result.signals) {\n console.log(` - ${signal.id}: ${signal.score} (${signal.level}): ${signal.description}`);\n }\n }\n }\n\n return {\n allowed,\n warned,\n totalScore: result.totalScore,\n riskLevel: result.riskLevel,\n signals: result.signals,\n latencyMs: performance.now() - startTime,\n cached: false,\n extractionTimeMs,\n scoringTimeMs,\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n\n if (this.config.verbose) {\n console.error(`[ScoringGate] Error: ${errorMessage}`);\n }\n\n // Fail-open or fail-closed\n if (this.config.failOpen) {\n return {\n allowed: true,\n reason: `Scoring error (fail-open): ${errorMessage}`,\n latencyMs: performance.now() - startTime,\n cached: false,\n };\n }\n\n return {\n allowed: false,\n reason: `Scoring error (fail-closed): ${errorMessage}`,\n latencyMs: performance.now() - startTime,\n cached: false,\n };\n }\n }\n\n /**\n * Get the current scorer type\n */\n getScorerType(): ScorerType {\n return this.config.scorerType;\n }\n\n /**\n * Get cache statistics\n */\n getCacheStats(): ReturnType<ScoringCache['getStats']> | null {\n return this.cache?.getStats() ?? null;\n }\n\n /**\n * Clear the cache\n */\n clearCache(): void {\n this.cache?.clear();\n }\n\n /**\n * Dispose of resources\n */\n dispose(): void {\n this.scorer?.dispose?.();\n this.cache?.clear();\n this.scorer = null;\n this.cache = null;\n this.initialized = false;\n }\n\n /**\n * Check if the gate is ready to evaluate\n */\n isReady(): boolean {\n return this.initialized && (this.scorer?.isReady() ?? false);\n }\n\n /**\n * Get the effective configuration\n */\n getConfig(): Readonly<typeof this.config> {\n return this.config;\n }\n}\n\n/**\n * Error thrown by the scoring gate\n */\nexport class ScoringGateError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ScoringGateError';\n }\n}\n\n/**\n * Factory function to create a scoring gate\n */\nexport function createScoringGate(config: ScoringGateConfig): ScoringGate {\n return new ScoringGate(config);\n}\n"]}
|