@vorionsys/cognigate 1.0.1 → 1.0.2

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/dist/index.cjs CHANGED
@@ -29,6 +29,8 @@ __export(index_exports, {
29
29
  TrustStatusSchema: () => TrustStatusSchema,
30
30
  TrustTier: () => import_shared_constants.TrustTier,
31
31
  WebhookRouter: () => WebhookRouter,
32
+ WorkerSandbox: () => WorkerSandbox,
33
+ createProofBridge: () => createProofBridge,
32
34
  parseWebhookPayload: () => parseWebhookPayload,
33
35
  verifyWebhookSignature: () => verifyWebhookSignature,
34
36
  z: () => import_zod2.z
@@ -190,7 +192,7 @@ var Cognigate = class {
190
192
  if (score >= 876) return import_shared_constants.TrustTier.T6_CERTIFIED;
191
193
  if (score >= 800) return import_shared_constants.TrustTier.T5_TRUSTED;
192
194
  if (score >= 650) return import_shared_constants.TrustTier.T4_STANDARD;
193
- if (score >= 501) return import_shared_constants.TrustTier.T3_MONITORED;
195
+ if (score >= 500) return import_shared_constants.TrustTier.T3_MONITORED;
194
196
  if (score >= 350) return import_shared_constants.TrustTier.T2_PROVISIONAL;
195
197
  if (score >= 200) return import_shared_constants.TrustTier.T1_OBSERVED;
196
198
  return import_shared_constants.TrustTier.T0_SANDBOX;
@@ -473,6 +475,281 @@ function timingSafeEqual(a, b) {
473
475
  return result === 0;
474
476
  }
475
477
 
478
+ // src/proof-bridge.ts
479
+ function createProofBridge(config) {
480
+ const { proofPlane, webhookRouter } = config;
481
+ let connected = true;
482
+ const handler = async (event) => {
483
+ if (!connected) return;
484
+ const payload = event.payload;
485
+ const now = /* @__PURE__ */ new Date();
486
+ const decision = {
487
+ decisionId: payload.decisionId ?? event.id,
488
+ intentId: payload.intentId ?? "",
489
+ agentId: payload.agentId ?? event.entityId,
490
+ correlationId: payload.correlationId ?? event.id,
491
+ permitted: payload.permitted ?? payload.decision === "ALLOW",
492
+ trustBand: payload.trustBand ?? 4,
493
+ trustScore: payload.trustScore ?? 0,
494
+ reasoning: Array.isArray(payload.reasoning) ? payload.reasoning : typeof payload.reasoning === "string" ? [payload.reasoning] : [],
495
+ decidedAt: payload.decidedAt ? new Date(payload.decidedAt) : now,
496
+ expiresAt: payload.expiresAt ? new Date(payload.expiresAt) : new Date(now.getTime() + 24 * 60 * 60 * 1e3),
497
+ latencyMs: payload.latencyMs ?? 0,
498
+ version: payload.version ?? 1
499
+ };
500
+ await proofPlane.logDecisionMade(decision, decision.correlationId);
501
+ };
502
+ webhookRouter.on("governance.decision", handler);
503
+ return {
504
+ disconnect: () => {
505
+ connected = false;
506
+ }
507
+ };
508
+ }
509
+
510
+ // src/sandbox/worker-sandbox.ts
511
+ var import_node_worker_threads = require("worker_threads");
512
+ var DEFAULT_TIMEOUT2 = 3e4;
513
+ var DEFAULT_MEMORY_LIMIT_MB = 64;
514
+ var WORKER_SCRIPT = `
515
+ const { parentPort, workerData } = require('node:worker_threads');
516
+ const vm = require('node:vm');
517
+
518
+ const { code, context } = workerData;
519
+ const startTime = performance.now();
520
+ const memBefore = process.memoryUsage().heapUsed;
521
+
522
+ // Build restricted globals for the vm context
523
+ const safeGlobals = {
524
+ console: {
525
+ log: function() {},
526
+ warn: function() {},
527
+ error: function() {},
528
+ info: function() {},
529
+ },
530
+ JSON: JSON,
531
+ Math: Math,
532
+ Date: Date,
533
+ Array: Array,
534
+ Object: Object,
535
+ String: String,
536
+ Number: Number,
537
+ Boolean: Boolean,
538
+ Map: Map,
539
+ Set: Set,
540
+ WeakMap: WeakMap,
541
+ WeakSet: WeakSet,
542
+ Promise: Promise,
543
+ Symbol: Symbol,
544
+ RegExp: RegExp,
545
+ Error: Error,
546
+ TypeError: TypeError,
547
+ RangeError: RangeError,
548
+ SyntaxError: SyntaxError,
549
+ URIError: URIError,
550
+ parseInt: parseInt,
551
+ parseFloat: parseFloat,
552
+ isNaN: isNaN,
553
+ isFinite: isFinite,
554
+ encodeURIComponent: encodeURIComponent,
555
+ decodeURIComponent: decodeURIComponent,
556
+ encodeURI: encodeURI,
557
+ decodeURI: decodeURI,
558
+ undefined: undefined,
559
+ NaN: NaN,
560
+ Infinity: Infinity,
561
+ setTimeout: function(fn, ms) { return setTimeout(fn, Math.min(ms, 5000)); },
562
+ clearTimeout: clearTimeout,
563
+ };
564
+
565
+ const vmContext = vm.createContext(safeGlobals);
566
+
567
+ // Wrap code in an async IIFE to support await and return
568
+ const wrappedCode = '(async () => { ' + code + ' })()';
569
+
570
+ async function run() {
571
+ try {
572
+ const script = new vm.Script(wrappedCode, {
573
+ filename: 'sandbox-' + context.agentId + '.js',
574
+ });
575
+
576
+ const result = await script.runInContext(vmContext, {
577
+ timeout: context.timeout,
578
+ });
579
+
580
+ const durationMs = performance.now() - startTime;
581
+ const memAfter = process.memoryUsage().heapUsed;
582
+
583
+ parentPort.postMessage({
584
+ type: 'result',
585
+ output: result,
586
+ durationMs: durationMs,
587
+ memoryUsedBytes: Math.max(0, memAfter - memBefore),
588
+ });
589
+ } catch (err) {
590
+ const durationMs = performance.now() - startTime;
591
+ const memAfter = process.memoryUsage().heapUsed;
592
+
593
+ parentPort.postMessage({
594
+ type: 'error',
595
+ error: err && err.message ? err.message : String(err),
596
+ durationMs: durationMs,
597
+ memoryUsedBytes: Math.max(0, memAfter - memBefore),
598
+ });
599
+ }
600
+ }
601
+
602
+ run();
603
+ `;
604
+ var WorkerSandbox = class {
605
+ worker = null;
606
+ isShutdown = false;
607
+ /**
608
+ * Execute code in an isolated worker thread.
609
+ *
610
+ * Spawns a new worker for each execution to ensure full isolation.
611
+ * The worker has memory limits enforced by V8 via `resourceLimits`,
612
+ * a vm-level timeout for synchronous code, and a main-thread timeout
613
+ * as a fallback for async code or hangs.
614
+ *
615
+ * @param code - JavaScript code string to execute inside the sandbox.
616
+ * The code is wrapped in an async IIFE, so `return` and `await` are valid.
617
+ * @param context - Execution context with identity and resource constraints
618
+ * @returns Promise resolving to a SandboxResult
619
+ */
620
+ async execute(code, context) {
621
+ if (this.isShutdown) {
622
+ return {
623
+ success: false,
624
+ output: void 0,
625
+ error: "Sandbox has been shut down",
626
+ durationMs: 0,
627
+ memoryUsedBytes: 0
628
+ };
629
+ }
630
+ const timeout = context.timeout || DEFAULT_TIMEOUT2;
631
+ const memoryLimitMb = context.memoryLimitMb || DEFAULT_MEMORY_LIMIT_MB;
632
+ const startTime = performance.now();
633
+ return new Promise((resolve) => {
634
+ let settled = false;
635
+ let timeoutId = null;
636
+ const settle = (result) => {
637
+ if (settled) return;
638
+ settled = true;
639
+ if (timeoutId) {
640
+ clearTimeout(timeoutId);
641
+ timeoutId = null;
642
+ }
643
+ resolve(result);
644
+ };
645
+ try {
646
+ const worker = new import_node_worker_threads.Worker(WORKER_SCRIPT, {
647
+ eval: true,
648
+ workerData: {
649
+ code,
650
+ context: {
651
+ tenantId: context.tenantId,
652
+ agentId: context.agentId,
653
+ trustLevel: context.trustLevel ?? 0,
654
+ allowedModules: context.allowedModules ?? [],
655
+ timeout,
656
+ memoryLimitMb
657
+ }
658
+ },
659
+ resourceLimits: {
660
+ maxOldGenerationSizeMb: memoryLimitMb,
661
+ maxYoungGenerationSizeMb: Math.max(1, Math.floor(memoryLimitMb / 4)),
662
+ codeRangeSizeMb: Math.max(1, Math.floor(memoryLimitMb / 8))
663
+ }
664
+ });
665
+ this.worker = worker;
666
+ timeoutId = setTimeout(() => {
667
+ const durationMs = performance.now() - startTime;
668
+ worker.terminate().catch(() => {
669
+ });
670
+ settle({
671
+ success: false,
672
+ output: void 0,
673
+ error: `Execution timed out after ${timeout}ms`,
674
+ durationMs,
675
+ memoryUsedBytes: 0
676
+ });
677
+ }, timeout + 500);
678
+ worker.on("message", (message) => {
679
+ if (message.type === "result") {
680
+ settle({
681
+ success: true,
682
+ output: message.output,
683
+ durationMs: message.durationMs,
684
+ memoryUsedBytes: message.memoryUsedBytes
685
+ });
686
+ } else if (message.type === "error") {
687
+ settle({
688
+ success: false,
689
+ output: void 0,
690
+ error: message.error,
691
+ durationMs: message.durationMs,
692
+ memoryUsedBytes: message.memoryUsedBytes
693
+ });
694
+ }
695
+ worker.terminate().catch(() => {
696
+ });
697
+ });
698
+ worker.on("error", (error) => {
699
+ const durationMs = performance.now() - startTime;
700
+ settle({
701
+ success: false,
702
+ output: void 0,
703
+ error: error.message || "Worker error",
704
+ durationMs,
705
+ memoryUsedBytes: 0
706
+ });
707
+ });
708
+ worker.on("exit", (exitCode) => {
709
+ if (exitCode !== 0) {
710
+ const durationMs = performance.now() - startTime;
711
+ settle({
712
+ success: false,
713
+ output: void 0,
714
+ error: `Worker exited with code ${exitCode} (possible memory limit exceeded)`,
715
+ durationMs,
716
+ memoryUsedBytes: 0
717
+ });
718
+ }
719
+ this.worker = null;
720
+ });
721
+ } catch (err) {
722
+ const durationMs = performance.now() - startTime;
723
+ const errorMessage = err instanceof Error ? err.message : String(err);
724
+ settle({
725
+ success: false,
726
+ output: void 0,
727
+ error: `Failed to spawn worker: ${errorMessage}`,
728
+ durationMs,
729
+ memoryUsedBytes: 0
730
+ });
731
+ }
732
+ });
733
+ }
734
+ /**
735
+ * Gracefully shut down the sandbox.
736
+ * Terminates any running worker and prevents future executions.
737
+ */
738
+ async shutdown() {
739
+ this.isShutdown = true;
740
+ if (this.worker) {
741
+ await this.worker.terminate();
742
+ this.worker = null;
743
+ }
744
+ }
745
+ /**
746
+ * Check whether the sandbox has been shut down.
747
+ */
748
+ get terminated() {
749
+ return this.isShutdown;
750
+ }
751
+ };
752
+
476
753
  // src/index.ts
477
754
  var import_zod2 = require("zod");
478
755
  // Annotate the CommonJS export names for ESM import in node:
@@ -486,6 +763,8 @@ var import_zod2 = require("zod");
486
763
  TrustStatusSchema,
487
764
  TrustTier,
488
765
  WebhookRouter,
766
+ WorkerSandbox,
767
+ createProofBridge,
489
768
  parseWebhookPayload,
490
769
  verifyWebhookSignature,
491
770
  z