@naylence/advanced-security 0.3.14 → 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 (136) hide show
  1. package/dist/browser/index.cjs +5813 -3134
  2. package/dist/browser/index.mjs +5837 -3158
  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/browser.js +11 -0
  6. package/dist/cjs/browser.js.map +1 -1
  7. package/dist/cjs/naylence/fame/expr/ast.js +135 -0
  8. package/dist/cjs/naylence/fame/expr/ast.js.map +1 -0
  9. package/dist/cjs/naylence/fame/expr/builtins.js +477 -0
  10. package/dist/cjs/naylence/fame/expr/builtins.js.map +1 -0
  11. package/dist/cjs/naylence/fame/expr/errors.js +88 -0
  12. package/dist/cjs/naylence/fame/expr/errors.js.map +1 -0
  13. package/dist/cjs/naylence/fame/expr/evaluator.js +385 -0
  14. package/dist/cjs/naylence/fame/expr/evaluator.js.map +1 -0
  15. package/dist/cjs/naylence/fame/expr/index.js +21 -0
  16. package/dist/cjs/naylence/fame/expr/index.js.map +1 -0
  17. package/dist/cjs/naylence/fame/expr/limits.js +80 -0
  18. package/dist/cjs/naylence/fame/expr/limits.js.map +1 -0
  19. package/dist/cjs/naylence/fame/expr/parser.js +429 -0
  20. package/dist/cjs/naylence/fame/expr/parser.js.map +1 -0
  21. package/dist/cjs/naylence/fame/expr/tokenizer.js +336 -0
  22. package/dist/cjs/naylence/fame/expr/tokenizer.js.map +1 -0
  23. package/dist/cjs/naylence/fame/factory-manifest.js +2 -0
  24. package/dist/cjs/naylence/fame/factory-manifest.js.map +1 -1
  25. package/dist/cjs/naylence/fame/security/auth/index.js +7 -0
  26. package/dist/cjs/naylence/fame/security/auth/index.js.map +1 -0
  27. package/dist/cjs/naylence/fame/security/auth/policy/advanced-authorization-policy-factory.js +70 -0
  28. package/dist/cjs/naylence/fame/security/auth/policy/advanced-authorization-policy-factory.js.map +1 -0
  29. package/dist/cjs/naylence/fame/security/auth/policy/advanced-authorization-policy.js +562 -0
  30. package/dist/cjs/naylence/fame/security/auth/policy/advanced-authorization-policy.js.map +1 -0
  31. package/dist/cjs/naylence/fame/security/auth/policy/expr-builtins.js +129 -0
  32. package/dist/cjs/naylence/fame/security/auth/policy/expr-builtins.js.map +1 -0
  33. package/dist/cjs/naylence/fame/security/auth/policy/index.js +15 -0
  34. package/dist/cjs/naylence/fame/security/auth/policy/index.js.map +1 -0
  35. package/dist/cjs/naylence/fame/security/index.js +2 -0
  36. package/dist/cjs/naylence/fame/security/index.js.map +1 -1
  37. package/dist/cjs/naylence/fame/security/register-advanced-security-factories.js +2 -0
  38. package/dist/cjs/naylence/fame/security/register-advanced-security-factories.js.map +1 -1
  39. package/dist/cjs/naylence/fame/security/strict-overlay-security-profile.js +64 -0
  40. package/dist/cjs/naylence/fame/security/strict-overlay-security-profile.js.map +1 -0
  41. package/dist/cjs/node.js +27 -0
  42. package/dist/cjs/node.js.map +1 -1
  43. package/dist/cjs/plugin.js +2 -0
  44. package/dist/cjs/plugin.js.map +1 -1
  45. package/dist/cjs/version.js +2 -2
  46. package/dist/cjs/version.js.map +1 -1
  47. package/dist/esm/advanced-security-isomorphic.js +4 -0
  48. package/dist/esm/advanced-security-isomorphic.js.map +1 -1
  49. package/dist/esm/browser.js +11 -0
  50. package/dist/esm/browser.js.map +1 -1
  51. package/dist/esm/naylence/fame/expr/ast.js +135 -0
  52. package/dist/esm/naylence/fame/expr/ast.js.map +1 -0
  53. package/dist/esm/naylence/fame/expr/builtins.js +477 -0
  54. package/dist/esm/naylence/fame/expr/builtins.js.map +1 -0
  55. package/dist/esm/naylence/fame/expr/errors.js +88 -0
  56. package/dist/esm/naylence/fame/expr/errors.js.map +1 -0
  57. package/dist/esm/naylence/fame/expr/evaluator.js +385 -0
  58. package/dist/esm/naylence/fame/expr/evaluator.js.map +1 -0
  59. package/dist/esm/naylence/fame/expr/index.js +21 -0
  60. package/dist/esm/naylence/fame/expr/index.js.map +1 -0
  61. package/dist/esm/naylence/fame/expr/limits.js +80 -0
  62. package/dist/esm/naylence/fame/expr/limits.js.map +1 -0
  63. package/dist/esm/naylence/fame/expr/parser.js +429 -0
  64. package/dist/esm/naylence/fame/expr/parser.js.map +1 -0
  65. package/dist/esm/naylence/fame/expr/tokenizer.js +336 -0
  66. package/dist/esm/naylence/fame/expr/tokenizer.js.map +1 -0
  67. package/dist/esm/naylence/fame/factory-manifest.js +2 -0
  68. package/dist/esm/naylence/fame/factory-manifest.js.map +1 -1
  69. package/dist/esm/naylence/fame/security/auth/index.js +7 -0
  70. package/dist/esm/naylence/fame/security/auth/index.js.map +1 -0
  71. package/dist/esm/naylence/fame/security/auth/policy/advanced-authorization-policy-factory.js +70 -0
  72. package/dist/esm/naylence/fame/security/auth/policy/advanced-authorization-policy-factory.js.map +1 -0
  73. package/dist/esm/naylence/fame/security/auth/policy/advanced-authorization-policy.js +562 -0
  74. package/dist/esm/naylence/fame/security/auth/policy/advanced-authorization-policy.js.map +1 -0
  75. package/dist/esm/naylence/fame/security/auth/policy/expr-builtins.js +129 -0
  76. package/dist/esm/naylence/fame/security/auth/policy/expr-builtins.js.map +1 -0
  77. package/dist/esm/naylence/fame/security/auth/policy/index.js +15 -0
  78. package/dist/esm/naylence/fame/security/auth/policy/index.js.map +1 -0
  79. package/dist/esm/naylence/fame/security/index.js +2 -0
  80. package/dist/esm/naylence/fame/security/index.js.map +1 -1
  81. package/dist/esm/naylence/fame/security/register-advanced-security-factories.js +2 -0
  82. package/dist/esm/naylence/fame/security/register-advanced-security-factories.js.map +1 -1
  83. package/dist/esm/naylence/fame/security/strict-overlay-security-profile.js +64 -0
  84. package/dist/esm/naylence/fame/security/strict-overlay-security-profile.js.map +1 -0
  85. package/dist/esm/node.js +27 -0
  86. package/dist/esm/node.js.map +1 -1
  87. package/dist/esm/plugin.js +2 -0
  88. package/dist/esm/plugin.js.map +1 -1
  89. package/dist/esm/version.js +2 -2
  90. package/dist/esm/version.js.map +1 -1
  91. package/dist/node/index.cjs +2795 -6
  92. package/dist/node/index.mjs +2770 -15
  93. package/dist/node/node.cjs +6083 -3241
  94. package/dist/node/node.mjs +8347 -5540
  95. package/dist/types/advanced-security-isomorphic.d.ts +2 -0
  96. package/dist/types/advanced-security-isomorphic.d.ts.map +1 -1
  97. package/dist/types/browser.d.ts.map +1 -1
  98. package/dist/types/naylence/fame/expr/ast.d.ts +85 -0
  99. package/dist/types/naylence/fame/expr/ast.d.ts.map +1 -0
  100. package/dist/types/naylence/fame/expr/builtins.d.ts +79 -0
  101. package/dist/types/naylence/fame/expr/builtins.d.ts.map +1 -0
  102. package/dist/types/naylence/fame/expr/errors.d.ts +61 -0
  103. package/dist/types/naylence/fame/expr/errors.d.ts.map +1 -0
  104. package/dist/types/naylence/fame/expr/evaluator.d.ts +90 -0
  105. package/dist/types/naylence/fame/expr/evaluator.d.ts.map +1 -0
  106. package/dist/types/naylence/fame/expr/index.d.ts +16 -0
  107. package/dist/types/naylence/fame/expr/index.d.ts.map +1 -0
  108. package/dist/types/naylence/fame/expr/limits.d.ts +65 -0
  109. package/dist/types/naylence/fame/expr/limits.d.ts.map +1 -0
  110. package/dist/types/naylence/fame/expr/parser.d.ts +102 -0
  111. package/dist/types/naylence/fame/expr/parser.d.ts.map +1 -0
  112. package/dist/types/naylence/fame/expr/tokenizer.d.ts +51 -0
  113. package/dist/types/naylence/fame/expr/tokenizer.d.ts.map +1 -0
  114. package/dist/types/naylence/fame/factory-manifest.d.ts +1 -1
  115. package/dist/types/naylence/fame/factory-manifest.d.ts.map +1 -1
  116. package/dist/types/naylence/fame/security/auth/index.d.ts +7 -0
  117. package/dist/types/naylence/fame/security/auth/index.d.ts.map +1 -0
  118. package/dist/types/naylence/fame/security/auth/policy/advanced-authorization-policy-factory.d.ts +47 -0
  119. package/dist/types/naylence/fame/security/auth/policy/advanced-authorization-policy-factory.d.ts.map +1 -0
  120. package/dist/types/naylence/fame/security/auth/policy/advanced-authorization-policy.d.ts +73 -0
  121. package/dist/types/naylence/fame/security/auth/policy/advanced-authorization-policy.d.ts.map +1 -0
  122. package/dist/types/naylence/fame/security/auth/policy/expr-builtins.d.ts +14 -0
  123. package/dist/types/naylence/fame/security/auth/policy/expr-builtins.d.ts.map +1 -0
  124. package/dist/types/naylence/fame/security/auth/policy/index.d.ts +12 -0
  125. package/dist/types/naylence/fame/security/auth/policy/index.d.ts.map +1 -0
  126. package/dist/types/naylence/fame/security/index.d.ts +2 -0
  127. package/dist/types/naylence/fame/security/index.d.ts.map +1 -1
  128. package/dist/types/naylence/fame/security/register-advanced-security-factories.d.ts +1 -0
  129. package/dist/types/naylence/fame/security/register-advanced-security-factories.d.ts.map +1 -1
  130. package/dist/types/naylence/fame/security/strict-overlay-security-profile.d.ts +11 -0
  131. package/dist/types/naylence/fame/security/strict-overlay-security-profile.d.ts.map +1 -0
  132. package/dist/types/node.d.ts.map +1 -1
  133. package/dist/types/plugin.d.ts.map +1 -1
  134. package/dist/types/version.d.ts +1 -1
  135. package/dist/types/version.d.ts.map +1 -1
  136. package/package.json +3 -3
@@ -1,26 +1,2708 @@
1
- import { getLogger, EncryptionResult, urlsafeBase64Decode, sealedDecrypt, sealedEncrypt, FIXED_PREFIX_LEN, urlsafeBase64Encode, EncryptionManagerFactory, ENCRYPTION_MANAGER_FACTORY_BASE_TYPE, requireCryptoSupport, SECURE_CHANNEL_MANAGER_FACTORY_BASE_TYPE, SecureChannelManagerFactory, ENVELOPE_SIGNER_FACTORY_BASE_TYPE, EnvelopeSignerFactory, SigningConfigClass, validateSigningKey, JWKValidationError, decodeBase64Url, canonicalJson, secureDigest, frameDigest, immutableHeaders, encodeUtf8, ENVELOPE_VERIFIER_FACTORY_BASE_TYPE, EnvelopeVerifierFactory, TrustStoreProviderFactory, TaskSpawner, getKeyStore, DefaultKeyManager, validateJwkComplete, currentTraceId, DeliveryOriginType, KEY_MANAGER_FACTORY_BASE_TYPE, KeyManagerFactory, KeyStoreFactory, BaseNodeEventListener, LOAD_BALANCER_STICKINESS_MANAGER_FACTORY_BASE_TYPE, LoadBalancerStickinessManagerFactory, REPLICA_STICKINESS_MANAGER_FACTORY_BASE_TYPE, ReplicaStickinessManagerFactory, color, AnsiColor, validateHostLogicals, HTTP_CONNECTION_GRANT_TYPE, formatTimestamp, jsonDumps, WELCOME_SERVICE_FACTORY_BASE_TYPE, WelcomeServiceFactory, NodePlacementStrategyFactory, TransportProvisionerFactory, TokenIssuerFactory, AuthorizerFactory, validateHostLogical, AuthInjectionStrategyFactory, CERTIFICATE_MANAGER_FACTORY_BASE_TYPE, CertificateManagerFactory, TRUST_STORE_PROVIDER_FACTORY_BASE_TYPE } from '@naylence/runtime';
1
+ import { ExtensionManager, Expressions, Registry, AbstractResourceFactory } from '@naylence/factory';
2
+ import { KNOWN_POLICY_FIELDS, VALID_EFFECTS, compileGlobOnlyScopeRequirement, KNOWN_RULE_FIELDS, VALID_ACTIONS, compileGlobPattern, VALID_ORIGIN_TYPES, AUTHORIZATION_POLICY_FACTORY_BASE_TYPE, AuthorizationPolicyFactory, getLogger, EncryptionResult, urlsafeBase64Decode, sealedDecrypt, sealedEncrypt, FIXED_PREFIX_LEN, urlsafeBase64Encode, EncryptionManagerFactory, ENCRYPTION_MANAGER_FACTORY_BASE_TYPE, requireCryptoSupport, SECURE_CHANNEL_MANAGER_FACTORY_BASE_TYPE, SecureChannelManagerFactory, ENVELOPE_SIGNER_FACTORY_BASE_TYPE, EnvelopeSignerFactory, SigningConfigClass, validateSigningKey, JWKValidationError, decodeBase64Url, canonicalJson, secureDigest, frameDigest, immutableHeaders, encodeUtf8, ENVELOPE_VERIFIER_FACTORY_BASE_TYPE, EnvelopeVerifierFactory, TrustStoreProviderFactory, TaskSpawner, getKeyStore, DefaultKeyManager, validateJwkComplete, currentTraceId, DeliveryOriginType, KEY_MANAGER_FACTORY_BASE_TYPE, KeyManagerFactory, KeyStoreFactory, BaseNodeEventListener, LOAD_BALANCER_STICKINESS_MANAGER_FACTORY_BASE_TYPE, LoadBalancerStickinessManagerFactory, REPLICA_STICKINESS_MANAGER_FACTORY_BASE_TYPE, ReplicaStickinessManagerFactory, color, AnsiColor, validateHostLogicals, HTTP_CONNECTION_GRANT_TYPE, formatTimestamp, jsonDumps, WELCOME_SERVICE_FACTORY_BASE_TYPE, WelcomeServiceFactory, NodePlacementStrategyFactory, TransportProvisionerFactory, TokenIssuerFactory, AuthorizerFactory, registerProfile, SECURITY_MANAGER_FACTORY_BASE_TYPE, validateHostLogical, AuthInjectionStrategyFactory, CERTIFICATE_MANAGER_FACTORY_BASE_TYPE, CertificateManagerFactory, TRUST_STORE_PROVIDER_FACTORY_BASE_TYPE } from '@naylence/runtime';
2
3
  import { AsnConvert, OctetString } from '@peculiar/asn1-schema';
3
4
  import { Attributes, CertificationRequestInfo, CertificationRequest } from '@peculiar/asn1-csr';
4
5
  import { Certificate, SubjectAlternativeName, NameConstraints, id_ce_subjectAltName, id_ce_nameConstraints, SubjectPublicKeyInfo, GeneralName, Extensions, Extension, Attribute, AlgorithmIdentifier, Name, RelativeDistinguishedName, AttributeTypeAndValue, AttributeValue, BasicConstraints, id_ce_basicConstraints, KeyUsageFlags, id_ce_keyUsage, KeyUsage, id_ce_subjectKeyIdentifier, SubjectKeyIdentifier, id_ce_authorityKeyIdentifier, AuthorityKeyIdentifier, KeyIdentifier, GeneralSubtrees, GeneralSubtree, TBSCertificate, Validity, Version, id_ce_extKeyUsage, ExtendedKeyUsage, id_kp_clientAuth, id_kp_serverAuth } from '@peculiar/asn1-x509';
5
6
  import { verify, etc } from '@noble/ed25519';
6
- import { sha256, sha512 } from '@noble/hashes/sha2.js';
7
- import { localDeliveryContext, createFameEnvelope, generateId, formatAddress, FameAddress, SigningMaterial, DeliveryOriginType as DeliveryOriginType$1 } from '@naylence/core';
7
+ import { sha256 as sha256$1, sha512 } from '@noble/hashes/sha2.js';
8
+ import { generateFingerprintSync, localDeliveryContext, createFameEnvelope, generateId, formatAddress, FameAddress, SigningMaterial, DeliveryOriginType as DeliveryOriginType$1 } from '@naylence/core';
9
+ import { sha256 } from '@noble/hashes/sha256';
8
10
  import { chacha20poly1305 } from '@noble/ciphers/chacha.js';
9
11
  import { x25519 } from '@noble/curves/ed25519.js';
10
12
  import { hkdf } from '@noble/hashes/hkdf.js';
11
13
  import { utf8ToBytes, randomBytes as randomBytes$1 } from '@noble/hashes/utils.js';
12
14
  import { SignJWT, importPKCS8, compactVerify, importJWK, importSPKI } from 'jose';
13
- import { ExtensionManager, Registry, AbstractResourceFactory } from '@naylence/factory';
14
- import { sha256 as sha256$1 } from '@noble/hashes/sha256.js';
15
+ import { sha256 as sha256$2 } from '@noble/hashes/sha256.js';
15
16
  import { X509Certificate } from '@peculiar/x509';
16
17
 
17
18
  // This file is auto-generated during build - do not edit manually
18
- // Generated from package.json version: 0.3.14
19
+ // Generated from package.json version: 0.4.0
19
20
  /**
20
21
  * The package version, injected at build time.
21
22
  * @internal
22
23
  */
23
- const VERSION = '0.3.14';
24
+ const VERSION = '0.4.0';
25
+
26
+ /**
27
+ * Abstract Syntax Tree (AST) node types for the expression language.
28
+ *
29
+ * The AST is produced by the parser and consumed by the evaluator.
30
+ */
31
+ // ============================================================
32
+ // AST Utilities
33
+ // ============================================================
34
+ /**
35
+ * Counts the total number of nodes in an AST.
36
+ */
37
+ function countAstNodes(node) {
38
+ let count = 1;
39
+ switch (node.type) {
40
+ case "StringLiteral":
41
+ case "NumberLiteral":
42
+ case "BooleanLiteral":
43
+ case "NullLiteral":
44
+ case "Identifier":
45
+ return count;
46
+ case "ArrayLiteral":
47
+ for (const element of node.elements) {
48
+ count += countAstNodes(element);
49
+ }
50
+ return count;
51
+ case "MemberAccess":
52
+ return count + countAstNodes(node.object);
53
+ case "IndexAccess":
54
+ return count + countAstNodes(node.object) + countAstNodes(node.index);
55
+ case "FunctionCall":
56
+ for (const arg of node.args) {
57
+ count += countAstNodes(arg);
58
+ }
59
+ return count;
60
+ case "UnaryOp":
61
+ return count + countAstNodes(node.operand);
62
+ case "BinaryOp":
63
+ return count + countAstNodes(node.left) + countAstNodes(node.right);
64
+ case "TernaryOp":
65
+ return (count +
66
+ countAstNodes(node.condition) +
67
+ countAstNodes(node.consequent) +
68
+ countAstNodes(node.alternate));
69
+ }
70
+ }
71
+ /**
72
+ * Calculates the maximum depth of an AST.
73
+ */
74
+ function calculateAstDepth(node) {
75
+ switch (node.type) {
76
+ case "StringLiteral":
77
+ case "NumberLiteral":
78
+ case "BooleanLiteral":
79
+ case "NullLiteral":
80
+ case "Identifier":
81
+ return 1;
82
+ case "ArrayLiteral": {
83
+ let maxChildDepth = 0;
84
+ for (const element of node.elements) {
85
+ maxChildDepth = Math.max(maxChildDepth, calculateAstDepth(element));
86
+ }
87
+ return 1 + maxChildDepth;
88
+ }
89
+ case "MemberAccess":
90
+ return 1 + calculateAstDepth(node.object);
91
+ case "IndexAccess":
92
+ return (1 +
93
+ Math.max(calculateAstDepth(node.object), calculateAstDepth(node.index)));
94
+ case "FunctionCall": {
95
+ let maxArgDepth = 0;
96
+ for (const arg of node.args) {
97
+ maxArgDepth = Math.max(maxArgDepth, calculateAstDepth(arg));
98
+ }
99
+ return 1 + maxArgDepth;
100
+ }
101
+ case "UnaryOp":
102
+ return 1 + calculateAstDepth(node.operand);
103
+ case "BinaryOp":
104
+ return (1 +
105
+ Math.max(calculateAstDepth(node.left), calculateAstDepth(node.right)));
106
+ case "TernaryOp":
107
+ return (1 +
108
+ Math.max(calculateAstDepth(node.condition), calculateAstDepth(node.consequent), calculateAstDepth(node.alternate)));
109
+ }
110
+ }
111
+ /**
112
+ * Returns a human-readable representation of an AST node for debugging.
113
+ */
114
+ function astToString(node, indent = 0) {
115
+ const prefix = " ".repeat(indent);
116
+ switch (node.type) {
117
+ case "StringLiteral":
118
+ return `${prefix}String: "${node.value}"`;
119
+ case "NumberLiteral":
120
+ return `${prefix}Number: ${node.value}`;
121
+ case "BooleanLiteral":
122
+ return `${prefix}Boolean: ${node.value}`;
123
+ case "NullLiteral":
124
+ return `${prefix}Null`;
125
+ case "ArrayLiteral":
126
+ return (`${prefix}Array:\n` +
127
+ node.elements.map((e) => astToString(e, indent + 1)).join("\n"));
128
+ case "Identifier":
129
+ return `${prefix}Identifier: ${node.name}`;
130
+ case "MemberAccess":
131
+ return (`${prefix}MemberAccess: .${node.property}\n` +
132
+ astToString(node.object, indent + 1));
133
+ case "IndexAccess":
134
+ return (`${prefix}IndexAccess:\n` +
135
+ `${prefix} object:\n` +
136
+ astToString(node.object, indent + 2) +
137
+ `\n${prefix} index:\n` +
138
+ astToString(node.index, indent + 2));
139
+ case "FunctionCall":
140
+ return (`${prefix}FunctionCall: ${node.name}\n` +
141
+ node.args.map((a) => astToString(a, indent + 1)).join("\n"));
142
+ case "UnaryOp":
143
+ return (`${prefix}UnaryOp: ${node.operator}\n` +
144
+ astToString(node.operand, indent + 1));
145
+ case "BinaryOp":
146
+ return (`${prefix}BinaryOp: ${node.operator}\n` +
147
+ astToString(node.left, indent + 1) +
148
+ "\n" +
149
+ astToString(node.right, indent + 1));
150
+ case "TernaryOp":
151
+ return (`${prefix}TernaryOp:\n` +
152
+ `${prefix} condition:\n` +
153
+ astToString(node.condition, indent + 2) +
154
+ `\n${prefix} consequent:\n` +
155
+ astToString(node.consequent, indent + 2) +
156
+ `\n${prefix} alternate:\n` +
157
+ astToString(node.alternate, indent + 2));
158
+ }
159
+ }
160
+
161
+ /**
162
+ * Error types for the expression evaluation engine.
163
+ *
164
+ * All expression errors extend ExpressionError for consistent handling.
165
+ */
166
+ /**
167
+ * Base error class for all expression-related errors.
168
+ */
169
+ class ExpressionError extends Error {
170
+ constructor(message, position, expression) {
171
+ super(message);
172
+ this.name = "ExpressionError";
173
+ this.position = position;
174
+ this.expression = expression;
175
+ }
176
+ /**
177
+ * Returns a formatted error message with position context.
178
+ */
179
+ formatWithContext() {
180
+ if (this.expression === undefined || this.position === undefined) {
181
+ return this.message;
182
+ }
183
+ const pointer = " ".repeat(this.position) + "^";
184
+ return `${this.message}\n ${this.expression}\n ${pointer}`;
185
+ }
186
+ }
187
+ /**
188
+ * Error thrown during tokenization (lexical analysis).
189
+ */
190
+ class TokenizerError extends ExpressionError {
191
+ constructor(message, position, expression) {
192
+ super(message, position, expression);
193
+ this.name = "TokenizerError";
194
+ }
195
+ }
196
+ /**
197
+ * Error thrown during parsing (syntax analysis).
198
+ */
199
+ class ParseError extends ExpressionError {
200
+ constructor(message, position, expression) {
201
+ super(message, position, expression);
202
+ this.name = "ParseError";
203
+ }
204
+ }
205
+ /**
206
+ * Error thrown during evaluation (runtime error).
207
+ */
208
+ class EvaluationError extends ExpressionError {
209
+ constructor(message, position, expression, path) {
210
+ super(message, position, expression);
211
+ this.name = "EvaluationError";
212
+ this.path = path;
213
+ }
214
+ }
215
+ /**
216
+ * Error thrown for type mismatches during evaluation.
217
+ */
218
+ class TypeError extends EvaluationError {
219
+ constructor(expected, actual, position, expression) {
220
+ super(`Type error: expected ${expected}, got ${actual}`, position, expression);
221
+ this.name = "TypeError";
222
+ this.expected = expected;
223
+ this.actual = actual;
224
+ }
225
+ }
226
+ /**
227
+ * Error thrown when expression limits are exceeded.
228
+ */
229
+ class LimitExceededError extends ExpressionError {
230
+ constructor(limitName, limit, actual) {
231
+ super(`Limit exceeded: ${limitName} (limit: ${limit}, actual: ${actual})`);
232
+ this.name = "LimitExceededError";
233
+ this.limitName = limitName;
234
+ this.limit = limit;
235
+ this.actual = actual;
236
+ }
237
+ }
238
+ /**
239
+ * Error thrown when a built-in function encounters an error.
240
+ */
241
+ class BuiltinError extends EvaluationError {
242
+ constructor(functionName, message, position, expression) {
243
+ super(`${functionName}: ${message}`, position, expression);
244
+ this.name = "BuiltinError";
245
+ this.functionName = functionName;
246
+ }
247
+ }
248
+
249
+ /**
250
+ * Resource limits for expression parsing and evaluation.
251
+ *
252
+ * These limits protect against resource exhaustion attacks and
253
+ * overly complex expressions.
254
+ */
255
+ /**
256
+ * Default expression limits.
257
+ *
258
+ * These values are chosen to allow reasonable expressions while
259
+ * preventing resource exhaustion.
260
+ */
261
+ const DEFAULT_EXPRESSION_LIMITS = {
262
+ maxExpressionLength: 4096,
263
+ maxAstDepth: 32,
264
+ maxAstNodes: 256,
265
+ maxRegexPatternLength: 256,
266
+ maxGlobPatternLength: 256,
267
+ maxStringLength: 1024,
268
+ maxArrayLength: 64,
269
+ maxFunctionArgs: 16,
270
+ maxMemberAccessDepth: 16,
271
+ };
272
+ /**
273
+ * Validates that expression length is within limits.
274
+ */
275
+ function checkExpressionLength(expression, limits = DEFAULT_EXPRESSION_LIMITS) {
276
+ if (expression.length > limits.maxExpressionLength) {
277
+ throw new Error(`Expression length ${expression.length} exceeds limit of ${limits.maxExpressionLength}`);
278
+ }
279
+ }
280
+ /**
281
+ * Validates AST depth during parsing.
282
+ */
283
+ function checkAstDepth(depth, limits = DEFAULT_EXPRESSION_LIMITS) {
284
+ if (depth > limits.maxAstDepth) {
285
+ throw new Error(`AST depth ${depth} exceeds limit of ${limits.maxAstDepth}`);
286
+ }
287
+ }
288
+ /**
289
+ * Validates AST node count during parsing.
290
+ */
291
+ function checkAstNodeCount(count, limits = DEFAULT_EXPRESSION_LIMITS) {
292
+ if (count > limits.maxAstNodes) {
293
+ throw new Error(`AST node count ${count} exceeds limit of ${limits.maxAstNodes}`);
294
+ }
295
+ }
296
+ /**
297
+ * Validates regex pattern length before compilation.
298
+ */
299
+ function checkRegexPatternLength(pattern, limits = DEFAULT_EXPRESSION_LIMITS) {
300
+ if (pattern.length > limits.maxRegexPatternLength) {
301
+ throw new Error(`Regex pattern length ${pattern.length} exceeds limit of ${limits.maxRegexPatternLength}`);
302
+ }
303
+ }
304
+ /**
305
+ * Validates glob pattern length before compilation.
306
+ */
307
+ function checkGlobPatternLength(pattern, limits = DEFAULT_EXPRESSION_LIMITS) {
308
+ if (pattern.length > limits.maxGlobPatternLength) {
309
+ throw new Error(`Glob pattern length ${pattern.length} exceeds limit of ${limits.maxGlobPatternLength}`);
310
+ }
311
+ }
312
+ /**
313
+ * Validates array length during evaluation.
314
+ */
315
+ function checkArrayLength(length, limits = DEFAULT_EXPRESSION_LIMITS) {
316
+ if (length > limits.maxArrayLength) {
317
+ throw new Error(`Array length ${length} exceeds limit of ${limits.maxArrayLength}`);
318
+ }
319
+ }
320
+ /**
321
+ * Validates function argument count.
322
+ */
323
+ function checkFunctionArgCount(count, limits = DEFAULT_EXPRESSION_LIMITS) {
324
+ if (count > limits.maxFunctionArgs) {
325
+ throw new Error(`Function argument count ${count} exceeds limit of ${limits.maxFunctionArgs}`);
326
+ }
327
+ }
328
+
329
+ /**
330
+ * Tokenizer (lexer) for the expression language.
331
+ *
332
+ * Converts expression strings into a stream of tokens for the parser.
333
+ */
334
+ /**
335
+ * Keywords recognized by the tokenizer.
336
+ */
337
+ const KEYWORDS = new Map([
338
+ ["true", "TRUE"],
339
+ ["false", "FALSE"],
340
+ ["null", "NULL"],
341
+ ["in", "IN"],
342
+ ["not", "NOT"],
343
+ ]);
344
+ /**
345
+ * Checks if a character is a digit.
346
+ */
347
+ function isDigit(ch) {
348
+ return ch >= "0" && ch <= "9";
349
+ }
350
+ /**
351
+ * Checks if a character can start an identifier.
352
+ */
353
+ function isIdentifierStart(ch) {
354
+ return ((ch >= "a" && ch <= "z") ||
355
+ (ch >= "A" && ch <= "Z") ||
356
+ ch === "_");
357
+ }
358
+ /**
359
+ * Checks if a character can continue an identifier.
360
+ */
361
+ function isIdentifierPart(ch) {
362
+ return isIdentifierStart(ch) || isDigit(ch);
363
+ }
364
+ /**
365
+ * Checks if a character is whitespace.
366
+ */
367
+ function isWhitespace(ch) {
368
+ return ch === " " || ch === "\t" || ch === "\n" || ch === "\r";
369
+ }
370
+ /**
371
+ * Tokenizer for expression strings.
372
+ */
373
+ class Tokenizer {
374
+ constructor(source, limits) {
375
+ this.position = 0;
376
+ this.tokens = [];
377
+ this.source = source;
378
+ this.limits = limits;
379
+ }
380
+ /**
381
+ * Tokenizes the source expression and returns all tokens.
382
+ */
383
+ tokenize() {
384
+ checkExpressionLength(this.source, this.limits);
385
+ while (!this.isAtEnd()) {
386
+ this.scanToken();
387
+ }
388
+ this.tokens.push({
389
+ type: "EOF",
390
+ value: "",
391
+ position: this.position,
392
+ });
393
+ return this.tokens;
394
+ }
395
+ isAtEnd() {
396
+ return this.position >= this.source.length;
397
+ }
398
+ peek() {
399
+ if (this.isAtEnd())
400
+ return "\0";
401
+ return this.source[this.position];
402
+ }
403
+ peekNext() {
404
+ if (this.position + 1 >= this.source.length)
405
+ return "\0";
406
+ return this.source[this.position + 1];
407
+ }
408
+ advance() {
409
+ return this.source[this.position++];
410
+ }
411
+ addToken(type, value, position) {
412
+ this.tokens.push({ type, value, position });
413
+ }
414
+ scanToken() {
415
+ const ch = this.advance();
416
+ const startPosition = this.position - 1;
417
+ // Skip whitespace
418
+ if (isWhitespace(ch)) {
419
+ return;
420
+ }
421
+ // Single-character tokens
422
+ switch (ch) {
423
+ case "(":
424
+ this.addToken("LPAREN", "(", startPosition);
425
+ return;
426
+ case ")":
427
+ this.addToken("RPAREN", ")", startPosition);
428
+ return;
429
+ case "[":
430
+ this.addToken("LBRACKET", "[", startPosition);
431
+ return;
432
+ case "]":
433
+ this.addToken("RBRACKET", "]", startPosition);
434
+ return;
435
+ case ".":
436
+ this.addToken("DOT", ".", startPosition);
437
+ return;
438
+ case ",":
439
+ this.addToken("COMMA", ",", startPosition);
440
+ return;
441
+ case "+":
442
+ this.addToken("PLUS", "+", startPosition);
443
+ return;
444
+ case "-":
445
+ this.addToken("MINUS", "-", startPosition);
446
+ return;
447
+ case "*":
448
+ this.addToken("STAR", "*", startPosition);
449
+ return;
450
+ case "/":
451
+ this.addToken("SLASH", "/", startPosition);
452
+ return;
453
+ case "%":
454
+ this.addToken("PERCENT", "%", startPosition);
455
+ return;
456
+ case "?":
457
+ this.addToken("QUESTION", "?", startPosition);
458
+ return;
459
+ case ":":
460
+ this.addToken("COLON", ":", startPosition);
461
+ return;
462
+ }
463
+ // Two-character operators
464
+ if (ch === "<") {
465
+ if (this.peek() === "=") {
466
+ this.advance();
467
+ this.addToken("LE", "<=", startPosition);
468
+ }
469
+ else {
470
+ this.addToken("LT", "<", startPosition);
471
+ }
472
+ return;
473
+ }
474
+ if (ch === ">") {
475
+ if (this.peek() === "=") {
476
+ this.advance();
477
+ this.addToken("GE", ">=", startPosition);
478
+ }
479
+ else {
480
+ this.addToken("GT", ">", startPosition);
481
+ }
482
+ return;
483
+ }
484
+ if (ch === "=") {
485
+ if (this.peek() === "=") {
486
+ this.advance();
487
+ this.addToken("EQ", "==", startPosition);
488
+ return;
489
+ }
490
+ throw new TokenizerError("Unexpected '='. Did you mean '=='?", startPosition, this.source);
491
+ }
492
+ if (ch === "!") {
493
+ if (this.peek() === "=") {
494
+ this.advance();
495
+ this.addToken("NE", "!=", startPosition);
496
+ }
497
+ else {
498
+ this.addToken("NOT", "!", startPosition);
499
+ }
500
+ return;
501
+ }
502
+ if (ch === "&") {
503
+ if (this.peek() === "&") {
504
+ this.advance();
505
+ this.addToken("AND", "&&", startPosition);
506
+ return;
507
+ }
508
+ throw new TokenizerError("Unexpected '&'. Did you mean '&&'?", startPosition, this.source);
509
+ }
510
+ if (ch === "|") {
511
+ if (this.peek() === "|") {
512
+ this.advance();
513
+ this.addToken("OR", "||", startPosition);
514
+ return;
515
+ }
516
+ throw new TokenizerError("Unexpected '|'. Did you mean '||'?", startPosition, this.source);
517
+ }
518
+ // String literals
519
+ if (ch === '"' || ch === "'") {
520
+ this.scanString(ch, startPosition);
521
+ return;
522
+ }
523
+ // Number literals
524
+ if (isDigit(ch)) {
525
+ this.scanNumber(startPosition);
526
+ return;
527
+ }
528
+ // Identifiers and keywords
529
+ if (isIdentifierStart(ch)) {
530
+ this.scanIdentifier(startPosition);
531
+ return;
532
+ }
533
+ throw new TokenizerError(`Unexpected character: '${ch}'`, startPosition, this.source);
534
+ }
535
+ scanString(quote, startPosition) {
536
+ let value = "";
537
+ while (!this.isAtEnd() && this.peek() !== quote) {
538
+ const ch = this.advance();
539
+ if (ch === "\\") {
540
+ // Escape sequence
541
+ if (this.isAtEnd()) {
542
+ throw new TokenizerError("Unterminated string", startPosition, this.source);
543
+ }
544
+ const escaped = this.advance();
545
+ switch (escaped) {
546
+ case "n":
547
+ value += "\n";
548
+ break;
549
+ case "r":
550
+ value += "\r";
551
+ break;
552
+ case "t":
553
+ value += "\t";
554
+ break;
555
+ case "\\":
556
+ value += "\\";
557
+ break;
558
+ case '"':
559
+ value += '"';
560
+ break;
561
+ case "'":
562
+ value += "'";
563
+ break;
564
+ default:
565
+ throw new TokenizerError(`Invalid escape sequence: \\${escaped}`, this.position - 2, this.source);
566
+ }
567
+ }
568
+ else if (ch === "\n" || ch === "\r") {
569
+ throw new TokenizerError("Unterminated string (newline in string literal)", startPosition, this.source);
570
+ }
571
+ else {
572
+ value += ch;
573
+ }
574
+ }
575
+ if (this.isAtEnd()) {
576
+ throw new TokenizerError("Unterminated string", startPosition, this.source);
577
+ }
578
+ // Consume closing quote
579
+ this.advance();
580
+ this.addToken("STRING", value, startPosition);
581
+ }
582
+ scanNumber(startPosition) {
583
+ // Back up to include the first digit
584
+ this.position--;
585
+ let value = "";
586
+ // Integer part
587
+ while (isDigit(this.peek())) {
588
+ value += this.advance();
589
+ }
590
+ // Fractional part
591
+ if (this.peek() === "." && isDigit(this.peekNext())) {
592
+ value += this.advance(); // consume '.'
593
+ while (isDigit(this.peek())) {
594
+ value += this.advance();
595
+ }
596
+ }
597
+ // Exponent part
598
+ if (this.peek() === "e" || this.peek() === "E") {
599
+ value += this.advance();
600
+ if (this.peek() === "+" || this.peek() === "-") {
601
+ value += this.advance();
602
+ }
603
+ if (!isDigit(this.peek())) {
604
+ throw new TokenizerError("Invalid number: expected exponent digits", startPosition, this.source);
605
+ }
606
+ while (isDigit(this.peek())) {
607
+ value += this.advance();
608
+ }
609
+ }
610
+ this.addToken("NUMBER", value, startPosition);
611
+ }
612
+ scanIdentifier(startPosition) {
613
+ // Back up to include the first character
614
+ this.position--;
615
+ let value = "";
616
+ while (isIdentifierPart(this.peek())) {
617
+ value += this.advance();
618
+ }
619
+ // Check for "not in" compound keyword
620
+ const valueLower = value.toLowerCase();
621
+ if (valueLower === "not") {
622
+ // Check if followed by whitespace and "in"
623
+ const savedPosition = this.position;
624
+ // Skip whitespace
625
+ while (isWhitespace(this.peek())) {
626
+ this.advance();
627
+ }
628
+ // Check for "in"
629
+ if (this.peek() === "i" &&
630
+ this.peekNext() === "n" &&
631
+ !isIdentifierPart(this.source[this.position + 2] ?? "\0")) {
632
+ this.advance(); // consume 'i'
633
+ this.advance(); // consume 'n'
634
+ this.addToken("NOT_IN", "not in", startPosition);
635
+ return;
636
+ }
637
+ // Not "not in", restore position
638
+ this.position = savedPosition;
639
+ }
640
+ // Check for keyword
641
+ const keywordType = KEYWORDS.get(valueLower);
642
+ if (keywordType) {
643
+ this.addToken(keywordType, value, startPosition);
644
+ }
645
+ else {
646
+ this.addToken("IDENTIFIER", value, startPosition);
647
+ }
648
+ }
649
+ }
650
+ /**
651
+ * Tokenizes an expression string into tokens.
652
+ *
653
+ * @param source - The expression string to tokenize
654
+ * @param limits - Optional expression limits
655
+ * @returns Array of tokens
656
+ * @throws TokenizerError if the expression contains invalid tokens
657
+ */
658
+ function tokenize(source, limits) {
659
+ const tokenizer = new Tokenizer(source, limits);
660
+ return tokenizer.tokenize();
661
+ }
662
+
663
+ /**
664
+ * Parser for the expression language.
665
+ *
666
+ * Parses a stream of tokens into an Abstract Syntax Tree (AST).
667
+ * Uses recursive descent parsing with operator precedence.
668
+ *
669
+ * Precedence (lowest to highest):
670
+ * 1. Ternary: ? :
671
+ * 2. Logical OR: ||
672
+ * 3. Logical AND: &&
673
+ * 4. Membership: in, not in
674
+ * 5. Equality: ==, !=
675
+ * 6. Comparison: <, <=, >, >=
676
+ * 7. Additive: +, -
677
+ * 8. Multiplicative: *, /, %
678
+ * 9. Unary: !, -
679
+ * 10. Postfix: . [] ()
680
+ * 11. Primary: literals, identifiers, parentheses
681
+ */
682
+ /**
683
+ * Parser for expression strings.
684
+ */
685
+ class Parser {
686
+ constructor(tokens, source, limits = DEFAULT_EXPRESSION_LIMITS) {
687
+ this.current = 0;
688
+ this.tokens = tokens;
689
+ this.source = source;
690
+ this.limits = limits;
691
+ }
692
+ /**
693
+ * Parses the token stream into an AST.
694
+ */
695
+ parse() {
696
+ const ast = this.parseTernary();
697
+ if (!this.isAtEnd()) {
698
+ const token = this.peek();
699
+ throw new ParseError(`Unexpected token: ${token.value || token.type}`, token.position, this.source);
700
+ }
701
+ // Validate AST limits
702
+ const nodeCount = countAstNodes(ast);
703
+ checkAstNodeCount(nodeCount, this.limits);
704
+ const depth = calculateAstDepth(ast);
705
+ checkAstDepth(depth, this.limits);
706
+ return ast;
707
+ }
708
+ // ============================================================
709
+ // Token Helpers
710
+ // ============================================================
711
+ isAtEnd() {
712
+ return this.peek().type === "EOF";
713
+ }
714
+ peek() {
715
+ return this.tokens[this.current];
716
+ }
717
+ previous() {
718
+ return this.tokens[this.current - 1];
719
+ }
720
+ advance() {
721
+ if (!this.isAtEnd()) {
722
+ this.current++;
723
+ }
724
+ return this.previous();
725
+ }
726
+ check(type) {
727
+ if (this.isAtEnd())
728
+ return false;
729
+ return this.peek().type === type;
730
+ }
731
+ match(...types) {
732
+ for (const type of types) {
733
+ if (this.check(type)) {
734
+ this.advance();
735
+ return true;
736
+ }
737
+ }
738
+ return false;
739
+ }
740
+ consume(type, message) {
741
+ if (this.check(type)) {
742
+ return this.advance();
743
+ }
744
+ const token = this.peek();
745
+ throw new ParseError(message, token.position, this.source);
746
+ }
747
+ // ============================================================
748
+ // Expression Parsing (by precedence, lowest to highest)
749
+ // ============================================================
750
+ /**
751
+ * Parses ternary expressions: condition ? consequent : alternate
752
+ */
753
+ parseTernary() {
754
+ const position = this.peek().position;
755
+ let node = this.parseOr();
756
+ if (this.match("QUESTION")) {
757
+ const consequent = this.parseTernary();
758
+ this.consume("COLON", "Expected ':' in ternary expression");
759
+ const alternate = this.parseTernary();
760
+ node = {
761
+ type: "TernaryOp",
762
+ position,
763
+ condition: node,
764
+ consequent,
765
+ alternate,
766
+ };
767
+ }
768
+ return node;
769
+ }
770
+ /**
771
+ * Parses logical OR: ||
772
+ */
773
+ parseOr() {
774
+ let node = this.parseAnd();
775
+ while (this.match("OR")) {
776
+ const position = this.previous().position;
777
+ const right = this.parseAnd();
778
+ node = {
779
+ type: "BinaryOp",
780
+ position,
781
+ operator: "||",
782
+ left: node,
783
+ right,
784
+ };
785
+ }
786
+ return node;
787
+ }
788
+ /**
789
+ * Parses logical AND: &&
790
+ */
791
+ parseAnd() {
792
+ let node = this.parseEquality();
793
+ while (this.match("AND")) {
794
+ const position = this.previous().position;
795
+ const right = this.parseEquality();
796
+ node = {
797
+ type: "BinaryOp",
798
+ position,
799
+ operator: "&&",
800
+ left: node,
801
+ right,
802
+ };
803
+ }
804
+ return node;
805
+ }
806
+ /**
807
+ * Parses equality: ==, !=
808
+ */
809
+ parseEquality() {
810
+ let node = this.parseMembership();
811
+ while (this.match("EQ", "NE")) {
812
+ const operator = this.previous().type === "EQ" ? "==" : "!=";
813
+ const position = this.previous().position;
814
+ const right = this.parseMembership();
815
+ node = {
816
+ type: "BinaryOp",
817
+ position,
818
+ operator: operator,
819
+ left: node,
820
+ right,
821
+ };
822
+ }
823
+ return node;
824
+ }
825
+ /**
826
+ * Parses membership: in, not in
827
+ */
828
+ parseMembership() {
829
+ let node = this.parseComparison();
830
+ while (this.match("IN", "NOT_IN")) {
831
+ const operator = this.previous().type === "IN" ? "in" : "not in";
832
+ const position = this.previous().position;
833
+ const right = this.parseComparison();
834
+ node = {
835
+ type: "BinaryOp",
836
+ position,
837
+ operator: operator,
838
+ left: node,
839
+ right,
840
+ };
841
+ }
842
+ return node;
843
+ }
844
+ /**
845
+ * Parses comparison: <, <=, >, >=
846
+ */
847
+ parseComparison() {
848
+ let node = this.parseAdditive();
849
+ while (this.match("LT", "LE", "GT", "GE")) {
850
+ const token = this.previous();
851
+ let operator;
852
+ switch (token.type) {
853
+ case "LT":
854
+ operator = "<";
855
+ break;
856
+ case "LE":
857
+ operator = "<=";
858
+ break;
859
+ case "GT":
860
+ operator = ">";
861
+ break;
862
+ case "GE":
863
+ operator = ">=";
864
+ break;
865
+ default:
866
+ throw new ParseError(`Unexpected token: ${token.type}`, token.position, this.source);
867
+ }
868
+ const position = token.position;
869
+ const right = this.parseAdditive();
870
+ node = {
871
+ type: "BinaryOp",
872
+ position,
873
+ operator,
874
+ left: node,
875
+ right,
876
+ };
877
+ }
878
+ return node;
879
+ }
880
+ /**
881
+ * Parses additive: +, -
882
+ */
883
+ parseAdditive() {
884
+ let node = this.parseMultiplicative();
885
+ while (this.match("PLUS", "MINUS")) {
886
+ const operator = this.previous().type === "PLUS" ? "+" : "-";
887
+ const position = this.previous().position;
888
+ const right = this.parseMultiplicative();
889
+ node = {
890
+ type: "BinaryOp",
891
+ position,
892
+ operator: operator,
893
+ left: node,
894
+ right,
895
+ };
896
+ }
897
+ return node;
898
+ }
899
+ /**
900
+ * Parses multiplicative: *, /, %
901
+ */
902
+ parseMultiplicative() {
903
+ let node = this.parseUnary();
904
+ while (this.match("STAR", "SLASH", "PERCENT")) {
905
+ const token = this.previous();
906
+ let operator;
907
+ switch (token.type) {
908
+ case "STAR":
909
+ operator = "*";
910
+ break;
911
+ case "SLASH":
912
+ operator = "/";
913
+ break;
914
+ case "PERCENT":
915
+ operator = "%";
916
+ break;
917
+ default:
918
+ throw new ParseError(`Unexpected token: ${token.type}`, token.position, this.source);
919
+ }
920
+ const position = token.position;
921
+ const right = this.parseUnary();
922
+ node = {
923
+ type: "BinaryOp",
924
+ position,
925
+ operator,
926
+ left: node,
927
+ right,
928
+ };
929
+ }
930
+ return node;
931
+ }
932
+ /**
933
+ * Parses unary: !, -
934
+ */
935
+ parseUnary() {
936
+ if (this.match("NOT", "MINUS")) {
937
+ const token = this.previous();
938
+ const operator = token.type === "NOT" ? "!" : "-";
939
+ const position = token.position;
940
+ const operand = this.parseUnary();
941
+ return {
942
+ type: "UnaryOp",
943
+ position,
944
+ operator,
945
+ operand,
946
+ };
947
+ }
948
+ return this.parsePostfix();
949
+ }
950
+ /**
951
+ * Parses postfix: . [] ()
952
+ */
953
+ parsePostfix() {
954
+ let node = this.parsePrimary();
955
+ while (true) {
956
+ if (this.match("DOT")) {
957
+ const position = this.previous().position;
958
+ const propToken = this.consume("IDENTIFIER", "Expected property name after '.'");
959
+ node = {
960
+ type: "MemberAccess",
961
+ position,
962
+ object: node,
963
+ property: propToken.value,
964
+ };
965
+ }
966
+ else if (this.match("LBRACKET")) {
967
+ const position = this.previous().position;
968
+ const index = this.parseTernary();
969
+ this.consume("RBRACKET", "Expected ']' after index");
970
+ node = {
971
+ type: "IndexAccess",
972
+ position,
973
+ object: node,
974
+ index,
975
+ };
976
+ }
977
+ else if (this.match("LPAREN")) {
978
+ // Function call - node must be an identifier
979
+ if (node.type !== "Identifier") {
980
+ throw new ParseError("Only named functions can be called", node.position, this.source);
981
+ }
982
+ const position = this.previous().position;
983
+ const args = this.parseArgumentList();
984
+ checkFunctionArgCount(args.length, this.limits);
985
+ node = {
986
+ type: "FunctionCall",
987
+ position,
988
+ name: node.name,
989
+ args,
990
+ };
991
+ }
992
+ else {
993
+ break;
994
+ }
995
+ }
996
+ return node;
997
+ }
998
+ /**
999
+ * Parses function argument list (already consumed opening paren).
1000
+ */
1001
+ parseArgumentList() {
1002
+ const args = [];
1003
+ if (!this.check("RPAREN")) {
1004
+ do {
1005
+ args.push(this.parseTernary());
1006
+ } while (this.match("COMMA"));
1007
+ }
1008
+ this.consume("RPAREN", "Expected ')' after function arguments");
1009
+ return args;
1010
+ }
1011
+ /**
1012
+ * Parses primary expressions: literals, identifiers, parentheses, arrays.
1013
+ */
1014
+ parsePrimary() {
1015
+ const token = this.peek();
1016
+ const position = token.position;
1017
+ // Boolean literals
1018
+ if (this.match("TRUE")) {
1019
+ return { type: "BooleanLiteral", position, value: true };
1020
+ }
1021
+ if (this.match("FALSE")) {
1022
+ return { type: "BooleanLiteral", position, value: false };
1023
+ }
1024
+ // Null literal
1025
+ if (this.match("NULL")) {
1026
+ return { type: "NullLiteral", position };
1027
+ }
1028
+ // String literal
1029
+ if (this.match("STRING")) {
1030
+ return {
1031
+ type: "StringLiteral",
1032
+ position,
1033
+ value: this.previous().value,
1034
+ };
1035
+ }
1036
+ // Number literal
1037
+ if (this.match("NUMBER")) {
1038
+ const value = parseFloat(this.previous().value);
1039
+ if (!Number.isFinite(value)) {
1040
+ throw new ParseError("Invalid number", position, this.source);
1041
+ }
1042
+ return { type: "NumberLiteral", position, value };
1043
+ }
1044
+ // Identifier
1045
+ if (this.match("IDENTIFIER")) {
1046
+ return {
1047
+ type: "Identifier",
1048
+ position,
1049
+ name: this.previous().value,
1050
+ };
1051
+ }
1052
+ // Parenthesized expression
1053
+ if (this.match("LPAREN")) {
1054
+ const expr = this.parseTernary();
1055
+ this.consume("RPAREN", "Expected ')' after expression");
1056
+ return expr;
1057
+ }
1058
+ // Array literal
1059
+ if (this.match("LBRACKET")) {
1060
+ const elements = [];
1061
+ if (!this.check("RBRACKET")) {
1062
+ do {
1063
+ elements.push(this.parseTernary());
1064
+ } while (this.match("COMMA"));
1065
+ }
1066
+ this.consume("RBRACKET", "Expected ']' after array elements");
1067
+ checkArrayLength(elements.length, this.limits);
1068
+ return { type: "ArrayLiteral", position, elements };
1069
+ }
1070
+ throw new ParseError(`Unexpected token: ${token.value || token.type}`, position, this.source);
1071
+ }
1072
+ }
1073
+ /**
1074
+ * Parses an expression string into an AST.
1075
+ *
1076
+ * @param source - The expression string to parse
1077
+ * @param limits - Optional expression limits
1078
+ * @returns The parsed AST
1079
+ * @throws TokenizerError if tokenization fails
1080
+ * @throws ParseError if parsing fails
1081
+ */
1082
+ function parse(source, limits = DEFAULT_EXPRESSION_LIMITS) {
1083
+ const tokens = tokenize(source, limits);
1084
+ const parser = new Parser(tokens, source, limits);
1085
+ return parser.parse();
1086
+ }
1087
+
1088
+ /**
1089
+ * Built-in functions for the expression language.
1090
+ *
1091
+ * All built-in functions are pure and deterministic.
1092
+ *
1093
+ * Null handling semantics:
1094
+ * - `undefined` is normalized to `null` throughout the expression value model.
1095
+ * - Predicate-style builtins (starts_with, ends_with, contains, glob_match,
1096
+ * regex_match, etc.) return `false` when passed `null` for required args
1097
+ * instead of throwing an error.
1098
+ * - Wrong non-null types still raise BuiltinError to surface real bugs.
1099
+ * - Non-predicate operations (arithmetic, comparisons) remain strict.
1100
+ */
1101
+ /**
1102
+ * Normalizes a JavaScript value to an ExprValue.
1103
+ *
1104
+ * Rules:
1105
+ * - `undefined` -> `null`
1106
+ * - `null` -> `null`
1107
+ * - boolean/number/string -> returned as-is
1108
+ * - array -> elements are recursively normalized
1109
+ * - object -> returned as-is (reads will normalize on access)
1110
+ * - other types (function, symbol, etc.) -> `null`
1111
+ *
1112
+ * This ensures `undefined` never leaks into the expression value model.
1113
+ */
1114
+ function normalizeJsValue(value) {
1115
+ if (value === undefined || value === null) {
1116
+ return null;
1117
+ }
1118
+ if (typeof value === "boolean" || typeof value === "number") {
1119
+ return value;
1120
+ }
1121
+ if (typeof value === "string") {
1122
+ return value;
1123
+ }
1124
+ if (Array.isArray(value)) {
1125
+ return value.map((element) => normalizeJsValue(element));
1126
+ }
1127
+ if (typeof value === "object") {
1128
+ // Return the object as-is; reads will normalize on access
1129
+ return value;
1130
+ }
1131
+ // Function, symbol, bigint, etc. -> null
1132
+ return null;
1133
+ }
1134
+ /**
1135
+ * Gets the type name of a value for error messages.
1136
+ */
1137
+ function getTypeName(value) {
1138
+ if (value === null)
1139
+ return "null";
1140
+ if (Array.isArray(value))
1141
+ return "array";
1142
+ return typeof value;
1143
+ }
1144
+ /**
1145
+ * Asserts that a value is a string.
1146
+ */
1147
+ function assertString$1(value, argName, functionName) {
1148
+ if (typeof value !== "string") {
1149
+ throw new BuiltinError(functionName, `${argName} must be a string, got ${getTypeName(value)}`);
1150
+ }
1151
+ }
1152
+ /**
1153
+ * Checks if a value is null (for null-tolerant predicates).
1154
+ */
1155
+ function isNull$1(value) {
1156
+ return value === null;
1157
+ }
1158
+ /**
1159
+ * Asserts that a non-null value is a string (for null-tolerant predicates).
1160
+ * Returns false if the value is null (indicating predicate should return false).
1161
+ * Throws BuiltinError if the value is non-null but not a string.
1162
+ */
1163
+ function assertStringOrNull$1(value, argName, functionName) {
1164
+ if (isNull$1(value)) {
1165
+ return false;
1166
+ }
1167
+ if (typeof value !== "string") {
1168
+ throw new BuiltinError(functionName, `${argName} must be a string, got ${getTypeName(value)}`);
1169
+ }
1170
+ return true;
1171
+ }
1172
+ /**
1173
+ * Gets an argument by index, throwing if not present.
1174
+ */
1175
+ function getArg$1(args, index, functionName) {
1176
+ const value = args[index];
1177
+ if (value === undefined) {
1178
+ throw new BuiltinError(functionName, `missing argument at index ${index}`);
1179
+ }
1180
+ return value;
1181
+ }
1182
+ /**
1183
+ * Asserts argument count.
1184
+ */
1185
+ function assertArgCount$1(args, expected, functionName) {
1186
+ if (args.length !== expected) {
1187
+ throw new BuiltinError(functionName, `expected ${expected} argument(s), got ${args.length}`);
1188
+ }
1189
+ }
1190
+ /**
1191
+ * Asserts argument count range.
1192
+ */
1193
+ function assertArgCountRange(args, min, max, functionName) {
1194
+ if (args.length < min || args.length > max) {
1195
+ throw new BuiltinError(functionName, `expected ${min}-${max} argument(s), got ${args.length}`);
1196
+ }
1197
+ }
1198
+ // ============================================================
1199
+ // String Helpers
1200
+ // ============================================================
1201
+ /**
1202
+ * lower(s: string) -> string
1203
+ *
1204
+ * Returns the lowercase version of the string.
1205
+ */
1206
+ const lower = (args) => {
1207
+ assertArgCount$1(args, 1, "lower");
1208
+ const s = getArg$1(args, 0, "lower");
1209
+ assertString$1(s, "s", "lower");
1210
+ return s.toLowerCase();
1211
+ };
1212
+ /**
1213
+ * upper(s: string) -> string
1214
+ *
1215
+ * Returns the uppercase version of the string.
1216
+ */
1217
+ const upper = (args) => {
1218
+ assertArgCount$1(args, 1, "upper");
1219
+ const s = getArg$1(args, 0, "upper");
1220
+ assertString$1(s, "s", "upper");
1221
+ return s.toUpperCase();
1222
+ };
1223
+ /**
1224
+ * starts_with(s: string, prefix: string) -> bool
1225
+ *
1226
+ * Returns true if the string starts with the prefix.
1227
+ * Null-tolerant: returns false if either argument is null.
1228
+ */
1229
+ const starts_with = (args) => {
1230
+ assertArgCount$1(args, 2, "starts_with");
1231
+ const s = getArg$1(args, 0, "starts_with");
1232
+ const prefix = getArg$1(args, 1, "starts_with");
1233
+ // Null-tolerant: return false if either arg is null
1234
+ if (!assertStringOrNull$1(s, "s", "starts_with"))
1235
+ return false;
1236
+ if (!assertStringOrNull$1(prefix, "prefix", "starts_with"))
1237
+ return false;
1238
+ return s.startsWith(prefix);
1239
+ };
1240
+ /**
1241
+ * ends_with(s: string, suffix: string) -> bool
1242
+ *
1243
+ * Returns true if the string ends with the suffix.
1244
+ * Null-tolerant: returns false if either argument is null.
1245
+ */
1246
+ const ends_with = (args) => {
1247
+ assertArgCount$1(args, 2, "ends_with");
1248
+ const s = getArg$1(args, 0, "ends_with");
1249
+ const suffix = getArg$1(args, 1, "ends_with");
1250
+ // Null-tolerant: return false if either arg is null
1251
+ if (!assertStringOrNull$1(s, "s", "ends_with"))
1252
+ return false;
1253
+ if (!assertStringOrNull$1(suffix, "suffix", "ends_with"))
1254
+ return false;
1255
+ return s.endsWith(suffix);
1256
+ };
1257
+ /**
1258
+ * contains(s: string, substring: string) -> bool
1259
+ *
1260
+ * Returns true if the string contains the substring.
1261
+ * Null-tolerant: returns false if either argument is null.
1262
+ */
1263
+ const contains = (args) => {
1264
+ assertArgCount$1(args, 2, "contains");
1265
+ const s = getArg$1(args, 0, "contains");
1266
+ const substring = getArg$1(args, 1, "contains");
1267
+ // Null-tolerant: return false if either arg is null
1268
+ if (!assertStringOrNull$1(s, "s", "contains"))
1269
+ return false;
1270
+ if (!assertStringOrNull$1(substring, "substring", "contains"))
1271
+ return false;
1272
+ return s.includes(substring);
1273
+ };
1274
+ /**
1275
+ * split(s: string, separator: string) -> string[]
1276
+ *
1277
+ * Splits the string by the separator.
1278
+ */
1279
+ const split = (args) => {
1280
+ assertArgCountRange(args, 1, 2, "split");
1281
+ const s = getArg$1(args, 0, "split");
1282
+ assertString$1(s, "s", "split");
1283
+ const separator = args.length >= 2 ? getArg$1(args, 1, "split") : " ";
1284
+ assertString$1(separator, "separator", "split");
1285
+ return s.split(separator);
1286
+ };
1287
+ // ============================================================
1288
+ // Collection Helpers
1289
+ // ============================================================
1290
+ /**
1291
+ * len(x: string | array) -> number
1292
+ *
1293
+ * Returns the length of a string or array.
1294
+ */
1295
+ const len = (args) => {
1296
+ assertArgCount$1(args, 1, "len");
1297
+ const x = getArg$1(args, 0, "len");
1298
+ if (typeof x === "string") {
1299
+ return x.length;
1300
+ }
1301
+ if (Array.isArray(x)) {
1302
+ return x.length;
1303
+ }
1304
+ throw new BuiltinError("len", `expected string or array, got ${getTypeName(x)}`);
1305
+ };
1306
+ // ============================================================
1307
+ // Generic Helpers
1308
+ // ============================================================
1309
+ /**
1310
+ * exists(x: any) -> bool
1311
+ *
1312
+ * Returns true if the value is not null.
1313
+ * Missing bindings and missing properties evaluate to null, so this
1314
+ * can be used to check for presence.
1315
+ */
1316
+ const exists = (args) => {
1317
+ assertArgCount$1(args, 1, "exists");
1318
+ const x = getArg$1(args, 0, "exists");
1319
+ return x !== null;
1320
+ };
1321
+ /**
1322
+ * coalesce(a: any, b: any) -> any
1323
+ *
1324
+ * Returns `a` if it is not null, otherwise returns `b`.
1325
+ * This is useful for providing default values.
1326
+ */
1327
+ const coalesce = (args) => {
1328
+ assertArgCount$1(args, 2, "coalesce");
1329
+ const a = getArg$1(args, 0, "coalesce");
1330
+ const b = getArg$1(args, 1, "coalesce");
1331
+ return a !== null ? a : b;
1332
+ };
1333
+ /**
1334
+ * trim(s: string) -> string
1335
+ *
1336
+ * Trims whitespace from both ends of a string.
1337
+ * Returns an empty string if `s` is null (for convenient composition).
1338
+ * Throws BuiltinError if `s` is non-null but not a string.
1339
+ */
1340
+ const trim = (args) => {
1341
+ assertArgCount$1(args, 1, "trim");
1342
+ const s = getArg$1(args, 0, "trim");
1343
+ // Null-friendly: return empty string for null
1344
+ if (s === null) {
1345
+ return "";
1346
+ }
1347
+ // Strict type check for non-null values
1348
+ if (typeof s !== "string") {
1349
+ throw new BuiltinError("trim", `s must be a string, got ${getTypeName(s)}`);
1350
+ }
1351
+ return s.trim();
1352
+ };
1353
+ /**
1354
+ * secure_hash(input_str: string, length: number) -> string
1355
+ *
1356
+ * Generates a deterministic secure hash/fingerprint of the input string.
1357
+ * Uses SHA-256 hashing to create a stable identifier of the specified length.
1358
+ * Returns base62-encoded string (alphanumeric, case-sensitive).
1359
+ * Automatically rehashes if result contains blacklisted words.
1360
+ * Returns empty string if input_str is null (for convenient composition).
1361
+ * Throws BuiltinError if input_str is non-null but not a string, or if length is invalid.
1362
+ */
1363
+ const secure_hash = (args) => {
1364
+ assertArgCount$1(args, 2, "secure_hash");
1365
+ const input_str = getArg$1(args, 0, "secure_hash");
1366
+ const length = getArg$1(args, 1, "secure_hash");
1367
+ // Null-friendly: return empty string for null input
1368
+ if (input_str === null) {
1369
+ return "";
1370
+ }
1371
+ // Strict type check for input_str
1372
+ if (typeof input_str !== "string") {
1373
+ throw new BuiltinError("secure_hash", `input_str must be a string, got ${getTypeName(input_str)}`);
1374
+ }
1375
+ // Strict type check for length
1376
+ if (typeof length !== "number") {
1377
+ throw new BuiltinError("secure_hash", `length must be a number, got ${getTypeName(length)}`);
1378
+ }
1379
+ // Validate length is a positive integer
1380
+ if (!Number.isInteger(length) || length <= 0) {
1381
+ throw new BuiltinError("secure_hash", `length must be a positive integer, got ${length}`);
1382
+ }
1383
+ // Use generateFingerprintSync from @naylence/core
1384
+ // This provides SHA-256 hashing, base62 encoding, and profanity filtering
1385
+ return generateFingerprintSync(input_str, length, sha256);
1386
+ };
1387
+ // ============================================================
1388
+ // Pattern Helpers (BSL-only)
1389
+ // ============================================================
1390
+ /**
1391
+ * Escapes special regex characters in a string.
1392
+ */
1393
+ function escapeRegex(str) {
1394
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1395
+ }
1396
+ /**
1397
+ * Converts a glob pattern to a regex pattern.
1398
+ */
1399
+ function globToRegex(glob) {
1400
+ const parts = [];
1401
+ let i = 0;
1402
+ while (i < glob.length) {
1403
+ const ch = glob[i];
1404
+ if (ch === "*") {
1405
+ if (glob[i + 1] === "*") {
1406
+ // `**` matches any characters
1407
+ parts.push(".*");
1408
+ i += 2;
1409
+ }
1410
+ else {
1411
+ // `*` matches any characters except dots
1412
+ parts.push("[^.]*");
1413
+ i += 1;
1414
+ }
1415
+ }
1416
+ else if (ch === "?") {
1417
+ // `?` matches a single character
1418
+ parts.push("[^.]");
1419
+ i += 1;
1420
+ }
1421
+ else {
1422
+ parts.push(escapeRegex(ch));
1423
+ i += 1;
1424
+ }
1425
+ }
1426
+ return parts.join("");
1427
+ }
1428
+ /**
1429
+ * glob_match(value: string, pattern: string) -> bool
1430
+ *
1431
+ * Returns true if the value matches the glob pattern.
1432
+ * Glob syntax: * (single segment), ** (any depth), ? (single char)
1433
+ * Null-tolerant: returns false if either argument is null.
1434
+ */
1435
+ const glob_match = (args, context) => {
1436
+ assertArgCount$1(args, 2, "glob_match");
1437
+ const value = getArg$1(args, 0, "glob_match");
1438
+ const pattern = getArg$1(args, 1, "glob_match");
1439
+ // Null-tolerant: return false if either arg is null
1440
+ if (!assertStringOrNull$1(value, "value", "glob_match"))
1441
+ return false;
1442
+ if (!assertStringOrNull$1(pattern, "pattern", "glob_match"))
1443
+ return false;
1444
+ // Validate pattern length
1445
+ checkGlobPatternLength(pattern, context.limits);
1446
+ // Convert glob to regex
1447
+ const regexPattern = `^${globToRegex(pattern)}$`;
1448
+ try {
1449
+ const regex = new RegExp(regexPattern);
1450
+ return regex.test(value);
1451
+ }
1452
+ catch {
1453
+ throw new BuiltinError("glob_match", `invalid glob pattern: ${pattern}`);
1454
+ }
1455
+ };
1456
+ /**
1457
+ * Detects potentially catastrophic regex patterns.
1458
+ *
1459
+ * This is a best-effort heuristic check for common ReDoS patterns.
1460
+ */
1461
+ function isSafeRegex(pattern) {
1462
+ // Check for obvious catastrophic patterns:
1463
+ // - Nested quantifiers: (a+)+, (a*)*
1464
+ // - Overlapping alternation with quantifiers: (a|a)+
1465
+ // Simple heuristic: reject patterns with nested quantifiers
1466
+ const nestedQuantifiers = /([+*?]|\{\d+,?\d*\})\s*\)\s*([+*?]|\{\d+,?\d*\})/;
1467
+ if (nestedQuantifiers.test(pattern)) {
1468
+ return false;
1469
+ }
1470
+ // Reject patterns with excessive backtracking potential
1471
+ const excessiveBacktracking = /(\.\*){3,}|(\.\+){3,}/;
1472
+ if (excessiveBacktracking.test(pattern)) {
1473
+ return false;
1474
+ }
1475
+ return true;
1476
+ }
1477
+ /**
1478
+ * regex_match(value: string, pattern: string) -> bool
1479
+ *
1480
+ * Returns true if the value matches the regex pattern.
1481
+ * The pattern is anchored (full match).
1482
+ * Null-tolerant: returns false if either argument is null.
1483
+ */
1484
+ const regex_match = (args, context) => {
1485
+ assertArgCount$1(args, 2, "regex_match");
1486
+ const value = getArg$1(args, 0, "regex_match");
1487
+ const pattern = getArg$1(args, 1, "regex_match");
1488
+ // Null-tolerant: return false if either arg is null
1489
+ if (!assertStringOrNull$1(value, "value", "regex_match"))
1490
+ return false;
1491
+ if (!assertStringOrNull$1(pattern, "pattern", "regex_match"))
1492
+ return false;
1493
+ // Validate pattern length
1494
+ checkRegexPatternLength(pattern, context.limits);
1495
+ // Check for potentially unsafe patterns
1496
+ if (!isSafeRegex(pattern)) {
1497
+ throw new BuiltinError("regex_match", `pattern may cause excessive backtracking: ${pattern}`);
1498
+ }
1499
+ // Anchor the pattern for full match
1500
+ const anchoredPattern = pattern.startsWith("^")
1501
+ ? pattern
1502
+ : pattern.endsWith("$")
1503
+ ? pattern
1504
+ : `^(?:${pattern})$`;
1505
+ try {
1506
+ const regex = new RegExp(anchoredPattern);
1507
+ return regex.test(value);
1508
+ }
1509
+ catch (error) {
1510
+ throw new BuiltinError("regex_match", `invalid regex pattern: ${pattern} - ${error instanceof Error ? error.message : String(error)}`);
1511
+ }
1512
+ };
1513
+ // ============================================================
1514
+ // Registry
1515
+ // ============================================================
1516
+ /**
1517
+ * Registry of all built-in functions.
1518
+ */
1519
+ const BUILTIN_FUNCTIONS = new Map([
1520
+ // String helpers
1521
+ ["lower", lower],
1522
+ ["upper", upper],
1523
+ ["starts_with", starts_with],
1524
+ ["ends_with", ends_with],
1525
+ ["contains", contains],
1526
+ ["split", split],
1527
+ ["trim", trim],
1528
+ // Collection helpers
1529
+ ["len", len],
1530
+ // Generic helpers
1531
+ ["exists", exists],
1532
+ ["coalesce", coalesce],
1533
+ ["secure_hash", secure_hash],
1534
+ // Pattern helpers
1535
+ ["glob_match", glob_match],
1536
+ ["regex_match", regex_match],
1537
+ ]);
1538
+ /**
1539
+ * Calls a built-in function by name.
1540
+ *
1541
+ * @param name - The function name
1542
+ * @param args - The function arguments
1543
+ * @param context - The evaluation context
1544
+ * @returns The function result
1545
+ * @throws BuiltinError if the function doesn't exist or fails
1546
+ */
1547
+ function callBuiltin(name, args, context, functions = BUILTIN_FUNCTIONS) {
1548
+ const fn = functions.get(name);
1549
+ if (!fn) {
1550
+ throw new EvaluationError(`Unknown function: ${name}`, context.position, context.source);
1551
+ }
1552
+ return fn(args, context);
1553
+ }
1554
+ /**
1555
+ * Checks if a name is a built-in function.
1556
+ */
1557
+ function isBuiltinFunction(name, functions = BUILTIN_FUNCTIONS) {
1558
+ return functions.has(name);
1559
+ }
1560
+
1561
+ /**
1562
+ * Expression evaluator.
1563
+ *
1564
+ * Evaluates an AST against a set of variable bindings and returns a value.
1565
+ *
1566
+ * Null handling semantics:
1567
+ * - `undefined` values are normalized to `null` throughout evaluation.
1568
+ * - Missing identifiers evaluate to `null`.
1569
+ * - Member access on `null` or non-object returns `null`.
1570
+ * - Missing properties return `null` (including properties set to `undefined`).
1571
+ */
1572
+ /**
1573
+ * Evaluates an AST node and returns the result.
1574
+ */
1575
+ class Evaluator {
1576
+ constructor(context) {
1577
+ this.memberAccessDepth = 0;
1578
+ this.context = context;
1579
+ this.limits = context.limits ?? DEFAULT_EXPRESSION_LIMITS;
1580
+ this.source = context.source ?? "";
1581
+ this.functions = context.functions ?? BUILTIN_FUNCTIONS;
1582
+ }
1583
+ /**
1584
+ * Evaluates an AST node and returns the value.
1585
+ */
1586
+ evaluate(node) {
1587
+ switch (node.type) {
1588
+ case "StringLiteral":
1589
+ return node.value;
1590
+ case "NumberLiteral":
1591
+ return node.value;
1592
+ case "BooleanLiteral":
1593
+ return node.value;
1594
+ case "NullLiteral":
1595
+ return null;
1596
+ case "ArrayLiteral":
1597
+ return node.elements.map((e) => this.evaluate(e));
1598
+ case "Identifier":
1599
+ return this.evaluateIdentifier(node.name, node.position);
1600
+ case "MemberAccess":
1601
+ return this.evaluateMemberAccess(node);
1602
+ case "IndexAccess":
1603
+ return this.evaluateIndexAccess(node);
1604
+ case "FunctionCall":
1605
+ return this.evaluateFunctionCall(node);
1606
+ case "UnaryOp":
1607
+ return this.evaluateUnaryOp(node.operator, node.operand, node.position);
1608
+ case "BinaryOp":
1609
+ return this.evaluateBinaryOp(node.operator, node.left, node.right, node.position);
1610
+ case "TernaryOp":
1611
+ return this.evaluateTernaryOp(node.condition, node.consequent, node.alternate, node.position);
1612
+ }
1613
+ }
1614
+ /**
1615
+ * Evaluates as boolean with strict type checking.
1616
+ */
1617
+ evaluateAsBoolean(node) {
1618
+ const value = this.evaluate(node);
1619
+ if (typeof value !== "boolean") {
1620
+ throw new TypeError("boolean", getTypeName(value), node.position, this.source);
1621
+ }
1622
+ return value;
1623
+ }
1624
+ evaluateIdentifier(name, _position) {
1625
+ // Check if it's a top-level binding
1626
+ if (name in this.context.bindings) {
1627
+ // Normalize the value to ensure undefined becomes null
1628
+ return normalizeJsValue(this.context.bindings[name]);
1629
+ }
1630
+ // Unknown identifier evaluates to null (missing field)
1631
+ return null;
1632
+ }
1633
+ evaluateMemberAccess(node) {
1634
+ // Check member access depth
1635
+ this.memberAccessDepth++;
1636
+ if (this.memberAccessDepth > this.limits.maxMemberAccessDepth) {
1637
+ throw new EvaluationError(`Member access depth ${this.memberAccessDepth} exceeds limit of ${this.limits.maxMemberAccessDepth}`, node.position, this.source);
1638
+ }
1639
+ try {
1640
+ const obj = this.evaluate(node.object);
1641
+ // Null-safe member access: null.foo -> null
1642
+ if (obj === null) {
1643
+ return null;
1644
+ }
1645
+ // Must be an object (not primitive, not array)
1646
+ if (typeof obj !== "object" || Array.isArray(obj)) {
1647
+ // Type mismatch during access returns null (not error)
1648
+ return null;
1649
+ }
1650
+ const record = obj;
1651
+ if (node.property in record) {
1652
+ // Normalize the value to ensure undefined becomes null
1653
+ return normalizeJsValue(record[node.property]);
1654
+ }
1655
+ // Missing property evaluates to null
1656
+ return null;
1657
+ }
1658
+ finally {
1659
+ this.memberAccessDepth--;
1660
+ }
1661
+ }
1662
+ evaluateIndexAccess(node) {
1663
+ const obj = this.evaluate(node.object);
1664
+ const index = this.evaluate(node.index);
1665
+ // Null-safe index access: null[0] -> null
1666
+ if (obj === null) {
1667
+ return null;
1668
+ }
1669
+ // Array access with numeric index
1670
+ if (Array.isArray(obj)) {
1671
+ if (typeof index !== "number") {
1672
+ throw new TypeError("number", getTypeName(index), node.position, this.source);
1673
+ }
1674
+ const intIndex = Math.floor(index);
1675
+ if (intIndex < 0 || intIndex >= obj.length) {
1676
+ // Out of bounds evaluates to null
1677
+ return null;
1678
+ }
1679
+ // Normalize array element to ensure undefined becomes null
1680
+ return normalizeJsValue(obj[intIndex]);
1681
+ }
1682
+ // Object access with string key
1683
+ if (typeof obj === "object") {
1684
+ if (typeof index !== "string") {
1685
+ throw new TypeError("string", getTypeName(index), node.position, this.source);
1686
+ }
1687
+ const record = obj;
1688
+ if (index in record) {
1689
+ // Normalize the value to ensure undefined becomes null
1690
+ return normalizeJsValue(record[index]);
1691
+ }
1692
+ // Missing key evaluates to null
1693
+ return null;
1694
+ }
1695
+ // Type mismatch during access returns null
1696
+ return null;
1697
+ }
1698
+ evaluateFunctionCall(node) {
1699
+ // Evaluate arguments
1700
+ const args = node.args.map((arg) => this.evaluate(arg));
1701
+ const builtinContext = {
1702
+ limits: this.limits,
1703
+ position: node.position,
1704
+ source: this.source,
1705
+ };
1706
+ return callBuiltin(node.name, args, builtinContext, this.functions);
1707
+ }
1708
+ evaluateUnaryOp(operator, operand, position) {
1709
+ const value = this.evaluate(operand);
1710
+ switch (operator) {
1711
+ case "!":
1712
+ if (typeof value !== "boolean") {
1713
+ throw new TypeError("boolean", getTypeName(value), position, this.source);
1714
+ }
1715
+ return !value;
1716
+ case "-":
1717
+ if (typeof value !== "number") {
1718
+ throw new TypeError("number", getTypeName(value), position, this.source);
1719
+ }
1720
+ return -value;
1721
+ }
1722
+ }
1723
+ evaluateBinaryOp(operator, left, right, position) {
1724
+ // Short-circuit evaluation for logical operators
1725
+ if (operator === "&&") {
1726
+ const leftValue = this.evaluate(left);
1727
+ if (typeof leftValue !== "boolean") {
1728
+ throw new TypeError("boolean", getTypeName(leftValue), left.position, this.source);
1729
+ }
1730
+ if (!leftValue)
1731
+ return false;
1732
+ const rightValue = this.evaluate(right);
1733
+ if (typeof rightValue !== "boolean") {
1734
+ throw new TypeError("boolean", getTypeName(rightValue), right.position, this.source);
1735
+ }
1736
+ return rightValue;
1737
+ }
1738
+ if (operator === "||") {
1739
+ const leftValue = this.evaluate(left);
1740
+ if (typeof leftValue !== "boolean") {
1741
+ throw new TypeError("boolean", getTypeName(leftValue), left.position, this.source);
1742
+ }
1743
+ if (leftValue)
1744
+ return true;
1745
+ const rightValue = this.evaluate(right);
1746
+ if (typeof rightValue !== "boolean") {
1747
+ throw new TypeError("boolean", getTypeName(rightValue), right.position, this.source);
1748
+ }
1749
+ return rightValue;
1750
+ }
1751
+ // Eager evaluation for other operators
1752
+ const leftValue = this.evaluate(left);
1753
+ const rightValue = this.evaluate(right);
1754
+ switch (operator) {
1755
+ // Arithmetic
1756
+ case "+":
1757
+ if (typeof leftValue === "string" && typeof rightValue === "string") {
1758
+ return leftValue + rightValue;
1759
+ }
1760
+ if (typeof leftValue === "number" && typeof rightValue === "number") {
1761
+ return leftValue + rightValue;
1762
+ }
1763
+ throw new EvaluationError(`Cannot add ${getTypeName(leftValue)} and ${getTypeName(rightValue)}`, position, this.source);
1764
+ case "-":
1765
+ if (typeof leftValue !== "number" || typeof rightValue !== "number") {
1766
+ throw new EvaluationError(`Cannot subtract ${getTypeName(leftValue)} and ${getTypeName(rightValue)}`, position, this.source);
1767
+ }
1768
+ return leftValue - rightValue;
1769
+ case "*":
1770
+ if (typeof leftValue !== "number" || typeof rightValue !== "number") {
1771
+ throw new EvaluationError(`Cannot multiply ${getTypeName(leftValue)} and ${getTypeName(rightValue)}`, position, this.source);
1772
+ }
1773
+ return leftValue * rightValue;
1774
+ case "/":
1775
+ if (typeof leftValue !== "number" || typeof rightValue !== "number") {
1776
+ throw new EvaluationError(`Cannot divide ${getTypeName(leftValue)} and ${getTypeName(rightValue)}`, position, this.source);
1777
+ }
1778
+ if (rightValue === 0) {
1779
+ throw new EvaluationError("Division by zero", position, this.source);
1780
+ }
1781
+ return leftValue / rightValue;
1782
+ case "%":
1783
+ if (typeof leftValue !== "number" || typeof rightValue !== "number") {
1784
+ throw new EvaluationError(`Cannot compute modulo of ${getTypeName(leftValue)} and ${getTypeName(rightValue)}`, position, this.source);
1785
+ }
1786
+ if (rightValue === 0) {
1787
+ throw new EvaluationError("Modulo by zero", position, this.source);
1788
+ }
1789
+ return leftValue % rightValue;
1790
+ // Comparison
1791
+ case "<":
1792
+ case "<=":
1793
+ case ">":
1794
+ case ">=":
1795
+ return this.evaluateComparison(operator, leftValue, rightValue, position);
1796
+ // Equality
1797
+ case "==":
1798
+ return this.valuesEqual(leftValue, rightValue);
1799
+ case "!=":
1800
+ return !this.valuesEqual(leftValue, rightValue);
1801
+ // Membership
1802
+ case "in":
1803
+ return this.evaluateIn(leftValue, rightValue, position);
1804
+ case "not in":
1805
+ return !this.evaluateIn(leftValue, rightValue, position);
1806
+ }
1807
+ }
1808
+ evaluateComparison(operator, left, right, position) {
1809
+ // Numbers
1810
+ if (typeof left === "number" && typeof right === "number") {
1811
+ switch (operator) {
1812
+ case "<":
1813
+ return left < right;
1814
+ case "<=":
1815
+ return left <= right;
1816
+ case ">":
1817
+ return left > right;
1818
+ case ">=":
1819
+ return left >= right;
1820
+ }
1821
+ }
1822
+ // Strings
1823
+ if (typeof left === "string" && typeof right === "string") {
1824
+ switch (operator) {
1825
+ case "<":
1826
+ return left < right;
1827
+ case "<=":
1828
+ return left <= right;
1829
+ case ">":
1830
+ return left > right;
1831
+ case ">=":
1832
+ return left >= right;
1833
+ }
1834
+ }
1835
+ throw new EvaluationError(`Cannot compare ${getTypeName(left)} and ${getTypeName(right)} with ${operator}`, position, this.source);
1836
+ }
1837
+ evaluateIn(left, right, position) {
1838
+ // String in string (substring check)
1839
+ if (typeof left === "string" && typeof right === "string") {
1840
+ return right.includes(left);
1841
+ }
1842
+ // Value in array
1843
+ if (Array.isArray(right)) {
1844
+ return right.some((item) => this.valuesEqual(left, item));
1845
+ }
1846
+ // Key in object
1847
+ if (typeof right === "object" && right !== null && !Array.isArray(right)) {
1848
+ if (typeof left !== "string") {
1849
+ throw new EvaluationError(`Cannot check if ${getTypeName(left)} is a key in object (expected string)`, position, this.source);
1850
+ }
1851
+ return left in right;
1852
+ }
1853
+ throw new EvaluationError(`Cannot check membership: ${getTypeName(left)} in ${getTypeName(right)}`, position, this.source);
1854
+ }
1855
+ evaluateTernaryOp(condition, consequent, alternate, _position) {
1856
+ const condValue = this.evaluate(condition);
1857
+ if (typeof condValue !== "boolean") {
1858
+ throw new TypeError("boolean", getTypeName(condValue), condition.position, this.source);
1859
+ }
1860
+ return condValue ? this.evaluate(consequent) : this.evaluate(alternate);
1861
+ }
1862
+ /**
1863
+ * Deep equality check for expression values.
1864
+ */
1865
+ valuesEqual(a, b) {
1866
+ // Identical primitives or same reference
1867
+ if (a === b)
1868
+ return true;
1869
+ // Type mismatch
1870
+ if (typeof a !== typeof b)
1871
+ return false;
1872
+ // null check (both must be null if one is)
1873
+ if (a === null || b === null)
1874
+ return false;
1875
+ // Arrays
1876
+ if (Array.isArray(a) && Array.isArray(b)) {
1877
+ if (a.length !== b.length)
1878
+ return false;
1879
+ for (let i = 0; i < a.length; i++) {
1880
+ if (!this.valuesEqual(a[i], b[i])) {
1881
+ return false;
1882
+ }
1883
+ }
1884
+ return true;
1885
+ }
1886
+ // Objects
1887
+ if (typeof a === "object" && typeof b === "object") {
1888
+ const aKeys = Object.keys(a);
1889
+ const bKeys = Object.keys(b);
1890
+ if (aKeys.length !== bKeys.length)
1891
+ return false;
1892
+ for (const key of aKeys) {
1893
+ if (!Object.prototype.hasOwnProperty.call(b, key))
1894
+ return false;
1895
+ const aRecord = a;
1896
+ const bRecord = b;
1897
+ if (!this.valuesEqual(aRecord[key], bRecord[key])) {
1898
+ return false;
1899
+ }
1900
+ }
1901
+ return true;
1902
+ }
1903
+ return false;
1904
+ }
1905
+ }
1906
+ /**
1907
+ * Evaluates an AST against a context and returns the result.
1908
+ *
1909
+ * @param ast - The AST to evaluate
1910
+ * @param context - The evaluation context with bindings
1911
+ * @returns The evaluation result
1912
+ */
1913
+ function evaluate(ast, context) {
1914
+ try {
1915
+ const evaluator = new Evaluator(context);
1916
+ const value = evaluator.evaluate(ast);
1917
+ return { value, success: true };
1918
+ }
1919
+ catch (error) {
1920
+ const message = error instanceof Error ? error.message : String(error);
1921
+ return { value: null, success: false, error: message };
1922
+ }
1923
+ }
1924
+ /**
1925
+ * Evaluates an AST as a boolean condition.
1926
+ *
1927
+ * @param ast - The AST to evaluate
1928
+ * @param context - The evaluation context with bindings
1929
+ * @returns true if the condition is met, false otherwise (including errors)
1930
+ */
1931
+ function evaluateAsBoolean(ast, context) {
1932
+ try {
1933
+ const evaluator = new Evaluator(context);
1934
+ const value = evaluator.evaluateAsBoolean(ast);
1935
+ return { value };
1936
+ }
1937
+ catch (error) {
1938
+ const message = error instanceof Error ? error.message : String(error);
1939
+ return { value: false, error: message };
1940
+ }
1941
+ }
1942
+
1943
+ /**
1944
+ * Authorization-specific expression built-ins.
1945
+ *
1946
+ * Null handling semantics:
1947
+ * - Scope predicate builtins (has_scope, has_any_scope, has_all_scopes)
1948
+ * return `false` when passed `null` for required args.
1949
+ * - Wrong non-null types still raise BuiltinError to surface real bugs.
1950
+ */
1951
+ /**
1952
+ * Checks if a value is null.
1953
+ */
1954
+ function isNull(value) {
1955
+ return value === null;
1956
+ }
1957
+ /**
1958
+ * Creates a function registry with auth helpers installed.
1959
+ */
1960
+ function createAuthFunctionRegistry(grantedScopes = []) {
1961
+ const scopes = grantedScopes ?? [];
1962
+ /**
1963
+ * Checks if any granted scope matches a pattern (using glob syntax).
1964
+ */
1965
+ const matchesScope = (scope) => {
1966
+ // Exact match for now; safe and deterministic.
1967
+ return scopes.includes(scope);
1968
+ };
1969
+ /**
1970
+ * has_scope(scope: string) -> bool
1971
+ *
1972
+ * Returns true if the scope is in the granted scopes.
1973
+ * Null-tolerant: returns false if scope is null.
1974
+ */
1975
+ const has_scope = (args) => {
1976
+ assertArgCount(args, 1, "has_scope");
1977
+ const scope = getArg(args, 0, "has_scope");
1978
+ // Null-tolerant: return false if scope is null
1979
+ if (!assertStringOrNull(scope, "scope", "has_scope"))
1980
+ return false;
1981
+ return matchesScope(scope);
1982
+ };
1983
+ /**
1984
+ * has_any_scope(scopes: string[]) -> bool
1985
+ *
1986
+ * Returns true if any scope in the array is in the granted scopes.
1987
+ * Null-tolerant: returns false if scopes is null.
1988
+ */
1989
+ const has_any_scope = (args) => {
1990
+ assertArgCount(args, 1, "has_any_scope");
1991
+ const values = getArg(args, 0, "has_any_scope");
1992
+ // Null-tolerant: return false if scopes is null
1993
+ if (!assertStringArrayOrNull(values, "scopes", "has_any_scope"))
1994
+ return false;
1995
+ if (values.length === 0) {
1996
+ return false;
1997
+ }
1998
+ return values.some((scope) => matchesScope(scope));
1999
+ };
2000
+ /**
2001
+ * has_all_scopes(scopes: string[]) -> bool
2002
+ *
2003
+ * Returns true if all scopes in the array are in the granted scopes.
2004
+ * Null-tolerant: returns false if scopes is null.
2005
+ */
2006
+ const has_all_scopes = (args) => {
2007
+ assertArgCount(args, 1, "has_all_scopes");
2008
+ const values = getArg(args, 0, "has_all_scopes");
2009
+ // Null-tolerant: return false if scopes is null
2010
+ if (!assertStringArrayOrNull(values, "scopes", "has_all_scopes"))
2011
+ return false;
2012
+ if (values.length === 0) {
2013
+ return true;
2014
+ }
2015
+ return values.every((scope) => matchesScope(scope));
2016
+ };
2017
+ return new Map([
2018
+ ...BUILTIN_FUNCTIONS,
2019
+ ["has_scope", has_scope],
2020
+ ["has_any_scope", has_any_scope],
2021
+ ["has_all_scopes", has_all_scopes],
2022
+ ]);
2023
+ }
2024
+ /**
2025
+ * Asserts that a non-null value is a string (for null-tolerant predicates).
2026
+ * Returns false if the value is null (indicating predicate should return false).
2027
+ * Throws BuiltinError if the value is non-null but not a string.
2028
+ */
2029
+ function assertStringOrNull(value, argName, functionName) {
2030
+ if (isNull(value)) {
2031
+ return false;
2032
+ }
2033
+ if (typeof value !== "string") {
2034
+ throw new BuiltinError(functionName, `${argName} must be a string, got ${getTypeName(value)}`);
2035
+ }
2036
+ return true;
2037
+ }
2038
+ /**
2039
+ * Asserts that a non-null value is an array of strings (for null-tolerant predicates).
2040
+ * Returns false if the value is null (indicating predicate should return false).
2041
+ * Throws BuiltinError if the value is non-null but not a string array.
2042
+ */
2043
+ function assertStringArrayOrNull(value, argName, functionName) {
2044
+ if (isNull(value)) {
2045
+ return false;
2046
+ }
2047
+ if (!Array.isArray(value)) {
2048
+ throw new BuiltinError(functionName, `${argName} must be an array of strings, got ${getTypeName(value)}`);
2049
+ }
2050
+ for (let i = 0; i < value.length; i++) {
2051
+ if (typeof value[i] !== "string") {
2052
+ throw new BuiltinError(functionName, `${argName}[${i}] must be a string, got ${getTypeName(value[i])}`);
2053
+ }
2054
+ }
2055
+ return true;
2056
+ }
2057
+ function getArg(args, index, functionName) {
2058
+ const value = args[index];
2059
+ if (value === undefined) {
2060
+ throw new BuiltinError(functionName, `missing argument at index ${index}`);
2061
+ }
2062
+ return value;
2063
+ }
2064
+ function assertArgCount(args, expected, functionName) {
2065
+ if (args.length !== expected) {
2066
+ throw new BuiltinError(functionName, `expected ${expected} argument(s), got ${args.length}`);
2067
+ }
2068
+ }
2069
+
2070
+ /**
2071
+ * Expression-based authorization policy implementation.
2072
+ *
2073
+ * Extends the basic policy with support for `when` expression evaluation.
2074
+ * This is part of the BSL-licensed Advanced Security package.
2075
+ */
2076
+ /**
2077
+ * Simple console logger implementation.
2078
+ */
2079
+ const defaultLogger = {
2080
+ debug: () => { },
2081
+ warning: (event, data) => {
2082
+ console.warn(`[naylence.security.auth.policy.expression] ${event}`, data);
2083
+ },
2084
+ };
2085
+ /**
2086
+ * Extracts the target address string from the envelope.
2087
+ */
2088
+ function extractAddress(envelope) {
2089
+ const to = envelope.to;
2090
+ if (!to) {
2091
+ return undefined;
2092
+ }
2093
+ if (typeof to === "string") {
2094
+ return to;
2095
+ }
2096
+ if (typeof to === "object" && "toString" in to) {
2097
+ return to.toString();
2098
+ }
2099
+ return undefined;
2100
+ }
2101
+ /**
2102
+ * Extracts granted scopes from the authorization context.
2103
+ */
2104
+ function extractGrantedScopes(context) {
2105
+ const authContext = context?.security?.authorization;
2106
+ if (!authContext) {
2107
+ return [];
2108
+ }
2109
+ if (Array.isArray(authContext.grantedScopes)) {
2110
+ return authContext.grantedScopes;
2111
+ }
2112
+ const claims = authContext.claims;
2113
+ if (claims) {
2114
+ const scopeClaim = claims.scope ?? claims.scopes ?? claims.scp;
2115
+ if (typeof scopeClaim === "string") {
2116
+ return scopeClaim.split(/\s+/).filter((s) => s.length > 0);
2117
+ }
2118
+ if (Array.isArray(scopeClaim)) {
2119
+ return scopeClaim.filter((s) => typeof s === "string");
2120
+ }
2121
+ }
2122
+ return [];
2123
+ }
2124
+ /**
2125
+ * Extracts claims from the authorization context.
2126
+ */
2127
+ function extractClaims(context) {
2128
+ const authContext = context?.security?.authorization;
2129
+ if (!authContext?.claims) {
2130
+ return {};
2131
+ }
2132
+ return authContext.claims;
2133
+ }
2134
+ /**
2135
+ * Creates a safe envelope subset for expression bindings.
2136
+ */
2137
+ function createEnvelopeBindings(envelope) {
2138
+ const frame = envelope.frame;
2139
+ const envelopeRecord = envelope;
2140
+ return {
2141
+ id: envelope.id ?? null,
2142
+ traceId: envelopeRecord.traceId ?? null,
2143
+ corrId: envelopeRecord.corrId ?? null,
2144
+ flowId: envelopeRecord.flowId ?? null,
2145
+ to: extractAddress(envelope) ?? null,
2146
+ frame: frame
2147
+ ? { type: frame.type ?? null }
2148
+ : { type: null },
2149
+ };
2150
+ }
2151
+ /**
2152
+ * Creates delivery context bindings for expression evaluation.
2153
+ */
2154
+ function createDeliveryBindings(context, action) {
2155
+ return {
2156
+ origin_type: context?.originType ?? null,
2157
+ routing_action: action,
2158
+ };
2159
+ }
2160
+ /**
2161
+ * Expression-based authorization policy that evaluates rules with `when` expressions.
2162
+ *
2163
+ * Features:
2164
+ * - All features of BasicAuthorizationPolicy
2165
+ * - Expression evaluation for `when` clauses
2166
+ * - Deterministic, side-effect-free evaluation
2167
+ * - Missing fields evaluate to null (not error)
2168
+ * - Parse/evaluation errors cause rule to not match
2169
+ */
2170
+ class AdvancedAuthorizationPolicy {
2171
+ constructor(options) {
2172
+ const { policyDefinition, warnOnUnknownFields = true, expressionLimits = DEFAULT_EXPRESSION_LIMITS, logger = defaultLogger, } = options;
2173
+ this.expressionLimits = expressionLimits;
2174
+ this.logger = logger;
2175
+ // Validate and extract default effect
2176
+ this.defaultEffect = this.validateDefaultEffect(policyDefinition.default_effect);
2177
+ // Warn about unknown policy fields
2178
+ if (warnOnUnknownFields) {
2179
+ this.warnUnknownPolicyFields(policyDefinition);
2180
+ }
2181
+ // Compile rules for efficient evaluation
2182
+ this.compiledRules = this.compileRules(policyDefinition.rules, warnOnUnknownFields);
2183
+ this.logger.debug("expression_policy_compiled", {
2184
+ defaultEffect: this.defaultEffect,
2185
+ ruleCount: this.compiledRules.length,
2186
+ rulesWithWhen: this.compiledRules.filter((r) => r.whenAst).length,
2187
+ });
2188
+ }
2189
+ /**
2190
+ * Evaluates the policy against a request.
2191
+ */
2192
+ async evaluateRequest(_node, envelope, context, action) {
2193
+ const resolvedAction = action ?? "*";
2194
+ const resolvedActionNormalized = this.normalizeActionToken(resolvedAction) ?? resolvedAction;
2195
+ const address = extractAddress(envelope);
2196
+ const grantedScopes = extractGrantedScopes(context);
2197
+ const rawFrameType = envelope.frame
2198
+ ?.type;
2199
+ const frameTypeNormalized = typeof rawFrameType === "string" && rawFrameType.trim().length > 0
2200
+ ? rawFrameType.trim().toLowerCase()
2201
+ : "";
2202
+ const rawOriginType = context?.originType;
2203
+ const originTypeNormalized = typeof rawOriginType === "string"
2204
+ ? this.normalizeOriginTypeToken(rawOriginType) ?? undefined
2205
+ : undefined;
2206
+ // Prepare expression bindings (lazy)
2207
+ let expressionBindings = null;
2208
+ let functionRegistry = null;
2209
+ const evaluationTrace = [];
2210
+ // Evaluate rules in order (first match wins)
2211
+ for (const rule of this.compiledRules) {
2212
+ const step = {
2213
+ ruleId: rule.id,
2214
+ result: false,
2215
+ };
2216
+ // Check frame type match
2217
+ if (rule.frameTypes) {
2218
+ if (!frameTypeNormalized) {
2219
+ step.expression = "frame_type: missing";
2220
+ step.result = false;
2221
+ evaluationTrace.push(step);
2222
+ continue;
2223
+ }
2224
+ if (!rule.frameTypes.has(frameTypeNormalized)) {
2225
+ step.expression = `frame_type: ${rawFrameType ?? "unknown"} not in rule set`;
2226
+ step.result = false;
2227
+ evaluationTrace.push(step);
2228
+ continue;
2229
+ }
2230
+ }
2231
+ // Check origin type match
2232
+ if (rule.originTypes) {
2233
+ if (originTypeNormalized === undefined) {
2234
+ step.expression = "origin_type: missing (rule requires origin)";
2235
+ step.result = false;
2236
+ evaluationTrace.push(step);
2237
+ continue;
2238
+ }
2239
+ if (!rule.originTypes.has(originTypeNormalized)) {
2240
+ step.expression = `origin_type: ${rawOriginType ?? "unknown"} not in [${Array.from(rule.originTypes).join(", ")}]`;
2241
+ step.result = false;
2242
+ evaluationTrace.push(step);
2243
+ continue;
2244
+ }
2245
+ }
2246
+ // Check action match
2247
+ if (!rule.actions.has("*") && !rule.actions.has(resolvedActionNormalized)) {
2248
+ step.expression = `action: ${resolvedActionNormalized} not in [${Array.from(rule.actions).join(", ")}]`;
2249
+ step.result = false;
2250
+ evaluationTrace.push(step);
2251
+ continue;
2252
+ }
2253
+ // Check address match
2254
+ if (rule.addressPatterns) {
2255
+ if (!address) {
2256
+ step.expression = "address: pattern requires address, but none provided";
2257
+ step.result = false;
2258
+ evaluationTrace.push(step);
2259
+ continue;
2260
+ }
2261
+ const matched = rule.addressPatterns.some((p) => p.match(address));
2262
+ if (!matched) {
2263
+ const patterns = rule.addressPatterns.map((p) => p.source).join(", ");
2264
+ step.expression = `address: none of [${patterns}] matched ${address}`;
2265
+ step.result = false;
2266
+ evaluationTrace.push(step);
2267
+ continue;
2268
+ }
2269
+ }
2270
+ // Check scope match
2271
+ if (rule.scopeMatcher) {
2272
+ if (!rule.scopeMatcher(grantedScopes)) {
2273
+ step.expression = "scope: requirement not satisfied";
2274
+ step.boundValues = { grantedScopes: [...grantedScopes] };
2275
+ step.result = false;
2276
+ evaluationTrace.push(step);
2277
+ continue;
2278
+ }
2279
+ }
2280
+ // Check when expression
2281
+ if (rule.whenParseError) {
2282
+ // Parse error - rule does not match
2283
+ step.expression = `when: parse error - ${rule.whenParseError}`;
2284
+ step.result = false;
2285
+ evaluationTrace.push(step);
2286
+ continue;
2287
+ }
2288
+ if (rule.whenAst) {
2289
+ // Lazy initialization of expression bindings
2290
+ if (!expressionBindings) {
2291
+ expressionBindings = {
2292
+ claims: extractClaims(context),
2293
+ envelope: createEnvelopeBindings(envelope),
2294
+ delivery: createDeliveryBindings(context, resolvedAction),
2295
+ time: {
2296
+ now_ms: Date.now(),
2297
+ now_iso: new Date().toISOString(),
2298
+ },
2299
+ };
2300
+ }
2301
+ const functions = functionRegistry ?? createAuthFunctionRegistry(grantedScopes);
2302
+ functionRegistry = functions;
2303
+ const evalContext = {
2304
+ bindings: expressionBindings,
2305
+ limits: this.expressionLimits,
2306
+ source: rule.whenSource,
2307
+ functions,
2308
+ };
2309
+ const whenResult = evaluateAsBoolean(rule.whenAst, evalContext);
2310
+ if (whenResult.error) {
2311
+ // Evaluation error - rule does not match
2312
+ step.expression = `when: evaluation error - ${whenResult.error}`;
2313
+ step.result = false;
2314
+ evaluationTrace.push(step);
2315
+ continue;
2316
+ }
2317
+ if (!whenResult.value) {
2318
+ // Expression evaluated to false
2319
+ step.expression = `when: expression evaluated to false`;
2320
+ step.boundValues = {
2321
+ whenExpression: rule.whenSource,
2322
+ };
2323
+ step.result = false;
2324
+ evaluationTrace.push(step);
2325
+ continue;
2326
+ }
2327
+ // Expression evaluated to true
2328
+ step.expression = `when: expression evaluated to true`;
2329
+ }
2330
+ // Rule matched
2331
+ step.result = true;
2332
+ if (!step.expression) {
2333
+ step.expression = "all conditions matched";
2334
+ }
2335
+ step.boundValues = {
2336
+ action: resolvedAction,
2337
+ address,
2338
+ grantedScopes: [...grantedScopes],
2339
+ ...(rule.whenSource ? { whenExpression: rule.whenSource } : {}),
2340
+ };
2341
+ evaluationTrace.push(step);
2342
+ this.logger.debug("rule_matched", {
2343
+ ruleId: rule.id,
2344
+ effect: rule.effect,
2345
+ action: resolvedAction,
2346
+ address,
2347
+ hadWhenClause: Boolean(rule.whenAst),
2348
+ });
2349
+ return {
2350
+ effect: rule.effect,
2351
+ reason: rule.description ?? `Matched rule: ${rule.id}`,
2352
+ matchedRule: rule.id,
2353
+ evaluationTrace,
2354
+ };
2355
+ }
2356
+ // No rule matched, apply default effect
2357
+ this.logger.debug("no_rule_matched", {
2358
+ defaultEffect: this.defaultEffect,
2359
+ action: resolvedAction,
2360
+ address,
2361
+ });
2362
+ return {
2363
+ effect: this.defaultEffect,
2364
+ reason: `No rule matched, applying default effect: ${this.defaultEffect}`,
2365
+ evaluationTrace,
2366
+ };
2367
+ }
2368
+ validateDefaultEffect(effect) {
2369
+ if (effect === undefined || effect === null) {
2370
+ return "deny";
2371
+ }
2372
+ if (effect !== "allow" && effect !== "deny") {
2373
+ throw new Error(`Invalid default_effect: "${String(effect)}". Must be "allow" or "deny"`);
2374
+ }
2375
+ return effect;
2376
+ }
2377
+ warnUnknownPolicyFields(definition) {
2378
+ for (const key of Object.keys(definition)) {
2379
+ if (!KNOWN_POLICY_FIELDS.has(key)) {
2380
+ this.logger.warning("unknown_policy_field", { field: key });
2381
+ }
2382
+ }
2383
+ }
2384
+ compileRules(rules, warnOnUnknown) {
2385
+ return rules.map((rule, index) => this.compileRule(rule, index, warnOnUnknown));
2386
+ }
2387
+ compileRule(rule, index, warnOnUnknown) {
2388
+ const id = rule.id ?? `rule_${index}`;
2389
+ // Validate effect
2390
+ if (!VALID_EFFECTS.includes(rule.effect)) {
2391
+ throw new Error(`Invalid effect in rule "${id}": "${String(rule.effect)}". Must be "allow" or "deny"`);
2392
+ }
2393
+ // Compile action(s)
2394
+ const actions = this.compileActions(rule.action, id);
2395
+ // Compile address patterns
2396
+ const addressPatterns = this.compileAddress(rule.address, id);
2397
+ // Compile frame type gating
2398
+ const frameTypes = this.compileFrameTypes(rule.frame_type, id);
2399
+ // Compile origin type gating
2400
+ const originTypes = this.compileOriginTypes(rule.origin_type, id);
2401
+ // Compile scope matcher
2402
+ let scopeMatcher;
2403
+ if (rule.scope !== undefined) {
2404
+ try {
2405
+ const compiled = compileGlobOnlyScopeRequirement(rule.scope, id);
2406
+ scopeMatcher = (scopes) => compiled.evaluate(scopes);
2407
+ }
2408
+ catch (error) {
2409
+ throw new Error(`Invalid scope requirement in rule "${id}": ${error instanceof Error ? error.message : String(error)}`);
2410
+ }
2411
+ }
2412
+ // Compile when expression
2413
+ let whenAst;
2414
+ let whenSource;
2415
+ let whenParseError;
2416
+ if (typeof rule.when === "string" && rule.when.trim().length > 0) {
2417
+ whenSource = rule.when.trim();
2418
+ try {
2419
+ whenAst = parse(whenSource, this.expressionLimits);
2420
+ }
2421
+ catch (error) {
2422
+ // Parse error - store for evaluation time
2423
+ whenParseError =
2424
+ error instanceof Error ? error.message : String(error);
2425
+ this.logger.warning("when_parse_error", {
2426
+ ruleId: id,
2427
+ expression: whenSource,
2428
+ error: whenParseError,
2429
+ });
2430
+ }
2431
+ }
2432
+ // Warn about unknown fields
2433
+ if (warnOnUnknown) {
2434
+ for (const key of Object.keys(rule)) {
2435
+ if (!KNOWN_RULE_FIELDS.has(key)) {
2436
+ this.logger.warning("unknown_rule_field", { ruleId: id, field: key });
2437
+ }
2438
+ }
2439
+ }
2440
+ return {
2441
+ id,
2442
+ description: rule.description,
2443
+ effect: rule.effect,
2444
+ actions,
2445
+ frameTypes,
2446
+ originTypes,
2447
+ addressPatterns,
2448
+ scopeMatcher,
2449
+ whenAst,
2450
+ whenSource,
2451
+ whenParseError,
2452
+ };
2453
+ }
2454
+ compileActions(action, ruleId) {
2455
+ if (action === undefined) {
2456
+ return new Set(["*"]);
2457
+ }
2458
+ if (typeof action === "string") {
2459
+ const normalized = this.normalizeActionToken(action);
2460
+ if (!normalized) {
2461
+ throw new Error(`Invalid action in rule "${ruleId}": "${action}". Must be one of: ${VALID_ACTIONS.join(", ")}`);
2462
+ }
2463
+ return new Set([normalized]);
2464
+ }
2465
+ if (!Array.isArray(action)) {
2466
+ throw new Error(`Invalid action in rule "${ruleId}": must be a string or array of strings`);
2467
+ }
2468
+ if (action.length === 0) {
2469
+ throw new Error(`Invalid action in rule "${ruleId}": array must not be empty`);
2470
+ }
2471
+ const actions = new Set();
2472
+ for (const a of action) {
2473
+ if (typeof a !== "string") {
2474
+ throw new Error(`Invalid action in rule "${ruleId}": all values must be strings`);
2475
+ }
2476
+ const normalized = this.normalizeActionToken(a);
2477
+ if (!normalized) {
2478
+ throw new Error(`Invalid action in rule "${ruleId}": "${a}". Must be one of: ${VALID_ACTIONS.join(", ")}`);
2479
+ }
2480
+ actions.add(normalized);
2481
+ }
2482
+ return actions;
2483
+ }
2484
+ compileAddress(address, ruleId) {
2485
+ if (address === undefined) {
2486
+ return undefined;
2487
+ }
2488
+ const context = `address in rule "${ruleId}"`;
2489
+ if (typeof address === "string") {
2490
+ const trimmed = address.trim();
2491
+ if (!trimmed) {
2492
+ throw new Error(`Invalid address in rule "${ruleId}": value must not be empty`);
2493
+ }
2494
+ try {
2495
+ return [compileGlobPattern(trimmed, context)];
2496
+ }
2497
+ catch (error) {
2498
+ throw new Error(`Invalid address in rule "${ruleId}": ${error instanceof Error ? error.message : String(error)}`);
2499
+ }
2500
+ }
2501
+ if (!Array.isArray(address)) {
2502
+ throw new Error(`Invalid address in rule "${ruleId}": must be a string or array of strings`);
2503
+ }
2504
+ if (address.length === 0) {
2505
+ throw new Error(`Invalid address in rule "${ruleId}": array must not be empty`);
2506
+ }
2507
+ const patterns = [];
2508
+ for (const addr of address) {
2509
+ if (typeof addr !== "string") {
2510
+ throw new Error(`Invalid address in rule "${ruleId}": all values must be strings`);
2511
+ }
2512
+ const trimmed = addr.trim();
2513
+ if (!trimmed) {
2514
+ throw new Error(`Invalid address in rule "${ruleId}": values must not be empty`);
2515
+ }
2516
+ try {
2517
+ patterns.push(compileGlobPattern(trimmed, context));
2518
+ }
2519
+ catch (error) {
2520
+ throw new Error(`Invalid address in rule "${ruleId}": ${error instanceof Error ? error.message : String(error)}`);
2521
+ }
2522
+ }
2523
+ return patterns;
2524
+ }
2525
+ compileFrameTypes(frameType, ruleId) {
2526
+ if (frameType === undefined) {
2527
+ return undefined;
2528
+ }
2529
+ if (typeof frameType === "string") {
2530
+ const normalized = frameType.trim().toLowerCase();
2531
+ if (!normalized) {
2532
+ throw new Error(`Invalid frame_type in rule "${ruleId}": value must not be empty`);
2533
+ }
2534
+ return new Set([normalized]);
2535
+ }
2536
+ if (!Array.isArray(frameType)) {
2537
+ throw new Error(`Invalid frame_type in rule "${ruleId}": must be a string or array of strings`);
2538
+ }
2539
+ if (frameType.length === 0) {
2540
+ throw new Error(`Invalid frame_type in rule "${ruleId}": array must not be empty`);
2541
+ }
2542
+ const frameTypes = new Set();
2543
+ for (const ft of frameType) {
2544
+ if (typeof ft !== "string") {
2545
+ throw new Error(`Invalid frame_type in rule "${ruleId}": all values must be strings`);
2546
+ }
2547
+ const normalized = ft.trim().toLowerCase();
2548
+ if (!normalized) {
2549
+ throw new Error(`Invalid frame_type in rule "${ruleId}": values must not be empty`);
2550
+ }
2551
+ frameTypes.add(normalized);
2552
+ }
2553
+ return frameTypes;
2554
+ }
2555
+ compileOriginTypes(originType, ruleId) {
2556
+ if (originType === undefined) {
2557
+ return undefined;
2558
+ }
2559
+ if (typeof originType === "string") {
2560
+ const trimmed = originType.trim();
2561
+ if (!trimmed) {
2562
+ throw new Error(`Invalid origin_type in rule "${ruleId}": value must not be empty`);
2563
+ }
2564
+ const normalized = this.normalizeOriginTypeToken(trimmed);
2565
+ if (!normalized) {
2566
+ throw new Error(`Invalid origin_type in rule "${ruleId}": "${originType}". Must be one of: ${VALID_ORIGIN_TYPES.join(", ")}`);
2567
+ }
2568
+ return new Set([normalized]);
2569
+ }
2570
+ if (!Array.isArray(originType)) {
2571
+ throw new Error(`Invalid origin_type in rule "${ruleId}": must be a string or array of strings`);
2572
+ }
2573
+ if (originType.length === 0) {
2574
+ throw new Error(`Invalid origin_type in rule "${ruleId}": array must not be empty`);
2575
+ }
2576
+ const originTypes = new Set();
2577
+ for (const ot of originType) {
2578
+ if (typeof ot !== "string") {
2579
+ throw new Error(`Invalid origin_type in rule "${ruleId}": all values must be strings`);
2580
+ }
2581
+ const trimmed = ot.trim();
2582
+ if (!trimmed) {
2583
+ throw new Error(`Invalid origin_type in rule "${ruleId}": values must not be empty`);
2584
+ }
2585
+ const normalized = this.normalizeOriginTypeToken(trimmed);
2586
+ if (!normalized) {
2587
+ throw new Error(`Invalid origin_type in rule "${ruleId}": "${ot}". Must be one of: ${VALID_ORIGIN_TYPES.join(", ")}`);
2588
+ }
2589
+ originTypes.add(normalized);
2590
+ }
2591
+ return originTypes;
2592
+ }
2593
+ normalizeActionToken(value) {
2594
+ const trimmed = value.trim();
2595
+ if (!trimmed) {
2596
+ return null;
2597
+ }
2598
+ if (trimmed === "*") {
2599
+ return "*";
2600
+ }
2601
+ const normalized = trimmed.replace(/[\s_-]+/g, "").toLowerCase();
2602
+ const map = {
2603
+ connect: "Connect",
2604
+ forwardupstream: "ForwardUpstream",
2605
+ forwarddownstream: "ForwardDownstream",
2606
+ forwardpeer: "ForwardPeer",
2607
+ deliverlocal: "DeliverLocal",
2608
+ };
2609
+ return map[normalized] ?? null;
2610
+ }
2611
+ normalizeOriginTypeToken(value) {
2612
+ const trimmed = value.trim();
2613
+ if (!trimmed) {
2614
+ return null;
2615
+ }
2616
+ const normalized = trimmed.replace(/[\s_-]+/g, "").toLowerCase();
2617
+ const map = {
2618
+ downstream: "downstream",
2619
+ upstream: "upstream",
2620
+ peer: "peer",
2621
+ local: "local",
2622
+ };
2623
+ return map[normalized] ?? null;
2624
+ }
2625
+ }
2626
+
2627
+ var advancedAuthorizationPolicy = /*#__PURE__*/Object.freeze({
2628
+ __proto__: null,
2629
+ AdvancedAuthorizationPolicy: AdvancedAuthorizationPolicy
2630
+ });
2631
+
2632
+ /**
2633
+ * Factory for creating AdvancedAuthorizationPolicy instances.
2634
+ */
2635
+ let modulePromise = null;
2636
+ function getModule() {
2637
+ if (!modulePromise) {
2638
+ modulePromise = Promise.resolve().then(function () { return advancedAuthorizationPolicy; });
2639
+ }
2640
+ return modulePromise;
2641
+ }
2642
+ function normalizeConfig$5(config) {
2643
+ if (!config) {
2644
+ throw new Error("AdvancedAuthorizationPolicyFactory requires a configuration with a policyDefinition");
2645
+ }
2646
+ const candidate = config;
2647
+ // Support both camelCase and snake_case for policyDefinition
2648
+ const policyDefinition = (candidate.policyDefinition ??
2649
+ candidate.policy_definition);
2650
+ if (!policyDefinition || typeof policyDefinition !== "object") {
2651
+ throw new Error("AdvancedAuthorizationPolicyConfig requires a policyDefinition object");
2652
+ }
2653
+ // Support both camelCase and snake_case for warnOnUnknownFields
2654
+ const warnOnUnknownFields = candidate.warnOnUnknownFields ?? candidate.warn_on_unknown_fields;
2655
+ if (warnOnUnknownFields !== undefined &&
2656
+ typeof warnOnUnknownFields !== "boolean") {
2657
+ throw new Error("warnOnUnknownFields must be a boolean");
2658
+ }
2659
+ // Support both camelCase and snake_case for expressionLimits
2660
+ const expressionLimits = (candidate.expressionLimits ??
2661
+ candidate.expression_limits);
2662
+ return {
2663
+ policyDefinition,
2664
+ warnOnUnknownFields: warnOnUnknownFields ?? true,
2665
+ expressionLimits,
2666
+ };
2667
+ }
2668
+ /**
2669
+ * Factory metadata for registration.
2670
+ */
2671
+ const FACTORY_META$e = {
2672
+ base: AUTHORIZATION_POLICY_FACTORY_BASE_TYPE,
2673
+ key: "AdvancedAuthorizationPolicy",
2674
+ };
2675
+ /**
2676
+ * Factory for creating AdvancedAuthorizationPolicy instances.
2677
+ */
2678
+ class AdvancedAuthorizationPolicyFactory extends AuthorizationPolicyFactory {
2679
+ constructor() {
2680
+ super(...arguments);
2681
+ this.type = "AdvancedAuthorizationPolicy";
2682
+ }
2683
+ /**
2684
+ * Creates an AdvancedAuthorizationPolicy from the given configuration.
2685
+ *
2686
+ * @param config - Configuration with policyDefinition
2687
+ * @returns The created authorization policy
2688
+ */
2689
+ async create(config) {
2690
+ const normalized = normalizeConfig$5(config);
2691
+ const { AdvancedAuthorizationPolicy } = await getModule();
2692
+ return new AdvancedAuthorizationPolicy({
2693
+ policyDefinition: normalized.policyDefinition,
2694
+ warnOnUnknownFields: normalized.warnOnUnknownFields,
2695
+ expressionLimits: normalized.expressionLimits,
2696
+ });
2697
+ }
2698
+ }
2699
+
2700
+ var advancedAuthorizationPolicyFactory = /*#__PURE__*/Object.freeze({
2701
+ __proto__: null,
2702
+ AdvancedAuthorizationPolicyFactory: AdvancedAuthorizationPolicyFactory,
2703
+ FACTORY_META: FACTORY_META$e,
2704
+ default: AdvancedAuthorizationPolicyFactory
2705
+ });
24
2706
 
25
2707
  const logger$h = getLogger("naylence.fame.security.cert.util");
26
2708
  const CACHE_LIMIT = 512;
@@ -474,9 +3156,9 @@ function toHex(data) {
474
3156
  .join("");
475
3157
  }
476
3158
  function buildCacheKey(chainBytes, trustStorePem, enforceNameConstraints) {
477
- const chainHash = toHex(sha256(chainBytes));
3159
+ const chainHash = toHex(sha256$1(chainBytes));
478
3160
  const trustHash = trustStorePem
479
- ? toHex(sha256(textEncoder.encode(trustStorePem)))
3161
+ ? toHex(sha256$1(textEncoder.encode(trustStorePem)))
480
3162
  : "no-trust";
481
3163
  const constraintFlag = enforceNameConstraints ? "nc1" : "nc0";
482
3164
  return `${chainHash}|${trustHash}|${constraintFlag}`;
@@ -2960,7 +5642,7 @@ class DefaultSecureChannelManager {
2960
5642
  }
2961
5643
  deriveChannelKey(channelId, sharedSecret) {
2962
5644
  const info = utf8ToBytes(`fame-channel:${channelId}`);
2963
- return hkdf(sha256, sharedSecret, undefined, info, CHANNEL_KEY_LENGTH);
5645
+ return hkdf(sha256$1, sharedSecret, undefined, info, CHANNEL_KEY_LENGTH);
2964
5646
  }
2965
5647
  createChannelState({ key, algorithm, }) {
2966
5648
  return {
@@ -6069,6 +8751,7 @@ var advancedWelcomeServiceFactory = /*#__PURE__*/Object.freeze({
6069
8751
  * Provides the list of advanced security factory modules for registration.
6070
8752
  */
6071
8753
  const MODULES = [
8754
+ "./security/auth/policy/advanced-authorization-policy-factory.js",
6072
8755
  "./security/cert/default-ca-service-factory.js",
6073
8756
  "./security/cert/default-certificate-manager-factory.js",
6074
8757
  "./security/cert/trust-store/browser-trust-store-provider-factory.js",
@@ -6085,6 +8768,7 @@ const MODULES = [
6085
8768
  "./welcome/advanced-welcome-service-factory.js"
6086
8769
  ];
6087
8770
  const MODULE_LOADERS = {
8771
+ "./security/auth/policy/advanced-authorization-policy-factory.js": () => Promise.resolve().then(function () { return advancedAuthorizationPolicyFactory; }),
6088
8772
  "./security/cert/default-ca-service-factory.js": () => Promise.resolve().then(function () { return defaultCaServiceFactory; }),
6089
8773
  "./security/cert/default-certificate-manager-factory.js": () => Promise.resolve().then(function () { return defaultCertificateManagerFactory; }),
6090
8774
  "./security/cert/trust-store/browser-trust-store-provider-factory.js": () => Promise.resolve().then(function () { return browserTrustStoreProviderFactory; }),
@@ -6101,6 +8785,75 @@ const MODULE_LOADERS = {
6101
8785
  "./welcome/advanced-welcome-service-factory.js": () => Promise.resolve().then(function () { return advancedWelcomeServiceFactory; }),
6102
8786
  };
6103
8787
 
8788
+ /**
8789
+ * Strict Overlay Security Profile
8790
+ *
8791
+ * Provides the strict-overlay security profile for advanced security scenarios.
8792
+ * This profile requires X.509 certificate-based signing and supports both
8793
+ * channel and sealed encryption modes.
8794
+ */
8795
+ const ENV_VAR_DEFAULT_ENCRYPTION_LEVEL = "FAME_DEFAULT_ENCRYPTION_LEVEL";
8796
+ const ENV_VAR_AUTHORIZATION_PROFILE = "FAME_AUTHORIZATION_PROFILE";
8797
+ const PROFILE_NAME_STRICT_OVERLAY = "strict-overlay";
8798
+ const STRICT_OVERLAY_PROFILE = {
8799
+ type: "DefaultSecurityManager",
8800
+ security_policy: {
8801
+ type: "DefaultSecurityPolicy",
8802
+ signing: {
8803
+ signing_material: "x509-chain",
8804
+ require_cert_sid_match: true,
8805
+ inbound: {
8806
+ signature_policy: "required",
8807
+ unsigned_violation_action: "nack",
8808
+ invalid_signature_action: "nack",
8809
+ },
8810
+ response: {
8811
+ mirror_request_signing: true,
8812
+ always_sign_responses: false,
8813
+ sign_error_responses: true,
8814
+ },
8815
+ outbound: {
8816
+ default_signing: true,
8817
+ sign_sensitive_operations: true,
8818
+ sign_if_recipient_expects: true,
8819
+ },
8820
+ },
8821
+ encryption: {
8822
+ inbound: {
8823
+ allow_plaintext: true,
8824
+ allow_channel: true,
8825
+ allow_sealed: true,
8826
+ plaintext_violation_action: "nack",
8827
+ channel_violation_action: "nack",
8828
+ sealed_violation_action: "nack",
8829
+ },
8830
+ response: {
8831
+ mirror_request_level: true,
8832
+ minimum_response_level: "plaintext",
8833
+ escalate_sealed_responses: false,
8834
+ },
8835
+ outbound: {
8836
+ default_level: Expressions.env(ENV_VAR_DEFAULT_ENCRYPTION_LEVEL, "channel"),
8837
+ escalate_if_peer_supports: false,
8838
+ prefer_sealed_for_sensitive: false,
8839
+ },
8840
+ },
8841
+ },
8842
+ authorizer: {
8843
+ type: "AuthorizationProfile",
8844
+ profile: Expressions.env(ENV_VAR_AUTHORIZATION_PROFILE, "jwt"),
8845
+ },
8846
+ };
8847
+ // Register the strict-overlay profile
8848
+ registerProfile(SECURITY_MANAGER_FACTORY_BASE_TYPE, PROFILE_NAME_STRICT_OVERLAY, STRICT_OVERLAY_PROFILE, { source: "advanced-security:strict-overlay-security-profile", allowOverride: true });
8849
+
8850
+ var strictOverlaySecurityProfile = /*#__PURE__*/Object.freeze({
8851
+ __proto__: null,
8852
+ ENV_VAR_AUTHORIZATION_PROFILE: ENV_VAR_AUTHORIZATION_PROFILE,
8853
+ ENV_VAR_DEFAULT_ENCRYPTION_LEVEL: ENV_VAR_DEFAULT_ENCRYPTION_LEVEL,
8854
+ PROFILE_NAME_STRICT_OVERLAY: PROFILE_NAME_STRICT_OVERLAY
8855
+ });
8856
+
6104
8857
  const SECURITY_PREFIX = "./security/";
6105
8858
  const SECURITY_MODULES = MODULES.filter((spec) => spec.startsWith(SECURITY_PREFIX));
6106
8859
  const EXTRA_MODULES = MODULES.filter((spec) => !spec.startsWith(SECURITY_PREFIX));
@@ -7414,7 +10167,7 @@ function computeEarliestExpiry(roots) {
7414
10167
  function computeBundleVersion(roots) {
7415
10168
  const encoder = new TextEncoder();
7416
10169
  const serialized = roots.map((root) => root.pem).join("\n");
7417
- const digest = sha256$1(encoder.encode(serialized));
10170
+ const digest = sha256$2(encoder.encode(serialized));
7418
10171
  const hex = Array.from(digest)
7419
10172
  .map((byte) => byte.toString(16).padStart(2, "0"))
7420
10173
  .join("");
@@ -8589,7 +11342,7 @@ function computeSpkiSha256(pem) {
8589
11342
  return null;
8590
11343
  }
8591
11344
  const der = new Uint8Array(publicKey.rawData);
8592
- const digest = sha256(der);
11345
+ const digest = sha256$1(der);
8593
11346
  return toBase64Url(digest);
8594
11347
  }
8595
11348
  catch {
@@ -9042,7 +11795,7 @@ function normalizeRefreshInterval(value) {
9042
11795
  return Math.max(MIN_REFRESH_INTERVAL_MS, Math.floor(value));
9043
11796
  }
9044
11797
  function computeHash(payload) {
9045
- const digest = sha256(payload);
11798
+ const digest = sha256$1(payload);
9046
11799
  return toBase64Url(digest);
9047
11800
  }
9048
11801
  function hexToBase64Url(hex) {
@@ -9062,7 +11815,7 @@ function bytesToUtf8(data) {
9062
11815
  return String.fromCharCode(...Array.from(data));
9063
11816
  }
9064
11817
  function computeCacheKey(value) {
9065
- const digest = sha256(new TextEncoder().encode(value));
11818
+ const digest = sha256$1(new TextEncoder().encode(value));
9066
11819
  return Array.from(digest)
9067
11820
  .map((byte) => byte.toString(16).padStart(2, "0"))
9068
11821
  .join("");
@@ -9837,6 +12590,8 @@ const advancedSecurityPlugin = {
9837
12590
  try {
9838
12591
  // console.log('[naylence:advanced-security] registering advanced security factories...');
9839
12592
  await registerAdvancedSecurityPluginFactories();
12593
+ // Import modules with side-effect registrations (not in manifest)
12594
+ await Promise.resolve().then(function () { return strictOverlaySecurityProfile; });
9840
12595
  // console.log('[naylence:advanced-security] advanced security factories registered');
9841
12596
  initialized = true;
9842
12597
  }
@@ -9856,4 +12611,4 @@ var plugin = /*#__PURE__*/Object.freeze({
9856
12611
  registerAdvancedSecurityPluginFactories: registerAdvancedSecurityPluginFactories
9857
12612
  });
9858
12613
 
9859
- export { FACTORY_META$9 as ADVANCED_EDDSA_ENVELOPE_SIGNER_FACTORY_META, FACTORY_META$8 as ADVANCED_EDDSA_ENVELOPE_VERIFIER_FACTORY_META, FACTORY_META$4 as ADVANCED_WELCOME_FACTORY_META, AFTHelper, AFTLoadBalancerStickinessManager, AFTLoadBalancerStickinessManagerFactory, AFTReplicaStickinessManager, AFTReplicaStickinessManagerFactory, FACTORY_META$6 as AFT_LOAD_BALANCER_FACTORY_META, FACTORY_META$5 as AFT_REPLICA_FACTORY_META, AdvancedEdDSAEnvelopeSignerFactory, AdvancedEdDSAEnvelopeVerifierFactory, AdvancedWelcomeService, AdvancedWelcomeServiceFactory, CAServiceClient, CompositeEncryptionManager, CompositeEncryptionManagerFactory, FACTORY_META$b as DEFAULT_SECURE_CHANNEL_MANAGER_FACTORY_META, DEFAULT_STICKINESS_SECURITY_LEVEL, DefaultSecureChannelManager, DefaultSecureChannelManagerFactory, ENV_VAR_FAME_CA_SERVICE_URL, EdDSAEnvelopeVerifier, GRANT_PURPOSE_CA_SIGN, NoAFTSigner, SidOnlyAFTVerifier, SignedAFTSigner, SignedOptionalAFTVerifier, StickinessMode, StrictAFTVerifier, UnsignedAFTSigner, VERSION, X5CKeyManager, X5CKeyManagerFactory, FACTORY_META$7 as X5C_KEY_MANAGER_FACTORY_META, __advancedSecurityPluginLoader, base64UrlDecode, base64UrlEncode, index as channelEncryption, createAftHelper, createAftPayload, createAftReplicaStickinessManager, createAftSigner, createAftVerifier, createEd25519Csr, extractCertificateInfo, formatCertificateInfo, normalizeStickinessMode, publicKeyFromX5c, registerAdvancedSecurityFactories, index$1 as sealedEncryption, serializeAftClaims, serializeAftHeader, utf8Decode, validateJwkX5cCertificate };
12614
+ export { FACTORY_META$e as ADVANCED_AUTHORIZATION_POLICY_FACTORY_META, FACTORY_META$9 as ADVANCED_EDDSA_ENVELOPE_SIGNER_FACTORY_META, FACTORY_META$8 as ADVANCED_EDDSA_ENVELOPE_VERIFIER_FACTORY_META, FACTORY_META$4 as ADVANCED_WELCOME_FACTORY_META, AFTHelper, AFTLoadBalancerStickinessManager, AFTLoadBalancerStickinessManagerFactory, AFTReplicaStickinessManager, AFTReplicaStickinessManagerFactory, FACTORY_META$6 as AFT_LOAD_BALANCER_FACTORY_META, FACTORY_META$5 as AFT_REPLICA_FACTORY_META, AdvancedAuthorizationPolicy, AdvancedAuthorizationPolicyFactory, AdvancedEdDSAEnvelopeSignerFactory, AdvancedEdDSAEnvelopeVerifierFactory, AdvancedWelcomeService, AdvancedWelcomeServiceFactory, BUILTIN_FUNCTIONS, BuiltinError, CAServiceClient, CompositeEncryptionManager, CompositeEncryptionManagerFactory, DEFAULT_EXPRESSION_LIMITS, FACTORY_META$b as DEFAULT_SECURE_CHANNEL_MANAGER_FACTORY_META, DEFAULT_STICKINESS_SECURITY_LEVEL, DefaultSecureChannelManager, DefaultSecureChannelManagerFactory, ENV_VAR_FAME_CA_SERVICE_URL, EdDSAEnvelopeVerifier, EvaluationError, Evaluator, ExpressionError, GRANT_PURPOSE_CA_SIGN, LimitExceededError, NoAFTSigner, ParseError, Parser, SidOnlyAFTVerifier, SignedAFTSigner, SignedOptionalAFTVerifier, StickinessMode, StrictAFTVerifier, Tokenizer, TokenizerError, TypeError, UnsignedAFTSigner, VERSION, X5CKeyManager, X5CKeyManagerFactory, FACTORY_META$7 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, evaluate, evaluateAsBoolean, extractCertificateInfo, formatCertificateInfo, getTypeName, isBuiltinFunction, normalizeJsValue, normalizeStickinessMode, parse, publicKeyFromX5c, registerAdvancedSecurityFactories, index$1 as sealedEncryption, serializeAftClaims, serializeAftHeader, tokenize, utf8Decode, validateJwkX5cCertificate };