@naylence/advanced-security 0.3.15 → 0.4.0

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