@naylence/advanced-security 0.3.15 → 0.4.1

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