@naylence/advanced-security 0.3.15 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/dist/browser/index.cjs +2673 -3
  2. package/dist/browser/index.mjs +2684 -14
  3. package/dist/cjs/advanced-security-isomorphic.js +4 -0
  4. package/dist/cjs/advanced-security-isomorphic.js.map +1 -1
  5. package/dist/cjs/naylence/fame/expr/ast.js +135 -0
  6. package/dist/cjs/naylence/fame/expr/ast.js.map +1 -0
  7. package/dist/cjs/naylence/fame/expr/builtins.js +477 -0
  8. package/dist/cjs/naylence/fame/expr/builtins.js.map +1 -0
  9. package/dist/cjs/naylence/fame/expr/errors.js +88 -0
  10. package/dist/cjs/naylence/fame/expr/errors.js.map +1 -0
  11. package/dist/cjs/naylence/fame/expr/evaluator.js +385 -0
  12. package/dist/cjs/naylence/fame/expr/evaluator.js.map +1 -0
  13. package/dist/cjs/naylence/fame/expr/index.js +21 -0
  14. package/dist/cjs/naylence/fame/expr/index.js.map +1 -0
  15. package/dist/cjs/naylence/fame/expr/limits.js +80 -0
  16. package/dist/cjs/naylence/fame/expr/limits.js.map +1 -0
  17. package/dist/cjs/naylence/fame/expr/parser.js +429 -0
  18. package/dist/cjs/naylence/fame/expr/parser.js.map +1 -0
  19. package/dist/cjs/naylence/fame/expr/tokenizer.js +336 -0
  20. package/dist/cjs/naylence/fame/expr/tokenizer.js.map +1 -0
  21. package/dist/cjs/naylence/fame/factory-manifest.js +2 -0
  22. package/dist/cjs/naylence/fame/factory-manifest.js.map +1 -1
  23. package/dist/cjs/naylence/fame/security/auth/index.js +7 -0
  24. package/dist/cjs/naylence/fame/security/auth/index.js.map +1 -0
  25. package/dist/cjs/naylence/fame/security/auth/policy/advanced-authorization-policy-factory.js +70 -0
  26. package/dist/cjs/naylence/fame/security/auth/policy/advanced-authorization-policy-factory.js.map +1 -0
  27. package/dist/cjs/naylence/fame/security/auth/policy/advanced-authorization-policy.js +562 -0
  28. package/dist/cjs/naylence/fame/security/auth/policy/advanced-authorization-policy.js.map +1 -0
  29. package/dist/cjs/naylence/fame/security/auth/policy/expr-builtins.js +129 -0
  30. package/dist/cjs/naylence/fame/security/auth/policy/expr-builtins.js.map +1 -0
  31. package/dist/cjs/naylence/fame/security/auth/policy/index.js +15 -0
  32. package/dist/cjs/naylence/fame/security/auth/policy/index.js.map +1 -0
  33. package/dist/cjs/naylence/fame/security/index.js +2 -0
  34. package/dist/cjs/naylence/fame/security/index.js.map +1 -1
  35. package/dist/cjs/naylence/fame/security/register-advanced-security-factories.js +2 -0
  36. package/dist/cjs/naylence/fame/security/register-advanced-security-factories.js.map +1 -1
  37. package/dist/cjs/naylence/fame/security/strict-overlay-security-profile.js +64 -0
  38. package/dist/cjs/naylence/fame/security/strict-overlay-security-profile.js.map +1 -0
  39. package/dist/cjs/plugin.js +2 -0
  40. package/dist/cjs/plugin.js.map +1 -1
  41. package/dist/cjs/version.js +2 -2
  42. package/dist/cjs/version.js.map +1 -1
  43. package/dist/esm/advanced-security-isomorphic.js +4 -0
  44. package/dist/esm/advanced-security-isomorphic.js.map +1 -1
  45. package/dist/esm/naylence/fame/expr/ast.js +135 -0
  46. package/dist/esm/naylence/fame/expr/ast.js.map +1 -0
  47. package/dist/esm/naylence/fame/expr/builtins.js +477 -0
  48. package/dist/esm/naylence/fame/expr/builtins.js.map +1 -0
  49. package/dist/esm/naylence/fame/expr/errors.js +88 -0
  50. package/dist/esm/naylence/fame/expr/errors.js.map +1 -0
  51. package/dist/esm/naylence/fame/expr/evaluator.js +385 -0
  52. package/dist/esm/naylence/fame/expr/evaluator.js.map +1 -0
  53. package/dist/esm/naylence/fame/expr/index.js +21 -0
  54. package/dist/esm/naylence/fame/expr/index.js.map +1 -0
  55. package/dist/esm/naylence/fame/expr/limits.js +80 -0
  56. package/dist/esm/naylence/fame/expr/limits.js.map +1 -0
  57. package/dist/esm/naylence/fame/expr/parser.js +429 -0
  58. package/dist/esm/naylence/fame/expr/parser.js.map +1 -0
  59. package/dist/esm/naylence/fame/expr/tokenizer.js +336 -0
  60. package/dist/esm/naylence/fame/expr/tokenizer.js.map +1 -0
  61. package/dist/esm/naylence/fame/factory-manifest.js +2 -0
  62. package/dist/esm/naylence/fame/factory-manifest.js.map +1 -1
  63. package/dist/esm/naylence/fame/security/auth/index.js +7 -0
  64. package/dist/esm/naylence/fame/security/auth/index.js.map +1 -0
  65. package/dist/esm/naylence/fame/security/auth/policy/advanced-authorization-policy-factory.js +70 -0
  66. package/dist/esm/naylence/fame/security/auth/policy/advanced-authorization-policy-factory.js.map +1 -0
  67. package/dist/esm/naylence/fame/security/auth/policy/advanced-authorization-policy.js +562 -0
  68. package/dist/esm/naylence/fame/security/auth/policy/advanced-authorization-policy.js.map +1 -0
  69. package/dist/esm/naylence/fame/security/auth/policy/expr-builtins.js +129 -0
  70. package/dist/esm/naylence/fame/security/auth/policy/expr-builtins.js.map +1 -0
  71. package/dist/esm/naylence/fame/security/auth/policy/index.js +15 -0
  72. package/dist/esm/naylence/fame/security/auth/policy/index.js.map +1 -0
  73. package/dist/esm/naylence/fame/security/index.js +2 -0
  74. package/dist/esm/naylence/fame/security/index.js.map +1 -1
  75. package/dist/esm/naylence/fame/security/register-advanced-security-factories.js +2 -0
  76. package/dist/esm/naylence/fame/security/register-advanced-security-factories.js.map +1 -1
  77. package/dist/esm/naylence/fame/security/strict-overlay-security-profile.js +64 -0
  78. package/dist/esm/naylence/fame/security/strict-overlay-security-profile.js.map +1 -0
  79. package/dist/esm/plugin.js +2 -0
  80. package/dist/esm/plugin.js.map +1 -1
  81. package/dist/esm/version.js +2 -2
  82. package/dist/esm/version.js.map +1 -1
  83. package/dist/node/index.cjs +2795 -6
  84. package/dist/node/index.mjs +2770 -15
  85. package/dist/node/node.cjs +2819 -3
  86. package/dist/node/node.mjs +2796 -15
  87. package/dist/types/advanced-security-isomorphic.d.ts +2 -0
  88. package/dist/types/advanced-security-isomorphic.d.ts.map +1 -1
  89. package/dist/types/naylence/fame/expr/ast.d.ts +85 -0
  90. package/dist/types/naylence/fame/expr/ast.d.ts.map +1 -0
  91. package/dist/types/naylence/fame/expr/builtins.d.ts +79 -0
  92. package/dist/types/naylence/fame/expr/builtins.d.ts.map +1 -0
  93. package/dist/types/naylence/fame/expr/errors.d.ts +61 -0
  94. package/dist/types/naylence/fame/expr/errors.d.ts.map +1 -0
  95. package/dist/types/naylence/fame/expr/evaluator.d.ts +90 -0
  96. package/dist/types/naylence/fame/expr/evaluator.d.ts.map +1 -0
  97. package/dist/types/naylence/fame/expr/index.d.ts +16 -0
  98. package/dist/types/naylence/fame/expr/index.d.ts.map +1 -0
  99. package/dist/types/naylence/fame/expr/limits.d.ts +65 -0
  100. package/dist/types/naylence/fame/expr/limits.d.ts.map +1 -0
  101. package/dist/types/naylence/fame/expr/parser.d.ts +102 -0
  102. package/dist/types/naylence/fame/expr/parser.d.ts.map +1 -0
  103. package/dist/types/naylence/fame/expr/tokenizer.d.ts +51 -0
  104. package/dist/types/naylence/fame/expr/tokenizer.d.ts.map +1 -0
  105. package/dist/types/naylence/fame/factory-manifest.d.ts +1 -1
  106. package/dist/types/naylence/fame/factory-manifest.d.ts.map +1 -1
  107. package/dist/types/naylence/fame/security/auth/index.d.ts +7 -0
  108. package/dist/types/naylence/fame/security/auth/index.d.ts.map +1 -0
  109. package/dist/types/naylence/fame/security/auth/policy/advanced-authorization-policy-factory.d.ts +47 -0
  110. package/dist/types/naylence/fame/security/auth/policy/advanced-authorization-policy-factory.d.ts.map +1 -0
  111. package/dist/types/naylence/fame/security/auth/policy/advanced-authorization-policy.d.ts +73 -0
  112. package/dist/types/naylence/fame/security/auth/policy/advanced-authorization-policy.d.ts.map +1 -0
  113. package/dist/types/naylence/fame/security/auth/policy/expr-builtins.d.ts +14 -0
  114. package/dist/types/naylence/fame/security/auth/policy/expr-builtins.d.ts.map +1 -0
  115. package/dist/types/naylence/fame/security/auth/policy/index.d.ts +12 -0
  116. package/dist/types/naylence/fame/security/auth/policy/index.d.ts.map +1 -0
  117. package/dist/types/naylence/fame/security/index.d.ts +2 -0
  118. package/dist/types/naylence/fame/security/index.d.ts.map +1 -1
  119. package/dist/types/naylence/fame/security/register-advanced-security-factories.d.ts +1 -0
  120. package/dist/types/naylence/fame/security/register-advanced-security-factories.d.ts.map +1 -1
  121. package/dist/types/naylence/fame/security/strict-overlay-security-profile.d.ts +11 -0
  122. package/dist/types/naylence/fame/security/strict-overlay-security-profile.d.ts.map +1 -0
  123. package/dist/types/plugin.d.ts.map +1 -1
  124. package/dist/types/version.d.ts +1 -1
  125. package/dist/types/version.d.ts.map +1 -1
  126. package/package.json +3 -3
@@ -2,13 +2,14 @@
2
2
 
3
3
  var factory = require('@naylence/factory');
4
4
  var runtime = require('@naylence/runtime');
5
+ var sha256 = require('@noble/hashes/sha256');
6
+ var core = require('@naylence/core');
5
7
  var asn1Schema = require('@peculiar/asn1-schema');
6
8
  var asn1X509 = require('@peculiar/asn1-x509');
7
9
  var sha2_js = require('@noble/hashes/sha2.js');
8
10
  var ed25519 = require('@noble/ed25519');
9
11
  var asn1Csr = require('@peculiar/asn1-csr');
10
12
  var x509 = require('@peculiar/x509');
11
- var core = require('@naylence/core');
12
13
  var chacha_js = require('@noble/ciphers/chacha.js');
13
14
  var ed25519_js = require('@noble/curves/ed25519.js');
14
15
  var hkdf_js = require('@noble/hashes/hkdf.js');
@@ -23,6 +24,7 @@ var sha256_js = require('@noble/hashes/sha256.js');
23
24
  * Provides the list of advanced security factory modules for registration.
24
25
  */
25
26
  const MODULES = [
27
+ "./security/auth/policy/advanced-authorization-policy-factory.js",
26
28
  "./security/cert/default-ca-service-factory.js",
27
29
  "./security/cert/default-certificate-manager-factory.js",
28
30
  "./security/cert/trust-store/browser-trust-store-provider-factory.js",
@@ -39,6 +41,7 @@ const MODULES = [
39
41
  "./welcome/advanced-welcome-service-factory.js"
40
42
  ];
41
43
  const MODULE_LOADERS = {
44
+ "./security/auth/policy/advanced-authorization-policy-factory.js": () => Promise.resolve().then(function () { return advancedAuthorizationPolicyFactory; }),
42
45
  "./security/cert/default-ca-service-factory.js": () => Promise.resolve().then(function () { return defaultCaServiceFactory; }),
43
46
  "./security/cert/default-certificate-manager-factory.js": () => Promise.resolve().then(function () { return defaultCertificateManagerFactory; }),
44
47
  "./security/cert/trust-store/browser-trust-store-provider-factory.js": () => Promise.resolve().then(function () { return browserTrustStoreProviderFactory; }),
@@ -219,6 +222,75 @@ function registerEncryptionManagerFactory(factory) {
219
222
  globalRegistry.registerFactory(factory);
220
223
  }
221
224
 
225
+ /**
226
+ * Strict Overlay Security Profile
227
+ *
228
+ * Provides the strict-overlay security profile for advanced security scenarios.
229
+ * This profile requires X.509 certificate-based signing and supports both
230
+ * channel and sealed encryption modes.
231
+ */
232
+ const ENV_VAR_DEFAULT_ENCRYPTION_LEVEL = "FAME_DEFAULT_ENCRYPTION_LEVEL";
233
+ const ENV_VAR_AUTHORIZATION_PROFILE = "FAME_AUTHORIZATION_PROFILE";
234
+ const PROFILE_NAME_STRICT_OVERLAY = "strict-overlay";
235
+ const STRICT_OVERLAY_PROFILE = {
236
+ type: "DefaultSecurityManager",
237
+ security_policy: {
238
+ type: "DefaultSecurityPolicy",
239
+ signing: {
240
+ signing_material: "x509-chain",
241
+ require_cert_sid_match: true,
242
+ inbound: {
243
+ signature_policy: "required",
244
+ unsigned_violation_action: "nack",
245
+ invalid_signature_action: "nack",
246
+ },
247
+ response: {
248
+ mirror_request_signing: true,
249
+ always_sign_responses: false,
250
+ sign_error_responses: true,
251
+ },
252
+ outbound: {
253
+ default_signing: true,
254
+ sign_sensitive_operations: true,
255
+ sign_if_recipient_expects: true,
256
+ },
257
+ },
258
+ encryption: {
259
+ inbound: {
260
+ allow_plaintext: true,
261
+ allow_channel: true,
262
+ allow_sealed: true,
263
+ plaintext_violation_action: "nack",
264
+ channel_violation_action: "nack",
265
+ sealed_violation_action: "nack",
266
+ },
267
+ response: {
268
+ mirror_request_level: true,
269
+ minimum_response_level: "plaintext",
270
+ escalate_sealed_responses: false,
271
+ },
272
+ outbound: {
273
+ default_level: factory.Expressions.env(ENV_VAR_DEFAULT_ENCRYPTION_LEVEL, "channel"),
274
+ escalate_if_peer_supports: false,
275
+ prefer_sealed_for_sensitive: false,
276
+ },
277
+ },
278
+ },
279
+ authorizer: {
280
+ type: "AuthorizationProfile",
281
+ profile: factory.Expressions.env(ENV_VAR_AUTHORIZATION_PROFILE, "jwt"),
282
+ },
283
+ };
284
+ // Register the strict-overlay profile
285
+ runtime.registerProfile(runtime.SECURITY_MANAGER_FACTORY_BASE_TYPE, PROFILE_NAME_STRICT_OVERLAY, STRICT_OVERLAY_PROFILE, { source: "advanced-security:strict-overlay-security-profile", allowOverride: true });
286
+
287
+ var strictOverlaySecurityProfile = /*#__PURE__*/Object.freeze({
288
+ __proto__: null,
289
+ ENV_VAR_AUTHORIZATION_PROFILE: ENV_VAR_AUTHORIZATION_PROFILE,
290
+ ENV_VAR_DEFAULT_ENCRYPTION_LEVEL: ENV_VAR_DEFAULT_ENCRYPTION_LEVEL,
291
+ PROFILE_NAME_STRICT_OVERLAY: PROFILE_NAME_STRICT_OVERLAY
292
+ });
293
+
222
294
  const SECURITY_PREFIX = "./security/";
223
295
  const SECURITY_MODULES = MODULES.filter((spec) => spec.startsWith(SECURITY_PREFIX));
224
296
  const EXTRA_MODULES = MODULES.filter((spec) => !spec.startsWith(SECURITY_PREFIX));
@@ -503,12 +575,12 @@ async function registerAdvancedSecurityFactories(registrar = factory.Registry, o
503
575
  }
504
576
 
505
577
  // This file is auto-generated during build - do not edit manually
506
- // Generated from package.json version: 0.3.15
578
+ // Generated from package.json version: 0.4.0
507
579
  /**
508
580
  * The package version, injected at build time.
509
581
  * @internal
510
582
  */
511
- const VERSION = '0.3.15';
583
+ const VERSION = '0.4.0';
512
584
 
513
585
  async function registerAdvancedSecurityPluginFactories(registrar = factory.Registry) {
514
586
  await registerAdvancedSecurityFactories(registrar, { includeExtras: true });
@@ -533,6 +605,8 @@ const advancedSecurityPlugin = {
533
605
  try {
534
606
  // console.log('[naylence:advanced-security] registering advanced security factories...');
535
607
  await registerAdvancedSecurityPluginFactories();
608
+ // Import modules with side-effect registrations (not in manifest)
609
+ await Promise.resolve().then(function () { return strictOverlaySecurityProfile; });
536
610
  // console.log('[naylence:advanced-security] advanced security factories registered');
537
611
  initialized = true;
538
612
  }
@@ -552,6 +626,2713 @@ var plugin = /*#__PURE__*/Object.freeze({
552
626
  registerAdvancedSecurityPluginFactories: registerAdvancedSecurityPluginFactories
553
627
  });
554
628
 
629
+ /**
630
+ * Abstract Syntax Tree (AST) node types for the expression language.
631
+ *
632
+ * The AST is produced by the parser and consumed by the evaluator.
633
+ */
634
+ // ============================================================
635
+ // AST Utilities
636
+ // ============================================================
637
+ /**
638
+ * Counts the total number of nodes in an AST.
639
+ */
640
+ function countAstNodes(node) {
641
+ let count = 1;
642
+ switch (node.type) {
643
+ case "StringLiteral":
644
+ case "NumberLiteral":
645
+ case "BooleanLiteral":
646
+ case "NullLiteral":
647
+ case "Identifier":
648
+ return count;
649
+ case "ArrayLiteral":
650
+ for (const element of node.elements) {
651
+ count += countAstNodes(element);
652
+ }
653
+ return count;
654
+ case "MemberAccess":
655
+ return count + countAstNodes(node.object);
656
+ case "IndexAccess":
657
+ return count + countAstNodes(node.object) + countAstNodes(node.index);
658
+ case "FunctionCall":
659
+ for (const arg of node.args) {
660
+ count += countAstNodes(arg);
661
+ }
662
+ return count;
663
+ case "UnaryOp":
664
+ return count + countAstNodes(node.operand);
665
+ case "BinaryOp":
666
+ return count + countAstNodes(node.left) + countAstNodes(node.right);
667
+ case "TernaryOp":
668
+ return (count +
669
+ countAstNodes(node.condition) +
670
+ countAstNodes(node.consequent) +
671
+ countAstNodes(node.alternate));
672
+ }
673
+ }
674
+ /**
675
+ * Calculates the maximum depth of an AST.
676
+ */
677
+ function calculateAstDepth(node) {
678
+ switch (node.type) {
679
+ case "StringLiteral":
680
+ case "NumberLiteral":
681
+ case "BooleanLiteral":
682
+ case "NullLiteral":
683
+ case "Identifier":
684
+ return 1;
685
+ case "ArrayLiteral": {
686
+ let maxChildDepth = 0;
687
+ for (const element of node.elements) {
688
+ maxChildDepth = Math.max(maxChildDepth, calculateAstDepth(element));
689
+ }
690
+ return 1 + maxChildDepth;
691
+ }
692
+ case "MemberAccess":
693
+ return 1 + calculateAstDepth(node.object);
694
+ case "IndexAccess":
695
+ return (1 +
696
+ Math.max(calculateAstDepth(node.object), calculateAstDepth(node.index)));
697
+ case "FunctionCall": {
698
+ let maxArgDepth = 0;
699
+ for (const arg of node.args) {
700
+ maxArgDepth = Math.max(maxArgDepth, calculateAstDepth(arg));
701
+ }
702
+ return 1 + maxArgDepth;
703
+ }
704
+ case "UnaryOp":
705
+ return 1 + calculateAstDepth(node.operand);
706
+ case "BinaryOp":
707
+ return (1 +
708
+ Math.max(calculateAstDepth(node.left), calculateAstDepth(node.right)));
709
+ case "TernaryOp":
710
+ return (1 +
711
+ Math.max(calculateAstDepth(node.condition), calculateAstDepth(node.consequent), calculateAstDepth(node.alternate)));
712
+ }
713
+ }
714
+ /**
715
+ * Returns a human-readable representation of an AST node for debugging.
716
+ */
717
+ function astToString(node, indent = 0) {
718
+ const prefix = " ".repeat(indent);
719
+ switch (node.type) {
720
+ case "StringLiteral":
721
+ return `${prefix}String: "${node.value}"`;
722
+ case "NumberLiteral":
723
+ return `${prefix}Number: ${node.value}`;
724
+ case "BooleanLiteral":
725
+ return `${prefix}Boolean: ${node.value}`;
726
+ case "NullLiteral":
727
+ return `${prefix}Null`;
728
+ case "ArrayLiteral":
729
+ return (`${prefix}Array:\n` +
730
+ node.elements.map((e) => astToString(e, indent + 1)).join("\n"));
731
+ case "Identifier":
732
+ return `${prefix}Identifier: ${node.name}`;
733
+ case "MemberAccess":
734
+ return (`${prefix}MemberAccess: .${node.property}\n` +
735
+ astToString(node.object, indent + 1));
736
+ case "IndexAccess":
737
+ return (`${prefix}IndexAccess:\n` +
738
+ `${prefix} object:\n` +
739
+ astToString(node.object, indent + 2) +
740
+ `\n${prefix} index:\n` +
741
+ astToString(node.index, indent + 2));
742
+ case "FunctionCall":
743
+ return (`${prefix}FunctionCall: ${node.name}\n` +
744
+ node.args.map((a) => astToString(a, indent + 1)).join("\n"));
745
+ case "UnaryOp":
746
+ return (`${prefix}UnaryOp: ${node.operator}\n` +
747
+ astToString(node.operand, indent + 1));
748
+ case "BinaryOp":
749
+ return (`${prefix}BinaryOp: ${node.operator}\n` +
750
+ astToString(node.left, indent + 1) +
751
+ "\n" +
752
+ astToString(node.right, indent + 1));
753
+ case "TernaryOp":
754
+ return (`${prefix}TernaryOp:\n` +
755
+ `${prefix} condition:\n` +
756
+ astToString(node.condition, indent + 2) +
757
+ `\n${prefix} consequent:\n` +
758
+ astToString(node.consequent, indent + 2) +
759
+ `\n${prefix} alternate:\n` +
760
+ astToString(node.alternate, indent + 2));
761
+ }
762
+ }
763
+
764
+ /**
765
+ * Error types for the expression evaluation engine.
766
+ *
767
+ * All expression errors extend ExpressionError for consistent handling.
768
+ */
769
+ /**
770
+ * Base error class for all expression-related errors.
771
+ */
772
+ class ExpressionError extends Error {
773
+ constructor(message, position, expression) {
774
+ super(message);
775
+ this.name = "ExpressionError";
776
+ this.position = position;
777
+ this.expression = expression;
778
+ }
779
+ /**
780
+ * Returns a formatted error message with position context.
781
+ */
782
+ formatWithContext() {
783
+ if (this.expression === undefined || this.position === undefined) {
784
+ return this.message;
785
+ }
786
+ const pointer = " ".repeat(this.position) + "^";
787
+ return `${this.message}\n ${this.expression}\n ${pointer}`;
788
+ }
789
+ }
790
+ /**
791
+ * Error thrown during tokenization (lexical analysis).
792
+ */
793
+ class TokenizerError extends ExpressionError {
794
+ constructor(message, position, expression) {
795
+ super(message, position, expression);
796
+ this.name = "TokenizerError";
797
+ }
798
+ }
799
+ /**
800
+ * Error thrown during parsing (syntax analysis).
801
+ */
802
+ class ParseError extends ExpressionError {
803
+ constructor(message, position, expression) {
804
+ super(message, position, expression);
805
+ this.name = "ParseError";
806
+ }
807
+ }
808
+ /**
809
+ * Error thrown during evaluation (runtime error).
810
+ */
811
+ class EvaluationError extends ExpressionError {
812
+ constructor(message, position, expression, path) {
813
+ super(message, position, expression);
814
+ this.name = "EvaluationError";
815
+ this.path = path;
816
+ }
817
+ }
818
+ /**
819
+ * Error thrown for type mismatches during evaluation.
820
+ */
821
+ class TypeError extends EvaluationError {
822
+ constructor(expected, actual, position, expression) {
823
+ super(`Type error: expected ${expected}, got ${actual}`, position, expression);
824
+ this.name = "TypeError";
825
+ this.expected = expected;
826
+ this.actual = actual;
827
+ }
828
+ }
829
+ /**
830
+ * Error thrown when expression limits are exceeded.
831
+ */
832
+ class LimitExceededError extends ExpressionError {
833
+ constructor(limitName, limit, actual) {
834
+ super(`Limit exceeded: ${limitName} (limit: ${limit}, actual: ${actual})`);
835
+ this.name = "LimitExceededError";
836
+ this.limitName = limitName;
837
+ this.limit = limit;
838
+ this.actual = actual;
839
+ }
840
+ }
841
+ /**
842
+ * Error thrown when a built-in function encounters an error.
843
+ */
844
+ class BuiltinError extends EvaluationError {
845
+ constructor(functionName, message, position, expression) {
846
+ super(`${functionName}: ${message}`, position, expression);
847
+ this.name = "BuiltinError";
848
+ this.functionName = functionName;
849
+ }
850
+ }
851
+
852
+ /**
853
+ * Resource limits for expression parsing and evaluation.
854
+ *
855
+ * These limits protect against resource exhaustion attacks and
856
+ * overly complex expressions.
857
+ */
858
+ /**
859
+ * Default expression limits.
860
+ *
861
+ * These values are chosen to allow reasonable expressions while
862
+ * preventing resource exhaustion.
863
+ */
864
+ const DEFAULT_EXPRESSION_LIMITS = {
865
+ maxExpressionLength: 4096,
866
+ maxAstDepth: 32,
867
+ maxAstNodes: 256,
868
+ maxRegexPatternLength: 256,
869
+ maxGlobPatternLength: 256,
870
+ maxStringLength: 1024,
871
+ maxArrayLength: 64,
872
+ maxFunctionArgs: 16,
873
+ maxMemberAccessDepth: 16,
874
+ };
875
+ /**
876
+ * Validates that expression length is within limits.
877
+ */
878
+ function checkExpressionLength(expression, limits = DEFAULT_EXPRESSION_LIMITS) {
879
+ if (expression.length > limits.maxExpressionLength) {
880
+ throw new Error(`Expression length ${expression.length} exceeds limit of ${limits.maxExpressionLength}`);
881
+ }
882
+ }
883
+ /**
884
+ * Validates AST depth during parsing.
885
+ */
886
+ function checkAstDepth(depth, limits = DEFAULT_EXPRESSION_LIMITS) {
887
+ if (depth > limits.maxAstDepth) {
888
+ throw new Error(`AST depth ${depth} exceeds limit of ${limits.maxAstDepth}`);
889
+ }
890
+ }
891
+ /**
892
+ * Validates AST node count during parsing.
893
+ */
894
+ function checkAstNodeCount(count, limits = DEFAULT_EXPRESSION_LIMITS) {
895
+ if (count > limits.maxAstNodes) {
896
+ throw new Error(`AST node count ${count} exceeds limit of ${limits.maxAstNodes}`);
897
+ }
898
+ }
899
+ /**
900
+ * Validates regex pattern length before compilation.
901
+ */
902
+ function checkRegexPatternLength(pattern, limits = DEFAULT_EXPRESSION_LIMITS) {
903
+ if (pattern.length > limits.maxRegexPatternLength) {
904
+ throw new Error(`Regex pattern length ${pattern.length} exceeds limit of ${limits.maxRegexPatternLength}`);
905
+ }
906
+ }
907
+ /**
908
+ * Validates glob pattern length before compilation.
909
+ */
910
+ function checkGlobPatternLength(pattern, limits = DEFAULT_EXPRESSION_LIMITS) {
911
+ if (pattern.length > limits.maxGlobPatternLength) {
912
+ throw new Error(`Glob pattern length ${pattern.length} exceeds limit of ${limits.maxGlobPatternLength}`);
913
+ }
914
+ }
915
+ /**
916
+ * Validates array length during evaluation.
917
+ */
918
+ function checkArrayLength(length, limits = DEFAULT_EXPRESSION_LIMITS) {
919
+ if (length > limits.maxArrayLength) {
920
+ throw new Error(`Array length ${length} exceeds limit of ${limits.maxArrayLength}`);
921
+ }
922
+ }
923
+ /**
924
+ * Validates function argument count.
925
+ */
926
+ function checkFunctionArgCount(count, limits = DEFAULT_EXPRESSION_LIMITS) {
927
+ if (count > limits.maxFunctionArgs) {
928
+ throw new Error(`Function argument count ${count} exceeds limit of ${limits.maxFunctionArgs}`);
929
+ }
930
+ }
931
+
932
+ /**
933
+ * Tokenizer (lexer) for the expression language.
934
+ *
935
+ * Converts expression strings into a stream of tokens for the parser.
936
+ */
937
+ /**
938
+ * Keywords recognized by the tokenizer.
939
+ */
940
+ const KEYWORDS = new Map([
941
+ ["true", "TRUE"],
942
+ ["false", "FALSE"],
943
+ ["null", "NULL"],
944
+ ["in", "IN"],
945
+ ["not", "NOT"],
946
+ ]);
947
+ /**
948
+ * Checks if a character is a digit.
949
+ */
950
+ function isDigit(ch) {
951
+ return ch >= "0" && ch <= "9";
952
+ }
953
+ /**
954
+ * Checks if a character can start an identifier.
955
+ */
956
+ function isIdentifierStart(ch) {
957
+ return ((ch >= "a" && ch <= "z") ||
958
+ (ch >= "A" && ch <= "Z") ||
959
+ ch === "_");
960
+ }
961
+ /**
962
+ * Checks if a character can continue an identifier.
963
+ */
964
+ function isIdentifierPart(ch) {
965
+ return isIdentifierStart(ch) || isDigit(ch);
966
+ }
967
+ /**
968
+ * Checks if a character is whitespace.
969
+ */
970
+ function isWhitespace(ch) {
971
+ return ch === " " || ch === "\t" || ch === "\n" || ch === "\r";
972
+ }
973
+ /**
974
+ * Tokenizer for expression strings.
975
+ */
976
+ class Tokenizer {
977
+ constructor(source, limits) {
978
+ this.position = 0;
979
+ this.tokens = [];
980
+ this.source = source;
981
+ this.limits = limits;
982
+ }
983
+ /**
984
+ * Tokenizes the source expression and returns all tokens.
985
+ */
986
+ tokenize() {
987
+ checkExpressionLength(this.source, this.limits);
988
+ while (!this.isAtEnd()) {
989
+ this.scanToken();
990
+ }
991
+ this.tokens.push({
992
+ type: "EOF",
993
+ value: "",
994
+ position: this.position,
995
+ });
996
+ return this.tokens;
997
+ }
998
+ isAtEnd() {
999
+ return this.position >= this.source.length;
1000
+ }
1001
+ peek() {
1002
+ if (this.isAtEnd())
1003
+ return "\0";
1004
+ return this.source[this.position];
1005
+ }
1006
+ peekNext() {
1007
+ if (this.position + 1 >= this.source.length)
1008
+ return "\0";
1009
+ return this.source[this.position + 1];
1010
+ }
1011
+ advance() {
1012
+ return this.source[this.position++];
1013
+ }
1014
+ addToken(type, value, position) {
1015
+ this.tokens.push({ type, value, position });
1016
+ }
1017
+ scanToken() {
1018
+ const ch = this.advance();
1019
+ const startPosition = this.position - 1;
1020
+ // Skip whitespace
1021
+ if (isWhitespace(ch)) {
1022
+ return;
1023
+ }
1024
+ // Single-character tokens
1025
+ switch (ch) {
1026
+ case "(":
1027
+ this.addToken("LPAREN", "(", startPosition);
1028
+ return;
1029
+ case ")":
1030
+ this.addToken("RPAREN", ")", startPosition);
1031
+ return;
1032
+ case "[":
1033
+ this.addToken("LBRACKET", "[", startPosition);
1034
+ return;
1035
+ case "]":
1036
+ this.addToken("RBRACKET", "]", startPosition);
1037
+ return;
1038
+ case ".":
1039
+ this.addToken("DOT", ".", startPosition);
1040
+ return;
1041
+ case ",":
1042
+ this.addToken("COMMA", ",", startPosition);
1043
+ return;
1044
+ case "+":
1045
+ this.addToken("PLUS", "+", startPosition);
1046
+ return;
1047
+ case "-":
1048
+ this.addToken("MINUS", "-", startPosition);
1049
+ return;
1050
+ case "*":
1051
+ this.addToken("STAR", "*", startPosition);
1052
+ return;
1053
+ case "/":
1054
+ this.addToken("SLASH", "/", startPosition);
1055
+ return;
1056
+ case "%":
1057
+ this.addToken("PERCENT", "%", startPosition);
1058
+ return;
1059
+ case "?":
1060
+ this.addToken("QUESTION", "?", startPosition);
1061
+ return;
1062
+ case ":":
1063
+ this.addToken("COLON", ":", startPosition);
1064
+ return;
1065
+ }
1066
+ // Two-character operators
1067
+ if (ch === "<") {
1068
+ if (this.peek() === "=") {
1069
+ this.advance();
1070
+ this.addToken("LE", "<=", startPosition);
1071
+ }
1072
+ else {
1073
+ this.addToken("LT", "<", startPosition);
1074
+ }
1075
+ return;
1076
+ }
1077
+ if (ch === ">") {
1078
+ if (this.peek() === "=") {
1079
+ this.advance();
1080
+ this.addToken("GE", ">=", startPosition);
1081
+ }
1082
+ else {
1083
+ this.addToken("GT", ">", startPosition);
1084
+ }
1085
+ return;
1086
+ }
1087
+ if (ch === "=") {
1088
+ if (this.peek() === "=") {
1089
+ this.advance();
1090
+ this.addToken("EQ", "==", startPosition);
1091
+ return;
1092
+ }
1093
+ throw new TokenizerError("Unexpected '='. Did you mean '=='?", startPosition, this.source);
1094
+ }
1095
+ if (ch === "!") {
1096
+ if (this.peek() === "=") {
1097
+ this.advance();
1098
+ this.addToken("NE", "!=", startPosition);
1099
+ }
1100
+ else {
1101
+ this.addToken("NOT", "!", startPosition);
1102
+ }
1103
+ return;
1104
+ }
1105
+ if (ch === "&") {
1106
+ if (this.peek() === "&") {
1107
+ this.advance();
1108
+ this.addToken("AND", "&&", startPosition);
1109
+ return;
1110
+ }
1111
+ throw new TokenizerError("Unexpected '&'. Did you mean '&&'?", startPosition, this.source);
1112
+ }
1113
+ if (ch === "|") {
1114
+ if (this.peek() === "|") {
1115
+ this.advance();
1116
+ this.addToken("OR", "||", startPosition);
1117
+ return;
1118
+ }
1119
+ throw new TokenizerError("Unexpected '|'. Did you mean '||'?", startPosition, this.source);
1120
+ }
1121
+ // String literals
1122
+ if (ch === '"' || ch === "'") {
1123
+ this.scanString(ch, startPosition);
1124
+ return;
1125
+ }
1126
+ // Number literals
1127
+ if (isDigit(ch)) {
1128
+ this.scanNumber(startPosition);
1129
+ return;
1130
+ }
1131
+ // Identifiers and keywords
1132
+ if (isIdentifierStart(ch)) {
1133
+ this.scanIdentifier(startPosition);
1134
+ return;
1135
+ }
1136
+ throw new TokenizerError(`Unexpected character: '${ch}'`, startPosition, this.source);
1137
+ }
1138
+ scanString(quote, startPosition) {
1139
+ let value = "";
1140
+ while (!this.isAtEnd() && this.peek() !== quote) {
1141
+ const ch = this.advance();
1142
+ if (ch === "\\") {
1143
+ // Escape sequence
1144
+ if (this.isAtEnd()) {
1145
+ throw new TokenizerError("Unterminated string", startPosition, this.source);
1146
+ }
1147
+ const escaped = this.advance();
1148
+ switch (escaped) {
1149
+ case "n":
1150
+ value += "\n";
1151
+ break;
1152
+ case "r":
1153
+ value += "\r";
1154
+ break;
1155
+ case "t":
1156
+ value += "\t";
1157
+ break;
1158
+ case "\\":
1159
+ value += "\\";
1160
+ break;
1161
+ case '"':
1162
+ value += '"';
1163
+ break;
1164
+ case "'":
1165
+ value += "'";
1166
+ break;
1167
+ default:
1168
+ throw new TokenizerError(`Invalid escape sequence: \\${escaped}`, this.position - 2, this.source);
1169
+ }
1170
+ }
1171
+ else if (ch === "\n" || ch === "\r") {
1172
+ throw new TokenizerError("Unterminated string (newline in string literal)", startPosition, this.source);
1173
+ }
1174
+ else {
1175
+ value += ch;
1176
+ }
1177
+ }
1178
+ if (this.isAtEnd()) {
1179
+ throw new TokenizerError("Unterminated string", startPosition, this.source);
1180
+ }
1181
+ // Consume closing quote
1182
+ this.advance();
1183
+ this.addToken("STRING", value, startPosition);
1184
+ }
1185
+ scanNumber(startPosition) {
1186
+ // Back up to include the first digit
1187
+ this.position--;
1188
+ let value = "";
1189
+ // Integer part
1190
+ while (isDigit(this.peek())) {
1191
+ value += this.advance();
1192
+ }
1193
+ // Fractional part
1194
+ if (this.peek() === "." && isDigit(this.peekNext())) {
1195
+ value += this.advance(); // consume '.'
1196
+ while (isDigit(this.peek())) {
1197
+ value += this.advance();
1198
+ }
1199
+ }
1200
+ // Exponent part
1201
+ if (this.peek() === "e" || this.peek() === "E") {
1202
+ value += this.advance();
1203
+ if (this.peek() === "+" || this.peek() === "-") {
1204
+ value += this.advance();
1205
+ }
1206
+ if (!isDigit(this.peek())) {
1207
+ throw new TokenizerError("Invalid number: expected exponent digits", startPosition, this.source);
1208
+ }
1209
+ while (isDigit(this.peek())) {
1210
+ value += this.advance();
1211
+ }
1212
+ }
1213
+ this.addToken("NUMBER", value, startPosition);
1214
+ }
1215
+ scanIdentifier(startPosition) {
1216
+ // Back up to include the first character
1217
+ this.position--;
1218
+ let value = "";
1219
+ while (isIdentifierPart(this.peek())) {
1220
+ value += this.advance();
1221
+ }
1222
+ // Check for "not in" compound keyword
1223
+ const valueLower = value.toLowerCase();
1224
+ if (valueLower === "not") {
1225
+ // Check if followed by whitespace and "in"
1226
+ const savedPosition = this.position;
1227
+ // Skip whitespace
1228
+ while (isWhitespace(this.peek())) {
1229
+ this.advance();
1230
+ }
1231
+ // Check for "in"
1232
+ if (this.peek() === "i" &&
1233
+ this.peekNext() === "n" &&
1234
+ !isIdentifierPart(this.source[this.position + 2] ?? "\0")) {
1235
+ this.advance(); // consume 'i'
1236
+ this.advance(); // consume 'n'
1237
+ this.addToken("NOT_IN", "not in", startPosition);
1238
+ return;
1239
+ }
1240
+ // Not "not in", restore position
1241
+ this.position = savedPosition;
1242
+ }
1243
+ // Check for keyword
1244
+ const keywordType = KEYWORDS.get(valueLower);
1245
+ if (keywordType) {
1246
+ this.addToken(keywordType, value, startPosition);
1247
+ }
1248
+ else {
1249
+ this.addToken("IDENTIFIER", value, startPosition);
1250
+ }
1251
+ }
1252
+ }
1253
+ /**
1254
+ * Tokenizes an expression string into tokens.
1255
+ *
1256
+ * @param source - The expression string to tokenize
1257
+ * @param limits - Optional expression limits
1258
+ * @returns Array of tokens
1259
+ * @throws TokenizerError if the expression contains invalid tokens
1260
+ */
1261
+ function tokenize(source, limits) {
1262
+ const tokenizer = new Tokenizer(source, limits);
1263
+ return tokenizer.tokenize();
1264
+ }
1265
+
1266
+ /**
1267
+ * Parser for the expression language.
1268
+ *
1269
+ * Parses a stream of tokens into an Abstract Syntax Tree (AST).
1270
+ * Uses recursive descent parsing with operator precedence.
1271
+ *
1272
+ * Precedence (lowest to highest):
1273
+ * 1. Ternary: ? :
1274
+ * 2. Logical OR: ||
1275
+ * 3. Logical AND: &&
1276
+ * 4. Membership: in, not in
1277
+ * 5. Equality: ==, !=
1278
+ * 6. Comparison: <, <=, >, >=
1279
+ * 7. Additive: +, -
1280
+ * 8. Multiplicative: *, /, %
1281
+ * 9. Unary: !, -
1282
+ * 10. Postfix: . [] ()
1283
+ * 11. Primary: literals, identifiers, parentheses
1284
+ */
1285
+ /**
1286
+ * Parser for expression strings.
1287
+ */
1288
+ class Parser {
1289
+ constructor(tokens, source, limits = DEFAULT_EXPRESSION_LIMITS) {
1290
+ this.current = 0;
1291
+ this.tokens = tokens;
1292
+ this.source = source;
1293
+ this.limits = limits;
1294
+ }
1295
+ /**
1296
+ * Parses the token stream into an AST.
1297
+ */
1298
+ parse() {
1299
+ const ast = this.parseTernary();
1300
+ if (!this.isAtEnd()) {
1301
+ const token = this.peek();
1302
+ throw new ParseError(`Unexpected token: ${token.value || token.type}`, token.position, this.source);
1303
+ }
1304
+ // Validate AST limits
1305
+ const nodeCount = countAstNodes(ast);
1306
+ checkAstNodeCount(nodeCount, this.limits);
1307
+ const depth = calculateAstDepth(ast);
1308
+ checkAstDepth(depth, this.limits);
1309
+ return ast;
1310
+ }
1311
+ // ============================================================
1312
+ // Token Helpers
1313
+ // ============================================================
1314
+ isAtEnd() {
1315
+ return this.peek().type === "EOF";
1316
+ }
1317
+ peek() {
1318
+ return this.tokens[this.current];
1319
+ }
1320
+ previous() {
1321
+ return this.tokens[this.current - 1];
1322
+ }
1323
+ advance() {
1324
+ if (!this.isAtEnd()) {
1325
+ this.current++;
1326
+ }
1327
+ return this.previous();
1328
+ }
1329
+ check(type) {
1330
+ if (this.isAtEnd())
1331
+ return false;
1332
+ return this.peek().type === type;
1333
+ }
1334
+ match(...types) {
1335
+ for (const type of types) {
1336
+ if (this.check(type)) {
1337
+ this.advance();
1338
+ return true;
1339
+ }
1340
+ }
1341
+ return false;
1342
+ }
1343
+ consume(type, message) {
1344
+ if (this.check(type)) {
1345
+ return this.advance();
1346
+ }
1347
+ const token = this.peek();
1348
+ throw new ParseError(message, token.position, this.source);
1349
+ }
1350
+ // ============================================================
1351
+ // Expression Parsing (by precedence, lowest to highest)
1352
+ // ============================================================
1353
+ /**
1354
+ * Parses ternary expressions: condition ? consequent : alternate
1355
+ */
1356
+ parseTernary() {
1357
+ const position = this.peek().position;
1358
+ let node = this.parseOr();
1359
+ if (this.match("QUESTION")) {
1360
+ const consequent = this.parseTernary();
1361
+ this.consume("COLON", "Expected ':' in ternary expression");
1362
+ const alternate = this.parseTernary();
1363
+ node = {
1364
+ type: "TernaryOp",
1365
+ position,
1366
+ condition: node,
1367
+ consequent,
1368
+ alternate,
1369
+ };
1370
+ }
1371
+ return node;
1372
+ }
1373
+ /**
1374
+ * Parses logical OR: ||
1375
+ */
1376
+ parseOr() {
1377
+ let node = this.parseAnd();
1378
+ while (this.match("OR")) {
1379
+ const position = this.previous().position;
1380
+ const right = this.parseAnd();
1381
+ node = {
1382
+ type: "BinaryOp",
1383
+ position,
1384
+ operator: "||",
1385
+ left: node,
1386
+ right,
1387
+ };
1388
+ }
1389
+ return node;
1390
+ }
1391
+ /**
1392
+ * Parses logical AND: &&
1393
+ */
1394
+ parseAnd() {
1395
+ let node = this.parseEquality();
1396
+ while (this.match("AND")) {
1397
+ const position = this.previous().position;
1398
+ const right = this.parseEquality();
1399
+ node = {
1400
+ type: "BinaryOp",
1401
+ position,
1402
+ operator: "&&",
1403
+ left: node,
1404
+ right,
1405
+ };
1406
+ }
1407
+ return node;
1408
+ }
1409
+ /**
1410
+ * Parses equality: ==, !=
1411
+ */
1412
+ parseEquality() {
1413
+ let node = this.parseMembership();
1414
+ while (this.match("EQ", "NE")) {
1415
+ const operator = this.previous().type === "EQ" ? "==" : "!=";
1416
+ const position = this.previous().position;
1417
+ const right = this.parseMembership();
1418
+ node = {
1419
+ type: "BinaryOp",
1420
+ position,
1421
+ operator: operator,
1422
+ left: node,
1423
+ right,
1424
+ };
1425
+ }
1426
+ return node;
1427
+ }
1428
+ /**
1429
+ * Parses membership: in, not in
1430
+ */
1431
+ parseMembership() {
1432
+ let node = this.parseComparison();
1433
+ while (this.match("IN", "NOT_IN")) {
1434
+ const operator = this.previous().type === "IN" ? "in" : "not in";
1435
+ const position = this.previous().position;
1436
+ const right = this.parseComparison();
1437
+ node = {
1438
+ type: "BinaryOp",
1439
+ position,
1440
+ operator: operator,
1441
+ left: node,
1442
+ right,
1443
+ };
1444
+ }
1445
+ return node;
1446
+ }
1447
+ /**
1448
+ * Parses comparison: <, <=, >, >=
1449
+ */
1450
+ parseComparison() {
1451
+ let node = this.parseAdditive();
1452
+ while (this.match("LT", "LE", "GT", "GE")) {
1453
+ const token = this.previous();
1454
+ let operator;
1455
+ switch (token.type) {
1456
+ case "LT":
1457
+ operator = "<";
1458
+ break;
1459
+ case "LE":
1460
+ operator = "<=";
1461
+ break;
1462
+ case "GT":
1463
+ operator = ">";
1464
+ break;
1465
+ case "GE":
1466
+ operator = ">=";
1467
+ break;
1468
+ default:
1469
+ throw new ParseError(`Unexpected token: ${token.type}`, token.position, this.source);
1470
+ }
1471
+ const position = token.position;
1472
+ const right = this.parseAdditive();
1473
+ node = {
1474
+ type: "BinaryOp",
1475
+ position,
1476
+ operator,
1477
+ left: node,
1478
+ right,
1479
+ };
1480
+ }
1481
+ return node;
1482
+ }
1483
+ /**
1484
+ * Parses additive: +, -
1485
+ */
1486
+ parseAdditive() {
1487
+ let node = this.parseMultiplicative();
1488
+ while (this.match("PLUS", "MINUS")) {
1489
+ const operator = this.previous().type === "PLUS" ? "+" : "-";
1490
+ const position = this.previous().position;
1491
+ const right = this.parseMultiplicative();
1492
+ node = {
1493
+ type: "BinaryOp",
1494
+ position,
1495
+ operator: operator,
1496
+ left: node,
1497
+ right,
1498
+ };
1499
+ }
1500
+ return node;
1501
+ }
1502
+ /**
1503
+ * Parses multiplicative: *, /, %
1504
+ */
1505
+ parseMultiplicative() {
1506
+ let node = this.parseUnary();
1507
+ while (this.match("STAR", "SLASH", "PERCENT")) {
1508
+ const token = this.previous();
1509
+ let operator;
1510
+ switch (token.type) {
1511
+ case "STAR":
1512
+ operator = "*";
1513
+ break;
1514
+ case "SLASH":
1515
+ operator = "/";
1516
+ break;
1517
+ case "PERCENT":
1518
+ operator = "%";
1519
+ break;
1520
+ default:
1521
+ throw new ParseError(`Unexpected token: ${token.type}`, token.position, this.source);
1522
+ }
1523
+ const position = token.position;
1524
+ const right = this.parseUnary();
1525
+ node = {
1526
+ type: "BinaryOp",
1527
+ position,
1528
+ operator,
1529
+ left: node,
1530
+ right,
1531
+ };
1532
+ }
1533
+ return node;
1534
+ }
1535
+ /**
1536
+ * Parses unary: !, -
1537
+ */
1538
+ parseUnary() {
1539
+ if (this.match("NOT", "MINUS")) {
1540
+ const token = this.previous();
1541
+ const operator = token.type === "NOT" ? "!" : "-";
1542
+ const position = token.position;
1543
+ const operand = this.parseUnary();
1544
+ return {
1545
+ type: "UnaryOp",
1546
+ position,
1547
+ operator,
1548
+ operand,
1549
+ };
1550
+ }
1551
+ return this.parsePostfix();
1552
+ }
1553
+ /**
1554
+ * Parses postfix: . [] ()
1555
+ */
1556
+ parsePostfix() {
1557
+ let node = this.parsePrimary();
1558
+ while (true) {
1559
+ if (this.match("DOT")) {
1560
+ const position = this.previous().position;
1561
+ const propToken = this.consume("IDENTIFIER", "Expected property name after '.'");
1562
+ node = {
1563
+ type: "MemberAccess",
1564
+ position,
1565
+ object: node,
1566
+ property: propToken.value,
1567
+ };
1568
+ }
1569
+ else if (this.match("LBRACKET")) {
1570
+ const position = this.previous().position;
1571
+ const index = this.parseTernary();
1572
+ this.consume("RBRACKET", "Expected ']' after index");
1573
+ node = {
1574
+ type: "IndexAccess",
1575
+ position,
1576
+ object: node,
1577
+ index,
1578
+ };
1579
+ }
1580
+ else if (this.match("LPAREN")) {
1581
+ // Function call - node must be an identifier
1582
+ if (node.type !== "Identifier") {
1583
+ throw new ParseError("Only named functions can be called", node.position, this.source);
1584
+ }
1585
+ const position = this.previous().position;
1586
+ const args = this.parseArgumentList();
1587
+ checkFunctionArgCount(args.length, this.limits);
1588
+ node = {
1589
+ type: "FunctionCall",
1590
+ position,
1591
+ name: node.name,
1592
+ args,
1593
+ };
1594
+ }
1595
+ else {
1596
+ break;
1597
+ }
1598
+ }
1599
+ return node;
1600
+ }
1601
+ /**
1602
+ * Parses function argument list (already consumed opening paren).
1603
+ */
1604
+ parseArgumentList() {
1605
+ const args = [];
1606
+ if (!this.check("RPAREN")) {
1607
+ do {
1608
+ args.push(this.parseTernary());
1609
+ } while (this.match("COMMA"));
1610
+ }
1611
+ this.consume("RPAREN", "Expected ')' after function arguments");
1612
+ return args;
1613
+ }
1614
+ /**
1615
+ * Parses primary expressions: literals, identifiers, parentheses, arrays.
1616
+ */
1617
+ parsePrimary() {
1618
+ const token = this.peek();
1619
+ const position = token.position;
1620
+ // Boolean literals
1621
+ if (this.match("TRUE")) {
1622
+ return { type: "BooleanLiteral", position, value: true };
1623
+ }
1624
+ if (this.match("FALSE")) {
1625
+ return { type: "BooleanLiteral", position, value: false };
1626
+ }
1627
+ // Null literal
1628
+ if (this.match("NULL")) {
1629
+ return { type: "NullLiteral", position };
1630
+ }
1631
+ // String literal
1632
+ if (this.match("STRING")) {
1633
+ return {
1634
+ type: "StringLiteral",
1635
+ position,
1636
+ value: this.previous().value,
1637
+ };
1638
+ }
1639
+ // Number literal
1640
+ if (this.match("NUMBER")) {
1641
+ const value = parseFloat(this.previous().value);
1642
+ if (!Number.isFinite(value)) {
1643
+ throw new ParseError("Invalid number", position, this.source);
1644
+ }
1645
+ return { type: "NumberLiteral", position, value };
1646
+ }
1647
+ // Identifier
1648
+ if (this.match("IDENTIFIER")) {
1649
+ return {
1650
+ type: "Identifier",
1651
+ position,
1652
+ name: this.previous().value,
1653
+ };
1654
+ }
1655
+ // Parenthesized expression
1656
+ if (this.match("LPAREN")) {
1657
+ const expr = this.parseTernary();
1658
+ this.consume("RPAREN", "Expected ')' after expression");
1659
+ return expr;
1660
+ }
1661
+ // Array literal
1662
+ if (this.match("LBRACKET")) {
1663
+ const elements = [];
1664
+ if (!this.check("RBRACKET")) {
1665
+ do {
1666
+ elements.push(this.parseTernary());
1667
+ } while (this.match("COMMA"));
1668
+ }
1669
+ this.consume("RBRACKET", "Expected ']' after array elements");
1670
+ checkArrayLength(elements.length, this.limits);
1671
+ return { type: "ArrayLiteral", position, elements };
1672
+ }
1673
+ throw new ParseError(`Unexpected token: ${token.value || token.type}`, position, this.source);
1674
+ }
1675
+ }
1676
+ /**
1677
+ * Parses an expression string into an AST.
1678
+ *
1679
+ * @param source - The expression string to parse
1680
+ * @param limits - Optional expression limits
1681
+ * @returns The parsed AST
1682
+ * @throws TokenizerError if tokenization fails
1683
+ * @throws ParseError if parsing fails
1684
+ */
1685
+ function parse(source, limits = DEFAULT_EXPRESSION_LIMITS) {
1686
+ const tokens = tokenize(source, limits);
1687
+ const parser = new Parser(tokens, source, limits);
1688
+ return parser.parse();
1689
+ }
1690
+
1691
+ /**
1692
+ * Built-in functions for the expression language.
1693
+ *
1694
+ * All built-in functions are pure and deterministic.
1695
+ *
1696
+ * Null handling semantics:
1697
+ * - `undefined` is normalized to `null` throughout the expression value model.
1698
+ * - Predicate-style builtins (starts_with, ends_with, contains, glob_match,
1699
+ * regex_match, etc.) return `false` when passed `null` for required args
1700
+ * instead of throwing an error.
1701
+ * - Wrong non-null types still raise BuiltinError to surface real bugs.
1702
+ * - Non-predicate operations (arithmetic, comparisons) remain strict.
1703
+ */
1704
+ /**
1705
+ * Normalizes a JavaScript value to an ExprValue.
1706
+ *
1707
+ * Rules:
1708
+ * - `undefined` -> `null`
1709
+ * - `null` -> `null`
1710
+ * - boolean/number/string -> returned as-is
1711
+ * - array -> elements are recursively normalized
1712
+ * - object -> returned as-is (reads will normalize on access)
1713
+ * - other types (function, symbol, etc.) -> `null`
1714
+ *
1715
+ * This ensures `undefined` never leaks into the expression value model.
1716
+ */
1717
+ function normalizeJsValue(value) {
1718
+ if (value === undefined || value === null) {
1719
+ return null;
1720
+ }
1721
+ if (typeof value === "boolean" || typeof value === "number") {
1722
+ return value;
1723
+ }
1724
+ if (typeof value === "string") {
1725
+ return value;
1726
+ }
1727
+ if (Array.isArray(value)) {
1728
+ return value.map((element) => normalizeJsValue(element));
1729
+ }
1730
+ if (typeof value === "object") {
1731
+ // Return the object as-is; reads will normalize on access
1732
+ return value;
1733
+ }
1734
+ // Function, symbol, bigint, etc. -> null
1735
+ return null;
1736
+ }
1737
+ /**
1738
+ * Gets the type name of a value for error messages.
1739
+ */
1740
+ function getTypeName(value) {
1741
+ if (value === null)
1742
+ return "null";
1743
+ if (Array.isArray(value))
1744
+ return "array";
1745
+ return typeof value;
1746
+ }
1747
+ /**
1748
+ * Asserts that a value is a string.
1749
+ */
1750
+ function assertString$1(value, argName, functionName) {
1751
+ if (typeof value !== "string") {
1752
+ throw new BuiltinError(functionName, `${argName} must be a string, got ${getTypeName(value)}`);
1753
+ }
1754
+ }
1755
+ /**
1756
+ * Checks if a value is null (for null-tolerant predicates).
1757
+ */
1758
+ function isNull$1(value) {
1759
+ return value === null;
1760
+ }
1761
+ /**
1762
+ * Asserts that a non-null value is a string (for null-tolerant predicates).
1763
+ * Returns false if the value is null (indicating predicate should return false).
1764
+ * Throws BuiltinError if the value is non-null but not a string.
1765
+ */
1766
+ function assertStringOrNull$1(value, argName, functionName) {
1767
+ if (isNull$1(value)) {
1768
+ return false;
1769
+ }
1770
+ if (typeof value !== "string") {
1771
+ throw new BuiltinError(functionName, `${argName} must be a string, got ${getTypeName(value)}`);
1772
+ }
1773
+ return true;
1774
+ }
1775
+ /**
1776
+ * Gets an argument by index, throwing if not present.
1777
+ */
1778
+ function getArg$1(args, index, functionName) {
1779
+ const value = args[index];
1780
+ if (value === undefined) {
1781
+ throw new BuiltinError(functionName, `missing argument at index ${index}`);
1782
+ }
1783
+ return value;
1784
+ }
1785
+ /**
1786
+ * Asserts argument count.
1787
+ */
1788
+ function assertArgCount$1(args, expected, functionName) {
1789
+ if (args.length !== expected) {
1790
+ throw new BuiltinError(functionName, `expected ${expected} argument(s), got ${args.length}`);
1791
+ }
1792
+ }
1793
+ /**
1794
+ * Asserts argument count range.
1795
+ */
1796
+ function assertArgCountRange(args, min, max, functionName) {
1797
+ if (args.length < min || args.length > max) {
1798
+ throw new BuiltinError(functionName, `expected ${min}-${max} argument(s), got ${args.length}`);
1799
+ }
1800
+ }
1801
+ // ============================================================
1802
+ // String Helpers
1803
+ // ============================================================
1804
+ /**
1805
+ * lower(s: string) -> string
1806
+ *
1807
+ * Returns the lowercase version of the string.
1808
+ */
1809
+ const lower = (args) => {
1810
+ assertArgCount$1(args, 1, "lower");
1811
+ const s = getArg$1(args, 0, "lower");
1812
+ assertString$1(s, "s", "lower");
1813
+ return s.toLowerCase();
1814
+ };
1815
+ /**
1816
+ * upper(s: string) -> string
1817
+ *
1818
+ * Returns the uppercase version of the string.
1819
+ */
1820
+ const upper = (args) => {
1821
+ assertArgCount$1(args, 1, "upper");
1822
+ const s = getArg$1(args, 0, "upper");
1823
+ assertString$1(s, "s", "upper");
1824
+ return s.toUpperCase();
1825
+ };
1826
+ /**
1827
+ * starts_with(s: string, prefix: string) -> bool
1828
+ *
1829
+ * Returns true if the string starts with the prefix.
1830
+ * Null-tolerant: returns false if either argument is null.
1831
+ */
1832
+ const starts_with = (args) => {
1833
+ assertArgCount$1(args, 2, "starts_with");
1834
+ const s = getArg$1(args, 0, "starts_with");
1835
+ const prefix = getArg$1(args, 1, "starts_with");
1836
+ // Null-tolerant: return false if either arg is null
1837
+ if (!assertStringOrNull$1(s, "s", "starts_with"))
1838
+ return false;
1839
+ if (!assertStringOrNull$1(prefix, "prefix", "starts_with"))
1840
+ return false;
1841
+ return s.startsWith(prefix);
1842
+ };
1843
+ /**
1844
+ * ends_with(s: string, suffix: string) -> bool
1845
+ *
1846
+ * Returns true if the string ends with the suffix.
1847
+ * Null-tolerant: returns false if either argument is null.
1848
+ */
1849
+ const ends_with = (args) => {
1850
+ assertArgCount$1(args, 2, "ends_with");
1851
+ const s = getArg$1(args, 0, "ends_with");
1852
+ const suffix = getArg$1(args, 1, "ends_with");
1853
+ // Null-tolerant: return false if either arg is null
1854
+ if (!assertStringOrNull$1(s, "s", "ends_with"))
1855
+ return false;
1856
+ if (!assertStringOrNull$1(suffix, "suffix", "ends_with"))
1857
+ return false;
1858
+ return s.endsWith(suffix);
1859
+ };
1860
+ /**
1861
+ * contains(s: string, substring: string) -> bool
1862
+ *
1863
+ * Returns true if the string contains the substring.
1864
+ * Null-tolerant: returns false if either argument is null.
1865
+ */
1866
+ const contains = (args) => {
1867
+ assertArgCount$1(args, 2, "contains");
1868
+ const s = getArg$1(args, 0, "contains");
1869
+ const substring = getArg$1(args, 1, "contains");
1870
+ // Null-tolerant: return false if either arg is null
1871
+ if (!assertStringOrNull$1(s, "s", "contains"))
1872
+ return false;
1873
+ if (!assertStringOrNull$1(substring, "substring", "contains"))
1874
+ return false;
1875
+ return s.includes(substring);
1876
+ };
1877
+ /**
1878
+ * split(s: string, separator: string) -> string[]
1879
+ *
1880
+ * Splits the string by the separator.
1881
+ */
1882
+ const split = (args) => {
1883
+ assertArgCountRange(args, 1, 2, "split");
1884
+ const s = getArg$1(args, 0, "split");
1885
+ assertString$1(s, "s", "split");
1886
+ const separator = args.length >= 2 ? getArg$1(args, 1, "split") : " ";
1887
+ assertString$1(separator, "separator", "split");
1888
+ return s.split(separator);
1889
+ };
1890
+ // ============================================================
1891
+ // Collection Helpers
1892
+ // ============================================================
1893
+ /**
1894
+ * len(x: string | array) -> number
1895
+ *
1896
+ * Returns the length of a string or array.
1897
+ */
1898
+ const len = (args) => {
1899
+ assertArgCount$1(args, 1, "len");
1900
+ const x = getArg$1(args, 0, "len");
1901
+ if (typeof x === "string") {
1902
+ return x.length;
1903
+ }
1904
+ if (Array.isArray(x)) {
1905
+ return x.length;
1906
+ }
1907
+ throw new BuiltinError("len", `expected string or array, got ${getTypeName(x)}`);
1908
+ };
1909
+ // ============================================================
1910
+ // Generic Helpers
1911
+ // ============================================================
1912
+ /**
1913
+ * exists(x: any) -> bool
1914
+ *
1915
+ * Returns true if the value is not null.
1916
+ * Missing bindings and missing properties evaluate to null, so this
1917
+ * can be used to check for presence.
1918
+ */
1919
+ const exists = (args) => {
1920
+ assertArgCount$1(args, 1, "exists");
1921
+ const x = getArg$1(args, 0, "exists");
1922
+ return x !== null;
1923
+ };
1924
+ /**
1925
+ * coalesce(a: any, b: any) -> any
1926
+ *
1927
+ * Returns `a` if it is not null, otherwise returns `b`.
1928
+ * This is useful for providing default values.
1929
+ */
1930
+ const coalesce = (args) => {
1931
+ assertArgCount$1(args, 2, "coalesce");
1932
+ const a = getArg$1(args, 0, "coalesce");
1933
+ const b = getArg$1(args, 1, "coalesce");
1934
+ return a !== null ? a : b;
1935
+ };
1936
+ /**
1937
+ * trim(s: string) -> string
1938
+ *
1939
+ * Trims whitespace from both ends of a string.
1940
+ * Returns an empty string if `s` is null (for convenient composition).
1941
+ * Throws BuiltinError if `s` is non-null but not a string.
1942
+ */
1943
+ const trim = (args) => {
1944
+ assertArgCount$1(args, 1, "trim");
1945
+ const s = getArg$1(args, 0, "trim");
1946
+ // Null-friendly: return empty string for null
1947
+ if (s === null) {
1948
+ return "";
1949
+ }
1950
+ // Strict type check for non-null values
1951
+ if (typeof s !== "string") {
1952
+ throw new BuiltinError("trim", `s must be a string, got ${getTypeName(s)}`);
1953
+ }
1954
+ return s.trim();
1955
+ };
1956
+ /**
1957
+ * secure_hash(input_str: string, length: number) -> string
1958
+ *
1959
+ * Generates a deterministic secure hash/fingerprint of the input string.
1960
+ * Uses SHA-256 hashing to create a stable identifier of the specified length.
1961
+ * Returns base62-encoded string (alphanumeric, case-sensitive).
1962
+ * Automatically rehashes if result contains blacklisted words.
1963
+ * Returns empty string if input_str is null (for convenient composition).
1964
+ * Throws BuiltinError if input_str is non-null but not a string, or if length is invalid.
1965
+ */
1966
+ const secure_hash = (args) => {
1967
+ assertArgCount$1(args, 2, "secure_hash");
1968
+ const input_str = getArg$1(args, 0, "secure_hash");
1969
+ const length = getArg$1(args, 1, "secure_hash");
1970
+ // Null-friendly: return empty string for null input
1971
+ if (input_str === null) {
1972
+ return "";
1973
+ }
1974
+ // Strict type check for input_str
1975
+ if (typeof input_str !== "string") {
1976
+ throw new BuiltinError("secure_hash", `input_str must be a string, got ${getTypeName(input_str)}`);
1977
+ }
1978
+ // Strict type check for length
1979
+ if (typeof length !== "number") {
1980
+ throw new BuiltinError("secure_hash", `length must be a number, got ${getTypeName(length)}`);
1981
+ }
1982
+ // Validate length is a positive integer
1983
+ if (!Number.isInteger(length) || length <= 0) {
1984
+ throw new BuiltinError("secure_hash", `length must be a positive integer, got ${length}`);
1985
+ }
1986
+ // Use generateFingerprintSync from @naylence/core
1987
+ // This provides SHA-256 hashing, base62 encoding, and profanity filtering
1988
+ return core.generateFingerprintSync(input_str, length, sha256.sha256);
1989
+ };
1990
+ // ============================================================
1991
+ // Pattern Helpers (BSL-only)
1992
+ // ============================================================
1993
+ /**
1994
+ * Escapes special regex characters in a string.
1995
+ */
1996
+ function escapeRegex(str) {
1997
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1998
+ }
1999
+ /**
2000
+ * Converts a glob pattern to a regex pattern.
2001
+ */
2002
+ function globToRegex(glob) {
2003
+ const parts = [];
2004
+ let i = 0;
2005
+ while (i < glob.length) {
2006
+ const ch = glob[i];
2007
+ if (ch === "*") {
2008
+ if (glob[i + 1] === "*") {
2009
+ // `**` matches any characters
2010
+ parts.push(".*");
2011
+ i += 2;
2012
+ }
2013
+ else {
2014
+ // `*` matches any characters except dots
2015
+ parts.push("[^.]*");
2016
+ i += 1;
2017
+ }
2018
+ }
2019
+ else if (ch === "?") {
2020
+ // `?` matches a single character
2021
+ parts.push("[^.]");
2022
+ i += 1;
2023
+ }
2024
+ else {
2025
+ parts.push(escapeRegex(ch));
2026
+ i += 1;
2027
+ }
2028
+ }
2029
+ return parts.join("");
2030
+ }
2031
+ /**
2032
+ * glob_match(value: string, pattern: string) -> bool
2033
+ *
2034
+ * Returns true if the value matches the glob pattern.
2035
+ * Glob syntax: * (single segment), ** (any depth), ? (single char)
2036
+ * Null-tolerant: returns false if either argument is null.
2037
+ */
2038
+ const glob_match = (args, context) => {
2039
+ assertArgCount$1(args, 2, "glob_match");
2040
+ const value = getArg$1(args, 0, "glob_match");
2041
+ const pattern = getArg$1(args, 1, "glob_match");
2042
+ // Null-tolerant: return false if either arg is null
2043
+ if (!assertStringOrNull$1(value, "value", "glob_match"))
2044
+ return false;
2045
+ if (!assertStringOrNull$1(pattern, "pattern", "glob_match"))
2046
+ return false;
2047
+ // Validate pattern length
2048
+ checkGlobPatternLength(pattern, context.limits);
2049
+ // Convert glob to regex
2050
+ const regexPattern = `^${globToRegex(pattern)}$`;
2051
+ try {
2052
+ const regex = new RegExp(regexPattern);
2053
+ return regex.test(value);
2054
+ }
2055
+ catch {
2056
+ throw new BuiltinError("glob_match", `invalid glob pattern: ${pattern}`);
2057
+ }
2058
+ };
2059
+ /**
2060
+ * Detects potentially catastrophic regex patterns.
2061
+ *
2062
+ * This is a best-effort heuristic check for common ReDoS patterns.
2063
+ */
2064
+ function isSafeRegex(pattern) {
2065
+ // Check for obvious catastrophic patterns:
2066
+ // - Nested quantifiers: (a+)+, (a*)*
2067
+ // - Overlapping alternation with quantifiers: (a|a)+
2068
+ // Simple heuristic: reject patterns with nested quantifiers
2069
+ const nestedQuantifiers = /([+*?]|\{\d+,?\d*\})\s*\)\s*([+*?]|\{\d+,?\d*\})/;
2070
+ if (nestedQuantifiers.test(pattern)) {
2071
+ return false;
2072
+ }
2073
+ // Reject patterns with excessive backtracking potential
2074
+ const excessiveBacktracking = /(\.\*){3,}|(\.\+){3,}/;
2075
+ if (excessiveBacktracking.test(pattern)) {
2076
+ return false;
2077
+ }
2078
+ return true;
2079
+ }
2080
+ /**
2081
+ * regex_match(value: string, pattern: string) -> bool
2082
+ *
2083
+ * Returns true if the value matches the regex pattern.
2084
+ * The pattern is anchored (full match).
2085
+ * Null-tolerant: returns false if either argument is null.
2086
+ */
2087
+ const regex_match = (args, context) => {
2088
+ assertArgCount$1(args, 2, "regex_match");
2089
+ const value = getArg$1(args, 0, "regex_match");
2090
+ const pattern = getArg$1(args, 1, "regex_match");
2091
+ // Null-tolerant: return false if either arg is null
2092
+ if (!assertStringOrNull$1(value, "value", "regex_match"))
2093
+ return false;
2094
+ if (!assertStringOrNull$1(pattern, "pattern", "regex_match"))
2095
+ return false;
2096
+ // Validate pattern length
2097
+ checkRegexPatternLength(pattern, context.limits);
2098
+ // Check for potentially unsafe patterns
2099
+ if (!isSafeRegex(pattern)) {
2100
+ throw new BuiltinError("regex_match", `pattern may cause excessive backtracking: ${pattern}`);
2101
+ }
2102
+ // Anchor the pattern for full match
2103
+ const anchoredPattern = pattern.startsWith("^")
2104
+ ? pattern
2105
+ : pattern.endsWith("$")
2106
+ ? pattern
2107
+ : `^(?:${pattern})$`;
2108
+ try {
2109
+ const regex = new RegExp(anchoredPattern);
2110
+ return regex.test(value);
2111
+ }
2112
+ catch (error) {
2113
+ throw new BuiltinError("regex_match", `invalid regex pattern: ${pattern} - ${error instanceof Error ? error.message : String(error)}`);
2114
+ }
2115
+ };
2116
+ // ============================================================
2117
+ // Registry
2118
+ // ============================================================
2119
+ /**
2120
+ * Registry of all built-in functions.
2121
+ */
2122
+ const BUILTIN_FUNCTIONS = new Map([
2123
+ // String helpers
2124
+ ["lower", lower],
2125
+ ["upper", upper],
2126
+ ["starts_with", starts_with],
2127
+ ["ends_with", ends_with],
2128
+ ["contains", contains],
2129
+ ["split", split],
2130
+ ["trim", trim],
2131
+ // Collection helpers
2132
+ ["len", len],
2133
+ // Generic helpers
2134
+ ["exists", exists],
2135
+ ["coalesce", coalesce],
2136
+ ["secure_hash", secure_hash],
2137
+ // Pattern helpers
2138
+ ["glob_match", glob_match],
2139
+ ["regex_match", regex_match],
2140
+ ]);
2141
+ /**
2142
+ * Calls a built-in function by name.
2143
+ *
2144
+ * @param name - The function name
2145
+ * @param args - The function arguments
2146
+ * @param context - The evaluation context
2147
+ * @returns The function result
2148
+ * @throws BuiltinError if the function doesn't exist or fails
2149
+ */
2150
+ function callBuiltin(name, args, context, functions = BUILTIN_FUNCTIONS) {
2151
+ const fn = functions.get(name);
2152
+ if (!fn) {
2153
+ throw new EvaluationError(`Unknown function: ${name}`, context.position, context.source);
2154
+ }
2155
+ return fn(args, context);
2156
+ }
2157
+ /**
2158
+ * Checks if a name is a built-in function.
2159
+ */
2160
+ function isBuiltinFunction(name, functions = BUILTIN_FUNCTIONS) {
2161
+ return functions.has(name);
2162
+ }
2163
+
2164
+ /**
2165
+ * Expression evaluator.
2166
+ *
2167
+ * Evaluates an AST against a set of variable bindings and returns a value.
2168
+ *
2169
+ * Null handling semantics:
2170
+ * - `undefined` values are normalized to `null` throughout evaluation.
2171
+ * - Missing identifiers evaluate to `null`.
2172
+ * - Member access on `null` or non-object returns `null`.
2173
+ * - Missing properties return `null` (including properties set to `undefined`).
2174
+ */
2175
+ /**
2176
+ * Evaluates an AST node and returns the result.
2177
+ */
2178
+ class Evaluator {
2179
+ constructor(context) {
2180
+ this.memberAccessDepth = 0;
2181
+ this.context = context;
2182
+ this.limits = context.limits ?? DEFAULT_EXPRESSION_LIMITS;
2183
+ this.source = context.source ?? "";
2184
+ this.functions = context.functions ?? BUILTIN_FUNCTIONS;
2185
+ }
2186
+ /**
2187
+ * Evaluates an AST node and returns the value.
2188
+ */
2189
+ evaluate(node) {
2190
+ switch (node.type) {
2191
+ case "StringLiteral":
2192
+ return node.value;
2193
+ case "NumberLiteral":
2194
+ return node.value;
2195
+ case "BooleanLiteral":
2196
+ return node.value;
2197
+ case "NullLiteral":
2198
+ return null;
2199
+ case "ArrayLiteral":
2200
+ return node.elements.map((e) => this.evaluate(e));
2201
+ case "Identifier":
2202
+ return this.evaluateIdentifier(node.name, node.position);
2203
+ case "MemberAccess":
2204
+ return this.evaluateMemberAccess(node);
2205
+ case "IndexAccess":
2206
+ return this.evaluateIndexAccess(node);
2207
+ case "FunctionCall":
2208
+ return this.evaluateFunctionCall(node);
2209
+ case "UnaryOp":
2210
+ return this.evaluateUnaryOp(node.operator, node.operand, node.position);
2211
+ case "BinaryOp":
2212
+ return this.evaluateBinaryOp(node.operator, node.left, node.right, node.position);
2213
+ case "TernaryOp":
2214
+ return this.evaluateTernaryOp(node.condition, node.consequent, node.alternate, node.position);
2215
+ }
2216
+ }
2217
+ /**
2218
+ * Evaluates as boolean with strict type checking.
2219
+ */
2220
+ evaluateAsBoolean(node) {
2221
+ const value = this.evaluate(node);
2222
+ if (typeof value !== "boolean") {
2223
+ throw new TypeError("boolean", getTypeName(value), node.position, this.source);
2224
+ }
2225
+ return value;
2226
+ }
2227
+ evaluateIdentifier(name, _position) {
2228
+ // Check if it's a top-level binding
2229
+ if (name in this.context.bindings) {
2230
+ // Normalize the value to ensure undefined becomes null
2231
+ return normalizeJsValue(this.context.bindings[name]);
2232
+ }
2233
+ // Unknown identifier evaluates to null (missing field)
2234
+ return null;
2235
+ }
2236
+ evaluateMemberAccess(node) {
2237
+ // Check member access depth
2238
+ this.memberAccessDepth++;
2239
+ if (this.memberAccessDepth > this.limits.maxMemberAccessDepth) {
2240
+ throw new EvaluationError(`Member access depth ${this.memberAccessDepth} exceeds limit of ${this.limits.maxMemberAccessDepth}`, node.position, this.source);
2241
+ }
2242
+ try {
2243
+ const obj = this.evaluate(node.object);
2244
+ // Null-safe member access: null.foo -> null
2245
+ if (obj === null) {
2246
+ return null;
2247
+ }
2248
+ // Must be an object (not primitive, not array)
2249
+ if (typeof obj !== "object" || Array.isArray(obj)) {
2250
+ // Type mismatch during access returns null (not error)
2251
+ return null;
2252
+ }
2253
+ const record = obj;
2254
+ if (node.property in record) {
2255
+ // Normalize the value to ensure undefined becomes null
2256
+ return normalizeJsValue(record[node.property]);
2257
+ }
2258
+ // Missing property evaluates to null
2259
+ return null;
2260
+ }
2261
+ finally {
2262
+ this.memberAccessDepth--;
2263
+ }
2264
+ }
2265
+ evaluateIndexAccess(node) {
2266
+ const obj = this.evaluate(node.object);
2267
+ const index = this.evaluate(node.index);
2268
+ // Null-safe index access: null[0] -> null
2269
+ if (obj === null) {
2270
+ return null;
2271
+ }
2272
+ // Array access with numeric index
2273
+ if (Array.isArray(obj)) {
2274
+ if (typeof index !== "number") {
2275
+ throw new TypeError("number", getTypeName(index), node.position, this.source);
2276
+ }
2277
+ const intIndex = Math.floor(index);
2278
+ if (intIndex < 0 || intIndex >= obj.length) {
2279
+ // Out of bounds evaluates to null
2280
+ return null;
2281
+ }
2282
+ // Normalize array element to ensure undefined becomes null
2283
+ return normalizeJsValue(obj[intIndex]);
2284
+ }
2285
+ // Object access with string key
2286
+ if (typeof obj === "object") {
2287
+ if (typeof index !== "string") {
2288
+ throw new TypeError("string", getTypeName(index), node.position, this.source);
2289
+ }
2290
+ const record = obj;
2291
+ if (index in record) {
2292
+ // Normalize the value to ensure undefined becomes null
2293
+ return normalizeJsValue(record[index]);
2294
+ }
2295
+ // Missing key evaluates to null
2296
+ return null;
2297
+ }
2298
+ // Type mismatch during access returns null
2299
+ return null;
2300
+ }
2301
+ evaluateFunctionCall(node) {
2302
+ // Evaluate arguments
2303
+ const args = node.args.map((arg) => this.evaluate(arg));
2304
+ const builtinContext = {
2305
+ limits: this.limits,
2306
+ position: node.position,
2307
+ source: this.source,
2308
+ };
2309
+ return callBuiltin(node.name, args, builtinContext, this.functions);
2310
+ }
2311
+ evaluateUnaryOp(operator, operand, position) {
2312
+ const value = this.evaluate(operand);
2313
+ switch (operator) {
2314
+ case "!":
2315
+ if (typeof value !== "boolean") {
2316
+ throw new TypeError("boolean", getTypeName(value), position, this.source);
2317
+ }
2318
+ return !value;
2319
+ case "-":
2320
+ if (typeof value !== "number") {
2321
+ throw new TypeError("number", getTypeName(value), position, this.source);
2322
+ }
2323
+ return -value;
2324
+ }
2325
+ }
2326
+ evaluateBinaryOp(operator, left, right, position) {
2327
+ // Short-circuit evaluation for logical operators
2328
+ if (operator === "&&") {
2329
+ const leftValue = this.evaluate(left);
2330
+ if (typeof leftValue !== "boolean") {
2331
+ throw new TypeError("boolean", getTypeName(leftValue), left.position, this.source);
2332
+ }
2333
+ if (!leftValue)
2334
+ return false;
2335
+ const rightValue = this.evaluate(right);
2336
+ if (typeof rightValue !== "boolean") {
2337
+ throw new TypeError("boolean", getTypeName(rightValue), right.position, this.source);
2338
+ }
2339
+ return rightValue;
2340
+ }
2341
+ if (operator === "||") {
2342
+ const leftValue = this.evaluate(left);
2343
+ if (typeof leftValue !== "boolean") {
2344
+ throw new TypeError("boolean", getTypeName(leftValue), left.position, this.source);
2345
+ }
2346
+ if (leftValue)
2347
+ return true;
2348
+ const rightValue = this.evaluate(right);
2349
+ if (typeof rightValue !== "boolean") {
2350
+ throw new TypeError("boolean", getTypeName(rightValue), right.position, this.source);
2351
+ }
2352
+ return rightValue;
2353
+ }
2354
+ // Eager evaluation for other operators
2355
+ const leftValue = this.evaluate(left);
2356
+ const rightValue = this.evaluate(right);
2357
+ switch (operator) {
2358
+ // Arithmetic
2359
+ case "+":
2360
+ if (typeof leftValue === "string" && typeof rightValue === "string") {
2361
+ return leftValue + rightValue;
2362
+ }
2363
+ if (typeof leftValue === "number" && typeof rightValue === "number") {
2364
+ return leftValue + rightValue;
2365
+ }
2366
+ throw new EvaluationError(`Cannot add ${getTypeName(leftValue)} and ${getTypeName(rightValue)}`, position, this.source);
2367
+ case "-":
2368
+ if (typeof leftValue !== "number" || typeof rightValue !== "number") {
2369
+ throw new EvaluationError(`Cannot subtract ${getTypeName(leftValue)} and ${getTypeName(rightValue)}`, position, this.source);
2370
+ }
2371
+ return leftValue - rightValue;
2372
+ case "*":
2373
+ if (typeof leftValue !== "number" || typeof rightValue !== "number") {
2374
+ throw new EvaluationError(`Cannot multiply ${getTypeName(leftValue)} and ${getTypeName(rightValue)}`, position, this.source);
2375
+ }
2376
+ return leftValue * rightValue;
2377
+ case "/":
2378
+ if (typeof leftValue !== "number" || typeof rightValue !== "number") {
2379
+ throw new EvaluationError(`Cannot divide ${getTypeName(leftValue)} and ${getTypeName(rightValue)}`, position, this.source);
2380
+ }
2381
+ if (rightValue === 0) {
2382
+ throw new EvaluationError("Division by zero", position, this.source);
2383
+ }
2384
+ return leftValue / rightValue;
2385
+ case "%":
2386
+ if (typeof leftValue !== "number" || typeof rightValue !== "number") {
2387
+ throw new EvaluationError(`Cannot compute modulo of ${getTypeName(leftValue)} and ${getTypeName(rightValue)}`, position, this.source);
2388
+ }
2389
+ if (rightValue === 0) {
2390
+ throw new EvaluationError("Modulo by zero", position, this.source);
2391
+ }
2392
+ return leftValue % rightValue;
2393
+ // Comparison
2394
+ case "<":
2395
+ case "<=":
2396
+ case ">":
2397
+ case ">=":
2398
+ return this.evaluateComparison(operator, leftValue, rightValue, position);
2399
+ // Equality
2400
+ case "==":
2401
+ return this.valuesEqual(leftValue, rightValue);
2402
+ case "!=":
2403
+ return !this.valuesEqual(leftValue, rightValue);
2404
+ // Membership
2405
+ case "in":
2406
+ return this.evaluateIn(leftValue, rightValue, position);
2407
+ case "not in":
2408
+ return !this.evaluateIn(leftValue, rightValue, position);
2409
+ }
2410
+ }
2411
+ evaluateComparison(operator, left, right, position) {
2412
+ // Numbers
2413
+ if (typeof left === "number" && typeof right === "number") {
2414
+ switch (operator) {
2415
+ case "<":
2416
+ return left < right;
2417
+ case "<=":
2418
+ return left <= right;
2419
+ case ">":
2420
+ return left > right;
2421
+ case ">=":
2422
+ return left >= right;
2423
+ }
2424
+ }
2425
+ // Strings
2426
+ if (typeof left === "string" && typeof right === "string") {
2427
+ switch (operator) {
2428
+ case "<":
2429
+ return left < right;
2430
+ case "<=":
2431
+ return left <= right;
2432
+ case ">":
2433
+ return left > right;
2434
+ case ">=":
2435
+ return left >= right;
2436
+ }
2437
+ }
2438
+ throw new EvaluationError(`Cannot compare ${getTypeName(left)} and ${getTypeName(right)} with ${operator}`, position, this.source);
2439
+ }
2440
+ evaluateIn(left, right, position) {
2441
+ // String in string (substring check)
2442
+ if (typeof left === "string" && typeof right === "string") {
2443
+ return right.includes(left);
2444
+ }
2445
+ // Value in array
2446
+ if (Array.isArray(right)) {
2447
+ return right.some((item) => this.valuesEqual(left, item));
2448
+ }
2449
+ // Key in object
2450
+ if (typeof right === "object" && right !== null && !Array.isArray(right)) {
2451
+ if (typeof left !== "string") {
2452
+ throw new EvaluationError(`Cannot check if ${getTypeName(left)} is a key in object (expected string)`, position, this.source);
2453
+ }
2454
+ return left in right;
2455
+ }
2456
+ throw new EvaluationError(`Cannot check membership: ${getTypeName(left)} in ${getTypeName(right)}`, position, this.source);
2457
+ }
2458
+ evaluateTernaryOp(condition, consequent, alternate, _position) {
2459
+ const condValue = this.evaluate(condition);
2460
+ if (typeof condValue !== "boolean") {
2461
+ throw new TypeError("boolean", getTypeName(condValue), condition.position, this.source);
2462
+ }
2463
+ return condValue ? this.evaluate(consequent) : this.evaluate(alternate);
2464
+ }
2465
+ /**
2466
+ * Deep equality check for expression values.
2467
+ */
2468
+ valuesEqual(a, b) {
2469
+ // Identical primitives or same reference
2470
+ if (a === b)
2471
+ return true;
2472
+ // Type mismatch
2473
+ if (typeof a !== typeof b)
2474
+ return false;
2475
+ // null check (both must be null if one is)
2476
+ if (a === null || b === null)
2477
+ return false;
2478
+ // Arrays
2479
+ if (Array.isArray(a) && Array.isArray(b)) {
2480
+ if (a.length !== b.length)
2481
+ return false;
2482
+ for (let i = 0; i < a.length; i++) {
2483
+ if (!this.valuesEqual(a[i], b[i])) {
2484
+ return false;
2485
+ }
2486
+ }
2487
+ return true;
2488
+ }
2489
+ // Objects
2490
+ if (typeof a === "object" && typeof b === "object") {
2491
+ const aKeys = Object.keys(a);
2492
+ const bKeys = Object.keys(b);
2493
+ if (aKeys.length !== bKeys.length)
2494
+ return false;
2495
+ for (const key of aKeys) {
2496
+ if (!Object.prototype.hasOwnProperty.call(b, key))
2497
+ return false;
2498
+ const aRecord = a;
2499
+ const bRecord = b;
2500
+ if (!this.valuesEqual(aRecord[key], bRecord[key])) {
2501
+ return false;
2502
+ }
2503
+ }
2504
+ return true;
2505
+ }
2506
+ return false;
2507
+ }
2508
+ }
2509
+ /**
2510
+ * Evaluates an AST against a context and returns the result.
2511
+ *
2512
+ * @param ast - The AST to evaluate
2513
+ * @param context - The evaluation context with bindings
2514
+ * @returns The evaluation result
2515
+ */
2516
+ function evaluate(ast, context) {
2517
+ try {
2518
+ const evaluator = new Evaluator(context);
2519
+ const value = evaluator.evaluate(ast);
2520
+ return { value, success: true };
2521
+ }
2522
+ catch (error) {
2523
+ const message = error instanceof Error ? error.message : String(error);
2524
+ return { value: null, success: false, error: message };
2525
+ }
2526
+ }
2527
+ /**
2528
+ * Evaluates an AST as a boolean condition.
2529
+ *
2530
+ * @param ast - The AST to evaluate
2531
+ * @param context - The evaluation context with bindings
2532
+ * @returns true if the condition is met, false otherwise (including errors)
2533
+ */
2534
+ function evaluateAsBoolean(ast, context) {
2535
+ try {
2536
+ const evaluator = new Evaluator(context);
2537
+ const value = evaluator.evaluateAsBoolean(ast);
2538
+ return { value };
2539
+ }
2540
+ catch (error) {
2541
+ const message = error instanceof Error ? error.message : String(error);
2542
+ return { value: false, error: message };
2543
+ }
2544
+ }
2545
+
2546
+ /**
2547
+ * Generic expression engine.
2548
+ *
2549
+ * This module provides a deterministic, side-effect-free expression
2550
+ * evaluation engine with injectable built-in functions.
2551
+ *
2552
+ * @packageDocumentation
2553
+ */
2554
+ // Core types and utilities
2555
+
2556
+ /**
2557
+ * Authorization-specific expression built-ins.
2558
+ *
2559
+ * Null handling semantics:
2560
+ * - Scope predicate builtins (has_scope, has_any_scope, has_all_scopes)
2561
+ * return `false` when passed `null` for required args.
2562
+ * - Wrong non-null types still raise BuiltinError to surface real bugs.
2563
+ */
2564
+ /**
2565
+ * Checks if a value is null.
2566
+ */
2567
+ function isNull(value) {
2568
+ return value === null;
2569
+ }
2570
+ /**
2571
+ * Creates a function registry with auth helpers installed.
2572
+ */
2573
+ function createAuthFunctionRegistry(grantedScopes = []) {
2574
+ const scopes = grantedScopes ?? [];
2575
+ /**
2576
+ * Checks if any granted scope matches a pattern (using glob syntax).
2577
+ */
2578
+ const matchesScope = (scope) => {
2579
+ // Exact match for now; safe and deterministic.
2580
+ return scopes.includes(scope);
2581
+ };
2582
+ /**
2583
+ * has_scope(scope: string) -> bool
2584
+ *
2585
+ * Returns true if the scope is in the granted scopes.
2586
+ * Null-tolerant: returns false if scope is null.
2587
+ */
2588
+ const has_scope = (args) => {
2589
+ assertArgCount(args, 1, "has_scope");
2590
+ const scope = getArg(args, 0, "has_scope");
2591
+ // Null-tolerant: return false if scope is null
2592
+ if (!assertStringOrNull(scope, "scope", "has_scope"))
2593
+ return false;
2594
+ return matchesScope(scope);
2595
+ };
2596
+ /**
2597
+ * has_any_scope(scopes: string[]) -> bool
2598
+ *
2599
+ * Returns true if any scope in the array is in the granted scopes.
2600
+ * Null-tolerant: returns false if scopes is null.
2601
+ */
2602
+ const has_any_scope = (args) => {
2603
+ assertArgCount(args, 1, "has_any_scope");
2604
+ const values = getArg(args, 0, "has_any_scope");
2605
+ // Null-tolerant: return false if scopes is null
2606
+ if (!assertStringArrayOrNull(values, "scopes", "has_any_scope"))
2607
+ return false;
2608
+ if (values.length === 0) {
2609
+ return false;
2610
+ }
2611
+ return values.some((scope) => matchesScope(scope));
2612
+ };
2613
+ /**
2614
+ * has_all_scopes(scopes: string[]) -> bool
2615
+ *
2616
+ * Returns true if all scopes in the array are in the granted scopes.
2617
+ * Null-tolerant: returns false if scopes is null.
2618
+ */
2619
+ const has_all_scopes = (args) => {
2620
+ assertArgCount(args, 1, "has_all_scopes");
2621
+ const values = getArg(args, 0, "has_all_scopes");
2622
+ // Null-tolerant: return false if scopes is null
2623
+ if (!assertStringArrayOrNull(values, "scopes", "has_all_scopes"))
2624
+ return false;
2625
+ if (values.length === 0) {
2626
+ return true;
2627
+ }
2628
+ return values.every((scope) => matchesScope(scope));
2629
+ };
2630
+ return new Map([
2631
+ ...BUILTIN_FUNCTIONS,
2632
+ ["has_scope", has_scope],
2633
+ ["has_any_scope", has_any_scope],
2634
+ ["has_all_scopes", has_all_scopes],
2635
+ ]);
2636
+ }
2637
+ /**
2638
+ * Asserts that a non-null value is a string (for null-tolerant predicates).
2639
+ * Returns false if the value is null (indicating predicate should return false).
2640
+ * Throws BuiltinError if the value is non-null but not a string.
2641
+ */
2642
+ function assertStringOrNull(value, argName, functionName) {
2643
+ if (isNull(value)) {
2644
+ return false;
2645
+ }
2646
+ if (typeof value !== "string") {
2647
+ throw new BuiltinError(functionName, `${argName} must be a string, got ${getTypeName(value)}`);
2648
+ }
2649
+ return true;
2650
+ }
2651
+ /**
2652
+ * Asserts that a non-null value is an array of strings (for null-tolerant predicates).
2653
+ * Returns false if the value is null (indicating predicate should return false).
2654
+ * Throws BuiltinError if the value is non-null but not a string array.
2655
+ */
2656
+ function assertStringArrayOrNull(value, argName, functionName) {
2657
+ if (isNull(value)) {
2658
+ return false;
2659
+ }
2660
+ if (!Array.isArray(value)) {
2661
+ throw new BuiltinError(functionName, `${argName} must be an array of strings, got ${getTypeName(value)}`);
2662
+ }
2663
+ for (let i = 0; i < value.length; i++) {
2664
+ if (typeof value[i] !== "string") {
2665
+ throw new BuiltinError(functionName, `${argName}[${i}] must be a string, got ${getTypeName(value[i])}`);
2666
+ }
2667
+ }
2668
+ return true;
2669
+ }
2670
+ function getArg(args, index, functionName) {
2671
+ const value = args[index];
2672
+ if (value === undefined) {
2673
+ throw new BuiltinError(functionName, `missing argument at index ${index}`);
2674
+ }
2675
+ return value;
2676
+ }
2677
+ function assertArgCount(args, expected, functionName) {
2678
+ if (args.length !== expected) {
2679
+ throw new BuiltinError(functionName, `expected ${expected} argument(s), got ${args.length}`);
2680
+ }
2681
+ }
2682
+
2683
+ /**
2684
+ * Expression-based authorization policy implementation.
2685
+ *
2686
+ * Extends the basic policy with support for `when` expression evaluation.
2687
+ * This is part of the BSL-licensed Advanced Security package.
2688
+ */
2689
+ /**
2690
+ * Simple console logger implementation.
2691
+ */
2692
+ const defaultLogger = {
2693
+ debug: () => { },
2694
+ warning: (event, data) => {
2695
+ console.warn(`[naylence.security.auth.policy.expression] ${event}`, data);
2696
+ },
2697
+ };
2698
+ /**
2699
+ * Extracts the target address string from the envelope.
2700
+ */
2701
+ function extractAddress(envelope) {
2702
+ const to = envelope.to;
2703
+ if (!to) {
2704
+ return undefined;
2705
+ }
2706
+ if (typeof to === "string") {
2707
+ return to;
2708
+ }
2709
+ if (typeof to === "object" && "toString" in to) {
2710
+ return to.toString();
2711
+ }
2712
+ return undefined;
2713
+ }
2714
+ /**
2715
+ * Extracts granted scopes from the authorization context.
2716
+ */
2717
+ function extractGrantedScopes(context) {
2718
+ const authContext = context?.security?.authorization;
2719
+ if (!authContext) {
2720
+ return [];
2721
+ }
2722
+ if (Array.isArray(authContext.grantedScopes)) {
2723
+ return authContext.grantedScopes;
2724
+ }
2725
+ const claims = authContext.claims;
2726
+ if (claims) {
2727
+ const scopeClaim = claims.scope ?? claims.scopes ?? claims.scp;
2728
+ if (typeof scopeClaim === "string") {
2729
+ return scopeClaim.split(/\s+/).filter((s) => s.length > 0);
2730
+ }
2731
+ if (Array.isArray(scopeClaim)) {
2732
+ return scopeClaim.filter((s) => typeof s === "string");
2733
+ }
2734
+ }
2735
+ return [];
2736
+ }
2737
+ /**
2738
+ * Extracts claims from the authorization context.
2739
+ */
2740
+ function extractClaims(context) {
2741
+ const authContext = context?.security?.authorization;
2742
+ if (!authContext?.claims) {
2743
+ return {};
2744
+ }
2745
+ return authContext.claims;
2746
+ }
2747
+ /**
2748
+ * Creates a safe envelope subset for expression bindings.
2749
+ */
2750
+ function createEnvelopeBindings(envelope) {
2751
+ const frame = envelope.frame;
2752
+ const envelopeRecord = envelope;
2753
+ return {
2754
+ id: envelope.id ?? null,
2755
+ traceId: envelopeRecord.traceId ?? null,
2756
+ corrId: envelopeRecord.corrId ?? null,
2757
+ flowId: envelopeRecord.flowId ?? null,
2758
+ to: extractAddress(envelope) ?? null,
2759
+ frame: frame
2760
+ ? { type: frame.type ?? null }
2761
+ : { type: null },
2762
+ };
2763
+ }
2764
+ /**
2765
+ * Creates delivery context bindings for expression evaluation.
2766
+ */
2767
+ function createDeliveryBindings(context, action) {
2768
+ return {
2769
+ origin_type: context?.originType ?? null,
2770
+ routing_action: action,
2771
+ };
2772
+ }
2773
+ /**
2774
+ * Expression-based authorization policy that evaluates rules with `when` expressions.
2775
+ *
2776
+ * Features:
2777
+ * - All features of BasicAuthorizationPolicy
2778
+ * - Expression evaluation for `when` clauses
2779
+ * - Deterministic, side-effect-free evaluation
2780
+ * - Missing fields evaluate to null (not error)
2781
+ * - Parse/evaluation errors cause rule to not match
2782
+ */
2783
+ class AdvancedAuthorizationPolicy {
2784
+ constructor(options) {
2785
+ const { policyDefinition, warnOnUnknownFields = true, expressionLimits = DEFAULT_EXPRESSION_LIMITS, logger = defaultLogger, } = options;
2786
+ this.expressionLimits = expressionLimits;
2787
+ this.logger = logger;
2788
+ // Validate and extract default effect
2789
+ this.defaultEffect = this.validateDefaultEffect(policyDefinition.default_effect);
2790
+ // Warn about unknown policy fields
2791
+ if (warnOnUnknownFields) {
2792
+ this.warnUnknownPolicyFields(policyDefinition);
2793
+ }
2794
+ // Compile rules for efficient evaluation
2795
+ this.compiledRules = this.compileRules(policyDefinition.rules, warnOnUnknownFields);
2796
+ this.logger.debug("expression_policy_compiled", {
2797
+ defaultEffect: this.defaultEffect,
2798
+ ruleCount: this.compiledRules.length,
2799
+ rulesWithWhen: this.compiledRules.filter((r) => r.whenAst).length,
2800
+ });
2801
+ }
2802
+ /**
2803
+ * Evaluates the policy against a request.
2804
+ */
2805
+ async evaluateRequest(_node, envelope, context, action) {
2806
+ const resolvedAction = action ?? "*";
2807
+ const resolvedActionNormalized = this.normalizeActionToken(resolvedAction) ?? resolvedAction;
2808
+ const address = extractAddress(envelope);
2809
+ const grantedScopes = extractGrantedScopes(context);
2810
+ const rawFrameType = envelope.frame
2811
+ ?.type;
2812
+ const frameTypeNormalized = typeof rawFrameType === "string" && rawFrameType.trim().length > 0
2813
+ ? rawFrameType.trim().toLowerCase()
2814
+ : "";
2815
+ const rawOriginType = context?.originType;
2816
+ const originTypeNormalized = typeof rawOriginType === "string"
2817
+ ? this.normalizeOriginTypeToken(rawOriginType) ?? undefined
2818
+ : undefined;
2819
+ // Prepare expression bindings (lazy)
2820
+ let expressionBindings = null;
2821
+ let functionRegistry = null;
2822
+ const evaluationTrace = [];
2823
+ // Evaluate rules in order (first match wins)
2824
+ for (const rule of this.compiledRules) {
2825
+ const step = {
2826
+ ruleId: rule.id,
2827
+ result: false,
2828
+ };
2829
+ // Check frame type match
2830
+ if (rule.frameTypes) {
2831
+ if (!frameTypeNormalized) {
2832
+ step.expression = "frame_type: missing";
2833
+ step.result = false;
2834
+ evaluationTrace.push(step);
2835
+ continue;
2836
+ }
2837
+ if (!rule.frameTypes.has(frameTypeNormalized)) {
2838
+ step.expression = `frame_type: ${rawFrameType ?? "unknown"} not in rule set`;
2839
+ step.result = false;
2840
+ evaluationTrace.push(step);
2841
+ continue;
2842
+ }
2843
+ }
2844
+ // Check origin type match
2845
+ if (rule.originTypes) {
2846
+ if (originTypeNormalized === undefined) {
2847
+ step.expression = "origin_type: missing (rule requires origin)";
2848
+ step.result = false;
2849
+ evaluationTrace.push(step);
2850
+ continue;
2851
+ }
2852
+ if (!rule.originTypes.has(originTypeNormalized)) {
2853
+ step.expression = `origin_type: ${rawOriginType ?? "unknown"} not in [${Array.from(rule.originTypes).join(", ")}]`;
2854
+ step.result = false;
2855
+ evaluationTrace.push(step);
2856
+ continue;
2857
+ }
2858
+ }
2859
+ // Check action match
2860
+ if (!rule.actions.has("*") && !rule.actions.has(resolvedActionNormalized)) {
2861
+ step.expression = `action: ${resolvedActionNormalized} not in [${Array.from(rule.actions).join(", ")}]`;
2862
+ step.result = false;
2863
+ evaluationTrace.push(step);
2864
+ continue;
2865
+ }
2866
+ // Check address match
2867
+ if (rule.addressPatterns) {
2868
+ if (!address) {
2869
+ step.expression = "address: pattern requires address, but none provided";
2870
+ step.result = false;
2871
+ evaluationTrace.push(step);
2872
+ continue;
2873
+ }
2874
+ const matched = rule.addressPatterns.some((p) => p.match(address));
2875
+ if (!matched) {
2876
+ const patterns = rule.addressPatterns.map((p) => p.source).join(", ");
2877
+ step.expression = `address: none of [${patterns}] matched ${address}`;
2878
+ step.result = false;
2879
+ evaluationTrace.push(step);
2880
+ continue;
2881
+ }
2882
+ }
2883
+ // Check scope match
2884
+ if (rule.scopeMatcher) {
2885
+ if (!rule.scopeMatcher(grantedScopes)) {
2886
+ step.expression = "scope: requirement not satisfied";
2887
+ step.boundValues = { grantedScopes: [...grantedScopes] };
2888
+ step.result = false;
2889
+ evaluationTrace.push(step);
2890
+ continue;
2891
+ }
2892
+ }
2893
+ // Check when expression
2894
+ if (rule.whenParseError) {
2895
+ // Parse error - rule does not match
2896
+ step.expression = `when: parse error - ${rule.whenParseError}`;
2897
+ step.result = false;
2898
+ evaluationTrace.push(step);
2899
+ continue;
2900
+ }
2901
+ if (rule.whenAst) {
2902
+ // Lazy initialization of expression bindings
2903
+ if (!expressionBindings) {
2904
+ expressionBindings = {
2905
+ claims: extractClaims(context),
2906
+ envelope: createEnvelopeBindings(envelope),
2907
+ delivery: createDeliveryBindings(context, resolvedAction),
2908
+ time: {
2909
+ now_ms: Date.now(),
2910
+ now_iso: new Date().toISOString(),
2911
+ },
2912
+ };
2913
+ }
2914
+ const functions = functionRegistry ?? createAuthFunctionRegistry(grantedScopes);
2915
+ functionRegistry = functions;
2916
+ const evalContext = {
2917
+ bindings: expressionBindings,
2918
+ limits: this.expressionLimits,
2919
+ source: rule.whenSource,
2920
+ functions,
2921
+ };
2922
+ const whenResult = evaluateAsBoolean(rule.whenAst, evalContext);
2923
+ if (whenResult.error) {
2924
+ // Evaluation error - rule does not match
2925
+ step.expression = `when: evaluation error - ${whenResult.error}`;
2926
+ step.result = false;
2927
+ evaluationTrace.push(step);
2928
+ continue;
2929
+ }
2930
+ if (!whenResult.value) {
2931
+ // Expression evaluated to false
2932
+ step.expression = `when: expression evaluated to false`;
2933
+ step.boundValues = {
2934
+ whenExpression: rule.whenSource,
2935
+ };
2936
+ step.result = false;
2937
+ evaluationTrace.push(step);
2938
+ continue;
2939
+ }
2940
+ // Expression evaluated to true
2941
+ step.expression = `when: expression evaluated to true`;
2942
+ }
2943
+ // Rule matched
2944
+ step.result = true;
2945
+ if (!step.expression) {
2946
+ step.expression = "all conditions matched";
2947
+ }
2948
+ step.boundValues = {
2949
+ action: resolvedAction,
2950
+ address,
2951
+ grantedScopes: [...grantedScopes],
2952
+ ...(rule.whenSource ? { whenExpression: rule.whenSource } : {}),
2953
+ };
2954
+ evaluationTrace.push(step);
2955
+ this.logger.debug("rule_matched", {
2956
+ ruleId: rule.id,
2957
+ effect: rule.effect,
2958
+ action: resolvedAction,
2959
+ address,
2960
+ hadWhenClause: Boolean(rule.whenAst),
2961
+ });
2962
+ return {
2963
+ effect: rule.effect,
2964
+ reason: rule.description ?? `Matched rule: ${rule.id}`,
2965
+ matchedRule: rule.id,
2966
+ evaluationTrace,
2967
+ };
2968
+ }
2969
+ // No rule matched, apply default effect
2970
+ this.logger.debug("no_rule_matched", {
2971
+ defaultEffect: this.defaultEffect,
2972
+ action: resolvedAction,
2973
+ address,
2974
+ });
2975
+ return {
2976
+ effect: this.defaultEffect,
2977
+ reason: `No rule matched, applying default effect: ${this.defaultEffect}`,
2978
+ evaluationTrace,
2979
+ };
2980
+ }
2981
+ validateDefaultEffect(effect) {
2982
+ if (effect === undefined || effect === null) {
2983
+ return "deny";
2984
+ }
2985
+ if (effect !== "allow" && effect !== "deny") {
2986
+ throw new Error(`Invalid default_effect: "${String(effect)}". Must be "allow" or "deny"`);
2987
+ }
2988
+ return effect;
2989
+ }
2990
+ warnUnknownPolicyFields(definition) {
2991
+ for (const key of Object.keys(definition)) {
2992
+ if (!runtime.KNOWN_POLICY_FIELDS.has(key)) {
2993
+ this.logger.warning("unknown_policy_field", { field: key });
2994
+ }
2995
+ }
2996
+ }
2997
+ compileRules(rules, warnOnUnknown) {
2998
+ return rules.map((rule, index) => this.compileRule(rule, index, warnOnUnknown));
2999
+ }
3000
+ compileRule(rule, index, warnOnUnknown) {
3001
+ const id = rule.id ?? `rule_${index}`;
3002
+ // Validate effect
3003
+ if (!runtime.VALID_EFFECTS.includes(rule.effect)) {
3004
+ throw new Error(`Invalid effect in rule "${id}": "${String(rule.effect)}". Must be "allow" or "deny"`);
3005
+ }
3006
+ // Compile action(s)
3007
+ const actions = this.compileActions(rule.action, id);
3008
+ // Compile address patterns
3009
+ const addressPatterns = this.compileAddress(rule.address, id);
3010
+ // Compile frame type gating
3011
+ const frameTypes = this.compileFrameTypes(rule.frame_type, id);
3012
+ // Compile origin type gating
3013
+ const originTypes = this.compileOriginTypes(rule.origin_type, id);
3014
+ // Compile scope matcher
3015
+ let scopeMatcher;
3016
+ if (rule.scope !== undefined) {
3017
+ try {
3018
+ const compiled = runtime.compileGlobOnlyScopeRequirement(rule.scope, id);
3019
+ scopeMatcher = (scopes) => compiled.evaluate(scopes);
3020
+ }
3021
+ catch (error) {
3022
+ throw new Error(`Invalid scope requirement in rule "${id}": ${error instanceof Error ? error.message : String(error)}`);
3023
+ }
3024
+ }
3025
+ // Compile when expression
3026
+ let whenAst;
3027
+ let whenSource;
3028
+ let whenParseError;
3029
+ if (typeof rule.when === "string" && rule.when.trim().length > 0) {
3030
+ whenSource = rule.when.trim();
3031
+ try {
3032
+ whenAst = parse(whenSource, this.expressionLimits);
3033
+ }
3034
+ catch (error) {
3035
+ // Parse error - store for evaluation time
3036
+ whenParseError =
3037
+ error instanceof Error ? error.message : String(error);
3038
+ this.logger.warning("when_parse_error", {
3039
+ ruleId: id,
3040
+ expression: whenSource,
3041
+ error: whenParseError,
3042
+ });
3043
+ }
3044
+ }
3045
+ // Warn about unknown fields
3046
+ if (warnOnUnknown) {
3047
+ for (const key of Object.keys(rule)) {
3048
+ if (!runtime.KNOWN_RULE_FIELDS.has(key)) {
3049
+ this.logger.warning("unknown_rule_field", { ruleId: id, field: key });
3050
+ }
3051
+ }
3052
+ }
3053
+ return {
3054
+ id,
3055
+ description: rule.description,
3056
+ effect: rule.effect,
3057
+ actions,
3058
+ frameTypes,
3059
+ originTypes,
3060
+ addressPatterns,
3061
+ scopeMatcher,
3062
+ whenAst,
3063
+ whenSource,
3064
+ whenParseError,
3065
+ };
3066
+ }
3067
+ compileActions(action, ruleId) {
3068
+ if (action === undefined) {
3069
+ return new Set(["*"]);
3070
+ }
3071
+ if (typeof action === "string") {
3072
+ const normalized = this.normalizeActionToken(action);
3073
+ if (!normalized) {
3074
+ throw new Error(`Invalid action in rule "${ruleId}": "${action}". Must be one of: ${runtime.VALID_ACTIONS.join(", ")}`);
3075
+ }
3076
+ return new Set([normalized]);
3077
+ }
3078
+ if (!Array.isArray(action)) {
3079
+ throw new Error(`Invalid action in rule "${ruleId}": must be a string or array of strings`);
3080
+ }
3081
+ if (action.length === 0) {
3082
+ throw new Error(`Invalid action in rule "${ruleId}": array must not be empty`);
3083
+ }
3084
+ const actions = new Set();
3085
+ for (const a of action) {
3086
+ if (typeof a !== "string") {
3087
+ throw new Error(`Invalid action in rule "${ruleId}": all values must be strings`);
3088
+ }
3089
+ const normalized = this.normalizeActionToken(a);
3090
+ if (!normalized) {
3091
+ throw new Error(`Invalid action in rule "${ruleId}": "${a}". Must be one of: ${runtime.VALID_ACTIONS.join(", ")}`);
3092
+ }
3093
+ actions.add(normalized);
3094
+ }
3095
+ return actions;
3096
+ }
3097
+ compileAddress(address, ruleId) {
3098
+ if (address === undefined) {
3099
+ return undefined;
3100
+ }
3101
+ const context = `address in rule "${ruleId}"`;
3102
+ if (typeof address === "string") {
3103
+ const trimmed = address.trim();
3104
+ if (!trimmed) {
3105
+ throw new Error(`Invalid address in rule "${ruleId}": value must not be empty`);
3106
+ }
3107
+ try {
3108
+ return [runtime.compileGlobPattern(trimmed, context)];
3109
+ }
3110
+ catch (error) {
3111
+ throw new Error(`Invalid address in rule "${ruleId}": ${error instanceof Error ? error.message : String(error)}`);
3112
+ }
3113
+ }
3114
+ if (!Array.isArray(address)) {
3115
+ throw new Error(`Invalid address in rule "${ruleId}": must be a string or array of strings`);
3116
+ }
3117
+ if (address.length === 0) {
3118
+ throw new Error(`Invalid address in rule "${ruleId}": array must not be empty`);
3119
+ }
3120
+ const patterns = [];
3121
+ for (const addr of address) {
3122
+ if (typeof addr !== "string") {
3123
+ throw new Error(`Invalid address in rule "${ruleId}": all values must be strings`);
3124
+ }
3125
+ const trimmed = addr.trim();
3126
+ if (!trimmed) {
3127
+ throw new Error(`Invalid address in rule "${ruleId}": values must not be empty`);
3128
+ }
3129
+ try {
3130
+ patterns.push(runtime.compileGlobPattern(trimmed, context));
3131
+ }
3132
+ catch (error) {
3133
+ throw new Error(`Invalid address in rule "${ruleId}": ${error instanceof Error ? error.message : String(error)}`);
3134
+ }
3135
+ }
3136
+ return patterns;
3137
+ }
3138
+ compileFrameTypes(frameType, ruleId) {
3139
+ if (frameType === undefined) {
3140
+ return undefined;
3141
+ }
3142
+ if (typeof frameType === "string") {
3143
+ const normalized = frameType.trim().toLowerCase();
3144
+ if (!normalized) {
3145
+ throw new Error(`Invalid frame_type in rule "${ruleId}": value must not be empty`);
3146
+ }
3147
+ return new Set([normalized]);
3148
+ }
3149
+ if (!Array.isArray(frameType)) {
3150
+ throw new Error(`Invalid frame_type in rule "${ruleId}": must be a string or array of strings`);
3151
+ }
3152
+ if (frameType.length === 0) {
3153
+ throw new Error(`Invalid frame_type in rule "${ruleId}": array must not be empty`);
3154
+ }
3155
+ const frameTypes = new Set();
3156
+ for (const ft of frameType) {
3157
+ if (typeof ft !== "string") {
3158
+ throw new Error(`Invalid frame_type in rule "${ruleId}": all values must be strings`);
3159
+ }
3160
+ const normalized = ft.trim().toLowerCase();
3161
+ if (!normalized) {
3162
+ throw new Error(`Invalid frame_type in rule "${ruleId}": values must not be empty`);
3163
+ }
3164
+ frameTypes.add(normalized);
3165
+ }
3166
+ return frameTypes;
3167
+ }
3168
+ compileOriginTypes(originType, ruleId) {
3169
+ if (originType === undefined) {
3170
+ return undefined;
3171
+ }
3172
+ if (typeof originType === "string") {
3173
+ const trimmed = originType.trim();
3174
+ if (!trimmed) {
3175
+ throw new Error(`Invalid origin_type in rule "${ruleId}": value must not be empty`);
3176
+ }
3177
+ const normalized = this.normalizeOriginTypeToken(trimmed);
3178
+ if (!normalized) {
3179
+ throw new Error(`Invalid origin_type in rule "${ruleId}": "${originType}". Must be one of: ${runtime.VALID_ORIGIN_TYPES.join(", ")}`);
3180
+ }
3181
+ return new Set([normalized]);
3182
+ }
3183
+ if (!Array.isArray(originType)) {
3184
+ throw new Error(`Invalid origin_type in rule "${ruleId}": must be a string or array of strings`);
3185
+ }
3186
+ if (originType.length === 0) {
3187
+ throw new Error(`Invalid origin_type in rule "${ruleId}": array must not be empty`);
3188
+ }
3189
+ const originTypes = new Set();
3190
+ for (const ot of originType) {
3191
+ if (typeof ot !== "string") {
3192
+ throw new Error(`Invalid origin_type in rule "${ruleId}": all values must be strings`);
3193
+ }
3194
+ const trimmed = ot.trim();
3195
+ if (!trimmed) {
3196
+ throw new Error(`Invalid origin_type in rule "${ruleId}": values must not be empty`);
3197
+ }
3198
+ const normalized = this.normalizeOriginTypeToken(trimmed);
3199
+ if (!normalized) {
3200
+ throw new Error(`Invalid origin_type in rule "${ruleId}": "${ot}". Must be one of: ${runtime.VALID_ORIGIN_TYPES.join(", ")}`);
3201
+ }
3202
+ originTypes.add(normalized);
3203
+ }
3204
+ return originTypes;
3205
+ }
3206
+ normalizeActionToken(value) {
3207
+ const trimmed = value.trim();
3208
+ if (!trimmed) {
3209
+ return null;
3210
+ }
3211
+ if (trimmed === "*") {
3212
+ return "*";
3213
+ }
3214
+ const normalized = trimmed.replace(/[\s_-]+/g, "").toLowerCase();
3215
+ const map = {
3216
+ connect: "Connect",
3217
+ forwardupstream: "ForwardUpstream",
3218
+ forwarddownstream: "ForwardDownstream",
3219
+ forwardpeer: "ForwardPeer",
3220
+ deliverlocal: "DeliverLocal",
3221
+ };
3222
+ return map[normalized] ?? null;
3223
+ }
3224
+ normalizeOriginTypeToken(value) {
3225
+ const trimmed = value.trim();
3226
+ if (!trimmed) {
3227
+ return null;
3228
+ }
3229
+ const normalized = trimmed.replace(/[\s_-]+/g, "").toLowerCase();
3230
+ const map = {
3231
+ downstream: "downstream",
3232
+ upstream: "upstream",
3233
+ peer: "peer",
3234
+ local: "local",
3235
+ };
3236
+ return map[normalized] ?? null;
3237
+ }
3238
+ }
3239
+
3240
+ var advancedAuthorizationPolicy = /*#__PURE__*/Object.freeze({
3241
+ __proto__: null,
3242
+ AdvancedAuthorizationPolicy: AdvancedAuthorizationPolicy
3243
+ });
3244
+
3245
+ /**
3246
+ * Factory for creating AdvancedAuthorizationPolicy instances.
3247
+ */
3248
+ let modulePromise = null;
3249
+ function getModule() {
3250
+ if (!modulePromise) {
3251
+ modulePromise = Promise.resolve().then(function () { return advancedAuthorizationPolicy; });
3252
+ }
3253
+ return modulePromise;
3254
+ }
3255
+ function normalizeConfig$5(config) {
3256
+ if (!config) {
3257
+ throw new Error("AdvancedAuthorizationPolicyFactory requires a configuration with a policyDefinition");
3258
+ }
3259
+ const candidate = config;
3260
+ // Support both camelCase and snake_case for policyDefinition
3261
+ const policyDefinition = (candidate.policyDefinition ??
3262
+ candidate.policy_definition);
3263
+ if (!policyDefinition || typeof policyDefinition !== "object") {
3264
+ throw new Error("AdvancedAuthorizationPolicyConfig requires a policyDefinition object");
3265
+ }
3266
+ // Support both camelCase and snake_case for warnOnUnknownFields
3267
+ const warnOnUnknownFields = candidate.warnOnUnknownFields ?? candidate.warn_on_unknown_fields;
3268
+ if (warnOnUnknownFields !== undefined &&
3269
+ typeof warnOnUnknownFields !== "boolean") {
3270
+ throw new Error("warnOnUnknownFields must be a boolean");
3271
+ }
3272
+ // Support both camelCase and snake_case for expressionLimits
3273
+ const expressionLimits = (candidate.expressionLimits ??
3274
+ candidate.expression_limits);
3275
+ return {
3276
+ policyDefinition,
3277
+ warnOnUnknownFields: warnOnUnknownFields ?? true,
3278
+ expressionLimits,
3279
+ };
3280
+ }
3281
+ /**
3282
+ * Factory metadata for registration.
3283
+ */
3284
+ const FACTORY_META$f = {
3285
+ base: runtime.AUTHORIZATION_POLICY_FACTORY_BASE_TYPE,
3286
+ key: "AdvancedAuthorizationPolicy",
3287
+ };
3288
+ /**
3289
+ * Factory for creating AdvancedAuthorizationPolicy instances.
3290
+ */
3291
+ class AdvancedAuthorizationPolicyFactory extends runtime.AuthorizationPolicyFactory {
3292
+ constructor() {
3293
+ super(...arguments);
3294
+ this.type = "AdvancedAuthorizationPolicy";
3295
+ }
3296
+ /**
3297
+ * Creates an AdvancedAuthorizationPolicy from the given configuration.
3298
+ *
3299
+ * @param config - Configuration with policyDefinition
3300
+ * @returns The created authorization policy
3301
+ */
3302
+ async create(config) {
3303
+ const normalized = normalizeConfig$5(config);
3304
+ const { AdvancedAuthorizationPolicy } = await getModule();
3305
+ return new AdvancedAuthorizationPolicy({
3306
+ policyDefinition: normalized.policyDefinition,
3307
+ warnOnUnknownFields: normalized.warnOnUnknownFields,
3308
+ expressionLimits: normalized.expressionLimits,
3309
+ });
3310
+ }
3311
+ }
3312
+
3313
+ var advancedAuthorizationPolicyFactory = /*#__PURE__*/Object.freeze({
3314
+ __proto__: null,
3315
+ AdvancedAuthorizationPolicyFactory: AdvancedAuthorizationPolicyFactory,
3316
+ FACTORY_META: FACTORY_META$f,
3317
+ default: AdvancedAuthorizationPolicyFactory
3318
+ });
3319
+
3320
+ /**
3321
+ * Advanced authorization policy module exports.
3322
+ *
3323
+ * This module provides expression-based authorization policies
3324
+ * for the Naylence Advanced Security package.
3325
+ *
3326
+ * @packageDocumentation
3327
+ */
3328
+ // Auth expression helpers
3329
+
3330
+ /**
3331
+ * Advanced security authentication/authorization module exports.
3332
+ *
3333
+ * @packageDocumentation
3334
+ */
3335
+
555
3336
  const logger$g = runtime.getLogger("naylence.fame.security.cert.util");
556
3337
  const CACHE_LIMIT = 512;
557
3338
  const OID_ED25519 = "1.3.101.112";
@@ -10169,6 +12950,7 @@ if (isNode && proc && proc.env) {
10169
12950
  }
10170
12951
  }
10171
12952
 
12953
+ exports.ADVANCED_AUTHORIZATION_POLICY_FACTORY_META = FACTORY_META$f;
10172
12954
  exports.ADVANCED_EDDSA_ENVELOPE_SIGNER_FACTORY_META = FACTORY_META$a;
10173
12955
  exports.ADVANCED_EDDSA_ENVELOPE_VERIFIER_FACTORY_META = FACTORY_META$9;
10174
12956
  exports.ADVANCED_WELCOME_FACTORY_META = FACTORY_META$5;
@@ -10179,12 +12961,16 @@ exports.AFTReplicaStickinessManager = AFTReplicaStickinessManager;
10179
12961
  exports.AFTReplicaStickinessManagerFactory = AFTReplicaStickinessManagerFactory;
10180
12962
  exports.AFT_LOAD_BALANCER_FACTORY_META = FACTORY_META$7;
10181
12963
  exports.AFT_REPLICA_FACTORY_META = FACTORY_META$6;
12964
+ exports.AdvancedAuthorizationPolicy = AdvancedAuthorizationPolicy;
12965
+ exports.AdvancedAuthorizationPolicyFactory = AdvancedAuthorizationPolicyFactory;
10182
12966
  exports.AdvancedEdDSAEnvelopeSignerFactory = AdvancedEdDSAEnvelopeSignerFactory;
10183
12967
  exports.AdvancedEdDSAEnvelopeVerifierFactory = AdvancedEdDSAEnvelopeVerifierFactory;
10184
12968
  exports.AdvancedWelcomeService = AdvancedWelcomeService;
10185
12969
  exports.AdvancedWelcomeServiceFactory = AdvancedWelcomeServiceFactory;
10186
12970
  exports.BROWSER_TRUST_STORE_PROVIDER_FACTORY_META = FACTORY_META$2;
12971
+ exports.BUILTIN_FUNCTIONS = BUILTIN_FUNCTIONS;
10187
12972
  exports.BrowserTrustStoreProviderFactory = BrowserTrustStoreProviderFactory;
12973
+ exports.BuiltinError = BuiltinError;
10188
12974
  exports.CAService = CAService;
10189
12975
  exports.CAServiceClient = CAServiceClient;
10190
12976
  exports.CAServiceFactory = CAServiceFactory;
@@ -10194,6 +12980,7 @@ exports.CertificateRequestError = CertificateRequestError;
10194
12980
  exports.CompositeEncryptionManager = CompositeEncryptionManager;
10195
12981
  exports.CompositeEncryptionManagerFactory = CompositeEncryptionManagerFactory;
10196
12982
  exports.DEFAULT_CERTIFICATE_MANAGER_FACTORY_META = FACTORY_META$4;
12983
+ exports.DEFAULT_EXPRESSION_LIMITS = DEFAULT_EXPRESSION_LIMITS;
10197
12984
  exports.DEFAULT_SECURE_CHANNEL_MANAGER_FACTORY_META = FACTORY_META$c;
10198
12985
  exports.DEFAULT_STICKINESS_SECURITY_LEVEL = DEFAULT_STICKINESS_SECURITY_LEVEL;
10199
12986
  exports.DefaultCAService = DefaultCAService;
@@ -10216,35 +13003,59 @@ exports.ENV_TRUST_STORE_PROVIDER_FACTORY_META = FACTORY_META$3;
10216
13003
  exports.ENV_VAR_FAME_CA_SERVICE_URL = ENV_VAR_FAME_CA_SERVICE_URL;
10217
13004
  exports.EdDSAEnvelopeVerifier = EdDSAEnvelopeVerifier;
10218
13005
  exports.EnvTrustStoreProviderFactory = EnvTrustStoreProviderFactory;
13006
+ exports.EvaluationError = EvaluationError;
13007
+ exports.Evaluator = Evaluator;
13008
+ exports.ExpressionError = ExpressionError;
10219
13009
  exports.GRANT_PURPOSE_CA_SIGN = GRANT_PURPOSE_CA_SIGN;
10220
13010
  exports.LOGICALS_OID = LOGICALS_OID;
13011
+ exports.LimitExceededError = LimitExceededError;
10221
13012
  exports.NODE_ID_OID = NODE_ID_OID;
10222
13013
  exports.NoAFTSigner = NoAFTSigner;
10223
13014
  exports.NullTrustStoreProvider = NullTrustStoreProvider;
13015
+ exports.PROFILE_NAME_STRICT_OVERLAY = PROFILE_NAME_STRICT_OVERLAY;
13016
+ exports.ParseError = ParseError;
13017
+ exports.Parser = Parser;
10224
13018
  exports.SID_OID = SID_OID;
10225
13019
  exports.SidOnlyAFTVerifier = SidOnlyAFTVerifier;
10226
13020
  exports.SignedAFTSigner = SignedAFTSigner;
10227
13021
  exports.SignedOptionalAFTVerifier = SignedOptionalAFTVerifier;
10228
13022
  exports.StrictAFTVerifier = StrictAFTVerifier;
10229
13023
  exports.TRUST_STORE_PROVIDER_FACTORY_BASE_TYPE = TRUST_STORE_PROVIDER_FACTORY_BASE_TYPE;
13024
+ exports.Tokenizer = Tokenizer;
13025
+ exports.TokenizerError = TokenizerError;
10230
13026
  exports.TrustStoreProviderFactory = TrustStoreProviderFactory;
13027
+ exports.TypeError = TypeError;
10231
13028
  exports.UnsignedAFTSigner = UnsignedAFTSigner;
10232
13029
  exports.VERSION = VERSION;
10233
13030
  exports.X5CKeyManager = X5CKeyManager;
10234
13031
  exports.X5CKeyManagerFactory = X5CKeyManagerFactory;
10235
13032
  exports.X5C_KEY_MANAGER_FACTORY_META = FACTORY_META$8;
10236
13033
  exports.__advancedSecurityPluginLoader = __advancedSecurityPluginLoader;
13034
+ exports.astToString = astToString;
10237
13035
  exports.base64UrlDecode = base64UrlDecode;
10238
13036
  exports.base64UrlEncode = base64UrlEncode;
13037
+ exports.calculateAstDepth = calculateAstDepth;
13038
+ exports.callBuiltin = callBuiltin;
10239
13039
  exports.channelEncryption = index;
13040
+ exports.checkArrayLength = checkArrayLength;
13041
+ exports.checkAstDepth = checkAstDepth;
13042
+ exports.checkAstNodeCount = checkAstNodeCount;
13043
+ exports.checkExpressionLength = checkExpressionLength;
13044
+ exports.checkFunctionArgCount = checkFunctionArgCount;
13045
+ exports.checkGlobPatternLength = checkGlobPatternLength;
13046
+ exports.checkRegexPatternLength = checkRegexPatternLength;
13047
+ exports.countAstNodes = countAstNodes;
10240
13048
  exports.createAftHelper = createAftHelper;
10241
13049
  exports.createAftPayload = createAftPayload;
10242
13050
  exports.createAftReplicaStickinessManager = createAftReplicaStickinessManager;
10243
13051
  exports.createAftSigner = createAftSigner;
10244
13052
  exports.createAftVerifier = createAftVerifier;
13053
+ exports.createAuthFunctionRegistry = createAuthFunctionRegistry;
10245
13054
  exports.createEd25519Csr = createEd25519Csr;
10246
13055
  exports.createEd25519CsrFromPem = createEd25519CsrFromPem;
10247
13056
  exports.createTestCA = createTestCA;
13057
+ exports.evaluate = evaluate;
13058
+ exports.evaluateAsBoolean = evaluateAsBoolean;
10248
13059
  exports.extractCertificateInfo = extractCertificateInfo;
10249
13060
  exports.extractLogicalHostsFromCert = extractLogicalHostsFromCert;
10250
13061
  exports.extractNodeIdFromCert = extractNodeIdFromCert;
@@ -10252,12 +13063,17 @@ exports.extractSidFromCert = extractSidFromCert;
10252
13063
  exports.extractSidFromSpiffeId = extractSidFromSpiffeId;
10253
13064
  exports.extractSpiffeIdFromCert = extractSpiffeIdFromCert;
10254
13065
  exports.formatCertificateInfo = formatCertificateInfo;
13066
+ exports.getTypeName = getTypeName;
13067
+ exports.isBuiltinFunction = isBuiltinFunction;
13068
+ exports.normalizeJsValue = normalizeJsValue;
10255
13069
  exports.normalizeStickinessMode = normalizeStickinessMode;
13070
+ exports.parse = parse;
10256
13071
  exports.publicKeyFromX5c = publicKeyFromX5c;
10257
13072
  exports.registerAdvancedSecurityFactories = registerAdvancedSecurityFactories;
10258
13073
  exports.sealedEncryption = index$1;
10259
13074
  exports.serializeAftClaims = serializeAftClaims;
10260
13075
  exports.serializeAftHeader = serializeAftHeader;
13076
+ exports.tokenize = tokenize;
10261
13077
  exports.utf8Decode = utf8Decode;
10262
13078
  exports.validateJwkX5cCertificate = validateJwkX5cCertificate;
10263
13079
  exports.verifyCertSidIntegrity = verifyCertSidIntegrity;