agentshield-sdk 7.2.0 → 7.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/main.js CHANGED
@@ -27,7 +27,7 @@ function safeRequire(path, label) {
27
27
  // Core (these are critical — if they fail, we still export what we can)
28
28
  const { AgentShield } = safeRequire('./index', 'core');
29
29
  const { scanText, getPatterns, SEVERITY_ORDER } = safeRequire('./detector-core', 'detector-core');
30
- const { expressMiddleware, wrapAgent, shieldTools, extractTextFromBody } = safeRequire('./middleware', 'middleware');
30
+ const { expressMiddleware, wrapAgent, shieldTools, extractTextFromBody, rateLimitMiddleware, shieldMiddleware } = safeRequire('./middleware', 'middleware');
31
31
 
32
32
  // Protection
33
33
  const { CircuitBreaker, shadowMode, RateLimiter, STATE } = safeRequire('./circuit-breaker', 'circuit-breaker');
@@ -51,7 +51,7 @@ const { SteganographyDetector, EncodingBruteforceDetector, StructuredDataScanner
51
51
  const { OutputWatermark, DifferentialPrivacy } = safeRequire('./watermark', 'watermark');
52
52
 
53
53
  // Utilities
54
- const { getGrade, getGradeLabel, makeBar, truncate, formatHeader, generateId } = safeRequire('./utils', 'utils');
54
+ const { getGrade, getGradeLabel, makeBar, truncate, formatHeader, generateId, createGracefulShutdown, loadEnvFile } = safeRequire('./utils', 'utils');
55
55
 
56
56
  // Error codes & deprecation
57
57
  const { ERROR_CODES, createShieldError, deprecationWarning } = safeRequire('./errors', 'errors');
@@ -173,6 +173,48 @@ const { OpenClawShieldSkill, shieldOpenClawMessages, generateOpenClawSkill } = s
173
173
  // v7.2 — IPIA Detector
174
174
  const { IPIADetector, ContextConstructor, FeatureExtractor, TreeClassifier, ExternalEmbedder, createIPIAScanner, ipiaMiddleware, FEATURE_NAMES: IPIA_FEATURE_NAMES, INJECTION_LEXICON: IPIA_INJECTION_LEXICON } = safeRequire('./ipia-detector', 'ipia-detector');
175
175
 
176
+ // v7.2.1 — Pre-Deployment Audit
177
+ const { SecurityAudit, AuditReport, AUDIT_ATTACKS, generateMutations: auditMutations, runAuditCLI } = safeRequire('./audit', 'audit');
178
+
179
+ // v7.2.1 — Flight Recorder
180
+ const { FlightRecorder } = safeRequire('./flight-recorder', 'flight-recorder');
181
+
182
+ // v7.2.1 — HTML Report Generator
183
+ const { generateHTMLReport, generateReportFile } = safeRequire('./report-generator', 'report-generator');
184
+
185
+ // v7.3 — Supply Chain Verification
186
+ const { ToolChainValidator, ResponseScanner, DomainAllowlist, RESPONSE_INJECTION_PATTERNS, EXFILTRATION_URL_PATTERNS, CREDENTIAL_PATTERNS, CHAIN_SUSPICIOUS_PATTERNS } = safeRequire('./supply-chain', 'supply-chain');
187
+
188
+ // v7.4 — Herd Immunity
189
+ const { HerdImmunity, ImmuneMemory, createHerdNetwork } = safeRequire('./herd-immunity', 'herd-immunity');
190
+
191
+ // v7.4 — Adversarial Evolution Simulator
192
+ const { EvolutionSimulator, MutationEngine, hardenFromEvolution } = safeRequire('./evolution-simulator', 'evolution-simulator');
193
+
194
+ // v7.4 — Attack Replay Platform
195
+ const { AttackReplayEngine, compareDefenses } = safeRequire('./attack-replay', 'attack-replay');
196
+
197
+ // v7.4 — Enterprise SOC Dashboard
198
+ const { SOCDashboard, SlackAlertChannel, PagerDutyAlertChannel, TeamsAlertChannel } = safeRequire('./soc-dashboard', 'soc-dashboard');
199
+
200
+ // v7.4 — Attack Genome (loaded when available)
201
+ const { AttackGenome, GenomeDatabase, detectByGenome, INTENT_PATTERNS: GENOME_INTENT_PATTERNS, TECHNIQUE_PATTERNS: GENOME_TECHNIQUE_PATTERNS, EVASION_PATTERNS: GENOME_EVASION_PATTERNS, TARGET_PATTERNS: GENOME_TARGET_PATTERNS } = safeRequire('./attack-genome', 'attack-genome');
202
+
203
+ // v7.4 — Intent Firewall (loaded when available)
204
+ const { IntentFirewall, ContextAnalyzer: IntentContextAnalyzer, IntentRules, intentDemo, INTENT_CATEGORIES, INTENT_SIGNALS, CONTEXT_MODIFIERS } = safeRequire('./intent-firewall', 'intent-firewall');
205
+
206
+ // v7.4 — Real Attack Dataset Testing
207
+ const { DatasetRunner, HACKAPROMPT_SAMPLES, TENSORTRUST_SAMPLES, RESEARCH_SAMPLES, BENIGN_SAMPLES } = safeRequire('./real-attack-datasets', 'real-attack-datasets');
208
+
209
+ // v7.4 — Federated Threat Intelligence
210
+ const { ThreatIntelFederation, createFederationMesh } = safeRequire('./threat-intel-federation', 'threat-intel-federation');
211
+
212
+ // v7.4 — Behavioral DNA (loaded when available)
213
+ const { BehavioralDNA, AgentProfiler, extractFeatures: extractBehavioralFeatures, DEFAULT_NUMERIC_FEATURES, DEFAULT_CATEGORICAL_FEATURES } = safeRequire('./behavioral-dna', 'behavioral-dna');
214
+
215
+ // v7.4 — Compliance Certification Authority (loaded when available)
216
+ const { ComplianceCertificateAuthority, ComplianceReport: ComplianceCertReport, ComplianceScheduler, AUTHORITY_FRAMEWORKS, CAPABILITY_MAP: CA_CAPABILITY_MAP, CERTIFICATE_LEVELS: CA_CERTIFICATE_LEVELS } = safeRequire('./compliance-authority', 'compliance-authority');
217
+
176
218
  // --- v1.2 Modules ---
177
219
 
178
220
  // Semantic Detection
@@ -288,6 +330,8 @@ const _exports = {
288
330
  wrapAgent,
289
331
  shieldTools,
290
332
  extractTextFromBody,
333
+ rateLimitMiddleware,
334
+ shieldMiddleware,
291
335
 
292
336
  // Protection
293
337
  CircuitBreaker,
@@ -343,6 +387,8 @@ const _exports = {
343
387
  truncate,
344
388
  formatHeader,
345
389
  generateId,
390
+ createGracefulShutdown,
391
+ loadEnvFile,
346
392
 
347
393
  // Integrations
348
394
  ShieldCallbackHandler,
@@ -753,6 +799,93 @@ const _exports = {
753
799
  ipiaMiddleware,
754
800
  IPIA_FEATURE_NAMES,
755
801
  IPIA_INJECTION_LEXICON,
802
+
803
+ // v7.2.1 — Pre-Deployment Audit
804
+ SecurityAudit,
805
+ AuditReport,
806
+ AUDIT_ATTACKS,
807
+ auditMutations,
808
+ runAuditCLI,
809
+
810
+ // v7.2.1 — Flight Recorder
811
+ FlightRecorder,
812
+
813
+ // v7.2.1 — HTML Report Generator
814
+ generateHTMLReport,
815
+ generateReportFile,
816
+
817
+ // v7.3 — Supply Chain Verification
818
+ ToolChainValidator,
819
+ ResponseScanner,
820
+ DomainAllowlist,
821
+ RESPONSE_INJECTION_PATTERNS,
822
+ EXFILTRATION_URL_PATTERNS,
823
+ CREDENTIAL_PATTERNS,
824
+ CHAIN_SUSPICIOUS_PATTERNS,
825
+
826
+ // v7.4 — Herd Immunity
827
+ HerdImmunity,
828
+ ImmuneMemory,
829
+ createHerdNetwork,
830
+
831
+ // v7.4 — Adversarial Evolution Simulator
832
+ EvolutionSimulator,
833
+ MutationEngine,
834
+ hardenFromEvolution,
835
+
836
+ // v7.4 — Attack Replay Platform
837
+ AttackReplayEngine,
838
+ compareDefenses,
839
+
840
+ // v7.4 — Enterprise SOC Dashboard
841
+ SOCDashboard,
842
+ SlackAlertChannel,
843
+ PagerDutyAlertChannel,
844
+ TeamsAlertChannel,
845
+
846
+ // v7.4 — Attack Genome
847
+ AttackGenome,
848
+ GenomeDatabase,
849
+ detectByGenome,
850
+ GENOME_INTENT_PATTERNS,
851
+ GENOME_TECHNIQUE_PATTERNS,
852
+ GENOME_EVASION_PATTERNS,
853
+ GENOME_TARGET_PATTERNS,
854
+
855
+ // v7.4 — Intent Firewall
856
+ IntentFirewall,
857
+ IntentContextAnalyzer,
858
+ IntentRules,
859
+ intentDemo,
860
+ INTENT_CATEGORIES,
861
+ INTENT_SIGNALS,
862
+ CONTEXT_MODIFIERS,
863
+
864
+ // v7.4 — Real Attack Datasets
865
+ DatasetRunner,
866
+ HACKAPROMPT_SAMPLES,
867
+ TENSORTRUST_SAMPLES,
868
+ RESEARCH_SAMPLES,
869
+ BENIGN_SAMPLES,
870
+
871
+ // v7.4 — Federated Threat Intelligence
872
+ ThreatIntelFederation,
873
+ createFederationMesh,
874
+
875
+ // v7.4 — Behavioral DNA
876
+ BehavioralDNA,
877
+ AgentProfiler,
878
+ extractBehavioralFeatures,
879
+ DEFAULT_NUMERIC_FEATURES,
880
+ DEFAULT_CATEGORICAL_FEATURES,
881
+
882
+ // v7.5 — Compliance Certification Authority
883
+ ComplianceCertificateAuthority,
884
+ ComplianceCertReport,
885
+ ComplianceScheduler,
886
+ AUTHORITY_FRAMEWORKS,
887
+ CA_CAPABILITY_MAP,
888
+ CA_CERTIFICATE_LEVELS,
756
889
  };
757
890
 
758
891
  // Filter out undefined exports (from modules that failed to load)
@@ -23,6 +23,7 @@
23
23
  */
24
24
 
25
25
  const crypto = require('crypto');
26
+ const { createShieldError } = require('./errors');
26
27
  const { MCPBridge, MCPSessionGuard, MCPResourceScanner, MCPToolPolicy } = require('./mcp-bridge');
27
28
  const { AuthorizationContext, ConfusedDeputyGuard } = require('./confused-deputy');
28
29
  const { BehaviorProfile } = require('./behavior-profiling');
@@ -199,14 +200,14 @@ class MCPSecurityRuntime {
199
200
  */
200
201
  createSession(params) {
201
202
  if (!params.userId || !params.agentId) {
202
- throw new Error(`${LOG_PREFIX} createSession requires userId and agentId`);
203
+ throw createShieldError('AS-AUT-004', { reason: 'createSession requires userId and agentId' });
203
204
  }
204
205
 
205
206
  // Enforce per-user session limit
206
207
  const userSessions = this._userSessions.get(params.userId) || new Set();
207
208
  if (userSessions.size >= this._maxSessionsPerUser) {
208
209
  this._audit('session_denied', { userId: params.userId, reason: 'max_sessions_exceeded' });
209
- throw new Error(`${LOG_PREFIX} Max sessions (${this._maxSessionsPerUser}) exceeded for user`);
210
+ throw createShieldError('AS-AUT-005', { userId: params.userId, maxSessions: this._maxSessionsPerUser });
210
211
  }
211
212
 
212
213
  const sessionId = crypto.randomUUID();
@@ -693,18 +694,18 @@ class MCPSecurityRuntime {
693
694
  delegateSession(sessionId, delegateAgentId, delegateScopes) {
694
695
  const parentSession = this._sessions.get(sessionId);
695
696
  if (!parentSession) {
696
- throw new Error(`${LOG_PREFIX} Cannot delegate: invalid session`);
697
+ throw createShieldError('AS-AUT-006', { sessionId, reason: 'Cannot delegate: invalid session' });
697
698
  }
698
699
 
699
700
  // Enforce delegation depth limit
700
701
  if ((parentSession.authCtx.delegationDepth || 0) >= this._maxDelegationDepth) {
701
- throw new Error(`${LOG_PREFIX} Cannot delegate: max delegation depth (${this._maxDelegationDepth}) exceeded`);
702
+ throw createShieldError('AS-AUT-007', { maxDepth: this._maxDelegationDepth, reason: 'Cannot delegate: max delegation depth exceeded' });
702
703
  }
703
704
 
704
705
  // Enforce per-user session limit for delegated sessions too
705
706
  const userSessions = this._userSessions.get(parentSession.authCtx.userId) || new Set();
706
707
  if (userSessions.size >= this._maxSessionsPerUser) {
707
- throw new Error(`${LOG_PREFIX} Cannot delegate: max sessions (${this._maxSessionsPerUser}) exceeded for user`);
708
+ throw createShieldError('AS-AUT-005', { userId: parentSession.authCtx.userId, maxSessions: this._maxSessionsPerUser, reason: 'Cannot delegate: max sessions exceeded for user' });
708
709
  }
709
710
 
710
711
  const childCtx = parentSession.authCtx.delegate(delegateAgentId, delegateScopes);
@@ -812,16 +813,41 @@ class MCPSecurityRuntime {
812
813
 
813
814
  /**
814
815
  * Shuts down the runtime and cleans up resources.
816
+ * @param {object} [options]
817
+ * @param {number} [options.timeoutMs=10000] - Max time to wait for drain before forced cleanup.
818
+ * @returns {Promise<void>}
815
819
  */
816
- shutdown() {
820
+ async shutdown(options = {}) {
821
+ const timeoutMs = options.timeoutMs || 10000;
822
+
817
823
  if (this._cleanupInterval) {
818
824
  clearInterval(this._cleanupInterval);
819
825
  this._cleanupInterval = null;
820
826
  }
821
- const sessionIds = [...this._sessions.keys()];
822
- for (const sessionId of sessionIds) {
823
- this.terminateSession(sessionId);
824
- }
827
+
828
+ // Drain: wait for in-flight operations with timeout
829
+ const drainPromise = new Promise((resolve) => {
830
+ const sessionIds = [...this._sessions.keys()];
831
+ for (const sessionId of sessionIds) {
832
+ try {
833
+ this.terminateSession(sessionId);
834
+ } catch (err) {
835
+ console.error(`${LOG_PREFIX} Error terminating session ${sessionId}: ${err.message}`);
836
+ }
837
+ }
838
+ resolve();
839
+ });
840
+
841
+ const timeoutPromise = new Promise((resolve) => {
842
+ const timer = setTimeout(() => {
843
+ console.error(`${LOG_PREFIX} Shutdown drain timeout (${timeoutMs}ms), forcing cleanup`);
844
+ resolve();
845
+ }, timeoutMs);
846
+ if (timer.unref) timer.unref();
847
+ });
848
+
849
+ await Promise.race([drainPromise, timeoutPromise]);
850
+
825
851
  this._audit('runtime_shutdown', { totalProcessed: this.stats.toolCallsProcessed });
826
852
  }
827
853
 
package/src/mcp-server.js CHANGED
@@ -707,6 +707,11 @@ class MCPServer {
707
707
  // =========================================================================
708
708
 
709
709
  if (require.main === module) {
710
+ const { createGracefulShutdown, loadEnvFile } = require('./utils');
711
+
712
+ // Load .env file if present
713
+ loadEnvFile();
714
+
710
715
  let config = {};
711
716
 
712
717
  // Parse --config flag
@@ -726,15 +731,14 @@ if (require.main === module) {
726
731
  const server = new MCPServer(config);
727
732
  server.start();
728
733
 
729
- // Graceful shutdown
730
- process.on('SIGINT', () => {
731
- server.stop();
732
- process.exit(0);
733
- });
734
- process.on('SIGTERM', () => {
735
- server.stop();
736
- process.exit(0);
734
+ // Graceful shutdown with timeout enforcement
735
+ const { shutdown } = createGracefulShutdown({
736
+ timeoutMs: parseInt(process.env.SHIELD_SHUTDOWN_TIMEOUT_MS, 10) || 10000,
737
+ cleanupFns: [() => server.stop()]
737
738
  });
739
+
740
+ process.on('SIGINT', () => shutdown('SIGINT').then(() => process.exit(0)));
741
+ process.on('SIGTERM', () => shutdown('SIGTERM').then(() => process.exit(0)));
738
742
  }
739
743
 
740
744
  module.exports = { MCPServer, MCPToolHandler };