@probelabs/visor 0.1.130-ee → 0.1.130

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 (27) hide show
  1. package/dist/index.js +22 -1719
  2. package/dist/output/traces/run-2026-02-11T16-20-59-999Z.ndjson +138 -0
  3. package/dist/output/traces/run-2026-02-11T16-21-47-711Z.ndjson +1357 -0
  4. package/dist/sdk/{check-provider-registry-S7DKTEM6.mjs → check-provider-registry-M3Y6JMTW.mjs} +3 -3
  5. package/dist/sdk/{chunk-TQ4D3YOF.mjs → chunk-EUUAQBTW.mjs} +10 -10
  6. package/dist/sdk/{chunk-TQ4D3YOF.mjs.map → chunk-EUUAQBTW.mjs.map} +1 -1
  7. package/dist/sdk/{schedule-tool-handler-EBNKDUJC.mjs → schedule-tool-handler-IEB2VS7O.mjs} +3 -3
  8. package/dist/sdk/sdk.js +273 -1531
  9. package/dist/sdk/sdk.js.map +1 -1
  10. package/dist/sdk/sdk.mjs +2 -2
  11. package/dist/sdk/{workflow-check-provider-E7YPEZ45.mjs → workflow-check-provider-2ET3SFZH.mjs} +3 -3
  12. package/dist/traces/run-2026-02-11T16-20-59-999Z.ndjson +138 -0
  13. package/dist/traces/run-2026-02-11T16-21-47-711Z.ndjson +1357 -0
  14. package/package.json +1 -1
  15. package/dist/sdk/host-OUSD2OIQ.mjs +0 -63
  16. package/dist/sdk/host-OUSD2OIQ.mjs.map +0 -1
  17. package/dist/sdk/knex-store-HPXJILBL.mjs +0 -411
  18. package/dist/sdk/knex-store-HPXJILBL.mjs.map +0 -1
  19. package/dist/sdk/loader-ID5LMXOW.mjs +0 -89
  20. package/dist/sdk/loader-ID5LMXOW.mjs.map +0 -1
  21. package/dist/sdk/opa-policy-engine-UUPFN5CL.mjs +0 -655
  22. package/dist/sdk/opa-policy-engine-UUPFN5CL.mjs.map +0 -1
  23. package/dist/sdk/validator-XTZJZZJH.mjs +0 -134
  24. package/dist/sdk/validator-XTZJZZJH.mjs.map +0 -1
  25. /package/dist/sdk/{check-provider-registry-S7DKTEM6.mjs.map → check-provider-registry-M3Y6JMTW.mjs.map} +0 -0
  26. /package/dist/sdk/{schedule-tool-handler-EBNKDUJC.mjs.map → schedule-tool-handler-IEB2VS7O.mjs.map} +0 -0
  27. /package/dist/sdk/{workflow-check-provider-E7YPEZ45.mjs.map → workflow-check-provider-2ET3SFZH.mjs.map} +0 -0
package/dist/index.js CHANGED
@@ -148954,7 +148954,7 @@ async function handleDumpPolicyInput(checkId, argv) {
148954
148954
  let PolicyInputBuilder;
148955
148955
  try {
148956
148956
  // @ts-ignore — enterprise/ may not exist in OSS builds (caught at runtime)
148957
- const mod = await Promise.resolve().then(() => __importStar(__nccwpck_require__(17117)));
148957
+ const mod = await Promise.resolve().then(() => __importStar(__nccwpck_require__(71370)));
148958
148958
  PolicyInputBuilder = mod.PolicyInputBuilder;
148959
148959
  }
148960
148960
  catch {
@@ -153795,1690 +153795,6 @@ class DependencyResolver {
153795
153795
  exports.DependencyResolver = DependencyResolver;
153796
153796
 
153797
153797
 
153798
- /***/ }),
153799
-
153800
- /***/ 50069:
153801
- /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
153802
-
153803
- "use strict";
153804
-
153805
- /**
153806
- * Copyright (c) ProbeLabs. All rights reserved.
153807
- * Licensed under the Elastic License 2.0; you may not use this file except
153808
- * in compliance with the Elastic License 2.0.
153809
- */
153810
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
153811
- if (k2 === undefined) k2 = k;
153812
- var desc = Object.getOwnPropertyDescriptor(m, k);
153813
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
153814
- desc = { enumerable: true, get: function() { return m[k]; } };
153815
- }
153816
- Object.defineProperty(o, k2, desc);
153817
- }) : (function(o, m, k, k2) {
153818
- if (k2 === undefined) k2 = k;
153819
- o[k2] = m[k];
153820
- }));
153821
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
153822
- Object.defineProperty(o, "default", { enumerable: true, value: v });
153823
- }) : function(o, v) {
153824
- o["default"] = v;
153825
- });
153826
- var __importStar = (this && this.__importStar) || (function () {
153827
- var ownKeys = function(o) {
153828
- ownKeys = Object.getOwnPropertyNames || function (o) {
153829
- var ar = [];
153830
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
153831
- return ar;
153832
- };
153833
- return ownKeys(o);
153834
- };
153835
- return function (mod) {
153836
- if (mod && mod.__esModule) return mod;
153837
- var result = {};
153838
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
153839
- __setModuleDefault(result, mod);
153840
- return result;
153841
- };
153842
- })();
153843
- Object.defineProperty(exports, "__esModule", ({ value: true }));
153844
- exports.LicenseValidator = void 0;
153845
- const crypto = __importStar(__nccwpck_require__(76982));
153846
- const fs = __importStar(__nccwpck_require__(79896));
153847
- const path = __importStar(__nccwpck_require__(16928));
153848
- class LicenseValidator {
153849
- /** Ed25519 public key for license verification (PEM format). */
153850
- static PUBLIC_KEY = '-----BEGIN PUBLIC KEY-----\n' +
153851
- 'MCowBQYDK2VwAyEAI/Zd08EFmgIdrDm/HXd0l3/5GBt7R1PrdvhdmEXhJlU=\n' +
153852
- '-----END PUBLIC KEY-----\n';
153853
- cache = null;
153854
- static CACHE_TTL = 5 * 60 * 1000; // 5 minutes
153855
- static GRACE_PERIOD = 72 * 3600 * 1000; // 72 hours after expiry
153856
- /**
153857
- * Load and validate license from environment or file.
153858
- *
153859
- * Resolution order:
153860
- * 1. VISOR_LICENSE env var (JWT string)
153861
- * 2. VISOR_LICENSE_FILE env var (path to file)
153862
- * 3. .visor-license in project root (cwd)
153863
- * 4. .visor-license in ~/.config/visor/
153864
- */
153865
- async loadAndValidate() {
153866
- // Return cached result if still fresh
153867
- if (this.cache && Date.now() - this.cache.validatedAt < LicenseValidator.CACHE_TTL) {
153868
- return this.cache.payload;
153869
- }
153870
- const token = this.resolveToken();
153871
- if (!token)
153872
- return null;
153873
- const payload = this.verifyAndDecode(token);
153874
- if (!payload)
153875
- return null;
153876
- this.cache = { payload, validatedAt: Date.now() };
153877
- return payload;
153878
- }
153879
- /** Check if a specific feature is licensed */
153880
- hasFeature(feature) {
153881
- if (!this.cache)
153882
- return false;
153883
- return this.cache.payload.features.includes(feature);
153884
- }
153885
- /** Check if license is valid (with grace period) */
153886
- isValid() {
153887
- if (!this.cache)
153888
- return false;
153889
- const now = Date.now();
153890
- const expiryMs = this.cache.payload.exp * 1000;
153891
- return now < expiryMs + LicenseValidator.GRACE_PERIOD;
153892
- }
153893
- /** Check if the license is within its grace period (expired but still valid) */
153894
- isInGracePeriod() {
153895
- if (!this.cache)
153896
- return false;
153897
- const now = Date.now();
153898
- const expiryMs = this.cache.payload.exp * 1000;
153899
- return now >= expiryMs && now < expiryMs + LicenseValidator.GRACE_PERIOD;
153900
- }
153901
- resolveToken() {
153902
- // 1. Direct env var
153903
- if (process.env.VISOR_LICENSE) {
153904
- return process.env.VISOR_LICENSE.trim();
153905
- }
153906
- // 2. File path from env (validate against path traversal)
153907
- if (process.env.VISOR_LICENSE_FILE) {
153908
- // path.resolve() produces an absolute path with all '..' segments resolved,
153909
- // so a separate resolved.includes('..') check is unnecessary.
153910
- const resolved = path.resolve(process.env.VISOR_LICENSE_FILE);
153911
- const home = process.env.HOME || process.env.USERPROFILE || '';
153912
- const allowedPrefixes = [path.normalize(process.cwd())];
153913
- if (home)
153914
- allowedPrefixes.push(path.normalize(path.join(home, '.config', 'visor')));
153915
- // Resolve symlinks so an attacker cannot create a symlink inside an
153916
- // allowed prefix that points to an arbitrary file outside it.
153917
- let realPath;
153918
- try {
153919
- realPath = fs.realpathSync(resolved);
153920
- }
153921
- catch {
153922
- return null; // File doesn't exist or isn't accessible
153923
- }
153924
- const isSafe = allowedPrefixes.some(prefix => realPath === prefix || realPath.startsWith(prefix + path.sep));
153925
- if (!isSafe)
153926
- return null;
153927
- return this.readFile(realPath);
153928
- }
153929
- // 3. .visor-license in cwd
153930
- const cwdPath = path.join(process.cwd(), '.visor-license');
153931
- const cwdToken = this.readFile(cwdPath);
153932
- if (cwdToken)
153933
- return cwdToken;
153934
- // 4. ~/.config/visor/.visor-license
153935
- const home = process.env.HOME || process.env.USERPROFILE || '';
153936
- if (home) {
153937
- const configPath = path.join(home, '.config', 'visor', '.visor-license');
153938
- const configToken = this.readFile(configPath);
153939
- if (configToken)
153940
- return configToken;
153941
- }
153942
- return null;
153943
- }
153944
- readFile(filePath) {
153945
- try {
153946
- return fs.readFileSync(filePath, 'utf-8').trim();
153947
- }
153948
- catch {
153949
- return null;
153950
- }
153951
- }
153952
- verifyAndDecode(token) {
153953
- try {
153954
- const parts = token.split('.');
153955
- if (parts.length !== 3)
153956
- return null;
153957
- const [headerB64, payloadB64, signatureB64] = parts;
153958
- // Decode header to verify algorithm
153959
- const header = JSON.parse(Buffer.from(headerB64, 'base64url').toString());
153960
- if (header.alg !== 'EdDSA')
153961
- return null;
153962
- // Verify signature
153963
- const data = `${headerB64}.${payloadB64}`;
153964
- const signature = Buffer.from(signatureB64, 'base64url');
153965
- const publicKey = crypto.createPublicKey(LicenseValidator.PUBLIC_KEY);
153966
- // Validate that the loaded public key is actually Ed25519 (OID 1.3.101.112).
153967
- // This prevents algorithm-confusion attacks if the embedded key were ever
153968
- // swapped to a different type.
153969
- if (publicKey.asymmetricKeyType !== 'ed25519') {
153970
- return null;
153971
- }
153972
- // Ed25519 verification: algorithm must be null because EdDSA performs its
153973
- // own internal hashing (SHA-512) — passing a digest algorithm here would
153974
- // cause Node.js to throw. The key type is validated above.
153975
- const isValid = crypto.verify(null, Buffer.from(data), publicKey, signature);
153976
- if (!isValid)
153977
- return null;
153978
- // Decode payload
153979
- const payload = JSON.parse(Buffer.from(payloadB64, 'base64url').toString());
153980
- // Validate required fields
153981
- if (!payload.org ||
153982
- !Array.isArray(payload.features) ||
153983
- typeof payload.exp !== 'number' ||
153984
- typeof payload.iat !== 'number' ||
153985
- !payload.sub) {
153986
- return null;
153987
- }
153988
- // Check expiry (with grace period)
153989
- const now = Date.now();
153990
- const expiryMs = payload.exp * 1000;
153991
- if (now >= expiryMs + LicenseValidator.GRACE_PERIOD) {
153992
- return null;
153993
- }
153994
- return payload;
153995
- }
153996
- catch {
153997
- return null;
153998
- }
153999
- }
154000
- }
154001
- exports.LicenseValidator = LicenseValidator;
154002
-
154003
-
154004
- /***/ }),
154005
-
154006
- /***/ 87068:
154007
- /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
154008
-
154009
- "use strict";
154010
-
154011
- /**
154012
- * Copyright (c) ProbeLabs. All rights reserved.
154013
- * Licensed under the Elastic License 2.0; you may not use this file except
154014
- * in compliance with the Elastic License 2.0.
154015
- */
154016
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
154017
- if (k2 === undefined) k2 = k;
154018
- var desc = Object.getOwnPropertyDescriptor(m, k);
154019
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
154020
- desc = { enumerable: true, get: function() { return m[k]; } };
154021
- }
154022
- Object.defineProperty(o, k2, desc);
154023
- }) : (function(o, m, k, k2) {
154024
- if (k2 === undefined) k2 = k;
154025
- o[k2] = m[k];
154026
- }));
154027
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
154028
- Object.defineProperty(o, "default", { enumerable: true, value: v });
154029
- }) : function(o, v) {
154030
- o["default"] = v;
154031
- });
154032
- var __importStar = (this && this.__importStar) || (function () {
154033
- var ownKeys = function(o) {
154034
- ownKeys = Object.getOwnPropertyNames || function (o) {
154035
- var ar = [];
154036
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
154037
- return ar;
154038
- };
154039
- return ownKeys(o);
154040
- };
154041
- return function (mod) {
154042
- if (mod && mod.__esModule) return mod;
154043
- var result = {};
154044
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
154045
- __setModuleDefault(result, mod);
154046
- return result;
154047
- };
154048
- })();
154049
- Object.defineProperty(exports, "__esModule", ({ value: true }));
154050
- exports.loadEnterprisePolicyEngine = loadEnterprisePolicyEngine;
154051
- exports.loadEnterpriseStoreBackend = loadEnterpriseStoreBackend;
154052
- const default_engine_1 = __nccwpck_require__(93866);
154053
- /**
154054
- * Load the enterprise policy engine if licensed, otherwise return the default no-op engine.
154055
- *
154056
- * This is the sole import boundary between OSS and enterprise code. Core code
154057
- * must only import from this module (via dynamic `await import()`), never from
154058
- * individual enterprise submodules.
154059
- */
154060
- async function loadEnterprisePolicyEngine(config) {
154061
- try {
154062
- const { LicenseValidator } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(50069)));
154063
- const validator = new LicenseValidator();
154064
- const license = await validator.loadAndValidate();
154065
- if (!license || !validator.hasFeature('policy')) {
154066
- return new default_engine_1.DefaultPolicyEngine();
154067
- }
154068
- if (validator.isInGracePeriod()) {
154069
- // eslint-disable-next-line no-console
154070
- console.warn('[visor:enterprise] License has expired but is within the 72-hour grace period. ' +
154071
- 'Please renew your license.');
154072
- }
154073
- const { OpaPolicyEngine } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(39530)));
154074
- const engine = new OpaPolicyEngine(config);
154075
- await engine.initialize(config);
154076
- return engine;
154077
- }
154078
- catch (err) {
154079
- // Enterprise code not available or initialization failed
154080
- const msg = err instanceof Error ? err.message : String(err);
154081
- try {
154082
- const { logger } = __nccwpck_require__(86999);
154083
- logger.warn(`[PolicyEngine] Enterprise policy init failed, falling back to default: ${msg}`);
154084
- }
154085
- catch {
154086
- // silent
154087
- }
154088
- return new default_engine_1.DefaultPolicyEngine();
154089
- }
154090
- }
154091
- /**
154092
- * Load the enterprise schedule store backend if licensed.
154093
- *
154094
- * @param driver Database driver ('postgresql', 'mysql', or 'mssql')
154095
- * @param storageConfig Storage configuration with connection details
154096
- * @param haConfig Optional HA configuration
154097
- * @throws Error if enterprise license is not available or missing 'scheduler-sql' feature
154098
- */
154099
- async function loadEnterpriseStoreBackend(driver, storageConfig, haConfig) {
154100
- const { LicenseValidator } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(50069)));
154101
- const validator = new LicenseValidator();
154102
- const license = await validator.loadAndValidate();
154103
- if (!license || !validator.hasFeature('scheduler-sql')) {
154104
- throw new Error(`The ${driver} schedule storage driver requires a Visor Enterprise license ` +
154105
- `with the 'scheduler-sql' feature. Please upgrade or use driver: 'sqlite' (default).`);
154106
- }
154107
- if (validator.isInGracePeriod()) {
154108
- // eslint-disable-next-line no-console
154109
- console.warn('[visor:enterprise] License has expired but is within the 72-hour grace period. ' +
154110
- 'Please renew your license.');
154111
- }
154112
- const { KnexStoreBackend } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(63737)));
154113
- return new KnexStoreBackend(driver, storageConfig, haConfig);
154114
- }
154115
-
154116
-
154117
- /***/ }),
154118
-
154119
- /***/ 628:
154120
- /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
154121
-
154122
- "use strict";
154123
-
154124
- /**
154125
- * Copyright (c) ProbeLabs. All rights reserved.
154126
- * Licensed under the Elastic License 2.0; you may not use this file except
154127
- * in compliance with the Elastic License 2.0.
154128
- */
154129
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
154130
- if (k2 === undefined) k2 = k;
154131
- var desc = Object.getOwnPropertyDescriptor(m, k);
154132
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
154133
- desc = { enumerable: true, get: function() { return m[k]; } };
154134
- }
154135
- Object.defineProperty(o, k2, desc);
154136
- }) : (function(o, m, k, k2) {
154137
- if (k2 === undefined) k2 = k;
154138
- o[k2] = m[k];
154139
- }));
154140
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
154141
- Object.defineProperty(o, "default", { enumerable: true, value: v });
154142
- }) : function(o, v) {
154143
- o["default"] = v;
154144
- });
154145
- var __importStar = (this && this.__importStar) || (function () {
154146
- var ownKeys = function(o) {
154147
- ownKeys = Object.getOwnPropertyNames || function (o) {
154148
- var ar = [];
154149
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
154150
- return ar;
154151
- };
154152
- return ownKeys(o);
154153
- };
154154
- return function (mod) {
154155
- if (mod && mod.__esModule) return mod;
154156
- var result = {};
154157
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
154158
- __setModuleDefault(result, mod);
154159
- return result;
154160
- };
154161
- })();
154162
- Object.defineProperty(exports, "__esModule", ({ value: true }));
154163
- exports.OpaCompiler = void 0;
154164
- const fs = __importStar(__nccwpck_require__(79896));
154165
- const path = __importStar(__nccwpck_require__(16928));
154166
- const os = __importStar(__nccwpck_require__(70857));
154167
- const crypto = __importStar(__nccwpck_require__(76982));
154168
- const child_process_1 = __nccwpck_require__(35317);
154169
- /**
154170
- * OPA Rego Compiler - compiles .rego policy files to WASM bundles using the `opa` CLI.
154171
- *
154172
- * Handles:
154173
- * - Resolving input paths to WASM bytes (direct .wasm, directory with policy.wasm, or .rego files)
154174
- * - Compiling .rego files to WASM via `opa build`
154175
- * - Caching compiled bundles based on content hashes
154176
- * - Extracting policy.wasm from OPA tar.gz bundles
154177
- *
154178
- * Requires:
154179
- * - `opa` CLI on PATH (only when auto-compiling .rego files)
154180
- */
154181
- class OpaCompiler {
154182
- static CACHE_DIR = path.join(os.tmpdir(), 'visor-opa-cache');
154183
- /**
154184
- * Resolve the input paths to WASM bytes.
154185
- *
154186
- * Strategy:
154187
- * 1. If any path is a .wasm file, read it directly
154188
- * 2. If a directory contains policy.wasm, read it
154189
- * 3. Otherwise, collect all .rego files and auto-compile via `opa build`
154190
- */
154191
- async resolveWasmBytes(paths) {
154192
- // Collect .rego files and check for existing .wasm
154193
- const regoFiles = [];
154194
- for (const p of paths) {
154195
- const resolved = path.resolve(p);
154196
- // Reject paths containing '..' after resolution (path traversal)
154197
- if (path.normalize(resolved).includes('..')) {
154198
- throw new Error(`Policy path contains traversal sequences: ${p}`);
154199
- }
154200
- // Direct .wasm file
154201
- if (resolved.endsWith('.wasm') && fs.existsSync(resolved)) {
154202
- return fs.readFileSync(resolved);
154203
- }
154204
- if (!fs.existsSync(resolved))
154205
- continue;
154206
- const stat = fs.statSync(resolved);
154207
- if (stat.isDirectory()) {
154208
- // Check for pre-compiled policy.wasm in directory
154209
- const wasmCandidate = path.join(resolved, 'policy.wasm');
154210
- if (fs.existsSync(wasmCandidate)) {
154211
- return fs.readFileSync(wasmCandidate);
154212
- }
154213
- // Collect all .rego files from directory
154214
- const files = fs.readdirSync(resolved);
154215
- for (const f of files) {
154216
- if (f.endsWith('.rego')) {
154217
- regoFiles.push(path.join(resolved, f));
154218
- }
154219
- }
154220
- }
154221
- else if (resolved.endsWith('.rego')) {
154222
- regoFiles.push(resolved);
154223
- }
154224
- }
154225
- if (regoFiles.length === 0) {
154226
- throw new Error(`OPA WASM evaluator: no .wasm bundle or .rego files found in: ${paths.join(', ')}`);
154227
- }
154228
- // Auto-compile .rego -> .wasm
154229
- return this.compileRego(regoFiles);
154230
- }
154231
- /**
154232
- * Auto-compile .rego files to a WASM bundle using the `opa` CLI.
154233
- *
154234
- * Caches the compiled bundle based on a content hash of all input .rego files
154235
- * so subsequent runs skip compilation if policies haven't changed.
154236
- */
154237
- compileRego(regoFiles) {
154238
- // Check that `opa` CLI is available
154239
- try {
154240
- (0, child_process_1.execFileSync)('opa', ['version'], { stdio: 'pipe' });
154241
- }
154242
- catch {
154243
- throw new Error('OPA CLI (`opa`) not found on PATH. Install it from https://www.openpolicyagent.org/docs/latest/#running-opa\n' +
154244
- 'Or pre-compile your .rego files: opa build -t wasm -e visor -o bundle.tar.gz ' +
154245
- regoFiles.join(' '));
154246
- }
154247
- // Compute content hash for cache key
154248
- const hash = crypto.createHash('sha256');
154249
- for (const f of regoFiles.sort()) {
154250
- hash.update(fs.readFileSync(f));
154251
- hash.update(f); // include filename for disambiguation
154252
- }
154253
- const cacheKey = hash.digest('hex').slice(0, 16);
154254
- const cacheDir = OpaCompiler.CACHE_DIR;
154255
- const cachedWasm = path.join(cacheDir, `${cacheKey}.wasm`);
154256
- // Return cached bundle if still valid
154257
- if (fs.existsSync(cachedWasm)) {
154258
- return fs.readFileSync(cachedWasm);
154259
- }
154260
- // Compile to WASM via opa build
154261
- fs.mkdirSync(cacheDir, { recursive: true });
154262
- const bundleTar = path.join(cacheDir, `${cacheKey}-bundle.tar.gz`);
154263
- try {
154264
- const args = [
154265
- 'build',
154266
- '-t',
154267
- 'wasm',
154268
- '-e',
154269
- 'visor', // entrypoint: the visor package tree
154270
- '-o',
154271
- bundleTar,
154272
- ...regoFiles,
154273
- ];
154274
- (0, child_process_1.execFileSync)('opa', args, {
154275
- stdio: 'pipe',
154276
- timeout: 30000,
154277
- });
154278
- }
154279
- catch (err) {
154280
- const stderr = err?.stderr?.toString() || '';
154281
- throw new Error(`Failed to compile .rego files to WASM:\n${stderr}\n` +
154282
- 'Ensure your .rego files are valid and the `opa` CLI is installed.');
154283
- }
154284
- // Extract policy.wasm from the tar.gz bundle
154285
- // OPA bundles are tar.gz with /policy.wasm inside
154286
- try {
154287
- (0, child_process_1.execFileSync)('tar', ['-xzf', bundleTar, '-C', cacheDir, '/policy.wasm'], {
154288
- stdio: 'pipe',
154289
- });
154290
- const extractedWasm = path.join(cacheDir, 'policy.wasm');
154291
- if (fs.existsSync(extractedWasm)) {
154292
- // Move to cache-key named file
154293
- fs.renameSync(extractedWasm, cachedWasm);
154294
- }
154295
- }
154296
- catch {
154297
- // Some tar implementations don't like leading /
154298
- try {
154299
- (0, child_process_1.execFileSync)('tar', ['-xzf', bundleTar, '-C', cacheDir, 'policy.wasm'], {
154300
- stdio: 'pipe',
154301
- });
154302
- const extractedWasm = path.join(cacheDir, 'policy.wasm');
154303
- if (fs.existsSync(extractedWasm)) {
154304
- fs.renameSync(extractedWasm, cachedWasm);
154305
- }
154306
- }
154307
- catch (err2) {
154308
- throw new Error(`Failed to extract policy.wasm from OPA bundle: ${err2?.message || err2}`);
154309
- }
154310
- }
154311
- // Clean up tar
154312
- try {
154313
- fs.unlinkSync(bundleTar);
154314
- }
154315
- catch { }
154316
- if (!fs.existsSync(cachedWasm)) {
154317
- throw new Error('OPA build succeeded but policy.wasm was not found in the bundle');
154318
- }
154319
- return fs.readFileSync(cachedWasm);
154320
- }
154321
- }
154322
- exports.OpaCompiler = OpaCompiler;
154323
-
154324
-
154325
- /***/ }),
154326
-
154327
- /***/ 44693:
154328
- /***/ ((__unused_webpack_module, exports) => {
154329
-
154330
- "use strict";
154331
-
154332
- /**
154333
- * Copyright (c) ProbeLabs. All rights reserved.
154334
- * Licensed under the Elastic License 2.0; you may not use this file except
154335
- * in compliance with the Elastic License 2.0.
154336
- */
154337
- Object.defineProperty(exports, "__esModule", ({ value: true }));
154338
- exports.OpaHttpEvaluator = void 0;
154339
- /**
154340
- * OPA HTTP Evaluator - evaluates policies via an external OPA server's REST API.
154341
- *
154342
- * Uses the built-in `fetch` API (Node 18+), so no extra dependencies are needed.
154343
- */
154344
- class OpaHttpEvaluator {
154345
- baseUrl;
154346
- timeout;
154347
- constructor(baseUrl, timeout = 5000) {
154348
- // Validate URL format and protocol
154349
- let parsed;
154350
- try {
154351
- parsed = new URL(baseUrl);
154352
- }
154353
- catch {
154354
- throw new Error(`OPA HTTP evaluator: invalid URL: ${baseUrl}`);
154355
- }
154356
- if (!['http:', 'https:'].includes(parsed.protocol)) {
154357
- throw new Error(`OPA HTTP evaluator: url must use http:// or https:// protocol, got: ${baseUrl}`);
154358
- }
154359
- // Block cloud metadata, loopback, link-local, and private network addresses
154360
- const hostname = parsed.hostname;
154361
- if (this.isBlockedHostname(hostname)) {
154362
- throw new Error(`OPA HTTP evaluator: url must not point to internal, loopback, or private network addresses`);
154363
- }
154364
- // Normalize: strip trailing slash
154365
- this.baseUrl = baseUrl.replace(/\/+$/, '');
154366
- this.timeout = timeout;
154367
- }
154368
- /**
154369
- * Check if a hostname is blocked due to SSRF concerns.
154370
- *
154371
- * Blocks:
154372
- * - Loopback addresses (127.x.x.x, localhost, 0.0.0.0, ::1)
154373
- * - Link-local addresses (169.254.x.x)
154374
- * - Private networks (10.x.x.x, 172.16-31.x.x, 192.168.x.x)
154375
- * - IPv6 unique local addresses (fd00::/8)
154376
- * - Cloud metadata services (*.internal)
154377
- */
154378
- isBlockedHostname(hostname) {
154379
- if (!hostname)
154380
- return true; // block empty hostnames
154381
- // Normalize hostname: lowercase and remove brackets for IPv6
154382
- const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, '');
154383
- // Block .internal domains (cloud metadata services)
154384
- if (normalized === 'metadata.google.internal' || normalized.endsWith('.internal')) {
154385
- return true;
154386
- }
154387
- // Block localhost variants
154388
- if (normalized === 'localhost' || normalized === 'localhost.localdomain') {
154389
- return true;
154390
- }
154391
- // Block IPv6 loopback
154392
- if (normalized === '::1' || normalized === '0:0:0:0:0:0:0:1') {
154393
- return true;
154394
- }
154395
- // Check IPv4 patterns
154396
- const ipv4Pattern = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
154397
- const ipv4Match = normalized.match(ipv4Pattern);
154398
- if (ipv4Match) {
154399
- const octets = ipv4Match.slice(1, 5).map(Number);
154400
- // Validate octets are in range [0, 255]
154401
- if (octets.some(octet => octet > 255)) {
154402
- return false;
154403
- }
154404
- const [a, b] = octets;
154405
- // Block loopback: 127.0.0.0/8
154406
- if (a === 127) {
154407
- return true;
154408
- }
154409
- // Block 0.0.0.0/8 (this host)
154410
- if (a === 0) {
154411
- return true;
154412
- }
154413
- // Block link-local: 169.254.0.0/16
154414
- if (a === 169 && b === 254) {
154415
- return true;
154416
- }
154417
- // Block private networks
154418
- // 10.0.0.0/8
154419
- if (a === 10) {
154420
- return true;
154421
- }
154422
- // 172.16.0.0/12 (172.16.x.x through 172.31.x.x)
154423
- if (a === 172 && b >= 16 && b <= 31) {
154424
- return true;
154425
- }
154426
- // 192.168.0.0/16
154427
- if (a === 192 && b === 168) {
154428
- return true;
154429
- }
154430
- }
154431
- // Check IPv6 patterns
154432
- // Block unique local addresses: fd00::/8
154433
- if (normalized.startsWith('fd') || normalized.startsWith('fc')) {
154434
- return true;
154435
- }
154436
- // Block link-local: fe80::/10
154437
- if (normalized.startsWith('fe80:')) {
154438
- return true;
154439
- }
154440
- return false;
154441
- }
154442
- /**
154443
- * Evaluate a policy rule against an input document via OPA REST API.
154444
- *
154445
- * @param input - The input document to evaluate
154446
- * @param rulePath - OPA rule path (e.g., 'visor/check/execute')
154447
- * @returns The result object from OPA, or undefined on error
154448
- */
154449
- async evaluate(input, rulePath) {
154450
- // OPA Data API: POST /v1/data/<path>
154451
- const encodedPath = rulePath
154452
- .split('/')
154453
- .map(s => encodeURIComponent(s))
154454
- .join('/');
154455
- const url = `${this.baseUrl}/v1/data/${encodedPath}`;
154456
- const controller = new AbortController();
154457
- const timer = setTimeout(() => controller.abort(), this.timeout);
154458
- try {
154459
- const response = await fetch(url, {
154460
- method: 'POST',
154461
- headers: { 'Content-Type': 'application/json' },
154462
- body: JSON.stringify({ input }),
154463
- signal: controller.signal,
154464
- });
154465
- if (!response.ok) {
154466
- throw new Error(`OPA HTTP ${response.status}: ${response.statusText}`);
154467
- }
154468
- let body;
154469
- try {
154470
- body = await response.json();
154471
- }
154472
- catch (jsonErr) {
154473
- throw new Error(`OPA HTTP evaluator: failed to parse JSON response: ${jsonErr instanceof Error ? jsonErr.message : String(jsonErr)}`);
154474
- }
154475
- // OPA returns { result: { ... } }
154476
- return body?.result;
154477
- }
154478
- finally {
154479
- clearTimeout(timer);
154480
- }
154481
- }
154482
- async shutdown() {
154483
- // No persistent connections to close
154484
- }
154485
- }
154486
- exports.OpaHttpEvaluator = OpaHttpEvaluator;
154487
-
154488
-
154489
- /***/ }),
154490
-
154491
- /***/ 39530:
154492
- /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
154493
-
154494
- "use strict";
154495
-
154496
- /**
154497
- * Copyright (c) ProbeLabs. All rights reserved.
154498
- * Licensed under the Elastic License 2.0; you may not use this file except
154499
- * in compliance with the Elastic License 2.0.
154500
- */
154501
- Object.defineProperty(exports, "__esModule", ({ value: true }));
154502
- exports.OpaPolicyEngine = void 0;
154503
- const opa_wasm_evaluator_1 = __nccwpck_require__(8613);
154504
- const opa_http_evaluator_1 = __nccwpck_require__(44693);
154505
- const policy_input_builder_1 = __nccwpck_require__(17117);
154506
- /**
154507
- * Enterprise OPA Policy Engine.
154508
- *
154509
- * Wraps both WASM (local) and HTTP (remote) OPA evaluators behind the
154510
- * OSS PolicyEngine interface. All OPA input building and role resolution
154511
- * is handled internally — the OSS call sites pass only plain types.
154512
- */
154513
- class OpaPolicyEngine {
154514
- evaluator = null;
154515
- fallback;
154516
- timeout;
154517
- config;
154518
- inputBuilder = null;
154519
- logger = null;
154520
- constructor(config) {
154521
- this.config = config;
154522
- this.fallback = config.fallback || 'deny';
154523
- this.timeout = config.timeout || 5000;
154524
- }
154525
- async initialize(config) {
154526
- // Resolve logger once at initialization
154527
- try {
154528
- this.logger = (__nccwpck_require__(86999).logger);
154529
- }
154530
- catch {
154531
- // logger not available in this context
154532
- }
154533
- // Build actor/repo context from environment (available at engine init time)
154534
- const actor = {
154535
- authorAssociation: process.env.VISOR_AUTHOR_ASSOCIATION,
154536
- login: process.env.VISOR_AUTHOR_LOGIN || process.env.GITHUB_ACTOR,
154537
- isLocalMode: !process.env.GITHUB_ACTIONS,
154538
- };
154539
- const repo = {
154540
- owner: process.env.GITHUB_REPOSITORY_OWNER,
154541
- name: process.env.GITHUB_REPOSITORY?.split('/')[1],
154542
- branch: process.env.GITHUB_HEAD_REF,
154543
- baseBranch: process.env.GITHUB_BASE_REF,
154544
- event: process.env.GITHUB_EVENT_NAME,
154545
- };
154546
- const prNum = process.env.GITHUB_PR_NUMBER
154547
- ? parseInt(process.env.GITHUB_PR_NUMBER, 10)
154548
- : undefined;
154549
- const pullRequest = {
154550
- number: prNum !== undefined && Number.isFinite(prNum) ? prNum : undefined,
154551
- };
154552
- this.inputBuilder = new policy_input_builder_1.PolicyInputBuilder(config, actor, repo, pullRequest);
154553
- if (config.engine === 'local') {
154554
- if (!config.rules) {
154555
- throw new Error('OPA local mode requires `policy.rules` path to .wasm or .rego files');
154556
- }
154557
- const wasm = new opa_wasm_evaluator_1.OpaWasmEvaluator();
154558
- await wasm.initialize(config.rules);
154559
- if (config.data) {
154560
- wasm.loadData(config.data);
154561
- }
154562
- this.evaluator = wasm;
154563
- }
154564
- else if (config.engine === 'remote') {
154565
- if (!config.url) {
154566
- throw new Error('OPA remote mode requires `policy.url` pointing to OPA server');
154567
- }
154568
- this.evaluator = new opa_http_evaluator_1.OpaHttpEvaluator(config.url, this.timeout);
154569
- }
154570
- else {
154571
- this.evaluator = null;
154572
- }
154573
- }
154574
- /**
154575
- * Update actor/repo/PR context (e.g., after PR info becomes available).
154576
- * Called by the enterprise loader when engine context is enriched.
154577
- */
154578
- setActorContext(actor, repo, pullRequest) {
154579
- this.inputBuilder = new policy_input_builder_1.PolicyInputBuilder(this.config, actor, repo, pullRequest);
154580
- }
154581
- async evaluateCheckExecution(checkId, checkConfig) {
154582
- if (!this.evaluator || !this.inputBuilder)
154583
- return { allowed: true };
154584
- const cfg = checkConfig && typeof checkConfig === 'object'
154585
- ? checkConfig
154586
- : {};
154587
- const policyOverride = cfg.policy;
154588
- const input = this.inputBuilder.forCheckExecution({
154589
- id: checkId,
154590
- type: cfg.type || 'ai',
154591
- group: cfg.group,
154592
- tags: cfg.tags,
154593
- criticality: cfg.criticality,
154594
- sandbox: cfg.sandbox,
154595
- policy: policyOverride,
154596
- });
154597
- return this.doEvaluate(input, this.resolveRulePath('check.execute', policyOverride?.rule));
154598
- }
154599
- async evaluateToolInvocation(serverName, methodName, transport) {
154600
- if (!this.evaluator || !this.inputBuilder)
154601
- return { allowed: true };
154602
- const input = this.inputBuilder.forToolInvocation(serverName, methodName, transport);
154603
- return this.doEvaluate(input, 'visor/tool/invoke');
154604
- }
154605
- async evaluateCapabilities(checkId, capabilities) {
154606
- if (!this.evaluator || !this.inputBuilder)
154607
- return { allowed: true };
154608
- const input = this.inputBuilder.forCapabilityResolve(checkId, capabilities);
154609
- return this.doEvaluate(input, 'visor/capability/resolve');
154610
- }
154611
- async shutdown() {
154612
- if (this.evaluator && 'shutdown' in this.evaluator) {
154613
- await this.evaluator.shutdown();
154614
- }
154615
- this.evaluator = null;
154616
- this.inputBuilder = null;
154617
- }
154618
- resolveRulePath(defaultScope, override) {
154619
- if (override) {
154620
- return override.startsWith('visor/') ? override : `visor/${override}`;
154621
- }
154622
- return `visor/${defaultScope.replace(/\./g, '/')}`;
154623
- }
154624
- async doEvaluate(input, rulePath) {
154625
- try {
154626
- this.logger?.debug(`[PolicyEngine] Evaluating ${rulePath}`, JSON.stringify(input));
154627
- let timer;
154628
- const timeoutPromise = new Promise((_resolve, reject) => {
154629
- timer = setTimeout(() => reject(new Error('policy evaluation timeout')), this.timeout);
154630
- });
154631
- try {
154632
- const result = await Promise.race([this.rawEvaluate(input, rulePath), timeoutPromise]);
154633
- const decision = this.parseDecision(result);
154634
- // In warn mode, override denied decisions to allowed but flag as warn
154635
- if (!decision.allowed && this.fallback === 'warn') {
154636
- decision.allowed = true;
154637
- decision.warn = true;
154638
- decision.reason = `audit: ${decision.reason || 'policy denied'}`;
154639
- }
154640
- this.logger?.debug(`[PolicyEngine] Decision for ${rulePath}: allowed=${decision.allowed}, warn=${decision.warn || false}, reason=${decision.reason || 'none'}`);
154641
- return decision;
154642
- }
154643
- finally {
154644
- if (timer)
154645
- clearTimeout(timer);
154646
- }
154647
- }
154648
- catch (err) {
154649
- const msg = err instanceof Error ? err.message : String(err);
154650
- this.logger?.warn(`[PolicyEngine] Evaluation failed for ${rulePath}: ${msg}`);
154651
- return {
154652
- allowed: this.fallback === 'allow' || this.fallback === 'warn',
154653
- warn: this.fallback === 'warn' ? true : undefined,
154654
- reason: `policy evaluation failed, fallback=${this.fallback}`,
154655
- };
154656
- }
154657
- }
154658
- async rawEvaluate(input, rulePath) {
154659
- if (this.evaluator instanceof opa_wasm_evaluator_1.OpaWasmEvaluator) {
154660
- const result = await this.evaluator.evaluate(input);
154661
- // WASM compiled with `-e visor` entrypoint returns the full visor package tree.
154662
- // Navigate to the specific rule subtree using rulePath segments.
154663
- // e.g., 'visor/check/execute' → result.check.execute
154664
- return this.navigateWasmResult(result, rulePath);
154665
- }
154666
- return this.evaluator.evaluate(input, rulePath);
154667
- }
154668
- /**
154669
- * Navigate nested OPA WASM result tree to reach the specific rule's output.
154670
- * The WASM entrypoint `-e visor` means the result root IS the visor package,
154671
- * so we strip the `visor/` prefix and walk the remaining segments.
154672
- */
154673
- navigateWasmResult(result, rulePath) {
154674
- if (!result || typeof result !== 'object')
154675
- return result;
154676
- // Strip the 'visor/' prefix (matches our compilation entrypoint)
154677
- const segments = rulePath.replace(/^visor\//, '').split('/');
154678
- let current = result;
154679
- for (const seg of segments) {
154680
- if (current && typeof current === 'object' && seg in current) {
154681
- current = current[seg];
154682
- }
154683
- else {
154684
- return undefined; // path not found in result tree
154685
- }
154686
- }
154687
- return current;
154688
- }
154689
- parseDecision(result) {
154690
- if (result === undefined || result === null) {
154691
- return {
154692
- allowed: this.fallback === 'allow' || this.fallback === 'warn',
154693
- warn: this.fallback === 'warn' ? true : undefined,
154694
- reason: this.fallback === 'warn' ? 'audit: no policy result' : 'no policy result',
154695
- };
154696
- }
154697
- const allowed = result.allowed !== false;
154698
- const decision = {
154699
- allowed,
154700
- reason: result.reason,
154701
- };
154702
- if (result.capabilities) {
154703
- decision.capabilities = result.capabilities;
154704
- }
154705
- return decision;
154706
- }
154707
- }
154708
- exports.OpaPolicyEngine = OpaPolicyEngine;
154709
-
154710
-
154711
- /***/ }),
154712
-
154713
- /***/ 8613:
154714
- /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
154715
-
154716
- "use strict";
154717
-
154718
- /**
154719
- * Copyright (c) ProbeLabs. All rights reserved.
154720
- * Licensed under the Elastic License 2.0; you may not use this file except
154721
- * in compliance with the Elastic License 2.0.
154722
- */
154723
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
154724
- if (k2 === undefined) k2 = k;
154725
- var desc = Object.getOwnPropertyDescriptor(m, k);
154726
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
154727
- desc = { enumerable: true, get: function() { return m[k]; } };
154728
- }
154729
- Object.defineProperty(o, k2, desc);
154730
- }) : (function(o, m, k, k2) {
154731
- if (k2 === undefined) k2 = k;
154732
- o[k2] = m[k];
154733
- }));
154734
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
154735
- Object.defineProperty(o, "default", { enumerable: true, value: v });
154736
- }) : function(o, v) {
154737
- o["default"] = v;
154738
- });
154739
- var __importStar = (this && this.__importStar) || (function () {
154740
- var ownKeys = function(o) {
154741
- ownKeys = Object.getOwnPropertyNames || function (o) {
154742
- var ar = [];
154743
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
154744
- return ar;
154745
- };
154746
- return ownKeys(o);
154747
- };
154748
- return function (mod) {
154749
- if (mod && mod.__esModule) return mod;
154750
- var result = {};
154751
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
154752
- __setModuleDefault(result, mod);
154753
- return result;
154754
- };
154755
- })();
154756
- Object.defineProperty(exports, "__esModule", ({ value: true }));
154757
- exports.OpaWasmEvaluator = void 0;
154758
- const fs = __importStar(__nccwpck_require__(79896));
154759
- const path = __importStar(__nccwpck_require__(16928));
154760
- const opa_compiler_1 = __nccwpck_require__(628);
154761
- /**
154762
- * OPA WASM Evaluator - loads and evaluates OPA policies locally.
154763
- *
154764
- * Supports three input formats:
154765
- * 1. Pre-compiled `.wasm` bundle — loaded directly (fastest startup)
154766
- * 2. `.rego` files or directory — auto-compiled to WASM via `opa build` CLI
154767
- * 3. Directory with `policy.wasm` inside — loaded directly
154768
- *
154769
- * Compilation and caching of .rego files is delegated to {@link OpaCompiler}.
154770
- *
154771
- * Requires:
154772
- * - `@open-policy-agent/opa-wasm` npm package (optional dep)
154773
- * - `opa` CLI on PATH (only when auto-compiling .rego files)
154774
- */
154775
- class OpaWasmEvaluator {
154776
- policy = null;
154777
- dataDocument = {};
154778
- compiler = new opa_compiler_1.OpaCompiler();
154779
- async initialize(rulesPath) {
154780
- const paths = Array.isArray(rulesPath) ? rulesPath : [rulesPath];
154781
- const wasmBytes = await this.compiler.resolveWasmBytes(paths);
154782
- try {
154783
- // Use createRequire to load the optional dep at runtime without ncc bundling it.
154784
- // `new Function('id', 'return require(id)')` fails in ncc bundles because
154785
- // `require` is not in the `new Function` scope. `createRequire` works correctly
154786
- // because it creates a real Node.js require rooted at the given path.
154787
- // eslint-disable-next-line @typescript-eslint/no-var-requires
154788
- const { createRequire } = __nccwpck_require__(73339);
154789
- const runtimeRequire = createRequire(__filename);
154790
- const opaWasm = runtimeRequire('@open-policy-agent/opa-wasm');
154791
- const loadPolicy = opaWasm.loadPolicy || opaWasm.default?.loadPolicy;
154792
- if (!loadPolicy) {
154793
- throw new Error('loadPolicy not found in @open-policy-agent/opa-wasm');
154794
- }
154795
- this.policy = await loadPolicy(wasmBytes);
154796
- }
154797
- catch (err) {
154798
- if (err?.code === 'MODULE_NOT_FOUND' || err?.code === 'ERR_MODULE_NOT_FOUND') {
154799
- throw new Error('OPA WASM evaluator requires @open-policy-agent/opa-wasm. ' +
154800
- 'Install it with: npm install @open-policy-agent/opa-wasm');
154801
- }
154802
- throw err;
154803
- }
154804
- }
154805
- /**
154806
- * Load external data from a JSON file to use as the OPA data document.
154807
- * The loaded data will be passed to `policy.setData()` during evaluation,
154808
- * making it available in Rego via `data.<key>`.
154809
- */
154810
- loadData(dataPath) {
154811
- const resolved = path.resolve(dataPath);
154812
- if (path.normalize(resolved).includes('..')) {
154813
- throw new Error(`Data path contains traversal sequences: ${dataPath}`);
154814
- }
154815
- if (!fs.existsSync(resolved)) {
154816
- throw new Error(`OPA data file not found: ${resolved}`);
154817
- }
154818
- const stat = fs.statSync(resolved);
154819
- if (stat.size > 10 * 1024 * 1024) {
154820
- throw new Error(`OPA data file exceeds 10MB limit: ${resolved} (${stat.size} bytes)`);
154821
- }
154822
- const raw = fs.readFileSync(resolved, 'utf-8');
154823
- try {
154824
- const parsed = JSON.parse(raw);
154825
- if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
154826
- throw new Error('OPA data file must contain a JSON object (not an array or primitive)');
154827
- }
154828
- this.dataDocument = parsed;
154829
- }
154830
- catch (err) {
154831
- if (err.message.startsWith('OPA data file must')) {
154832
- throw err;
154833
- }
154834
- throw new Error(`Failed to parse OPA data file ${resolved}: ${err.message}`);
154835
- }
154836
- }
154837
- async evaluate(input) {
154838
- if (!this.policy) {
154839
- throw new Error('OPA WASM evaluator not initialized');
154840
- }
154841
- this.policy.setData(this.dataDocument);
154842
- const resultSet = this.policy.evaluate(input);
154843
- if (Array.isArray(resultSet) && resultSet.length > 0) {
154844
- return resultSet[0].result;
154845
- }
154846
- return undefined;
154847
- }
154848
- async shutdown() {
154849
- if (this.policy) {
154850
- // opa-wasm policy objects may have a close/free method for WASM cleanup
154851
- if (typeof this.policy.close === 'function') {
154852
- try {
154853
- this.policy.close();
154854
- }
154855
- catch { }
154856
- }
154857
- else if (typeof this.policy.free === 'function') {
154858
- try {
154859
- this.policy.free();
154860
- }
154861
- catch { }
154862
- }
154863
- }
154864
- this.policy = null;
154865
- }
154866
- }
154867
- exports.OpaWasmEvaluator = OpaWasmEvaluator;
154868
-
154869
-
154870
- /***/ }),
154871
-
154872
- /***/ 17117:
154873
- /***/ ((__unused_webpack_module, exports) => {
154874
-
154875
- "use strict";
154876
-
154877
- /**
154878
- * Copyright (c) ProbeLabs. All rights reserved.
154879
- * Licensed under the Elastic License 2.0; you may not use this file except
154880
- * in compliance with the Elastic License 2.0.
154881
- */
154882
- Object.defineProperty(exports, "__esModule", ({ value: true }));
154883
- exports.PolicyInputBuilder = void 0;
154884
- /**
154885
- * Builds OPA-compatible input documents from engine context.
154886
- *
154887
- * Resolves actor roles from the `policy.roles` config section by matching
154888
- * the actor's authorAssociation and login against role definitions.
154889
- */
154890
- class PolicyInputBuilder {
154891
- roles;
154892
- actor;
154893
- repository;
154894
- pullRequest;
154895
- constructor(policyConfig, actor, repository, pullRequest) {
154896
- this.roles = policyConfig.roles || {};
154897
- this.actor = actor;
154898
- this.repository = repository;
154899
- this.pullRequest = pullRequest;
154900
- }
154901
- /** Resolve which roles apply to the current actor. */
154902
- resolveRoles() {
154903
- const matched = [];
154904
- for (const [roleName, roleConfig] of Object.entries(this.roles)) {
154905
- let identityMatch = false;
154906
- if (roleConfig.author_association &&
154907
- this.actor.authorAssociation &&
154908
- roleConfig.author_association.includes(this.actor.authorAssociation)) {
154909
- identityMatch = true;
154910
- }
154911
- if (!identityMatch &&
154912
- roleConfig.users &&
154913
- this.actor.login &&
154914
- roleConfig.users.includes(this.actor.login)) {
154915
- identityMatch = true;
154916
- }
154917
- // Slack user ID match
154918
- if (!identityMatch &&
154919
- roleConfig.slack_users &&
154920
- this.actor.slack?.userId &&
154921
- roleConfig.slack_users.includes(this.actor.slack.userId)) {
154922
- identityMatch = true;
154923
- }
154924
- // Email match (case-insensitive)
154925
- if (!identityMatch && roleConfig.emails && this.actor.slack?.email) {
154926
- const actorEmail = this.actor.slack.email.toLowerCase();
154927
- if (roleConfig.emails.some(e => e.toLowerCase() === actorEmail)) {
154928
- identityMatch = true;
154929
- }
154930
- }
154931
- // Note: teams-based role resolution requires GitHub API access (read:org scope)
154932
- // and is not yet implemented. If configured, the role will not match via teams.
154933
- if (!identityMatch)
154934
- continue;
154935
- // slack_channels gate: if set, the role only applies when triggered from one of these channels
154936
- if (roleConfig.slack_channels && roleConfig.slack_channels.length > 0) {
154937
- if (!this.actor.slack?.channelId ||
154938
- !roleConfig.slack_channels.includes(this.actor.slack.channelId)) {
154939
- continue;
154940
- }
154941
- }
154942
- matched.push(roleName);
154943
- }
154944
- return matched;
154945
- }
154946
- buildActor() {
154947
- return {
154948
- authorAssociation: this.actor.authorAssociation,
154949
- login: this.actor.login,
154950
- roles: this.resolveRoles(),
154951
- isLocalMode: this.actor.isLocalMode,
154952
- ...(this.actor.slack && { slack: this.actor.slack }),
154953
- };
154954
- }
154955
- forCheckExecution(check) {
154956
- return {
154957
- scope: 'check.execute',
154958
- check: {
154959
- id: check.id,
154960
- type: check.type,
154961
- group: check.group,
154962
- tags: check.tags,
154963
- criticality: check.criticality,
154964
- sandbox: check.sandbox,
154965
- policy: check.policy,
154966
- },
154967
- actor: this.buildActor(),
154968
- repository: this.repository,
154969
- pullRequest: this.pullRequest,
154970
- };
154971
- }
154972
- forToolInvocation(serverName, methodName, transport) {
154973
- return {
154974
- scope: 'tool.invoke',
154975
- tool: { serverName, methodName, transport },
154976
- actor: this.buildActor(),
154977
- repository: this.repository,
154978
- pullRequest: this.pullRequest,
154979
- };
154980
- }
154981
- forCapabilityResolve(checkId, capabilities) {
154982
- return {
154983
- scope: 'capability.resolve',
154984
- check: { id: checkId, type: 'ai' },
154985
- capability: capabilities,
154986
- actor: this.buildActor(),
154987
- repository: this.repository,
154988
- pullRequest: this.pullRequest,
154989
- };
154990
- }
154991
- }
154992
- exports.PolicyInputBuilder = PolicyInputBuilder;
154993
-
154994
-
154995
- /***/ }),
154996
-
154997
- /***/ 63737:
154998
- /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
154999
-
155000
- "use strict";
155001
-
155002
- /**
155003
- * Copyright (c) ProbeLabs. All rights reserved.
155004
- * Licensed under the Elastic License 2.0; you may not use this file except
155005
- * in compliance with the Elastic License 2.0.
155006
- */
155007
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
155008
- if (k2 === undefined) k2 = k;
155009
- var desc = Object.getOwnPropertyDescriptor(m, k);
155010
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
155011
- desc = { enumerable: true, get: function() { return m[k]; } };
155012
- }
155013
- Object.defineProperty(o, k2, desc);
155014
- }) : (function(o, m, k, k2) {
155015
- if (k2 === undefined) k2 = k;
155016
- o[k2] = m[k];
155017
- }));
155018
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
155019
- Object.defineProperty(o, "default", { enumerable: true, value: v });
155020
- }) : function(o, v) {
155021
- o["default"] = v;
155022
- });
155023
- var __importStar = (this && this.__importStar) || (function () {
155024
- var ownKeys = function(o) {
155025
- ownKeys = Object.getOwnPropertyNames || function (o) {
155026
- var ar = [];
155027
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
155028
- return ar;
155029
- };
155030
- return ownKeys(o);
155031
- };
155032
- return function (mod) {
155033
- if (mod && mod.__esModule) return mod;
155034
- var result = {};
155035
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
155036
- __setModuleDefault(result, mod);
155037
- return result;
155038
- };
155039
- })();
155040
- Object.defineProperty(exports, "__esModule", ({ value: true }));
155041
- exports.KnexStoreBackend = void 0;
155042
- /**
155043
- * Knex-backed schedule store for PostgreSQL, MySQL, and MSSQL (Enterprise)
155044
- *
155045
- * Uses Knex query builder for database-agnostic SQL. Same schema as SQLite backend
155046
- * but with real distributed locking via row-level claims (claimed_by/claimed_at/lock_token).
155047
- */
155048
- const fs = __importStar(__nccwpck_require__(79896));
155049
- const path = __importStar(__nccwpck_require__(16928));
155050
- const uuid_1 = __nccwpck_require__(31914);
155051
- const logger_1 = __nccwpck_require__(86999);
155052
- function toNum(val) {
155053
- if (val === null || val === undefined)
155054
- return undefined;
155055
- return typeof val === 'string' ? parseInt(val, 10) : val;
155056
- }
155057
- function safeJsonParse(value) {
155058
- if (!value)
155059
- return undefined;
155060
- try {
155061
- return JSON.parse(value);
155062
- }
155063
- catch {
155064
- return undefined;
155065
- }
155066
- }
155067
- function fromDbRow(row) {
155068
- return {
155069
- id: row.id,
155070
- creatorId: row.creator_id,
155071
- creatorContext: row.creator_context ?? undefined,
155072
- creatorName: row.creator_name ?? undefined,
155073
- timezone: row.timezone,
155074
- schedule: row.schedule_expr,
155075
- runAt: toNum(row.run_at),
155076
- isRecurring: row.is_recurring === true || row.is_recurring === 1,
155077
- originalExpression: row.original_expression,
155078
- workflow: row.workflow ?? undefined,
155079
- workflowInputs: safeJsonParse(row.workflow_inputs),
155080
- outputContext: safeJsonParse(row.output_context),
155081
- status: row.status,
155082
- createdAt: toNum(row.created_at),
155083
- lastRunAt: toNum(row.last_run_at),
155084
- nextRunAt: toNum(row.next_run_at),
155085
- runCount: row.run_count,
155086
- failureCount: row.failure_count,
155087
- lastError: row.last_error ?? undefined,
155088
- previousResponse: row.previous_response ?? undefined,
155089
- };
155090
- }
155091
- function toInsertRow(schedule) {
155092
- return {
155093
- id: schedule.id,
155094
- creator_id: schedule.creatorId,
155095
- creator_context: schedule.creatorContext ?? null,
155096
- creator_name: schedule.creatorName ?? null,
155097
- timezone: schedule.timezone,
155098
- schedule_expr: schedule.schedule,
155099
- run_at: schedule.runAt ?? null,
155100
- is_recurring: schedule.isRecurring,
155101
- original_expression: schedule.originalExpression,
155102
- workflow: schedule.workflow ?? null,
155103
- workflow_inputs: schedule.workflowInputs ? JSON.stringify(schedule.workflowInputs) : null,
155104
- output_context: schedule.outputContext ? JSON.stringify(schedule.outputContext) : null,
155105
- status: schedule.status,
155106
- created_at: schedule.createdAt,
155107
- last_run_at: schedule.lastRunAt ?? null,
155108
- next_run_at: schedule.nextRunAt ?? null,
155109
- run_count: schedule.runCount,
155110
- failure_count: schedule.failureCount,
155111
- last_error: schedule.lastError ?? null,
155112
- previous_response: schedule.previousResponse ?? null,
155113
- };
155114
- }
155115
- /**
155116
- * Enterprise Knex-backed store for PostgreSQL, MySQL, and MSSQL
155117
- */
155118
- class KnexStoreBackend {
155119
- knex = null;
155120
- driver;
155121
- connection;
155122
- constructor(driver, storageConfig, _haConfig) {
155123
- this.driver = driver;
155124
- this.connection = (storageConfig.connection || {});
155125
- }
155126
- async initialize() {
155127
- // Load knex dynamically
155128
- const { createRequire } = __nccwpck_require__(73339);
155129
- const runtimeRequire = createRequire(__filename);
155130
- let knexFactory;
155131
- try {
155132
- knexFactory = runtimeRequire('knex');
155133
- }
155134
- catch (err) {
155135
- const code = err?.code;
155136
- if (code === 'MODULE_NOT_FOUND' || code === 'ERR_MODULE_NOT_FOUND') {
155137
- throw new Error('knex is required for PostgreSQL/MySQL/MSSQL schedule storage. ' +
155138
- 'Install it with: npm install knex');
155139
- }
155140
- throw err;
155141
- }
155142
- const clientMap = {
155143
- postgresql: 'pg',
155144
- mysql: 'mysql2',
155145
- mssql: 'tedious',
155146
- };
155147
- const client = clientMap[this.driver];
155148
- // Build connection config
155149
- let connection;
155150
- if (this.connection.connection_string) {
155151
- connection = this.connection.connection_string;
155152
- }
155153
- else if (this.driver === 'mssql') {
155154
- connection = this.buildMssqlConnection();
155155
- }
155156
- else {
155157
- connection = this.buildStandardConnection();
155158
- }
155159
- this.knex = knexFactory({
155160
- client,
155161
- connection,
155162
- pool: {
155163
- min: this.connection.pool?.min ?? 0,
155164
- max: this.connection.pool?.max ?? 10,
155165
- },
155166
- });
155167
- // Run schema migration
155168
- await this.migrateSchema();
155169
- logger_1.logger.info(`[KnexStore] Initialized (${this.driver})`);
155170
- }
155171
- buildStandardConnection() {
155172
- return {
155173
- host: this.connection.host || 'localhost',
155174
- port: this.connection.port,
155175
- database: this.connection.database || 'visor',
155176
- user: this.connection.user,
155177
- password: this.connection.password,
155178
- ssl: this.resolveSslConfig(),
155179
- };
155180
- }
155181
- buildMssqlConnection() {
155182
- const ssl = this.connection.ssl;
155183
- const sslEnabled = ssl === true || (typeof ssl === 'object' && ssl.enabled !== false);
155184
- return {
155185
- server: this.connection.host || 'localhost',
155186
- port: this.connection.port,
155187
- database: this.connection.database || 'visor',
155188
- user: this.connection.user,
155189
- password: this.connection.password,
155190
- options: {
155191
- encrypt: sslEnabled,
155192
- trustServerCertificate: typeof ssl === 'object' ? ssl.reject_unauthorized === false : !sslEnabled,
155193
- },
155194
- };
155195
- }
155196
- resolveSslConfig() {
155197
- const ssl = this.connection.ssl;
155198
- if (ssl === false || ssl === undefined)
155199
- return false;
155200
- if (ssl === true)
155201
- return { rejectUnauthorized: true };
155202
- // Object config
155203
- if (ssl.enabled === false)
155204
- return false;
155205
- const result = {
155206
- rejectUnauthorized: ssl.reject_unauthorized !== false,
155207
- };
155208
- if (ssl.ca) {
155209
- const caPath = this.validateSslPath(ssl.ca, 'CA certificate');
155210
- result.ca = fs.readFileSync(caPath, 'utf8');
155211
- }
155212
- if (ssl.cert) {
155213
- const certPath = this.validateSslPath(ssl.cert, 'client certificate');
155214
- result.cert = fs.readFileSync(certPath, 'utf8');
155215
- }
155216
- if (ssl.key) {
155217
- const keyPath = this.validateSslPath(ssl.key, 'client key');
155218
- result.key = fs.readFileSync(keyPath, 'utf8');
155219
- }
155220
- return result;
155221
- }
155222
- validateSslPath(filePath, label) {
155223
- const resolved = path.resolve(filePath);
155224
- if (resolved !== path.normalize(resolved)) {
155225
- throw new Error(`SSL ${label} path contains invalid sequences: ${filePath}`);
155226
- }
155227
- if (!fs.existsSync(resolved)) {
155228
- throw new Error(`SSL ${label} not found: ${filePath}`);
155229
- }
155230
- return resolved;
155231
- }
155232
- async shutdown() {
155233
- if (this.knex) {
155234
- await this.knex.destroy();
155235
- this.knex = null;
155236
- }
155237
- }
155238
- async migrateSchema() {
155239
- const knex = this.getKnex();
155240
- const exists = await knex.schema.hasTable('schedules');
155241
- if (!exists) {
155242
- await knex.schema.createTable('schedules', table => {
155243
- table.string('id', 36).primary();
155244
- table.string('creator_id', 255).notNullable().index();
155245
- table.string('creator_context', 255);
155246
- table.string('creator_name', 255);
155247
- table.string('timezone', 64).notNullable().defaultTo('UTC');
155248
- table.string('schedule_expr', 255);
155249
- table.bigInteger('run_at');
155250
- table.boolean('is_recurring').notNullable();
155251
- table.text('original_expression');
155252
- table.string('workflow', 255);
155253
- table.text('workflow_inputs');
155254
- table.text('output_context');
155255
- table.string('status', 20).notNullable().index();
155256
- table.bigInteger('created_at').notNullable();
155257
- table.bigInteger('last_run_at');
155258
- table.bigInteger('next_run_at');
155259
- table.integer('run_count').notNullable().defaultTo(0);
155260
- table.integer('failure_count').notNullable().defaultTo(0);
155261
- table.text('last_error');
155262
- table.text('previous_response');
155263
- table.index(['status', 'next_run_at']);
155264
- });
155265
- }
155266
- // Create scheduler_locks table for distributed locking
155267
- const locksExist = await knex.schema.hasTable('scheduler_locks');
155268
- if (!locksExist) {
155269
- await knex.schema.createTable('scheduler_locks', table => {
155270
- table.string('lock_id', 255).primary();
155271
- table.string('node_id', 255).notNullable();
155272
- table.string('lock_token', 36).notNullable();
155273
- table.bigInteger('acquired_at').notNullable();
155274
- table.bigInteger('expires_at').notNullable();
155275
- });
155276
- }
155277
- }
155278
- getKnex() {
155279
- if (!this.knex) {
155280
- throw new Error('[KnexStore] Not initialized. Call initialize() first.');
155281
- }
155282
- return this.knex;
155283
- }
155284
- // --- CRUD ---
155285
- async create(schedule) {
155286
- const knex = this.getKnex();
155287
- const newSchedule = {
155288
- ...schedule,
155289
- id: (0, uuid_1.v4)(),
155290
- createdAt: Date.now(),
155291
- runCount: 0,
155292
- failureCount: 0,
155293
- status: 'active',
155294
- };
155295
- await knex('schedules').insert(toInsertRow(newSchedule));
155296
- logger_1.logger.info(`[KnexStore] Created schedule ${newSchedule.id} for user ${newSchedule.creatorId}`);
155297
- return newSchedule;
155298
- }
155299
- async importSchedule(schedule) {
155300
- const knex = this.getKnex();
155301
- const existing = await knex('schedules').where('id', schedule.id).first();
155302
- if (existing)
155303
- return; // Already imported (idempotent)
155304
- await knex('schedules').insert(toInsertRow(schedule));
155305
- }
155306
- async get(id) {
155307
- const knex = this.getKnex();
155308
- const row = await knex('schedules').where('id', id).first();
155309
- return row ? fromDbRow(row) : undefined;
155310
- }
155311
- async update(id, patch) {
155312
- const knex = this.getKnex();
155313
- const existing = await knex('schedules').where('id', id).first();
155314
- if (!existing)
155315
- return undefined;
155316
- const current = fromDbRow(existing);
155317
- const updated = { ...current, ...patch, id: current.id };
155318
- const row = toInsertRow(updated);
155319
- // Remove id from update (PK cannot change)
155320
- delete row.id;
155321
- await knex('schedules').where('id', id).update(row);
155322
- return updated;
155323
- }
155324
- async delete(id) {
155325
- const knex = this.getKnex();
155326
- const deleted = await knex('schedules').where('id', id).del();
155327
- if (deleted > 0) {
155328
- logger_1.logger.info(`[KnexStore] Deleted schedule ${id}`);
155329
- return true;
155330
- }
155331
- return false;
155332
- }
155333
- // --- Queries ---
155334
- async getByCreator(creatorId) {
155335
- const knex = this.getKnex();
155336
- const rows = await knex('schedules').where('creator_id', creatorId);
155337
- return rows.map((r) => fromDbRow(r));
155338
- }
155339
- async getActiveSchedules() {
155340
- const knex = this.getKnex();
155341
- const rows = await knex('schedules').where('status', 'active');
155342
- return rows.map((r) => fromDbRow(r));
155343
- }
155344
- async getDueSchedules(now) {
155345
- const ts = now ?? Date.now();
155346
- const knex = this.getKnex();
155347
- // MSSQL uses 1/0 for booleans
155348
- const bFalse = this.driver === 'mssql' ? 0 : false;
155349
- const bTrue = this.driver === 'mssql' ? 1 : true;
155350
- const rows = await knex('schedules')
155351
- .where('status', 'active')
155352
- .andWhere(function () {
155353
- this.where(function () {
155354
- this.where('is_recurring', bFalse)
155355
- .whereNotNull('run_at')
155356
- .where('run_at', '<=', ts);
155357
- }).orWhere(function () {
155358
- this.where('is_recurring', bTrue)
155359
- .whereNotNull('next_run_at')
155360
- .where('next_run_at', '<=', ts);
155361
- });
155362
- });
155363
- return rows.map((r) => fromDbRow(r));
155364
- }
155365
- async findByWorkflow(creatorId, workflowName) {
155366
- const knex = this.getKnex();
155367
- const escaped = workflowName.toLowerCase().replace(/[%_\\]/g, '\\$&');
155368
- const pattern = `%${escaped}%`;
155369
- const rows = await knex('schedules')
155370
- .where('creator_id', creatorId)
155371
- .where('status', 'active')
155372
- .whereRaw("LOWER(workflow) LIKE ? ESCAPE '\\'", [pattern]);
155373
- return rows.map((r) => fromDbRow(r));
155374
- }
155375
- async getAll() {
155376
- const knex = this.getKnex();
155377
- const rows = await knex('schedules');
155378
- return rows.map((r) => fromDbRow(r));
155379
- }
155380
- async getStats() {
155381
- const knex = this.getKnex();
155382
- // MSSQL uses 1/0 for booleans; PostgreSQL/MySQL accept both true/1
155383
- const boolTrue = this.driver === 'mssql' ? '1' : 'true';
155384
- const boolFalse = this.driver === 'mssql' ? '0' : 'false';
155385
- const result = await knex('schedules')
155386
- .select(knex.raw('COUNT(*) as total'), knex.raw("SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active"), knex.raw("SUM(CASE WHEN status = 'paused' THEN 1 ELSE 0 END) as paused"), knex.raw("SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed"), knex.raw("SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed"), knex.raw(`SUM(CASE WHEN is_recurring = ${boolTrue} THEN 1 ELSE 0 END) as recurring`), knex.raw(`SUM(CASE WHEN is_recurring = ${boolFalse} THEN 1 ELSE 0 END) as one_time`))
155387
- .first();
155388
- return {
155389
- total: Number(result.total) || 0,
155390
- active: Number(result.active) || 0,
155391
- paused: Number(result.paused) || 0,
155392
- completed: Number(result.completed) || 0,
155393
- failed: Number(result.failed) || 0,
155394
- recurring: Number(result.recurring) || 0,
155395
- oneTime: Number(result.one_time) || 0,
155396
- };
155397
- }
155398
- async validateLimits(creatorId, isRecurring, limits) {
155399
- const knex = this.getKnex();
155400
- if (limits.maxGlobal) {
155401
- const result = await knex('schedules').count('* as cnt').first();
155402
- if (Number(result?.cnt) >= limits.maxGlobal) {
155403
- throw new Error(`Global schedule limit reached (${limits.maxGlobal})`);
155404
- }
155405
- }
155406
- if (limits.maxPerUser) {
155407
- const result = await knex('schedules')
155408
- .where('creator_id', creatorId)
155409
- .count('* as cnt')
155410
- .first();
155411
- if (Number(result?.cnt) >= limits.maxPerUser) {
155412
- throw new Error(`You have reached the maximum number of schedules (${limits.maxPerUser})`);
155413
- }
155414
- }
155415
- if (isRecurring && limits.maxRecurringPerUser) {
155416
- const bTrue = this.driver === 'mssql' ? 1 : true;
155417
- const result = await knex('schedules')
155418
- .where('creator_id', creatorId)
155419
- .where('is_recurring', bTrue)
155420
- .count('* as cnt')
155421
- .first();
155422
- if (Number(result?.cnt) >= limits.maxRecurringPerUser) {
155423
- throw new Error(`You have reached the maximum number of recurring schedules (${limits.maxRecurringPerUser})`);
155424
- }
155425
- }
155426
- }
155427
- // --- HA Distributed Locking (via scheduler_locks table) ---
155428
- async tryAcquireLock(lockId, nodeId, ttlSeconds) {
155429
- const knex = this.getKnex();
155430
- const now = Date.now();
155431
- const expiresAt = now + ttlSeconds * 1000;
155432
- const token = (0, uuid_1.v4)();
155433
- // Step 1: Try to claim an existing expired lock
155434
- const updated = await knex('scheduler_locks')
155435
- .where('lock_id', lockId)
155436
- .where('expires_at', '<', now)
155437
- .update({
155438
- node_id: nodeId,
155439
- lock_token: token,
155440
- acquired_at: now,
155441
- expires_at: expiresAt,
155442
- });
155443
- if (updated > 0)
155444
- return token;
155445
- // Step 2: Try to INSERT a new lock row
155446
- try {
155447
- await knex('scheduler_locks').insert({
155448
- lock_id: lockId,
155449
- node_id: nodeId,
155450
- lock_token: token,
155451
- acquired_at: now,
155452
- expires_at: expiresAt,
155453
- });
155454
- return token;
155455
- }
155456
- catch {
155457
- // Unique constraint violation — another node holds the lock
155458
- return null;
155459
- }
155460
- }
155461
- async releaseLock(lockId, lockToken) {
155462
- const knex = this.getKnex();
155463
- await knex('scheduler_locks').where('lock_id', lockId).where('lock_token', lockToken).del();
155464
- }
155465
- async renewLock(lockId, lockToken, ttlSeconds) {
155466
- const knex = this.getKnex();
155467
- const now = Date.now();
155468
- const expiresAt = now + ttlSeconds * 1000;
155469
- const updated = await knex('scheduler_locks')
155470
- .where('lock_id', lockId)
155471
- .where('lock_token', lockToken)
155472
- .update({ acquired_at: now, expires_at: expiresAt });
155473
- return updated > 0;
155474
- }
155475
- async flush() {
155476
- // No-op for server-based backends
155477
- }
155478
- }
155479
- exports.KnexStoreBackend = KnexStoreBackend;
155480
-
155481
-
155482
153798
  /***/ }),
155483
153799
 
155484
153800
  /***/ 83864:
@@ -165414,35 +163730,6 @@ class OutputFormatters {
165414
163730
  exports.OutputFormatters = OutputFormatters;
165415
163731
 
165416
163732
 
165417
- /***/ }),
165418
-
165419
- /***/ 93866:
165420
- /***/ ((__unused_webpack_module, exports) => {
165421
-
165422
- "use strict";
165423
-
165424
- Object.defineProperty(exports, "__esModule", ({ value: true }));
165425
- exports.DefaultPolicyEngine = void 0;
165426
- /**
165427
- * Default (no-op) policy engine — always allows everything.
165428
- * Used when no enterprise license is present or policy is disabled.
165429
- */
165430
- class DefaultPolicyEngine {
165431
- async initialize(_config) { }
165432
- async evaluateCheckExecution(_checkId, _checkConfig) {
165433
- return { allowed: true };
165434
- }
165435
- async evaluateToolInvocation(_serverName, _methodName, _transport) {
165436
- return { allowed: true };
165437
- }
165438
- async evaluateCapabilities(_checkId, _capabilities) {
165439
- return { allowed: true };
165440
- }
165441
- async shutdown() { }
165442
- }
165443
- exports.DefaultPolicyEngine = DefaultPolicyEngine;
165444
-
165445
-
165446
163733
  /***/ }),
165447
163734
 
165448
163735
  /***/ 96611:
@@ -184076,7 +182363,7 @@ class StateMachineExecutionEngine {
184076
182363
  try {
184077
182364
  logger_1.logger.debug(`[PolicyEngine] Loading enterprise policy engine (engine=${configWithTagFilter.policy.engine})`);
184078
182365
  // @ts-ignore — enterprise/ may not exist in OSS builds (caught at runtime)
184079
- const { loadEnterprisePolicyEngine } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(87068)));
182366
+ const { loadEnterprisePolicyEngine } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(7065)));
184080
182367
  context.policyEngine = await loadEnterprisePolicyEngine(configWithTagFilter.policy);
184081
182368
  logger_1.logger.debug(`[PolicyEngine] Initialized: ${context.policyEngine?.constructor?.name || 'unknown'}`);
184082
182369
  }
@@ -194293,7 +192580,7 @@ async function initTelemetry(opts = {}) {
194293
192580
  const path = __nccwpck_require__(16928);
194294
192581
  const outDir = opts.file?.dir ||
194295
192582
  process.env.VISOR_TRACE_DIR ||
194296
- path.join(process.cwd(), 'output', 'traces');
192583
+ __nccwpck_require__.ab + "traces";
194297
192584
  fs.mkdirSync(outDir, { recursive: true });
194298
192585
  const ts = new Date().toISOString().replace(/[:.]/g, '-');
194299
192586
  process.env.VISOR_FALLBACK_TRACE_FILE = path.join(outDir, `run-${ts}.ndjson`);
@@ -194496,7 +192783,7 @@ async function shutdownTelemetry() {
194496
192783
  if (process.env.VISOR_TRACE_REPORT === 'true') {
194497
192784
  const fs = __nccwpck_require__(79896);
194498
192785
  const path = __nccwpck_require__(16928);
194499
- const outDir = process.env.VISOR_TRACE_DIR || path.join(process.cwd(), 'output', 'traces');
192786
+ const outDir = process.env.VISOR_TRACE_DIR || __nccwpck_require__.ab + "traces";
194500
192787
  if (!fs.existsSync(outDir))
194501
192788
  fs.mkdirSync(outDir, { recursive: true });
194502
192789
  const ts = new Date().toISOString().replace(/[:.]/g, '-');
@@ -194971,7 +193258,7 @@ function __getOrCreateNdjsonPath() {
194971
193258
  fs.mkdirSync(dir, { recursive: true });
194972
193259
  return __ndjsonPath;
194973
193260
  }
194974
- const outDir = process.env.VISOR_TRACE_DIR || path.join(process.cwd(), 'output', 'traces');
193261
+ const outDir = process.env.VISOR_TRACE_DIR || __nccwpck_require__.ab + "traces";
194975
193262
  if (!fs.existsSync(outDir))
194976
193263
  fs.mkdirSync(outDir, { recursive: true });
194977
193264
  if (!__ndjsonPath) {
@@ -206881,6 +205168,22 @@ class WorkflowRegistry {
206881
205168
  exports.WorkflowRegistry = WorkflowRegistry;
206882
205169
 
206883
205170
 
205171
+ /***/ }),
205172
+
205173
+ /***/ 7065:
205174
+ /***/ ((module) => {
205175
+
205176
+ module.exports = eval("require")("./enterprise/loader");
205177
+
205178
+
205179
+ /***/ }),
205180
+
205181
+ /***/ 71370:
205182
+ /***/ ((module) => {
205183
+
205184
+ module.exports = eval("require")("./enterprise/policy/policy-input-builder");
205185
+
205186
+
206884
205187
  /***/ }),
206885
205188
 
206886
205189
  /***/ 18327:
@@ -363765,7 +362068,7 @@ module.exports = /*#__PURE__*/JSON.parse('{"100":"Continue","101":"Switching Pro
363765
362068
  /***/ ((module) => {
363766
362069
 
363767
362070
  "use strict";
363768
- module.exports = /*#__PURE__*/JSON.parse('{"name":"@probelabs/visor","version":"0.1.42","main":"dist/index.js","bin":{"visor":"./dist/index.js"},"exports":{".":{"require":"./dist/index.js","import":"./dist/index.js"},"./sdk":{"types":"./dist/sdk/sdk.d.ts","import":"./dist/sdk/sdk.mjs","require":"./dist/sdk/sdk.js"},"./cli":{"require":"./dist/index.js"}},"files":["dist/","defaults/","action.yml","README.md","LICENSE"],"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"scripts":{"build:cli":"ncc build src/index.ts -o dist && cp -r defaults dist/ && cp -r output dist/ && cp -r docs dist/ && cp -r examples dist/ && cp -r src/debug-visualizer/ui dist/debug-visualizer/ && node scripts/inject-version.js && echo \'#!/usr/bin/env node\' | cat - dist/index.js > temp && mv temp dist/index.js && chmod +x dist/index.js","build:sdk":"tsup src/sdk.ts --dts --sourcemap --format esm,cjs --out-dir dist/sdk","build":"./scripts/build-oss.sh","build:ee":"npm run build:cli && npm run build:sdk","test":"jest && npm run test:yaml","test:unit":"jest","prepublishOnly":"npm run build","test:watch":"jest --watch","test:coverage":"jest --coverage","test:ee":"jest --testPathPatterns=\'tests/ee\' --testPathIgnorePatterns=\'/node_modules/\' --no-coverage","test:manual:bash":"RUN_MANUAL_TESTS=true jest tests/manual/bash-config-manual.test.ts","lint":"eslint src tests --ext .ts","lint:fix":"eslint src tests --ext .ts --fix","format":"prettier --write src tests","format:check":"prettier --check src tests","clean":"","prebuild":"npm run clean && node scripts/generate-config-schema.js","pretest":"node scripts/generate-config-schema.js && npm run build:cli","pretest:unit":"node scripts/generate-config-schema.js && npm run build:cli","test:with-build":"npm run build:cli && jest","test:yaml":"node dist/index.js test --progress compact","test:yaml:parallel":"node dist/index.js test --progress compact --max-parallel 4","prepare":"husky","pre-commit":"lint-staged","deploy:site":"cd site && npx wrangler pages deploy . --project-name=visor-site --commit-dirty=true","deploy:worker":"npx wrangler deploy","deploy":"npm run deploy:site && npm run deploy:worker","publish:ee":"./scripts/publish-ee.sh","release":"./scripts/release.sh","release:patch":"./scripts/release.sh patch","release:minor":"./scripts/release.sh minor","release:major":"./scripts/release.sh major","release:prerelease":"./scripts/release.sh prerelease","docs:validate":"node scripts/validate-readme-links.js","workshop:setup":"npm install -D reveal-md@6.1.2","workshop:serve":"cd workshop && reveal-md slides.md -w","workshop:export":"reveal-md workshop/slides.md --static workshop/build","workshop:pdf":"reveal-md workshop/slides.md --print workshop/Visor-Workshop.pdf --print-size letter","workshop:pdf:ci":"reveal-md workshop/slides.md --print workshop/Visor-Workshop.pdf --print-size letter --puppeteer-launch-args=\\"--no-sandbox --disable-dev-shm-usage\\"","workshop:pdf:a4":"reveal-md workshop/slides.md --print workshop/Visor-Workshop-A4.pdf --print-size A4","workshop:build":"npm run workshop:export && npm run workshop:pdf","simulate:issue":"TS_NODE_TRANSPILE_ONLY=1 ts-node scripts/simulate-gh-run.ts --event issues --action opened --debug","simulate:comment":"TS_NODE_TRANSPILE_ONLY=1 ts-node scripts/simulate-gh-run.ts --event issue_comment --action created --debug"},"keywords":["code-review","ai","github-action","cli","pr-review","visor"],"author":"Probe Labs","license":"MIT","description":"AI-powered code review tool for GitHub Pull Requests - CLI and GitHub Action","repository":{"type":"git","url":"git+https://github.com/probelabs/visor.git"},"bugs":{"url":"https://github.com/probelabs/visor/issues"},"homepage":"https://github.com/probelabs/visor#readme","dependencies":{"@actions/core":"^1.11.1","@modelcontextprotocol/sdk":"^1.25.3","@nyariv/sandboxjs":"github:probelabs/SandboxJS#f1c13b8eee98734a8ea024061eada4aa9a9ff2e9","@octokit/action":"^8.0.2","@octokit/auth-app":"^8.1.0","@octokit/core":"^7.0.3","@octokit/rest":"^22.0.0","@probelabs/probe":"^0.6.0-rc229","@types/commander":"^2.12.0","@types/uuid":"^10.0.0","ajv":"^8.17.1","ajv-formats":"^3.0.1","blessed":"^0.1.81","cli-table3":"^0.6.5","commander":"^14.0.0","dotenv":"^17.2.3","ignore":"^7.0.5","js-yaml":"^4.1.0","liquidjs":"^10.21.1","node-cron":"^3.0.3","open":"^9.1.0","simple-git":"^3.28.0","uuid":"^11.1.0","ws":"^8.18.3"},"optionalDependencies":{"@anthropic/claude-code-sdk":"npm:null@*","@open-policy-agent/opa-wasm":"^1.10.0","@opentelemetry/api":"^1.9.0","@opentelemetry/core":"^1.30.1","@opentelemetry/exporter-trace-otlp-grpc":"^0.203.0","@opentelemetry/exporter-trace-otlp-http":"^0.203.0","@opentelemetry/instrumentation":"^0.203.0","@opentelemetry/resources":"^1.30.1","@opentelemetry/sdk-metrics":"^1.30.1","@opentelemetry/sdk-node":"^0.203.0","@opentelemetry/sdk-trace-base":"^1.30.1","@opentelemetry/semantic-conventions":"^1.30.1","better-sqlite3":"^11.0.0","knex":"^3.1.0","mysql2":"^3.11.0","pg":"^8.13.0","tedious":"^19.0.0"},"devDependencies":{"@eslint/js":"^9.34.0","@kie/act-js":"^2.6.2","@kie/mock-github":"^2.0.1","@swc/core":"^1.13.2","@swc/jest":"^0.2.37","@types/better-sqlite3":"^7.6.0","@types/blessed":"^0.1.27","@types/jest":"^30.0.0","@types/js-yaml":"^4.0.9","@types/node":"^24.3.0","@types/node-cron":"^3.0.11","@types/ws":"^8.18.1","@typescript-eslint/eslint-plugin":"^8.42.0","@typescript-eslint/parser":"^8.42.0","@vercel/ncc":"^0.38.4","eslint":"^9.34.0","eslint-config-prettier":"^10.1.8","eslint-plugin-prettier":"^5.5.4","husky":"^9.1.7","jest":"^30.1.3","lint-staged":"^16.1.6","prettier":"^3.6.2","reveal-md":"^6.1.2","ts-json-schema-generator":"^1.5.1","ts-node":"^10.9.2","tsup":"^8.5.0","typescript":"^5.9.2","wrangler":"^3.0.0"},"peerDependenciesMeta":{"@anthropic/claude-code-sdk":{"optional":true}},"directories":{"test":"tests"},"lint-staged":{"src/**/*.{ts,js}":["eslint --fix","prettier --write"],"tests/**/*.{ts,js}":["eslint --fix","prettier --write"],"*.{json,md,yml,yaml}":["prettier --write"]}}');
362071
+ module.exports = /*#__PURE__*/JSON.parse('{"name":"@probelabs/visor","version":"0.1.130","main":"dist/index.js","bin":{"visor":"./dist/index.js"},"exports":{".":{"require":"./dist/index.js","import":"./dist/index.js"},"./sdk":{"types":"./dist/sdk/sdk.d.ts","import":"./dist/sdk/sdk.mjs","require":"./dist/sdk/sdk.js"},"./cli":{"require":"./dist/index.js"}},"files":["dist/","defaults/","action.yml","README.md","LICENSE"],"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"scripts":{"build:cli":"ncc build src/index.ts -o dist && cp -r defaults dist/ && cp -r output dist/ && cp -r docs dist/ && cp -r examples dist/ && cp -r src/debug-visualizer/ui dist/debug-visualizer/ && node scripts/inject-version.js && echo \'#!/usr/bin/env node\' | cat - dist/index.js > temp && mv temp dist/index.js && chmod +x dist/index.js","build:sdk":"tsup src/sdk.ts --dts --sourcemap --format esm,cjs --out-dir dist/sdk","build":"./scripts/build-oss.sh","build:ee":"npm run build:cli && npm run build:sdk","test":"jest && npm run test:yaml","test:unit":"jest","prepublishOnly":"npm run build","test:watch":"jest --watch","test:coverage":"jest --coverage","test:ee":"jest --testPathPatterns=\'tests/ee\' --testPathIgnorePatterns=\'/node_modules/\' --no-coverage","test:manual:bash":"RUN_MANUAL_TESTS=true jest tests/manual/bash-config-manual.test.ts","lint":"eslint src tests --ext .ts","lint:fix":"eslint src tests --ext .ts --fix","format":"prettier --write src tests","format:check":"prettier --check src tests","clean":"","prebuild":"npm run clean && node scripts/generate-config-schema.js","pretest":"node scripts/generate-config-schema.js && npm run build:cli","pretest:unit":"node scripts/generate-config-schema.js && npm run build:cli","test:with-build":"npm run build:cli && jest","test:yaml":"node dist/index.js test --progress compact","test:yaml:parallel":"node dist/index.js test --progress compact --max-parallel 4","prepare":"husky","pre-commit":"lint-staged","deploy:site":"cd site && npx wrangler pages deploy . --project-name=visor-site --commit-dirty=true","deploy:worker":"npx wrangler deploy","deploy":"npm run deploy:site && npm run deploy:worker","publish:ee":"./scripts/publish-ee.sh","release":"./scripts/release.sh","release:patch":"./scripts/release.sh patch","release:minor":"./scripts/release.sh minor","release:major":"./scripts/release.sh major","release:prerelease":"./scripts/release.sh prerelease","docs:validate":"node scripts/validate-readme-links.js","workshop:setup":"npm install -D reveal-md@6.1.2","workshop:serve":"cd workshop && reveal-md slides.md -w","workshop:export":"reveal-md workshop/slides.md --static workshop/build","workshop:pdf":"reveal-md workshop/slides.md --print workshop/Visor-Workshop.pdf --print-size letter","workshop:pdf:ci":"reveal-md workshop/slides.md --print workshop/Visor-Workshop.pdf --print-size letter --puppeteer-launch-args=\\"--no-sandbox --disable-dev-shm-usage\\"","workshop:pdf:a4":"reveal-md workshop/slides.md --print workshop/Visor-Workshop-A4.pdf --print-size A4","workshop:build":"npm run workshop:export && npm run workshop:pdf","simulate:issue":"TS_NODE_TRANSPILE_ONLY=1 ts-node scripts/simulate-gh-run.ts --event issues --action opened --debug","simulate:comment":"TS_NODE_TRANSPILE_ONLY=1 ts-node scripts/simulate-gh-run.ts --event issue_comment --action created --debug"},"keywords":["code-review","ai","github-action","cli","pr-review","visor"],"author":"Probe Labs","license":"MIT","description":"AI-powered code review tool for GitHub Pull Requests - CLI and GitHub Action","repository":{"type":"git","url":"git+https://github.com/probelabs/visor.git"},"bugs":{"url":"https://github.com/probelabs/visor/issues"},"homepage":"https://github.com/probelabs/visor#readme","dependencies":{"@actions/core":"^1.11.1","@modelcontextprotocol/sdk":"^1.25.3","@nyariv/sandboxjs":"github:probelabs/SandboxJS#f1c13b8eee98734a8ea024061eada4aa9a9ff2e9","@octokit/action":"^8.0.2","@octokit/auth-app":"^8.1.0","@octokit/core":"^7.0.3","@octokit/rest":"^22.0.0","@probelabs/probe":"^0.6.0-rc229","@types/commander":"^2.12.0","@types/uuid":"^10.0.0","ajv":"^8.17.1","ajv-formats":"^3.0.1","blessed":"^0.1.81","cli-table3":"^0.6.5","commander":"^14.0.0","dotenv":"^17.2.3","ignore":"^7.0.5","js-yaml":"^4.1.0","liquidjs":"^10.21.1","node-cron":"^3.0.3","open":"^9.1.0","simple-git":"^3.28.0","uuid":"^11.1.0","ws":"^8.18.3"},"optionalDependencies":{"@anthropic/claude-code-sdk":"npm:null@*","@open-policy-agent/opa-wasm":"^1.10.0","@opentelemetry/api":"^1.9.0","@opentelemetry/core":"^1.30.1","@opentelemetry/exporter-trace-otlp-grpc":"^0.203.0","@opentelemetry/exporter-trace-otlp-http":"^0.203.0","@opentelemetry/instrumentation":"^0.203.0","@opentelemetry/resources":"^1.30.1","@opentelemetry/sdk-metrics":"^1.30.1","@opentelemetry/sdk-node":"^0.203.0","@opentelemetry/sdk-trace-base":"^1.30.1","@opentelemetry/semantic-conventions":"^1.30.1","better-sqlite3":"^11.0.0","knex":"^3.1.0","mysql2":"^3.11.0","pg":"^8.13.0","tedious":"^19.0.0"},"devDependencies":{"@eslint/js":"^9.34.0","@kie/act-js":"^2.6.2","@kie/mock-github":"^2.0.1","@swc/core":"^1.13.2","@swc/jest":"^0.2.37","@types/better-sqlite3":"^7.6.0","@types/blessed":"^0.1.27","@types/jest":"^30.0.0","@types/js-yaml":"^4.0.9","@types/node":"^24.3.0","@types/node-cron":"^3.0.11","@types/ws":"^8.18.1","@typescript-eslint/eslint-plugin":"^8.42.0","@typescript-eslint/parser":"^8.42.0","@vercel/ncc":"^0.38.4","eslint":"^9.34.0","eslint-config-prettier":"^10.1.8","eslint-plugin-prettier":"^5.5.4","husky":"^9.1.7","jest":"^30.1.3","lint-staged":"^16.1.6","prettier":"^3.6.2","reveal-md":"^6.1.2","ts-json-schema-generator":"^1.5.1","ts-node":"^10.9.2","tsup":"^8.5.0","typescript":"^5.9.2","wrangler":"^3.0.0"},"peerDependenciesMeta":{"@anthropic/claude-code-sdk":{"optional":true}},"directories":{"test":"tests"},"lint-staged":{"src/**/*.{ts,js}":["eslint --fix","prettier --write"],"tests/**/*.{ts,js}":["eslint --fix","prettier --write"],"*.{json,md,yml,yaml}":["prettier --write"]}}');
363769
362072
 
363770
362073
  /***/ })
363771
362074