@bonginkan/maria 4.2.6 → 4.2.8

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.js CHANGED
@@ -7,8 +7,8 @@ import * as path2 from 'path';
7
7
  import path2__default, { join } from 'path';
8
8
  import { promisify } from 'util';
9
9
  import { spawn } from 'child_process';
10
- import * as crypto3 from 'crypto';
11
- import crypto3__default, { createHash } from 'crypto';
10
+ import * as crypto2 from 'crypto';
11
+ import crypto2__default, { createHash } from 'crypto';
12
12
  import * as jwt from 'jsonwebtoken';
13
13
  import * as fs3 from 'fs/promises';
14
14
  import { mkdir, writeFile } from 'fs/promises';
@@ -18770,14 +18770,14 @@ var require_view = __commonJS({
18770
18770
  var require_etag = __commonJS({
18771
18771
  "node_modules/.pnpm/etag@1.8.1/node_modules/etag/index.js"(exports, module) {
18772
18772
  module.exports = etag;
18773
- var crypto9 = __require("crypto");
18773
+ var crypto8 = __require("crypto");
18774
18774
  var Stats = __require("fs").Stats;
18775
18775
  var toString = Object.prototype.toString;
18776
18776
  function entitytag(entity) {
18777
18777
  if (entity.length === 0) {
18778
18778
  return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"';
18779
18779
  }
18780
- var hash = crypto9.createHash("sha1").update(entity, "utf8").digest("base64").substring(0, 27);
18780
+ var hash = crypto8.createHash("sha1").update(entity, "utf8").digest("base64").substring(0, 27);
18781
18781
  var len = typeof entity === "string" ? Buffer.byteLength(entity, "utf8") : entity.length;
18782
18782
  return '"' + len.toString(16) + "-" + hash + '"';
18783
18783
  }
@@ -22233,17 +22233,17 @@ var require_content_disposition = __commonJS({
22233
22233
  // node_modules/.pnpm/cookie-signature@1.2.2/node_modules/cookie-signature/index.js
22234
22234
  var require_cookie_signature = __commonJS({
22235
22235
  "node_modules/.pnpm/cookie-signature@1.2.2/node_modules/cookie-signature/index.js"(exports) {
22236
- var crypto9 = __require("crypto");
22236
+ var crypto8 = __require("crypto");
22237
22237
  exports.sign = function(val, secret) {
22238
22238
  if ("string" != typeof val) throw new TypeError("Cookie value must be provided as a string.");
22239
22239
  if (null == secret) throw new TypeError("Secret key must be provided.");
22240
- return val + "." + crypto9.createHmac("sha256", secret).update(val).digest("base64").replace(/\=+$/, "");
22240
+ return val + "." + crypto8.createHmac("sha256", secret).update(val).digest("base64").replace(/\=+$/, "");
22241
22241
  };
22242
22242
  exports.unsign = function(input2, secret) {
22243
22243
  if ("string" != typeof input2) throw new TypeError("Signed cookie string must be provided.");
22244
22244
  if (null == secret) throw new TypeError("Secret key must be provided.");
22245
22245
  var tentativeValue = input2.slice(0, input2.lastIndexOf(".")), expectedInput = exports.sign(tentativeValue, secret), expectedBuffer = Buffer.from(expectedInput), inputBuffer = Buffer.from(input2);
22246
- return expectedBuffer.length === inputBuffer.length && crypto9.timingSafeEqual(expectedBuffer, inputBuffer) ? tentativeValue : false;
22246
+ return expectedBuffer.length === inputBuffer.length && crypto8.timingSafeEqual(expectedBuffer, inputBuffer) ? tentativeValue : false;
22247
22247
  };
22248
22248
  }
22249
22249
  });
@@ -29968,12 +29968,12 @@ var DualMemoryEngine = class {
29968
29968
  async query(memoryQuery) {
29969
29969
  const _startTime = Date.now();
29970
29970
  const cacheKey = this.generateCacheKey(memoryQuery);
29971
- const cached2 = this.performanceCache.get(cacheKey);
29972
- if (cached2 && this.isCacheValid(cached2)) {
29973
- cached2.hits++;
29971
+ const cached = this.performanceCache.get(cacheKey);
29972
+ if (cached && this.isCacheValid(cached)) {
29973
+ cached.hits++;
29974
29974
  this.operationMetrics.totalOperations++;
29975
29975
  return {
29976
- _data: cached2._result,
29976
+ _data: cached._result,
29977
29977
  source: "both",
29978
29978
  confidence: 0.9,
29979
29979
  latency: Date.now() - _startTime,
@@ -30175,8 +30175,8 @@ var DualMemoryEngine = class {
30175
30175
  }
30176
30176
  getCacheStatus(query) {
30177
30177
  const cacheKey = this.generateCacheKey(query);
30178
- const cached2 = this.performanceCache.get(cacheKey);
30179
- return cached2 ? 0.8 : 0.2;
30178
+ const cached = this.performanceCache.get(cacheKey);
30179
+ return cached ? 0.8 : 0.2;
30180
30180
  }
30181
30181
  calculateSystem1Score(_factors) {
30182
30182
  const _urgencyWeight = _factors.urgency * 0.4;
@@ -30427,9 +30427,9 @@ var DualMemoryEngine = class {
30427
30427
  cleanupCache() {
30428
30428
  const _now = /* @__PURE__ */ new Date();
30429
30429
  const _maxAge = 30 * 60 * 1e3;
30430
- for (const [key, cached2] of this.performanceCache.entries()) {
30431
- const age = _now.getTime() - cached2.timestamp.getTime();
30432
- if (age > _maxAge || cached2.hits < 2) {
30430
+ for (const [key, cached] of this.performanceCache.entries()) {
30431
+ const age = _now.getTime() - cached.timestamp.getTime();
30432
+ if (age > _maxAge || cached.hits < 2) {
30433
30433
  this.performanceCache.delete(key);
30434
30434
  }
30435
30435
  }
@@ -30470,8 +30470,8 @@ var DualMemoryEngine = class {
30470
30470
  const _embeddingStr = query.embedding ? query.embedding.slice(0, 5).join(",") : "";
30471
30471
  return `${query.type}:${query.query}:${_contextStr}:${_embeddingStr}:${query.limit || 10}`;
30472
30472
  }
30473
- isCacheValid(cached2) {
30474
- const age = Date.now() - cached2.timestamp.getTime();
30473
+ isCacheValid(cached) {
30474
+ const age = Date.now() - cached.timestamp.getTime();
30475
30475
  const _maxAge = 10 * 60 * 1e3;
30476
30476
  return age < _maxAge;
30477
30477
  }
@@ -30502,7 +30502,7 @@ var DualMemoryEngine = class {
30502
30502
  // ========== Public API for Monitoring ==========
30503
30503
  getMetrics() {
30504
30504
  const _totalCacheAccess = Array.from(this.performanceCache.values()).reduce(
30505
- (sum, cached2) => sum + cached2.hits,
30505
+ (sum, cached) => sum + cached.hits,
30506
30506
  0
30507
30507
  );
30508
30508
  this.operationMetrics.cacheHitRate = this.operationMetrics.totalOperations > 0 ? _totalCacheAccess / this.operationMetrics.totalOperations : 0;
@@ -34994,11 +34994,11 @@ var SlashCommandHandler = class {
34994
34994
  * Get all categories
34995
34995
  */
34996
34996
  getCategories() {
34997
- const categories = /* @__PURE__ */ new Set();
34997
+ const categories2 = /* @__PURE__ */ new Set();
34998
34998
  for (const command of this.commands.values()) {
34999
- categories.add(command.category);
34999
+ categories2.add(command.category);
35000
35000
  }
35001
- return Array.from(categories);
35001
+ return Array.from(categories2);
35002
35002
  }
35003
35003
  /**
35004
35004
  * Validate command arguments
@@ -35338,9 +35338,9 @@ var RBACCommandGuard = class extends EventEmitter {
35338
35338
  async getUserPermissions(user2) {
35339
35339
  const cacheKey = `${user2.id}:${user2.roles.join(",")}:${this.policyVersion}`;
35340
35340
  if (this.config.cachePermissions) {
35341
- const cached2 = this.permissionCache.get(cacheKey);
35342
- if (cached2 && cached2.expires > /* @__PURE__ */ new Date()) {
35343
- return cached2.permissions;
35341
+ const cached = this.permissionCache.get(cacheKey);
35342
+ if (cached && cached.expires > /* @__PURE__ */ new Date()) {
35343
+ return cached.permissions;
35344
35344
  }
35345
35345
  }
35346
35346
  const permissions = await this.computePermissions(user2);
@@ -35362,14 +35362,14 @@ var RBACCommandGuard = class extends EventEmitter {
35362
35362
  async computePermissions(user2) {
35363
35363
  const commandPermissions = [];
35364
35364
  const allPermissions = /* @__PURE__ */ new Set();
35365
- const userRoles = user2.roles.map((roleId) => this.roles.get(roleId)).filter((role2) => role2 && role2.active).sort((a2, b) => (b?.priority || 0) - (a2?.priority || 0));
35366
- for (const role2 of userRoles) {
35367
- if (!role2) continue;
35368
- for (const permission of role2.permissions) {
35365
+ const userRoles = user2.roles.map((roleId) => this.roles.get(roleId)).filter((role) => role && role.active).sort((a2, b) => (b?.priority || 0) - (a2?.priority || 0));
35366
+ for (const role of userRoles) {
35367
+ if (!role) continue;
35368
+ for (const permission of role.permissions) {
35369
35369
  allPermissions.add(permission);
35370
35370
  }
35371
- if (this.config.inheritanceEnabled && role2.inheritsFrom.length > 0) {
35372
- for (const parentRoleId of role2.inheritsFrom) {
35371
+ if (this.config.inheritanceEnabled && role.inheritsFrom.length > 0) {
35372
+ for (const parentRoleId of role.inheritsFrom) {
35373
35373
  const parentRole = this.roles.get(parentRoleId);
35374
35374
  if (parentRole && parentRole.active) {
35375
35375
  for (const permission of parentRole.permissions) {
@@ -35441,22 +35441,22 @@ var RBACCommandGuard = class extends EventEmitter {
35441
35441
  const failedConditions = [];
35442
35442
  let mfaRequired = false;
35443
35443
  for (const roleId of user2.roles) {
35444
- const role2 = this.roles.get(roleId);
35445
- if (!role2) continue;
35446
- for (const condition2 of role2.conditions) {
35447
- if (!condition2.enforced) continue;
35448
- switch (condition2.type) {
35444
+ const role = this.roles.get(roleId);
35445
+ if (!role) continue;
35446
+ for (const condition of role.conditions) {
35447
+ if (!condition.enforced) continue;
35448
+ switch (condition.type) {
35449
35449
  case "mfa":
35450
35450
  if (!user2.mfaVerified) {
35451
35451
  mfaRequired = true;
35452
- if (condition2.requirement.required) {
35453
- failedConditions.push(`MFA required for role ${role2.name}`);
35452
+ if (condition.requirement.required) {
35453
+ failedConditions.push(`MFA required for role ${role.name}`);
35454
35454
  }
35455
35455
  }
35456
35456
  break;
35457
35457
  case "time":
35458
- if (!this.evaluateTimeCondition(condition2.requirement)) {
35459
- failedConditions.push(`Time restriction for role ${role2.name}`);
35458
+ if (!this.evaluateTimeCondition(condition.requirement)) {
35459
+ failedConditions.push(`Time restriction for role ${role.name}`);
35460
35460
  }
35461
35461
  break;
35462
35462
  }
@@ -35559,1224 +35559,6 @@ var RBACCommandGuard = class extends EventEmitter {
35559
35559
  };
35560
35560
  }
35561
35561
  };
35562
- var AccessControlManager = class extends EventEmitter {
35563
- config;
35564
- users;
35565
- roles;
35566
- cache;
35567
- auditLog;
35568
- policyEngine;
35569
- encryptionKey;
35570
- gdprCompliance;
35571
- hipaaCompliance;
35572
- constructor(_config) {
35573
- super();
35574
- this._config = _config;
35575
- this.users = /* @__PURE__ */ new Map();
35576
- this.roles = /* @__PURE__ */ new Map();
35577
- this.auditLog = [];
35578
- this.cache = this.initializeCache();
35579
- this.policyEngine = new PolicyEngine(_config);
35580
- this.encryptionKey = this.generateEncryptionKey();
35581
- this.initializeDefaultRoles();
35582
- }
35583
- // ========== Access Control Methods ==========
35584
- async enforceHierarchicalAccess(_user, resource, operation) {
35585
- if (!this.hasOrganizationAccess(_user, resource)) {
35586
- return {
35587
- allowed: false,
35588
- reason: "User does not have organization-_level access to this resource"
35589
- };
35590
- }
35591
- if (resource.type === "memory" && resource.path?.includes("/projects/")) {
35592
- const _projectId = this.extractProjectId(resource._path);
35593
- if (_projectId && !user.projects.includes(_projectId)) {
35594
- return {
35595
- allowed: false,
35596
- reason: `User does not have access to project: ${_projectId}`
35597
- };
35598
- }
35599
- }
35600
- if (resource.type === "memory" && resource.path?.includes("/teams/")) {
35601
- const _teamId = this.extractTeamId(resource._path);
35602
- if (_teamId && !user.teams.includes(_teamId)) {
35603
- return {
35604
- allowed: false,
35605
- reason: `User does not have access to team: ${_teamId}`
35606
- };
35607
- }
35608
- }
35609
- const _inheritedPermissions = this.calculateInheritedPermissions(_user, resource);
35610
- const _hasRequiredPermission = this.checkPermissionAtAllLevels(
35611
- _user,
35612
- _inheritedPermissions,
35613
- operation
35614
- );
35615
- if (!_hasRequiredPermission) {
35616
- return {
35617
- allowed: false,
35618
- reason: `Insufficient _permissions for operation: ${operation}`
35619
- };
35620
- }
35621
- return {
35622
- allowed: true,
35623
- _permissions: _inheritedPermissions
35624
- };
35625
- }
35626
- hasOrganizationAccess(_user, _resource) {
35627
- return _user.organizationId === this.config.organizationId;
35628
- }
35629
- extractProjectId(_path) {
35630
- const _match = _path._match(/\/projects\/([^\/]+)/);
35631
- return _match ? _match[1] : null;
35632
- }
35633
- extractTeamId(_path) {
35634
- const _match = _path._match(/\/teams\/([^\/]+)/);
35635
- return _match ? _match[1] : null;
35636
- }
35637
- calculateInheritedPermissions(_user, _resource) {
35638
- let _inheritedPermissions = { ...this.config.defaultPermissions };
35639
- _inheritedPermissions = this.mergePermissions(_inheritedPermissions, _user.permissions);
35640
- const _sortedRoles = _user.roles.sort((a2, b) => b.priority - a2.priority);
35641
- for (const _role of _sortedRoles) {
35642
- const _level = this.config.hierarchyLevels.find((l) => l._level === _role._level);
35643
- if (_level?.inheritFromParent) {
35644
- _inheritedPermissions = this.mergePermissions(_inheritedPermissions, _role.permissions);
35645
- } else if (_level?.overrideChild) {
35646
- _inheritedPermissions = _role.permissions;
35647
- }
35648
- }
35649
- return _inheritedPermissions;
35650
- }
35651
- checkPermissionAtAllLevels(_user, _permissions, operation) {
35652
- if (this.hasPermissionAtLevel(_permissions, operation, "personal")) {
35653
- return true;
35654
- }
35655
- if (this.hasPermissionAtLevel(_permissions, operation, "team")) {
35656
- return true;
35657
- }
35658
- if (this.hasPermissionAtLevel(_permissions, operation, "project")) {
35659
- return true;
35660
- }
35661
- if (this.hasPermissionAtLevel(_permissions, operation, "organization")) {
35662
- return true;
35663
- }
35664
- return false;
35665
- }
35666
- hasPermissionAtLevel(_permissions, operation, _level) {
35667
- const operationMap = {
35668
- read: "read",
35669
- write: "write",
35670
- delete: "delete",
35671
- share: "share",
35672
- export: "export"
35673
- };
35674
- const _permissionKey = operationMap[operation];
35675
- if (!_permissionKey) {
35676
- return false;
35677
- }
35678
- const _scopes = _permissions.memory[_permissionKey] || [];
35679
- return _scopes.some((scope) => scope.type === _level);
35680
- }
35681
- mergePermissions(base, additional) {
35682
- return {
35683
- memory: {
35684
- read: [...base.memory.read || [], ...additional.memory.read || []],
35685
- write: [...base.memory.write || [], ...additional.memory.write || []],
35686
- delete: [...base.memory.delete || [], ...additional.memory.delete || []],
35687
- share: [...base.memory.share || [], ...additional.memory.share || []],
35688
- export: [...base.memory.export || [], ...additional.memory.export || []]
35689
- },
35690
- data: {
35691
- classification: [
35692
- ...base.data.classification || [],
35693
- ...additional.data.classification || []
35694
- ],
35695
- sensitivity: [...base.data.sensitivity || [], ...additional.data.sensitivity || []],
35696
- categories: [...base.data.categories || [], ...additional.data.categories || []],
35697
- tags: [...base.data.tags || [], ...additional.data.tags || []],
35698
- excludedFields: [
35699
- ...base.data.excludedFields || [],
35700
- ...additional.data.excludedFields || []
35701
- ]
35702
- },
35703
- operations: { ...base.operations, ...additional.operations },
35704
- administration: { ...base.administration, ...additional.administration }
35705
- };
35706
- }
35707
- async checkAccess(request) {
35708
- const _startTime = Date.now();
35709
- console.log(
35710
- `Access request: _user=${request.userId}, resource=${request.resource.id}, operation=${request.operation}`
35711
- );
35712
- const _cacheKey = this.generateCacheKey(request);
35713
- const _cached = this.cache.decisions.get(_cacheKey);
35714
- if (_cached && _cached.expires > /* @__PURE__ */ new Date()) {
35715
- _cached.hits++;
35716
- this.cache.hitRate++;
35717
- this.emit("accessChecked", {
35718
- request,
35719
- decision: _cached.decision,
35720
- _cached: true
35721
- });
35722
- return _cached.decision;
35723
- }
35724
- this.cache.missRate++;
35725
- const _user = this.users.get(request.userId);
35726
- if (!_user) {
35727
- console.log(`User not found: ${request.userId}`);
35728
- return this.createDeniedDecision(request, "User not found");
35729
- }
35730
- console.log(`User found: ${_user.email}, clearance: ${_user.attributes.clearanceLevel}`);
35731
- console.log(`User _permissions:`, JSON.stringify(_user._permissions.memory, null, 2));
35732
- const _restrictionCheck = await this.checkRestrictions(_user, request);
35733
- console.log(`Restriction check: passed=${_restrictionCheck.passed}`);
35734
- if (!_restrictionCheck.passed) {
35735
- console.log(`Access denied due to restrictions: ${_restrictionCheck.reason}`);
35736
- return this.createDeniedDecision(request, _restrictionCheck.reason);
35737
- }
35738
- const _permissions = await this.evaluatePermissions(_user, request);
35739
- console.log(`Evaluated _permissions:`, JSON.stringify(_permissions.data.classification, null, 2));
35740
- const _classificationCheck = await this.checkDataClassification(
35741
- _user,
35742
- request.resource,
35743
- _permissions
35744
- );
35745
- console.log(
35746
- `Resource classification:`,
35747
- JSON.stringify(request.resource.classification, null, 2)
35748
- );
35749
- console.log(`Classification check: allowed=${_classificationCheck.allowed}`);
35750
- if (!_classificationCheck.allowed) {
35751
- console.log(`Access denied due to classification: ${_classificationCheck.reason}`);
35752
- return this.createDeniedDecision(request, _classificationCheck.reason);
35753
- }
35754
- const _isPublicResource = request.resource.classification?.level === "public";
35755
- const _hasAnyReadPermission = _permissions.memory.read && _permissions.memory.read.length > 0;
35756
- console.log(
35757
- `Permission check: isPublic=${_isPublicResource}, operation=${request.operation}, hasAnyRead=${_hasAnyReadPermission}`
35758
- );
35759
- console.log(`Final _permissions:`, JSON.stringify(_permissions.memory, null, 2));
35760
- let hasPermission = false;
35761
- if (_isPublicResource && request.operation === "read" && _hasAnyReadPermission) {
35762
- hasPermission = true;
35763
- console.log(`Granted access to public resource`);
35764
- } else {
35765
- hasPermission = this.checkPermissionAtAllLevels(_user, _permissions, request.operation);
35766
- console.log(`Permission check result: ${hasPermission}`);
35767
- }
35768
- if (!hasPermission) {
35769
- console.log(`Access denied: Insufficient _permissions for operation: ${request.operation}`);
35770
- return this.createDeniedDecision(
35771
- request,
35772
- `Insufficient _permissions for operation: ${request.operation}`
35773
- );
35774
- }
35775
- const _modifications = await this.determineDataModifications(
35776
- _user,
35777
- request.resource,
35778
- _permissions
35779
- );
35780
- const decision = {
35781
- requestId: request.id,
35782
- granted: true,
35783
- _permissions,
35784
- restrictions: _restrictionCheck.activeRestrictions,
35785
- audit: this.createAuditEntry(
35786
- request,
35787
- "granted",
35788
- void 0,
35789
- _modifications,
35790
- Date.now() - _startTime
35791
- ),
35792
- ttl: this.calculateTTL(_permissions)
35793
- };
35794
- this.cacheDecision(_cacheKey, decision);
35795
- if (this.config.auditEnabled) {
35796
- this.auditLog.push(decision.audit);
35797
- this.emit("auditLogged", decision.audit);
35798
- }
35799
- this.emit("accessChecked", { request, decision, _cached: false });
35800
- return decision;
35801
- }
35802
- async checkRestrictions(_user, request) {
35803
- const activeRestrictions = [];
35804
- for (const restriction of user.restrictions) {
35805
- if (restriction.expires && restriction.expires < /* @__PURE__ */ new Date()) {
35806
- continue;
35807
- }
35808
- const _applies = await this.evaluateRestriction(restriction, _user, request);
35809
- if (_applies) {
35810
- activeRestrictions.push(restriction);
35811
- if (restriction.action === "deny") {
35812
- return {
35813
- passed: false,
35814
- reason: `Access denied by restriction: ${restriction.type}`
35815
- };
35816
- }
35817
- if (restriction.action === "require-mfa" && !request.context.mfaVerified) {
35818
- return {
35819
- passed: false,
35820
- reason: "MFA verification required"
35821
- };
35822
- }
35823
- }
35824
- }
35825
- return { passed: true, activeRestrictions };
35826
- }
35827
- async evaluateRestriction(restriction, _user, request) {
35828
- const _condition = restriction._condition;
35829
- if (_condition.temporal) {
35830
- if (!this.checkTemporalCondition(_condition.temporal)) {
35831
- return false;
35832
- }
35833
- }
35834
- if (_condition.geographical) {
35835
- if (!this.checkGeographicalCondition(_condition.geographical, request.context)) {
35836
- return false;
35837
- }
35838
- }
35839
- if (_condition.conditional) {
35840
- if (!await this.evaluateConditionalExpression(_condition.conditional, _user, request)) {
35841
- return false;
35842
- }
35843
- }
35844
- if (_condition.compliance) {
35845
- if (!this.checkComplianceRequirement(_condition.compliance, _user)) {
35846
- return false;
35847
- }
35848
- }
35849
- return true;
35850
- }
35851
- checkTemporalCondition(_condition) {
35852
- const _now = /* @__PURE__ */ new Date();
35853
- const _timezone = _condition._timezone || "UTC";
35854
- if (_condition.allowedDays) {
35855
- const _dayName = _now.toLocaleDateString("en-US", {
35856
- weekday: "lowercase",
35857
- timeZone: _timezone
35858
- });
35859
- if (!_condition.allowedDays.includes(_dayName)) {
35860
- return false;
35861
- }
35862
- }
35863
- if (_condition.allowedHours) {
35864
- const _currentTime = _now.toLocaleTimeString("en-US", {
35865
- hour12: false,
35866
- timeZone: _timezone
35867
- });
35868
- if (_currentTime < _condition.allowedHours.start || _currentTime > _condition.allowedHours.end) {
35869
- return false;
35870
- }
35871
- }
35872
- if (_condition.blackoutDates) {
35873
- const _today = _now.toDateString();
35874
- if (_condition.blackoutDates.some((date) => date.toDateString() === _today)) {
35875
- return false;
35876
- }
35877
- }
35878
- return true;
35879
- }
35880
- checkGeographicalCondition(_condition, _context) {
35881
- if (_context.location) {
35882
- if (condition.allowedCountries && !_condition.allowedCountries.includes(_context.location.country)) {
35883
- return false;
35884
- }
35885
- if (_condition.deniedCountries && condition.deniedCountries.includes(_context.location.country)) {
35886
- return false;
35887
- }
35888
- }
35889
- if (_context.ip) {
35890
- if (_condition.allowedIPs && !_condition.allowedIPs.includes(_context.ip)) {
35891
- return false;
35892
- }
35893
- if (_condition.deniedIPs && _condition.deniedIPs.includes(_context.ip)) {
35894
- return false;
35895
- }
35896
- }
35897
- if (_condition.requireVPN && !this.isVPNConnection(_context.ip)) {
35898
- return false;
35899
- }
35900
- return true;
35901
- }
35902
- async evaluateConditionalExpression(_condition, _user, request) {
35903
- ({
35904
- ...condition.variables
35905
- });
35906
- try {
35907
- return true;
35908
- } catch (_error) {
35909
- this.emit("evaluationError", { _condition, _error });
35910
- return false;
35911
- }
35912
- }
35913
- checkComplianceRequirement(_requirement, _user) {
35914
- if (_requirement.certificationExpiry && _requirement.certificationExpiry < /* @__PURE__ */ new Date()) {
35915
- return false;
35916
- }
35917
- return true;
35918
- }
35919
- async evaluatePermissions(_user, request) {
35920
- let _permissions = this.clonePermissions(user._permissions);
35921
- console.log(`Base _user _permissions:`, JSON.stringify(_permissions.data.classification, null, 2));
35922
- for (const _role of user.roles) {
35923
- _permissions = this.mergePermissions(_permissions, _role._permissions);
35924
- }
35925
- console.log(
35926
- `After _role _permissions:`,
35927
- JSON.stringify(_permissions.data.classification, null, 2)
35928
- );
35929
- _permissions = await this.applyHierarchicalPermissions(_permissions, _user, request);
35930
- console.log(
35931
- `After hierarchical _permissions:`,
35932
- JSON.stringify(_permissions.data.classification, null, 2)
35933
- );
35934
- _permissions = await this.applyResourcePermissions(_permissions, request.resource);
35935
- console.log(
35936
- `After resource _permissions:`,
35937
- JSON.stringify(_permissions.data.classification, null, 2)
35938
- );
35939
- return _permissions;
35940
- }
35941
- async applyHierarchicalPermissions(_permissions, _user, _request) {
35942
- for (const _level of this.config.hierarchyLevels) {
35943
- const _levelPermissions = await this.getHierarchyPermissions(_level, _user);
35944
- if (_level.inheritFromParent) {
35945
- _permissions = this.mergePermissions(_permissions, _levelPermissions);
35946
- }
35947
- if (_level.overrideChild) {
35948
- _permissions = this.overridePermissions(_permissions, _levelPermissions);
35949
- }
35950
- }
35951
- return _permissions;
35952
- }
35953
- async getHierarchyPermissions(_level, _user) {
35954
- if (_level.overrideChild) {
35955
- return this.config.defaultPermissions;
35956
- }
35957
- return this.createEmptyPermissions();
35958
- }
35959
- async applyResourcePermissions(_permissions, _resource) {
35960
- return _permissions;
35961
- }
35962
- async checkDataClassification(_user, resource, _permissions) {
35963
- if (!resource.classification) {
35964
- return { allowed: true };
35965
- }
35966
- const _userClassifications = _permissions.data.classification;
35967
- const _hasAccess = _userClassifications.some(
35968
- (c) => c.level === resource.classification.level || this.isHigherClassification(c.level, resource.classification.level)
35969
- );
35970
- if (!_hasAccess) {
35971
- return {
35972
- allowed: false,
35973
- reason: `Insufficient clearance for ${resource.classification.level} data`
35974
- };
35975
- }
35976
- return { allowed: true };
35977
- }
35978
- isHigherClassification(_userLevel, resourceLevel) {
35979
- const _levels = ["public", "internal", "confidential", "restricted", "secret"];
35980
- return _levels.indexOf(_userLevel) >= _levels.indexOf(resourceLevel);
35981
- }
35982
- async determineDataModifications(_user, _resource, _permissions) {
35983
- const _modifications = [];
35984
- if (_permissions.data.excludedFields) {
35985
- for (const field of _permissions.data.excludedFields) {
35986
- modifications.push({
35987
- field,
35988
- action: "masked",
35989
- reason: "Field excluded by _permissions"
35990
- });
35991
- }
35992
- }
35993
- for (const sensitivity of _permissions.data.sensitivity) {
35994
- if (sensitivity.accessLevel === "masked") {
35995
- modifications.push({
35996
- field: sensitivity.type,
35997
- action: "masked",
35998
- reason: `${sensitivity.type} requires masking`
35999
- });
36000
- } else if (sensitivity.accessLevel === "none") {
36001
- modifications.push({
36002
- field: sensitivity.type,
36003
- action: "removed",
36004
- reason: `${sensitivity.type} access denied`
36005
- });
36006
- }
36007
- }
36008
- return _modifications;
36009
- }
36010
- // ========== GDPR Compliance Methods ==========
36011
- enableGDPRCompliance(gdprConfig) {
36012
- this.gdprCompliance = gdprConfig;
36013
- this.emit("gdprEnabled", gdprConfig);
36014
- }
36015
- async validateGDPRCompliance(request, _user) {
36016
- const violations2 = [];
36017
- const requirements = [];
36018
- if (!this.gdprCompliance?.enabled) {
36019
- return { compliant: true, violations: violations2, requirements };
36020
- }
36021
- const _dataTypes = this.extractDataTypes(request.resource);
36022
- for (const dataType of _dataTypes) {
36023
- const _basis = this.gdprCompliance.dataProcessingBasis.find(
36024
- (b) => b._dataTypes.includes(dataType)
36025
- );
36026
- if (!_basis) {
36027
- violations2.push(`No legal _basis found for processing data type: ${dataType}`);
36028
- } else if (_basis.validUntil && _basis.validUntil < /* @__PURE__ */ new Date()) {
36029
- violations2.push(`Legal _basis expired for data type: ${dataType}`);
36030
- }
36031
- }
36032
- if (this.gdprCompliance.consentManagement.required) {
36033
- const _consent = await this.checkUserConsent(_user.id, _dataTypes);
36034
- if (!_consent.valid) {
36035
- violations2.push("Valid _consent required but not found");
36036
- }
36037
- }
36038
- const _retentionCheck = await this.checkRetentionCompliance(request.resource);
36039
- if (!_retentionCheck.compliant) {
36040
- violations2.push(`Data retention policy violated: ${_retentionCheck.reason}`);
36041
- }
36042
- if (this.gdprCompliance.rightToErasure && request.operation === "delete") {
36043
- requirements.push("Data must be permanently deleted per GDPR Article 17");
36044
- }
36045
- if (this.gdprCompliance.privacyByDesign) {
36046
- const _privacyCheck = this.checkPrivacyByDesign(request);
36047
- if (!_privacyCheck.compliant) {
36048
- violations2.push(`Privacy by design violation: ${_privacyCheck.issue}`);
36049
- }
36050
- }
36051
- return {
36052
- compliant: violations2.length === 0,
36053
- violations: violations2,
36054
- requirements
36055
- };
36056
- }
36057
- async handleGDPRDataSubjectRequest(type, subjectId, details) {
36058
- if (!this.gdprCompliance?.enabled) {
36059
- return { success: false, _error: "GDPR compliance not enabled" };
36060
- }
36061
- switch (type) {
36062
- case "access":
36063
- return this.handleDataAccess(subjectId);
36064
- case "rectification":
36065
- if (!this.gdprCompliance.rightToRectification) {
36066
- return { success: false, _error: "Right to rectification not enabled" };
36067
- }
36068
- return this.handleDataRectification(subjectId, details);
36069
- case "erasure":
36070
- if (!this.gdprCompliance.rightToErasure) {
36071
- return { success: false, _error: "Right to erasure not enabled" };
36072
- }
36073
- return this.handleDataErasure(subjectId);
36074
- case "portability":
36075
- if (!this.gdprCompliance.rightToPortability) {
36076
- return { success: false, _error: "Right to portability not enabled" };
36077
- }
36078
- return this.handleDataPortability(subjectId);
36079
- case "restriction":
36080
- return this.handleProcessingRestriction(subjectId, details);
36081
- default:
36082
- return { success: false, _error: "Invalid request type" };
36083
- }
36084
- }
36085
- async checkUserConsent(_userId, _dataTypes) {
36086
- return {
36087
- valid: true,
36088
- consentDate: /* @__PURE__ */ new Date(),
36089
- expiryDate: this.gdprCompliance?.consentManagement.consentExpiry ? new Date(
36090
- Date.now() + this.gdprCompliance.consentManagement.consentExpiry * 24 * 60 * 60 * 1e3
36091
- ) : void 0
36092
- };
36093
- }
36094
- async checkRetentionCompliance(_resource) {
36095
- const _policies = this.gdprCompliance?.retentionPolicies || [];
36096
- for (const policy of _policies) {
36097
- if (policy.retentionPeriod && policy.enforcementDate) {
36098
- const _cutoffDate = new Date(
36099
- policy.enforcementDate.getTime() + policy.retentionPeriod * 24 * 60 * 60 * 1e3
36100
- );
36101
- if (/* @__PURE__ */ new Date() > _cutoffDate) {
36102
- return {
36103
- compliant: false,
36104
- reason: `Data exceeds retention period of ${policy.retentionPeriod} days`
36105
- };
36106
- }
36107
- }
36108
- }
36109
- return { compliant: true };
36110
- }
36111
- checkPrivacyByDesign(request) {
36112
- if (request.operation === "read" && !request.context?.mfaVerified) {
36113
- return {
36114
- compliant: false,
36115
- issue: "Multi-factor authentication required for data access"
36116
- };
36117
- }
36118
- return { compliant: true };
36119
- }
36120
- async handleDataAccess(subjectId) {
36121
- try {
36122
- const _userData = this.users.get(subjectId);
36123
- if (!_userData) {
36124
- return { success: false, _error: "User data not found" };
36125
- }
36126
- const _exportData = {
36127
- personalData: _userData,
36128
- accessLogs: this.auditLog.filter((log) => log.userId === subjectId),
36129
- processingActivities: this.getProcessingActivities(subjectId)
36130
- };
36131
- return { success: true, data: _exportData };
36132
- } catch (_error) {
36133
- return { success: false, _error: "Failed to retrieve data" };
36134
- }
36135
- }
36136
- async handleDataRectification(subjectId, updates) {
36137
- try {
36138
- await this.updateUser(subjectId, updates);
36139
- return { success: true };
36140
- } catch (_error) {
36141
- return { success: false, _error: "Failed to update data" };
36142
- }
36143
- }
36144
- async handleDataErasure(subjectId) {
36145
- try {
36146
- await this.deleteUser(subjectId);
36147
- this.auditLog = this.auditLog.map(
36148
- (entry) => entry.userId === subjectId ? { ...entry, _userId: "ANONYMIZED" } : entry
36149
- );
36150
- return { success: true };
36151
- } catch (_error) {
36152
- return { success: false, _error: "Failed to erase data" };
36153
- }
36154
- }
36155
- async handleDataPortability(subjectId) {
36156
- const _accessResult = await this.handleDataAccess(subjectId);
36157
- if (!_accessResult.success) {
36158
- return _accessResult;
36159
- }
36160
- const _portableData = {
36161
- format: "JSON",
36162
- version: "1.0",
36163
- exported: (/* @__PURE__ */ new Date()).toISOString(),
36164
- data: _accessResult.data
36165
- };
36166
- return { success: true, data: _portableData };
36167
- }
36168
- async handleProcessingRestriction(subjectId, details) {
36169
- const _user = this.users.get(subjectId);
36170
- if (!_user) {
36171
- return { success: false, _error: "User not found" };
36172
- }
36173
- const restriction = {
36174
- type: "gdpr_processing_restriction",
36175
- reason: details.reason || "Data subject requested processing restriction",
36176
- _startTime: /* @__PURE__ */ new Date(),
36177
- conditions: details.conditions || []
36178
- };
36179
- _user.restrictions = _user.restrictions || [];
36180
- user.restrictions.push(restriction);
36181
- return { success: true };
36182
- }
36183
- // ========== HIPAA Compliance Methods ==========
36184
- enableHIPAACompliance(hipaaConfig) {
36185
- this.hipaaCompliance = hipaaConfig;
36186
- this.emit("hipaaEnabled", hipaaConfig);
36187
- }
36188
- async validateHIPAACompliance(request, _user) {
36189
- const violations2 = [];
36190
- const requirements = [];
36191
- if (!this.hipaaCompliance?.enabled) {
36192
- return { compliant: true, violations: violations2, requirements };
36193
- }
36194
- const _isPHI = this.isPHIData(request.resource);
36195
- if (!_isPHI) {
36196
- return { compliant: true, violations: violations2, requirements };
36197
- }
36198
- if (this.hipaaCompliance.phi.minimumNecessary && request.operation === "read") {
36199
- const _minimumCheck = this.checkMinimumNecessary(request, _user);
36200
- if (!_minimumCheck.compliant) {
36201
- violations2.push(`Minimum necessary standard violated: ${_minimumCheck.reason}`);
36202
- }
36203
- }
36204
- if (this.hipaaCompliance.technicalSafeguards.accessControl) {
36205
- const _accessControlCheck = this.checkHIPAAAccessControl(_user, request);
36206
- if (!_accessControlCheck.compliant) {
36207
- violations2.push(`HIPAA access control violation: ${_accessControlCheck.reason}`);
36208
- }
36209
- }
36210
- if (this.hipaaCompliance.auditControls) {
36211
- requirements.push("All PHI access must be logged per HIPAA Security Rule");
36212
- }
36213
- if (this.hipaaCompliance.technicalSafeguards.encryption.atRest && request.operation === "write") {
36214
- requirements.push("Data must be encrypted at rest per HIPAA Security Rule");
36215
- }
36216
- if (this.hipaaCompliance.technicalSafeguards.encryption.inTransit) {
36217
- requirements.push("Data transmission must be encrypted per HIPAA Security Rule");
36218
- }
36219
- if (!request.context?.mfaVerified) {
36220
- violations2.push("Multi-factor authentication required for PHI access");
36221
- }
36222
- return {
36223
- compliant: violations2.length === 0,
36224
- violations: violations2,
36225
- requirements
36226
- };
36227
- }
36228
- async handleHIPAABreach(breachDetails) {
36229
- if (!this.hipaaCompliance?.enabled || !this.hipaaCompliance.breachNotification.enabled) {
36230
- return { success: false, _error: "HIPAA breach notification not enabled" };
36231
- }
36232
- const notifications = [];
36233
- try {
36234
- if (breachDetails.individualsAffected > 500) {
36235
- notifications.push("HHS Secretary notified within 60 days");
36236
- notifications.push("Media notification required");
36237
- }
36238
- if (this.hipaaCompliance.breachNotification.individuals) {
36239
- notifications.push(
36240
- `${breachDetails.individualsAffected} individuals must be notified within 60 days`
36241
- );
36242
- }
36243
- const auditEntry = {
36244
- id: crypto3.randomUUID(),
36245
- timestamp: /* @__PURE__ */ new Date(),
36246
- _userId: "SYSTEM",
36247
- action: "HIPAA_BREACH_REPORTED",
36248
- resource: {
36249
- type: "configuration",
36250
- id: "breach_notification"
36251
- },
36252
- decision: "granted",
36253
- reason: breachDetails.description,
36254
- _context: {
36255
- sessionId: "breach_notification"
36256
- },
36257
- _modifications: []
36258
- };
36259
- this.auditLog.push(auditEntry);
36260
- this.emit("hipaaBreachReported", {
36261
- breachDetails,
36262
- notifications,
36263
- auditEntry
36264
- });
36265
- return { success: true, notifications };
36266
- } catch (_error) {
36267
- return { success: false, _error: "Failed to process HIPAA breach notification" };
36268
- }
36269
- }
36270
- isPHIData(resource) {
36271
- this.hipaaCompliance?.phi.identifiers || [];
36272
- return resource.classification?.level === "confidential" || resource.path?.includes("/phi/") || phiIdentifiers.some((identifier) => resource.path?.includes(identifier));
36273
- }
36274
- checkMinimumNecessary(request, _user) {
36275
- const _hasFullPHIAccess = _user.roles.some(
36276
- (_role) => _role.name.includes("Physician") || _role.name.includes("Nurse") || role.name.includes("Admin")
36277
- );
36278
- if (!_hasFullPHIAccess && request.operation === "read") {
36279
- return {
36280
- compliant: false,
36281
- reason: "User _role does not justify full PHI access - minimum necessary standard"
36282
- };
36283
- }
36284
- return { compliant: true };
36285
- }
36286
- checkHIPAAAccessControl(_user, _request) {
36287
- const _clearanceLevel = _user.attributes._clearanceLevel;
36288
- if (_clearanceLevel !== "confidential" && _clearanceLevel !== "secret") {
36289
- return {
36290
- compliant: false,
36291
- reason: "Insufficient clearance _level for PHI access"
36292
- };
36293
- }
36294
- const _hasRequiredTraining = _user.attributes.customAttributes?.hipaaTrainingCompleted;
36295
- if (!_hasRequiredTraining) {
36296
- return {
36297
- compliant: false,
36298
- reason: "HIPAA training required before PHI access"
36299
- };
36300
- }
36301
- return { compliant: true };
36302
- }
36303
- extractDataTypes(resource) {
36304
- const _dataTypes = [];
36305
- if (resource._path) {
36306
- if (resource.path.includes("/personal/")) {
36307
- _dataTypes.push("personal");
36308
- }
36309
- if (resource.path.includes("/financial/")) {
36310
- _dataTypes.push("financial");
36311
- }
36312
- if (resource.path.includes("/health/")) {
36313
- _dataTypes.push("health");
36314
- }
36315
- if (resource.path.includes("/phi/")) {
36316
- _dataTypes.push("phi");
36317
- }
36318
- }
36319
- return _dataTypes;
36320
- }
36321
- getProcessingActivities(_userId) {
36322
- return this.auditLog.filter((log) => log.userId === _userId).map((log) => ({
36323
- activity: log.action,
36324
- timestamp: log.timestamp,
36325
- resource: log.resource,
36326
- purpose: "Memory system access"
36327
- }));
36328
- }
36329
- // ========== User & Role Management ==========
36330
- async createUser(_userData) {
36331
- const _userId = this.generateUserId();
36332
- const _user = {
36333
- ..._userData,
36334
- id: _userId
36335
- };
36336
- this.users.set(_userId, _user);
36337
- this.emit("userCreated", { _userId, _user });
36338
- return _userId;
36339
- }
36340
- async updateUser(_userId, updates) {
36341
- const _user = this.users.get(_userId);
36342
- if (!_user) {
36343
- throw new Error(`User not found: ${_userId}`);
36344
- }
36345
- const _updatedUser = { ..._user, ...updates };
36346
- this.users.set(_userId, _updatedUser);
36347
- this.invalidateUserCache(_userId);
36348
- this.emit("userUpdated", { _userId, updates });
36349
- }
36350
- async deleteUser(_userId) {
36351
- const _user = this.users.get(_userId);
36352
- if (!_user) {
36353
- throw new Error(`User not found: ${_userId}`);
36354
- }
36355
- this.users.delete(_userId);
36356
- this.invalidateUserCache(_userId);
36357
- this.emit("userDeleted", { _userId });
36358
- }
36359
- async createRole(_roleData) {
36360
- const _roleId = this.generateRoleId();
36361
- const _role = {
36362
- ..._roleData,
36363
- id: _roleId
36364
- };
36365
- this.roles.set(_roleId, _role);
36366
- this.emit("roleCreated", { _roleId, _role });
36367
- return _roleId;
36368
- }
36369
- async assignRole(_userId, _roleId) {
36370
- const _user = this.users.get(_userId);
36371
- const _role = this.roles.get(_roleId);
36372
- if (!_user) {
36373
- throw new Error(`User not found: ${_userId}`);
36374
- }
36375
- if (!_role) {
36376
- throw new Error(`Role not found: ${_roleId}`);
36377
- }
36378
- if (!_user.roles.some((r) => r.id === _roleId)) {
36379
- user.roles.push(_role);
36380
- this.invalidateUserCache(_userId);
36381
- this.emit("roleAssigned", { _userId, _roleId });
36382
- }
36383
- }
36384
- async revokeRole(_userId, _roleId) {
36385
- const _user = this.users.get(_userId);
36386
- if (!_user) {
36387
- throw new Error(`User not found: ${_userId}`);
36388
- }
36389
- _user.roles = _user.roles.filter((r) => r.id !== _roleId);
36390
- this.invalidateUserCache(_userId);
36391
- this.emit("roleRevoked", { _userId, _roleId });
36392
- }
36393
- // ========== Utility Methods ==========
36394
- initializeCache() {
36395
- return {
36396
- decisions: /* @__PURE__ */ new Map(),
36397
- maxSize: 1e4,
36398
- ttl: 3e5,
36399
- // 5 minutes default
36400
- hitRate: 0,
36401
- missRate: 0
36402
- };
36403
- }
36404
- initializeDefaultRoles() {
36405
- const defaultRoles = [
36406
- {
36407
- name: "admin",
36408
- _level: "system",
36409
- _permissions: this.createAdminPermissions(),
36410
- priority: 100,
36411
- inherited: false
36412
- },
36413
- {
36414
- name: "_user",
36415
- _level: "system",
36416
- _permissions: this.createUserPermissions(),
36417
- priority: 10,
36418
- inherited: true
36419
- },
36420
- {
36421
- name: "guest",
36422
- _level: "system",
36423
- _permissions: this.createGuestPermissions(),
36424
- priority: 1,
36425
- inherited: true
36426
- }
36427
- ];
36428
- for (const roleData of defaultRoles) {
36429
- this.createRole(roleData);
36430
- }
36431
- }
36432
- createAdminPermissions() {
36433
- return {
36434
- memory: {
36435
- read: [{ type: "global" }],
36436
- write: [{ type: "global" }],
36437
- delete: [{ type: "global" }],
36438
- share: [{ type: "global" }],
36439
- export: [{ type: "global" }]
36440
- },
36441
- data: {
36442
- classification: [
36443
- {
36444
- _level: "secret",
36445
- handling: "standard",
36446
- retention: { duration: 365 }
36447
- }
36448
- ],
36449
- sensitivity: [],
36450
- categories: ["*"],
36451
- tags: ["*"]
36452
- },
36453
- operations: {
36454
- query: { maxResults: void 0, maxDepth: void 0 },
36455
- analyze: {
36456
- algorithms: ["*"],
36457
- mlModels: ["*"],
36458
- aggregations: ["*"],
36459
- exports: [{ format: "json" }, { format: "csv" }]
36460
- },
36461
- modify: {
36462
- create: true,
36463
- update: true,
36464
- delete: true,
36465
- bulkOperations: true
36466
- },
36467
- integrate: {
36468
- apis: ["*"],
36469
- webhooks: ["*"],
36470
- external: []
36471
- }
36472
- },
36473
- administration: {
36474
- manageUsers: true,
36475
- manageRoles: true,
36476
- managePermissions: true,
36477
- viewAudit: true,
36478
- configureSystem: true,
36479
- emergencyAccess: true
36480
- }
36481
- };
36482
- }
36483
- createUserPermissions() {
36484
- return {
36485
- memory: {
36486
- read: [{ type: "personal" }, { type: "team" }, { type: "project" }],
36487
- write: [{ type: "personal" }, { type: "team" }],
36488
- delete: [{ type: "personal" }],
36489
- share: [{ type: "personal" }],
36490
- export: [{ type: "personal" }]
36491
- },
36492
- data: {
36493
- classification: [
36494
- {
36495
- _level: "internal",
36496
- handling: "standard",
36497
- retention: { duration: 90 }
36498
- }
36499
- ],
36500
- sensitivity: [
36501
- {
36502
- type: "pii",
36503
- accessLevel: "masked",
36504
- auditRequired: true
36505
- }
36506
- ],
36507
- categories: ["general"],
36508
- tags: []
36509
- },
36510
- operations: {
36511
- query: { maxResults: 1e3, maxDepth: 3 },
36512
- analyze: {
36513
- algorithms: ["basic"],
36514
- mlModels: [],
36515
- aggregations: ["count", "sum", "average"],
36516
- exports: [{ format: "json", maxSize: 10 }]
36517
- },
36518
- modify: {
36519
- create: true,
36520
- update: true,
36521
- delete: false,
36522
- bulkOperations: false
36523
- },
36524
- integrate: {
36525
- apis: [],
36526
- webhooks: [],
36527
- external: []
36528
- }
36529
- },
36530
- administration: {
36531
- manageUsers: false,
36532
- manageRoles: false,
36533
- managePermissions: false,
36534
- viewAudit: false,
36535
- configureSystem: false,
36536
- emergencyAccess: false
36537
- }
36538
- };
36539
- }
36540
- createGuestPermissions() {
36541
- return {
36542
- memory: {
36543
- read: [{ type: "personal", timeRange: { rolling: 7 } }],
36544
- write: [],
36545
- delete: [],
36546
- share: [],
36547
- export: []
36548
- },
36549
- data: {
36550
- classification: [
36551
- {
36552
- _level: "public",
36553
- handling: "standard",
36554
- retention: { duration: 7 }
36555
- }
36556
- ],
36557
- sensitivity: [
36558
- {
36559
- type: "pii",
36560
- accessLevel: "none",
36561
- auditRequired: true
36562
- }
36563
- ],
36564
- categories: ["public"],
36565
- tags: []
36566
- },
36567
- operations: {
36568
- query: { maxResults: 100, maxDepth: 1, timeLimit: 10 },
36569
- analyze: {
36570
- algorithms: [],
36571
- mlModels: [],
36572
- aggregations: ["count"],
36573
- exports: []
36574
- },
36575
- modify: {
36576
- create: false,
36577
- update: false,
36578
- delete: false,
36579
- bulkOperations: false
36580
- },
36581
- integrate: {
36582
- apis: [],
36583
- webhooks: [],
36584
- external: []
36585
- }
36586
- },
36587
- administration: {
36588
- manageUsers: false,
36589
- manageRoles: false,
36590
- managePermissions: false,
36591
- viewAudit: false,
36592
- configureSystem: false,
36593
- emergencyAccess: false
36594
- }
36595
- };
36596
- }
36597
- createEmptyPermissions() {
36598
- return {
36599
- memory: {
36600
- read: [],
36601
- write: [],
36602
- delete: [],
36603
- share: [],
36604
- export: []
36605
- },
36606
- data: {
36607
- classification: [],
36608
- sensitivity: [],
36609
- categories: [],
36610
- tags: []
36611
- },
36612
- operations: {
36613
- query: Record,
36614
- analyze: { algorithms: [], mlModels: [], aggregations: [], exports: [] },
36615
- modify: {
36616
- create: false,
36617
- update: false,
36618
- delete: false,
36619
- bulkOperations: false
36620
- },
36621
- integrate: {
36622
- apis: [],
36623
- webhooks: [],
36624
- external: []
36625
- }
36626
- },
36627
- administration: {
36628
- manageUsers: false,
36629
- manageRoles: false,
36630
- managePermissions: false,
36631
- viewAudit: false,
36632
- configureSystem: false,
36633
- emergencyAccess: false
36634
- }
36635
- };
36636
- }
36637
- clonePermissions(_permissions) {
36638
- return JSON.parse(JSON.stringify(_permissions));
36639
- }
36640
- overridePermissions(_base, override) {
36641
- return override;
36642
- }
36643
- generateCacheKey(request) {
36644
- return crypto3.createHash("sha256").update(
36645
- `${request.userId}:${request.resource.type}:${request.resource.id}:${request.operation}`
36646
- ).digest("hex");
36647
- }
36648
- cacheDecision(_key, decision) {
36649
- if (this.cache.decisions.size >= this.cache.maxSize) {
36650
- const _firstKey = this.cache.decisions.keys().next().value;
36651
- this.cache.decisions.delete(_firstKey);
36652
- }
36653
- this.cache.decisions.set(_key, {
36654
- decision,
36655
- expires: new Date(Date.now() + (decision.ttl || this.cache.ttl)),
36656
- hits: 0,
36657
- created: /* @__PURE__ */ new Date()
36658
- });
36659
- }
36660
- invalidateUserCache(_userId) {
36661
- for (const [key, _cached] of this.cache.decisions) {
36662
- if (cached.decision.audit?.userId === _userId) {
36663
- this.cache.decisions.delete(key);
36664
- }
36665
- }
36666
- }
36667
- calculateTTL(_permissions) {
36668
- if (_permissions.administration.emergencyAccess) {
36669
- return 6e4;
36670
- }
36671
- if (_permissions.data.classification.some((c) => c.level === "secret")) {
36672
- return 18e4;
36673
- }
36674
- return 3e5;
36675
- }
36676
- createDeniedDecision(_request, reason) {
36677
- return {
36678
- requestId: _request.id,
36679
- granted: false,
36680
- reason,
36681
- audit: this.createAuditEntry(_request, "denied", reason)
36682
- };
36683
- }
36684
- createAuditEntry(request, decision, reason, _modifications, duration) {
36685
- return {
36686
- id: this.generateAuditId(),
36687
- timestamp: /* @__PURE__ */ new Date(),
36688
- _userId: request.userId,
36689
- action: request.operation,
36690
- resource: request.resource,
36691
- decision,
36692
- reason,
36693
- _context: request.context,
36694
- duration,
36695
- _modifications
36696
- };
36697
- }
36698
- isVPNConnection(_ip) {
36699
- return false;
36700
- }
36701
- generateUserId() {
36702
- return `user_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
36703
- }
36704
- generateRoleId() {
36705
- return `role_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
36706
- }
36707
- generateAuditId() {
36708
- return `audit_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
36709
- }
36710
- generateEncryptionKey() {
36711
- return crypto3.randomBytes(32);
36712
- }
36713
- // ========== Public API ==========
36714
- getUser(_userId) {
36715
- return this.users.get(_userId);
36716
- }
36717
- getRole(_roleId) {
36718
- return this.roles.get(_roleId);
36719
- }
36720
- getAuditLog(filters) {
36721
- let logs = [...this.auditLog];
36722
- if (filters?.userId) {
36723
- logs = logs.filter((l) => l.userId === filters.userId);
36724
- }
36725
- if (filters?.startDate) {
36726
- logs = logs.filter((l) => l.timestamp >= filters.startDate);
36727
- }
36728
- if (filters?.endDate) {
36729
- logs = logs.filter((l) => l.timestamp <= filters.endDate);
36730
- }
36731
- if (filters?.decision) {
36732
- logs = logs.filter((l) => l.decision === filters.decision);
36733
- }
36734
- return logs;
36735
- }
36736
- getCacheStatistics() {
36737
- const _total = this.cache.hitRate + this.cache.missRate;
36738
- return {
36739
- size: this.cache.decisions.size,
36740
- hitRate: this.cache.hitRate,
36741
- missRate: this.cache.missRate,
36742
- efficiency: _total > 0 ? this.cache.hitRate / _total : 0
36743
- };
36744
- }
36745
- async exportConfiguration() {
36746
- return JSON.stringify(
36747
- {
36748
- config: this.config,
36749
- roles: Array.from(this.roles.entries()),
36750
- statistics: this.getCacheStatistics(),
36751
- exportedAt: (/* @__PURE__ */ new Date()).toISOString()
36752
- },
36753
- null,
36754
- 2
36755
- );
36756
- }
36757
- async importConfiguration(data2) {
36758
- const _imported = JSON.parse(data2);
36759
- if (_imported.config) {
36760
- this.config = _imported.config;
36761
- }
36762
- if (_imported.roles) {
36763
- this.roles = new Map(_imported.roles);
36764
- }
36765
- this.emit("configurationImported", { importedAt: /* @__PURE__ */ new Date() });
36766
- }
36767
- };
36768
- var PolicyEngine = class {
36769
- config;
36770
- constructor(_config) {
36771
- this._config = _config;
36772
- }
36773
- evaluatePolicy(_policy, _context) {
36774
- return true;
36775
- }
36776
- validatePolicy(_policy) {
36777
- return { valid: true };
36778
- }
36779
- };
36780
35562
  var EnterpriseAuthManager = class extends EventEmitter {
36781
35563
  providers;
36782
35564
  users;
@@ -37494,8 +36276,8 @@ var EnterpriseAuthManager = class extends EventEmitter {
37494
36276
  if (!rule.actions.includes(action) && !rule.actions.includes("*")) {
37495
36277
  return false;
37496
36278
  }
37497
- for (const condition2 of rule.conditions) {
37498
- if (!this.conditionMatches(condition2, _user, resource, context2)) {
36279
+ for (const condition of rule.conditions) {
36280
+ if (!this.conditionMatches(condition, _user, resource, context2)) {
37499
36281
  return false;
37500
36282
  }
37501
36283
  }
@@ -37518,25 +36300,25 @@ var EnterpriseAuthManager = class extends EventEmitter {
37518
36300
  resourceMatches(_ruleResource, resource) {
37519
36301
  return this.matchesPattern(_ruleResource.pattern, resource);
37520
36302
  }
37521
- conditionMatches(condition2, _user, resource, context2) {
36303
+ conditionMatches(condition, _user, resource, context2) {
37522
36304
  let value2;
37523
- switch (condition2.context) {
36305
+ switch (condition.context) {
37524
36306
  case "_user":
37525
- value2 = _user[condition2.attribute] || user.attributes[condition2.attribute];
36307
+ value2 = _user[condition.attribute] || user.attributes[condition.attribute];
37526
36308
  break;
37527
36309
  case "resource":
37528
36310
  value2 = resource;
37529
36311
  break;
37530
36312
  case "environment":
37531
- value2 = this.getEnvironmentValue(condition2.attribute);
36313
+ value2 = this.getEnvironmentValue(condition.attribute);
37532
36314
  break;
37533
36315
  case "_session":
37534
- value2 = context2?.metadata?.[condition2.attribute];
36316
+ value2 = context2?.metadata?.[condition.attribute];
37535
36317
  break;
37536
36318
  default:
37537
- value2 = context2?.metadata?.[condition2.attribute];
36319
+ value2 = context2?.metadata?.[condition.attribute];
37538
36320
  }
37539
- return this.compareValues(value2, condition2.operator, condition2.value);
36321
+ return this.compareValues(value2, condition.operator, condition.value);
37540
36322
  }
37541
36323
  hasAttribute(_user, _attributeName, expectedAttributes) {
37542
36324
  if (!expectedAttributes) {
@@ -37602,12 +36384,12 @@ var EnterpriseAuthManager = class extends EventEmitter {
37602
36384
  return `${prefix}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
37603
36385
  }
37604
36386
  generateTOTPSecret() {
37605
- return crypto3.randomBytes(20).toString("hex");
36387
+ return crypto2.randomBytes(20).toString("hex");
37606
36388
  }
37607
36389
  generateBackupCodes() {
37608
36390
  return Array.from(
37609
36391
  { length: 8 },
37610
- () => crypto3.randomBytes(4).toString("hex").toUpperCase()
36392
+ () => crypto2.randomBytes(4).toString("hex").toUpperCase()
37611
36393
  );
37612
36394
  }
37613
36395
  generateQRCode(_email, _secret) {
@@ -37997,17 +36779,17 @@ var EnterpriseSecurityManager = class extends EventEmitter {
37997
36779
  }
37998
36780
  };
37999
36781
  }
38000
- evaluateDataCondition(condition2, data2, context2) {
38001
- const _value = this.getFieldValue(condition2.field, data2, context2);
38002
- switch (condition2.operator) {
36782
+ evaluateDataCondition(condition, data2, context2) {
36783
+ const _value = this.getFieldValue(condition.field, data2, context2);
36784
+ switch (condition.operator) {
38003
36785
  case "equals":
38004
- return _value === condition2._value;
36786
+ return _value === condition._value;
38005
36787
  case "contains":
38006
- return String(_value).includes(String(condition2._value));
36788
+ return String(_value).includes(String(condition._value));
38007
36789
  case "matches":
38008
- return new RegExp(String(condition2._value)).test(String(_value));
36790
+ return new RegExp(String(condition._value)).test(String(_value));
38009
36791
  case "in":
38010
- return Array.isArray(condition2._value) && condition2._value.includes(_value);
36792
+ return Array.isArray(condition._value) && condition._value.includes(_value);
38011
36793
  default:
38012
36794
  return false;
38013
36795
  }
@@ -38028,8 +36810,8 @@ var EnterpriseSecurityManager = class extends EventEmitter {
38028
36810
  return _value;
38029
36811
  }
38030
36812
  async validateEncryptedData(encryptedData) {
38031
- const calculatedChecksum = crypto3.createHash("sha256").update(Buffer.from(encryptedData.ciphertext, "base64")).digest("hex");
38032
- if (!crypto3.timingSafeEqual(
36813
+ const calculatedChecksum = crypto2.createHash("sha256").update(Buffer.from(encryptedData.ciphertext, "base64")).digest("hex");
36814
+ if (!crypto2.timingSafeEqual(
38033
36815
  Buffer.from(calculatedChecksum, "hex"),
38034
36816
  Buffer.from(encryptedData.metadata._checksum, "hex")
38035
36817
  )) {
@@ -38057,8 +36839,8 @@ var EnterpriseSecurityManager = class extends EventEmitter {
38057
36839
  }
38058
36840
  }
38059
36841
  async verifyDataIntegrity(encryptedData) {
38060
- const calculatedChecksum = crypto3.createHash("sha256").update(Buffer.from(encryptedData.ciphertext, "base64")).digest("hex");
38061
- return crypto3.timingSafeEqual(
36842
+ const calculatedChecksum = crypto2.createHash("sha256").update(Buffer.from(encryptedData.ciphertext, "base64")).digest("hex");
36843
+ return crypto2.timingSafeEqual(
38062
36844
  Buffer.from(calculatedChecksum, "hex"),
38063
36845
  Buffer.from(encryptedData.metadata._checksum, "hex")
38064
36846
  );
@@ -38185,7 +36967,7 @@ var EnterpriseSecurityManager = class extends EventEmitter {
38185
36967
  this.emit("securityError", { type, _error, context: context2 });
38186
36968
  }
38187
36969
  generateTransferId() {
38188
- return crypto3.randomBytes(16).toString("hex");
36970
+ return crypto2.randomBytes(16).toString("hex");
38189
36971
  }
38190
36972
  };
38191
36973
  var KeyManager = class extends EventEmitter {
@@ -38193,15 +36975,15 @@ var KeyManager = class extends EventEmitter {
38193
36975
  super();
38194
36976
  this.config = config;
38195
36977
  this.currentKeyIdValue = `key_${Date.now()}`;
38196
- this.dataKeys.set(this.currentKeyIdValue, crypto3.randomBytes(32));
38197
- this.signingKeyPair = crypto3.generateKeyPairSync("ed25519");
36978
+ this.dataKeys.set(this.currentKeyIdValue, crypto2.randomBytes(32));
36979
+ this.signingKeyPair = crypto2.generateKeyPairSync("ed25519");
38198
36980
  }
38199
36981
  currentKeyIdValue;
38200
36982
  dataKeys = /* @__PURE__ */ new Map();
38201
36983
  signingKeyPair = null;
38202
36984
  async rotateKey(keyId) {
38203
36985
  const id = keyId ?? `key_${Date.now()}`;
38204
- this.dataKeys.set(id, crypto3.randomBytes(32));
36986
+ this.dataKeys.set(id, crypto2.randomBytes(32));
38205
36987
  this.currentKeyIdValue = id;
38206
36988
  this.emit("keyRotated", id);
38207
36989
  }
@@ -38226,11 +37008,11 @@ var KeyManager = class extends EventEmitter {
38226
37008
  async sign(data2) {
38227
37009
  if (!this.signingKeyPair)
38228
37010
  throw new SecurityError("NO_SIGNING_KEY", "signing key missing");
38229
- return crypto3.sign(null, data2, this.signingKeyPair.privateKey);
37011
+ return crypto2.sign(null, data2, this.signingKeyPair.privateKey);
38230
37012
  }
38231
37013
  async verifySignature(data2, signature) {
38232
37014
  if (!this.signingKeyPair) return false;
38233
- return crypto3.verify(null, data2, this.signingKeyPair.publicKey, signature);
37015
+ return crypto2.verify(null, data2, this.signingKeyPair.publicKey, signature);
38234
37016
  }
38235
37017
  async getKeyHealth() {
38236
37018
  return "low";
@@ -38249,13 +37031,13 @@ var EncryptionEngine = class {
38249
37031
  );
38250
37032
  if (key.length !== 32)
38251
37033
  throw new SecurityError("KEY_SIZE", "key must be 32 bytes");
38252
- const iv = crypto3.randomBytes(12);
38253
- const cipher2 = crypto3.createCipheriv("aes-256-gcm", key, iv);
37034
+ const iv = crypto2.randomBytes(12);
37035
+ const cipher2 = crypto2.createCipheriv("aes-256-gcm", key, iv);
38254
37036
  if (opts?.aad) cipher2.setAAD(Buffer.from(opts.aad, "utf8"));
38255
37037
  const plain = Buffer.from(JSON.stringify(data2), "utf8");
38256
37038
  const ct = Buffer.concat([cipher2.update(plain), cipher2.final()]);
38257
37039
  const tag = cipher2.getAuthTag();
38258
- const checksum = crypto3.createHash("sha256").update(ct).digest("hex");
37040
+ const checksum = crypto2.createHash("sha256").update(ct).digest("hex");
38259
37041
  return {
38260
37042
  ciphertext: ct.toString("base64"),
38261
37043
  iv: iv.toString("base64"),
@@ -38278,7 +37060,7 @@ var EncryptionEngine = class {
38278
37060
  const iv = Buffer.from(enc.iv, "base64");
38279
37061
  const tag = Buffer.from(enc._tag, "base64");
38280
37062
  const ct = Buffer.from(enc.ciphertext, "base64");
38281
- const decipher = crypto3.createDecipheriv("aes-256-gcm", key, iv);
37063
+ const decipher = crypto2.createDecipheriv("aes-256-gcm", key, iv);
38282
37064
  if (opts?.aad) decipher.setAAD(Buffer.from(opts.aad, "utf8"));
38283
37065
  decipher.setAuthTag(tag);
38284
37066
  const plain = Buffer.concat([decipher.update(ct), decipher.final()]);
@@ -38421,7 +37203,7 @@ var EnterpriseAuditLogger = class extends EventEmitter {
38421
37203
  this.hashChain = [];
38422
37204
  this.complianceRequirements = /* @__PURE__ */ new Map();
38423
37205
  this.realTimeMonitors = /* @__PURE__ */ new Set();
38424
- this.encryptionKey = encryptionKey ? Buffer.from(encryptionKey, "hex") : crypto3.randomBytes(32);
37206
+ this.encryptionKey = encryptionKey ? Buffer.from(encryptionKey, "hex") : crypto2.randomBytes(32);
38425
37207
  this.immutableStorage = new ImmutableAuditStorage();
38426
37208
  this.retentionPolicies = /* @__PURE__ */ new Map([
38427
37209
  ["public", 90],
@@ -38671,7 +37453,7 @@ var EnterpriseAuditLogger = class extends EventEmitter {
38671
37453
  resource: _event.resource,
38672
37454
  result: _event.result
38673
37455
  });
38674
- const _hmac = crypto3.createHmac("sha256", this.encryptionKey);
37456
+ const _hmac = crypto2.createHmac("sha256", this.encryptionKey);
38675
37457
  hmac.update(_data);
38676
37458
  return _hmac.digest("hex");
38677
37459
  }
@@ -38685,7 +37467,7 @@ var EnterpriseAuditLogger = class extends EventEmitter {
38685
37467
  ..._event,
38686
37468
  _hash: void 0
38687
37469
  });
38688
- return crypto3.createHash("sha256").update(_data).digest("hex");
37470
+ return crypto2.createHash("sha256").update(_data).digest("hex");
38689
37471
  }
38690
37472
  async checkCompliance(_event) {
38691
37473
  for (const requirement of Array.from(
@@ -38964,7 +37746,7 @@ var EnterpriseAuditLogger = class extends EventEmitter {
38964
37746
  return "US";
38965
37747
  }
38966
37748
  getDeviceId() {
38967
- return `device_${crypto3.randomBytes(8).toString("hex")}`;
37749
+ return `device_${crypto2.randomBytes(8).toString("hex")}`;
38968
37750
  }
38969
37751
  calculateRiskScore(metadata) {
38970
37752
  let score = 0.1;
@@ -39126,7 +37908,7 @@ var FeatureFlagController = class {
39126
37908
  healthHistory = [];
39127
37909
  MAX_HISTORY = 100;
39128
37910
  monitoringInterval;
39129
- hashSalt = crypto3__default.randomBytes(16).toString("hex");
37911
+ hashSalt = crypto2__default.randomBytes(16).toString("hex");
39130
37912
  constructor(initialConfig) {
39131
37913
  this.config = this.mergeWithDefaults(initialConfig || {});
39132
37914
  this.status = this.initializeStatus();
@@ -39311,7 +38093,7 @@ var FeatureFlagController = class {
39311
38093
  if (this.userCache.has(cacheKey)) {
39312
38094
  return this.userCache.get(cacheKey);
39313
38095
  }
39314
- const hash = crypto3__default.createHash("sha256").update(`${userId}:${this.hashSalt}`).digest("hex");
38096
+ const hash = crypto2__default.createHash("sha256").update(`${userId}:${this.hashSalt}`).digest("hex");
39315
38097
  const hashValue = parseInt(hash.slice(0, 8), 16);
39316
38098
  const bucket = hashValue % 100;
39317
38099
  const inRollout = bucket < this.config.rolloutPercentage;
@@ -39326,7 +38108,7 @@ var FeatureFlagController = class {
39326
38108
  if (this.commandCache.has(cacheKey)) {
39327
38109
  return this.commandCache.get(cacheKey);
39328
38110
  }
39329
- const hash = crypto3__default.createHash("sha256").update(`${commandName}:${this.hashSalt}`).digest("hex");
38111
+ const hash = crypto2__default.createHash("sha256").update(`${commandName}:${this.hashSalt}`).digest("hex");
39330
38112
  const hashValue = parseInt(hash.slice(0, 8), 16);
39331
38113
  const bucket = hashValue % 100;
39332
38114
  const inRollout = bucket < this.config.rolloutPercentage;
@@ -39337,7 +38119,7 @@ var FeatureFlagController = class {
39337
38119
  * Determine if session should be in rollout
39338
38120
  */
39339
38121
  isSessionInRollout(sessionId) {
39340
- const hash = crypto3__default.createHash("sha256").update(`${sessionId}:${this.hashSalt}`).digest("hex");
38122
+ const hash = crypto2__default.createHash("sha256").update(`${sessionId}:${this.hashSalt}`).digest("hex");
39341
38123
  const hashValue = parseInt(hash.slice(0, 8), 16);
39342
38124
  const bucket = hashValue % 100;
39343
38125
  return bucket < this.config.rolloutPercentage;
@@ -39580,6 +38362,7 @@ var EnterpriseSecurityIntegration = class extends EventEmitter {
39580
38362
  secureCommandAdapter;
39581
38363
  rbacGuard;
39582
38364
  accessControl;
38365
+ // AccessControlManager - temporarily disabled
39583
38366
  authManager;
39584
38367
  securityManager;
39585
38368
  auditLogger;
@@ -39977,6 +38760,345 @@ async function createEnterpriseSecurityIntegration(config, dependencies) {
39977
38760
  integration.once("initialization_error", (error2) => reject(error2));
39978
38761
  });
39979
38762
  }
38763
+ var AccessControlManager2 = class extends EventEmitter {
38764
+ config;
38765
+ users = /* @__PURE__ */ new Map();
38766
+ roles = /* @__PURE__ */ new Map();
38767
+ sessions = /* @__PURE__ */ new Map();
38768
+ cache = /* @__PURE__ */ new Map();
38769
+ constructor(config) {
38770
+ super();
38771
+ this.config = config;
38772
+ this.initialize();
38773
+ }
38774
+ initialize() {
38775
+ this.config.hierarchyLevels.forEach((level) => {
38776
+ const defaultRole = {
38777
+ id: `default-${level.level}`,
38778
+ name: `Default ${level.level} Role`,
38779
+ level: level.level,
38780
+ permissions: this.config.defaultPermissions,
38781
+ priority: level.priority,
38782
+ inheritFromParent: level.inheritFromParent,
38783
+ overrideChild: level.overrideChild
38784
+ };
38785
+ this.roles.set(defaultRole.id, defaultRole);
38786
+ });
38787
+ this.emit("initialized", { organizationId: this.config.organizationId });
38788
+ }
38789
+ /**
38790
+ * Check if a user has access to a resource
38791
+ */
38792
+ async checkAccess(userId, resource, action, context2) {
38793
+ const cacheKey = `${userId}:${resource}:${action}`;
38794
+ const cached = this.cache.get(cacheKey);
38795
+ if (cached && cached.expiresAt > Date.now()) {
38796
+ return cached.decision;
38797
+ }
38798
+ const user2 = this.users.get(userId);
38799
+ if (!user2) {
38800
+ return { allowed: false, reason: "User not found" };
38801
+ }
38802
+ const applicablePermissions = this.collectPermissions(user2);
38803
+ const decision = this.evaluatePermissions(
38804
+ applicablePermissions,
38805
+ resource,
38806
+ action,
38807
+ context2
38808
+ );
38809
+ this.cache.set(cacheKey, {
38810
+ decision,
38811
+ expiresAt: Date.now() + 5 * 60 * 1e3
38812
+ // 5 minutes
38813
+ });
38814
+ if (this.config.auditEnabled) {
38815
+ this.emit("access-check", {
38816
+ userId,
38817
+ resource,
38818
+ action,
38819
+ decision,
38820
+ timestamp: /* @__PURE__ */ new Date()
38821
+ });
38822
+ }
38823
+ return decision;
38824
+ }
38825
+ /**
38826
+ * Grant a role to a user
38827
+ */
38828
+ async grantRole(userId, roleId) {
38829
+ const user2 = this.users.get(userId);
38830
+ const role = this.roles.get(roleId);
38831
+ if (!user2 || !role) {
38832
+ throw new Error("User or role not found");
38833
+ }
38834
+ if (!user2.roles.find((r) => r.id === roleId)) {
38835
+ user2.roles.push(role);
38836
+ this.clearUserCache(userId);
38837
+ this.emit("role-granted", {
38838
+ userId,
38839
+ roleId,
38840
+ timestamp: /* @__PURE__ */ new Date()
38841
+ });
38842
+ }
38843
+ }
38844
+ /**
38845
+ * Revoke a role from a user
38846
+ */
38847
+ async revokeRole(userId, roleId) {
38848
+ const user2 = this.users.get(userId);
38849
+ if (!user2) {
38850
+ throw new Error("User not found");
38851
+ }
38852
+ const index = user2.roles.findIndex((r) => r.id === roleId);
38853
+ if (index !== -1) {
38854
+ user2.roles.splice(index, 1);
38855
+ this.clearUserCache(userId);
38856
+ this.emit("role-revoked", {
38857
+ userId,
38858
+ roleId,
38859
+ timestamp: /* @__PURE__ */ new Date()
38860
+ });
38861
+ }
38862
+ }
38863
+ /**
38864
+ * Register a new user
38865
+ */
38866
+ async registerUser(user2) {
38867
+ this.users.set(user2.id, user2);
38868
+ const defaultRole = this.roles.get("default-individual");
38869
+ if (defaultRole && !user2.roles.find((r) => r.id === defaultRole.id)) {
38870
+ user2.roles.push(defaultRole);
38871
+ }
38872
+ this.emit("user-registered", {
38873
+ userId: user2.id,
38874
+ timestamp: /* @__PURE__ */ new Date()
38875
+ });
38876
+ }
38877
+ /**
38878
+ * Create a custom role
38879
+ */
38880
+ async createRole(role) {
38881
+ this.roles.set(role.id, role);
38882
+ this.emit("role-created", {
38883
+ roleId: role.id,
38884
+ timestamp: /* @__PURE__ */ new Date()
38885
+ });
38886
+ }
38887
+ /**
38888
+ * Get classification level for data
38889
+ */
38890
+ getDataClassification(data2) {
38891
+ for (const rule of this.config.dataClassification.rules) {
38892
+ const pattern2 = rule.pattern instanceof RegExp ? rule.pattern : new RegExp(rule.pattern, "i");
38893
+ if (pattern2.test(data2)) {
38894
+ return rule.level;
38895
+ }
38896
+ }
38897
+ return this.config.dataClassification.defaultLevel;
38898
+ }
38899
+ /**
38900
+ * Collect all permissions for a user
38901
+ */
38902
+ collectPermissions(user2) {
38903
+ const permissions = [];
38904
+ if (user2.permissions) {
38905
+ permissions.push(user2.permissions);
38906
+ }
38907
+ const sortedRoles = [...user2.roles].sort((a2, b) => b.priority - a2.priority);
38908
+ for (const role of sortedRoles) {
38909
+ permissions.push(role.permissions);
38910
+ if (role.inheritFromParent) {
38911
+ const parentRole = this.findParentRole(role);
38912
+ if (parentRole) {
38913
+ permissions.push(parentRole.permissions);
38914
+ }
38915
+ }
38916
+ }
38917
+ return permissions;
38918
+ }
38919
+ /**
38920
+ * Evaluate permissions against a resource and action
38921
+ */
38922
+ evaluatePermissions(permissions, resource, action, context2) {
38923
+ for (const permSet of permissions) {
38924
+ if (!permSet.actions.includes(action) && !permSet.actions.includes("*")) {
38925
+ continue;
38926
+ }
38927
+ const resourcePerms = permSet.resources[resource] || permSet.resources["*"];
38928
+ if (!resourcePerms) {
38929
+ continue;
38930
+ }
38931
+ const hasPermission = this.mapActionToPermission(action, resourcePerms);
38932
+ if (!hasPermission) {
38933
+ continue;
38934
+ }
38935
+ if (permSet.conditions) {
38936
+ const conditionsMet = this.evaluateConditions(permSet.conditions, context2);
38937
+ if (!conditionsMet) {
38938
+ continue;
38939
+ }
38940
+ }
38941
+ return {
38942
+ allowed: true,
38943
+ conditions: permSet.conditions
38944
+ };
38945
+ }
38946
+ return {
38947
+ allowed: false,
38948
+ reason: "No matching permissions found"
38949
+ };
38950
+ }
38951
+ /**
38952
+ * Map an action to resource permissions
38953
+ */
38954
+ mapActionToPermission(action, perms) {
38955
+ const actionMap = {
38956
+ read: "read",
38957
+ view: "read",
38958
+ write: "write",
38959
+ create: "write",
38960
+ update: "write",
38961
+ delete: "delete",
38962
+ remove: "delete",
38963
+ execute: "execute",
38964
+ run: "execute",
38965
+ share: "share",
38966
+ admin: "admin",
38967
+ manage: "admin"
38968
+ };
38969
+ const permKey = actionMap[action.toLowerCase()];
38970
+ return permKey ? perms[permKey] === true : false;
38971
+ }
38972
+ /**
38973
+ * Evaluate permission conditions
38974
+ */
38975
+ evaluateConditions(conditions, context2) {
38976
+ if (!context2) return false;
38977
+ for (const condition of conditions) {
38978
+ if (!this.evaluateCondition(condition, context2)) {
38979
+ return false;
38980
+ }
38981
+ }
38982
+ return true;
38983
+ }
38984
+ /**
38985
+ * Evaluate a single condition
38986
+ */
38987
+ evaluateCondition(condition, context2) {
38988
+ const value2 = context2[condition.type];
38989
+ if (value2 === void 0) return false;
38990
+ switch (condition.operator) {
38991
+ case "equals":
38992
+ return value2 === condition.value;
38993
+ case "contains":
38994
+ return String(value2).includes(String(condition.value));
38995
+ case "matches":
38996
+ return new RegExp(condition.value).test(String(value2));
38997
+ case "between":
38998
+ return value2 >= condition.value[0] && value2 <= condition.value[1];
38999
+ default:
39000
+ return false;
39001
+ }
39002
+ }
39003
+ /**
39004
+ * Find parent role in hierarchy
39005
+ */
39006
+ findParentRole(role) {
39007
+ const currentLevel = this.config.hierarchyLevels.find(
39008
+ (l) => l.level === role.level
39009
+ );
39010
+ if (!currentLevel) return void 0;
39011
+ const parentLevel = this.config.hierarchyLevels.find(
39012
+ (l) => l.priority === currentLevel.priority + 1
39013
+ );
39014
+ if (!parentLevel) return void 0;
39015
+ return Array.from(this.roles.values()).find(
39016
+ (r) => r.level === parentLevel.level
39017
+ );
39018
+ }
39019
+ /**
39020
+ * Clear cache for a user
39021
+ */
39022
+ clearUserCache(userId) {
39023
+ const keysToDelete = [];
39024
+ for (const key of this.cache.keys()) {
39025
+ if (key.startsWith(`${userId}:`)) {
39026
+ keysToDelete.push(key);
39027
+ }
39028
+ }
39029
+ keysToDelete.forEach((key) => this.cache.delete(key));
39030
+ }
39031
+ /**
39032
+ * Get user by ID
39033
+ */
39034
+ getUser(userId) {
39035
+ return this.users.get(userId);
39036
+ }
39037
+ /**
39038
+ * Get role by ID
39039
+ */
39040
+ getRole(roleId) {
39041
+ return this.roles.get(roleId);
39042
+ }
39043
+ /**
39044
+ * List all users
39045
+ */
39046
+ listUsers() {
39047
+ return Array.from(this.users.values());
39048
+ }
39049
+ /**
39050
+ * List all roles
39051
+ */
39052
+ listRoles() {
39053
+ return Array.from(this.roles.values());
39054
+ }
39055
+ };
39056
+ new AccessControlManager2({
39057
+ organizationId: "default",
39058
+ hierarchyLevels: [
39059
+ {
39060
+ level: "individual",
39061
+ priority: 1,
39062
+ inheritFromParent: false,
39063
+ overrideChild: true
39064
+ },
39065
+ {
39066
+ level: "team",
39067
+ priority: 2,
39068
+ inheritFromParent: true,
39069
+ overrideChild: true
39070
+ },
39071
+ {
39072
+ level: "department",
39073
+ priority: 3,
39074
+ inheritFromParent: true,
39075
+ overrideChild: true
39076
+ },
39077
+ {
39078
+ level: "organization",
39079
+ priority: 4,
39080
+ inheritFromParent: false,
39081
+ overrideChild: false
39082
+ }
39083
+ ],
39084
+ defaultPermissions: {
39085
+ resources: {
39086
+ "*": {
39087
+ read: true,
39088
+ write: false,
39089
+ delete: false,
39090
+ execute: false
39091
+ }
39092
+ },
39093
+ actions: ["read", "view"]
39094
+ },
39095
+ dataClassification: {
39096
+ levels: ["public", "internal", "confidential", "restricted"],
39097
+ defaultLevel: "internal",
39098
+ rules: []
39099
+ },
39100
+ auditEnabled: true
39101
+ });
39980
39102
  var MemoryPortabilityFramework = class extends EventEmitter {
39981
39103
  config;
39982
39104
  dataPorter;
@@ -43824,8 +42946,8 @@ var SafeEncryptionService = class extends EventEmitter {
43824
42946
  try {
43825
42947
  const dataBuffer = Buffer.isBuffer(data2) ? data2 : Buffer.from(data2, "utf8");
43826
42948
  const keyInfo = await this.getEncryptionKey();
43827
- const iv = crypto3.randomBytes(12);
43828
- const cipher2 = crypto3.createCipher("aes-256-gcm", keyInfo.key);
42949
+ const iv = crypto2.randomBytes(12);
42950
+ const cipher2 = crypto2.createCipher("aes-256-gcm", keyInfo.key);
43829
42951
  cipher2.setAAD(Buffer.from(keyInfo.version, "utf8"));
43830
42952
  const encrypted = Buffer.concat([
43831
42953
  cipher2.update(dataBuffer),
@@ -43861,7 +42983,7 @@ var SafeEncryptionService = class extends EventEmitter {
43861
42983
  const authTag = encryptedBuffer.subarray(12, 28);
43862
42984
  const encrypted = encryptedBuffer.subarray(28);
43863
42985
  const keyInfo = await this.getDecryptionKey(request.keyVersion);
43864
- const decipher = crypto3.createDecipher("aes-256-gcm", keyInfo.key);
42986
+ const decipher = crypto2.createDecipher("aes-256-gcm", keyInfo.key);
43865
42987
  decipher.setAuthTag(authTag);
43866
42988
  decipher.setAAD(Buffer.from(keyInfo.version, "utf8"));
43867
42989
  const decrypted = Buffer.concat([
@@ -43943,11 +43065,11 @@ var SafeEncryptionService = class extends EventEmitter {
43943
43065
  * Derive encryption key using configured KDF
43944
43066
  */
43945
43067
  async deriveKey(input2) {
43946
- const salt = crypto3.randomBytes(this.config.kdf.saltSize);
43068
+ const salt = crypto2.randomBytes(this.config.kdf.saltSize);
43947
43069
  switch (this.config.kdf.method) {
43948
43070
  case "scrypt":
43949
43071
  return new Promise((resolve3, reject) => {
43950
- crypto3.scrypt(
43072
+ crypto2.scrypt(
43951
43073
  input2,
43952
43074
  salt,
43953
43075
  this.config.kdf.keySize,
@@ -43965,7 +43087,7 @@ var SafeEncryptionService = class extends EventEmitter {
43965
43087
  });
43966
43088
  case "PBKDF2":
43967
43089
  return new Promise((resolve3, reject) => {
43968
- crypto3.pbkdf2(
43090
+ crypto2.pbkdf2(
43969
43091
  input2,
43970
43092
  salt,
43971
43093
  this.config.kdf.iterations || 1e5,
@@ -45210,14 +44332,14 @@ var EnterpriseDataPorter = class extends EventEmitter {
45210
44332
  async generateChecksums(data2) {
45211
44333
  const _dataStr = typeof data2 === "string" ? data2 : JSON.stringify(data2);
45212
44334
  return {
45213
- md5: crypto3.createHash("md5").update(_dataStr).digest("hex"),
45214
- sha256: crypto3.createHash("sha256").update(_dataStr).digest("hex"),
45215
- sha512: crypto3.createHash("sha512").update(_dataStr).digest("hex"),
44335
+ md5: crypto2.createHash("md5").update(_dataStr).digest("hex"),
44336
+ sha256: crypto2.createHash("sha256").update(_dataStr).digest("hex"),
44337
+ sha512: crypto2.createHash("sha512").update(_dataStr).digest("hex"),
45216
44338
  crc32: this.calculateCRC32(_dataStr)
45217
44339
  };
45218
44340
  }
45219
44341
  calculateCRC32(data2) {
45220
- return crypto3.createHash("md5").update(data2).digest("hex").substring(0, 8);
44342
+ return crypto2.createHash("md5").update(data2).digest("hex").substring(0, 8);
45221
44343
  }
45222
44344
  // Data writing implementations for different destination types
45223
44345
  async writeToDatabase(data2, connection, destination) {
@@ -46199,21 +45321,21 @@ var EncryptionService = class {
46199
45321
  }
46200
45322
  }
46201
45323
  async deriveKey(providedSalt, iterations) {
46202
- const salt = providedSalt || crypto3.randomBytes(this.config.keyDerivation.saltSize);
45324
+ const salt = providedSalt || crypto2.randomBytes(this.config.keyDerivation.saltSize);
46203
45325
  const iterationCount = iterations || this.config.keyDerivation.iterations;
46204
45326
  const password = process.env.ENCRYPTION_PASSWORD || "default-encryption-key-maria-data-porter";
46205
45327
  let key;
46206
45328
  let iv;
46207
45329
  switch (this.config.keyDerivation.method) {
46208
45330
  case "PBKDF2":
46209
- key = crypto3.pbkdf2Sync(
45331
+ key = crypto2.pbkdf2Sync(
46210
45332
  password,
46211
45333
  salt,
46212
45334
  iterationCount,
46213
45335
  this.config.keyDerivation.keySize,
46214
45336
  "sha256"
46215
45337
  );
46216
- iv = crypto3.pbkdf2Sync(
45338
+ iv = crypto2.pbkdf2Sync(
46217
45339
  password + "iv",
46218
45340
  salt,
46219
45341
  Math.floor(iterationCount / 2),
@@ -46222,22 +45344,22 @@ var EncryptionService = class {
46222
45344
  );
46223
45345
  break;
46224
45346
  case "scrypt":
46225
- key = crypto3.scryptSync(
45347
+ key = crypto2.scryptSync(
46226
45348
  password,
46227
45349
  salt,
46228
45350
  this.config.keyDerivation.keySize
46229
45351
  );
46230
- iv = crypto3.scryptSync(password + "iv", salt, 16);
45352
+ iv = crypto2.scryptSync(password + "iv", salt, 16);
46231
45353
  break;
46232
45354
  case "Argon2":
46233
- key = crypto3.pbkdf2Sync(
45355
+ key = crypto2.pbkdf2Sync(
46234
45356
  password,
46235
45357
  salt,
46236
45358
  iterationCount,
46237
45359
  this.config.keyDerivation.keySize,
46238
45360
  "sha256"
46239
45361
  );
46240
- iv = crypto3.pbkdf2Sync(
45362
+ iv = crypto2.pbkdf2Sync(
46241
45363
  password + "iv",
46242
45364
  salt,
46243
45365
  Math.floor(iterationCount / 2),
@@ -46290,7 +45412,7 @@ var EncryptionService = class {
46290
45412
  `Unsupported encryption algorithm: ${this.config.algorithm}`
46291
45413
  );
46292
45414
  }
46293
- const decipher = crypto3.createDecipher(algorithm, key);
45415
+ const decipher = crypto2.createDecipher(algorithm, key);
46294
45416
  let cipherData = encryptedData;
46295
45417
  if (this.config.algorithm === "AES-256-GCM") {
46296
45418
  const tag = encryptedData.slice(-16);
@@ -46377,13 +45499,13 @@ var EncryptionService = class {
46377
45499
  * Generate a secure random key for one-time use
46378
45500
  */
46379
45501
  generateRandomKey(length = 32) {
46380
- return crypto3.randomBytes(length);
45502
+ return crypto2.randomBytes(length);
46381
45503
  }
46382
45504
  /**
46383
45505
  * Generate a secure hash of data for integrity verification
46384
45506
  */
46385
45507
  generateHash(data2, algorithm = "sha256") {
46386
- const hash = crypto3.createHash(algorithm);
45508
+ const hash = crypto2.createHash(algorithm);
46387
45509
  hash.update(typeof data2 === "string" ? Buffer.from(data2) : data2);
46388
45510
  return hash.digest("hex");
46389
45511
  }
@@ -47119,9 +46241,9 @@ var ModelRegistry2 = class extends EventEmitter {
47119
46241
  */
47120
46242
  list(filters = {}) {
47121
46243
  const cacheKey = this.generateCacheKey(filters);
47122
- const cached2 = this.cache.get(cacheKey);
47123
- if (cached2 && Date.now() - cached2.timestamp < cached2.ttl) {
47124
- return cached2.result;
46244
+ const cached = this.cache.get(cacheKey);
46245
+ if (cached && Date.now() - cached.timestamp < cached.ttl) {
46246
+ return cached.result;
47125
46247
  }
47126
46248
  let result2 = Array.from(this.models.values());
47127
46249
  if (filters.provider) {
@@ -47620,7 +46742,91 @@ function createModelSelector(options) {
47620
46742
  };
47621
46743
  }
47622
46744
  (/* @__PURE__ */ new Date()).toISOString();
47623
- var PolicyEngine2 = class extends EventEmitter {
46745
+
46746
+ // src/lib/command-groups.ts
46747
+ var commandGroups = {
46748
+ core: [
46749
+ "about",
46750
+ "changelog",
46751
+ "config",
46752
+ "contact",
46753
+ "doctor",
46754
+ "examples",
46755
+ "help",
46756
+ "history",
46757
+ "list",
46758
+ "logout",
46759
+ "model",
46760
+ "ping",
46761
+ "plan",
46762
+ "plugins",
46763
+ "status",
46764
+ "tutorial",
46765
+ "usage",
46766
+ "verify",
46767
+ "version"
46768
+ ],
46769
+ auth: ["login", "logout", "whoami"],
46770
+ code: ["code", "mm", "multimodal"],
46771
+ configuration: ["config", "hooks", "model", "permissions", "settings", "theme"],
46772
+ multimodal: ["face", "image", "mm", "multimodal", "screenshot", "video", "voice"],
46773
+ evolution: ["benchmark", "evolve", "quality"],
46774
+ memory: ["forget", "memory", "recall", "remember"],
46775
+ analysis: ["analyze", "diagram", "diff", "visualize"],
46776
+ system: ["doctor", "health", "manifest", "selftest"],
46777
+ workflow: ["nl", "nl-poc"],
46778
+ safety: ["check"],
46779
+ evaluation: ["run"],
46780
+ assistant: ["ask", "chat", "think"],
46781
+ data: ["db", "export", "import", "sync"],
46782
+ utilities: ["alias", "clear", "history", "reset"],
46783
+ experimental: ["preview", "test"],
46784
+ business: ["battlecard", "sales-dashboard", "tune", "pilot-setup"],
46785
+ plugins: ["plugins"],
46786
+ search: ["search"],
46787
+ enterprise: ["admin", "audit", "compliance", "security"],
46788
+ development: ["debug", "profile", "trace"]
46789
+ };
46790
+ var allCommands = Object.values(commandGroups).flat();
46791
+ var categories = Object.keys(commandGroups);
46792
+ var commandCategories = {
46793
+ core: "Core",
46794
+ auth: "Authentication",
46795
+ code: "Code Generation",
46796
+ configuration: "Configuration",
46797
+ multimodal: "Multimodal",
46798
+ evolution: "Evolution",
46799
+ memory: "Memory",
46800
+ analysis: "Analysis",
46801
+ system: "System",
46802
+ workflow: "Workflow",
46803
+ safety: "Safety",
46804
+ evaluation: "Evaluation",
46805
+ assistant: "Assistant",
46806
+ data: "Data",
46807
+ utilities: "Utilities",
46808
+ experimental: "Experimental",
46809
+ business: "Business",
46810
+ plugins: "Plugins",
46811
+ search: "Search",
46812
+ enterprise: "Enterprise",
46813
+ development: "Development"
46814
+ };
46815
+ var commandInfo = {};
46816
+ for (const [category, commands] of Object.entries(commandGroups)) {
46817
+ for (const command of commands) {
46818
+ commandInfo[command] = {
46819
+ name: `/${command}`,
46820
+ category
46821
+ };
46822
+ }
46823
+ }
46824
+ commandInfo["model"] = { ...commandInfo["model"], aliases: ["/m", "/models"] };
46825
+ commandInfo["memory"] = { ...commandInfo["memory"], aliases: ["/mem"] };
46826
+ commandInfo["login"] = { ...commandInfo["login"], aliases: ["/signin"] };
46827
+ commandInfo["logout"] = { ...commandInfo["logout"], aliases: ["/signout"] };
46828
+ commandInfo["evolve"] = { ...commandInfo["evolve"], aliases: ["/evolution", "/auto-evolve"] };
46829
+ var PolicyEngine = class extends EventEmitter {
47624
46830
  constructor(firestoreClient, options = {
47625
46831
  cacheExpirationMs: 3e5,
47626
46832
  // 5 minutes
@@ -47652,11 +46858,11 @@ var PolicyEngine2 = class extends EventEmitter {
47652
46858
  * Get policy with hot cache support
47653
46859
  */
47654
46860
  async getPolicy(policyId) {
47655
- const cached2 = this.policyCache.get(policyId);
47656
- if (cached2 && this.isCacheValid(cached2)) {
47657
- cached2.lastAccessedAt = /* @__PURE__ */ new Date();
47658
- cached2.hitCount++;
47659
- return cached2.policy;
46861
+ const cached = this.policyCache.get(policyId);
46862
+ if (cached && this.isCacheValid(cached)) {
46863
+ cached.lastAccessedAt = /* @__PURE__ */ new Date();
46864
+ cached.hitCount++;
46865
+ return cached.policy;
47660
46866
  }
47661
46867
  const policy = await this.loadPolicyFromFirestore(policyId);
47662
46868
  this.updateCache(policyId, policy);
@@ -47850,31 +47056,31 @@ var PolicyEngine2 = class extends EventEmitter {
47850
47056
  hitCount: 0
47851
47057
  });
47852
47058
  }
47853
- evaluateRuleCondition(condition2, task) {
47059
+ evaluateRuleCondition(condition, task) {
47854
47060
  const reasons = [];
47855
- if (condition2["task.kind"]) {
47856
- const allowedKinds = Array.isArray(condition2["task.kind"]) ? condition2["task.kind"] : [condition2["task.kind"]];
47061
+ if (condition["task.kind"]) {
47062
+ const allowedKinds = Array.isArray(condition["task.kind"]) ? condition["task.kind"] : [condition["task.kind"]];
47857
47063
  if (!allowedKinds.includes(task.task.kind)) {
47858
47064
  return { matched: false, reason: `Task kind ${task.task.kind} not in ${allowedKinds.join(", ")}` };
47859
47065
  }
47860
47066
  reasons.push(`Task kind matches: ${task.task.kind}`);
47861
47067
  }
47862
- if (condition2["task.subtype"] && task.task.subtype) {
47863
- const allowedSubtypes = Array.isArray(condition2["task.subtype"]) ? condition2["task.subtype"] : [condition2["task.subtype"]];
47068
+ if (condition["task.subtype"] && task.task.subtype) {
47069
+ const allowedSubtypes = Array.isArray(condition["task.subtype"]) ? condition["task.subtype"] : [condition["task.subtype"]];
47864
47070
  if (!allowedSubtypes.includes(task.task.subtype)) {
47865
47071
  return { matched: false, reason: `Task subtype ${task.task.subtype} not in ${allowedSubtypes.join(", ")}` };
47866
47072
  }
47867
47073
  reasons.push(`Task subtype matches: ${task.task.subtype}`);
47868
47074
  }
47869
- if (condition2["session.plan"]) {
47870
- const allowedPlans = Array.isArray(condition2["session.plan"]) ? condition2["session.plan"] : [condition2["session.plan"]];
47075
+ if (condition["session.plan"]) {
47076
+ const allowedPlans = Array.isArray(condition["session.plan"]) ? condition["session.plan"] : [condition["session.plan"]];
47871
47077
  if (!allowedPlans.includes(task.session.plan)) {
47872
47078
  return { matched: false, reason: `User plan ${task.session.plan} not in ${allowedPlans.join(", ")}` };
47873
47079
  }
47874
47080
  reasons.push(`User plan matches: ${task.session.plan}`);
47875
47081
  }
47876
- if (condition2["task.tokensIn"]) {
47877
- const tokenCondition = condition2["task.tokensIn"];
47082
+ if (condition["task.tokensIn"]) {
47083
+ const tokenCondition = condition["task.tokensIn"];
47878
47084
  const tokensIn = task.task.tokensIn;
47879
47085
  if (tokenCondition.gt !== void 0 && tokensIn <= tokenCondition.gt) {
47880
47086
  return { matched: false, reason: `Tokens ${tokensIn} not > ${tokenCondition.gt}` };
@@ -47890,10 +47096,10 @@ var PolicyEngine2 = class extends EventEmitter {
47890
47096
  }
47891
47097
  reasons.push(`Token count condition satisfied: ${tokensIn}`);
47892
47098
  }
47893
- if (condition2.timeOfDay) {
47099
+ if (condition.timeOfDay) {
47894
47100
  const now = /* @__PURE__ */ new Date();
47895
47101
  const timeStr = now.toTimeString().slice(0, 5);
47896
- const { start, end } = condition2.timeOfDay;
47102
+ const { start, end } = condition.timeOfDay;
47897
47103
  if (timeStr < start || timeStr > end) {
47898
47104
  return { matched: false, reason: `Current time ${timeStr} not between ${start} and ${end}` };
47899
47105
  }
@@ -48014,9 +47220,9 @@ var ModelPoolManager = class extends EventEmitter {
48014
47220
  * Get model pool with caching
48015
47221
  */
48016
47222
  async getModelPool(poolId) {
48017
- const cached2 = this.poolCache.get(poolId);
48018
- if (cached2 && this.isPoolCacheValid(cached2)) {
48019
- return cached2.pool;
47223
+ const cached = this.poolCache.get(poolId);
47224
+ if (cached && this.isPoolCacheValid(cached)) {
47225
+ return cached.pool;
48020
47226
  }
48021
47227
  const pool = await this.loadPoolFromFirestore(poolId);
48022
47228
  this.updatePoolCache(poolId, pool);
@@ -48186,8 +47392,8 @@ var ModelPoolManager = class extends EventEmitter {
48186
47392
  version: pool.version
48187
47393
  });
48188
47394
  }
48189
- isPoolCacheValid(cached2) {
48190
- const age = Date.now() - cached2.cachedAt.getTime();
47395
+ isPoolCacheValid(cached) {
47396
+ const age = Date.now() - cached.cachedAt.getTime();
48191
47397
  return age < 3e5;
48192
47398
  }
48193
47399
  getCircuitBreakerState(modelId) {
@@ -49954,7 +49160,7 @@ var CompletePIIRedactor = class extends EventEmitter {
49954
49160
  };
49955
49161
  }
49956
49162
  generateEncryptionKey() {
49957
- return crypto3__default.randomBytes(32);
49163
+ return crypto2__default.randomBytes(32);
49958
49164
  }
49959
49165
  /**
49960
49166
  * Get comprehensive audit trail for compliance reporting
@@ -51873,7 +51079,7 @@ var IMSRouter = class extends EventEmitter {
51873
51079
  constructor(config) {
51874
51080
  super();
51875
51081
  this.config = config;
51876
- this.policyEngine = new PolicyEngine2(config.firestoreClient);
51082
+ this.policyEngine = new PolicyEngine(config.firestoreClient);
51877
51083
  this.poolManager = new ModelPoolManager(config.firestoreClient);
51878
51084
  this.piiRedactor = new CompletePIIRedactor();
51879
51085
  this.decisionEngine = new RoutingDecisionEngine(
@@ -53969,13 +53175,13 @@ var UnifiedProviderInterface = class extends EventEmitter {
53969
53175
  this.emit("cleanup");
53970
53176
  }
53971
53177
  };
53972
- function RequireRole(role2) {
53178
+ function RequireRole(role) {
53973
53179
  return function(target, propertyName, descriptor) {
53974
53180
  const method = descriptor.value;
53975
53181
  descriptor.value = function(...args) {
53976
53182
  const req = args[0];
53977
- if (!req.user || !req.user.roles.includes(role2)) {
53978
- throw new Error(`Insufficient permissions. Required role: ${role2}`);
53183
+ if (!req.user || !req.user.roles.includes(role)) {
53184
+ throw new Error(`Insufficient permissions. Required role: ${role}`);
53979
53185
  }
53980
53186
  return method.apply(this, args);
53981
53187
  };
@@ -54133,13 +53339,13 @@ var AdminAPI = class extends EventEmitter {
54133
53339
  const { category, active } = req.query;
54134
53340
  const testCases = this.dependencies.goldenDatasetMonitor.getTestCases(category);
54135
53341
  const filteredCases = active === "true" ? testCases.filter((tc) => tc.isActive) : testCases;
54136
- const categories = [...new Set(testCases.map((tc) => tc.category))];
53342
+ const categories2 = [...new Set(testCases.map((tc) => tc.category))];
54137
53343
  this.logAdminAction(req.user, "VIEW_GOLDEN_DATASET", { category, active });
54138
53344
  return {
54139
53345
  testCases: filteredCases,
54140
53346
  totalCount: testCases.length,
54141
53347
  activeCount: testCases.filter((tc) => tc.isActive).length,
54142
- categories
53348
+ categories: categories2
54143
53349
  };
54144
53350
  }
54145
53351
  async runGoldenDatasetTests(req) {
@@ -54427,6 +53633,6 @@ __decorateClass([
54427
53633
  RequireRole("ims.viewer")
54428
53634
  ], AdminAPI.prototype, "getSystemHealth");
54429
53635
 
54430
- export { AccessControlManager, AdaptiveSSEController, AdminAPI, DocumentType, DualMemoryEngine, EnterpriseDataPorter, EnterpriseSecurityIntegration, FileSystemService, FilenameInferenceService, HotCache, HysteresisHealthChecker, IMSAPIEndpoints, IMSRouter, IdempotencyManager, IntelligentDocumentSaveService, IntelligentRouterService, MemoryPortabilityFramework, ModelRegistry2 as ModelRegistry, ModelSelectorEngine2 as ModelSelectorEngine, ModelSelectorV2Facade2 as ModelSelectorV2Facade, MultimodalDeploymentConfig, MultimodalService, PreciseCostCalculator, RBACCommandGuard, RecommendationEngine, RunawayPreventionCircuitBreaker, SecureSlashCommandAdapter, System1MemoryManager, System2MemoryManager, TTFBAuditor, UnifiedProviderInterface, autoSaveDocument, autoSaveIntelligently, autoSaveMultipleDocuments, autoSaveMultipleIntelligently, classifyDocument, createEnterpriseSecurityIntegration, createMemoryPortabilityFramework, createModelSelector, generateDocumentFilename, getModelSelectorV2Config, intelligentSave, isModelSelectorV2Enabled, saveDocumentToFile };
53636
+ export { AccessControlManager2 as AccessControlManager, AdaptiveSSEController, AdminAPI, DocumentType, DualMemoryEngine, EnterpriseDataPorter, EnterpriseSecurityIntegration, FileSystemService, FilenameInferenceService, HotCache, HysteresisHealthChecker, IMSAPIEndpoints, IMSRouter, IdempotencyManager, IntelligentDocumentSaveService, IntelligentRouterService, MemoryPortabilityFramework, ModelRegistry2 as ModelRegistry, ModelSelectorEngine2 as ModelSelectorEngine, ModelSelectorV2Facade2 as ModelSelectorV2Facade, MultimodalDeploymentConfig, MultimodalService, PreciseCostCalculator, RBACCommandGuard, RecommendationEngine, RunawayPreventionCircuitBreaker, SecureSlashCommandAdapter, System1MemoryManager, System2MemoryManager, TTFBAuditor, UnifiedProviderInterface, allCommands, autoSaveDocument, autoSaveIntelligently, autoSaveMultipleDocuments, autoSaveMultipleIntelligently, categories, classifyDocument, commandCategories, commandGroups, commandInfo, createEnterpriseSecurityIntegration, createMemoryPortabilityFramework, createModelSelector, generateDocumentFilename, getModelSelectorV2Config, intelligentSave, isModelSelectorV2Enabled, saveDocumentToFile };
54431
53637
  //# sourceMappingURL=index.js.map
54432
53638
  //# sourceMappingURL=index.js.map